@sync-in/server 1.9.0 → 1.9.3

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.
Files changed (167) hide show
  1. package/CHANGELOG.md +13 -8
  2. package/package.json +7 -7
  3. package/server/app.constants.js +3 -3
  4. package/server/app.constants.js.map +1 -1
  5. package/server/app.functions.js +42 -0
  6. package/server/app.functions.js.map +1 -0
  7. package/server/applications/files/services/files-manager.service.js +2 -2
  8. package/server/applications/files/services/files-manager.service.js.map +1 -1
  9. package/server/applications/files/services/files-tasks-manager.service.js +1 -1
  10. package/server/applications/files/services/files-tasks-manager.service.js.map +1 -1
  11. package/server/applications/files/utils/send-file.js +18 -9
  12. package/server/applications/files/utils/send-file.js.map +1 -1
  13. package/server/applications/files/utils/url-file.js +6 -6
  14. package/server/applications/files/utils/url-file.js.map +1 -1
  15. package/server/applications/links/services/links-manager.service.js +1 -1
  16. package/server/applications/links/services/links-manager.service.js.map +1 -1
  17. package/server/applications/shares/interfaces/share-props.interface.js.map +1 -1
  18. package/server/applications/shares/services/shares-manager.service.js +6 -4
  19. package/server/applications/shares/services/shares-manager.service.js.map +1 -1
  20. package/server/applications/spaces/services/spaces-manager.service.js +15 -12
  21. package/server/applications/spaces/services/spaces-manager.service.js.map +1 -1
  22. package/server/applications/users/services/admin-users-manager.service.js +4 -0
  23. package/server/applications/users/services/admin-users-manager.service.js.map +1 -1
  24. package/server/applications/users/users.controller.js +4 -1
  25. package/server/applications/users/users.controller.js.map +1 -1
  26. package/static/assets/pdfjs/build/pdf.mjs +35 -20
  27. package/static/assets/pdfjs/build/pdf.mjs.map +1 -1
  28. package/static/assets/pdfjs/build/pdf.sandbox.mjs +2 -2
  29. package/static/assets/pdfjs/build/pdf.worker.mjs +1488 -52
  30. package/static/assets/pdfjs/build/pdf.worker.mjs.map +1 -1
  31. package/static/assets/pdfjs/version +1 -1
  32. package/static/assets/pdfjs/web/locale/be/viewer.ftl +2 -12
  33. package/static/assets/pdfjs/web/locale/bg/viewer.ftl +4 -0
  34. package/static/assets/pdfjs/web/locale/bs/viewer.ftl +0 -15
  35. package/static/assets/pdfjs/web/locale/ca/viewer.ftl +0 -4
  36. package/static/assets/pdfjs/web/locale/cs/viewer.ftl +4 -14
  37. package/static/assets/pdfjs/web/locale/cy/viewer.ftl +2 -12
  38. package/static/assets/pdfjs/web/locale/da/viewer.ftl +2 -12
  39. package/static/assets/pdfjs/web/locale/de/viewer.ftl +0 -12
  40. package/static/assets/pdfjs/web/locale/dsb/viewer.ftl +0 -12
  41. package/static/assets/pdfjs/web/locale/el/viewer.ftl +2 -12
  42. package/static/assets/pdfjs/web/locale/en-CA/viewer.ftl +0 -12
  43. package/static/assets/pdfjs/web/locale/en-GB/viewer.ftl +0 -12
  44. package/static/assets/pdfjs/web/locale/eo/viewer.ftl +2 -12
  45. package/static/assets/pdfjs/web/locale/es-AR/viewer.ftl +0 -12
  46. package/static/assets/pdfjs/web/locale/es-CL/viewer.ftl +2 -12
  47. package/static/assets/pdfjs/web/locale/es-ES/viewer.ftl +2 -12
  48. package/static/assets/pdfjs/web/locale/es-MX/viewer.ftl +0 -12
  49. package/static/assets/pdfjs/web/locale/eu/viewer.ftl +0 -12
  50. package/static/assets/pdfjs/web/locale/fi/viewer.ftl +0 -12
  51. package/static/assets/pdfjs/web/locale/fr/viewer.ftl +0 -12
  52. package/static/assets/pdfjs/web/locale/fur/viewer.ftl +0 -12
  53. package/static/assets/pdfjs/web/locale/fy-NL/viewer.ftl +0 -12
  54. package/static/assets/pdfjs/web/locale/gn/viewer.ftl +2 -12
  55. package/static/assets/pdfjs/web/locale/he/viewer.ftl +0 -12
  56. package/static/assets/pdfjs/web/locale/hsb/viewer.ftl +0 -12
  57. package/static/assets/pdfjs/web/locale/hu/viewer.ftl +0 -12
  58. package/static/assets/pdfjs/web/locale/hy-AM/viewer.ftl +0 -15
  59. package/static/assets/pdfjs/web/locale/ia/viewer.ftl +0 -12
  60. package/static/assets/pdfjs/web/locale/id/viewer.ftl +0 -15
  61. package/static/assets/pdfjs/web/locale/is/viewer.ftl +0 -15
  62. package/static/assets/pdfjs/web/locale/it/viewer.ftl +2 -14
  63. package/static/assets/pdfjs/web/locale/ja/viewer.ftl +7 -2
  64. package/static/assets/pdfjs/web/locale/ka/viewer.ftl +0 -12
  65. package/static/assets/pdfjs/web/locale/kab/viewer.ftl +0 -12
  66. package/static/assets/pdfjs/web/locale/kk/viewer.ftl +3 -12
  67. package/static/assets/pdfjs/web/locale/ko/viewer.ftl +0 -12
  68. package/static/assets/pdfjs/web/locale/nb-NO/viewer.ftl +2 -12
  69. package/static/assets/pdfjs/web/locale/nl/viewer.ftl +0 -12
  70. package/static/assets/pdfjs/web/locale/nn-NO/viewer.ftl +0 -12
  71. package/static/assets/pdfjs/web/locale/pa-IN/viewer.ftl +4 -12
  72. package/static/assets/pdfjs/web/locale/pl/viewer.ftl +2 -12
  73. package/static/assets/pdfjs/web/locale/pt-BR/viewer.ftl +2 -12
  74. package/static/assets/pdfjs/web/locale/rm/viewer.ftl +0 -12
  75. package/static/assets/pdfjs/web/locale/ro/viewer.ftl +2 -14
  76. package/static/assets/pdfjs/web/locale/ru/viewer.ftl +0 -12
  77. package/static/assets/pdfjs/web/locale/sc/viewer.ftl +0 -1
  78. package/static/assets/pdfjs/web/locale/sk/viewer.ftl +0 -12
  79. package/static/assets/pdfjs/web/locale/sl/viewer.ftl +2 -12
  80. package/static/assets/pdfjs/web/locale/sq/viewer.ftl +2 -12
  81. package/static/assets/pdfjs/web/locale/sv-SE/viewer.ftl +0 -12
  82. package/static/assets/pdfjs/web/locale/tg/viewer.ftl +2 -12
  83. package/static/assets/pdfjs/web/locale/th/viewer.ftl +0 -12
  84. package/static/assets/pdfjs/web/locale/tr/viewer.ftl +2 -12
  85. package/static/assets/pdfjs/web/locale/vi/viewer.ftl +0 -12
  86. package/static/assets/pdfjs/web/locale/zh-CN/viewer.ftl +2 -12
  87. package/static/assets/pdfjs/web/locale/zh-TW/viewer.ftl +0 -12
  88. package/static/assets/pdfjs/web/viewer.css +53 -41
  89. package/static/assets/pdfjs/web/viewer.html +493 -132
  90. package/static/assets/pdfjs/web/viewer.mjs +225 -150
  91. package/static/assets/pdfjs/web/viewer.mjs.map +1 -1
  92. package/static/{chunk-LYZGJZNP.js → chunk-25PWAXTJ.js} +1 -1
  93. package/static/{chunk-EKEGRXCV.js → chunk-27XEAHMV.js} +1 -1
  94. package/static/{chunk-YMAN4LIU.js → chunk-2CAAJBRO.js} +1 -1
  95. package/static/{chunk-MNNCSSHN.js → chunk-2LHHXDD5.js} +1 -1
  96. package/static/{chunk-YCTCESL4.js → chunk-2XY4PMI5.js} +1 -1
  97. package/static/{chunk-ERDZ7IVF.js → chunk-33WFRCUP.js} +1 -1
  98. package/static/chunk-3LVFDMTN.js +1 -0
  99. package/static/{chunk-4FJUCMEG.js → chunk-4DF2SQD4.js} +1 -1
  100. package/static/{chunk-Q556XB3S.js → chunk-4EUHBTWV.js} +1 -1
  101. package/static/{chunk-AADK5D2H.js → chunk-4KXJ6C4N.js} +1 -1
  102. package/static/{chunk-BHZEPHRI.js → chunk-4OV3SAUS.js} +1 -1
  103. package/static/{chunk-T74SMT7I.js → chunk-5HCVWZMA.js} +1 -1
  104. package/static/{chunk-ZCOWBVOT.js → chunk-5HYSNQR4.js} +1 -1
  105. package/static/{chunk-XOTKK2NJ.js → chunk-5NHB7SV3.js} +1 -1
  106. package/static/chunk-6VJI4X2A.js +1 -0
  107. package/static/{chunk-XCLK7NJL.js → chunk-7H5O4BLV.js} +1 -1
  108. package/static/{chunk-ACUF7IKP.js → chunk-7NI353LS.js} +1 -1
  109. package/static/{chunk-Y44XDRM5.js → chunk-A6J6SOM6.js} +1 -1
  110. package/static/{chunk-XOF4UW3S.js → chunk-A7DSX7VP.js} +1 -1
  111. package/static/chunk-A7R246NW.js +1 -0
  112. package/static/{chunk-EL6QL4TP.js → chunk-ASBPYTLT.js} +1 -1
  113. package/static/chunk-BJARRIS6.js +562 -0
  114. package/static/{chunk-RT3K6DZR.js → chunk-CAZSNVMS.js} +1 -1
  115. package/static/{chunk-EIYRBM4J.js → chunk-CURVLK7L.js} +1 -1
  116. package/static/{chunk-7CFSJ4BO.js → chunk-DDRGLHOP.js} +1 -1
  117. package/static/{chunk-2XPHUNYN.js → chunk-FLPZB3OX.js} +1 -1
  118. package/static/{chunk-23UUFZSR.js → chunk-FRBTL2ER.js} +1 -1
  119. package/static/{chunk-MRF3CNLZ.js → chunk-FXM7XXWA.js} +1 -1
  120. package/static/{chunk-7CKHC72R.js → chunk-GDPJRUVU.js} +1 -1
  121. package/static/{chunk-QMHUIHSR.js → chunk-GENTF6JM.js} +1 -1
  122. package/static/{chunk-XX7JXKA6.js → chunk-H4RLHI3Y.js} +1 -1
  123. package/static/{chunk-KNZ3AQPR.js → chunk-HE6EDXWI.js} +1 -1
  124. package/static/{chunk-LXQGVNU2.js → chunk-IUJ4IK26.js} +1 -1
  125. package/static/{chunk-MVZJSG5R.js → chunk-JEVBUJQ4.js} +1 -1
  126. package/static/{chunk-2FOWUJQF.js → chunk-K3MOXDU5.js} +1 -1
  127. package/static/{chunk-PG54TWBO.js → chunk-KBWK65KM.js} +1 -1
  128. package/static/{chunk-5HNQLBSW.js → chunk-L3PDWJZ3.js} +2 -2
  129. package/static/{chunk-KDEEERWZ.js → chunk-LBXOAKBD.js} +1 -1
  130. package/static/{chunk-Y5RLD72B.js → chunk-LFAQLJZK.js} +1 -1
  131. package/static/{chunk-M4XL3JN5.js → chunk-MBFMTBVJ.js} +1 -1
  132. package/static/{chunk-FTSIPHMG.js → chunk-MZBO5PAR.js} +1 -1
  133. package/static/{chunk-DJDRX53V.js → chunk-NFIES7BC.js} +1 -1
  134. package/static/{chunk-24Q7OUU2.js → chunk-NK2NMAJI.js} +1 -1
  135. package/static/{chunk-BYWSTP3P.js → chunk-O7UXVNR2.js} +1 -1
  136. package/static/{chunk-3IISSX63.js → chunk-PKU4IIIR.js} +1 -1
  137. package/static/{chunk-NN4ONTOT.js → chunk-QUSS6SUC.js} +1 -1
  138. package/static/{chunk-Y2I36A4K.js → chunk-R6VB3INJ.js} +1 -1
  139. package/static/{chunk-CCGGCHGN.js → chunk-RJOHDAPM.js} +1 -1
  140. package/static/{chunk-N3P6P6GW.js → chunk-S6YKBWJE.js} +1 -1
  141. package/static/{chunk-AZ5TF5Y3.js → chunk-SDR3UG2F.js} +1 -1
  142. package/static/{chunk-C3AAEQKW.js → chunk-TGHBDJZA.js} +1 -1
  143. package/static/{chunk-HNMGPG72.js → chunk-TVJQXN73.js} +1 -1
  144. package/static/{chunk-KHRF67SG.js → chunk-U75PLYIJ.js} +1 -1
  145. package/static/chunk-UUX3M6DC.js +1 -0
  146. package/static/{chunk-S6EVLDHA.js → chunk-VJ2HWQRJ.js} +2 -2
  147. package/static/{chunk-QNFNXDSX.js → chunk-VO4WVT6K.js} +1 -1
  148. package/static/{chunk-5XUIPWOH.js → chunk-W72JYHOH.js} +1 -1
  149. package/static/{chunk-OJCAIKUK.js → chunk-WJYVS27M.js} +1 -1
  150. package/static/{chunk-HKRGIRKB.js → chunk-XAIOGRBO.js} +1 -1
  151. package/static/{chunk-BQZWSZNN.js → chunk-XHQEF2IX.js} +1 -1
  152. package/static/{chunk-RX3YQ67K.js → chunk-XXYMVRSH.js} +1 -1
  153. package/static/{chunk-HHWXIK2M.js → chunk-YTBSB2GE.js} +1 -1
  154. package/static/{chunk-LJSVNPPQ.js → chunk-YXWF2DGF.js} +1 -1
  155. package/static/{chunk-JMYAD7E2.js → chunk-Z6RJZIDG.js} +1 -1
  156. package/static/{chunk-F7TXTNZC.js → chunk-ZC5ZDCDC.js} +1 -1
  157. package/static/{chunk-EDJAISWO.js → chunk-ZERBTNFW.js} +8 -8
  158. package/static/{chunk-MRMSMTWD.js → chunk-ZPI7RQ2S.js} +1 -1
  159. package/static/{chunk-NOPACN4F.js → chunk-ZRBLCAOK.js} +1 -1
  160. package/static/index.html +2 -2
  161. package/static/{main-3PLRDZTO.js → main-FE6GWZXU.js} +4 -4
  162. package/static/{styles-Q4OZOSSK.css → styles-S5HVK4H5.css} +1 -1
  163. package/static/chunk-H6WOTGQ5.js +0 -1
  164. package/static/chunk-HC7F57NA.js +0 -1
  165. package/static/chunk-IOIBQGHN.js +0 -562
  166. package/static/chunk-J6YSFHLZ.js +0 -1
  167. package/static/chunk-QVFPHTOH.js +0 -1
