@awacloud/pdf 0.0.0-stage → 1.0.0

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 (345) hide show
  1. package/CHANGELOG.md +609 -0
  2. package/LICENSE +661 -0
  3. package/NOTICE +77 -0
  4. package/README.md +363 -2
  5. package/dist/build/index.js +21 -0
  6. package/dist/build/pdf-full-rw.js +10972 -0
  7. package/dist/build/pdf-full-rw.meta.json +105 -0
  8. package/dist/build/pdf-full-rw.min.js +53 -0
  9. package/dist/build/pdf-full.js +6078 -0
  10. package/dist/build/pdf-full.meta.json +90 -0
  11. package/dist/build/pdf-full.min.js +32 -0
  12. package/dist/build/pdf-large-rw.js +10367 -0
  13. package/dist/build/pdf-large-rw.meta.json +99 -0
  14. package/dist/build/pdf-large-rw.min.js +53 -0
  15. package/dist/build/pdf-large.js +5473 -0
  16. package/dist/build/pdf-large.meta.json +84 -0
  17. package/dist/build/pdf-large.min.js +32 -0
  18. package/dist/build/pdf-legacy-rw.js +12402 -0
  19. package/dist/build/pdf-legacy-rw.meta.json +110 -0
  20. package/dist/build/pdf-legacy-rw.min.js +53 -0
  21. package/dist/build/pdf-legacy.js +7508 -0
  22. package/dist/build/pdf-legacy.meta.json +95 -0
  23. package/dist/build/pdf-legacy.min.js +32 -0
  24. package/dist/build/pdf-rw.js +7578 -0
  25. package/dist/build/pdf-rw.meta.json +77 -0
  26. package/dist/build/pdf-rw.min.js +53 -0
  27. package/dist/build/pdf.js +2684 -0
  28. package/dist/build/pdf.meta.json +62 -0
  29. package/dist/build/pdf.min.js +32 -0
  30. package/dist/standalone/pdf-full-rw.js +16798 -0
  31. package/dist/standalone/pdf-full-rw.meta.json +78 -0
  32. package/dist/standalone/pdf-full-rw.min.js +56 -0
  33. package/dist/standalone/pdf-full.js +11904 -0
  34. package/dist/standalone/pdf-full.meta.json +63 -0
  35. package/dist/standalone/pdf-full.min.js +35 -0
  36. package/dist/standalone/pdf-large-rw.js +16193 -0
  37. package/dist/standalone/pdf-large-rw.meta.json +72 -0
  38. package/dist/standalone/pdf-large-rw.min.js +56 -0
  39. package/dist/standalone/pdf-large.js +11299 -0
  40. package/dist/standalone/pdf-large.meta.json +57 -0
  41. package/dist/standalone/pdf-large.min.js +35 -0
  42. package/dist/standalone/pdf-legacy-rw.js +18228 -0
  43. package/dist/standalone/pdf-legacy-rw.meta.json +83 -0
  44. package/dist/standalone/pdf-legacy-rw.min.js +56 -0
  45. package/dist/standalone/pdf-legacy.js +13334 -0
  46. package/dist/standalone/pdf-legacy.meta.json +68 -0
  47. package/dist/standalone/pdf-legacy.min.js +35 -0
  48. package/dist/standalone/pdf-rw.js +13404 -0
  49. package/dist/standalone/pdf-rw.meta.json +50 -0
  50. package/dist/standalone/pdf-rw.min.js +56 -0
  51. package/dist/standalone/pdf.js +8510 -0
  52. package/dist/standalone/pdf.meta.json +35 -0
  53. package/dist/standalone/pdf.min.js +35 -0
  54. package/docs/README.md +53 -0
  55. package/docs/api/README.md +38 -0
  56. package/docs/api/_shared/README.md +91 -0
  57. package/docs/api/action/README.md +29 -0
  58. package/docs/api/action/action.md +81 -0
  59. package/docs/api/action/goTo.md +66 -0
  60. package/docs/api/action/launch.md +58 -0
  61. package/docs/api/action/named.md +55 -0
  62. package/docs/api/action/uri.md +54 -0
  63. package/docs/api/annot/README.md +53 -0
  64. package/docs/api/annot/annot.md +114 -0
  65. package/docs/api/annot/fileAttach.md +53 -0
  66. package/docs/api/annot/freeText.md +68 -0
  67. package/docs/api/annot/ink.md +69 -0
  68. package/docs/api/annot/link.md +74 -0
  69. package/docs/api/annot/markup.md +83 -0
  70. package/docs/api/annot/popup.md +52 -0
  71. package/docs/api/annot/projection.md +56 -0
  72. package/docs/api/annot/redact.md +67 -0
  73. package/docs/api/annot/square.md +87 -0
  74. package/docs/api/annot/stamp.md +54 -0
  75. package/docs/api/annot/text.md +69 -0
  76. package/docs/api/annot/widget.md +69 -0
  77. package/docs/api/associatedFiles/README.md +9 -0
  78. package/docs/api/associatedFiles/associatedFiles.md +78 -0
  79. package/docs/api/bundles/README.md +68 -0
  80. package/docs/api/bundles/dist-matrix.md +165 -0
  81. package/docs/api/bundles/pdf-full.md +148 -0
  82. package/docs/api/bundles/pdf-large.md +144 -0
  83. package/docs/api/bundles/pdf-legacy.md +169 -0
  84. package/docs/api/content/README.md +29 -0
  85. package/docs/api/content/color.md +99 -0
  86. package/docs/api/content/graphics.md +114 -0
  87. package/docs/api/content/images.md +124 -0
  88. package/docs/api/content/ops.md +100 -0
  89. package/docs/api/content/stream.md +107 -0
  90. package/docs/api/content/text.md +98 -0
  91. package/docs/api/crypto/README.md +29 -0
  92. package/docs/api/crypto/aesGcm.md +72 -0
  93. package/docs/api/crypto/permissions.md +79 -0
  94. package/docs/api/crypto/security.md +98 -0
  95. package/docs/api/crypto/standardV4.md +104 -0
  96. package/docs/api/crypto/standardV5.md +84 -0
  97. package/docs/api/crypto/standardV6.md +93 -0
  98. package/docs/api/destination/README.md +9 -0
  99. package/docs/api/destination/destination.md +79 -0
  100. package/docs/api/document/README.md +29 -0
  101. package/docs/api/document/builder.md +281 -0
  102. package/docs/api/document/catalog.md +98 -0
  103. package/docs/api/document/document.md +187 -0
  104. package/docs/api/document/encryptedWriter.md +149 -0
  105. package/docs/api/document/incrementalWriter.md +148 -0
  106. package/docs/api/document/page.md +99 -0
  107. package/docs/api/document/pages.md +82 -0
  108. package/docs/api/document/resources.md +102 -0
  109. package/docs/api/document/writer.md +157 -0
  110. package/docs/api/document/xrefStreamWriter.md +122 -0
  111. package/docs/api/embedded/README.md +13 -0
  112. package/docs/api/embedded/collection.md +80 -0
  113. package/docs/api/embedded/embeddedFile.md +86 -0
  114. package/docs/api/embedded/fileSpec.md +87 -0
  115. package/docs/api/errors.md +110 -0
  116. package/docs/api/extra/3d-richmedia.md +76 -0
  117. package/docs/api/extra/README.md +99 -0
  118. package/docs/api/extra/annot-extended.md +71 -0
  119. package/docs/api/extra/associated-files.md +70 -0
  120. package/docs/api/extra/ccitt-fax-decoder.md +74 -0
  121. package/docs/api/extra/color-spaces-extended.md +72 -0
  122. package/docs/api/extra/content-ops-extended.md +82 -0
  123. package/docs/api/extra/document-parts.md +69 -0
  124. package/docs/api/extra/embedded-files-portfolio.md +87 -0
  125. package/docs/api/extra/font-cid-typed.md +77 -0
  126. package/docs/api/extra/font-color-tagging.md +76 -0
  127. package/docs/api/extra/form-actions-extended.md +75 -0
  128. package/docs/api/extra/info-dict-deprecated.md +72 -0
  129. package/docs/api/extra/jbig2-read.md +80 -0
  130. package/docs/api/extra/legacy-deprecated-annots.md +89 -0
  131. package/docs/api/extra/legacy-deprecated-filters.md +78 -0
  132. package/docs/api/extra/legacy-rc4-read.md +74 -0
  133. package/docs/api/extra/legacy-xfa-read.md +65 -0
  134. package/docs/api/extra/linearization-write.md +71 -0
  135. package/docs/api/extra/misc.md +93 -0
  136. package/docs/api/extra/optional-content-extended.md +83 -0
  137. package/docs/api/extra/pdf-a-output-intent.md +65 -0
  138. package/docs/api/extra/pdf-sandbox.md +76 -0
  139. package/docs/api/extra/pdf-ua-tagged.md +63 -0
  140. package/docs/api/extra/pdf-x-prepress.md +65 -0
  141. package/docs/api/extra/redaction-iso32005.md +65 -0
  142. package/docs/api/extra/shading-typed.md +73 -0
  143. package/docs/api/extra/sig-aes-gcm.md +69 -0
  144. package/docs/api/extra/sig-pades.md +103 -0
  145. package/docs/api/extra/tagged-pdf-typed.md +78 -0
  146. package/docs/api/extra/transparency-typed.md +74 -0
  147. package/docs/api/extra/well-tagged-pdf.md +61 -0
  148. package/docs/api/extra/xmp-extended.md +65 -0
  149. package/docs/api/font/README.md +25 -0
  150. package/docs/api/font/embed.md +157 -0
  151. package/docs/api/font/encoding.md +95 -0
  152. package/docs/api/font/font.md +97 -0
  153. package/docs/api/font/type3.md +89 -0
  154. package/docs/api/form/README.md +35 -0
  155. package/docs/api/form/acroform.md +88 -0
  156. package/docs/api/form/appearance.md +87 -0
  157. package/docs/api/form/button.md +97 -0
  158. package/docs/api/form/choice.md +96 -0
  159. package/docs/api/form/fieldTree.md +93 -0
  160. package/docs/api/form/signature.md +90 -0
  161. package/docs/api/form/text.md +88 -0
  162. package/docs/api/linearization/README.md +11 -0
  163. package/docs/api/linearization/linearization.md +81 -0
  164. package/docs/api/main.md +116 -0
  165. package/docs/api/metadata/README.md +10 -0
  166. package/docs/api/metadata/info.md +70 -0
  167. package/docs/api/metadata/xmp.md +62 -0
  168. package/docs/api/ocg/README.md +23 -0
  169. package/docs/api/ocg/config.md +95 -0
  170. package/docs/api/ocg/ocg.md +77 -0
  171. package/docs/api/outline/README.md +11 -0
  172. package/docs/api/outline/outline.md +107 -0
  173. package/docs/api/pdf.md +152 -0
  174. package/docs/api/prepress/README.md +10 -0
  175. package/docs/api/prepress/outputIntent.md +79 -0
  176. package/docs/api/prepress/pageBoundary.md +75 -0
  177. package/docs/api/sig/README.md +32 -0
  178. package/docs/api/sig/byteRange.md +120 -0
  179. package/docs/api/sig/certChain.md +84 -0
  180. package/docs/api/sig/dss.md +111 -0
  181. package/docs/api/sig/oids.md +76 -0
  182. package/docs/api/sig/sha1.md +72 -0
  183. package/docs/api/sig/sign.md +317 -0
  184. package/docs/api/sig/signature.md +178 -0
  185. package/docs/api/sig/timestamp.md +84 -0
  186. package/docs/api/syntax/README.md +29 -0
  187. package/docs/api/syntax/crossRefStream.md +115 -0
  188. package/docs/api/syntax/filters/README.md +50 -0
  189. package/docs/api/syntax/filters/ascii85.md +76 -0
  190. package/docs/api/syntax/filters/asciiHex.md +73 -0
  191. package/docs/api/syntax/filters/dispatch.md +125 -0
  192. package/docs/api/syntax/filters/flate.md +134 -0
  193. package/docs/api/syntax/filters/runLength.md +78 -0
  194. package/docs/api/syntax/objStream.md +88 -0
  195. package/docs/api/syntax/parser-obj.md +97 -0
  196. package/docs/api/syntax/parser.md +151 -0
  197. package/docs/api/syntax/serializer.md +109 -0
  198. package/docs/api/syntax/tokenizer.md +104 -0
  199. package/docs/api/syntax/trailer.md +85 -0
  200. package/docs/api/syntax/xref.md +139 -0
  201. package/docs/api/tagged/README.md +25 -0
  202. package/docs/api/tagged/classMap.md +67 -0
  203. package/docs/api/tagged/markedContent.md +62 -0
  204. package/docs/api/tagged/parentTree.md +67 -0
  205. package/docs/api/tagged/roleMap.md +67 -0
  206. package/docs/api/tagged/structElement.md +76 -0
  207. package/docs/api/tagged/structTree.md +75 -0
  208. package/docs/guide/coverage.md +113 -0
  209. package/docs/guide/crypto.md +121 -0
  210. package/docs/guide/extending.md +76 -0
  211. package/docs/guide/getting-started.md +75 -0
  212. package/docs/guide/legacy-1.7.md +42 -0
  213. package/docs/guide/pades-integration.md +579 -0
  214. package/docs/guide/read-pdf.md +89 -0
  215. package/package.json +97 -4
  216. package/src/_shared/index.js +179 -0
  217. package/src/action/action.js +119 -0
  218. package/src/action/goTo.js +89 -0
  219. package/src/action/launch.js +61 -0
  220. package/src/action/named.js +54 -0
  221. package/src/action/uri.js +51 -0
  222. package/src/annot/annot.js +212 -0
  223. package/src/annot/fileAttach.js +55 -0
  224. package/src/annot/freeText.js +82 -0
  225. package/src/annot/ink.js +77 -0
  226. package/src/annot/link.js +77 -0
  227. package/src/annot/markup.js +91 -0
  228. package/src/annot/popup.js +53 -0
  229. package/src/annot/projection.js +52 -0
  230. package/src/annot/redact.js +87 -0
  231. package/src/annot/square.js +132 -0
  232. package/src/annot/stamp.js +48 -0
  233. package/src/annot/text.js +54 -0
  234. package/src/annot/widget.js +61 -0
  235. package/src/associatedFiles/associatedFiles.js +86 -0
  236. package/src/bundles/pdf-full.js +91 -0
  237. package/src/bundles/pdf-large.js +81 -0
  238. package/src/bundles/pdf-legacy.js +107 -0
  239. package/src/content/color.js +114 -0
  240. package/src/content/graphics.js +192 -0
  241. package/src/content/images.js +160 -0
  242. package/src/content/ops.js +137 -0
  243. package/src/content/stream.js +154 -0
  244. package/src/content/text.js +125 -0
  245. package/src/crypto/aesGcm.js +123 -0
  246. package/src/crypto/permissions.js +112 -0
  247. package/src/crypto/security.js +327 -0
  248. package/src/crypto/standardV4.js +443 -0
  249. package/src/crypto/standardV5.js +306 -0
  250. package/src/crypto/standardV6.js +334 -0
  251. package/src/destination/destination.js +183 -0
  252. package/src/document/builder.js +618 -0
  253. package/src/document/catalog.js +100 -0
  254. package/src/document/document.js +472 -0
  255. package/src/document/encryptedWriter.js +554 -0
  256. package/src/document/incrementalWriter.js +514 -0
  257. package/src/document/page.js +131 -0
  258. package/src/document/pages.js +103 -0
  259. package/src/document/resources.js +146 -0
  260. package/src/document/writer.js +211 -0
  261. package/src/document/xrefStreamWriter.js +353 -0
  262. package/src/embedded/collection.js +102 -0
  263. package/src/embedded/embeddedFile.js +99 -0
  264. package/src/embedded/fileSpec.js +137 -0
  265. package/src/errors.js +78 -0
  266. package/src/extra/3d-richmedia.js +171 -0
  267. package/src/extra/annot-extended.js +200 -0
  268. package/src/extra/associated-files.js +131 -0
  269. package/src/extra/ccitt-fax-decoder.js +776 -0
  270. package/src/extra/color-spaces-extended.js +196 -0
  271. package/src/extra/content-ops-extended.js +153 -0
  272. package/src/extra/document-parts.js +149 -0
  273. package/src/extra/embedded-files-portfolio.js +234 -0
  274. package/src/extra/font-cid-typed.js +185 -0
  275. package/src/extra/font-color-tagging.js +144 -0
  276. package/src/extra/form-actions-extended.js +196 -0
  277. package/src/extra/info-dict-deprecated.js +137 -0
  278. package/src/extra/jbig2-read.js +169 -0
  279. package/src/extra/legacy-deprecated-annots.js +198 -0
  280. package/src/extra/legacy-deprecated-filters.js +167 -0
  281. package/src/extra/legacy-rc4-read.js +235 -0
  282. package/src/extra/legacy-xfa-read.js +104 -0
  283. package/src/extra/linearization-write.js +97 -0
  284. package/src/extra/misc.js +217 -0
  285. package/src/extra/optional-content-extended.js +142 -0
  286. package/src/extra/pdf-a-output-intent.js +112 -0
  287. package/src/extra/pdf-sandbox.js +88 -0
  288. package/src/extra/pdf-ua-tagged.js +116 -0
  289. package/src/extra/pdf-x-prepress.js +114 -0
  290. package/src/extra/redaction-iso32005.js +136 -0
  291. package/src/extra/shading-typed.js +222 -0
  292. package/src/extra/sig-aes-gcm.js +135 -0
  293. package/src/extra/sig-pades.js +242 -0
  294. package/src/extra/tagged-pdf-typed.js +203 -0
  295. package/src/extra/transparency-typed.js +135 -0
  296. package/src/extra/well-tagged-pdf.js +138 -0
  297. package/src/extra/xmp-extended.js +190 -0
  298. package/src/font/embed.js +480 -0
  299. package/src/font/encoding.js +92 -0
  300. package/src/font/font.js +101 -0
  301. package/src/font/type3.js +75 -0
  302. package/src/form/acroform.js +94 -0
  303. package/src/form/appearance.js +90 -0
  304. package/src/form/button.js +105 -0
  305. package/src/form/choice.js +152 -0
  306. package/src/form/fieldTree.js +120 -0
  307. package/src/form/signature.js +100 -0
  308. package/src/form/text.js +101 -0
  309. package/src/linearization/linearization.js +107 -0
  310. package/src/main.js +411 -0
  311. package/src/metadata/info.js +87 -0
  312. package/src/metadata/xmp.js +62 -0
  313. package/src/ocg/config.js +156 -0
  314. package/src/ocg/ocg.js +124 -0
  315. package/src/outline/outline.js +157 -0
  316. package/src/pdf.js +133 -0
  317. package/src/prepress/outputIntent.js +118 -0
  318. package/src/prepress/pageBoundary.js +108 -0
  319. package/src/sig/byteRange.js +306 -0
  320. package/src/sig/certChain.js +247 -0
  321. package/src/sig/dss.js +317 -0
  322. package/src/sig/oids.js +157 -0
  323. package/src/sig/sha1.js +142 -0
  324. package/src/sig/sign.js +1899 -0
  325. package/src/sig/signature.js +1441 -0
  326. package/src/sig/timestamp.js +236 -0
  327. package/src/syntax/crossRefStream.js +133 -0
  328. package/src/syntax/filters/ascii85.js +122 -0
  329. package/src/syntax/filters/asciiHex.js +83 -0
  330. package/src/syntax/filters/dispatch.js +176 -0
  331. package/src/syntax/filters/flate.js +316 -0
  332. package/src/syntax/filters/runLength.js +96 -0
  333. package/src/syntax/objStream.js +99 -0
  334. package/src/syntax/parser-obj.js +52 -0
  335. package/src/syntax/parser.js +321 -0
  336. package/src/syntax/serializer.js +221 -0
  337. package/src/syntax/tokenizer.js +290 -0
  338. package/src/syntax/trailer.js +76 -0
  339. package/src/syntax/xref.js +341 -0
  340. package/src/tagged/classMap.js +81 -0
  341. package/src/tagged/markedContent.js +123 -0
  342. package/src/tagged/parentTree.js +126 -0
  343. package/src/tagged/roleMap.js +107 -0
  344. package/src/tagged/structElement.js +138 -0
  345. package/src/tagged/structTree.js +94 -0
