docxmlater 11.0.10 → 12.1.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 (361) hide show
  1. package/README.md +53 -13
  2. package/dist/core/Document.d.ts +29 -3
  3. package/dist/core/Document.d.ts.map +1 -1
  4. package/dist/core/Document.js +733 -170
  5. package/dist/core/Document.js.map +1 -1
  6. package/dist/core/DocumentGenerator.d.ts +1 -0
  7. package/dist/core/DocumentGenerator.d.ts.map +1 -1
  8. package/dist/core/DocumentGenerator.js +77 -25
  9. package/dist/core/DocumentGenerator.js.map +1 -1
  10. package/dist/core/DocumentParser.d.ts +7 -3
  11. package/dist/core/DocumentParser.d.ts.map +1 -1
  12. package/dist/core/DocumentParser.js +427 -81
  13. package/dist/core/DocumentParser.js.map +1 -1
  14. package/dist/core/RelationshipManager.d.ts.map +1 -1
  15. package/dist/core/RelationshipManager.js +2 -2
  16. package/dist/core/RelationshipManager.js.map +1 -1
  17. package/dist/elements/Comment.d.ts +15 -1
  18. package/dist/elements/Comment.d.ts.map +1 -1
  19. package/dist/elements/Comment.js +67 -12
  20. package/dist/elements/Comment.js.map +1 -1
  21. package/dist/elements/CommentManager.d.ts +4 -0
  22. package/dist/elements/CommentManager.d.ts.map +1 -1
  23. package/dist/elements/CommentManager.js +74 -16
  24. package/dist/elements/CommentManager.js.map +1 -1
  25. package/dist/elements/EndnoteManager.d.ts.map +1 -1
  26. package/dist/elements/EndnoteManager.js.map +1 -1
  27. package/dist/elements/Field.d.ts +10 -1
  28. package/dist/elements/Field.d.ts.map +1 -1
  29. package/dist/elements/Field.js +76 -34
  30. package/dist/elements/Field.js.map +1 -1
  31. package/dist/elements/FieldHelpers.d.ts +1 -0
  32. package/dist/elements/FieldHelpers.d.ts.map +1 -1
  33. package/dist/elements/FieldHelpers.js +8 -4
  34. package/dist/elements/FieldHelpers.js.map +1 -1
  35. package/dist/elements/Footer.d.ts +3 -1
  36. package/dist/elements/Footer.d.ts.map +1 -1
  37. package/dist/elements/Footer.js +39 -53
  38. package/dist/elements/Footer.js.map +1 -1
  39. package/dist/elements/FootnoteManager.d.ts.map +1 -1
  40. package/dist/elements/FootnoteManager.js.map +1 -1
  41. package/dist/elements/Header.d.ts +3 -1
  42. package/dist/elements/Header.d.ts.map +1 -1
  43. package/dist/elements/Header.js +39 -53
  44. package/dist/elements/Header.js.map +1 -1
  45. package/dist/elements/HeaderFooterManager.d.ts +4 -2
  46. package/dist/elements/HeaderFooterManager.d.ts.map +1 -1
  47. package/dist/elements/HeaderFooterManager.js +36 -6
  48. package/dist/elements/HeaderFooterManager.js.map +1 -1
  49. package/dist/elements/Hyperlink.d.ts +6 -1
  50. package/dist/elements/Hyperlink.d.ts.map +1 -1
  51. package/dist/elements/Hyperlink.js +69 -44
  52. package/dist/elements/Hyperlink.js.map +1 -1
  53. package/dist/elements/Image.d.ts.map +1 -1
  54. package/dist/elements/Image.js +33 -6
  55. package/dist/elements/Image.js.map +1 -1
  56. package/dist/elements/ImageManager.d.ts +1 -0
  57. package/dist/elements/ImageManager.d.ts.map +1 -1
  58. package/dist/elements/ImageManager.js +11 -0
  59. package/dist/elements/ImageManager.js.map +1 -1
  60. package/dist/elements/Paragraph.d.ts +3 -0
  61. package/dist/elements/Paragraph.d.ts.map +1 -1
  62. package/dist/elements/Paragraph.js +91 -26
  63. package/dist/elements/Paragraph.js.map +1 -1
  64. package/dist/elements/Revision.d.ts +4 -0
  65. package/dist/elements/Revision.d.ts.map +1 -1
  66. package/dist/elements/Revision.js +369 -29
  67. package/dist/elements/Revision.js.map +1 -1
  68. package/dist/elements/Run.d.ts +1 -0
  69. package/dist/elements/Run.d.ts.map +1 -1
  70. package/dist/elements/Run.js +24 -4
  71. package/dist/elements/Run.js.map +1 -1
  72. package/dist/elements/Section.d.ts.map +1 -1
  73. package/dist/elements/Section.js +17 -7
  74. package/dist/elements/Section.js.map +1 -1
  75. package/dist/elements/Shape.d.ts.map +1 -1
  76. package/dist/elements/Shape.js +50 -42
  77. package/dist/elements/Shape.js.map +1 -1
  78. package/dist/elements/StructuredDocumentTag.d.ts +9 -1
  79. package/dist/elements/StructuredDocumentTag.d.ts.map +1 -1
  80. package/dist/elements/StructuredDocumentTag.js +46 -6
  81. package/dist/elements/StructuredDocumentTag.js.map +1 -1
  82. package/dist/elements/Table.d.ts +2 -0
  83. package/dist/elements/Table.d.ts.map +1 -1
  84. package/dist/elements/Table.js +90 -42
  85. package/dist/elements/Table.js.map +1 -1
  86. package/dist/elements/TableCell.d.ts +1 -0
  87. package/dist/elements/TableCell.d.ts.map +1 -1
  88. package/dist/elements/TableCell.js +32 -13
  89. package/dist/elements/TableCell.js.map +1 -1
  90. package/dist/elements/TableOfContents.d.ts.map +1 -1
  91. package/dist/elements/TableOfContents.js +5 -7
  92. package/dist/elements/TableOfContents.js.map +1 -1
  93. package/dist/elements/TableRow.d.ts +1 -0
  94. package/dist/elements/TableRow.d.ts.map +1 -1
  95. package/dist/elements/TableRow.js +16 -1
  96. package/dist/elements/TableRow.js.map +1 -1
  97. package/dist/elements/TextBox.d.ts.map +1 -1
  98. package/dist/elements/TextBox.js +55 -42
  99. package/dist/elements/TextBox.js.map +1 -1
  100. package/dist/esm/core/Document.js +735 -172
  101. package/dist/esm/core/Document.js.map +1 -1
  102. package/dist/esm/core/DocumentGenerator.js +77 -25
  103. package/dist/esm/core/DocumentGenerator.js.map +1 -1
  104. package/dist/esm/core/DocumentParser.js +427 -81
  105. package/dist/esm/core/DocumentParser.js.map +1 -1
  106. package/dist/esm/core/RelationshipManager.js +2 -2
  107. package/dist/esm/core/RelationshipManager.js.map +1 -1
  108. package/dist/esm/elements/Comment.js +67 -12
  109. package/dist/esm/elements/Comment.js.map +1 -1
  110. package/dist/esm/elements/CommentManager.js +74 -16
  111. package/dist/esm/elements/CommentManager.js.map +1 -1
  112. package/dist/esm/elements/EndnoteManager.js.map +1 -1
  113. package/dist/esm/elements/Field.js +77 -35
  114. package/dist/esm/elements/Field.js.map +1 -1
  115. package/dist/esm/elements/FieldHelpers.js +7 -4
  116. package/dist/esm/elements/FieldHelpers.js.map +1 -1
  117. package/dist/esm/elements/Footer.js +39 -53
  118. package/dist/esm/elements/Footer.js.map +1 -1
  119. package/dist/esm/elements/FootnoteManager.js.map +1 -1
  120. package/dist/esm/elements/Header.js +39 -53
  121. package/dist/esm/elements/Header.js.map +1 -1
  122. package/dist/esm/elements/HeaderFooterManager.js +36 -6
  123. package/dist/esm/elements/HeaderFooterManager.js.map +1 -1
  124. package/dist/esm/elements/Hyperlink.js +69 -44
  125. package/dist/esm/elements/Hyperlink.js.map +1 -1
  126. package/dist/esm/elements/Image.js +33 -6
  127. package/dist/esm/elements/Image.js.map +1 -1
  128. package/dist/esm/elements/ImageManager.js +11 -0
  129. package/dist/esm/elements/ImageManager.js.map +1 -1
  130. package/dist/esm/elements/Paragraph.js +91 -26
  131. package/dist/esm/elements/Paragraph.js.map +1 -1
  132. package/dist/esm/elements/Revision.js +369 -29
  133. package/dist/esm/elements/Revision.js.map +1 -1
  134. package/dist/esm/elements/Run.js +24 -4
  135. package/dist/esm/elements/Run.js.map +1 -1
  136. package/dist/esm/elements/Section.js +17 -7
  137. package/dist/esm/elements/Section.js.map +1 -1
  138. package/dist/esm/elements/Shape.js +50 -42
  139. package/dist/esm/elements/Shape.js.map +1 -1
  140. package/dist/esm/elements/StructuredDocumentTag.js +46 -6
  141. package/dist/esm/elements/StructuredDocumentTag.js.map +1 -1
  142. package/dist/esm/elements/Table.js +90 -42
  143. package/dist/esm/elements/Table.js.map +1 -1
  144. package/dist/esm/elements/TableCell.js +32 -13
  145. package/dist/esm/elements/TableCell.js.map +1 -1
  146. package/dist/esm/elements/TableOfContents.js +5 -7
  147. package/dist/esm/elements/TableOfContents.js.map +1 -1
  148. package/dist/esm/elements/TableRow.js +16 -1
  149. package/dist/esm/elements/TableRow.js.map +1 -1
  150. package/dist/esm/elements/TextBox.js +55 -42
  151. package/dist/esm/elements/TextBox.js.map +1 -1
  152. package/dist/esm/formatting/AbstractNumbering.js +1 -1
  153. package/dist/esm/formatting/AbstractNumbering.js.map +1 -1
  154. package/dist/esm/formatting/NumberingLevel.js +8 -6
  155. package/dist/esm/formatting/NumberingLevel.js.map +1 -1
  156. package/dist/esm/formatting/NumberingManager.js +16 -1
  157. package/dist/esm/formatting/NumberingManager.js.map +1 -1
  158. package/dist/esm/formatting/Style.js +14 -0
  159. package/dist/esm/formatting/Style.js.map +1 -1
  160. package/dist/esm/formatting/StylesManager.js +14 -2
  161. package/dist/esm/formatting/StylesManager.js.map +1 -1
  162. package/dist/esm/helpers/CleanupHelper.js +103 -26
  163. package/dist/esm/helpers/CleanupHelper.js.map +1 -1
  164. package/dist/esm/images/ImageOptimizer.js +52 -4
  165. package/dist/esm/images/ImageOptimizer.js.map +1 -1
  166. package/dist/esm/index.js +1 -0
  167. package/dist/esm/index.js.map +1 -1
  168. package/dist/esm/internal.js +1 -1
  169. package/dist/esm/internal.js.map +1 -1
  170. package/dist/esm/processors/CompatibilityUpgrader.js +7 -1
  171. package/dist/esm/processors/CompatibilityUpgrader.js.map +1 -1
  172. package/dist/esm/processors/InMemoryRevisionAcceptor.js +134 -13
  173. package/dist/esm/processors/InMemoryRevisionAcceptor.js.map +1 -1
  174. package/dist/esm/processors/RevisionWalker.js +223 -39
  175. package/dist/esm/processors/RevisionWalker.js.map +1 -1
  176. package/dist/esm/processors/SelectiveRevisionAcceptor.js +116 -17
  177. package/dist/esm/processors/SelectiveRevisionAcceptor.js.map +1 -1
  178. package/dist/esm/processors/acceptRevisions.js +20 -11
  179. package/dist/esm/processors/acceptRevisions.js.map +1 -1
  180. package/dist/esm/processors/cnfStyleDecoder.js +7 -7
  181. package/dist/esm/processors/cnfStyleDecoder.js.map +1 -1
  182. package/dist/esm/processors/stripTrackedChanges.js +16 -5
  183. package/dist/esm/processors/stripTrackedChanges.js.map +1 -1
  184. package/dist/esm/utils/deepClone.js +24 -11
  185. package/dist/esm/utils/deepClone.js.map +1 -1
  186. package/dist/esm/utils/units.js +1 -1
  187. package/dist/esm/utils/units.js.map +1 -1
  188. package/dist/esm/utils/validation.js +11 -23
  189. package/dist/esm/utils/validation.js.map +1 -1
  190. package/dist/esm/utils/xmlSanitization.js +131 -7
  191. package/dist/esm/utils/xmlSanitization.js.map +1 -1
  192. package/dist/esm/validation/RevisionAutoFixer.js +69 -55
  193. package/dist/esm/validation/RevisionAutoFixer.js.map +1 -1
  194. package/dist/esm/validation/RevisionValidator.js +24 -20
  195. package/dist/esm/validation/RevisionValidator.js.map +1 -1
  196. package/dist/esm/xml/XMLBuilder.js +52 -20
  197. package/dist/esm/xml/XMLBuilder.js.map +1 -1
  198. package/dist/esm/xml/XMLParser.js +55 -13
  199. package/dist/esm/xml/XMLParser.js.map +1 -1
  200. package/dist/esm/zip/ZipHandler.js +37 -13
  201. package/dist/esm/zip/ZipHandler.js.map +1 -1
  202. package/dist/esm/zip/ZipReader.js +53 -6
  203. package/dist/esm/zip/ZipReader.js.map +1 -1
  204. package/dist/esm/zip/errors.js +7 -0
  205. package/dist/esm/zip/errors.js.map +1 -1
  206. package/dist/esm/zip/types.js +4 -0
  207. package/dist/esm/zip/types.js.map +1 -1
  208. package/dist/formatting/AbstractNumbering.d.ts.map +1 -1
  209. package/dist/formatting/AbstractNumbering.js +1 -1
  210. package/dist/formatting/AbstractNumbering.js.map +1 -1
  211. package/dist/formatting/NumberingLevel.d.ts +1 -1
  212. package/dist/formatting/NumberingLevel.d.ts.map +1 -1
  213. package/dist/formatting/NumberingLevel.js +8 -6
  214. package/dist/formatting/NumberingLevel.js.map +1 -1
  215. package/dist/formatting/NumberingManager.d.ts.map +1 -1
  216. package/dist/formatting/NumberingManager.js +16 -1
  217. package/dist/formatting/NumberingManager.js.map +1 -1
  218. package/dist/formatting/Style.d.ts.map +1 -1
  219. package/dist/formatting/Style.js +14 -0
  220. package/dist/formatting/Style.js.map +1 -1
  221. package/dist/formatting/StylesManager.d.ts +2 -0
  222. package/dist/formatting/StylesManager.d.ts.map +1 -1
  223. package/dist/formatting/StylesManager.js +14 -2
  224. package/dist/formatting/StylesManager.js.map +1 -1
  225. package/dist/helpers/CleanupHelper.d.ts.map +1 -1
  226. package/dist/helpers/CleanupHelper.js +103 -26
  227. package/dist/helpers/CleanupHelper.js.map +1 -1
  228. package/dist/images/ImageOptimizer.d.ts.map +1 -1
  229. package/dist/images/ImageOptimizer.js +52 -4
  230. package/dist/images/ImageOptimizer.js.map +1 -1
  231. package/dist/index.d.ts +3 -1
  232. package/dist/index.d.ts.map +1 -1
  233. package/dist/index.js +4 -2
  234. package/dist/index.js.map +1 -1
  235. package/dist/internal.d.ts +1 -1
  236. package/dist/internal.d.ts.map +1 -1
  237. package/dist/internal.js +2 -1
  238. package/dist/internal.js.map +1 -1
  239. package/dist/processors/CompatibilityUpgrader.d.ts.map +1 -1
  240. package/dist/processors/CompatibilityUpgrader.js +7 -1
  241. package/dist/processors/CompatibilityUpgrader.js.map +1 -1
  242. package/dist/processors/InMemoryRevisionAcceptor.d.ts +1 -0
  243. package/dist/processors/InMemoryRevisionAcceptor.d.ts.map +1 -1
  244. package/dist/processors/InMemoryRevisionAcceptor.js +135 -13
  245. package/dist/processors/InMemoryRevisionAcceptor.js.map +1 -1
  246. package/dist/processors/RevisionWalker.d.ts +9 -3
  247. package/dist/processors/RevisionWalker.d.ts.map +1 -1
  248. package/dist/processors/RevisionWalker.js +223 -39
  249. package/dist/processors/RevisionWalker.js.map +1 -1
  250. package/dist/processors/SelectiveRevisionAcceptor.d.ts.map +1 -1
  251. package/dist/processors/SelectiveRevisionAcceptor.js +116 -17
  252. package/dist/processors/SelectiveRevisionAcceptor.js.map +1 -1
  253. package/dist/processors/acceptRevisions.d.ts +1 -0
  254. package/dist/processors/acceptRevisions.d.ts.map +1 -1
  255. package/dist/processors/acceptRevisions.js +21 -11
  256. package/dist/processors/acceptRevisions.js.map +1 -1
  257. package/dist/processors/cnfStyleDecoder.d.ts.map +1 -1
  258. package/dist/processors/cnfStyleDecoder.js +7 -7
  259. package/dist/processors/cnfStyleDecoder.js.map +1 -1
  260. package/dist/processors/stripTrackedChanges.d.ts.map +1 -1
  261. package/dist/processors/stripTrackedChanges.js +16 -5
  262. package/dist/processors/stripTrackedChanges.js.map +1 -1
  263. package/dist/utils/deepClone.d.ts.map +1 -1
  264. package/dist/utils/deepClone.js +24 -11
  265. package/dist/utils/deepClone.js.map +1 -1
  266. package/dist/utils/units.d.ts.map +1 -1
  267. package/dist/utils/units.js +1 -1
  268. package/dist/utils/units.js.map +1 -1
  269. package/dist/utils/validation.d.ts.map +1 -1
  270. package/dist/utils/validation.js +11 -23
  271. package/dist/utils/validation.js.map +1 -1
  272. package/dist/utils/xmlSanitization.d.ts +2 -0
  273. package/dist/utils/xmlSanitization.d.ts.map +1 -1
  274. package/dist/utils/xmlSanitization.js +133 -7
  275. package/dist/utils/xmlSanitization.js.map +1 -1
  276. package/dist/validation/RevisionAutoFixer.d.ts +6 -2
  277. package/dist/validation/RevisionAutoFixer.d.ts.map +1 -1
  278. package/dist/validation/RevisionAutoFixer.js +68 -54
  279. package/dist/validation/RevisionAutoFixer.js.map +1 -1
  280. package/dist/validation/RevisionValidator.d.ts +2 -0
  281. package/dist/validation/RevisionValidator.d.ts.map +1 -1
  282. package/dist/validation/RevisionValidator.js +26 -21
  283. package/dist/validation/RevisionValidator.js.map +1 -1
  284. package/dist/xml/XMLBuilder.d.ts +1 -0
  285. package/dist/xml/XMLBuilder.d.ts.map +1 -1
  286. package/dist/xml/XMLBuilder.js +52 -20
  287. package/dist/xml/XMLBuilder.js.map +1 -1
  288. package/dist/xml/XMLParser.d.ts +1 -0
  289. package/dist/xml/XMLParser.d.ts.map +1 -1
  290. package/dist/xml/XMLParser.js +55 -13
  291. package/dist/xml/XMLParser.js.map +1 -1
  292. package/dist/zip/ZipHandler.d.ts.map +1 -1
  293. package/dist/zip/ZipHandler.js +37 -13
  294. package/dist/zip/ZipHandler.js.map +1 -1
  295. package/dist/zip/ZipReader.d.ts.map +1 -1
  296. package/dist/zip/ZipReader.js +52 -5
  297. package/dist/zip/ZipReader.js.map +1 -1
  298. package/dist/zip/errors.d.ts +3 -0
  299. package/dist/zip/errors.d.ts.map +1 -1
  300. package/dist/zip/errors.js +9 -1
  301. package/dist/zip/errors.js.map +1 -1
  302. package/dist/zip/types.d.ts +4 -0
  303. package/dist/zip/types.d.ts.map +1 -1
  304. package/dist/zip/types.js +4 -0
  305. package/dist/zip/types.js.map +1 -1
  306. package/package.json +2 -2
  307. package/src/core/Document.ts +1184 -242
  308. package/src/core/DocumentGenerator.ts +106 -26
  309. package/src/core/DocumentParser.ts +681 -114
  310. package/src/core/RelationshipManager.ts +446 -442
  311. package/src/elements/Comment.ts +123 -18
  312. package/src/elements/CommentManager.ts +121 -22
  313. package/src/elements/EndnoteManager.ts +4 -1
  314. package/src/elements/Field.ts +134 -43
  315. package/src/elements/FieldHelpers.ts +20 -4
  316. package/src/elements/Footer.ts +62 -67
  317. package/src/elements/FootnoteManager.ts +4 -1
  318. package/src/elements/Header.ts +62 -67
  319. package/src/elements/HeaderFooterManager.ts +56 -8
  320. package/src/elements/Hyperlink.ts +150 -55
  321. package/src/elements/Image.ts +51 -7
  322. package/src/elements/ImageManager.ts +24 -0
  323. package/src/elements/Paragraph.ts +161 -40
  324. package/src/elements/Revision.ts +446 -47
  325. package/src/elements/Run.ts +44 -6
  326. package/src/elements/Section.ts +25 -9
  327. package/src/elements/Shape.ts +52 -44
  328. package/src/elements/StructuredDocumentTag.ts +83 -8
  329. package/src/elements/Table.ts +151 -50
  330. package/src/elements/TableCell.ts +57 -17
  331. package/src/elements/TableOfContents.ts +10 -9
  332. package/src/elements/TableRow.ts +35 -3
  333. package/src/elements/TextBox.ts +58 -43
  334. package/src/formatting/AbstractNumbering.ts +4 -2
  335. package/src/formatting/NumberingLevel.ts +50 -12
  336. package/src/formatting/NumberingManager.ts +32 -3
  337. package/src/formatting/Style.ts +14 -0
  338. package/src/formatting/StylesManager.ts +29 -2
  339. package/src/helpers/CleanupHelper.ts +122 -30
  340. package/src/images/ImageOptimizer.ts +64 -5
  341. package/src/index.ts +7 -0
  342. package/src/internal.ts +1 -0
  343. package/src/processors/CompatibilityUpgrader.ts +15 -2
  344. package/src/processors/InMemoryRevisionAcceptor.ts +276 -17
  345. package/src/processors/RevisionWalker.ts +390 -46
  346. package/src/processors/SelectiveRevisionAcceptor.ts +164 -28
  347. package/src/processors/acceptRevisions.ts +67 -17
  348. package/src/processors/cnfStyleDecoder.ts +18 -12
  349. package/src/processors/stripTrackedChanges.ts +47 -10
  350. package/src/utils/deepClone.ts +48 -14
  351. package/src/utils/units.ts +3 -1
  352. package/src/utils/validation.ts +30 -32
  353. package/src/utils/xmlSanitization.ts +218 -22
  354. package/src/validation/RevisionAutoFixer.ts +109 -65
  355. package/src/validation/RevisionValidator.ts +48 -23
  356. package/src/xml/XMLBuilder.ts +82 -22
  357. package/src/xml/XMLParser.ts +87 -20
  358. package/src/zip/ZipHandler.ts +61 -21
  359. package/src/zip/ZipReader.ts +135 -13
  360. package/src/zip/errors.ts +15 -0
  361. package/src/zip/types.ts +44 -2