@@ -21,8 +21,8 @@
21
21
  */
22
22
 
23
23
  /**
24
- * pdfjsVersion = 5.4.394
25
- * pdfjsBuild = 2cc809ade
24
+ * pdfjsVersion = 5.4.449
25
+ * pdfjsBuild = f44e5f0e6
26
26
  */
27
27
  /******/ // The require scope
28
28
  /******/ var __webpack_require__ = {};
@@ -1029,6 +1029,9 @@ class Dict {
1029
1029
  getRawValues() {
1030
1030
  return [...this._map.values()];
1031
1031
  }
1032
+ getRawEntries() {
1033
+ return this._map.entries();
1034
+ }
1032
1035
  set(key, value) {
1033
1036
  this._map.set(key, value);
1034
1037
  }
@@ -1059,6 +1062,11 @@ class Dict {
1059
1062
  this.set(key, value);
1060
1063
  }
1061
1064
  }
1065
+ setIfDict(key, value) {
1066
+ if (value instanceof Dict) {
1067
+ this.set(key, value);
1068
+ }
1069
+ }
1062
1070
  has(key) {
1063
1071
  return this._map.has(key);
1064
1072
  }
@@ -1207,6 +1215,11 @@ class RefSetCache {
1207
1215
  yield [Ref.fromString(ref), value];
1208
1216
  }
1209
1217
  }
1218
+ *keys() {
1219
+ for (const ref of this._map.keys()) {
1220
+ yield Ref.fromString(ref);
1221
+ }
1222
+ }
1210
1223
  }