@@ -0,0 +1,2684 @@
1
+ /*!
2
+ * Copyright (c) 2026 AwaCloud SAS
3
+ * Author: Matthieu Bouilloux
4
+ * SPDX-License-Identifier: AGPL-3.0-only
5
+ * Dual-licensed; see the NOTICE file for licensing and any additional terms.
6
+ */
7
+ /* GENERATED — do not edit. Source: packages/front/office/pdf/tools/generate-bundles.mjs */
8
+
9
+ /**
10
+ * @fileoverview `@awacloud/pdf/bundles/prebuilt/pdf-package` — pre-built single-factory bundle.
11
+ *
12
+ * Variant **package** : declares the 26 fw modules as dependencies and inlines every
13
+ * pdf-local factory transitively reachable from `pdf` .
14
+ *
15
+ * @module pdf/bundles/prebuilt/pdf-package
16
+ */
17
+
18
+ export const pdfPackage = {
19
+ name: "pdfPackage",
20
+ dependencies: ["bitstream","huffman","lz77","deflate","adler32","b64","hex","zlib","lzw","utf8","aes","cbc","gcm","sha256","sha384","sha512","bitArray","asn1","asn1Oid","pem","random","bn","hmac","rsa","ecc","ed25519"],
21
+ factory(bitstream, huffman, lz77, deflate, adler32, b64, hex, zlib, lzw, utf8, aes, cbc, gcm, sha256, sha384, sha512, bitArray, asn1, asn1Oid, pem, random, bn, hmac, rsa, ecc, ed25519) {
22
+ const __reg = Object.create(null);
23
+ const __cache = Object.create(null);
24
+ function __register(m) { __reg[m.name] = m; }
25
+ function __resolve(name) {
26
+ if (name in __cache) return __cache[name];
27
+ const def = __reg[name];
28
+ if (!def) throw new Error('prebuilt: unknown module ' + name);
29
+ const args = def.dependencies.map(__resolve);
30
+ return (__cache[name] = def.factory.apply({}, args));
31
+ }
32
+
33
+ // fw modules — injected by DI.
34
+ __cache["bitstream"] = bitstream;
35
+ __cache["huffman"] = huffman;
36
+ __cache["lz77"] = lz77;
37
+ __cache["deflate"] = deflate;
38
+ __cache["adler32"] = adler32;
39
+ __cache["b64"] = b64;
40
+ __cache["hex"] = hex;
41
+ __cache["zlib"] = zlib;
42
+ __cache["lzw"] = lzw;
43
+ __cache["utf8"] = utf8;
44
+ __cache["aes"] = aes;
45
+ __cache["cbc"] = cbc;
46
+ __cache["gcm"] = gcm;
47
+ __cache["sha256"] = sha256;
48
+ __cache["sha384"] = sha384;
49
+ __cache["sha512"] = sha512;
50
+ __cache["bitArray"] = bitArray;
51
+ __cache["asn1"] = asn1;
52
+ __cache["asn1Oid"] = asn1Oid;
53
+ __cache["pem"] = pem;
54
+ __cache["random"] = random;
55
+ __cache["bn"] = bn;
56
+ __cache["hmac"] = hmac;
57
+ __cache["rsa"] = rsa;
58
+ __cache["ecc"] = ecc;
59
+ __cache["ed25519"] = ed25519;
60
+
61
+ // pdf-local factories — inlined and topo-ordered.
62
+ __register({ name: "pdfErrors", dependencies: [], factory: function() {
63
+ class PdfError extends Error {
64
+ constructor(code, message, opts) {
65
+ super(message);
66
+ this.name = new.target.name;
67
+ this.code = code;
68
+ if (opts && opts.context)
69
+ this.context = opts.context;
70
+ if (opts && opts.cause)
71
+ this.cause = opts.cause;
72
+ }
73
+ }
74
+
75
+ class ParseError extends PdfError {
76
+ }
77
+
78
+ class RenderError extends PdfError {
79
+ }
80
+
81
+ class ContractError extends PdfError {
82
+ }
83
+
84
+ class EncryptionError extends PdfError {
85
+ }
86
+ function isPdfError(e) {
87
+ return e instanceof PdfError;
88
+ }
89
+ return {
90
+ PdfError,
91
+ ParseError,
92
+ RenderError,
93
+ ContractError,
94
+ EncryptionError,
95
+ isPdfError
96
+ };
97
+ } });
98
+ __register({ name: "pdfShared", dependencies: [], factory: function() {
99
+ const HEADER_PREFIX = new Uint8Array([37, 80, 68, 70, 45]), EOF_MARKER = new Uint8Array([37, 37, 69, 79, 70]), BINARY_MARKER = new Uint8Array([37, 226, 227, 207, 211, 10]), ASCII = Object.freeze({
100
+ NUL: 0,
101
+ HT: 9,
102
+ LF: 10,
103
+ FF: 12,
104
+ CR: 13,
105
+ SP: 32,
106
+ HASH: 35,
107
+ PERCENT: 37,
108
+ LPAREN: 40,
109
+ RPAREN: 41,
110
+ PLUS: 43,
111
+ MINUS: 45,
112
+ DOT: 46,
113
+ SLASH: 47,
114
+ ZERO: 48,
115
+ NINE: 57,
116
+ LANGLE: 60,
117
+ RANGLE: 62,
118
+ A_UP: 65,
119
+ F_UP: 70,
120
+ Z_UP: 90,
121
+ LBRACK: 91,
122
+ BACKSLASH: 92,
123
+ RBRACK: 93,
124
+ A_LO: 97,
125
+ F_LO: 102,
126
+ Z_LO: 122,
127
+ LBRACE: 123,
128
+ RBRACE: 125
129
+ });
130
+ function isWs(b) {
131
+ return b === 32 || b === 9 || b === 10 || b === 13 || b === 12 || b === 0;
132
+ }
133
+ function isEol(b) {
134
+ return b === 10 || b === 13;
135
+ }
136
+ function isDigit(b) {
137
+ return b >= 48 && b <= 57;
138
+ }
139
+ function isHex(b) {
140
+ return b >= 48 && b <= 57 || b >= 65 && b <= 70 || b >= 97 && b <= 102;
141
+ }
142
+ function isDelim(b) {
143
+ return b === 40 || b === 41 || b === 60 || b === 62 || b === 91 || b === 93 || b === 47 || b === 37 || b === 123 || b === 125;
144
+ }
145
+ function isRegular(b) {
146
+ return !isWs(b) && !isDelim(b);
147
+ }
148
+ function hexNibble(b) {
149
+ if (b >= 48 && b <= 57)
150
+ return b - 48;
151
+ if (b >= 65 && b <= 70)
152
+ return b - 65 + 10;
153
+ if (b >= 97 && b <= 102)
154
+ return b - 97 + 10;
155
+ return -1;
156
+ }
157
+ const HEX_LO = function buildHexLo() {
158
+ const t = new Int8Array(128);
159
+ t.fill(-1);
160
+ for (let c = 48;c <= 57; c++)
161
+ t[c] = c - 48;
162
+ for (let c = 65;c <= 70; c++)
163
+ t[c] = c - 65 + 10;
164
+ for (let c = 97;c <= 102; c++)
165
+ t[c] = c - 97 + 10;
166
+ return t;
167
+ }(), te = new TextEncoder, tdUtf8 = new TextDecoder("utf-8"), tdUtf8Lenient = new TextDecoder("utf-8", { fatal: !1 }), tdLatin1 = new TextDecoder("latin1");
168
+ function encodeAscii(s) {
169
+ return te.encode(s);
170
+ }
171
+ function decodeUtf8(bytes) {
172
+ return tdUtf8.decode(bytes);
173
+ }
174
+ function decodeUtf8Lenient(b) {
175
+ return tdUtf8Lenient.decode(b);
176
+ }
177
+ function decodeLatin1(bytes) {
178
+ return tdLatin1.decode(bytes);
179
+ }
180
+ function pad10(n) {
181
+ return String(n).padStart(10, "0");
182
+ }
183
+ function hexLit(bytes) {
184
+ let s = "<";
185
+ for (let i = 0;i < bytes.length; i++)
186
+ s += "0123456789ABCDEF"[bytes[i] >> 4] + "0123456789ABCDEF"[bytes[i] & 15];
187
+ return s + ">";
188
+ }
189
+ function bytesEqual(a, b, n) {
190
+ if (!a || !b)
191
+ return !1;
192
+ if (n == null) {
193
+ if (a.length !== b.length)
194
+ return !1;
195
+ n = a.length;
196
+ } else if (a.length < n || b.length < n)
197
+ return !1;
198
+ let diff = 0;
199
+ for (let i = 0;i < n; i++)
200
+ diff |= a[i] ^ b[i];
201
+ return diff === 0;
202
+ }
203
+ function concatBytes(arrays) {
204
+ let total = 0;
205
+ for (const a of arrays)
206
+ total += a.length;
207
+ const out = new Uint8Array(total);
208
+ let o = 0;
209
+ for (const a of arrays) {
210
+ out.set(a, o);
211
+ o += a.length;
212
+ }
213
+ return out;
214
+ }
215
+ return {
216
+ HEADER_PREFIX,
217
+ EOF_MARKER,
218
+ BINARY_MARKER,
219
+ ASCII,
220
+ isWs,
221
+ isEol,
222
+ isDigit,
223
+ isHex,
224
+ isDelim,
225
+ isRegular,
226
+ hexNibble,
227
+ HEX_LO,
228
+ te,
229
+ tdUtf8,
230
+ tdUtf8Lenient,
231
+ tdLatin1,
232
+ encodeAscii,
233
+ decodeUtf8,
234
+ decodeUtf8Lenient,
235
+ decodeLatin1,
236
+ pad10,
237
+ hexLit,
238
+ bytesEqual,
239
+ concatBytes
240
+ };
241
+ } });
242
+ __register({ name: "pdfTokenizer", dependencies: ["pdfErrors","pdfShared"], factory: function(errors, shared) {
243
+ const { ParseError } = errors, { ASCII, isWs, isEol, isDigit, isRegular, hexNibble } = shared, {
244
+ HT,
245
+ LF,
246
+ CR,
247
+ FF,
248
+ LPAREN,
249
+ RPAREN,
250
+ LANGLE,
251
+ RANGLE,
252
+ LBRACK,
253
+ RBRACK,
254
+ SLASH,
255
+ PERCENT,
256
+ BACKSLASH,
257
+ PLUS,
258
+ MINUS,
259
+ DOT,
260
+ ZERO,
261
+ HASH
262
+ } = ASCII;
263
+ function tokenize(bytes, opts) {
264
+ if (!(bytes instanceof Uint8Array))
265
+ throw new ParseError("pdf/tokenizer/bad-input", "tokenize() expects a Uint8Array", { context: { typeof: typeof bytes } });
266
+ const keepWs = !!(opts && opts.keepWhitespace);
267
+ let i = opts && opts.start | 0 || 0;
268
+ const N = opts && Number.isFinite(opts.end) ? Math.min(opts.end | 0, bytes.length) : bytes.length;
269
+ let lookahead = null;
270
+ function pos() {
271
+ return i;
272
+ }
273
+ function seek(n) {
274
+ if (n < 0 || n > bytes.length)
275
+ throw new ParseError("pdf/tokenizer/bad-seek", "seek out of range", { context: { offset: n, total: bytes.length } });
276
+ i = n;
277
+ lookahead = null;
278
+ }
279
+ function readName() {
280
+ const start = i;
281
+ i++;
282
+ const out = [];
283
+ while (i < N) {
284
+ const b = bytes[i];
285
+ if (!isRegular(b))
286
+ break;
287
+ if (b === HASH) {
288
+ if (i + 2 >= N)
289
+ throw new ParseError("pdf/tokenizer/bad-name-escape", "truncated #xx escape in name", { context: { offset: i } });
290
+ const hi = hexNibble(bytes[i + 1]), lo = hexNibble(bytes[i + 2]);
291
+ if (hi < 0 || lo < 0)
292
+ throw new ParseError("pdf/tokenizer/bad-name-escape", "invalid hex digits in name escape", { context: { offset: i } });
293
+ out.push(hi << 4 | lo);
294
+ i += 3;
295
+ } else {
296
+ out.push(b);
297
+ i++;
298
+ }
299
+ }
300
+ return { kind: "name", value: new TextDecoder("utf-8", { fatal: !1 }).decode(Uint8Array.from(out)), offset: start, end: i };
301
+ }
302
+ function readNumber() {
303
+ const start = i;
304
+ let isReal = !1;
305
+ if (bytes[i] === PLUS || bytes[i] === MINUS)
306
+ i++;
307
+ while (i < N) {
308
+ const b = bytes[i];
309
+ if (isDigit(b)) {
310
+ i++;
311
+ continue;
312
+ }
313
+ if (b === DOT && !isReal) {
314
+ isReal = !0;
315
+ i++;
316
+ continue;
317
+ }
318
+ break;
319
+ }
320
+ const raw = new TextDecoder("latin1").decode(bytes.subarray(start, i));
321
+ if (raw === "" || raw === "+" || raw === "-" || raw === ".")
322
+ throw new ParseError("pdf/tokenizer/bad-number", "empty number token", { context: { offset: start } });
323
+ const n = Number(raw);
324
+ if (!Number.isFinite(n))
325
+ throw new ParseError("pdf/tokenizer/bad-number", "cannot parse number", { context: { raw, offset: start } });
326
+ return { kind: isReal ? "real" : "int", value: n, offset: start, end: i, raw };
327
+ }
328
+ function readLiteralString() {
329
+ const start = i;
330
+ i++;
331
+ const out = [];
332
+ let depth = 1;
333
+ while (i < N && depth > 0) {
334
+ const b = bytes[i];
335
+ if (b === LPAREN) {
336
+ depth++;
337
+ out.push(b);
338
+ i++;
339
+ continue;
340
+ }
341
+ if (b === RPAREN) {
342
+ depth--;
343
+ if (depth === 0) {
344
+ i++;
345
+ break;
346
+ }
347
+ out.push(b);
348
+ i++;
349
+ continue;
350
+ }
351
+ if (b === BACKSLASH) {
352
+ if (i + 1 >= N)
353
+ throw new ParseError("pdf/tokenizer/bad-string", "trailing backslash in literal string", { context: { offset: i } });
354
+ const nxt = bytes[i + 1];
355
+ if (nxt === LF) {
356
+ i += 2;
357
+ continue;
358
+ }
359
+ if (nxt === CR) {
360
+ i += 2;
361
+ if (i < N && bytes[i] === LF)
362
+ i++;
363
+ continue;
364
+ }
365
+ if (nxt === 110) {
366
+ out.push(LF);
367
+ i += 2;
368
+ continue;
369
+ }
370
+ if (nxt === 114) {
371
+ out.push(CR);
372
+ i += 2;
373
+ continue;
374
+ }
375
+ if (nxt === 116) {
376
+ out.push(HT);
377
+ i += 2;
378
+ continue;
379
+ }
380
+ if (nxt === 98) {
381
+ out.push(8);
382
+ i += 2;
383
+ continue;
384
+ }
385
+ if (nxt === 102) {
386
+ out.push(FF);
387
+ i += 2;
388
+ continue;
389
+ }
390
+ if (nxt === LPAREN || nxt === RPAREN || nxt === BACKSLASH) {
391
+ out.push(nxt);
392
+ i += 2;
393
+ continue;
394
+ }
395
+ if (nxt >= ZERO && nxt <= ZERO + 7) {
396
+ let v = 0, k = 0;
397
+ i++;
398
+ while (k < 3 && i < N && bytes[i] >= ZERO && bytes[i] <= ZERO + 7) {
399
+ v = v << 3 | bytes[i] - ZERO;
400
+ i++;
401
+ k++;
402
+ }
403
+ out.push(v & 255);
404
+ continue;
405
+ }
406
+ i++;
407
+ continue;
408
+ }
409
+ if (b === CR) {
410
+ out.push(LF);
411
+ i++;
412
+ if (i < N && bytes[i] === LF)
413
+ i++;
414
+ continue;
415
+ }
416
+ out.push(b);
417
+ i++;
418
+ }
419
+ if (depth !== 0)
420
+ throw new ParseError("pdf/tokenizer/unterminated-string", "literal string was not closed", { context: { offset: start } });
421
+ return { kind: "string", value: Uint8Array.from(out), offset: start, end: i };
422
+ }
423
+ function readHexString() {
424
+ const start = i;
425
+ i++;
426
+ const nibbles = [];
427
+ while (i < N) {
428
+ const b = bytes[i];
429
+ if (b === RANGLE) {
430
+ i++;
431
+ break;
432
+ }
433
+ if (isWs(b)) {
434
+ i++;
435
+ continue;
436
+ }
437
+ const v = hexNibble(b);
438
+ if (v < 0)
439
+ throw new ParseError("pdf/tokenizer/bad-hex", "non-hex byte in hex string", { context: { offset: i, byte: b } });
440
+ nibbles.push(v);
441
+ i++;
442
+ }
443
+ if (nibbles.length % 2 === 1)
444
+ nibbles.push(0);
445
+ const out = new Uint8Array(nibbles.length / 2);
446
+ for (let k = 0;k < out.length; k++)
447
+ out[k] = nibbles[2 * k] << 4 | nibbles[2 * k + 1];
448
+ return { kind: "hex", value: out, offset: start, end: i };
449
+ }
450
+ function readKeyword() {
451
+ const start = i;
452
+ while (i < N && isRegular(bytes[i]))
453
+ i++;
454
+ const raw = new TextDecoder("latin1").decode(bytes.subarray(start, i));
455
+ if (raw === "")
456
+ throw new ParseError("pdf/tokenizer/empty-keyword", "empty keyword", { context: { offset: start } });
457
+ return { kind: "kw", value: raw, offset: start, end: i };
458
+ }
459
+ function next() {
460
+ if (lookahead) {
461
+ const t = lookahead;
462
+ lookahead = null;
463
+ return t;
464
+ }
465
+ while (i < N) {
466
+ const b = bytes[i];
467
+ if (isWs(b)) {
468
+ if (keepWs) {
469
+ const start = i;
470
+ while (i < N && isWs(bytes[i]))
471
+ i++;
472
+ return { kind: "ws", offset: start, end: i };
473
+ }
474
+ i++;
475
+ continue;
476
+ }
477
+ if (b === PERCENT) {
478
+ if (i + 4 < N && bytes[i + 1] === PERCENT && bytes[i + 2] === 69 && bytes[i + 3] === 79 && bytes[i + 4] === 70) {
479
+ const start = i;
480
+ i += 5;
481
+ return { kind: "eof_marker", offset: start, end: i };
482
+ }
483
+ while (i < N && !isEol(bytes[i]))
484
+ i++;
485
+ if (i < N && bytes[i] === CR)
486
+ i++;
487
+ if (i < N && bytes[i] === LF)
488
+ i++;
489
+ continue;
490
+ }
491
+ break;
492
+ }
493
+ if (i >= N)
494
+ return null;
495
+ const b = bytes[i];
496
+ if (b === SLASH)
497
+ return readName();
498
+ if (b === LBRACK)
499
+ return { kind: "open_arr", offset: i++, end: i };
500
+ if (b === RBRACK)
501
+ return { kind: "close_arr", offset: i++, end: i };
502
+ if (b === LANGLE) {
503
+ if (i + 1 < N && bytes[i + 1] === LANGLE) {
504
+ const off = i;
505
+ i += 2;
506
+ return { kind: "open_dict", offset: off, end: i };
507
+ }
508
+ return readHexString();
509
+ }
510
+ if (b === RANGLE) {
511
+ if (i + 1 < N && bytes[i + 1] === RANGLE) {
512
+ const off = i;
513
+ i += 2;
514
+ return { kind: "close_dict", offset: off, end: i };
515
+ }
516
+ throw new ParseError("pdf/tokenizer/unexpected-rangle", "lone > outside hex string", { context: { offset: i } });
517
+ }
518
+ if (b === LPAREN)
519
+ return readLiteralString();
520
+ if (b === PLUS || b === MINUS || b === DOT || isDigit(b))
521
+ return readNumber();
522
+ return readKeyword();
523
+ }
524
+ function peek() {
525
+ if (!lookahead)
526
+ lookahead = next();
527
+ return lookahead;
528
+ }
529
+ return { next, peek, pos, seek, bytes };
530
+ }
531
+ function lastIndexOfBytes(bytes, needle, from) {
532
+ const N = bytes.length, M = needle.length;
533
+ if (M === 0 || M > N)
534
+ return -1;
535
+ let start = Number.isFinite(from) ? Math.min(from | 0, N - M) : N - M;
536
+ outer:
537
+ for (let i = start;i >= 0; i--) {
538
+ for (let k = 0;k < M; k++)
539
+ if (bytes[i + k] !== needle[k])
540
+ continue outer;
541
+ return i;
542
+ }
543
+ return -1;
544
+ }
545
+ return { tokenize, lastIndexOfBytes };
546
+ } });
547
+ __register({ name: "pdfParserObj", dependencies: [], factory: function() {
548
+ const obj = {
549
+ nul: () => ({ type: "null" }),
550
+ bool: (v) => ({ type: "bool", value: !!v }),
551
+ int: (v) => ({ type: "int", value: v | 0 }),
552
+ real: (v) => ({ type: "real", value: +v }),
553
+ name: (s) => ({ type: "name", value: String(s) }),
554
+ string: (bytes, syntax) => ({
555
+ type: "string",
556
+ value: bytes,
557
+ syntax: syntax === "hex" ? "hex" : "lit"
558
+ }),
559
+ array: (items) => ({ type: "array", items: items || [] }),
560
+ dict: (entries) => ({ type: "dict", entries: entries || {} }),
561
+ ref: (num, gen) => ({ type: "ref", num: num | 0, gen: gen | 0 || 0 }),
562
+ stream: (dict, raw) => ({ type: "stream", dict, raw })
563
+ };
564
+ function getEntry(dict, key) {
565
+ if (!dict || dict.type !== "dict")
566
+ return;
567
+ return dict.entries[key];
568
+ }
569
+ function isType(v, kind) {
570
+ return !!(v && v.type === kind);
571
+ }
572
+ return { obj, getEntry, isType };
573
+ } });
574
+ __register({ name: "pdfParser", dependencies: ["pdfErrors","pdfParserObj","pdfTokenizer"], factory: function(errors, parserObj, tokenizerMod) {
575
+ const { ParseError } = errors, { obj, getEntry, isType } = parserObj, tokenize = tokenizerMod.tokenize;
576
+ function resolveStreamLength(streamDict, resolveRef) {
577
+ const e = streamDict.entries && streamDict.entries.Length;
578
+ if (!e)
579
+ return -1;
580
+ if (e.type === "int")
581
+ return e.value;
582
+ if (e.type === "ref" && typeof resolveRef === "function") {
583
+ const r = resolveRef(e);
584
+ if (r && r.type === "int")
585
+ return r.value;
586
+ }
587
+ return -1;
588
+ }
589
+ function findEndstream(bytes, from, quota) {
590
+ const needle = [101, 110, 100, 115, 116, 114, 101, 97, 109], lim = Math.min(bytes.length, from + (quota | 0));
591
+ outer:
592
+ for (let i = from;i + needle.length <= lim; i++) {
593
+ for (let k = 0;k < needle.length; k++)
594
+ if (bytes[i + k] !== needle[k])
595
+ continue outer;
596
+ let end = i;
597
+ if (end > from && bytes[end - 1] === 10)
598
+ end--;
599
+ if (end > from && bytes[end - 1] === 13)
600
+ end--;
601
+ return end;
602
+ }
603
+ return -1;
604
+ }
605
+ function skipEolWs(tok) {
606
+ const b = tok.bytes;
607
+ let p = tok.pos();
608
+ while (p < b.length) {
609
+ const c = b[p];
610
+ if (c === 32 || c === 9 || c === 10 || c === 13)
611
+ p++;
612
+ else
613
+ break;
614
+ }
615
+ tok.seek(p);
616
+ }
617
+ const parserLimits = {
618
+ maxDepth: 200,
619
+ maxArrayLen: 1e6,
620
+ maxStreamBytes: 268435456
621
+ };
622
+ function setParserLimits(partial) {
623
+ if (partial && typeof partial === "object") {
624
+ if (Number.isInteger(partial.maxDepth) && partial.maxDepth > 0)
625
+ parserLimits.maxDepth = partial.maxDepth;
626
+ if (Number.isInteger(partial.maxArrayLen) && partial.maxArrayLen > 0)
627
+ parserLimits.maxArrayLen = partial.maxArrayLen;
628
+ if (Number.isInteger(partial.maxStreamBytes) && partial.maxStreamBytes > 0)
629
+ parserLimits.maxStreamBytes = partial.maxStreamBytes;
630
+ }
631
+ return parserLimits;
632
+ }
633
+ function parseObject(tok) {
634
+ const t = tok.next();
635
+ if (!t)
636
+ throw new ParseError("pdf/parser/eof", "unexpected end of input");
637
+ return continueParse(tok, t, 0);
638
+ }
639
+ function continueParse(tok, t, depth) {
640
+ if (depth > parserLimits.maxDepth)
641
+ throw new ParseError("pdf/parser/depth-exceeded", "parser depth limit exceeded", { context: {
642
+ depth,
643
+ limit: parserLimits.maxDepth,
644
+ offset: t && t.offset
645
+ } });
646
+ switch (t.kind) {
647
+ case "kw":
648
+ if (t.value === "null")
649
+ return { type: "null" };
650
+ if (t.value === "true")
651
+ return { type: "bool", value: !0 };
652
+ if (t.value === "false")
653
+ return { type: "bool", value: !1 };
654
+ throw new ParseError("pdf/parser/unexpected-keyword", `unexpected keyword "${t.value}"`, { context: { offset: t.offset, keyword: t.value } });
655
+ case "name":
656
+ return { type: "name", value: t.value };
657
+ case "string":
658
+ return { type: "string", value: t.value, syntax: "lit" };
659
+ case "hex":
660
+ return { type: "string", value: t.value, syntax: "hex" };
661
+ case "int":
662
+ return tryReadRef(tok, t);
663
+ case "real":
664
+ return { type: "real", value: t.value };
665
+ case "open_arr":
666
+ return readArray(tok, t.offset, depth);
667
+ case "open_dict":
668
+ return readDict(tok, t.offset, depth);
669
+ case "close_arr":
670
+ case "close_dict":
671
+ throw new ParseError("pdf/parser/unbalanced", `unexpected ${t.kind}`, { context: { offset: t.offset } });
672
+ default:
673
+ throw new ParseError("pdf/parser/unexpected-token", `unexpected token of kind "${t.kind}"`, { context: { offset: t.offset, kind: t.kind } });
674
+ }
675
+ }
676
+ function tryReadRef(tok, intTok) {
677
+ const at = tok.pos(), p1 = tok.peek();
678
+ if (!p1 || p1.kind !== "int")
679
+ return { type: "int", value: intTok.value };
680
+ tok.next();
681
+ const p2 = tok.peek();
682
+ if (p2 && p2.kind === "kw" && p2.value === "R") {
683
+ tok.next();
684
+ return { type: "ref", num: intTok.value | 0, gen: p1.value | 0 };
685
+ }
686
+ tok.seek(at);
687
+ return { type: "int", value: intTok.value };
688
+ }
689
+ function readArray(tok, startOff, depth) {
690
+ const items = [];
691
+ for (;; ) {
692
+ const p = tok.peek();
693
+ if (!p)
694
+ throw new ParseError("pdf/parser/unterminated-array", "array not closed", { context: { offset: startOff } });
695
+ if (p.kind === "close_arr") {
696
+ tok.next();
697
+ return { type: "array", items };
698
+ }
699
+ if (items.length >= parserLimits.maxArrayLen)
700
+ throw new ParseError("pdf/parser/array-too-long", "array exceeds parserLimits.maxArrayLen", { context: {
701
+ length: items.length,
702
+ limit: parserLimits.maxArrayLen,
703
+ offset: startOff
704
+ } });
705
+ const sub = tok.next();
706
+ items.push(continueParse(tok, sub, (depth | 0) + 1));
707
+ }
708
+ }
709
+ function readDict(tok, startOff, depth) {
710
+ const entries = {};
711
+ for (;; ) {
712
+ const p = tok.peek();
713
+ if (!p)
714
+ throw new ParseError("pdf/parser/unterminated-dict", "dict not closed", { context: { offset: startOff } });
715
+ if (p.kind === "close_dict") {
716
+ tok.next();
717
+ return { type: "dict", entries };
718
+ }
719
+ if (p.kind !== "name")
720
+ throw new ParseError("pdf/parser/dict-key-not-name", "expected /Name as dict key", { context: { offset: p.offset, kind: p.kind } });
721
+ const keyTok = tok.next(), sub = tok.next();
722
+ if (!sub)
723
+ throw new ParseError("pdf/parser/eof", "unexpected end of input");
724
+ const value = continueParse(tok, sub, (depth | 0) + 1);
725
+ entries[keyTok.value] = value;
726
+ }
727
+ }
728
+ function parseIndirect(tok, resolveRef) {
729
+ const t1 = tok.next();
730
+ if (!t1 || t1.kind !== "int")
731
+ throw new ParseError("pdf/parser/indirect-bad-num", "expected object number", { context: { offset: t1 ? t1.offset : tok.pos() } });
732
+ const t2 = tok.next();
733
+ if (!t2 || t2.kind !== "int")
734
+ throw new ParseError("pdf/parser/indirect-bad-gen", "expected generation number", { context: { offset: t2 ? t2.offset : tok.pos() } });
735
+ const t3 = tok.next();
736
+ if (!t3 || t3.kind !== "kw" || t3.value !== "obj")
737
+ throw new ParseError("pdf/parser/indirect-missing-obj", "expected obj keyword", { context: { offset: t3 ? t3.offset : tok.pos() } });
738
+ const value = parseObject(tok);
739
+ let body = value;
740
+ const after = tok.peek();
741
+ if (value.type === "dict" && after && after.kind === "kw" && after.value === "stream") {
742
+ tok.next();
743
+ const bytes = tok.bytes;
744
+ let p = tok.pos();
745
+ if (p < bytes.length && bytes[p] === 13)
746
+ p++;
747
+ if (p < bytes.length && bytes[p] === 10)
748
+ p++;
749
+ tok.seek(p);
750
+ const dataStart = tok.pos(), length = resolveStreamLength(value, resolveRef);
751
+ let dataEnd;
752
+ if (Number.isFinite(length) && length >= 0 && dataStart + length <= bytes.length)
753
+ dataEnd = dataStart + length;
754
+ else {
755
+ dataEnd = findEndstream(bytes, dataStart, parserLimits.maxStreamBytes);
756
+ if (dataEnd < 0)
757
+ throw new ParseError("pdf/parser/stream/no-endstream", "cannot locate endstream within quota", { context: {
758
+ offset: dataStart,
759
+ num: t1.value,
760
+ gen: t2.value,
761
+ quota: parserLimits.maxStreamBytes
762
+ } });
763
+ }
764
+ const raw = bytes.subarray(dataStart, dataEnd);
765
+ tok.seek(dataEnd);
766
+ skipEolWs(tok);
767
+ const endTok = tok.next();
768
+ if (!endTok || endTok.kind !== "kw" || endTok.value !== "endstream")
769
+ throw new ParseError("pdf/parser/stream/expected-endstream", "expected endstream", { context: { offset: endTok ? endTok.offset : tok.pos() } });
770
+ body = { type: "stream", dict: value, raw };
771
+ }
772
+ const endObj = tok.next();
773
+ if (!endObj || endObj.kind !== "kw" || endObj.value !== "endobj")
774
+ throw new ParseError("pdf/parser/indirect-missing-endobj", "expected endobj", { context: {
775
+ offset: endObj ? endObj.offset : tok.pos(),
776
+ num: t1.value,
777
+ gen: t2.value
778
+ } });
779
+ return { num: t1.value, gen: t2.value, value: body };
780
+ }
781
+ function parseFromBytes(bytes) {
782
+ const tok = tokenize(bytes);
783
+ return parseObject(tok);
784
+ }
785
+ function parseIndirectFromBytes(bytes, at, resolveRef) {
786
+ const tok = tokenize(bytes, { start: at | 0 });
787
+ return parseIndirect(tok, resolveRef);
788
+ }
789
+ return {
790
+ tokenize,
791
+ parseObject,
792
+ parseIndirect,
793
+ parseFromBytes,
794
+ parseIndirectFromBytes,
795
+ parserLimits,
796
+ setParserLimits,
797
+ obj,
798
+ getEntry,
799
+ isType
800
+ };
801
+ } });
802
+ __register({ name: "pdfXref", dependencies: ["pdfErrors","pdfTokenizer","pdfParser"], factory: function(errors, tokenizerMod, parserMod) {
803
+ const { ParseError, RenderError } = errors, tokenize = tokenizerMod.tokenize, lastIndexOfBytes = tokenizerMod.lastIndexOfBytes, parseObject = parserMod.parseObject;
804
+ function locateStartXref(bytes) {
805
+ const tail = Math.max(0, bytes.length - 8192), idx = lastIndexOfBytes(bytes, new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]), bytes.length);
806
+ if (idx < tail)
807
+ return -1;
808
+ return idx;
809
+ }
810
+ function readStartXref(bytes, at) {
811
+ const tok = tokenize(bytes, { start: at }), kw = tok.next();
812
+ if (!kw || kw.kind !== "kw" || kw.value !== "startxref")
813
+ throw new ParseError("pdf/xref/no-startxref", "startxref keyword not found", { context: { offset: at } });
814
+ const num = tok.next();
815
+ if (!num || num.kind !== "int" || num.value < 0)
816
+ throw new ParseError("pdf/xref/bad-startxref", "startxref must be followed by a non-negative integer", { context: { offset: at } });
817
+ return num.value;
818
+ }
819
+ function parseIntBytes(bytes, off, len) {
820
+ let n = 0;
821
+ for (let i = 0;i < len; i++) {
822
+ const b = bytes[off + i];
823
+ if (b < 48 || b > 57)
824
+ throw new ParseError("pdf/xref/bad-digit", "expected ASCII digit in xref entry", { context: { offset: off + i, byte: b } });
825
+ n = n * 10 + (b - 48);
826
+ }
827
+ return n;
828
+ }
829
+ function parseXrefTable(bytes, at) {
830
+ const tok = tokenize(bytes, { start: at }), kw = tok.next();
831
+ if (!kw || kw.kind !== "kw" || kw.value !== "xref")
832
+ throw new ParseError("pdf/xref/no-xref-keyword", "expected xref keyword", { context: { offset: at } });
833
+ const entries = {};
834
+ for (;; ) {
835
+ const first = tok.peek();
836
+ if (!first || first.kind !== "int") {
837
+ if (first)
838
+ tok.seek(first.offset);
839
+ break;
840
+ }
841
+ tok.next();
842
+ const cnt = tok.next();
843
+ if (!cnt || cnt.kind !== "int" || cnt.value < 0)
844
+ throw new ParseError("pdf/xref/bad-subsection-header", "xref subsection header must be `<first> <count>`", { context: { offset: first.offset } });
845
+ let p = tok.pos();
846
+ if (p < bytes.length && bytes[p] === 13)
847
+ p++;
848
+ if (p < bytes.length && bytes[p] === 10)
849
+ p++;
850
+ for (let k = 0;k < cnt.value; k++) {
851
+ if (p + 20 > bytes.length)
852
+ throw new ParseError("pdf/xref/truncated-entry", "truncated xref entry", { context: { offset: p, expected: 20 } });
853
+ const off = parseIntBytes(bytes, p, 10);
854
+ if (bytes[p + 10] !== 32)
855
+ throw new ParseError("pdf/xref/bad-entry-format", "xref entry missing space at col 10", { context: { offset: p } });
856
+ const gen = parseIntBytes(bytes, p + 11, 5);
857
+ if (bytes[p + 16] !== 32)
858
+ throw new ParseError("pdf/xref/bad-entry-format", "xref entry missing space at col 16", { context: { offset: p } });
859
+ const tag = bytes[p + 17];
860
+ if (tag !== 110 && tag !== 102)
861
+ throw new ParseError("pdf/xref/bad-entry-flag", "xref entry flag must be n or f", { context: { offset: p, byte: tag } });
862
+ entries[first.value + k] = {
863
+ offset: off,
864
+ gen,
865
+ free: tag === 102
866
+ };
867
+ p += 20;
868
+ }
869
+ tok.seek(p);
870
+ }
871
+ return { entries, end: tok.pos() };
872
+ }
873
+ function parseTrailerDict(bytes, at) {
874
+ const tok = tokenize(bytes, { start: at }), kw = tok.next();
875
+ if (!kw || kw.kind !== "kw" || kw.value !== "trailer")
876
+ throw new ParseError("pdf/xref/no-trailer", "expected trailer keyword", { context: { offset: at } });
877
+ const dict = parseObject(tok);
878
+ if (dict.type !== "dict")
879
+ throw new ParseError("pdf/xref/trailer-not-dict", "trailer must be a dictionary", { context: { offset: at } });
880
+ return { dict, end: tok.pos() };
881
+ }
882
+ function readXrefStreamDict(bytes, at) {
883
+ const notStream = (why) => new ParseError("pdf/xref/not-xref-stream", `no cross-reference stream at offset ${at}: ${why}`, { context: { offset: at } });
884
+ if (!Number.isInteger(at) || at < 0 || at >= bytes.length)
885
+ throw notStream("offset outside the file");
886
+ let num, gen, kw, dict, after;
887
+ try {
888
+ const tok = tokenize(bytes, { start: at });
889
+ num = tok.next();
890
+ gen = tok.next();
891
+ kw = tok.next();
892
+ if (!num || num.kind !== "int" || !gen || gen.kind !== "int" || !kw || kw.kind !== "kw" || kw.value !== "obj")
893
+ throw notStream("no indirect object header");
894
+ dict = parseObject(tok);
895
+ after = tok.peek();
896
+ } catch (e) {
897
+ if (e && e.code === "pdf/xref/not-xref-stream")
898
+ throw e;
899
+ throw notStream("the object does not parse");
900
+ }
901
+ const type = dict && dict.type === "dict" && dict.entries.Type;
902
+ if (!type || type.type !== "name" || type.value !== "XRef" || !after || after.kind !== "kw" || after.value !== "stream")
903
+ throw notStream("the object is not a /Type /XRef stream");
904
+ return { num: num.value, gen: gen.value, dict };
905
+ }
906
+ function byteWidth(n) {
907
+ let w = 1;
908
+ while (n > 255) {
909
+ n = Math.floor(n / 256);
910
+ w++;
911
+ }
912
+ return w;
913
+ }
914
+ function hexLit(bytes) {
915
+ let s = "<";
916
+ for (let i = 0;i < bytes.length; i++)
917
+ s += "0123456789ABCDEF"[bytes[i] >> 4] + "0123456789ABCDEF"[bytes[i] & 15];
918
+ return s + ">";
919
+ }
920
+ function isRef(r) {
921
+ return !!r && Number.isInteger(r.num) && r.num >= 1;
922
+ }
923
+ function buildXrefStream(opts) {
924
+ const bad = (why) => new RenderError("pdf/xref/bad-stream-section", `cannot build the cross-reference stream: ${why}`);
925
+ if (!opts || !Number.isInteger(opts.num) || opts.num < 1)
926
+ throw bad("num must be an integer >= 1");
927
+ if (!Number.isInteger(opts.offset) || opts.offset < 0)
928
+ throw bad("offset must be an integer >= 0");
929
+ if (!Number.isInteger(opts.prev) || opts.prev < 0)
930
+ throw bad("prev must be an integer >= 0");
931
+ if (!isRef(opts.root))
932
+ throw bad("root must be { num >= 1, gen }");
933
+ if (opts.encrypt != null && !isRef(opts.encrypt))
934
+ throw bad("encrypt must be an indirect reference { num >= 1, gen }");
935
+ const rows = new Map;
936
+ rows.set(0, [0, 0, 65535]);
937
+ for (const e of opts.entries || []) {
938
+ if (!e || !Number.isInteger(e.num) || e.num < 1 || !Number.isInteger(e.offset) || e.offset < 0)
939
+ throw bad("each entry needs num >= 1 and offset >= 0");
940
+ rows.set(e.num, [1, e.offset, e.gen | 0]);
941
+ }
942
+ rows.set(opts.num, [1, opts.offset, 0]);
943
+ const nums = Array.from(rows.keys()).sort((a, b) => a - b);
944
+ let max2 = 0, max3 = 0;
945
+ for (const r of rows.values()) {
946
+ if (r[1] > max2)
947
+ max2 = r[1];
948
+ if (r[2] > max3)
949
+ max3 = r[2];
950
+ }
951
+ const w = [1, byteWidth(max2), byteWidth(max3)], rec = w[0] + w[1] + w[2], data = new Uint8Array(nums.length * rec);
952
+ let o = 0;
953
+ for (const n of nums) {
954
+ const r = rows.get(n);
955
+ let at = o;
956
+ for (let f = 0;f < 3; f++) {
957
+ let v = r[f];
958
+ for (let k = w[f] - 1;k >= 0; k--) {
959
+ data[at + k] = v & 255;
960
+ v = Math.floor(v / 256);
961
+ }
962
+ at += w[f];
963
+ }
964
+ o += rec;
965
+ }
966
+ const index = [];
967
+ for (let i = 0;i < nums.length; ) {
968
+ let j = i;
969
+ while (j + 1 < nums.length && nums[j + 1] === nums[j] + 1)
970
+ j++;
971
+ index.push(`${nums[i]} ${j - i + 1}`);
972
+ i = j + 1;
973
+ }
974
+ let d = `<< /Type /XRef /Size ${Math.max(opts.num + 1, Number.isInteger(opts.size) ? opts.size : 0)} /W [${w.join(" ")}] /Index [${index.join(" ")}] /Root ${opts.root.num} ${opts.root.gen | 0} R`;
975
+ if (isRef(opts.info))
976
+ d += ` /Info ${opts.info.num} ${opts.info.gen | 0} R`;
977
+ if (opts.id && opts.id[0] instanceof Uint8Array && opts.id[1] instanceof Uint8Array)
978
+ d += ` /ID [${hexLit(opts.id[0])}${hexLit(opts.id[1])}]`;
979
+ if (isRef(opts.encrypt))
980
+ d += ` /Encrypt ${opts.encrypt.num} ${opts.encrypt.gen | 0} R`;
981
+ d += ` /Prev ${opts.prev} /Length ${data.length} >>`;
982
+ const te = new TextEncoder, head = te.encode(`${opts.num} 0 obj
983
+ ${d}
984
+ stream
985
+ `), tail = te.encode(`
986
+ endstream
987
+ endobj
988
+ `), out = new Uint8Array(head.length + data.length + tail.length);
989
+ out.set(head, 0);
990
+ out.set(data, head.length);
991
+ out.set(tail, head.length + data.length);
992
+ return out;
993
+ }
994
+ return {
995
+ locateStartXref,
996
+ readStartXref,
997
+ parseXrefTable,
998
+ parseTrailerDict,
999
+ readXrefStreamDict,
1000
+ buildXrefStream
1001
+ };
1002
+ } });
1003
+ __register({ name: "pdfTrailer", dependencies: ["pdfErrors","pdfParserObj"], factory: function(errors, parserObj) {
1004
+ const { ParseError } = errors, { isType } = parserObj;
1005
+ function typeTrailer(dict) {
1006
+ if (!isType(dict, "dict"))
1007
+ throw new ParseError("pdf/trailer/not-dict", "trailer is not a dictionary", { context: { type: dict && dict.type } });
1008
+ const e = dict.entries, size = e.Size;
1009
+ if (!size || size.type !== "int" || size.value < 0)
1010
+ throw new ParseError("pdf/trailer/missing-size", "trailer is missing required /Size entry", { context: { hasSize: !!size } });
1011
+ const root = e.Root;
1012
+ if (!root || root.type !== "ref")
1013
+ throw new ParseError("pdf/trailer/missing-root", "trailer is missing required /Root indirect reference", { context: { hasRoot: !!root, type: root && root.type } });
1014
+ const out = {
1015
+ size: size.value,
1016
+ root: { num: root.num, gen: root.gen },
1017
+ raw: dict
1018
+ };
1019
+ if (e.Info && e.Info.type === "ref")
1020
+ out.info = { num: e.Info.num, gen: e.Info.gen };
1021
+ if (e.Prev && e.Prev.type === "int")
1022
+ out.prev = e.Prev.value;
1023
+ if (e.Encrypt)
1024
+ out.encrypt = e.Encrypt.type === "ref" ? { num: e.Encrypt.num, gen: e.Encrypt.gen } : e.Encrypt;
1025
+ if (e.ID && e.ID.type === "array" && e.ID.items.length === 2 && e.ID.items[0].type === "string" && e.ID.items[1].type === "string")
1026
+ out.id = [e.ID.items[0].value, e.ID.items[1].value];
1027
+ return out;
1028
+ }
1029
+ return { typeTrailer };
1030
+ } });
1031
+ __register({ name: "pdfSerializer", dependencies: ["pdfErrors"], factory: function(errors) {
1032
+ const { RenderError } = errors, te = new TextEncoder;
1033
+ function serializeObject(obj) {
1034
+ if (!obj || typeof obj.type !== "string")
1035
+ throw new RenderError("pdf/serializer/bad-input", "serializeObject expects a typed object", { context: { typeof: typeof obj } });
1036
+ return concat(emitObject(obj));
1037
+ }
1038
+ function serializeIndirect(num, gen, body) {
1039
+ if (!Number.isFinite(num) || num < 0)
1040
+ throw new RenderError("pdf/serializer/bad-num", "object number must be a non-negative integer", { context: { num } });
1041
+ if (!Number.isFinite(gen) || gen < 0)
1042
+ throw new RenderError("pdf/serializer/bad-gen", "generation number must be a non-negative integer", { context: { gen } });
1043
+ const head = te.encode(`${num | 0} ${gen | 0} obj
1044
+ `), tail = te.encode(`
1045
+ endobj
1046
+ `);
1047
+ if (body && body.type === "stream") {
1048
+ const raw = body.raw instanceof Uint8Array ? body.raw : new Uint8Array(0), updated = {
1049
+ type: "dict",
1050
+ entries: {
1051
+ ...(body.dict || { type: "dict", entries: {} }).entries,
1052
+ Length: { type: "int", value: raw.length }
1053
+ }
1054
+ }, dictBytes = concat(emitObject(updated)), streamHead = te.encode(`
1055
+ stream
1056
+ `), streamTail = te.encode(`
1057
+ endstream`);
1058
+ return concatU8([head, dictBytes, streamHead, raw, streamTail, tail]);
1059
+ }
1060
+ return concatU8([head, concat(emitObject(body)), tail]);
1061
+ }
1062
+ function formatReal(n) {
1063
+ if (!Number.isFinite(n))
1064
+ throw new RenderError("pdf/serializer/bad-real", "real number must be finite", { context: { value: n } });
1065
+ if (Number.isInteger(n))
1066
+ return `${n}`;
1067
+ let s = n.toFixed(5);
1068
+ if (s.indexOf(".") >= 0) {
1069
+ s = s.replace(/0+$/, "");
1070
+ if (s.endsWith("."))
1071
+ s = s.slice(0, -1);
1072
+ }
1073
+ if (s === "-0")
1074
+ s = "0";
1075
+ return s;
1076
+ }
1077
+ function emitObject(o) {
1078
+ switch (o.type) {
1079
+ case "null":
1080
+ return ["null"];
1081
+ case "bool":
1082
+ return [o.value ? "true" : "false"];
1083
+ case "int":
1084
+ return [`${o.value | 0}`];
1085
+ case "real":
1086
+ return [formatReal(o.value)];
1087
+ case "name":
1088
+ return [emitName(o.value)];
1089
+ case "string":
1090
+ return [emitString(o)];
1091
+ case "array":
1092
+ return emitArray(o);
1093
+ case "dict":
1094
+ return emitDict(o);
1095
+ case "ref":
1096
+ return [`${o.num | 0} ${o.gen | 0} R`];
1097
+ case "stream":
1098
+ throw new RenderError("pdf/serializer/inline-stream", "stream objects must be serialized via serializeIndirect");
1099
+ default:
1100
+ throw new RenderError("pdf/serializer/unknown-type", `unknown object type "${o.type}"`, { context: { type: o.type } });
1101
+ }
1102
+ }
1103
+ function emitName(value) {
1104
+ let out = "/";
1105
+ for (let i = 0;i < value.length; i++) {
1106
+ const cp = value.codePointAt(i);
1107
+ if (cp > 65535)
1108
+ i++;
1109
+ if (cp < 33 || cp > 126 || cp === 35 || cp === 47 || cp === 40 || cp === 41 || cp === 60 || cp === 62 || cp === 91 || cp === 93 || cp === 123 || cp === 125 || cp === 37) {
1110
+ const enc = te.encode(String.fromCodePoint(cp));
1111
+ for (const b of enc)
1112
+ out += "#" + b.toString(16).padStart(2, "0").toUpperCase();
1113
+ } else
1114
+ out += String.fromCharCode(cp);
1115
+ }
1116
+ return out;
1117
+ }
1118
+ function emitString(o) {
1119
+ const bytes = o.value;
1120
+ if (!(bytes instanceof Uint8Array))
1121
+ throw new RenderError("pdf/serializer/bad-string", "string value must be Uint8Array", { context: { typeof: typeof bytes } });
1122
+ if (o.syntax === "hex" || shouldUseHex(bytes))
1123
+ return emitHexString(bytes);
1124
+ return emitLiteralString(bytes);
1125
+ }
1126
+ function shouldUseHex(bytes) {
1127
+ let bad = 0;
1128
+ for (let i = 0;i < bytes.length; i++) {
1129
+ const b = bytes[i];
1130
+ if (b < 9 || b > 13 && b < 32 || b >= 127)
1131
+ bad++;
1132
+ if (bad > bytes.length / 4)
1133
+ return !0;
1134
+ }
1135
+ return !1;
1136
+ }
1137
+ function emitLiteralString(bytes) {
1138
+ const out = ["("];
1139
+ for (let i = 0;i < bytes.length; i++) {
1140
+ const b = bytes[i];
1141
+ if (b === 92)
1142
+ out.push("\\\\");
1143
+ else if (b === 40)
1144
+ out.push("\\(");
1145
+ else if (b === 41)
1146
+ out.push("\\)");
1147
+ else if (b === 10)
1148
+ out.push("\\n");
1149
+ else if (b === 13)
1150
+ out.push("\\r");
1151
+ else if (b === 9)
1152
+ out.push("\\t");
1153
+ else if (b === 8)
1154
+ out.push("\\b");
1155
+ else if (b === 12)
1156
+ out.push("\\f");
1157
+ else if (b < 32 || b > 126)
1158
+ out.push("\\" + b.toString(8).padStart(3, "0"));
1159
+ else
1160
+ out.push(String.fromCharCode(b));
1161
+ }
1162
+ out.push(")");
1163
+ return out.join("");
1164
+ }
1165
+ function emitHexString(bytes) {
1166
+ let s = "<";
1167
+ for (let i = 0;i < bytes.length; i++)
1168
+ s += "0123456789ABCDEF"[bytes[i] >> 4] + "0123456789ABCDEF"[bytes[i] & 15];
1169
+ return s + ">";
1170
+ }
1171
+ function emitArray(o) {
1172
+ const parts = ["["];
1173
+ let first = !0;
1174
+ for (const it of o.items) {
1175
+ if (!first)
1176
+ parts.push(" ");
1177
+ first = !1;
1178
+ for (const p of emitObject(it))
1179
+ parts.push(p);
1180
+ }
1181
+ parts.push("]");
1182
+ return parts;
1183
+ }
1184
+ function emitDict(o) {
1185
+ const parts = ["<<"];
1186
+ for (const k of Object.keys(o.entries)) {
1187
+ parts.push(" ");
1188
+ parts.push(emitName(k));
1189
+ parts.push(" ");
1190
+ for (const p of emitObject(o.entries[k]))
1191
+ parts.push(p);
1192
+ }
1193
+ parts.push(" >>");
1194
+ return parts;
1195
+ }
1196
+ function concat(parts) {
1197
+ let s = "";
1198
+ for (const p of parts)
1199
+ s += p;
1200
+ return te.encode(s);
1201
+ }
1202
+ function concatU8(arrays) {
1203
+ let n = 0;
1204
+ for (const a of arrays)
1205
+ n += a.length;
1206
+ const out = new Uint8Array(n);
1207
+ let o = 0;
1208
+ for (const a of arrays) {
1209
+ out.set(a, o);
1210
+ o += a.length;
1211
+ }
1212
+ return out;
1213
+ }
1214
+ return { serializeObject, serializeIndirect, formatReal };
1215
+ } });
1216
+ __register({ name: "pdfCatalog", dependencies: ["pdfErrors","pdfParser"], factory: function(errors, parserMod) {
1217
+ const { ParseError } = errors, isType = parserMod && parserMod.isType || ((v, kind) => !!(v && v.type === kind)), KNOWN = new Set([
1218
+ "Type",
1219
+ "Version",
1220
+ "Pages",
1221
+ "PageLabels",
1222
+ "Names",
1223
+ "Dests",
1224
+ "ViewerPreferences",
1225
+ "PageLayout",
1226
+ "PageMode",
1227
+ "Outlines",
1228
+ "Threads",
1229
+ "OpenAction",
1230
+ "AA",
1231
+ "URI",
1232
+ "AcroForm",
1233
+ "Metadata",
1234
+ "StructTreeRoot",
1235
+ "MarkInfo",
1236
+ "Lang",
1237
+ "SpiderInfo",
1238
+ "OutputIntents",
1239
+ "PieceInfo",
1240
+ "OCProperties",
1241
+ "Perms",
1242
+ "Legal",
1243
+ "Requirements",
1244
+ "Collection",
1245
+ "NeedsRendering",
1246
+ "DSS",
1247
+ "AF",
1248
+ "DPartRoot"
1249
+ ]);
1250
+ function typeCatalog(dict) {
1251
+ if (!isType(dict, "dict"))
1252
+ throw new ParseError("pdf/catalog/not-dict", "Catalog must be a dictionary", { context: { type: dict && dict.type } });
1253
+ const e = dict.entries;
1254
+ if (e.Type && (e.Type.type !== "name" || e.Type.value !== "Catalog"))
1255
+ throw new ParseError("pdf/catalog/bad-type", "/Type entry must be /Catalog", { context: { actual: e.Type.value } });
1256
+ if (!e.Pages || e.Pages.type !== "ref")
1257
+ throw new ParseError("pdf/catalog/missing-pages", "Catalog is missing required /Pages reference", { context: { type: e.Pages && e.Pages.type } });
1258
+ const out = {
1259
+ pages: { num: e.Pages.num, gen: e.Pages.gen },
1260
+ raw: dict,
1261
+ _extras: {}
1262
+ };
1263
+ if (e.Version && e.Version.type === "name")
1264
+ out.version = e.Version.value;
1265
+ if (e.PageLayout && e.PageLayout.type === "name")
1266
+ out.pageLayout = e.PageLayout.value;
1267
+ if (e.PageMode && e.PageMode.type === "name")
1268
+ out.pageMode = e.PageMode.value;
1269
+ if (e.Lang && e.Lang.type === "string")
1270
+ out.lang = e.Lang.value;
1271
+ if (e.Outlines && e.Outlines.type === "ref")
1272
+ out.outlines = e.Outlines;
1273
+ if (e.Metadata && e.Metadata.type === "ref")
1274
+ out.metadata = e.Metadata;
1275
+ if (e.StructTreeRoot && e.StructTreeRoot.type === "ref")
1276
+ out.structTreeRoot = e.StructTreeRoot;
1277
+ if (e.AcroForm)
1278
+ out.acroForm = e.AcroForm;
1279
+ if (e.Names)
1280
+ out.names = e.Names;
1281
+ if (e.Dests)
1282
+ out.dests = e.Dests;
1283
+ if (e.ViewerPreferences)
1284
+ out.viewerPrefs = e.ViewerPreferences;
1285
+ if (e.PageLabels)
1286
+ out.pageLabels = e.PageLabels;
1287
+ if (e.MarkInfo)
1288
+ out.markInfo = e.MarkInfo;
1289
+ if (e.OCProperties)
1290
+ out.ocProperties = e.OCProperties;
1291
+ if (e.OutputIntents)
1292
+ out.outputIntents = e.OutputIntents;
1293
+ for (const k of Object.keys(e))
1294
+ if (!KNOWN.has(k))
1295
+ out._extras[k] = e[k];
1296
+ return out;
1297
+ }
1298
+ return { typeCatalog };
1299
+ } });
1300
+ __register({ name: "pdfPages", dependencies: ["pdfErrors","pdfParser"], factory: function(errors, parserMod) {
1301
+ const { ParseError } = errors, isType = parserMod && parserMod.isType || ((v, kind) => !!(v && v.type === kind));
1302
+ function walkPageTree(rootRef, resolveRef, opts) {
1303
+ const maxDepth = opts && opts.maxDepth || 64, maxPages = opts && opts.maxPages || 200000, out = [], visited = new Set;
1304
+ walk(rootRef, 0);
1305
+ return out;
1306
+ function walk(ref, depth) {
1307
+ if (depth > maxDepth)
1308
+ throw new ParseError("pdf/pages/max-depth", "page tree depth limit exceeded", { context: { depth, maxDepth } });
1309
+ const key = ref.num + ":" + ref.gen;
1310
+ if (visited.has(key))
1311
+ throw new ParseError("pdf/pages/cycle", "cycle detected in page tree", { context: { ref } });
1312
+ visited.add(key);
1313
+ const node = resolveRef({ type: "ref", num: ref.num, gen: ref.gen });
1314
+ if (!isType(node, "dict"))
1315
+ throw new ParseError("pdf/pages/not-dict", "page tree node is not a dict", { context: { ref } });
1316
+ const t = node.entries.Type;
1317
+ if (t && t.type === "name" && t.value === "Page" || !node.entries.Kids && !t) {
1318
+ out.push({ num: ref.num, gen: ref.gen });
1319
+ if (out.length > maxPages)
1320
+ throw new ParseError("pdf/pages/too-many", "page count limit exceeded", { context: { maxPages } });
1321
+ return;
1322
+ }
1323
+ const kids = node.entries.Kids;
1324
+ if (!kids || kids.type !== "array")
1325
+ throw new ParseError("pdf/pages/missing-kids", "intermediate page tree node missing /Kids array", { context: { ref, hasKids: !!kids } });
1326
+ for (const k of kids.items) {
1327
+ if (k.type !== "ref")
1328
+ throw new ParseError("pdf/pages/non-ref-kid", "page tree /Kids entries must be indirect refs", { context: { kind: k.type } });
1329
+ walk({ num: k.num, gen: k.gen }, depth + 1);
1330
+ }
1331
+ }
1332
+ }
1333
+ function readPageCount(node) {
1334
+ if (!isType(node, "dict"))
1335
+ return null;
1336
+ const c = node.entries.Count;
1337
+ if (!c || c.type !== "int" && c.type !== "real")
1338
+ return null;
1339
+ return c.value | 0;
1340
+ }
1341
+ return { walkPageTree, readPageCount };
1342
+ } });
1343
+ __register({ name: "pdfPage", dependencies: ["pdfErrors","pdfParser"], factory: function(errors, parserMod) {
1344
+ const { ParseError } = errors, isType = parserMod && parserMod.isType || ((v, kind) => !!(v && v.type === kind)), KNOWN = new Set([
1345
+ "Type",
1346
+ "Parent",
1347
+ "LastModified",
1348
+ "Resources",
1349
+ "MediaBox",
1350
+ "CropBox",
1351
+ "BleedBox",
1352
+ "TrimBox",
1353
+ "ArtBox",
1354
+ "BoxColorInfo",
1355
+ "Contents",
1356
+ "Rotate",
1357
+ "Group",
1358
+ "Thumb",
1359
+ "B",
1360
+ "Dur",
1361
+ "Trans",
1362
+ "Annots",
1363
+ "AA",
1364
+ "Metadata",
1365
+ "PieceInfo",
1366
+ "StructParents",
1367
+ "ID",
1368
+ "PZ",
1369
+ "SeparationInfo",
1370
+ "Tabs",
1371
+ "TemplateInstantiated",
1372
+ "PresSteps",
1373
+ "UserUnit",
1374
+ "VP",
1375
+ "AF",
1376
+ "OutputIntents",
1377
+ "DPart",
1378
+ "AssociatedFiles"
1379
+ ]);
1380
+ function toBox(v) {
1381
+ if (!v || v.type !== "array" || v.items.length !== 4)
1382
+ return null;
1383
+ const r = Array(4);
1384
+ for (let i = 0;i < 4; i++) {
1385
+ const it = v.items[i];
1386
+ if (!it || it.type !== "int" && it.type !== "real")
1387
+ return null;
1388
+ r[i] = it.value;
1389
+ }
1390
+ return r;
1391
+ }
1392
+ function toRotate(v) {
1393
+ if (!v || v.type !== "int" && v.type !== "real")
1394
+ return 0;
1395
+ const m = ((v.value | 0) % 360 + 360) % 360;
1396
+ if (m % 90 !== 0)
1397
+ return 0;
1398
+ return m;
1399
+ }
1400
+ function toContentsRefs(v) {
1401
+ if (!v)
1402
+ return [];
1403
+ if (v.type === "ref")
1404
+ return [{ num: v.num, gen: v.gen }];
1405
+ if (v.type === "array") {
1406
+ const out = [];
1407
+ for (const it of v.items)
1408
+ if (it.type === "ref")
1409
+ out.push({ num: it.num, gen: it.gen });
1410
+ return out;
1411
+ }
1412
+ return [];
1413
+ }
1414
+ function toAnnots(v) {
1415
+ if (!v)
1416
+ return [];
1417
+ if (v.type === "ref")
1418
+ return [v];
1419
+ if (v.type === "array")
1420
+ return v.items.slice();
1421
+ return [];
1422
+ }
1423
+ function typePage(dict) {
1424
+ if (!isType(dict, "dict"))
1425
+ throw new ParseError("pdf/page/not-dict", "Page must be a dictionary", { context: { type: dict && dict.type } });
1426
+ const e = dict.entries;
1427
+ if (e.Type && (e.Type.type !== "name" || e.Type.value !== "Page"))
1428
+ throw new ParseError("pdf/page/bad-type", "/Type must be /Page when present", { context: { actual: e.Type.value } });
1429
+ const out = {
1430
+ parent: e.Parent && e.Parent.type === "ref" ? { num: e.Parent.num, gen: e.Parent.gen } : null,
1431
+ mediaBox: toBox(e.MediaBox),
1432
+ resources: e.Resources || null,
1433
+ contents: toContentsRefs(e.Contents),
1434
+ rotate: toRotate(e.Rotate),
1435
+ annots: toAnnots(e.Annots),
1436
+ raw: dict,
1437
+ _extras: {}
1438
+ };
1439
+ if (e.CropBox)
1440
+ out.cropBox = toBox(e.CropBox);
1441
+ if (e.BleedBox)
1442
+ out.bleedBox = toBox(e.BleedBox);
1443
+ if (e.TrimBox)
1444
+ out.trimBox = toBox(e.TrimBox);
1445
+ if (e.ArtBox)
1446
+ out.artBox = toBox(e.ArtBox);
1447
+ if (e.UserUnit && e.UserUnit.type === "real")
1448
+ out.userUnit = e.UserUnit.value;
1449
+ if (e.UserUnit && e.UserUnit.type === "int")
1450
+ out.userUnit = e.UserUnit.value;
1451
+ if (e.Tabs && e.Tabs.type === "name")
1452
+ out.tabs = e.Tabs.value;
1453
+ if (e.Metadata)
1454
+ out.metadata = e.Metadata;
1455
+ if (e.Group)
1456
+ out.group = e.Group;
1457
+ for (const k of Object.keys(e))
1458
+ if (!KNOWN.has(k))
1459
+ out._extras[k] = e[k];
1460
+ return out;
1461
+ }
1462
+ return { typePage };
1463
+ } });
1464
+ __register({ name: "pdfCrossRefStream", dependencies: ["pdfErrors","pdfParserObj"], factory: function(errors, parserObj) {
1465
+ const { ParseError } = errors, { isType } = parserObj;
1466
+ function readBE(bytes, off, len) {
1467
+ let v = 0;
1468
+ for (let i = 0;i < len; i++)
1469
+ v = v * 256 + bytes[off + i];
1470
+ return v;
1471
+ }
1472
+ function readInt(entry, label) {
1473
+ if (!entry || entry.type !== "int")
1474
+ throw new ParseError("pdf/xrefstm/missing-int", `XRef stream dict missing required /${label}`, { context: { label } });
1475
+ return entry.value;
1476
+ }
1477
+ function parseCrossRefStream(decoded, dict) {
1478
+ if (!(decoded instanceof Uint8Array))
1479
+ throw new ParseError("pdf/xrefstm/bad-input", "parseCrossRefStream expects Uint8Array");
1480
+ if (!isType(dict, "dict"))
1481
+ throw new ParseError("pdf/xrefstm/bad-dict", "XRef stream dict must be a typed dict");
1482
+ const e = dict.entries;
1483
+ if (!e.Type || e.Type.type !== "name" || e.Type.value !== "XRef")
1484
+ throw new ParseError("pdf/xrefstm/wrong-type", "/Type must be /XRef", { context: { actual: e.Type && e.Type.value } });
1485
+ const W = e.W;
1486
+ if (!W || W.type !== "array" || W.items.length !== 3)
1487
+ throw new ParseError("pdf/xrefstm/bad-W", "/W must be a 3-element array", { context: { items: W && W.items && W.items.length } });
1488
+ const w = W.items.map((it) => {
1489
+ if (it.type !== "int" || it.value < 0)
1490
+ throw new ParseError("pdf/xrefstm/bad-W-entry", "/W entries must be non-negative ints");
1491
+ return it.value;
1492
+ }), recordSize = w[0] + w[1] + w[2];
1493
+ if (recordSize <= 0)
1494
+ throw new ParseError("pdf/xrefstm/bad-W-zero", "/W must yield at least one non-zero field");
1495
+ let index;
1496
+ if (e.Index) {
1497
+ if (e.Index.type !== "array" || (e.Index.items.length & 1) !== 0)
1498
+ throw new ParseError("pdf/xrefstm/bad-Index", "/Index must be an array of (first, count) pairs");
1499
+ index = [];
1500
+ for (let i = 0;i < e.Index.items.length; i += 2) {
1501
+ const f = e.Index.items[i], c = e.Index.items[i + 1];
1502
+ if (f.type !== "int" || c.type !== "int")
1503
+ throw new ParseError("pdf/xrefstm/bad-Index-entry", "/Index entries must be ints");
1504
+ index.push([f.value, c.value]);
1505
+ }
1506
+ } else
1507
+ index = [[0, readInt(e.Size, "Size")]];
1508
+ const entries = {};
1509
+ let pos = 0;
1510
+ for (const [first, count] of index)
1511
+ for (let k = 0;k < count; k++) {
1512
+ if (pos + recordSize > decoded.length)
1513
+ throw new ParseError("pdf/xrefstm/truncated", "truncated xref stream payload", { context: { pos, recordSize, length: decoded.length } });
1514
+ const t = w[0] > 0 ? readBE(decoded, pos, w[0]) : 1, f2 = w[1] > 0 ? readBE(decoded, pos + w[0], w[1]) : 0, f3 = w[2] > 0 ? readBE(decoded, pos + w[0] + w[1], w[2]) : 0;
1515
+ pos += recordSize;
1516
+ const num = first + k;
1517
+ if (t === 0)
1518
+ entries[num] = { type: 0, offset: f2, gen: f3, free: !0 };
1519
+ else if (t === 1)
1520
+ entries[num] = { type: 1, offset: f2, gen: f3, free: !1 };
1521
+ else if (t === 2)
1522
+ entries[num] = {
1523
+ type: 2,
1524
+ objStm: f2,
1525
+ index: f3,
1526
+ free: !1,
1527
+ offset: 0,
1528
+ gen: 0
1529
+ };
1530
+ else
1531
+ entries[num] = { type: t, offset: 0, gen: 0, free: !0 };
1532
+ }
1533
+ return {
1534
+ entries,
1535
+ size: e.Size && e.Size.type === "int" ? e.Size.value : Object.keys(entries).length,
1536
+ trailer: dict
1537
+ };
1538
+ }
1539
+ return { parseCrossRefStream };
1540
+ } });
1541
+ __register({ name: "pdfObjStream", dependencies: ["pdfErrors","pdfParserObj","pdfTokenizer","pdfParser"], factory: function(errors, parserObj, tokenizerMod, parserMod) {
1542
+ const { ParseError } = errors, { isType } = parserObj, tokenize = tokenizerMod.tokenize, parseObject = parserMod.parseObject;
1543
+ function readInt(entry, label) {
1544
+ if (!entry || entry.type !== "int")
1545
+ throw new ParseError("pdf/objstm/missing-int", `ObjStm dict missing required /${label}`, { context: { label, hasEntry: !!entry, type: entry && entry.type } });
1546
+ return entry.value;
1547
+ }
1548
+ function parseObjectStream(decoded, dict) {
1549
+ if (!(decoded instanceof Uint8Array))
1550
+ throw new ParseError("pdf/objstm/bad-input", "parseObjectStream expects Uint8Array", { context: { typeof: typeof decoded } });
1551
+ if (!isType(dict, "dict"))
1552
+ throw new ParseError("pdf/objstm/bad-dict", "ObjStm dict must be a typed dict");
1553
+ const e = dict.entries;
1554
+ if (e.Type && (e.Type.type !== "name" || e.Type.value !== "ObjStm"))
1555
+ throw new ParseError("pdf/objstm/wrong-type", "/Type must be /ObjStm", { context: { actual: e.Type.value } });
1556
+ const N = readInt(e.N, "N"), First = readInt(e.First, "First");
1557
+ if (N < 0)
1558
+ throw new ParseError("pdf/objstm/bad-N", "/N must be non-negative", { context: { N } });
1559
+ if (First < 0 || First > decoded.length)
1560
+ throw new ParseError("pdf/objstm/bad-First", "/First out of payload range", { context: { First, length: decoded.length } });
1561
+ const header = tokenize(decoded, { start: 0, end: First }), nums = Array(N), offs = Array(N);
1562
+ for (let i = 0;i < N; i++) {
1563
+ const tNum = header.next(), tOff = header.next();
1564
+ if (!tNum || tNum.kind !== "int" || !tOff || tOff.kind !== "int")
1565
+ throw new ParseError("pdf/objstm/bad-pair", "ObjStm header expects N pairs of integers", { context: { index: i } });
1566
+ nums[i] = tNum.value;
1567
+ offs[i] = tOff.value;
1568
+ }
1569
+ const out = Array(N);
1570
+ for (let i = 0;i < N; i++) {
1571
+ const start = First + offs[i], end = i + 1 < N ? First + offs[i + 1] : decoded.length;
1572
+ if (start < First || end > decoded.length || start > end)
1573
+ throw new ParseError("pdf/objstm/bad-offset", "ObjStm member offset out of range", { context: { index: i, start, end, length: decoded.length } });
1574
+ const tok = tokenize(decoded, { start, end }), value = parseObject(tok);
1575
+ out[i] = { num: nums[i], gen: 0, value };
1576
+ }
1577
+ return out;
1578
+ }
1579
+ return { parseObjectStream };
1580
+ } });
1581
+ __register({ name: "pdfFlate", dependencies: ["pdfErrors","zlib"], factory: function(errors, fwZlib) {
1582
+ const { ParseError } = errors;
1583
+ if (!fwZlib || typeof fwZlib.unzlibSync !== "function" || typeof fwZlib.zlibSync !== "function")
1584
+ throw new ParseError("pdf/flate/missing-fw", "pdfFlate requires the @awacloud/fw zlib module", { context: { keys: fwZlib && Object.keys(fwZlib) } });
1585
+ function paeth(a, b, c) {
1586
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
1587
+ if (pa <= pb && pa <= pc)
1588
+ return a;
1589
+ if (pb <= pc)
1590
+ return b;
1591
+ return c;
1592
+ }
1593
+ function predictorParams(params) {
1594
+ const predictor = params && params.predictor != null ? params.predictor | 0 : params && params.Predictor != null ? params.Predictor | 0 : 1, columns = params && params.columns != null ? params.columns | 0 : params && params.Columns != null ? params.Columns | 0 : 1, colors = params && params.colors != null ? params.colors | 0 : params && params.Colors != null ? params.Colors | 0 : 1, bpc = params && params.bitsPerComponent != null ? params.bitsPerComponent | 0 : params && params.BitsPerComponent != null ? params.BitsPerComponent | 0 : 8;
1595
+ if (predictor !== 1 && predictor !== 2 && (predictor < 10 || predictor > 15))
1596
+ throw new ParseError("pdf/flate/bad-predictor", "unsupported Predictor value", { context: { predictor } });
1597
+ if (columns <= 0 || colors <= 0 || bpc <= 0)
1598
+ throw new ParseError("pdf/flate/bad-predictor-params", "Columns, Colors and BitsPerComponent must be > 0", { context: { columns, colors, bpc } });
1599
+ const bitsPerPixel = colors * bpc, bytesPerPixel = Math.max(1, bitsPerPixel + 7 >> 3), rowBytes = columns * bitsPerPixel + 7 >> 3;
1600
+ return { predictor, columns, colors, bpc, bytesPerPixel, rowBytes };
1601
+ }
1602
+ function pngUnfilterRow(filter, row, prevRow, bpp) {
1603
+ const out = new Uint8Array(row.length);
1604
+ for (let i = 0;i < row.length; i++) {
1605
+ const left = i >= bpp ? out[i - bpp] : 0, up = prevRow ? prevRow[i] : 0, upLeft = prevRow && i >= bpp ? prevRow[i - bpp] : 0;
1606
+ let v = row[i];
1607
+ switch (filter) {
1608
+ case 0:
1609
+ break;
1610
+ case 1:
1611
+ v = v + left & 255;
1612
+ break;
1613
+ case 2:
1614
+ v = v + up & 255;
1615
+ break;
1616
+ case 3:
1617
+ v = v + (left + up >> 1) & 255;
1618
+ break;
1619
+ case 4:
1620
+ v = v + paeth(left, up, upLeft) & 255;
1621
+ break;
1622
+ default:
1623
+ throw new ParseError("pdf/flate/bad-png-filter", "unknown PNG filter tag", { context: { tag: filter } });
1624
+ }
1625
+ out[i] = v;
1626
+ }
1627
+ return out;
1628
+ }
1629
+ function pngFilterRow(filter, row, prevRow, bpp) {
1630
+ const out = new Uint8Array(row.length);
1631
+ for (let i = 0;i < row.length; i++) {
1632
+ const left = i >= bpp ? row[i - bpp] : 0, up = prevRow ? prevRow[i] : 0, upLeft = prevRow && i >= bpp ? prevRow[i - bpp] : 0, v = row[i];
1633
+ switch (filter) {
1634
+ case 0:
1635
+ out[i] = v;
1636
+ break;
1637
+ case 1:
1638
+ out[i] = v - left & 255;
1639
+ break;
1640
+ case 2:
1641
+ out[i] = v - up & 255;
1642
+ break;
1643
+ case 3:
1644
+ out[i] = v - (left + up >> 1) & 255;
1645
+ break;
1646
+ case 4:
1647
+ out[i] = v - paeth(left, up, upLeft) & 255;
1648
+ break;
1649
+ default:
1650
+ throw new ParseError("pdf/flate/bad-png-filter", "unknown PNG filter tag", { context: { tag: filter } });
1651
+ }
1652
+ }
1653
+ return out;
1654
+ }
1655
+ function tiff2Decode(bytes, p) {
1656
+ if (p.bpc !== 8)
1657
+ throw new ParseError("pdf/flate/tiff-bpc-unsupported", "TIFF Predictor 2 requires BitsPerComponent=8", { context: { bpc: p.bpc } });
1658
+ const out = new Uint8Array(bytes.length), stride = p.colors, rowBytes = p.rowBytes, rows = bytes.length / rowBytes | 0;
1659
+ for (let r = 0;r < rows; r++) {
1660
+ const base = r * rowBytes;
1661
+ for (let i = 0;i < rowBytes; i++) {
1662
+ const left = i >= stride ? out[base + i - stride] : 0;
1663
+ out[base + i] = bytes[base + i] + left & 255;
1664
+ }
1665
+ }
1666
+ return out;
1667
+ }
1668
+ function tiff2Encode(bytes, p) {
1669
+ if (p.bpc !== 8)
1670
+ throw new ParseError("pdf/flate/tiff-bpc-unsupported", "TIFF Predictor 2 requires BitsPerComponent=8", { context: { bpc: p.bpc } });
1671
+ const out = new Uint8Array(bytes.length), stride = p.colors, rowBytes = p.rowBytes, rows = bytes.length / rowBytes | 0;
1672
+ for (let r = 0;r < rows; r++) {
1673
+ const base = r * rowBytes;
1674
+ for (let i = 0;i < rowBytes; i++) {
1675
+ const left = i >= stride ? bytes[base + i - stride] : 0;
1676
+ out[base + i] = bytes[base + i] - left & 255;
1677
+ }
1678
+ }
1679
+ return out;
1680
+ }
1681
+ function pngDecode(bytes, p) {
1682
+ const rowBytes = p.rowBytes, stride = rowBytes + 1;
1683
+ if (bytes.length % stride !== 0)
1684
+ throw new ParseError("pdf/flate/png-row-mismatch", "predicted stream length is not a multiple of (rowBytes+1)", { context: { length: bytes.length, stride } });
1685
+ const rows = bytes.length / stride, out = new Uint8Array(rows * rowBytes);
1686
+ let prev = null;
1687
+ for (let r = 0;r < rows; r++) {
1688
+ const tag = bytes[r * stride], row = bytes.subarray(r * stride + 1, r * stride + stride), unfiltered = pngUnfilterRow(tag, row, prev, p.bytesPerPixel);
1689
+ out.set(unfiltered, r * rowBytes);
1690
+ prev = unfiltered;
1691
+ }
1692
+ return out;
1693
+ }
1694
+ function pngEncode(bytes, p) {
1695
+ const rowBytes = p.rowBytes;
1696
+ if (bytes.length % rowBytes !== 0)
1697
+ throw new ParseError("pdf/flate/png-row-mismatch", "input length is not a multiple of rowBytes", { context: { length: bytes.length, rowBytes } });
1698
+ const rows = bytes.length / rowBytes, outStride = rowBytes + 1, out = new Uint8Array(rows * outStride), forced = p.predictor === 15 ? -1 : p.predictor - 10;
1699
+ let prev = null;
1700
+ for (let r = 0;r < rows; r++) {
1701
+ const row = bytes.subarray(r * rowBytes, (r + 1) * rowBytes);
1702
+ let tag = forced;
1703
+ if (tag < 0)
1704
+ tag = r === 0 ? 0 : 2;
1705
+ const filtered = pngFilterRow(tag, row, prev, p.bytesPerPixel);
1706
+ out[r * outStride] = tag;
1707
+ out.set(filtered, r * outStride + 1);
1708
+ prev = row;
1709
+ }
1710
+ return out;
1711
+ }
1712
+ function endedBeforeFinalBlock(e) {
1713
+ return !!e && e.code === 0;
1714
+ }
1715
+ function inflatePrefix(bytes) {
1716
+ const chunks = [];
1717
+ let total = 0;
1718
+ new fwZlib.UnzlibStream((chunk) => {
1719
+ chunks.push(chunk);
1720
+ total += chunk.length;
1721
+ }).push(bytes, !1);
1722
+ const out = new Uint8Array(total);
1723
+ let off = 0;
1724
+ for (const chunk of chunks) {
1725
+ out.set(chunk, off);
1726
+ off += chunk.length;
1727
+ }
1728
+ return out;
1729
+ }
1730
+ function markTruncated(out) {
1731
+ Object.defineProperty(out, "truncated", { value: !0, enumerable: !1 });
1732
+ return out;
1733
+ }
1734
+ function decode(bytes, params) {
1735
+ if (!(bytes instanceof Uint8Array))
1736
+ throw new ParseError("pdf/flate/bad-input", "FlateDecode expects Uint8Array");
1737
+ let raw, truncated = !1;
1738
+ try {
1739
+ raw = fwZlib.unzlibSync(bytes);
1740
+ } catch (e) {
1741
+ const inflateFailed = () => new ParseError("pdf/flate/inflate-failed", "inflate failed: " + (e && e.message), { context: { length: bytes.length }, cause: e });
1742
+ if (!endedBeforeFinalBlock(e) || typeof fwZlib.UnzlibStream !== "function")
1743
+ throw inflateFailed();
1744
+ let prefix;
1745
+ try {
1746
+ prefix = inflatePrefix(bytes);
1747
+ } catch {
1748
+ throw inflateFailed();
1749
+ }
1750
+ if (prefix.length === 0)
1751
+ throw inflateFailed();
1752
+ raw = prefix;
1753
+ truncated = !0;
1754
+ }
1755
+ const done = (out) => truncated ? markTruncated(out) : out;
1756
+ if (!params)
1757
+ return done(raw);
1758
+ if (!(params.predictor != null && params.predictor !== 1 || params.Predictor != null && params.Predictor !== 1))
1759
+ return done(raw);
1760
+ const p = predictorParams(params);
1761
+ if (p.predictor === 1)
1762
+ return done(raw);
1763
+ const stride = p.predictor === 2 ? p.rowBytes : p.rowBytes + 1;
1764
+ if (truncated)
1765
+ raw = raw.subarray(0, raw.length - raw.length % stride);
1766
+ if (p.predictor === 2)
1767
+ return done(tiff2Decode(raw, p));
1768
+ return done(pngDecode(raw, p));
1769
+ }
1770
+ function encode(bytes, params) {
1771
+ if (!(bytes instanceof Uint8Array))
1772
+ throw new ParseError("pdf/flate/bad-input", "FlateEncode expects Uint8Array");
1773
+ let payload = bytes;
1774
+ if (params) {
1775
+ if (params.predictor != null && params.predictor !== 1 || params.Predictor != null && params.Predictor !== 1) {
1776
+ const p = predictorParams(params);
1777
+ if (p.predictor === 2)
1778
+ payload = tiff2Encode(bytes, p);
1779
+ else if (p.predictor >= 10)
1780
+ payload = pngEncode(bytes, p);
1781
+ }
1782
+ }
1783
+ try {
1784
+ return fwZlib.zlibSync(payload);
1785
+ } catch (e) {
1786
+ throw new ParseError("pdf/flate/deflate-failed", "deflate failed: " + (e && e.message), { context: { length: payload.length }, cause: e });
1787
+ }
1788
+ }
1789
+ return { decode, encode };
1790
+ } });
1791
+ __register({ name: "pdfAsciiHex", dependencies: ["pdfErrors"], factory: function(errors) {
1792
+ const { ParseError } = errors, HEX_LO = [
1793
+ -1,
1794
+ -1,
1795
+ -1,
1796
+ -1,
1797
+ -1,
1798
+ -1,
1799
+ -1,
1800
+ -1,
1801
+ -1,
1802
+ -1,
1803
+ -1,
1804
+ -1,
1805
+ -1,
1806
+ -1,
1807
+ -1,
1808
+ -1,
1809
+ -1,
1810
+ -1,
1811
+ -1,
1812
+ -1,
1813
+ -1,
1814
+ -1,
1815
+ -1,
1816
+ -1,
1817
+ -1,
1818
+ -1,
1819
+ -1,
1820
+ -1,
1821
+ -1,
1822
+ -1,
1823
+ -1,
1824
+ -1,
1825
+ -1,
1826
+ -1,
1827
+ -1,
1828
+ -1,
1829
+ -1,
1830
+ -1,
1831
+ -1,
1832
+ -1,
1833
+ -1,
1834
+ -1,
1835
+ -1,
1836
+ -1,
1837
+ -1,
1838
+ -1,
1839
+ -1,
1840
+ -1,
1841
+ 0,
1842
+ 1,
1843
+ 2,
1844
+ 3,
1845
+ 4,
1846
+ 5,
1847
+ 6,
1848
+ 7,
1849
+ 8,
1850
+ 9,
1851
+ -1,
1852
+ -1,
1853
+ -1,
1854
+ -1,
1855
+ -1,
1856
+ -1,
1857
+ -1,
1858
+ 10,
1859
+ 11,
1860
+ 12,
1861
+ 13,
1862
+ 14,
1863
+ 15,
1864
+ -1,
1865
+ -1,
1866
+ -1,
1867
+ -1,
1868
+ -1,
1869
+ -1,
1870
+ -1,
1871
+ -1,
1872
+ -1,
1873
+ -1,
1874
+ -1,
1875
+ -1,
1876
+ -1,
1877
+ -1,
1878
+ -1,
1879
+ -1,
1880
+ -1,
1881
+ -1,
1882
+ -1,
1883
+ -1,
1884
+ -1,
1885
+ -1,
1886
+ -1,
1887
+ -1,
1888
+ -1,
1889
+ -1,
1890
+ 10,
1891
+ 11,
1892
+ 12,
1893
+ 13,
1894
+ 14,
1895
+ 15,
1896
+ -1
1897
+ ];
1898
+ function isWs(b) {
1899
+ return b === 32 || b === 9 || b === 10 || b === 13 || b === 12 || b === 0;
1900
+ }
1901
+ function decode(bytes) {
1902
+ if (!(bytes instanceof Uint8Array))
1903
+ throw new ParseError("pdf/asciiHex/bad-input", "ASCIIHexDecode expects Uint8Array");
1904
+ const out = [];
1905
+ let pending = -1;
1906
+ for (let i = 0;i < bytes.length; i++) {
1907
+ const b = bytes[i];
1908
+ if (b === 62)
1909
+ break;
1910
+ if (isWs(b))
1911
+ continue;
1912
+ const v = b < HEX_LO.length ? HEX_LO[b] : -1;
1913
+ if (v < 0)
1914
+ throw new ParseError("pdf/asciiHex/bad-digit", "invalid hex digit", { context: { offset: i, byte: b } });
1915
+ if (pending < 0)
1916
+ pending = v;
1917
+ else {
1918
+ out.push(pending << 4 | v);
1919
+ pending = -1;
1920
+ }
1921
+ }
1922
+ if (pending >= 0)
1923
+ out.push(pending << 4);
1924
+ return Uint8Array.from(out);
1925
+ }
1926
+ function encode(bytes) {
1927
+ if (!(bytes instanceof Uint8Array))
1928
+ throw new ParseError("pdf/asciiHex/bad-input", "ASCIIHexEncode expects Uint8Array");
1929
+ const H = "0123456789ABCDEF";
1930
+ let s = "";
1931
+ for (let i = 0;i < bytes.length; i++) {
1932
+ if (i > 0 && (i & 31) === 0)
1933
+ s += `
1934
+ `;
1935
+ const b = bytes[i];
1936
+ s += H[b >> 4] + H[b & 15];
1937
+ }
1938
+ s += ">";
1939
+ return new TextEncoder().encode(s);
1940
+ }
1941
+ return { decode, encode };
1942
+ } });
1943
+ __register({ name: "pdfAscii85", dependencies: ["pdfErrors"], factory: function(errors) {
1944
+ const { ParseError } = errors;
1945
+ function isWs(b) {
1946
+ return b === 32 || b === 9 || b === 10 || b === 13 || b === 12 || b === 0;
1947
+ }
1948
+ function decode(bytes) {
1949
+ if (!(bytes instanceof Uint8Array))
1950
+ throw new ParseError("pdf/ascii85/bad-input", "ASCII85Decode expects Uint8Array");
1951
+ const out = [];
1952
+ let group = 0, count = 0;
1953
+ for (let i = 0;i < bytes.length; i++) {
1954
+ const b = bytes[i];
1955
+ if (isWs(b))
1956
+ continue;
1957
+ if (b === 126) {
1958
+ if (i + 1 < bytes.length && bytes[i + 1] === 62)
1959
+ break;
1960
+ throw new ParseError("pdf/ascii85/bad-eod", "~ not followed by >", { context: { offset: i } });
1961
+ }
1962
+ if (b === 122) {
1963
+ if (count !== 0)
1964
+ throw new ParseError("pdf/ascii85/bad-z", "z must appear at group boundary", { context: { offset: i } });
1965
+ out.push(0, 0, 0, 0);
1966
+ continue;
1967
+ }
1968
+ if (b < 33 || b > 117)
1969
+ throw new ParseError("pdf/ascii85/bad-digit", "character outside ! .. u", { context: { offset: i, byte: b } });
1970
+ group = group * 85 + (b - 33);
1971
+ count++;
1972
+ if (count === 5) {
1973
+ out.push(group >>> 24 & 255, group >>> 16 & 255, group >>> 8 & 255, group & 255);
1974
+ group = 0;
1975
+ count = 0;
1976
+ }
1977
+ }
1978
+ if (count > 0) {
1979
+ for (let k = count;k < 5; k++)
1980
+ group = group * 85 + 84;
1981
+ const decoded = [
1982
+ group >>> 24 & 255,
1983
+ group >>> 16 & 255,
1984
+ group >>> 8 & 255,
1985
+ group & 255
1986
+ ];
1987
+ for (let k = 0;k < count - 1; k++)
1988
+ out.push(decoded[k]);
1989
+ }
1990
+ return Uint8Array.from(out);
1991
+ }
1992
+ function encode(bytes) {
1993
+ if (!(bytes instanceof Uint8Array))
1994
+ throw new ParseError("pdf/ascii85/bad-input", "ASCII85Encode expects Uint8Array");
1995
+ const chars = [];
1996
+ let i = 0;
1997
+ while (i + 4 <= bytes.length) {
1998
+ const v = bytes[i] * 16777216 + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3];
1999
+ if (v === 0)
2000
+ chars.push(122);
2001
+ else {
2002
+ const g = [0, 0, 0, 0, 0];
2003
+ let n = v;
2004
+ for (let k = 4;k >= 0; k--) {
2005
+ g[k] = n % 85 + 33;
2006
+ n = Math.floor(n / 85);
2007
+ }
2008
+ chars.push(g[0], g[1], g[2], g[3], g[4]);
2009
+ }
2010
+ i += 4;
2011
+ }
2012
+ const rem = bytes.length - i;
2013
+ if (rem > 0) {
2014
+ const padded = new Uint8Array(4);
2015
+ padded.set(bytes.subarray(i));
2016
+ const v = padded[0] * 16777216 + (padded[1] << 16) + (padded[2] << 8) + padded[3], g = [0, 0, 0, 0, 0];
2017
+ let n = v;
2018
+ for (let k = 4;k >= 0; k--) {
2019
+ g[k] = n % 85 + 33;
2020
+ n = Math.floor(n / 85);
2021
+ }
2022
+ for (let k = 0;k < rem + 1; k++)
2023
+ chars.push(g[k]);
2024
+ }
2025
+ chars.push(126, 62);
2026
+ return Uint8Array.from(chars);
2027
+ }
2028
+ return { decode, encode };
2029
+ } });
2030
+ __register({ name: "pdfRunLength", dependencies: ["pdfErrors"], factory: function(errors) {
2031
+ const { ParseError } = errors;
2032
+ function decode(bytes) {
2033
+ if (!(bytes instanceof Uint8Array))
2034
+ throw new ParseError("pdf/runLength/bad-input", "RunLengthDecode expects Uint8Array");
2035
+ const out = [];
2036
+ let i = 0;
2037
+ while (i < bytes.length) {
2038
+ const n = bytes[i++];
2039
+ if (n === 128)
2040
+ break;
2041
+ if (n < 128) {
2042
+ const count = n + 1;
2043
+ if (i + count > bytes.length)
2044
+ throw new ParseError("pdf/runLength/truncated-literal", "truncated literal run", { context: { offset: i - 1, want: count, have: bytes.length - i } });
2045
+ for (let k = 0;k < count; k++)
2046
+ out.push(bytes[i + k]);
2047
+ i += count;
2048
+ } else {
2049
+ if (i >= bytes.length)
2050
+ throw new ParseError("pdf/runLength/truncated-repeat", "truncated repeat run", { context: { offset: i - 1 } });
2051
+ const v = bytes[i++], count = 257 - n;
2052
+ for (let k = 0;k < count; k++)
2053
+ out.push(v);
2054
+ }
2055
+ }
2056
+ return Uint8Array.from(out);
2057
+ }
2058
+ function encode(bytes) {
2059
+ if (!(bytes instanceof Uint8Array))
2060
+ throw new ParseError("pdf/runLength/bad-input", "RunLengthEncode expects Uint8Array");
2061
+ const out = [];
2062
+ let i = 0;
2063
+ while (i < bytes.length) {
2064
+ const v = bytes[i];
2065
+ let runLen = 1;
2066
+ while (runLen < 128 && i + runLen < bytes.length && bytes[i + runLen] === v)
2067
+ runLen++;
2068
+ if (runLen >= 3) {
2069
+ out.push(257 - runLen, v);
2070
+ i += runLen;
2071
+ continue;
2072
+ }
2073
+ let litStart = i, litLen = 0;
2074
+ while (litLen < 128 && i < bytes.length) {
2075
+ let look = 1;
2076
+ while (look < 3 && i + look < bytes.length && bytes[i + look] === bytes[i])
2077
+ look++;
2078
+ if (look >= 3 && litLen > 0)
2079
+ break;
2080
+ i++;
2081
+ litLen++;
2082
+ }
2083
+ out.push(litLen - 1);
2084
+ for (let k = 0;k < litLen; k++)
2085
+ out.push(bytes[litStart + k]);
2086
+ }
2087
+ out.push(128);
2088
+ return Uint8Array.from(out);
2089
+ }
2090
+ return { decode, encode };
2091
+ } });
2092
+ __register({ name: "pdfFilterDispatch", dependencies: ["pdfErrors","pdfFlate","pdfAsciiHex","pdfAscii85","pdfRunLength"], factory: function(errors, flate, asciiHex, ascii85, runLength) {
2093
+ const { ParseError } = errors;
2094
+ function isType(node, kind) {
2095
+ return !!(node && node.type === kind);
2096
+ }
2097
+ const ABBREV = {
2098
+ Fl: "FlateDecode",
2099
+ AHx: "ASCIIHexDecode",
2100
+ A85: "ASCII85Decode",
2101
+ RL: "RunLengthDecode",
2102
+ LZW: "LZWDecode",
2103
+ DCT: "DCTDecode",
2104
+ JPX: "JPXDecode",
2105
+ CCF: "CCITTFaxDecode"
2106
+ };
2107
+ function resolveAbbrev(name) {
2108
+ return ABBREV[name] || name;
2109
+ }
2110
+ function passthrough() {
2111
+ return {
2112
+ decode(bytes) {
2113
+ return bytes;
2114
+ },
2115
+ encode(bytes) {
2116
+ return bytes;
2117
+ }
2118
+ };
2119
+ }
2120
+ function normalizeFilterList(filterEntry) {
2121
+ if (!filterEntry)
2122
+ return [];
2123
+ if (filterEntry.type === "name")
2124
+ return [resolveAbbrev(filterEntry.value)];
2125
+ if (filterEntry.type === "array") {
2126
+ const out = [];
2127
+ for (const it of filterEntry.items) {
2128
+ if (it.type !== "name")
2129
+ throw new ParseError("pdf/filter/non-name", "/Filter array entries must be names", { context: { kind: it.type } });
2130
+ out.push(resolveAbbrev(it.value));
2131
+ }
2132
+ return out;
2133
+ }
2134
+ throw new ParseError("pdf/filter/bad-type", "/Filter must be a name or array of names", { context: { type: filterEntry.type } });
2135
+ }
2136
+ function applyDecodeChain(bytes, filters, params, decoders) {
2137
+ let cur = bytes;
2138
+ for (let i = 0;i < filters.length; i++) {
2139
+ const name = filters[i], p = params ? params[i] || null : null, dec = decoders[name];
2140
+ if (!dec)
2141
+ throw new ParseError("pdf/filter/unsupported", `filter "${name}" not registered`, { context: { name, available: Object.keys(decoders) } });
2142
+ cur = dec.decode(cur, p);
2143
+ }
2144
+ return cur;
2145
+ }
2146
+ function applyEncodeChain(bytes, filters, params, decoders) {
2147
+ let cur = bytes;
2148
+ for (let i = 0;i < filters.length; i++) {
2149
+ const name = filters[i], p = params ? params[i] || null : null, enc = decoders[name];
2150
+ if (!enc || typeof enc.encode !== "function")
2151
+ throw new ParseError("pdf/filter/no-encoder", `filter "${name}" has no encoder`, { context: { name } });
2152
+ cur = enc.encode(cur, p);
2153
+ }
2154
+ return cur;
2155
+ }
2156
+ function plainParams(dictNode) {
2157
+ const entries = dictNode.entries || {}, out = {};
2158
+ for (const key of Object.keys(entries)) {
2159
+ const v = entries[key];
2160
+ out[key] = v ? v.value : void 0;
2161
+ }
2162
+ return out;
2163
+ }
2164
+ function decodeParmsList(entry, count) {
2165
+ if (!entry)
2166
+ return null;
2167
+ if (entry.type === "null")
2168
+ return null;
2169
+ if (entry.type === "dict") {
2170
+ const arr = Array(count).fill(null);
2171
+ if (count > 0)
2172
+ arr[0] = plainParams(entry);
2173
+ return arr;
2174
+ }
2175
+ if (entry.type === "array")
2176
+ return entry.items.map((it) => it.type === "dict" ? plainParams(it) : null);
2177
+ throw new ParseError("pdf/filter/bad-decodeparms", "/DecodeParms must be a dict, array, or null", { context: { type: entry.type } });
2178
+ }
2179
+ function decodeStream(streamObj, decoders) {
2180
+ if (!isType(streamObj, "stream"))
2181
+ throw new ParseError("pdf/filter/not-stream", "decodeStream expects a stream object");
2182
+ const dict = streamObj.dict, filters = normalizeFilterList(dict.entries.Filter), params = decodeParmsList(dict.entries.DecodeParms, filters.length);
2183
+ return applyDecodeChain(streamObj.raw, filters, params, decoders);
2184
+ }
2185
+ const decoders = {
2186
+ FlateDecode: flate,
2187
+ ASCIIHexDecode: asciiHex,
2188
+ ASCII85Decode: ascii85,
2189
+ RunLengthDecode: runLength,
2190
+ DCTDecode: passthrough(),
2191
+ JPXDecode: passthrough(),
2192
+ Crypt: passthrough()
2193
+ };
2194
+ function decode(streamObj) {
2195
+ return decodeStream(streamObj, decoders);
2196
+ }
2197
+ function decodeChain(bytes, filters, params) {
2198
+ return applyDecodeChain(bytes, filters, params, decoders);
2199
+ }
2200
+ function encodeChain(bytes, filters, params) {
2201
+ return applyEncodeChain(bytes, filters, params, decoders);
2202
+ }
2203
+ function register(name, impl) {
2204
+ decoders[name] = impl;
2205
+ }
2206
+ function names() {
2207
+ return Object.keys(decoders);
2208
+ }
2209
+ return {
2210
+ decode,
2211
+ decodeChain,
2212
+ encodeChain,
2213
+ register,
2214
+ names,
2215
+ decoders,
2216
+ normalizeFilterList,
2217
+ applyDecodeChain,
2218
+ applyEncodeChain,
2219
+ decodeStream
2220
+ };
2221
+ } });
2222
+ __register({ name: "pdfDocument", dependencies: ["pdfErrors","pdfTokenizer","pdfParser","pdfXref","pdfTrailer","pdfCatalog","pdfPage","pdfPages","pdfCrossRefStream","pdfObjStream","pdfFilterDispatch"], factory: function(errors, tokenizerMod, parserMod, xrefMod, trailerMod, catalogMod, pageMod, pagesMod, crossRefStreamMod, objStreamMod, filterDispatchMod) {
2223
+ const { ParseError } = errors, tokenize = tokenizerMod && tokenizerMod.tokenize, parseIndirect = parserMod && parserMod.parseIndirect, locateStartXref = xrefMod && xrefMod.locateStartXref, readStartXref = xrefMod && xrefMod.readStartXref, parseXrefTable = xrefMod && xrefMod.parseXrefTable, parseTrailerDict = xrefMod && xrefMod.parseTrailerDict, typeTrailer = trailerMod && trailerMod.typeTrailer, typeCatalog = catalogMod && catalogMod.typeCatalog, typePage = pageMod && pageMod.typePage, walkPageTree = pagesMod && pagesMod.walkPageTree, HEADER_PREFIX = new Uint8Array([37, 80, 68, 70, 45]), XREF_KEYWORD = new Uint8Array([120, 114, 101, 102]), PDF_NULL = Object.freeze({ type: "null" }), SECTION_LOCAL_KEYS = new Set([
2224
+ "Prev",
2225
+ "XRefStm",
2226
+ "Type",
2227
+ "W",
2228
+ "Index",
2229
+ "Length",
2230
+ "Filter",
2231
+ "DecodeParms",
2232
+ "F",
2233
+ "FFilter",
2234
+ "FDecodeParms",
2235
+ "DL"
2236
+ ]), EMPTY_PAGES_NODE = Object.freeze({
2237
+ type: "dict",
2238
+ entries: Object.freeze({
2239
+ Type: Object.freeze({ type: "name", value: "Pages" }),
2240
+ Kids: Object.freeze({ type: "array", items: Object.freeze([]) })
2241
+ })
2242
+ });
2243
+ function skipWhitespace(bytes, at) {
2244
+ let p = at < 0 ? 0 : at;
2245
+ while (p < bytes.length) {
2246
+ const b = bytes[p];
2247
+ if (b === 0 || b === 9 || b === 10 || b === 12 || b === 13 || b === 32) {
2248
+ p++;
2249
+ continue;
2250
+ }
2251
+ break;
2252
+ }
2253
+ return p;
2254
+ }
2255
+ function startsXrefTable(bytes, at) {
2256
+ for (let k = 0;k < XREF_KEYWORD.length; k++)
2257
+ if (bytes[at + k] !== XREF_KEYWORD[k])
2258
+ return !1;
2259
+ return !0;
2260
+ }
2261
+ function refuseIndirectLength(ref) {
2262
+ throw new ParseError("pdf/document/xrefstm-indirect-length", "a cross-reference stream may not use an indirect /Length", { context: { num: ref && ref.num, gen: ref && ref.gen } });
2263
+ }
2264
+ function requireStreamWiring(offset) {
2265
+ if (!crossRefStreamMod || !objStreamMod || !filterDispatchMod)
2266
+ throw new ParseError("pdf/document/xref-stream-unwired", "this pdfDocument was built without pdfCrossRefStream, " + "pdfObjStream and pdfFilterDispatch \u2014 cross-reference " + "streams and object streams cannot be read", { context: { offset } });
2267
+ }
2268
+ function readXrefStreamSection(bytes, at) {
2269
+ requireStreamWiring(at);
2270
+ const tok = tokenize(bytes, { start: at }), streamObj = parseIndirect(tok, refuseIndirectLength).value, typeEntry = streamObj && streamObj.dict && streamObj.dict.entries && streamObj.dict.entries.Type;
2271
+ if (!streamObj || streamObj.type !== "stream" || !typeEntry || typeEntry.type !== "name" || typeEntry.value !== "XRef")
2272
+ throw new ParseError("pdf/document/bad-xref-section", "neither an xref table nor a cross-reference stream at startxref", { context: { offset: at } });
2273
+ const decoded = filterDispatchMod.decode(streamObj);
2274
+ return { entries: crossRefStreamMod.parseCrossRefStream(decoded, streamObj.dict).entries, dict: streamObj.dict };
2275
+ }
2276
+ function mergeTrailerDicts(dicts) {
2277
+ if (dicts.length === 1)
2278
+ return dicts[0];
2279
+ for (const d of dicts)
2280
+ if (!d || d.type !== "dict")
2281
+ return d;
2282
+ const entries = { ...dicts[0].entries };
2283
+ for (let i = 1;i < dicts.length; i++)
2284
+ for (const k of Object.keys(dicts[i].entries)) {
2285
+ if (SECTION_LOCAL_KEYS.has(k))
2286
+ continue;
2287
+ if (!(k in entries))
2288
+ entries[k] = dicts[i].entries[k];
2289
+ }
2290
+ return { ...dicts[0], entries };
2291
+ }
2292
+ function readHeader(bytes) {
2293
+ if (bytes.length < 8)
2294
+ throw new ParseError("pdf/document/short", "input too short to contain a PDF header", { context: { length: bytes.length } });
2295
+ let off = -1;
2296
+ const maxScan = Math.min(bytes.length - 5, 1024);
2297
+ outer:
2298
+ for (let i = 0;i <= maxScan; i++) {
2299
+ for (let k = 0;k < 5; k++)
2300
+ if (bytes[i + k] !== HEADER_PREFIX[k])
2301
+ continue outer;
2302
+ off = i;
2303
+ break;
2304
+ }
2305
+ if (off < 0)
2306
+ throw new ParseError("pdf/document/bad-header", "no %PDF- header found in first 1024 bytes");
2307
+ let p = off + 5;
2308
+ const digits = [];
2309
+ while (p < bytes.length) {
2310
+ const b = bytes[p];
2311
+ if (b === 10 || b === 13)
2312
+ break;
2313
+ digits.push(b);
2314
+ p++;
2315
+ }
2316
+ const version = new TextDecoder("latin1").decode(Uint8Array.from(digits));
2317
+ if (p < bytes.length && bytes[p] === 13)
2318
+ p++;
2319
+ if (p < bytes.length && bytes[p] === 10)
2320
+ p++;
2321
+ return { version, end: p };
2322
+ }
2323
+ function readDocument(bytes, opts = {}) {
2324
+ if (!(bytes instanceof Uint8Array))
2325
+ throw new ParseError("pdf/document/bad-input", "readDocument expects a Uint8Array", { context: { typeof: typeof bytes } });
2326
+ const { version, end: headerEnd } = readHeader(bytes), sxAt = locateStartXref(bytes);
2327
+ if (sxAt < 0)
2328
+ throw new ParseError("pdf/document/no-startxref", "startxref keyword not found near EOF");
2329
+ const xrefAt = readStartXref(bytes, sxAt), xref = { entries: {}, sections: [] }, losses = [], trailerDicts = [];
2330
+ let cursor = xrefAt;
2331
+ const seenSections = new Set;
2332
+ function mergeSection(at, kind, entries) {
2333
+ xref.sections.push({ at, kind, entries });
2334
+ for (const k of Object.keys(entries))
2335
+ if (!(k in xref.entries))
2336
+ xref.entries[k] = entries[k];
2337
+ }
2338
+ for (let safety = 0;safety < 32 && cursor >= 0; safety++) {
2339
+ if (seenSections.has(cursor))
2340
+ break;
2341
+ seenSections.add(cursor);
2342
+ let dict;
2343
+ if (startsXrefTable(bytes, skipWhitespace(bytes, cursor))) {
2344
+ const section = parseXrefTable(bytes, cursor);
2345
+ mergeSection(cursor, "table", section.entries);
2346
+ dict = parseTrailerDict(bytes, section.end).dict;
2347
+ const stmAt = dict && dict.entries && dict.entries.XRefStm;
2348
+ if (stmAt && stmAt.type === "int" && stmAt.value >= 0 && stmAt.value < bytes.length) {
2349
+ const hybrid = readXrefStreamSection(bytes, stmAt.value);
2350
+ mergeSection(stmAt.value, "stream", hybrid.entries);
2351
+ }
2352
+ } else {
2353
+ const section = readXrefStreamSection(bytes, cursor);
2354
+ mergeSection(cursor, "stream", section.entries);
2355
+ dict = section.dict;
2356
+ }
2357
+ trailerDicts.push(dict);
2358
+ const prev = dict && dict.type === "dict" && dict.entries && dict.entries.Prev;
2359
+ if (prev && prev.type === "int" && prev.value >= 0 && prev.value !== cursor)
2360
+ cursor = prev.value;
2361
+ else
2362
+ break;
2363
+ }
2364
+ if (trailerDicts.length === 0)
2365
+ throw new ParseError("pdf/document/no-trailer", "no usable trailer dictionary found");
2366
+ const trailerTyped = typeTrailer(mergeTrailerDicts(trailerDicts));
2367
+ if (trailerTyped.encrypt && opts.allowEncrypted !== !0)
2368
+ throw new ParseError("pdf/document/encrypted", "document is encrypted (trailer /Encrypt present) \u2014 " + "no decrypt path is composed for readDocument; pass { allowEncrypted: true } to read the raw ciphertext container", { context: { encrypt: trailerTyped.encrypt } });
2369
+ const indirects = new Map, lossKeys = new Set, freeKeys = new Set, objStmMembers = new Map;
2370
+ function resolve(ref) {
2371
+ if (!ref || ref.type !== "ref")
2372
+ return ref;
2373
+ return resolveByKey(ref.num, ref.gen);
2374
+ }
2375
+ function resolveByKey(num, gen) {
2376
+ const key = num + ":" + gen;
2377
+ if (indirects.has(key))
2378
+ return indirects.get(key).value;
2379
+ let entry = xref.entries[num];
2380
+ if (!entry)
2381
+ throw new ParseError("pdf/document/missing-xref", `object ${num} ${gen} not in xref`, { context: { num, gen } });
2382
+ if (entry.free) {
2383
+ entry = resolveFreeEntry(num, gen);
2384
+ if (!entry)
2385
+ return PDF_NULL;
2386
+ }
2387
+ if (entry.type === 2) {
2388
+ const value = resolveCompressed(num, gen, entry);
2389
+ indirects.set(key, { value, offset: 0, objStm: entry.objStm });
2390
+ return value;
2391
+ }
2392
+ const offset = entry.offset;
2393
+ if (offset <= 0 || offset >= bytes.length)
2394
+ throw new ParseError("pdf/document/bad-offset", `object ${num} ${gen} xref offset out of range`, { context: { num, gen, offset, total: bytes.length } });
2395
+ const tok = tokenize(bytes, { start: offset }), def = parseIndirect(tok, resolve);
2396
+ if (def.num !== num || def.gen !== gen)
2397
+ throw new ParseError("pdf/document/xref-mismatch", "xref points to a different object", { context: { expected: { num, gen }, found: { num: def.num, gen: def.gen } } });
2398
+ indirects.set(key, { value: def.value, offset });
2399
+ return def.value;
2400
+ }
2401
+ function resolveFreeEntry(num, gen) {
2402
+ const key = num + ":" + gen;
2403
+ for (const section of xref.sections) {
2404
+ const e = section.entries[num];
2405
+ if (e && !e.free) {
2406
+ recordLoss("fallback:" + key, {
2407
+ code: "pdf/document/free-entry-fallback",
2408
+ message: `object ${num} is free in the newest xref section; resolved through an older section that defines it`,
2409
+ context: { num, gen, section: { at: section.at, kind: section.kind } }
2410
+ });
2411
+ return e;
2412
+ }
2413
+ }
2414
+ freeKeys.add(key);
2415
+ recordLoss("free:" + key, {
2416
+ code: "pdf/document/free-object",
2417
+ message: `object ${num} is free in every xref section; read as null`,
2418
+ context: { num, gen }
2419
+ });
2420
+ return null;
2421
+ }
2422
+ function recordLoss(dedupeKey, loss) {
2423
+ if (lossKeys.has(dedupeKey))
2424
+ return;
2425
+ lossKeys.add(dedupeKey);
2426
+ losses.push(loss);
2427
+ }
2428
+ function resolveCompressed(num, gen, entry) {
2429
+ if (trailerTyped && trailerTyped.encrypt)
2430
+ throw new ParseError("pdf/document/objstm-encrypted", "object streams of an encrypted document cannot be " + "read \u2014 no decrypt path is composed for readDocument", { context: { num, gen, objStm: entry.objStm } });
2431
+ const containerNum = entry.objStm;
2432
+ let members = objStmMembers.get(containerNum);
2433
+ if (!members) {
2434
+ requireStreamWiring(0);
2435
+ const containerEntry = xref.entries[containerNum];
2436
+ if (containerEntry && containerEntry.type === 2)
2437
+ throw new ParseError("pdf/document/objstm-nested", `object stream ${containerNum} is itself stored in an object stream`, { context: { num, objStm: containerNum } });
2438
+ const container = resolveByKey(containerNum, 0);
2439
+ if (!container || container.type !== "stream")
2440
+ throw new ParseError("pdf/document/objstm-not-stream", `object ${containerNum} is not a stream and cannot hold compressed objects`, { context: {
2441
+ num,
2442
+ objStm: containerNum,
2443
+ type: container && container.type
2444
+ } });
2445
+ members = objStreamMod.parseObjectStream(filterDispatchMod.decode(container), container.dict);
2446
+ objStmMembers.set(containerNum, members);
2447
+ }
2448
+ const member = members[entry.index];
2449
+ if (!member || member.num !== num)
2450
+ throw new ParseError("pdf/document/objstm-mismatch", "object stream member does not carry the expected object number", { context: {
2451
+ num,
2452
+ objStm: containerNum,
2453
+ index: entry.index,
2454
+ found: member ? member.num : null
2455
+ } });
2456
+ return member.value;
2457
+ }
2458
+ const rootRef = trailerTyped.root, catalogDict = resolve({ type: "ref", num: rootRef.num, gen: rootRef.gen });
2459
+ if (freeKeys.has(rootRef.num + ":" + rootRef.gen))
2460
+ throw new ParseError("pdf/document/free-object", `object ${rootRef.num} is free`, { context: { num: rootRef.num, gen: rootRef.gen, role: "catalog" } });
2461
+ const catalog = typeCatalog(catalogDict);
2462
+ function resolvePageTreeNode(ref) {
2463
+ const value = resolve(ref);
2464
+ if (ref && ref.type === "ref" && freeKeys.has(ref.num + ":" + ref.gen))
2465
+ return EMPTY_PAGES_NODE;
2466
+ return value;
2467
+ }
2468
+ const pages = walkPageTree(catalog.pages, resolvePageTreeNode).map((r) => typePage(resolve({ type: "ref", num: r.num, gen: r.gen })));
2469
+ return {
2470
+ version,
2471
+ catalog,
2472
+ pages,
2473
+ trailer: trailerTyped,
2474
+ xref,
2475
+ losses,
2476
+ _raw: {
2477
+ resolve,
2478
+ bytes,
2479
+ headerEnd,
2480
+ indirects
2481
+ }
2482
+ };
2483
+ }
2484
+ return { readDocument, readHeader };
2485
+ } });
2486
+ __register({ name: "pdfWriter", dependencies: ["pdfErrors","pdfSerializer"], factory: function(errors, serializerMod) {
2487
+ const { RenderError } = errors, serializeIndirect = serializerMod.serializeIndirect, te = new TextEncoder;
2488
+ function pad10(n) {
2489
+ return String(n).padStart(10, "0");
2490
+ }
2491
+ function hexLit(bytes) {
2492
+ let s = "<";
2493
+ for (let i = 0;i < bytes.length; i++)
2494
+ s += "0123456789ABCDEF"[bytes[i] >> 4] + "0123456789ABCDEF"[bytes[i] & 15];
2495
+ return s + ">";
2496
+ }
2497
+ function concat(arrays) {
2498
+ let n = 0;
2499
+ for (const a of arrays)
2500
+ n += a.length;
2501
+ const out = new Uint8Array(n);
2502
+ let o = 0;
2503
+ for (const a of arrays) {
2504
+ out.set(a, o);
2505
+ o += a.length;
2506
+ }
2507
+ return out;
2508
+ }
2509
+ function validateIndirects(list) {
2510
+ let prev = -1;
2511
+ for (const it of list) {
2512
+ if (!it || !Number.isFinite(it.num) || it.num < 1)
2513
+ throw new RenderError("pdf/writer/bad-indirect", "each indirect requires num >= 1", { context: { item: it } });
2514
+ if (it.num === prev)
2515
+ throw new RenderError("pdf/writer/duplicate-num", "duplicate object number", { context: { num: it.num } });
2516
+ prev = it.num;
2517
+ }
2518
+ }
2519
+ function buildXref(maxNum, offsets) {
2520
+ let s = `xref
2521
+ 0 ${maxNum + 1}
2522
+ `;
2523
+ s += `0000000000 65535 f
2524
+ `;
2525
+ for (let n = 1;n <= maxNum; n++)
2526
+ if (offsets.has(n))
2527
+ s += pad10(offsets.get(n)) + ` 00000 n
2528
+ `;
2529
+ else
2530
+ s += `0000000000 00000 f
2531
+ `;
2532
+ return te.encode(s);
2533
+ }
2534
+ function buildTrailer(opts) {
2535
+ const parts = [`trailer
2536
+ << /Size ${opts.size}`];
2537
+ parts.push(` /Root ${opts.root.num} ${opts.root.gen | 0} R`);
2538
+ if (opts.info)
2539
+ parts.push(` /Info ${opts.info.num} ${opts.info.gen | 0} R`);
2540
+ if (opts.id) {
2541
+ parts.push(" /ID [");
2542
+ parts.push(hexLit(opts.id[0]));
2543
+ parts.push(hexLit(opts.id[1]));
2544
+ parts.push("]");
2545
+ }
2546
+ parts.push(` >>
2547
+ `);
2548
+ parts.push(`startxref
2549
+ ${opts.xrefOffset}
2550
+ %%EOF
2551
+ `);
2552
+ return te.encode(parts.join(""));
2553
+ }
2554
+ function writeDocument(opts) {
2555
+ if (!opts || !Array.isArray(opts.indirects))
2556
+ throw new RenderError("pdf/writer/bad-input", "writeDocument expects { indirects: [...] }");
2557
+ if (!opts.root || !Number.isFinite(opts.root.num))
2558
+ throw new RenderError("pdf/writer/no-root", "writeDocument requires opts.root");
2559
+ const version = opts.version || "2.0";
2560
+ if (!/^\d\.\d$/.test(version))
2561
+ throw new RenderError("pdf/writer/bad-version", 'version must look like "x.y"', { context: { version } });
2562
+ const indirects = opts.indirects.slice().sort((a, b) => a.num - b.num);
2563
+ validateIndirects(indirects);
2564
+ const parts = [];
2565
+ let cursor = 0;
2566
+ const offsets = new Map;
2567
+ function push(u8) {
2568
+ parts.push(u8);
2569
+ cursor += u8.length;
2570
+ }
2571
+ push(te.encode(`%PDF-${version}
2572
+ `));
2573
+ push(new Uint8Array([37, 226, 227, 207, 211, 10]));
2574
+ const maxNum = indirects.length > 0 ? indirects[indirects.length - 1].num : 0;
2575
+ for (const { num, gen, value } of indirects) {
2576
+ offsets.set(num, cursor);
2577
+ push(serializeIndirect(num, gen, value));
2578
+ }
2579
+ const xrefOffset = cursor;
2580
+ push(buildXref(maxNum, offsets));
2581
+ const size = maxNum + 1;
2582
+ push(buildTrailer({
2583
+ size,
2584
+ root: opts.root,
2585
+ info: opts.info,
2586
+ id: opts.id,
2587
+ xrefOffset
2588
+ }));
2589
+ return concat(parts);
2590
+ }
2591
+ function assembleIndirects(model, opts) {
2592
+ if (!model || !model._raw || typeof model._raw.resolve !== "function")
2593
+ throw new RenderError("pdf/writer/bad-model", "assembleIndirects requires a model produced by pdf.read()");
2594
+ const skipped = [];
2595
+ for (const k of Object.keys(model.xref.entries)) {
2596
+ const e = model.xref.entries[k];
2597
+ if (e.free)
2598
+ continue;
2599
+ try {
2600
+ model._raw.resolve({ type: "ref", num: Number(k), gen: e.gen });
2601
+ } catch (err) {
2602
+ skipped.push({
2603
+ num: Number(k),
2604
+ gen: e.gen,
2605
+ code: errors.isPdfError(err) ? err.code : "unknown"
2606
+ });
2607
+ }
2608
+ }
2609
+ if (skipped.length > 0 && opts && opts.strict === !0)
2610
+ throw new RenderError("pdf/writer/unresolvable-objects", `${skipped.length} object${skipped.length === 1 ? "" : "s"} could not be resolved and would be dropped`, { context: { objects: skipped } });
2611
+ const out = [];
2612
+ for (const [key, rec] of model._raw.indirects.entries()) {
2613
+ const [n, g] = key.split(":").map(Number);
2614
+ out.push({ num: n, gen: g, value: rec.value });
2615
+ }
2616
+ out.sort((a, b) => a.num - b.num);
2617
+ Object.defineProperty(out, "skippedObjects", {
2618
+ value: skipped,
2619
+ enumerable: !1,
2620
+ writable: !0,
2621
+ configurable: !0
2622
+ });
2623
+ return out;
2624
+ }
2625
+ return { writeDocument, assembleIndirects };
2626
+ } });
2627
+ __register({ name: "pdf", dependencies: ["pdfErrors","pdfShared","pdfTokenizer","pdfParserObj","pdfParser","pdfXref","pdfTrailer","pdfSerializer","pdfCatalog","pdfPages","pdfPage","pdfDocument","pdfWriter"], factory: function(errors, shared, tokenizer, parserObj, parser, xref, trailer, serializer, catalog, pages, page, docMod, writerMod) {
2628
+ const { ContractError } = errors, readDocument = docMod.readDocument, readHeader = docMod.readHeader, writeDocument = writerMod.writeDocument, assembleIndirects = writerMod.assembleIndirects, usedExtensions = new Set, api = {
2629
+ read(bytes, opts) {
2630
+ return readDocument(bytes, opts);
2631
+ },
2632
+ header(bytes) {
2633
+ return readHeader(bytes);
2634
+ },
2635
+ write(model, opts) {
2636
+ const o = opts && typeof opts === "object" ? opts : {};
2637
+ let skipped = [], bytes;
2638
+ if (model && model._raw && typeof model._raw.resolve === "function") {
2639
+ const indirects = assembleIndirects(model, o.strict === !0 ? { strict: !0 } : void 0);
2640
+ skipped = indirects.skippedObjects || [];
2641
+ bytes = writeDocument({
2642
+ indirects,
2643
+ root: model.catalog.pages ? { num: model.trailer.root.num, gen: model.trailer.root.gen } : model.trailer.root,
2644
+ info: model.trailer.info,
2645
+ id: model.trailer.id,
2646
+ version: "2.0"
2647
+ });
2648
+ } else
2649
+ bytes = writeDocument(model);
2650
+ if (skipped.length > 0 && typeof o.onSkipped === "function")
2651
+ o.onSkipped(skipped.slice());
2652
+ Object.defineProperty(bytes, "skippedObjects", {
2653
+ value: skipped,
2654
+ enumerable: !1,
2655
+ writable: !0,
2656
+ configurable: !0
2657
+ });
2658
+ return bytes;
2659
+ },
2660
+ use(ext) {
2661
+ if (!ext || typeof ext.name !== "string" || typeof ext.register !== "function")
2662
+ throw new ContractError("pdf/use/bad-extension", ".use() requires { name: string, register: function }", { context: { keys: ext && Object.keys(ext) } });
2663
+ if (usedExtensions.has(ext.name))
2664
+ return api;
2665
+ usedExtensions.add(ext.name);
2666
+ const next = ext.register(api, { usedExtensions });
2667
+ if (next && typeof next === "object") {
2668
+ for (const k of Object.keys(next))
2669
+ if (k !== "use")
2670
+ api[k] = next[k];
2671
+ }
2672
+ return api;
2673
+ },
2674
+ usedExtension(name) {
2675
+ return usedExtensions.has(name);
2676
+ }
2677
+ };
2678
+ return api;
2679
+ } });
2680
+
2681
+ const __core = __resolve("pdf");
2682
+ return __core;
2683
+ }
2684
+ };