@@ -139,8 +139,9 @@ export class XMLParser {
139
139
  continue;
140
140
  }
141
141
 
142
- // Find the end of opening tag
143
- const openEnd = xml.indexOf('>', startIdx);
142
+ // Find the end of opening tag (quote-aware: attribute values may
143
+ // legally contain a raw '>')
144
+ const openEnd = XMLParser.findTagEnd(xml, startIdx);
144
145
  if (openEnd === -1) break;
145
146
 
146
147
  // Check if self-closing
@@ -333,8 +334,9 @@ export class XMLParser {
333
334
  const startIdx = xml.indexOf(startTag);
334
335
  if (startIdx === -1) return undefined;
335
336
 
336
- // Find the end of the opening tag
337
- const openEnd = xml.indexOf('>', startIdx);
337
+ // Find the end of the opening tag (quote-aware: attribute values may
338
+ // legally contain a raw '>')
339
+ const openEnd = XMLParser.findTagEnd(xml, startIdx);
338
340
  if (openEnd === -1) return undefined;
339
341
 
340
342
  // Find the closing tag
@@ -344,6 +346,28 @@ export class XMLParser {
344
346
  return xml.substring(openEnd + 1, endIdx);
345
347
  }
346
348
 
349
+ /**
350
+ * Finds the first '>' at or after startPos that is not inside a quoted
351
+ * attribute value. XML 1.0 §2.3 permits a raw '>' inside attribute values
352
+ * (only '<', '&', and the delimiting quote must be escaped), so a bare
353
+ * indexOf('>') can end a tag header mid-attribute.
354
+ * @private
355
+ */
356
+ private static findTagEnd(xml: string, startPos: number): number {
357
+ let quote: string | undefined;
358
+ for (let pos = startPos; pos < xml.length; pos++) {
359
+ const ch = xml[pos];
360
+ if (quote) {
361
+ if (ch === quote) quote = undefined;
362
+ } else if (ch === '"' || ch === "'") {
363
+ quote = ch;
364
+ } else if (ch === '>') {
365
+ return pos;
366
+ }
367
+ }
368
+ return -1;
369
+ }
370
+
347
371
  /**
348
372
  * Extracts a complete self-closing tag with its attributes
349
373
  * Handles cases where multiple similar tags exist (e.g., <w:sz.../> and <w:szCs.../>)
@@ -371,19 +395,17 @@ export class XMLParser {
371
395
 
372
396
  // Valid separators after tag name: space, '/', or '>'
373
397
  if (charAfterTag === ' ' || charAfterTag === '/' || charAfterTag === '>') {
374
- // Found the exact tag, now find its end
375
- const endIdx = xml.indexOf('/>', startIdx);
376
- if (endIdx === -1) {
377
- // Try finding a closing tag instead (non-self-closing)
378
- const closeTagStart = xml.indexOf('>', startIdx);
379
- if (closeTagStart === -1) return undefined;
380
-
381
- // Return attributes portion
382
- return xml.substring(startIdx + startPattern.length, closeTagStart);
383
- }
384
-
385
- // Return attributes portion (between tag name and />)
386
- return xml.substring(startIdx + startPattern.length, endIdx);
398
+ // Found the exact tag. Bound the search to this element's own tag
399
+ // header: a global indexOf('/>') can land inside a later sibling
400
+ // when the target is written in expanded form (<tag ...></tag>),
401
+ // attributing the sibling's attributes to this tag.
402
+ const tagEnd = XMLParser.findTagEnd(xml, startIdx + startPattern.length);
403
+ if (tagEnd === -1) return undefined;
404
+
405
+ // Self-closing: exclude the trailing '/'; expanded form: attributes
406
+ // run up to the '>' of the open tag.
407
+ const attrEnd = xml[tagEnd - 1] === '/' ? tagEnd - 1 : tagEnd;
408
+ return xml.substring(startIdx + startPattern.length, attrEnd);
387
409
  }
388
410
 
389
411
  // Not the exact tag (e.g., found "w:sz" when looking for "w:s")
@@ -477,6 +499,27 @@ export class XMLParser {
477
499
  return { value: {}, endPos: xml.length };
478
500
  }
479
501
 
502
+ // Skip processing instructions (e.g. <?mso-application ...?>); without
503
+ // this, '?' fails the element-name match and the PI body is mangled
504
+ // into text one character at a time
505
+ if (xml.substring(openTagStart, openTagStart + 2) === '<?') {
506
+ const piEnd = xml.indexOf('?>', openTagStart + 2);
507
+ if (piEnd !== -1) {
508
+ return XMLParser.parseElementToObject(xml, piEnd + 2, options, depth);
509
+ }
510
+ return { value: {}, endPos: xml.length };
511
+ }
512
+
513
+ // Skip CDATA found where an element is expected (e.g. at the root);
514
+ // CDATA inside element content is preserved by the content loop below
515
+ if (xml.substring(openTagStart, openTagStart + 9) === '<![CDATA[') {
516
+ const cdataEnd = xml.indexOf(']]>', openTagStart + 9);
517
+ if (cdataEnd !== -1) {
518
+ return XMLParser.parseElementToObject(xml, cdataEnd + 3, options, depth);
519
+ }
520
+ return { value: {}, endPos: xml.length };
521
+ }
522
+
480
523
  // Extract element name
481
524
  const nameMatch = /^([a-zA-Z0-9:_-]+)/.exec(xml.substring(openTagStart + 1));
482
525
  if (!nameMatch) {
@@ -485,7 +528,8 @@ export class XMLParser {
485
528
 
486
529
  const originalElementName: string = nameMatch[1] || '';
487
530
  let elementName: string = originalElementName;
488
- const tagHeaderEnd = xml.indexOf('>', openTagStart);
531
+ // Quote-aware scan: attribute values may legally contain a raw '>'
532
+ const tagHeaderEnd = XMLParser.findTagEnd(xml, openTagStart);
489
533
  if (tagHeaderEnd === -1) {
490
534
  return { value: {}, endPos: xml.length };
491
535
  }
@@ -558,6 +602,19 @@ export class XMLParser {
558
602
  }
559
603
  }
560
604
 
605
+ // CDATA: append the payload verbatim — its content is by definition
606
+ // already unescaped, so entity decoding must not be applied
607
+ if (content.startsWith('<![CDATA[', nextTag)) {
608
+ const cdataEnd = content.indexOf(']]>', nextTag + 9);
609
+ if (cdataEnd === -1) {
610
+ textContent += content.substring(nextTag + 9);
611
+ break;
612
+ }
613
+ textContent += content.substring(nextTag + 9, cdataEnd);
614
+ pos = cdataEnd + 3;
615
+ continue;
616
+ }
617
+
561
618
  // Parse child element (increment depth for children)
562
619
  const childResult = XMLParser.parseElementToObject(content, nextTag, options, depth + 1);
563
620
  const childObj = childResult.value as ParsedXMLObject;
@@ -602,6 +659,11 @@ export class XMLParser {
602
659
  // Add children
603
660
  if (children.length > 0) {
604
661
  const coalescedChildren = XMLParser.coalesceChildren(children, options);
662
+ // Mixed content with no attributes leaves elementValue as a bare
663
+ // string; fold it into object form so merging children keeps the text
664
+ if (typeof elementValue === 'string') {
665
+ elementValue = { [options.textNodeName]: elementValue };
666
+ }
605
667
  if (typeof elementValue === 'object' && !Array.isArray(elementValue)) {
606
668
  elementValue = { ...elementValue, ...coalescedChildren };
607
669
  } else {
@@ -705,10 +767,15 @@ export class XMLParser {
705
767
  // Add prefix to attribute name
706
768
  const prefixedName = options.attributeNamePrefix + attrName;
707
769
 
770
+ // Unescape XML entities so stored attribute values are the actual
771
+ // decoded strings, matching text-node handling and extractAttribute.
772
+ // This prevents double-escaping when the value is later re-serialized.
773
+ const decodedValue = XMLBuilder.unescapeXml(attrValue);
774
+
708
775
  // Parse attribute value
709
776
  attributes[prefixedName] = options.parseAttributeValue
710
- ? XMLParser.parseValue(attrValue)
711
- : attrValue;
777
+ ? XMLParser.parseValue(decodedValue)
778
+ : decodedValue;
712
779
  }
713
780
 
714
781
  return attributes;
@@ -14,7 +14,9 @@ import {
14
14
  SizeLimitOptions,
15
15
  DEFAULT_SIZE_LIMITS,
16
16
  } from './types.js';
17
+ import { ResourceLimitError } from './errors.js';
17
18
  import { getGlobalLogger, createScopedLogger, ILogger } from '../utils/logger.js';
19
+ import { normalizePath } from '../utils/validation.js';
18
20
 
19
21
  // Create scoped logger for ZipHandler operations
20
22
  function getLogger(): ILogger {
@@ -41,16 +43,19 @@ export class ZipHandler {
41
43
  * Validates document size against configured limits
42
44
  * @param sizeMB - Size in megabytes
43
45
  * @param limits - Size limit options (merged with defaults)
44
- * @throws Error if size exceeds maximum
46
+ * @throws {ResourceLimitError} If the compressed size exceeds maxSizeMB
45
47
  */
46
48
  private validateDocumentSize(sizeMB: number, limits: Required<SizeLimitOptions>): void {
47
49
  const logger = getLogger();
48
50
  const { warningSizeMB, maxSizeMB } = limits;
49
51
 
50
- // Check maximum size (if enabled)
52
+ // Check maximum size (if enabled). Throw the typed ResourceLimitError so this
53
+ // compressed-size guard is catchable by the same type as the uncompressed/ratio/
54
+ // entry-count guards enforced downstream in ZipReader — callers can distinguish a
55
+ // hostile/oversized payload from a genuinely corrupt archive.
51
56
  if (maxSizeMB > 0 && sizeMB > maxSizeMB) {
52
57
  logger.error('Document exceeds maximum size', { sizeMB: sizeMB.toFixed(1), maxSizeMB });
53
- throw new Error(
58
+ throw new ResourceLimitError(
54
59
  `Document size (${sizeMB.toFixed(1)}MB) exceeds maximum supported size (${maxSizeMB}MB). ` +
55
60
  `This would likely cause out-of-memory errors. Consider:\n` +
56
61
  `- Compressing/optimizing images\n` +
@@ -98,15 +103,26 @@ export class ZipHandler {
98
103
  const limits = this.getSizeLimits(options);
99
104
  this.validateDocumentSize(sizeMB, limits);
100
105
 
101
- await this.reader.loadFromFile(filePath, options);
102
-
103
- // Copy all files from reader to writer for modification
104
- const files = this.reader.getAllFiles();
105
- this.writer.clear();
106
- this.writer.addFiles(files);
107
-
108
- this.mode = 'modify';
109
- logger.info('DOCX file loaded', { fileCount: files.size, sizeMB: sizeMB.toFixed(2) });
106
+ try {
107
+ await this.reader.loadFromFile(filePath, options);
108
+
109
+ // Copy all files from reader to writer for modification
110
+ const files = this.reader.getAllFiles();
111
+ this.writer.clear();
112
+ this.writer.addFiles(files);
113
+
114
+ this.mode = 'modify';
115
+ logger.info('DOCX file loaded', { fileCount: files.size, sizeMB: sizeMB.toFixed(2) });
116
+ } catch (error) {
117
+ // A failed reload must not leave the handler serving the previously loaded
118
+ // archive. Reset to a deterministically empty state so getFile/save/etc.
119
+ // cannot silently return stale content. A fresh reader discards any
120
+ // partially-extracted files and the stale `loaded` flag.
121
+ this.writer.clear();
122
+ this.reader = new ZipReader();
123
+ this.mode = 'write';
124
+ throw error;
125
+ }
110
126
  }
111
127
 
112
128
  /**
@@ -125,15 +141,26 @@ export class ZipHandler {
125
141
  const limits = this.getSizeLimits(options);
126
142
  this.validateDocumentSize(sizeMB, limits);
127
143
 
128
- await this.reader.loadFromBuffer(buffer, options);
129
-
130
- // Copy all files from reader to writer for modification
131
- const files = this.reader.getAllFiles();
132
- this.writer.clear();
133
- this.writer.addFiles(files);
134
-
135
- this.mode = 'modify';
136
- logger.info('DOCX buffer loaded', { fileCount: files.size, sizeMB: sizeMB.toFixed(2) });
144
+ try {
145
+ await this.reader.loadFromBuffer(buffer, options);
146
+
147
+ // Copy all files from reader to writer for modification
148
+ const files = this.reader.getAllFiles();
149
+ this.writer.clear();
150
+ this.writer.addFiles(files);
151
+
152
+ this.mode = 'modify';
153
+ logger.info('DOCX buffer loaded', { fileCount: files.size, sizeMB: sizeMB.toFixed(2) });
154
+ } catch (error) {
155
+ // A failed reload must not leave the handler serving the previously loaded
156
+ // archive. Reset to a deterministically empty state so getFile/save/etc.
157
+ // cannot silently return stale content. A fresh reader discards any
158
+ // partially-extracted files and the stale `loaded` flag.
159
+ this.writer.clear();
160
+ this.reader = new ZipReader();
161
+ this.mode = 'write';
162
+ throw error;
163
+ }
137
164
  }
138
165
 
139
166
  // ==================== FILE OPERATIONS ====================
@@ -300,6 +327,13 @@ export class ZipHandler {
300
327
  if (!file) {
301
328
  return false;
302
329
  }
330
+ // Guard against degenerate rename where source and destination collapse to
331
+ // the same archive key (identical strings or backslash/forward-slash variants).
332
+ // Without this, addFile would overwrite the single entry and the subsequent
333
+ // removeFile would delete it, silently destroying the file.
334
+ if (normalizePath(oldPath) === normalizePath(newPath)) {
335
+ return true;
336
+ }
303
337
  this.addFile(newPath, file.content, {
304
338
  binary: file.isBinary,
305
339
  date: file.date,
@@ -336,6 +370,12 @@ export class ZipHandler {
336
370
  if (!this.copyFile(srcPath, destPath)) {
337
371
  return false;
338
372
  }
373
+ // Guard against degenerate move where source and destination collapse to the
374
+ // same archive key. copyFile already re-added the (identical) entry, so the
375
+ // removeFile below would delete it, silently destroying the file.
376
+ if (normalizePath(srcPath) === normalizePath(destPath)) {
377
+ return true;
378
+ }
339
379
  this.removeFile(srcPath);
340
380
  return true;
341
381
  }
@@ -4,12 +4,13 @@
4
4
 
5
5
  import JSZip from 'jszip';
6
6
  import { promises as fs } from 'fs';
7
- import { ZipFile, FileMap, LoadOptions } from './types.js';
7
+ import { ZipFile, FileMap, LoadOptions, SizeLimitOptions, DEFAULT_SIZE_LIMITS } from './types.js';
8
8
  import {
9
9
  DocxNotFoundError,
10
10
  InvalidDocxError,
11
11
  CorruptedArchiveError,
12
12
  FileOperationError,
13
+ ResourceLimitError,
13
14
  } from './errors.js';
14
15
  import {
15
16
  validateDocxStructure,
@@ -18,6 +19,25 @@ import {
18
19
  isValidZipBuffer,
19
20
  } from '../utils/validation.js';
20
21
 
22
+ /**
23
+ * Shape of JSZip's undocumented per-entry `_data` field, consulted only as an
24
+ * early-reject hint — never as the authoritative size guard (measured decompressed
25
+ * bytes are). Mirrors the commented-out `CompressedObject` interface in jszip's own
26
+ * `node_modules/jszip/index.d.ts`.
27
+ *
28
+ * [TS-5] Verified against jszip 3.10.x (package.json range `^3.10.1`). A minor jszip
29
+ * bump could rename or remove this field; if so the early-reject/ratio hints silently
30
+ * degrade to no-ops while the measured-byte accounting in {@link extractFiles} keeps
31
+ * enforcing the budgets. `tests/zip/JSZipInternalContract.test.ts` canaries the field
32
+ * so such a regression surfaces on upgrade.
33
+ */
34
+ interface JSZipObjectPrivate {
35
+ _data?: {
36
+ compressedSize?: number;
37
+ uncompressedSize?: number;
38
+ };
39
+ }
40
+
21
41
  /**
22
42
  * Handles reading operations on ZIP archives
23
43
  */
@@ -44,7 +64,14 @@ export class ZipReader {
44
64
  const buffer = await fs.readFile(filePath);
45
65
  await this.loadFromBuffer(buffer, options);
46
66
  } catch (error: unknown) {
47
- if (error instanceof DocxNotFoundError) {
67
+ // Surface load-classification errors verbatim so callers can distinguish a
68
+ // missing/oversized/hostile archive from a generic read failure.
69
+ if (
70
+ error instanceof DocxNotFoundError ||
71
+ error instanceof ResourceLimitError ||
72
+ error instanceof InvalidDocxError ||
73
+ error instanceof CorruptedArchiveError
74
+ ) {
48
75
  throw error;
49
76
  }
50
77
  const message = error instanceof Error ? error.message : String(error);
@@ -59,6 +86,7 @@ export class ZipReader {
59
86
  */
60
87
  async loadFromBuffer(buffer: Buffer, options: LoadOptions = {}): Promise<void> {
61
88
  const { validate = true } = options;
89
+ const limits: Required<SizeLimitOptions> = { ...DEFAULT_SIZE_LIMITS, ...options.sizeLimits };
62
90
 
63
91
  try {
64
92
  // Validate ZIP signature
@@ -69,8 +97,19 @@ export class ZipReader {
69
97
  // Load ZIP archive
70
98
  this.zip = await JSZip.loadAsync(buffer);
71
99
 
72
- // Extract all files
73
- await this.extractFiles();
100
+ // Enumerate non-directory entries once; reused for the count guard below and
101
+ // for extraction, so the file list is not filtered twice.
102
+ const filePaths = Object.keys(this.zip.files).filter((path) => !this.zip!.files[path]!.dir);
103
+
104
+ // Reject entry-count amplification before decompressing anything.
105
+ if (limits.maxEntryCount > 0 && filePaths.length > limits.maxEntryCount) {
106
+ throw new ResourceLimitError(
107
+ `archive entry count (${filePaths.length}) exceeds maxEntryCount (${limits.maxEntryCount})`
108
+ );
109
+ }
110
+
111
+ // Extract all files (enforces uncompressed/ratio budgets while decompressing)
112
+ await this.extractFiles(limits, filePaths);
74
113
 
75
114
  // Validate DOCX structure if requested
76
115
  if (validate) {
@@ -79,7 +118,9 @@ export class ZipReader {
79
118
 
80
119
  this.loaded = true;
81
120
  } catch (error: unknown) {
82
- if (error instanceof InvalidDocxError) {
121
+ // A resource-limit breach must not be masked as a generic corruption error;
122
+ // the cause (which budget was exceeded) is actionable for the caller.
123
+ if (error instanceof InvalidDocxError || error instanceof ResourceLimitError) {
83
124
  throw error;
84
125
  }
85
126
  const message = error instanceof Error ? error.message : String(error);
@@ -91,20 +132,41 @@ export class ZipReader {
91
132
  * Extracts all files from the ZIP archive into memory
92
133
  *
93
134
  * **Encoding Note:**
94
- * - Text files (XML, etc.) are extracted as UTF-8 strings using `async('string')`
135
+ * - Known-text parts (.xml, .rels, etc.) are extracted as UTF-8 strings using `async('string')`
95
136
  * - JSZip automatically decodes UTF-8 when extracting as 'string'
96
- * - Binary files are extracted as Buffers to preserve exact content
137
+ * - Everything else is extracted as a Buffer to preserve exact bytes — a
138
+ * string decode is lossy (invalid UTF-8 becomes U+FFFD), which would
139
+ * corrupt embedded binary parts (OLE packages, fonts, metafiles)
97
140
  * - All text content is guaranteed to be valid UTF-8
141
+ *
142
+ * **Resource limits:** the running total of *actual* decompressed bytes is the
143
+ * primary defense against high-ratio archives. JSZip's internal `_data` metadata
144
+ * is consulted only as an early-reject hint (it is undocumented and may be absent),
145
+ * never as the sole guard — every breach is re-checked against measured bytes.
146
+ *
147
+ * @param limits - Fully-resolved size limits to enforce while extracting
148
+ * @param filePaths - Pre-filtered non-directory entry paths (computed by the caller)
98
149
  */
99
- private async extractFiles(): Promise<void> {
150
+ private async extractFiles(
151
+ limits: Required<SizeLimitOptions>,
152
+ filePaths: string[]
153
+ ): Promise<void> {
100
154
  if (!this.zip) {
101
155
  throw new Error('ZIP archive not loaded');
102
156
  }
103
157
 
104
158
  this.files.clear();
105
159
 
106
- // Get all file paths
107
- const filePaths = Object.keys(this.zip.files).filter((path) => !this.zip!.files[path]!.dir);
160
+ const maxEntryBytes =
161
+ limits.maxEntryUncompressedMB > 0 ? limits.maxEntryUncompressedMB * 1024 * 1024 : 0;
162
+ const maxTotalBytes =
163
+ limits.maxTotalUncompressedMB > 0 ? limits.maxTotalUncompressedMB * 1024 * 1024 : 0;
164
+ // Only enforce the compression ratio on entries large enough for the ratio to be
165
+ // meaningful, so a small but highly-compressible part (e.g. tiny repetitive XML)
166
+ // cannot trip a false positive.
167
+ const ratioFloorBytes = 1024 * 1024;
168
+
169
+ let totalBytes = 0;
108
170
 
109
171
  // Extract each file
110
172
  for (const filePath of filePaths) {
@@ -115,20 +177,80 @@ export class ZipReader {
115
177
  continue;
116
178
  }
117
179
 
180
+ // Early-reject hint: JSZip exposes declared uncompressed/compressed sizes on a
181
+ // private `_data` field. Cast once per entry (see {@link JSZipObjectPrivate}) and
182
+ // use it only to avoid decompressing an obviously oversized entry; the
183
+ // authoritative check below uses the measured byte count.
184
+ const internalData = (zipObject as unknown as JSZipObjectPrivate)._data;
185
+ const declaredSize = internalData?.uncompressedSize;
186
+ if (typeof declaredSize === 'number' && declaredSize >= 0) {
187
+ if (maxEntryBytes > 0 && declaredSize > maxEntryBytes) {
188
+ throw new ResourceLimitError(
189
+ `entry "${normalizedPath}" uncompressed size (${declaredSize} bytes) exceeds ` +
190
+ `maxEntryUncompressedMB (${limits.maxEntryUncompressedMB}MB)`
191
+ );
192
+ }
193
+ if (maxTotalBytes > 0 && totalBytes + declaredSize > maxTotalBytes) {
194
+ throw new ResourceLimitError(
195
+ `total uncompressed size would exceed maxTotalUncompressedMB ` +
196
+ `(${limits.maxTotalUncompressedMB}MB)`
197
+ );
198
+ }
199
+ }
200
+
118
201
  const isBinary = isBinaryFile(normalizedPath);
119
202
 
120
203
  // Extract content based on type
121
- // For text files: JSZip's async('string') automatically uses UTF-8 decoding
122
- // For binary files: async('nodebuffer') preserves exact bytes
204
+ // For known-text files: JSZip's async('string') automatically uses UTF-8 decoding
205
+ // For everything else: async('nodebuffer') preserves exact bytes
123
206
  let content;
124
207
  if (isBinary) {
125
208
  content = await zipObject.async('nodebuffer');
126
209
  } else {
127
- // Text files are extracted as UTF-8 strings
210
+ // Known-text files are extracted as UTF-8 strings
128
211
  // JSZip automatically handles UTF-8 decoding for 'string' type
129
212
  content = await zipObject.async('string');
130
213
  }
131
214
 
215
+ // Measure the *actual* decompressed byte count (UTF-8 for strings) — this is the
216
+ // primary, authoritative resource accounting that does not trust archive metadata.
217
+ const entryBytes = Buffer.isBuffer(content)
218
+ ? content.length
219
+ : Buffer.byteLength(content, 'utf8');
220
+
221
+ if (maxEntryBytes > 0 && entryBytes > maxEntryBytes) {
222
+ throw new ResourceLimitError(
223
+ `entry "${normalizedPath}" uncompressed size (${entryBytes} bytes) exceeds ` +
224
+ `maxEntryUncompressedMB (${limits.maxEntryUncompressedMB}MB)`
225
+ );
226
+ }
227
+
228
+ totalBytes += entryBytes;
229
+ if (maxTotalBytes > 0 && totalBytes > maxTotalBytes) {
230
+ throw new ResourceLimitError(
231
+ `total uncompressed size (${totalBytes} bytes) exceeds maxTotalUncompressedMB ` +
232
+ `(${limits.maxTotalUncompressedMB}MB)`
233
+ );
234
+ }
235
+
236
+ // Compression-ratio guard for sizable entries, when the archive reports a
237
+ // compressed size we can divide by (reusing the single `_data` read above).
238
+ const compressedSize = internalData?.compressedSize;
239
+ if (
240
+ limits.maxCompressionRatio > 0 &&
241
+ entryBytes > ratioFloorBytes &&
242
+ typeof compressedSize === 'number' &&
243
+ compressedSize > 0
244
+ ) {
245
+ const ratio = entryBytes / compressedSize;
246
+ if (ratio > limits.maxCompressionRatio) {
247
+ throw new ResourceLimitError(
248
+ `entry "${normalizedPath}" compression ratio (${ratio.toFixed(1)}:1) exceeds ` +
249
+ `maxCompressionRatio (${limits.maxCompressionRatio}:1)`
250
+ );
251
+ }
252
+ }
253
+
132
254
  // Get file metadata
133
255
  const date = zipObject.date;
134
256
 
package/src/zip/errors.ts CHANGED
@@ -46,6 +46,21 @@ export class CorruptedArchiveError extends DocxError {
46
46
  }
47
47
  }
48
48
 
49
+ /**
50
+ * Error thrown when an archive breaches a configured resource limit.
51
+ *
52
+ * Distinct from {@link CorruptedArchiveError} so callers can tell a hostile/oversized
53
+ * input (a "zip bomb" style payload) apart from a genuinely malformed archive. The
54
+ * message names the specific limit that was exceeded so it is actionable.
55
+ */
56
+ export class ResourceLimitError extends DocxError {
57
+ constructor(message: string) {
58
+ super(`Resource limit exceeded: ${message}`);
59
+ this.name = 'ResourceLimitError';
60
+ Object.setPrototypeOf(this, ResourceLimitError.prototype);
61
+ }
62
+ }
63
+
49
64
  /**
50
65
  * Error thrown when a required DOCX file is missing
51
66
  */
package/src/zip/types.ts CHANGED
@@ -28,18 +28,60 @@ export interface SizeLimitOptions {
28
28
  */
29
29
  warningSizeMB?: number;
30
30
  /**
31
- * Maximum size in MB to load (default: 150 MB)
31
+ * Maximum *compressed* archive size in MB to load (default: 150 MB)
32
32
  * Set to 0 to disable the limit (not recommended)
33
33
  */
34
34
  maxSizeMB?: number;
35
+ /**
36
+ * Maximum total *uncompressed* size in MB across all archive entries
37
+ * (default: 300 MB). This is the primary, authoritative defense against
38
+ * high-ratio "zip bomb" payloads whose compressed size is small: it is
39
+ * enforced against measured decompressed bytes, never archive-reported
40
+ * metadata. Set to 0 to disable.
41
+ *
42
+ * Note: decompression is non-streaming (JSZip buffers each entry fully), so
43
+ * peak transient heap can approach `maxTotalUncompressedMB + maxEntryUncompressedMB`
44
+ * (the already-accumulated total plus the entry being decoded) before a limit
45
+ * fires. Size the limits with that headroom in mind for memory-constrained hosts.
46
+ */
47
+ maxTotalUncompressedMB?: number;
48
+ /**
49
+ * Maximum *uncompressed* size in MB for any single archive entry
50
+ * (default: 150 MB). Set to 0 to disable.
51
+ */
52
+ maxEntryUncompressedMB?: number;
53
+ /**
54
+ * Maximum number of entries (files) allowed in the archive
55
+ * (default: 2000). Guards against entry-count amplification. Set to 0 to disable.
56
+ */
57
+ maxEntryCount?: number;
58
+ /**
59
+ * Maximum allowed per-entry compression ratio (uncompressed / compressed)
60
+ * (default: 200). Only enforced for sizable entries where the ratio is
61
+ * meaningful and the compressed size is reported by the archive.
62
+ *
63
+ * Best-effort: it relies on a compressed size that JSZip exposes only on an
64
+ * undocumented internal field, so it is silently skipped for any entry where
65
+ * that size is absent. `maxTotalUncompressedMB` is the authoritative guard
66
+ * against high-ratio payloads; treat this ratio limit as a defense-in-depth
67
+ * early reject, not a sole defense. Set to 0 to disable.
68
+ */
69
+ maxCompressionRatio?: number;
35
70
  }
36
71
 
37
72
  /**
38
- * Default size limits for document loading
73
+ * Default size limits for document loading.
74
+ *
75
+ * Defaults are intentionally generous so legitimate large documents load
76
+ * unchanged; tighten them via {@link LoadOptions.sizeLimits} for untrusted input.
39
77
  */
40
78
  export const DEFAULT_SIZE_LIMITS: Required<SizeLimitOptions> = {
41
79
  warningSizeMB: 50,
42
80
  maxSizeMB: 150,
81
+ maxTotalUncompressedMB: 300,
82
+ maxEntryUncompressedMB: 150,
83
+ maxEntryCount: 2000,
84
+ maxCompressionRatio: 200,
43
85
  };
44
86
 
45
87
  /**