1211
1224
  function isName(v, name) {
1212
1225
  return v instanceof Name && (name === undefined || v.name === name);
@@ -2898,6 +2911,9 @@ class Stream extends BaseStream {
2898
2911
  makeSubStream(start, length, dict = null) {
2899
2912
  return new Stream(this.bytes.buffer, start, length, dict);
2900
2913
  }
2914
+ clone() {
2915
+ return new Stream(this.bytes.buffer, this.start, this.end - this.start, this.dict.clone());
2916
+ }
2901
2917
  }
2902
2918
  class StringStream extends Stream {
2903
2919
  constructor(str) {
@@ -3915,6 +3931,12 @@ class DecodeStream extends BaseStream {
3915
3931
  getBaseStreams() {
3916
3932
  return this.stream ? this.stream.getBaseStreams() : null;
3917
3933
  }
3934
+ clone() {
3935
+ while (!this.eof) {
3936
+ this.readBlock();
3937
+ }
3938
+ return new Stream(this.buffer, this.start, this.end - this.start, this.dict.clone());
3939
+ }
3918
3940
  }
3919
3941
  class StreamsSequenceStream extends DecodeStream {
3920
3942
  constructor(streams, onError = null) {
@@ -36331,7 +36353,7 @@ class NameOrNumberTree {
36331
36353
  this.xref = xref;
36332
36354
  this._type = type;
36333
36355
  }
36334
- getAll() {
36356
+ getAll(isRaw = false) {
36335
36357
  const map = new Map();
36336
36358
  if (!this.root) {
36337
36359
  return map;
@@ -36364,7 +36386,7 @@ class NameOrNumberTree {
36364
36386
  continue;
36365
36387
  }
36366
36388
  for (let i = 0, ii = entries.length; i < ii; i += 2) {
36367
- map.set(xref.fetchIfRef(entries[i]), xref.fetchIfRef(entries[i + 1]));
36389
+ map.set(xref.fetchIfRef(entries[i]), isRaw ? entries[i + 1] : xref.fetchIfRef(entries[i + 1]));
36368
36390
  }
36369
36391
  }
36370
36392
  return map;
@@ -37077,6 +37099,7 @@ class StructTreeRoot {
37077
37099
  this.roleMap = new Map();
37078
37100
  this.structParentIds = null;
37079
37101
  this.kidRefToPosition = undefined;
37102
+ this.parentTree = null;
37080
37103
  }
37081
37104
  getKidPosition(kidRef) {
37082
37105
  if (this.kidRefToPosition === undefined) {
@@ -37101,6 +37124,11 @@ class StructTreeRoot {
37101
37124
  }
37102
37125
  init() {
37103
37126
  this.readRoleMap();
37127
+ const parentTree = this.dict.get("ParentTree");
37128
+ if (!parentTree) {
37129
+ return;
37130
+ }
37131
+ this.parentTree = new NumberTree(parentTree, this.xref);
37104
37132
  }
37105
37133
  #addIdToPage(pageRef, id, type) {
37106
37134
  if (!(pageRef instanceof Ref) || id < 0) {
@@ -37723,7 +37751,9 @@ class StructTreePage {
37723
37751
  if (!this.root || !this.rootDict || !(pageRef instanceof Ref)) {
37724
37752
  return;
37725
37753
  }
37726
- const parentTree = this.rootDict.get("ParentTree");
37754
+ const {
37755
+ parentTree
37756
+ } = this.root;
37727
37757
  if (!parentTree) {
37728
37758
  return;
37729
37759
  }
@@ -37733,9 +37763,8 @@ class StructTreePage {
37733
37763
  return;
37734
37764
  }
37735
37765
  const map = new Map();
37736
- const numberTree = new NumberTree(parentTree, this.xref);
37737
37766
  if (Number.isInteger(id)) {
37738
- const parentArray = numberTree.get(id);
37767
+ const parentArray = parentTree.get(id);
37739
37768
  if (Array.isArray(parentArray)) {
37740
37769
  for (const ref of parentArray) {
37741
37770
  if (ref instanceof Ref) {
@@ -37748,7 +37777,7 @@ class StructTreePage {
37748
37777
  return;
37749
37778
  }
37750
37779
  for (const [elemId, type] of ids) {
37751
- const obj = numberTree.get(elemId);
37780
+ const obj = parentTree.get(elemId);
37752
37781
  if (obj) {
37753
37782
  const elem = this.addNode(this.xref.fetchIfRef(obj), map);
37754
37783
  if (elem?.kids?.length === 1 && elem.kids[0].type === StructElementType.OBJECT) {
@@ -38065,6 +38094,9 @@ class Catalog {
38065
38094
  }
38066
38095
  return markInfo;
38067
38096
  }
38097
+ get hasStructTree() {
38098
+ return this.#catDict.has("StructTreeRoot");
38099
+ }
38068
38100
  get structTreeRoot() {
38069
38101
  let structTree = null;
38070
38102
  try {
@@ -38477,6 +38509,14 @@ class Catalog {
38477
38509
  }
38478
38510
  return rawDests;
38479
38511
  }
38512
+ get rawPageLabels() {
38513
+ const obj = this.#catDict.getRaw("PageLabels");
38514
+ if (!obj) {
38515
+ return null;
38516
+ }
38517
+ const numberTree = new NumberTree(obj, this.xref);
38518
+ return numberTree.getAll();
38519
+ }
38480
38520
  get pageLabels() {
38481
38521
  let obj = null;
38482
38522
  try {
@@ -38490,15 +38530,13 @@ class Catalog {
38490
38530
  return shadow(this, "pageLabels", obj);
38491
38531
  }
38492
38532
  #readPageLabels() {
38493
- const obj = this.#catDict.getRaw("PageLabels");
38494
- if (!obj) {
38533
+ const nums = this.rawPageLabels;
38534
+ if (!nums) {
38495
38535
  return null;
38496
38536
  }
38497
38537
  const pageLabels = new Array(this.numPages);
38498
38538
  let style = null,
38499
38539
  prefix = "";
38500
- const numberTree = new NumberTree(obj, this.xref);
38501
- const nums = numberTree.getAll();
38502
38540
  let currentLabel = "",
38503
38541
  currentIndex = 1;
38504
38542
  for (let i = 0, ii = this.numPages; i < ii; i++) {
@@ -44729,7 +44767,7 @@ class Occur extends XFAObject {
44729
44767
  }) : "";
44730
44768
  this.max = attributes.max !== "" ? getInteger({
44731
44769
  data: attributes.max,
44732
- defaultValue: 1,
44770
+ defaultValue: -1,
44733
44771
  validate: x => true
44734
44772
  }) : "";
44735
44773
  this.min = attributes.min !== "" ? getInteger({
@@ -54367,6 +54405,9 @@ class DecryptStream extends DecodeStream {
54367
54405
  buffer.set(chunk, bufferLength);
54368
54406
  this.bufferLength = newLength;
54369
54407
  }
54408
+ getOriginalStream() {
54409
+ return this;
54410
+ }
54370
54411
  }
54371
54412
 
54372
54413
  ;// ./src/core/crypto.js
@@ -56000,7 +56041,7 @@ class Page {
56000
56041
  const resources = this.#getInheritableProperty("Resources");
56001
56042
  return shadow(this, "resources", resources instanceof Dict ? resources : Dict.empty);
56002
56043
  }
56003
- #getBoundingBox(name) {
56044
+ getBoundingBox(name) {
56004
56045
  if (this.xfaData) {
56005
56046
  return this.xfaData.bbox;
56006
56047
  }
@@ -56014,10 +56055,10 @@ class Page {
56014
56055
  return null;
56015
56056
  }
56016
56057
  get mediaBox() {
56017
- return shadow(this, "mediaBox", this.#getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
56058
+ return shadow(this, "mediaBox", this.getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
56018
56059
  }
56019
56060
  get cropBox() {
56020
- return shadow(this, "cropBox", this.#getBoundingBox("CropBox") || this.mediaBox);
56061
+ return shadow(this, "cropBox", this.getBoundingBox("CropBox") || this.mediaBox);
56021
56062
  }
56022
56063
  get userUnit() {
56023
56064
  const obj = this.pageDict.get("UserUnit");
@@ -57874,28 +57915,25 @@ class MessageHandler {
57874
57915
 
57875
57916
 
57876
57917
  async function writeObject(ref, obj, buffer, {
57877
- encrypt = null
57918
+ encrypt = null,
57919
+ encryptRef = null
57878
57920
  }) {
57879
- const transform = encrypt?.createCipherTransform(ref.num, ref.gen);
57921
+ const transform = encrypt && encryptRef !== ref ? encrypt.createCipherTransform(ref.num, ref.gen) : null;
57880
57922
  buffer.push(`${ref.num} ${ref.gen} obj\n`);
57881
- if (obj instanceof Dict) {
57882
- await writeDict(obj, buffer, transform);
57883
- } else if (obj instanceof BaseStream) {
57884
- await writeStream(obj, buffer, transform);
57885
- } else if (Array.isArray(obj) || ArrayBuffer.isView(obj)) {
57886
- await writeArray(obj, buffer, transform);
57887
- }
57923
+ await writeValue(obj, buffer, transform);
57888
57924
  buffer.push("\nendobj\n");
57889
57925
  }
57890
57926
  async function writeDict(dict, buffer, transform) {
57891
57927
  buffer.push("<<");
57892
- for (const key of dict.getKeys()) {
57928
+ for (const [key, rawObj] of dict.getRawEntries()) {
57893
57929
  buffer.push(` /${escapePDFName(key)} `);
57894
- await writeValue(dict.getRaw(key), buffer, transform);
57930
+ await writeValue(rawObj, buffer, transform);
57895
57931
  }
57896
57932
  buffer.push(">>");
57897
57933
  }
57898
57934
  async function writeStream(stream, buffer, transform) {
57935
+ stream = stream.getOriginalStream();
57936
+ stream.reset();
57899
57937
  let bytes = stream.getBytes();
57900
57938
  const {
57901
57939
  dict
@@ -57904,7 +57942,7 @@ async function writeStream(stream, buffer, transform) {
57904
57942
  const filterZero = Array.isArray(filter) ? await dict.xref.fetchIfRefAsync(filter[0]) : filter;
57905
57943
  const isFilterZeroFlateDecode = isName(filterZero, "FlateDecode");
57906
57944
  const MIN_LENGTH_FOR_COMPRESSING = 256;
57907
- if (bytes.length >= MIN_LENGTH_FOR_COMPRESSING || isFilterZeroFlateDecode) {
57945
+ if (bytes.length >= MIN_LENGTH_FOR_COMPRESSING && !isFilterZeroFlateDecode) {
57908
57946
  try {
57909
57947
  const cs = new CompressionStream("deflate");
57910
57948
  const writer = cs.writable.getWriter();
@@ -57944,14 +57982,11 @@ async function writeStream(stream, buffer, transform) {
57944
57982
  }
57945
57983
  async function writeArray(array, buffer, transform) {
57946
57984
  buffer.push("[");
57947
- let first = true;
57948
- for (const val of array) {
57949
- if (!first) {
57985
+ for (let i = 0, ii = array.length; i < ii; i++) {
57986
+ await writeValue(array[i], buffer, transform);
57987
+ if (i < ii - 1) {
57950
57988
  buffer.push(" ");
57951
- } else {
57952
- first = false;
57953
57989
  }
57954
- await writeValue(val, buffer, transform);
57955
57990
  }
57956
57991
  buffer.push("]");
57957
57992
  }
@@ -57968,7 +58003,7 @@ async function writeValue(value, buffer, transform) {
57968
58003
  }
57969
58004
  buffer.push(`(${escapeString(value)})`);
57970
58005
  } else if (typeof value === "number") {
57971
- buffer.push(numberToString(value));
58006
+ buffer.push(value.toString());
57972
58007
  } else if (typeof value === "boolean") {
57973
58008
  buffer.push(value.toString());
57974
58009
  } else if (value instanceof Dict) {
@@ -58107,7 +58142,7 @@ async function getXRefTable(xrefInfo, baseOffset, newRefs, newXref, buffer) {
58107
58142
  }
58108
58143
  computeIDs(baseOffset, xrefInfo, newXref);
58109
58144
  buffer.push("trailer\n");
58110
- await writeDict(newXref, buffer);
58145
+ await writeDict(newXref, buffer, null);
58111
58146
  buffer.push("\nstartxref\n", baseOffset.toString(), "\n%%EOF\n");
58112
58147
  }
58113
58148
  function getIndexes(newRefs) {
@@ -58129,11 +58164,16 @@ async function getXRefStreamTable(xrefInfo, baseOffset, newRefs, newXref, buffer
58129
58164
  let maxGen = 0;
58130
58165
  for (const {
58131
58166
  ref,
58132
- data
58167
+ data,
58168
+ objStreamRef,
58169
+ index
58133
58170
  } of newRefs) {
58134
58171
  let gen;
58135
58172
  maxOffset = Math.max(maxOffset, baseOffset);
58136
- if (data !== null) {
58173
+ if (objStreamRef) {
58174
+ gen = index;
58175
+ xrefTableData.push([2, objStreamRef.num, gen]);
58176
+ } else if (data !== null) {
58137
58177
  gen = Math.min(ref.gen, 0xffff);
58138
58178
  xrefTableData.push([1, baseOffset, gen]);
58139
58179
  baseOffset += data.length;
@@ -58165,12 +58205,12 @@ async function getXRefStreamTable(xrefInfo, baseOffset, newRefs, newXref, buffer
58165
58205
  function computeIDs(baseOffset, xrefInfo, newXref) {
58166
58206
  if (Array.isArray(xrefInfo.fileIds) && xrefInfo.fileIds.length > 0) {
58167
58207
  const md5 = computeMD5(baseOffset, xrefInfo);
58168
- newXref.set("ID", [xrefInfo.fileIds[0], md5]);
58208
+ newXref.set("ID", [xrefInfo.fileIds[0] || md5, md5]);
58169
58209
  }
58170
58210
  }
58171
58211
  function getTrailerDict(xrefInfo, changes, useXrefStream) {
58172
58212
  const newXref = new Dict(null);
58173
- newXref.set("Prev", xrefInfo.startXRef);
58213
+ newXref.setIfDefined("Prev", xrefInfo?.startXRef);
58174
58214
  const refForXrefTable = xrefInfo.newRef;
58175
58215
  if (useXrefStream) {
58176
58216
  changes.put(refForXrefTable, {
@@ -58181,22 +58221,27 @@ function getTrailerDict(xrefInfo, changes, useXrefStream) {
58181
58221
  } else {
58182
58222
  newXref.set("Size", refForXrefTable.num);
58183
58223
  }
58184
- if (xrefInfo.rootRef !== null) {
58185
- newXref.set("Root", xrefInfo.rootRef);
58186
- }
58187
- if (xrefInfo.infoRef !== null) {
58188
- newXref.set("Info", xrefInfo.infoRef);
58189
- }
58190
- if (xrefInfo.encryptRef !== null) {
58191
- newXref.set("Encrypt", xrefInfo.encryptRef);
58192
- }
58224
+ newXref.setIfDefined("Root", xrefInfo?.rootRef);
58225
+ newXref.setIfDefined("Info", xrefInfo?.infoRef);
58226
+ newXref.setIfDefined("Encrypt", xrefInfo?.encryptRef);
58193
58227
  return newXref;
58194
58228
  }
58195
58229
  async function writeChanges(changes, xref, buffer = []) {
58196
58230
  const newRefs = [];
58197
58231
  for (const [ref, {
58198
- data
58232
+ data,
58233
+ objStreamRef,
58234
+ index
58199
58235
  }] of changes.items()) {
58236
+ if (objStreamRef) {
58237
+ newRefs.push({
58238
+ ref,
58239
+ data,
58240
+ objStreamRef,
58241
+ index
58242
+ });
58243
+ continue;
58244
+ }
58200
58245
  if (data === null || typeof data === "string") {
58201
58246
  newRefs.push({
58202
58247
  ref,
@@ -58272,6 +58317,1310 @@ async function incrementalUpdate({
58272
58317
  return array;
58273
58318
  }
58274
58319
 
58320
+ ;// ./src/core/editor/pdf_editor.js
58321
+
58322
+
58323
+
58324
+
58325
+
58326
+
58327
+
58328
+ const MAX_LEAVES_PER_PAGES_NODE = 16;
58329
+ const MAX_IN_NAME_TREE_NODE = 64;
58330
+ class PageData {
58331
+ constructor(page, documentData) {
58332
+ this.page = page;
58333
+ this.documentData = documentData;
58334
+ this.annotations = null;
58335
+ this.pointingNamedDestinations = null;
58336
+ documentData.pagesMap.put(page.ref, this);
58337
+ }
58338
+ }
58339
+ class DocumentData {
58340
+ constructor(document) {
58341
+ this.document = document;
58342
+ this.destinations = null;
58343
+ this.pageLabels = null;
58344
+ this.pagesMap = new RefSetCache();
58345
+ this.oldRefMapping = new RefSetCache();
58346
+ this.dedupNamedDestinations = new Map();
58347
+ this.usedNamedDestinations = new Set();
58348
+ this.postponedRefCopies = new RefSetCache();
58349
+ this.usedStructParents = new Set();
58350
+ this.oldStructParentMapping = new Map();
58351
+ this.structTreeRoot = null;
58352
+ this.parentTree = null;
58353
+ this.idTree = null;
58354
+ this.roleMap = null;
58355
+ this.classMap = null;
58356
+ this.namespaces = null;
58357
+ this.structTreeAF = null;
58358
+ this.structTreePronunciationLexicon = [];
58359
+ }
58360
+ }
58361
+ class XRefWrapper {
58362
+ constructor(entries) {
58363
+ this.entries = entries;
58364
+ }
58365
+ fetch(ref) {
58366
+ return ref instanceof Ref ? this.entries[ref.num] : ref;
58367
+ }
58368
+ }
58369
+ class PDFEditor {
58370
+ constructor({
58371
+ useObjectStreams = true,
58372
+ title = "",
58373
+ author = ""
58374
+ } = {}) {
58375
+ this.hasSingleFile = false;
58376
+ this.currentDocument = null;
58377
+ this.oldPages = [];
58378
+ this.newPages = [];
58379
+ this.xref = [null];
58380
+ this.xrefWrapper = new XRefWrapper(this.xref);
58381
+ this.newRefCount = 1;
58382
+ [this.rootRef, this.rootDict] = this.newDict;
58383
+ [this.infoRef, this.infoDict] = this.newDict;
58384
+ [this.pagesRef, this.pagesDict] = this.newDict;
58385
+ this.namesDict = null;
58386
+ this.useObjectStreams = useObjectStreams;
58387
+ this.objStreamRefs = useObjectStreams ? new Set() : null;
58388
+ this.version = "1.7";
58389
+ this.title = title;
58390
+ this.author = author;
58391
+ this.pageLabels = null;
58392
+ this.namedDestinations = new Map();
58393
+ this.parentTree = new Map();
58394
+ this.structTreeKids = [];
58395
+ this.idTree = new Map();
58396
+ this.classMap = new Dict();
58397
+ this.roleMap = new Dict();
58398
+ this.namespaces = new Map();
58399
+ this.structTreeAF = [];
58400
+ this.structTreePronunciationLexicon = [];
58401
+ }
58402
+ get newRef() {
58403
+ const ref = Ref.get(this.newRefCount++, 0);
58404
+ return ref;
58405
+ }
58406
+ get newDict() {
58407
+ const ref = this.newRef;
58408
+ const dict = this.xref[ref.num] = new Dict();
58409
+ return [ref, dict];
58410
+ }
58411
+ async #cloneObject(obj, xref) {
58412
+ const ref = this.newRef;
58413
+ this.xref[ref.num] = await this.#collectDependencies(obj, true, xref);
58414
+ return ref;
58415
+ }
58416
+ cloneDict(dict) {
58417
+ const newDict = dict.clone();
58418
+ newDict.xref = this.xrefWrapper;
58419
+ return newDict;
58420
+ }
58421
+ async #collectDependencies(obj, mustClone, xref) {
58422
+ if (obj instanceof Ref) {
58423
+ const {
58424
+ currentDocument: {
58425
+ oldRefMapping
58426
+ }
58427
+ } = this;
58428
+ let newRef = oldRefMapping.get(obj);
58429
+ if (newRef) {
58430
+ return newRef;
58431
+ }
58432
+ const oldRef = obj;
58433
+ obj = await xref.fetchAsync(oldRef);
58434
+ if (typeof obj === "number") {
58435
+ return obj;
58436
+ }
58437
+ newRef = this.newRef;
58438
+ oldRefMapping.put(oldRef, newRef);
58439
+ this.xref[newRef.num] = await this.#collectDependencies(obj, true, xref);
58440
+ return newRef;
58441
+ }
58442
+ const promises = [];
58443
+ const {
58444
+ currentDocument: {
58445
+ postponedRefCopies
58446
+ }
58447
+ } = this;
58448
+ if (Array.isArray(obj)) {
58449
+ if (mustClone) {
58450
+ obj = obj.slice();
58451
+ }
58452
+ for (let i = 0, ii = obj.length; i < ii; i++) {
58453
+ const postponedActions = postponedRefCopies.get(obj[i]);
58454
+ if (postponedActions) {
58455
+ postponedActions.push(ref => obj[i] = ref);
58456
+ continue;
58457
+ }
58458
+ promises.push(this.#collectDependencies(obj[i], true, xref).then(newObj => obj[i] = newObj));
58459
+ }
58460
+ await Promise.all(promises);
58461
+ return obj;
58462
+ }
58463
+ let dict;
58464
+ if (obj instanceof BaseStream) {
58465
+ ({
58466
+ dict
58467
+ } = obj = obj.getOriginalStream().clone());
58468
+ dict.xref = this.xrefWrapper;
58469
+ } else if (obj instanceof Dict) {
58470
+ if (mustClone) {
58471
+ obj = obj.clone();
58472
+ obj.xref = this.xrefWrapper;
58473
+ }
58474
+ dict = obj;
58475
+ }
58476
+ if (dict) {
58477
+ for (const [key, rawObj] of dict.getRawEntries()) {
58478
+ const postponedActions = postponedRefCopies.get(rawObj);
58479
+ if (postponedActions) {
58480
+ postponedActions.push(ref => dict.set(key, ref));
58481
+ continue;
58482
+ }
58483
+ promises.push(this.#collectDependencies(rawObj, true, xref).then(newObj => dict.set(key, newObj)));
58484
+ }
58485
+ await Promise.all(promises);
58486
+ }
58487
+ return obj;
58488
+ }
58489
+ async #cloneStructTreeNode(parentStructRef, node, xref, removedStructElements, dedupIDs, dedupClasses, dedupRoles, visited = new RefSet()) {
58490
+ const {
58491
+ currentDocument: {
58492
+ pagesMap,
58493
+ oldRefMapping
58494
+ }
58495
+ } = this;
58496
+ const pg = node.getRaw("Pg");
58497
+ if (pg instanceof Ref && !pagesMap.has(pg)) {
58498
+ return null;
58499
+ }
58500
+ let kids;
58501
+ const k = kids = node.getRaw("K");
58502
+ if (k instanceof Ref) {
58503
+ if (visited.has(k)) {
58504
+ return null;
58505
+ }
58506
+ kids = await xref.fetchAsync(k);
58507
+ if (!Array.isArray(kids)) {
58508
+ kids = [k];
58509
+ }
58510
+ }
58511
+ kids = Array.isArray(kids) ? kids : [kids];
58512
+ const newKids = [];
58513
+ const structElemIndices = [];
58514
+ for (let kid of kids) {
58515
+ const kidRef = kid instanceof Ref ? kid : null;
58516
+ if (kidRef) {
58517
+ if (visited.has(kidRef)) {
58518
+ continue;
58519
+ }
58520
+ visited.put(kidRef);
58521
+ kid = await xref.fetchAsync(kidRef);
58522
+ }
58523
+ if (typeof kid === "number") {
58524
+ newKids.push(kid);
58525
+ continue;
58526
+ }
58527
+ if (!(kid instanceof Dict)) {
58528
+ continue;
58529
+ }
58530
+ const pgRef = kid.getRaw("Pg");
58531
+ if (pgRef instanceof Ref && !pagesMap.has(pgRef)) {
58532
+ continue;
58533
+ }
58534
+ const type = kid.get("Type");
58535
+ if (!type || isName(type, "StructElem")) {
58536
+ let setAsSpan = false;
58537
+ if (kidRef && removedStructElements.has(kidRef)) {
58538
+ if (!isName(kid.get("S"), "Link")) {
58539
+ continue;
58540
+ }
58541
+ setAsSpan = true;
58542
+ }
58543
+ const newKidRef = await this.#cloneStructTreeNode(kidRef, kid, xref, removedStructElements, dedupIDs, dedupClasses, dedupRoles, visited);
58544
+ if (newKidRef) {
58545
+ structElemIndices.push(newKids.length);
58546
+ newKids.push(newKidRef);
58547
+ if (kidRef) {
58548
+ oldRefMapping.put(kidRef, newKidRef);
58549
+ }
58550
+ if (setAsSpan) {
58551
+ this.xref[newKidRef.num].setIfName("S", "Span");
58552
+ }
58553
+ }
58554
+ continue;
58555
+ }
58556
+ if (isName(type, "OBJR")) {
58557
+ if (!kidRef) {
58558
+ continue;
58559
+ }
58560
+ const newKidRef = oldRefMapping.get(kidRef);
58561
+ if (!newKidRef) {
58562
+ continue;
58563
+ }
58564
+ const newKid = this.xref[newKidRef.num];
58565
+ const objRef = newKid.getRaw("Obj");
58566
+ if (objRef instanceof Ref) {
58567
+ const obj = this.xref[objRef.num];
58568
+ if (obj instanceof Dict && !obj.has("StructParent") && parentStructRef) {
58569
+ const structParent = this.parentTree.size;
58570
+ this.parentTree.set(structParent, [oldRefMapping, parentStructRef]);
58571
+ obj.set("StructParent", structParent);
58572
+ }
58573
+ }
58574
+ newKids.push(newKidRef);
58575
+ continue;
58576
+ }
58577
+ if (isName(type, "MCR")) {
58578
+ const newKid = await this.#collectDependencies(kidRef || kid, true, xref);
58579
+ newKids.push(newKid);
58580
+ continue;
58581
+ }
58582
+ if (kidRef) {
58583
+ const newKidRef = await this.#collectDependencies(kidRef, true, xref);
58584
+ newKids.push(newKidRef);
58585
+ }
58586
+ }
58587
+ if (kids.length !== 0 && newKids.length === 0) {
58588
+ return null;
58589
+ }
58590
+ const newNodeRef = this.newRef;
58591
+ const newNode = this.xref[newNodeRef.num] = this.cloneDict(node);
58592
+ newNode.delete("ID");
58593
+ newNode.delete("C");
58594
+ newNode.delete("K");
58595
+ newNode.delete("P");
58596
+ newNode.delete("S");
58597
+ await this.#collectDependencies(newNode, false, xref);
58598
+ const classNames = node.get("C");
58599
+ if (classNames instanceof Name) {
58600
+ const newClassName = dedupClasses.get(classNames.name);
58601
+ if (newClassName) {
58602
+ newNode.set("C", Name.get(newClassName));
58603
+ } else {
58604
+ newNode.set("C", classNames);
58605
+ }
58606
+ } else if (Array.isArray(classNames)) {
58607
+ const newClassNames = [];
58608
+ for (const className of classNames) {
58609
+ if (className instanceof Name) {
58610
+ const newClassName = dedupClasses.get(className.name);
58611
+ if (newClassName) {
58612
+ newClassNames.push(Name.get(newClassName));
58613
+ } else {
58614
+ newClassNames.push(className);
58615
+ }
58616
+ }
58617
+ }
58618
+ newNode.set("C", newClassNames);
58619
+ }
58620
+ const roleName = node.get("S");
58621
+ if (roleName instanceof Name) {
58622
+ const newRoleName = dedupRoles.get(roleName.name);
58623
+ if (newRoleName) {
58624
+ newNode.set("S", Name.get(newRoleName));
58625
+ } else {
58626
+ newNode.set("S", roleName);
58627
+ }
58628
+ }
58629
+ const id = node.get("ID");
58630
+ if (typeof id === "string") {
58631
+ const stringId = stringToPDFString(id, false);
58632
+ const newId = dedupIDs.get(stringId);
58633
+ if (newId) {
58634
+ newNode.set("ID", stringToAsciiOrUTF16BE(newId));
58635
+ } else {
58636
+ newNode.set("ID", id);
58637
+ }
58638
+ }
58639
+ let attributes = newNode.get("A");
58640
+ if (attributes) {
58641
+ if (!Array.isArray(attributes)) {
58642
+ attributes = [attributes];
58643
+ }
58644
+ for (let attr of attributes) {
58645
+ attr = this.xrefWrapper.fetch(attr);
58646
+ if (isName(attr.get("O"), "Table") && attr.has("Headers")) {
58647
+ const headers = this.xrefWrapper.fetch(attr.getRaw("Headers"));
58648
+ if (Array.isArray(headers)) {
58649
+ for (let i = 0, ii = headers.length; i < ii; i++) {
58650
+ const newId = dedupIDs.get(stringToPDFString(headers[i], false));
58651
+ if (newId) {
58652
+ headers[i] = newId;
58653
+ }
58654
+ }
58655
+ }
58656
+ }
58657
+ }
58658
+ }
58659
+ for (const index of structElemIndices) {
58660
+ const structElemRef = newKids[index];
58661
+ const structElem = this.xref[structElemRef.num];
58662
+ structElem.set("P", newNodeRef);
58663
+ }
58664
+ if (newKids.length === 1) {
58665
+ newNode.set("K", newKids[0]);
58666
+ } else if (newKids.length > 1) {
58667
+ newNode.set("K", newKids);
58668
+ }
58669
+ return newNodeRef;
58670
+ }
58671
+ async extractPages(pageInfos) {
58672
+ const promises = [];
58673
+ let newIndex = 0;
58674
+ this.hasSingleFile = pageInfos.length === 1;
58675
+ const allDocumentData = [];
58676
+ for (const {
58677
+ document,
58678
+ includePages,
58679
+ excludePages
58680
+ } of pageInfos) {
58681
+ if (!document) {
58682
+ continue;
58683
+ }
58684
+ const documentData = new DocumentData(document);
58685
+ allDocumentData.push(documentData);
58686
+ promises.push(this.#collectDocumentData(documentData));
58687
+ let keptIndices, keptRanges, deletedIndices, deletedRanges;
58688
+ for (const page of includePages || []) {
58689
+ if (Array.isArray(page)) {
58690
+ (keptRanges ||= []).push(page);
58691
+ } else {
58692
+ (keptIndices ||= new Set()).add(page);
58693
+ }
58694
+ }
58695
+ for (const page of excludePages || []) {
58696
+ if (Array.isArray(page)) {
58697
+ (deletedRanges ||= []).push(page);
58698
+ } else {
58699
+ (deletedIndices ||= new Set()).add(page);
58700
+ }
58701
+ }
58702
+ for (let i = 0, ii = document.numPages; i < ii; i++) {
58703
+ if (deletedIndices?.has(i)) {
58704
+ continue;
58705
+ }
58706
+ if (deletedRanges) {
58707
+ let isDeleted = false;
58708
+ for (const [start, end] of deletedRanges) {
58709
+ if (i >= start && i <= end) {
58710
+ isDeleted = true;
58711
+ break;
58712
+ }
58713
+ }
58714
+ if (isDeleted) {
58715
+ continue;
58716
+ }
58717
+ }
58718
+ let takePage = false;
58719
+ if (keptIndices) {
58720
+ takePage = keptIndices.has(i);
58721
+ }
58722
+ if (!takePage && keptRanges) {
58723
+ for (const [start, end] of keptRanges) {
58724
+ if (i >= start && i <= end) {
58725
+ takePage = true;
58726
+ break;
58727
+ }
58728
+ }
58729
+ }
58730
+ if (!takePage && !keptIndices && !keptRanges) {
58731
+ takePage = true;
58732
+ }
58733
+ if (!takePage) {
58734
+ continue;
58735
+ }
58736
+ const newPageIndex = newIndex++;
58737
+ promises.push(document.getPage(i).then(page => {
58738
+ this.oldPages[newPageIndex] = new PageData(page, documentData);
58739
+ }));
58740
+ }
58741
+ }
58742
+ await Promise.all(promises);
58743
+ promises.length = 0;
58744
+ this.#collectValidDestinations(allDocumentData);
58745
+ this.#collectPageLabels();
58746
+ for (const page of this.oldPages) {
58747
+ promises.push(this.#postCollectPageData(page));
58748
+ }
58749
+ await Promise.all(promises);
58750
+ this.#findDuplicateNamedDestinations();
58751
+ this.#setPostponedRefCopies(allDocumentData);
58752
+ for (let i = 0, ii = this.oldPages.length; i < ii; i++) {
58753
+ this.newPages[i] = await this.#makePageCopy(i, null);
58754
+ }
58755
+ this.#fixPostponedRefCopies(allDocumentData);
58756
+ await this.#mergeStructTrees(allDocumentData);
58757
+ return this.writePDF();
58758
+ }
58759
+ async #collectDocumentData(documentData) {
58760
+ const {
58761
+ document: {
58762
+ pdfManager,
58763
+ xref
58764
+ }
58765
+ } = documentData;
58766
+ await Promise.all([pdfManager.ensureCatalog("destinations").then(destinations => documentData.destinations = destinations), pdfManager.ensureCatalog("rawPageLabels").then(pageLabels => documentData.pageLabels = pageLabels), pdfManager.ensureCatalog("structTreeRoot").then(structTreeRoot => documentData.structTreeRoot = structTreeRoot)]);
58767
+ const structTreeRoot = documentData.structTreeRoot;
58768
+ if (structTreeRoot) {
58769
+ const rootDict = structTreeRoot.dict;
58770
+ const parentTree = rootDict.get("ParentTree");
58771
+ if (parentTree) {
58772
+ const numberTree = new NumberTree(parentTree, xref);
58773
+ documentData.parentTree = numberTree.getAll(true);
58774
+ }
58775
+ const idTree = rootDict.get("IDTree");
58776
+ if (idTree) {
58777
+ const nameTree = new NameTree(idTree, xref);
58778
+ documentData.idTree = nameTree.getAll(true);
58779
+ }
58780
+ documentData.roleMap = rootDict.get("RoleMap") || null;
58781
+ documentData.classMap = rootDict.get("ClassMap") || null;
58782
+ let namespaces = rootDict.get("Namespaces") || null;
58783
+ if (namespaces && !Array.isArray(namespaces)) {
58784
+ namespaces = [namespaces];
58785
+ }
58786
+ documentData.namespaces = namespaces;
58787
+ documentData.structTreeAF = rootDict.get("AF") || null;
58788
+ documentData.structTreePronunciationLexicon = rootDict.get("PronunciationLexicon") || null;
58789
+ }
58790
+ }
58791
+ async #postCollectPageData(pageData) {
58792
+ const {
58793
+ page: {
58794
+ xref,
58795
+ annotations
58796
+ },
58797
+ documentData: {
58798
+ pagesMap,
58799
+ destinations,
58800
+ usedNamedDestinations
58801
+ }
58802
+ } = pageData;
58803
+ if (!annotations) {
58804
+ return;
58805
+ }
58806
+ const promises = [];
58807
+ let newAnnotations = [];
58808
+ let newIndex = 0;
58809
+ for (const annotationRef of annotations) {
58810
+ const newAnnotationIndex = newIndex++;
58811
+ promises.push(xref.fetchIfRefAsync(annotationRef).then(async annotationDict => {
58812
+ if (!isName(annotationDict.get("Subtype"), "Link")) {
58813
+ newAnnotations[newAnnotationIndex] = annotationRef;
58814
+ return;
58815
+ }
58816
+ const action = annotationDict.get("A");
58817
+ const dest = action instanceof Dict ? action.get("D") : annotationDict.get("Dest");
58818
+ if (!dest || Array.isArray(dest) && (!(dest[0] instanceof Ref) || pagesMap.has(dest[0]))) {
58819
+ newAnnotations[newAnnotationIndex] = annotationRef;
58820
+ } else if (typeof dest === "string") {
58821
+ const destString = stringToPDFString(dest, true);
58822
+ if (destinations.has(destString)) {
58823
+ newAnnotations[newAnnotationIndex] = annotationRef;
58824
+ usedNamedDestinations.add(destString);
58825
+ }
58826
+ }
58827
+ }));
58828
+ }
58829
+ await Promise.all(promises);
58830
+ newAnnotations = newAnnotations.filter(annot => !!annot);
58831
+ pageData.annotations = newAnnotations.length > 0 ? newAnnotations : null;
58832
+ }
58833
+ #setPostponedRefCopies(allDocumentData) {
58834
+ for (const {
58835
+ postponedRefCopies,
58836
+ pagesMap
58837
+ } of allDocumentData) {
58838
+ for (const oldPageRef of pagesMap.keys()) {
58839
+ postponedRefCopies.put(oldPageRef, []);
58840
+ }
58841
+ }
58842
+ }
58843
+ #fixPostponedRefCopies(allDocumentData) {
58844
+ for (const {
58845
+ postponedRefCopies,
58846
+ oldRefMapping
58847
+ } of allDocumentData) {
58848
+ for (const [oldRef, actions] of postponedRefCopies.items()) {
58849
+ const newRef = oldRefMapping.get(oldRef);
58850
+ for (const action of actions) {
58851
+ action(newRef);
58852
+ }
58853
+ }
58854
+ postponedRefCopies.clear();
58855
+ }
58856
+ }
58857
+ #visitObject(obj, callback, visited = new RefSet()) {
58858
+ if (obj instanceof Ref) {
58859
+ if (!visited.has(obj)) {
58860
+ visited.put(obj);
58861
+ this.#visitObject(this.xref[obj.num], callback, visited);
58862
+ }
58863
+ return;
58864
+ }
58865
+ if (Array.isArray(obj)) {
58866
+ for (const item of obj) {
58867
+ this.#visitObject(item, callback, visited);
58868
+ }
58869
+ return;
58870
+ }
58871
+ let dict;
58872
+ if (obj instanceof BaseStream) {
58873
+ ({
58874
+ dict
58875
+ } = obj);
58876
+ } else if (obj instanceof Dict) {
58877
+ dict = obj;
58878
+ }
58879
+ if (dict) {
58880
+ callback(dict);
58881
+ for (const value of dict.getRawValues()) {
58882
+ this.#visitObject(value, callback, visited);
58883
+ }
58884
+ }
58885
+ }
58886
+ async #mergeStructTrees(allDocumentData) {
58887
+ let newStructParentId = 0;
58888
+ const {
58889
+ parentTree: newParentTree
58890
+ } = this;
58891
+ for (let i = 0, ii = this.newPages.length; i < ii; i++) {
58892
+ const {
58893
+ documentData: {
58894
+ parentTree,
58895
+ oldRefMapping,
58896
+ oldStructParentMapping,
58897
+ usedStructParents,
58898
+ document: {
58899
+ xref
58900
+ }
58901
+ }
58902
+ } = this.oldPages[i];
58903
+ if (!parentTree) {
58904
+ continue;
58905
+ }
58906
+ const pageRef = this.newPages[i];
58907
+ const pageDict = this.xref[pageRef.num];
58908
+ this.#visitObject(pageDict, dict => {
58909
+ const structParent = dict.get("StructParent") ?? dict.get("StructParents");
58910
+ if (typeof structParent !== "number") {
58911
+ return;
58912
+ }
58913
+ usedStructParents.add(structParent);
58914
+ let parent = parentTree.get(structParent);
58915
+ const parentRef = parent instanceof Ref ? parent : null;
58916
+ if (parentRef) {
58917
+ const array = xref.fetch(parentRef);
58918
+ if (Array.isArray(array)) {
58919
+ parent = array;
58920
+ }
58921
+ }
58922
+ if (Array.isArray(parent) && parent.every(ref => ref === null)) {
58923
+ parent = null;
58924
+ }
58925
+ if (!parent) {
58926
+ if (dict.has("StructParent")) {
58927
+ dict.delete("StructParent");
58928
+ } else {
58929
+ dict.delete("StructParents");
58930
+ }
58931
+ return;
58932
+ }
58933
+ let newStructParent = oldStructParentMapping.get(structParent);
58934
+ if (newStructParent === undefined) {
58935
+ newStructParent = newStructParentId++;
58936
+ oldStructParentMapping.set(structParent, newStructParent);
58937
+ newParentTree.set(newStructParent, [oldRefMapping, parent]);
58938
+ }
58939
+ if (dict.has("StructParent")) {
58940
+ dict.set("StructParent", newStructParent);
58941
+ } else {
58942
+ dict.set("StructParents", newStructParent);
58943
+ }
58944
+ });
58945
+ }
58946
+ const {
58947
+ structTreeKids,
58948
+ idTree: newIdTree,
58949
+ classMap: newClassMap,
58950
+ roleMap: newRoleMap,
58951
+ namespaces: newNamespaces,
58952
+ structTreeAF: newStructTreeAF,
58953
+ structTreePronunciationLexicon: newStructTreePronunciationLexicon
58954
+ } = this;
58955
+ for (const documentData of allDocumentData) {
58956
+ const {
58957
+ document: {
58958
+ xref
58959
+ },
58960
+ oldRefMapping,
58961
+ parentTree,
58962
+ usedStructParents,
58963
+ structTreeRoot,
58964
+ idTree,
58965
+ classMap,
58966
+ roleMap,
58967
+ namespaces,
58968
+ structTreeAF,
58969
+ structTreePronunciationLexicon
58970
+ } = documentData;
58971
+ if (!structTreeRoot) {
58972
+ continue;
58973
+ }
58974
+ this.currentDocument = documentData;
58975
+ const removedStructElements = new RefSet();
58976
+ for (const [key, value] of parentTree || []) {
58977
+ if (!usedStructParents.has(key) && value instanceof Ref) {
58978
+ removedStructElements.put(value);
58979
+ }
58980
+ }
58981
+ const dedupIDs = new Map();
58982
+ for (const [id, nodeRef] of idTree || []) {
58983
+ let _id = id;
58984
+ if (newIdTree.has(id)) {
58985
+ for (let i = 1;; i++) {
58986
+ const newId = `${id}_${i}`;
58987
+ if (!newIdTree.has(newId)) {
58988
+ dedupIDs.set(id, newId);
58989
+ _id = newId;
58990
+ break;
58991
+ }
58992
+ }
58993
+ }
58994
+ newIdTree.set(_id, nodeRef);
58995
+ }
58996
+ const dedupClasses = new Map();
58997
+ if (classMap?.size > 0) {
58998
+ for (let [className, classDict] of classMap) {
58999
+ classDict = await this.#collectDependencies(classDict, true, xref);
59000
+ if (newClassMap.has(className)) {
59001
+ for (let i = 1;; i++) {
59002
+ const newClassName = `${className}_${i}`;
59003
+ if (!newClassMap.has(newClassName)) {
59004
+ dedupClasses.set(className, newClassName);
59005
+ className = newClassName;
59006
+ break;
59007
+ }
59008
+ }
59009
+ }
59010
+ newClassMap.set(className, classDict);
59011
+ }
59012
+ }
59013
+ const dedupRoles = new Map();
59014
+ if (roleMap?.size > 0) {
59015
+ for (const [roleName, mappedName] of roleMap) {
59016
+ const newMappedName = newRoleMap.get(roleName);
59017
+ if (!newMappedName) {
59018
+ newRoleMap.set(roleName, mappedName);
59019
+ continue;
59020
+ }
59021
+ if (newMappedName === mappedName) {
59022
+ continue;
59023
+ }
59024
+ for (let i = 1;; i++) {
59025
+ const newRoleName = `${roleName}_${i}`;
59026
+ if (!newRoleMap.has(newRoleName)) {
59027
+ dedupRoles.set(roleName, newRoleName);
59028
+ newRoleMap.set(newRoleName, mappedName);
59029
+ break;
59030
+ }
59031
+ }
59032
+ }
59033
+ }
59034
+ if (namespaces?.length > 0) {
59035
+ for (const namespaceRef of namespaces) {
59036
+ const namespace = await xref.fetchIfRefAsync(namespaceRef);
59037
+ let ns = namespace.get("NS");
59038
+ if (!ns || newNamespaces.has(ns)) {
59039
+ continue;
59040
+ }
59041
+ ns = stringToPDFString(ns, false);
59042
+ const newNamespace = await this.#collectDependencies(namespace, true, xref);
59043
+ newNamespaces.set(ns, newNamespace);
59044
+ }
59045
+ }
59046
+ if (structTreeAF) {
59047
+ for (const afRef of structTreeAF) {
59048
+ newStructTreeAF.push(await this.#collectDependencies(afRef, true, xref));
59049
+ }
59050
+ }
59051
+ if (structTreePronunciationLexicon) {
59052
+ for (const lexiconRef of structTreePronunciationLexicon) {
59053
+ newStructTreePronunciationLexicon.push(await this.#collectDependencies(lexiconRef, true, xref));
59054
+ }
59055
+ }
59056
+ let kids = structTreeRoot.dict.get("K");
59057
+ if (!kids) {
59058
+ continue;
59059
+ }
59060
+ kids = Array.isArray(kids) ? kids : [kids];
59061
+ for (let kid of kids) {
59062
+ const kidRef = kid instanceof Ref ? kid : null;
59063
+ if (kidRef && removedStructElements.has(kidRef)) {
59064
+ continue;
59065
+ }
59066
+ kid = await xref.fetchIfRefAsync(kid);
59067
+ const newKidRef = await this.#cloneStructTreeNode(kidRef, kid, xref, removedStructElements, dedupIDs, dedupClasses, dedupRoles);
59068
+ if (newKidRef) {
59069
+ structTreeKids.push(newKidRef);
59070
+ }
59071
+ }
59072
+ for (const [id, nodeRef] of idTree || []) {
59073
+ const newNodeRef = oldRefMapping.get(nodeRef);
59074
+ const newId = dedupIDs.get(id) || id;
59075
+ if (newNodeRef) {
59076
+ newIdTree.set(newId, newNodeRef);
59077
+ } else {
59078
+ newIdTree.delete(newId);
59079
+ }
59080
+ }
59081
+ }
59082
+ for (const [key, [oldRefMapping, parent]] of newParentTree) {
59083
+ if (!parent) {
59084
+ newParentTree.delete(key);
59085
+ continue;
59086
+ }
59087
+ if (!Array.isArray(parent)) {
59088
+ const newParent = oldRefMapping.get(parent);
59089
+ if (newParent === undefined) {
59090
+ newParentTree.delete(key);
59091
+ } else {
59092
+ newParentTree.set(key, newParent);
59093
+ }
59094
+ continue;
59095
+ }
59096
+ const newParents = parent.map(ref => ref instanceof Ref && oldRefMapping.get(ref) || null);
59097
+ if (newParents.length === 0 || newParents.every(ref => ref === null)) {
59098
+ newParentTree.delete(key);
59099
+ continue;
59100
+ }
59101
+ newParentTree.set(key, newParents);
59102
+ }
59103
+ this.currentDocument = null;
59104
+ }
59105
+ #collectValidDestinations(allDocumentData) {
59106
+ for (const documentData of allDocumentData) {
59107
+ if (!documentData.destinations) {
59108
+ continue;
59109
+ }
59110
+ const {
59111
+ destinations,
59112
+ pagesMap
59113
+ } = documentData;
59114
+ const newDestinations = documentData.destinations = new Map();
59115
+ for (const [key, dest] of Object.entries(destinations)) {
59116
+ const pageRef = dest[0];
59117
+ const pageData = pagesMap.get(pageRef);
59118
+ if (!pageData) {
59119
+ continue;
59120
+ }
59121
+ (pageData.pointingNamedDestinations ||= new Set()).add(key);
59122
+ newDestinations.set(key, dest);
59123
+ }
59124
+ }
59125
+ }
59126
+ #findDuplicateNamedDestinations() {
59127
+ const {
59128
+ namedDestinations
59129
+ } = this;
59130
+ for (let i = 0, ii = this.oldPages.length; i < ii; i++) {
59131
+ const page = this.oldPages[i];
59132
+ const {
59133
+ documentData: {
59134
+ destinations,
59135
+ dedupNamedDestinations,
59136
+ usedNamedDestinations
59137
+ }
59138
+ } = page;
59139
+ let {
59140
+ pointingNamedDestinations
59141
+ } = page;
59142
+ if (!pointingNamedDestinations) {
59143
+ continue;
59144
+ }
59145
+ page.pointingNamedDestinations = pointingNamedDestinations = pointingNamedDestinations.intersection(usedNamedDestinations);
59146
+ for (const pointingDest of pointingNamedDestinations) {
59147
+ if (!usedNamedDestinations.has(pointingDest)) {
59148
+ continue;
59149
+ }
59150
+ const dest = destinations.get(pointingDest).slice();
59151
+ if (!namedDestinations.has(pointingDest)) {
59152
+ namedDestinations.set(pointingDest, dest);
59153
+ continue;
59154
+ }
59155
+ const newName = `${pointingDest}_p${i + 1}`;
59156
+ dedupNamedDestinations.set(pointingDest, newName);
59157
+ namedDestinations.set(newName, dest);
59158
+ }
59159
+ }
59160
+ }
59161
+ #fixNamedDestinations(annotations, dedupNamedDestinations) {
59162
+ if (dedupNamedDestinations.size === 0) {
59163
+ return;
59164
+ }
59165
+ const fixDestination = (dict, key, dest) => {
59166
+ if (typeof dest === "string") {
59167
+ dict.set(key, dedupNamedDestinations.get(stringToPDFString(dest, true)) || dest);
59168
+ }
59169
+ };
59170
+ for (const annotRef of annotations) {
59171
+ const annotDict = this.xref[annotRef.num];
59172
+ if (!isName(annotDict.get("Subtype"), "Link")) {
59173
+ continue;
59174
+ }
59175
+ const action = annotDict.get("A");
59176
+ if (action instanceof Dict && action.has("D")) {
59177
+ const dest = action.get("D");
59178
+ fixDestination(action, "D", dest);
59179
+ continue;
59180
+ }
59181
+ const dest = annotDict.get("Dest");
59182
+ fixDestination(annotDict, "Dest", dest);
59183
+ }
59184
+ }
59185
+ async #collectPageLabels() {
59186
+ if (!this.hasSingleFile) {
59187
+ return;
59188
+ }
59189
+ const {
59190
+ documentData: {
59191
+ document,
59192
+ pageLabels
59193
+ }
59194
+ } = this.oldPages[0];
59195
+ if (!pageLabels) {
59196
+ return;
59197
+ }
59198
+ const numPages = document.numPages;
59199
+ const oldPageLabels = [];
59200
+ const oldPageIndices = new Set(this.oldPages.map(({
59201
+ page: {
59202
+ pageIndex
59203
+ }
59204
+ }) => pageIndex));
59205
+ let currentLabel = null;
59206
+ let stFirstIndex = -1;
59207
+ for (let i = 0; i < numPages; i++) {
59208
+ const newLabel = pageLabels.get(i);
59209
+ if (newLabel) {
59210
+ currentLabel = newLabel;
59211
+ stFirstIndex = currentLabel.has("St") ? i : -1;
59212
+ }
59213
+ if (!oldPageIndices.has(i)) {
59214
+ continue;
59215
+ }
59216
+ if (stFirstIndex !== -1) {
59217
+ const st = currentLabel.get("St");
59218
+ currentLabel = this.cloneDict(currentLabel);
59219
+ currentLabel.set("St", st + (i - stFirstIndex));
59220
+ stFirstIndex = -1;
59221
+ }
59222
+ oldPageLabels.push(currentLabel);
59223
+ }
59224
+ currentLabel = oldPageLabels[0];
59225
+ let currentIndex = 0;
59226
+ const newPageLabels = this.pageLabels = [[0, currentLabel]];
59227
+ for (let i = 0, ii = oldPageLabels.length; i < ii; i++) {
59228
+ const label = oldPageLabels[i];
59229
+ if (label === currentLabel) {
59230
+ continue;
59231
+ }
59232
+ currentIndex = i;
59233
+ currentLabel = label;
59234
+ newPageLabels.push([currentIndex, currentLabel]);
59235
+ }
59236
+ }
59237
+ async #makePageCopy(pageIndex) {
59238
+ const {
59239
+ page,
59240
+ documentData,
59241
+ annotations,
59242
+ pointingNamedDestinations
59243
+ } = this.oldPages[pageIndex];
59244
+ this.currentDocument = documentData;
59245
+ const {
59246
+ dedupNamedDestinations,
59247
+ oldRefMapping
59248
+ } = documentData;
59249
+ const {
59250
+ xref,
59251
+ rotate,
59252
+ mediaBox,
59253
+ resources,
59254
+ ref: oldPageRef
59255
+ } = page;
59256
+ const pageRef = this.newRef;
59257
+ const pageDict = this.xref[pageRef.num] = this.cloneDict(page.pageDict);
59258
+ oldRefMapping.put(oldPageRef, pageRef);
59259
+ if (pointingNamedDestinations) {
59260
+ for (const pointingDest of pointingNamedDestinations) {
59261
+ const name = dedupNamedDestinations.get(pointingDest) || pointingDest;
59262
+ const dest = this.namedDestinations.get(name);
59263
+ dest[0] = pageRef;
59264
+ }
59265
+ }
59266
+ for (const key of ["Rotate", "MediaBox", "CropBox", "BleedBox", "TrimBox", "ArtBox", "Resources", "Annots", "Parent", "UserUnit"]) {
59267
+ pageDict.delete(key);
59268
+ }
59269
+ const lastRef = this.newRefCount;
59270
+ await this.#collectDependencies(pageDict, false, xref);
59271
+ pageDict.set("Rotate", rotate);
59272
+ pageDict.set("MediaBox", mediaBox);
59273
+ for (const boxName of ["CropBox", "BleedBox", "TrimBox", "ArtBox"]) {
59274
+ const box = page.getBoundingBox(boxName);
59275
+ if (box?.some((value, index) => value !== mediaBox[index])) {
59276
+ pageDict.set(boxName, box);
59277
+ }
59278
+ }
59279
+ const userUnit = page.userUnit;
59280
+ if (userUnit !== 1) {
59281
+ pageDict.set("UserUnit", userUnit);
59282
+ }
59283
+ pageDict.setIfDict("Resources", await this.#collectDependencies(resources, true, xref));
59284
+ if (annotations) {
59285
+ const newAnnotations = await this.#collectDependencies(annotations, true, xref);
59286
+ this.#fixNamedDestinations(newAnnotations, dedupNamedDestinations);
59287
+ pageDict.setIfArray("Annots", newAnnotations);
59288
+ }
59289
+ if (this.useObjectStreams) {
59290
+ const newLastRef = this.newRefCount;
59291
+ const pageObjectRefs = [];
59292
+ for (let i = lastRef; i < newLastRef; i++) {
59293
+ const obj = this.xref[i];
59294
+ if (obj instanceof BaseStream) {
59295
+ continue;
59296
+ }
59297
+ pageObjectRefs.push(Ref.get(i, 0));
59298
+ }
59299
+ for (let i = 0; i < pageObjectRefs.length; i += 0xffff) {
59300
+ const objStreamRef = this.newRef;
59301
+ this.objStreamRefs.add(objStreamRef.num);
59302
+ this.xref[objStreamRef.num] = pageObjectRefs.slice(i, i + 0xffff);
59303
+ }
59304
+ }
59305
+ this.currentDocument = null;
59306
+ return pageRef;
59307
+ }
59308
+ #makePageTree() {
59309
+ const {
59310
+ newPages: pages,
59311
+ rootDict,
59312
+ pagesRef,
59313
+ pagesDict
59314
+ } = this;
59315
+ rootDict.set("Pages", pagesRef);
59316
+ pagesDict.setIfName("Type", "Pages");
59317
+ pagesDict.set("Count", pages.length);
59318
+ const maxLeaves = MAX_LEAVES_PER_PAGES_NODE <= 1 ? pages.length : MAX_LEAVES_PER_PAGES_NODE;
59319
+ const stack = [{
59320
+ dict: pagesDict,
59321
+ kids: pages,
59322
+ parentRef: pagesRef
59323
+ }];
59324
+ while (stack.length > 0) {
59325
+ const {
59326
+ dict,
59327
+ kids,
59328
+ parentRef
59329
+ } = stack.pop();
59330
+ if (kids.length <= maxLeaves) {
59331
+ dict.set("Kids", kids);
59332
+ for (const ref of kids) {
59333
+ this.xref[ref.num].set("Parent", parentRef);
59334
+ }
59335
+ continue;
59336
+ }
59337
+ const chunkSize = Math.max(maxLeaves, Math.ceil(kids.length / maxLeaves));
59338
+ const kidsChunks = [];
59339
+ for (let i = 0; i < kids.length; i += chunkSize) {
59340
+ kidsChunks.push(kids.slice(i, i + chunkSize));
59341
+ }
59342
+ const kidsRefs = [];
59343
+ dict.set("Kids", kidsRefs);
59344
+ for (const chunk of kidsChunks) {
59345
+ const [kidRef, kidDict] = this.newDict;
59346
+ kidsRefs.push(kidRef);
59347
+ kidDict.setIfName("Type", "Pages");
59348
+ kidDict.set("Parent", parentRef);
59349
+ kidDict.set("Count", chunk.length);
59350
+ stack.push({
59351
+ dict: kidDict,
59352
+ kids: chunk,
59353
+ parentRef: kidRef
59354
+ });
59355
+ }
59356
+ }
59357
+ }
59358
+ #makeNameNumTree(map, areNames) {
59359
+ const allEntries = map.sort(areNames ? ([keyA], [keyB]) => keyA.localeCompare(keyB) : ([keyA], [keyB]) => keyA - keyB);
59360
+ const maxLeaves = MAX_IN_NAME_TREE_NODE <= 1 ? allEntries.length : MAX_IN_NAME_TREE_NODE;
59361
+ const [treeRef, treeDict] = this.newDict;
59362
+ const stack = [{
59363
+ dict: treeDict,
59364
+ entries: allEntries
59365
+ }];
59366
+ const valueType = areNames ? "Names" : "Nums";
59367
+ while (stack.length > 0) {
59368
+ const {
59369
+ dict,
59370
+ entries
59371
+ } = stack.pop();
59372
+ if (entries.length <= maxLeaves) {
59373
+ dict.set("Limits", [entries[0][0], entries.at(-1)[0]]);
59374
+ dict.set(valueType, entries.flat());
59375
+ continue;
59376
+ }
59377
+ const entriesChunks = [];
59378
+ const chunkSize = Math.max(maxLeaves, Math.ceil(entries.length / maxLeaves));
59379
+ for (let i = 0; i < entries.length; i += chunkSize) {
59380
+ entriesChunks.push(entries.slice(i, i + chunkSize));
59381
+ }
59382
+ const entriesRefs = [];
59383
+ dict.set("Kids", entriesRefs);
59384
+ for (const chunk of entriesChunks) {
59385
+ const [entriesRef, entriesDict] = this.newDict;
59386
+ entriesRefs.push(entriesRef);
59387
+ entriesDict.set("Limits", [chunk[0][0], chunk.at(-1)[0]]);
59388
+ stack.push({
59389
+ dict: entriesDict,
59390
+ entries: chunk
59391
+ });
59392
+ }
59393
+ }
59394
+ return treeRef;
59395
+ }
59396
+ #makePageLabelsTree() {
59397
+ const {
59398
+ pageLabels
59399
+ } = this;
59400
+ if (!pageLabels || pageLabels.length === 0) {
59401
+ return;
59402
+ }
59403
+ const {
59404
+ rootDict
59405
+ } = this;
59406
+ const pageLabelsRef = this.#makeNameNumTree(this.pageLabels, false);
59407
+ rootDict.set("PageLabels", pageLabelsRef);
59408
+ }
59409
+ #makeDestinationsTree() {
59410
+ const {
59411
+ namedDestinations
59412
+ } = this;
59413
+ if (namedDestinations.size === 0) {
59414
+ return;
59415
+ }
59416
+ if (!this.namesDict) {
59417
+ [this.namesRef, this.namesDict] = this.newDict;
59418
+ this.rootDict.set("Names", this.namesRef);
59419
+ }
59420
+ this.namesDict.set("Dests", this.#makeNameNumTree(Array.from(namedDestinations.entries()), true));
59421
+ }
59422
+ #makeStructTree() {
59423
+ const {
59424
+ structTreeKids
59425
+ } = this;
59426
+ if (!structTreeKids || structTreeKids.length === 0) {
59427
+ return;
59428
+ }
59429
+ const {
59430
+ rootDict
59431
+ } = this;
59432
+ const structTreeRef = this.newRef;
59433
+ const structTree = this.xref[structTreeRef.num] = new Dict();
59434
+ structTree.setIfName("Type", "StructTreeRoot");
59435
+ structTree.setIfArray("K", structTreeKids);
59436
+ for (const kidRef of structTreeKids) {
59437
+ const kid = this.xref[kidRef.num];
59438
+ const type = kid.get("Type");
59439
+ if (!type || isName(type, "StructElem")) {
59440
+ kid.set("P", structTreeRef);
59441
+ }
59442
+ }
59443
+ if (this.parentTree.size > 0) {
59444
+ const parentTreeRef = this.#makeNameNumTree(Array.from(this.parentTree.entries()), false);
59445
+ const parentTree = this.xref[parentTreeRef.num];
59446
+ parentTree.setIfName("Type", "ParentTree");
59447
+ structTree.set("ParentTree", parentTreeRef);
59448
+ structTree.set("ParentTreeNextKey", this.parentTree.size);
59449
+ }
59450
+ if (this.idTree.size > 0) {
59451
+ const idTreeRef = this.#makeNameNumTree(Array.from(this.idTree.entries()), true);
59452
+ const idTree = this.xref[idTreeRef.num];
59453
+ idTree.setIfName("Type", "IDTree");
59454
+ structTree.set("IDTree", idTreeRef);
59455
+ }
59456
+ if (this.classMap.size > 0) {
59457
+ const classMapRef = this.newRef;
59458
+ this.xref[classMapRef.num] = this.classMap;
59459
+ structTree.set("ClassMap", classMapRef);
59460
+ }
59461
+ if (this.roleMap.size > 0) {
59462
+ const roleMapRef = this.newRef;
59463
+ this.xref[roleMapRef.num] = this.roleMap;
59464
+ structTree.set("RoleMap", roleMapRef);
59465
+ }
59466
+ if (this.namespaces.size > 0) {
59467
+ const namespacesRef = this.newRef;
59468
+ this.xref[namespacesRef.num] = Array.from(this.namespaces.values());
59469
+ structTree.set("Namespaces", namespacesRef);
59470
+ }
59471
+ if (this.structTreeAF.length > 0) {
59472
+ const structTreeAFRef = this.newRef;
59473
+ this.xref[structTreeAFRef.num] = this.structTreeAF;
59474
+ structTree.set("AF", structTreeAFRef);
59475
+ }
59476
+ if (this.structTreePronunciationLexicon.length > 0) {
59477
+ const structTreePronunciationLexiconRef = this.newRef;
59478
+ this.xref[structTreePronunciationLexiconRef.num] = this.structTreePronunciationLexicon;
59479
+ structTree.set("PronunciationLexicon", structTreePronunciationLexiconRef);
59480
+ }
59481
+ rootDict.set("StructTreeRoot", structTreeRef);
59482
+ }
59483
+ async #makeRoot() {
59484
+ const {
59485
+ rootDict
59486
+ } = this;
59487
+ rootDict.setIfName("Type", "Catalog");
59488
+ rootDict.setIfName("Version", this.version);
59489
+ this.#makePageTree();
59490
+ this.#makePageLabelsTree();
59491
+ this.#makeDestinationsTree();
59492
+ this.#makeStructTree();
59493
+ }
59494
+ #makeInfo() {
59495
+ const infoMap = new Map();
59496
+ if (this.hasSingleFile) {
59497
+ const {
59498
+ xref: {
59499
+ trailer
59500
+ }
59501
+ } = this.oldPages[0].documentData.document;
59502
+ const oldInfoDict = trailer.get("Info");
59503
+ for (const [key, value] of oldInfoDict || []) {
59504
+ if (typeof value === "string") {
59505
+ infoMap.set(key, stringToPDFString(value));
59506
+ }
59507
+ }
59508
+ }
59509
+ infoMap.delete("ModDate");
59510
+ infoMap.set("CreationDate", getModificationDate());
59511
+ infoMap.set("Creator", "PDF.js");
59512
+ infoMap.set("Producer", "Firefox");
59513
+ if (this.author) {
59514
+ infoMap.set("Author", this.author);
59515
+ }
59516
+ if (this.title) {
59517
+ infoMap.set("Title", this.title);
59518
+ }
59519
+ for (const [key, value] of infoMap) {
59520
+ this.infoDict.set(key, stringToAsciiOrUTF16BE(value));
59521
+ }
59522
+ return infoMap;
59523
+ }
59524
+ async #makeEncrypt() {
59525
+ if (!this.hasSingleFile) {
59526
+ return [null, null, null];
59527
+ }
59528
+ const {
59529
+ documentData
59530
+ } = this.oldPages[0];
59531
+ const {
59532
+ document: {
59533
+ xref: {
59534
+ trailer,
59535
+ encrypt
59536
+ }
59537
+ }
59538
+ } = documentData;
59539
+ if (!trailer.has("Encrypt")) {
59540
+ return [null, null, null];
59541
+ }
59542
+ const encryptDict = trailer.get("Encrypt");
59543
+ if (!(encryptDict instanceof Dict)) {
59544
+ return [null, null, null];
59545
+ }
59546
+ this.currentDocument = documentData;
59547
+ const result = [await this.#cloneObject(encryptDict, trailer.xref), encrypt, trailer.get("ID")];
59548
+ this.currentDocument = null;
59549
+ return result;
59550
+ }
59551
+ async #createChanges() {
59552
+ const changes = new RefSetCache();
59553
+ changes.put(Ref.get(0, 0xffff), {
59554
+ data: null
59555
+ });
59556
+ for (let i = 1, ii = this.xref.length; i < ii; i++) {
59557
+ if (this.objStreamRefs?.has(i)) {
59558
+ await this.#createObjectStream(Ref.get(i, 0), this.xref[i], changes);
59559
+ } else {
59560
+ changes.put(Ref.get(i, 0), {
59561
+ data: this.xref[i]
59562
+ });
59563
+ }
59564
+ }
59565
+ return [changes, this.newRef];
59566
+ }
59567
+ async #createObjectStream(objStreamRef, objRefs, changes) {
59568
+ const streamBuffer = [""];
59569
+ const objOffsets = [];
59570
+ let offset = 0;
59571
+ const buffer = [];
59572
+ for (let i = 0, ii = objRefs.length; i < ii; i++) {
59573
+ const objRef = objRefs[i];
59574
+ changes.put(objRef, {
59575
+ data: null,
59576
+ objStreamRef,
59577
+ index: i
59578
+ });
59579
+ objOffsets.push(`${objRef.num} ${offset}`);
59580
+ const data = this.xref[objRef.num];
59581
+ await writeValue(data, buffer, null);
59582
+ const obj = buffer.join("");
59583
+ buffer.length = 0;
59584
+ streamBuffer.push(obj);
59585
+ offset += obj.length + 1;
59586
+ }
59587
+ streamBuffer[0] = objOffsets.join("\n");
59588
+ const objStream = new StringStream(streamBuffer.join("\n"));
59589
+ const objStreamDict = objStream.dict = new Dict();
59590
+ objStreamDict.setIfName("Type", "ObjStm");
59591
+ objStreamDict.set("N", objRefs.length);
59592
+ objStreamDict.set("First", streamBuffer[0].length + 1);
59593
+ changes.put(objStreamRef, {
59594
+ data: objStream
59595
+ });
59596
+ }
59597
+ async writePDF() {
59598
+ await this.#makeRoot();
59599
+ const infoMap = this.#makeInfo();
59600
+ const [encryptRef, encrypt, fileIds] = await this.#makeEncrypt();
59601
+ const [changes, xrefTableRef] = await this.#createChanges();
59602
+ const header = [...`%PDF-${this.version}\n%`.split("").map(c => c.charCodeAt(0)), 0xfa, 0xde, 0xfa, 0xce];
59603
+ return incrementalUpdate({
59604
+ originalData: new Uint8Array(header),
59605
+ changes,
59606
+ xrefInfo: {
59607
+ startXRef: null,
59608
+ rootRef: this.rootRef,
59609
+ infoRef: this.infoRef,
59610
+ encryptRef,
59611
+ newRef: xrefTableRef,
59612
+ fileIds: fileIds || [null, null],
59613
+ infoMap
59614
+ },
59615
+ useXrefStream: this.useObjectStreams,
59616
+ xref: {
59617
+ encrypt,
59618
+ encryptRef
59619
+ }
59620
+ });
59621
+ }
59622
+ }
59623
+
58275
59624
  ;// ./src/core/worker_stream.js
58276
59625
 
58277
59626
  class PDFWorkerStream {
@@ -58390,6 +59739,7 @@ class PDFWorkerStreamRangeReader {
58390
59739
 
58391
59740
 
58392
59741
 
59742
+
58393
59743
  class WorkerTask {
58394
59744
  constructor(name) {
58395
59745
  this.name = name;
@@ -58441,7 +59791,7 @@ class WorkerMessageHandler {
58441
59791
  docId,
58442
59792
  apiVersion
58443
59793
  } = docParams;
58444
- const workerVersion = "5.4.394";
59794
+ const workerVersion = "5.4.449";
58445
59795
  if (apiVersion !== workerVersion) {
58446
59796
  throw new Error(`The API version "${apiVersion}" does not match ` + `the Worker version "${workerVersion}".`);
58447
59797
  }
@@ -58734,7 +60084,7 @@ class WorkerMessageHandler {
58734
60084
  return pdfManager.ensureCatalog("permissions");
58735
60085
  });
58736
60086
  handler.on("GetMetadata", function (data) {
58737
- return Promise.all([pdfManager.ensureDoc("documentInfo"), pdfManager.ensureCatalog("metadata")]);
60087
+ return Promise.all([pdfManager.ensureDoc("documentInfo"), pdfManager.ensureCatalog("metadata"), pdfManager.ensureCatalog("hasStructTree")]);
58738
60088
  });
58739
60089
  handler.on("GetMarkInfo", function (data) {
58740
60090
  return pdfManager.ensureCatalog("markInfo");
@@ -58767,6 +60117,92 @@ class WorkerMessageHandler {
58767
60117
  handler.on("GetCalculationOrderIds", function (data) {
58768
60118
  return pdfManager.ensureDoc("calculationOrderIds");
58769
60119
  });
60120
+ handler.on("ExtractPages", async function ({
60121
+ pageInfos
60122
+ }) {
60123
+ if (!pageInfos) {
60124
+ warn("extractPages: nothing to extract.");
60125
+ return null;
60126
+ }
60127
+ if (!Array.isArray(pageInfos)) {
60128
+ pageInfos = [pageInfos];
60129
+ }
60130
+ let newDocumentId = 0;
60131
+ for (const pageInfo of pageInfos) {
60132
+ if (pageInfo.document === null) {
60133
+ pageInfo.document = pdfManager.pdfDocument;
60134
+ } else if (ArrayBuffer.isView(pageInfo.document)) {
60135
+ const manager = new LocalPdfManager({
60136
+ source: pageInfo.document,
60137
+ docId: `${docId}_extractPages_${newDocumentId++}`,
60138
+ handler,
60139
+ password: pageInfo.password ?? null,
60140
+ evaluatorOptions: Object.assign({}, pdfManager.evaluatorOptions)
60141
+ });
60142
+ let recoveryMode = false;
60143
+ let isValid = true;
60144
+ while (true) {
60145
+ try {
60146
+ await manager.requestLoadedStream();
60147
+ await manager.ensureDoc("checkHeader");
60148
+ await manager.ensureDoc("parseStartXRef");
60149
+ await manager.ensureDoc("parse", [recoveryMode]);
60150
+ break;
60151
+ } catch (e) {
60152
+ if (e instanceof XRefParseException) {
60153
+ if (recoveryMode === false) {
60154
+ recoveryMode = true;
60155
+ continue;
60156
+ } else {
60157
+ isValid = false;
60158
+ warn("extractPages: XRefParseException.");
60159
+ }
60160
+ } else if (e instanceof PasswordException) {
60161
+ const task = new WorkerTask(`PasswordException: response ${e.code}`);
60162
+ startWorkerTask(task);
60163
+ try {
60164
+ const {
60165
+ password
60166
+ } = await handler.sendWithPromise("PasswordRequest", e);
60167
+ manager.updatePassword(password);
60168
+ } catch {
60169
+ isValid = false;
60170
+ warn("extractPages: invalid password.");
60171
+ } finally {
60172
+ finishWorkerTask(task);
60173
+ }
60174
+ } else {
60175
+ isValid = false;
60176
+ warn("extractPages: invalid document.");
60177
+ }
60178
+ if (!isValid) {
60179
+ break;
60180
+ }
60181
+ }
60182
+ }
60183
+ if (!isValid) {
60184
+ pageInfo.document = null;
60185
+ }
60186
+ const isPureXfa = await manager.ensureDoc("isPureXfa");
60187
+ if (isPureXfa) {
60188
+ pageInfo.document = null;
60189
+ warn("extractPages does not support pure XFA documents.");
60190
+ } else {
60191
+ pageInfo.document = manager.pdfDocument;
60192
+ }
60193
+ } else {
60194
+ warn("extractPages: invalid document.");
60195
+ }
60196
+ }
60197
+ try {
60198
+ const pdfEditor = new PDFEditor();
60199
+ const buffer = await pdfEditor.extractPages(pageInfos);
60200
+ return buffer;
60201
+ } catch (reason) {
60202
+ console.error(reason);
60203
+ return null;
60204
+ }
60205
+ });
58770
60206
  handler.on("SaveDocument", async function ({
58771
60207
  isPureXfa,
58772
60208
  numPages,