open-agreements 0.3.1 → 0.4.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 (429) hide show
  1. package/content/templates/closing-checklist/template.docx +0 -0
  2. package/dist/core/checklist/docx-import.d.ts +50 -0
  3. package/dist/core/checklist/docx-import.d.ts.map +1 -0
  4. package/dist/core/checklist/docx-import.js +613 -0
  5. package/dist/core/checklist/docx-import.js.map +1 -0
  6. package/dist/core/checklist/docx-table-helpers.d.ts +33 -0
  7. package/dist/core/checklist/docx-table-helpers.d.ts.map +1 -0
  8. package/dist/core/checklist/docx-table-helpers.js +154 -0
  9. package/dist/core/checklist/docx-table-helpers.js.map +1 -0
  10. package/dist/core/checklist/format-checklist-docx.d.ts.map +1 -1
  11. package/dist/core/checklist/format-checklist-docx.js +37 -88
  12. package/dist/core/checklist/format-checklist-docx.js.map +1 -1
  13. package/dist/core/checklist/index.d.ts +15 -12
  14. package/dist/core/checklist/index.d.ts.map +1 -1
  15. package/dist/core/checklist/index.js +48 -30
  16. package/dist/core/checklist/index.js.map +1 -1
  17. package/dist/core/checklist/status-labels.d.ts +6 -0
  18. package/dist/core/checklist/status-labels.d.ts.map +1 -1
  19. package/dist/core/checklist/status-labels.js +8 -0
  20. package/dist/core/checklist/status-labels.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/node_modules/@usejunior/docx-core/dist/atomizer.d.ts +218 -0
  26. package/node_modules/@usejunior/docx-core/dist/atomizer.d.ts.map +1 -0
  27. package/node_modules/@usejunior/docx-core/dist/atomizer.js +869 -0
  28. package/node_modules/@usejunior/docx-core/dist/atomizer.js.map +1 -0
  29. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/atomLcs.d.ts +96 -0
  30. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/atomLcs.d.ts.map +1 -0
  31. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/atomLcs.js +347 -0
  32. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/atomLcs.js.map +1 -0
  33. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/consumerCompatibility.d.ts +2 -0
  34. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/consumerCompatibility.d.ts.map +1 -0
  35. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/consumerCompatibility.js +188 -0
  36. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/consumerCompatibility.js.map +1 -0
  37. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/debug.d.ts +41 -0
  38. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/debug.d.ts.map +1 -0
  39. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/debug.js +85 -0
  40. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/debug.js.map +1 -0
  41. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/documentReconstructor.d.ts +64 -0
  42. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/documentReconstructor.d.ts.map +1 -0
  43. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/documentReconstructor.js +985 -0
  44. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/documentReconstructor.js.map +1 -0
  45. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/hierarchicalLcs.d.ts +111 -0
  46. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/hierarchicalLcs.d.ts.map +1 -0
  47. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/hierarchicalLcs.js +469 -0
  48. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/hierarchicalLcs.js.map +1 -0
  49. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/inPlaceModifier.d.ts +277 -0
  50. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/inPlaceModifier.d.ts.map +1 -0
  51. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/inPlaceModifier.js +2279 -0
  52. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/inPlaceModifier.js.map +1 -0
  53. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/numberingIntegration.d.ts +59 -0
  54. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/numberingIntegration.d.ts.map +1 -0
  55. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/numberingIntegration.js +209 -0
  56. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/numberingIntegration.js.map +1 -0
  57. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/pipeline.d.ts +69 -0
  58. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/pipeline.d.ts.map +1 -0
  59. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/pipeline.js +910 -0
  60. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/pipeline.js.map +1 -0
  61. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/premergeRuns.d.ts +26 -0
  62. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/premergeRuns.d.ts.map +1 -0
  63. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/premergeRuns.js +153 -0
  64. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/premergeRuns.js.map +1 -0
  65. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptor.d.ts +63 -0
  66. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptor.d.ts.map +1 -0
  67. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptor.js +254 -0
  68. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptor.js.map +1 -0
  69. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptorAst.d.ts +64 -0
  70. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptorAst.d.ts.map +1 -0
  71. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptorAst.js +616 -0
  72. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/trackChangesAcceptorAst.js.map +1 -0
  73. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/xmlToWmlElement.d.ts +65 -0
  74. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/xmlToWmlElement.d.ts.map +1 -0
  75. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/xmlToWmlElement.js +95 -0
  76. package/node_modules/@usejunior/docx-core/dist/baselines/atomizer/xmlToWmlElement.js.map +1 -0
  77. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DocxodusWasm.d.ts +51 -0
  78. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DocxodusWasm.d.ts.map +1 -0
  79. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DocxodusWasm.js +83 -0
  80. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DocxodusWasm.js.map +1 -0
  81. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DotnetCli.d.ts +40 -0
  82. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DotnetCli.d.ts.map +1 -0
  83. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DotnetCli.js +135 -0
  84. package/node_modules/@usejunior/docx-core/dist/baselines/wmlcomparer/DotnetCli.js.map +1 -0
  85. package/node_modules/@usejunior/docx-core/dist/cli/compare-two.d.ts +28 -0
  86. package/node_modules/@usejunior/docx-core/dist/cli/compare-two.d.ts.map +1 -0
  87. package/node_modules/@usejunior/docx-core/dist/cli/compare-two.js +110 -0
  88. package/node_modules/@usejunior/docx-core/dist/cli/compare-two.js.map +1 -0
  89. package/node_modules/@usejunior/docx-core/dist/cli/index.d.ts +3 -0
  90. package/node_modules/@usejunior/docx-core/dist/cli/index.d.ts.map +1 -0
  91. package/node_modules/@usejunior/docx-core/dist/cli/index.js +21 -0
  92. package/node_modules/@usejunior/docx-core/dist/cli/index.js.map +1 -0
  93. package/node_modules/@usejunior/docx-core/dist/core-types.d.ts +296 -0
  94. package/node_modules/@usejunior/docx-core/dist/core-types.d.ts.map +1 -0
  95. package/node_modules/@usejunior/docx-core/dist/core-types.js +122 -0
  96. package/node_modules/@usejunior/docx-core/dist/core-types.js.map +1 -0
  97. package/node_modules/@usejunior/docx-core/dist/footnotes.d.ts +144 -0
  98. package/node_modules/@usejunior/docx-core/dist/footnotes.d.ts.map +1 -0
  99. package/node_modules/@usejunior/docx-core/dist/footnotes.js +291 -0
  100. package/node_modules/@usejunior/docx-core/dist/footnotes.js.map +1 -0
  101. package/node_modules/@usejunior/docx-core/dist/format-detection.d.ts +120 -0
  102. package/node_modules/@usejunior/docx-core/dist/format-detection.d.ts.map +1 -0
  103. package/node_modules/@usejunior/docx-core/dist/format-detection.js +338 -0
  104. package/node_modules/@usejunior/docx-core/dist/format-detection.js.map +1 -0
  105. package/node_modules/@usejunior/docx-core/dist/index.d.ts +177 -0
  106. package/node_modules/@usejunior/docx-core/dist/index.d.ts.map +1 -0
  107. package/node_modules/@usejunior/docx-core/dist/index.js +55 -0
  108. package/node_modules/@usejunior/docx-core/dist/index.js.map +1 -0
  109. package/node_modules/@usejunior/docx-core/dist/integration/output-artifacts.d.ts +6 -0
  110. package/node_modules/@usejunior/docx-core/dist/integration/output-artifacts.d.ts.map +1 -0
  111. package/node_modules/@usejunior/docx-core/dist/integration/output-artifacts.js +30 -0
  112. package/node_modules/@usejunior/docx-core/dist/integration/output-artifacts.js.map +1 -0
  113. package/node_modules/@usejunior/docx-core/dist/move-detection.d.ts +211 -0
  114. package/node_modules/@usejunior/docx-core/dist/move-detection.d.ts.map +1 -0
  115. package/node_modules/@usejunior/docx-core/dist/move-detection.js +391 -0
  116. package/node_modules/@usejunior/docx-core/dist/move-detection.js.map +1 -0
  117. package/node_modules/@usejunior/docx-core/dist/numbering.d.ts +136 -0
  118. package/node_modules/@usejunior/docx-core/dist/numbering.d.ts.map +1 -0
  119. package/node_modules/@usejunior/docx-core/dist/numbering.js +446 -0
  120. package/node_modules/@usejunior/docx-core/dist/numbering.js.map +1 -0
  121. package/node_modules/@usejunior/docx-core/dist/primitives/accept_changes.d.ts +30 -0
  122. package/node_modules/@usejunior/docx-core/dist/primitives/accept_changes.d.ts.map +1 -0
  123. package/node_modules/@usejunior/docx-core/dist/primitives/accept_changes.js +241 -0
  124. package/node_modules/@usejunior/docx-core/dist/primitives/accept_changes.js.map +1 -0
  125. package/node_modules/@usejunior/docx-core/dist/primitives/bookmarks.d.ts +12 -0
  126. package/node_modules/@usejunior/docx-core/dist/primitives/bookmarks.d.ts.map +1 -0
  127. package/node_modules/@usejunior/docx-core/dist/primitives/bookmarks.js +248 -0
  128. package/node_modules/@usejunior/docx-core/dist/primitives/bookmarks.js.map +1 -0
  129. package/node_modules/@usejunior/docx-core/dist/primitives/comments.d.ts +88 -0
  130. package/node_modules/@usejunior/docx-core/dist/primitives/comments.d.ts.map +1 -0
  131. package/node_modules/@usejunior/docx-core/dist/primitives/comments.js +703 -0
  132. package/node_modules/@usejunior/docx-core/dist/primitives/comments.js.map +1 -0
  133. package/node_modules/@usejunior/docx-core/dist/primitives/document.d.ts +186 -0
  134. package/node_modules/@usejunior/docx-core/dist/primitives/document.d.ts.map +1 -0
  135. package/node_modules/@usejunior/docx-core/dist/primitives/document.js +555 -0
  136. package/node_modules/@usejunior/docx-core/dist/primitives/document.js.map +1 -0
  137. package/node_modules/@usejunior/docx-core/dist/primitives/document_view.d.ts +97 -0
  138. package/node_modules/@usejunior/docx-core/dist/primitives/document_view.d.ts.map +1 -0
  139. package/node_modules/@usejunior/docx-core/dist/primitives/document_view.js +749 -0
  140. package/node_modules/@usejunior/docx-core/dist/primitives/document_view.js.map +1 -0
  141. package/node_modules/@usejunior/docx-core/dist/primitives/dom-helpers.d.ts +94 -0
  142. package/node_modules/@usejunior/docx-core/dist/primitives/dom-helpers.d.ts.map +1 -0
  143. package/node_modules/@usejunior/docx-core/dist/primitives/dom-helpers.js +219 -0
  144. package/node_modules/@usejunior/docx-core/dist/primitives/dom-helpers.js.map +1 -0
  145. package/node_modules/@usejunior/docx-core/dist/primitives/errors.d.ts +7 -0
  146. package/node_modules/@usejunior/docx-core/dist/primitives/errors.d.ts.map +1 -0
  147. package/node_modules/@usejunior/docx-core/dist/primitives/errors.js +10 -0
  148. package/node_modules/@usejunior/docx-core/dist/primitives/errors.js.map +1 -0
  149. package/node_modules/@usejunior/docx-core/dist/primitives/extract_revisions.d.ts +50 -0
  150. package/node_modules/@usejunior/docx-core/dist/primitives/extract_revisions.d.ts.map +1 -0
  151. package/node_modules/@usejunior/docx-core/dist/primitives/extract_revisions.js +340 -0
  152. package/node_modules/@usejunior/docx-core/dist/primitives/extract_revisions.js.map +1 -0
  153. package/node_modules/@usejunior/docx-core/dist/primitives/footnotes.d.ts +37 -0
  154. package/node_modules/@usejunior/docx-core/dist/primitives/footnotes.d.ts.map +1 -0
  155. package/node_modules/@usejunior/docx-core/dist/primitives/footnotes.js +552 -0
  156. package/node_modules/@usejunior/docx-core/dist/primitives/footnotes.js.map +1 -0
  157. package/node_modules/@usejunior/docx-core/dist/primitives/formatting_tags.d.ts +43 -0
  158. package/node_modules/@usejunior/docx-core/dist/primitives/formatting_tags.d.ts.map +1 -0
  159. package/node_modules/@usejunior/docx-core/dist/primitives/formatting_tags.js +291 -0
  160. package/node_modules/@usejunior/docx-core/dist/primitives/formatting_tags.js.map +1 -0
  161. package/node_modules/@usejunior/docx-core/dist/primitives/index.d.ts +27 -0
  162. package/node_modules/@usejunior/docx-core/dist/primitives/index.d.ts.map +1 -0
  163. package/node_modules/@usejunior/docx-core/dist/primitives/index.js +27 -0
  164. package/node_modules/@usejunior/docx-core/dist/primitives/index.js.map +1 -0
  165. package/node_modules/@usejunior/docx-core/dist/primitives/layout.d.ts +53 -0
  166. package/node_modules/@usejunior/docx-core/dist/primitives/layout.d.ts.map +1 -0
  167. package/node_modules/@usejunior/docx-core/dist/primitives/layout.js +178 -0
  168. package/node_modules/@usejunior/docx-core/dist/primitives/layout.js.map +1 -0
  169. package/node_modules/@usejunior/docx-core/dist/primitives/list_labels.d.ts +19 -0
  170. package/node_modules/@usejunior/docx-core/dist/primitives/list_labels.d.ts.map +1 -0
  171. package/node_modules/@usejunior/docx-core/dist/primitives/list_labels.js +57 -0
  172. package/node_modules/@usejunior/docx-core/dist/primitives/list_labels.js.map +1 -0
  173. package/node_modules/@usejunior/docx-core/dist/primitives/matching.d.ts +31 -0
  174. package/node_modules/@usejunior/docx-core/dist/primitives/matching.d.ts.map +1 -0
  175. package/node_modules/@usejunior/docx-core/dist/primitives/matching.js +223 -0
  176. package/node_modules/@usejunior/docx-core/dist/primitives/matching.js.map +1 -0
  177. package/node_modules/@usejunior/docx-core/dist/primitives/merge_runs.d.ts +23 -0
  178. package/node_modules/@usejunior/docx-core/dist/primitives/merge_runs.d.ts.map +1 -0
  179. package/node_modules/@usejunior/docx-core/dist/primitives/merge_runs.js +243 -0
  180. package/node_modules/@usejunior/docx-core/dist/primitives/merge_runs.js.map +1 -0
  181. package/node_modules/@usejunior/docx-core/dist/primitives/namespaces.d.ts +91 -0
  182. package/node_modules/@usejunior/docx-core/dist/primitives/namespaces.d.ts.map +1 -0
  183. package/node_modules/@usejunior/docx-core/dist/primitives/namespaces.js +108 -0
  184. package/node_modules/@usejunior/docx-core/dist/primitives/namespaces.js.map +1 -0
  185. package/node_modules/@usejunior/docx-core/dist/primitives/numbering.d.ts +27 -0
  186. package/node_modules/@usejunior/docx-core/dist/primitives/numbering.d.ts.map +1 -0
  187. package/node_modules/@usejunior/docx-core/dist/primitives/numbering.js +182 -0
  188. package/node_modules/@usejunior/docx-core/dist/primitives/numbering.js.map +1 -0
  189. package/node_modules/@usejunior/docx-core/dist/primitives/prevent_double_elevation.d.ts +18 -0
  190. package/node_modules/@usejunior/docx-core/dist/primitives/prevent_double_elevation.d.ts.map +1 -0
  191. package/node_modules/@usejunior/docx-core/dist/primitives/prevent_double_elevation.js +190 -0
  192. package/node_modules/@usejunior/docx-core/dist/primitives/prevent_double_elevation.js.map +1 -0
  193. package/node_modules/@usejunior/docx-core/dist/primitives/reject_changes.d.ts +27 -0
  194. package/node_modules/@usejunior/docx-core/dist/primitives/reject_changes.d.ts.map +1 -0
  195. package/node_modules/@usejunior/docx-core/dist/primitives/reject_changes.js +371 -0
  196. package/node_modules/@usejunior/docx-core/dist/primitives/reject_changes.js.map +1 -0
  197. package/node_modules/@usejunior/docx-core/dist/primitives/relationships.d.ts +7 -0
  198. package/node_modules/@usejunior/docx-core/dist/primitives/relationships.d.ts.map +1 -0
  199. package/node_modules/@usejunior/docx-core/dist/primitives/relationships.js +24 -0
  200. package/node_modules/@usejunior/docx-core/dist/primitives/relationships.js.map +1 -0
  201. package/node_modules/@usejunior/docx-core/dist/primitives/semantic_tags.d.ts +17 -0
  202. package/node_modules/@usejunior/docx-core/dist/primitives/semantic_tags.d.ts.map +1 -0
  203. package/node_modules/@usejunior/docx-core/dist/primitives/semantic_tags.js +58 -0
  204. package/node_modules/@usejunior/docx-core/dist/primitives/semantic_tags.js.map +1 -0
  205. package/node_modules/@usejunior/docx-core/dist/primitives/simplify_redlines.d.ts +19 -0
  206. package/node_modules/@usejunior/docx-core/dist/primitives/simplify_redlines.d.ts.map +1 -0
  207. package/node_modules/@usejunior/docx-core/dist/primitives/simplify_redlines.js +94 -0
  208. package/node_modules/@usejunior/docx-core/dist/primitives/simplify_redlines.js.map +1 -0
  209. package/node_modules/@usejunior/docx-core/dist/primitives/styles.d.ts +36 -0
  210. package/node_modules/@usejunior/docx-core/dist/primitives/styles.d.ts.map +1 -0
  211. package/node_modules/@usejunior/docx-core/dist/primitives/styles.js +205 -0
  212. package/node_modules/@usejunior/docx-core/dist/primitives/styles.js.map +1 -0
  213. package/node_modules/@usejunior/docx-core/dist/primitives/tables.d.ts +54 -0
  214. package/node_modules/@usejunior/docx-core/dist/primitives/tables.d.ts.map +1 -0
  215. package/node_modules/@usejunior/docx-core/dist/primitives/tables.js +205 -0
  216. package/node_modules/@usejunior/docx-core/dist/primitives/tables.js.map +1 -0
  217. package/node_modules/@usejunior/docx-core/dist/primitives/text.d.ts +30 -0
  218. package/node_modules/@usejunior/docx-core/dist/primitives/text.d.ts.map +1 -0
  219. package/node_modules/@usejunior/docx-core/dist/primitives/text.js +461 -0
  220. package/node_modules/@usejunior/docx-core/dist/primitives/text.js.map +1 -0
  221. package/node_modules/@usejunior/docx-core/dist/primitives/validate_document.d.ts +24 -0
  222. package/node_modules/@usejunior/docx-core/dist/primitives/validate_document.d.ts.map +1 -0
  223. package/node_modules/@usejunior/docx-core/dist/primitives/validate_document.js +147 -0
  224. package/node_modules/@usejunior/docx-core/dist/primitives/validate_document.js.map +1 -0
  225. package/node_modules/@usejunior/docx-core/dist/primitives/xml.d.ts +5 -0
  226. package/node_modules/@usejunior/docx-core/dist/primitives/xml.d.ts.map +1 -0
  227. package/node_modules/@usejunior/docx-core/dist/primitives/xml.js +19 -0
  228. package/node_modules/@usejunior/docx-core/dist/primitives/xml.js.map +1 -0
  229. package/node_modules/@usejunior/docx-core/dist/primitives/zip.d.ts +25 -0
  230. package/node_modules/@usejunior/docx-core/dist/primitives/zip.d.ts.map +1 -0
  231. package/node_modules/@usejunior/docx-core/dist/primitives/zip.js +78 -0
  232. package/node_modules/@usejunior/docx-core/dist/primitives/zip.js.map +1 -0
  233. package/node_modules/@usejunior/docx-core/dist/shared/docx/DocxArchive.d.ts +94 -0
  234. package/node_modules/@usejunior/docx-core/dist/shared/docx/DocxArchive.d.ts.map +1 -0
  235. package/node_modules/@usejunior/docx-core/dist/shared/docx/DocxArchive.js +169 -0
  236. package/node_modules/@usejunior/docx-core/dist/shared/docx/DocxArchive.js.map +1 -0
  237. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/namespaces.d.ts +149 -0
  238. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/namespaces.d.ts.map +1 -0
  239. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/namespaces.js +224 -0
  240. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/namespaces.js.map +1 -0
  241. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/types.d.ts +136 -0
  242. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/types.d.ts.map +1 -0
  243. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/types.js +7 -0
  244. package/node_modules/@usejunior/docx-core/dist/shared/ooxml/types.js.map +1 -0
  245. package/node_modules/@usejunior/docx-core/dist/shared/validators/structural.d.ts +31 -0
  246. package/node_modules/@usejunior/docx-core/dist/shared/validators/structural.d.ts.map +1 -0
  247. package/node_modules/@usejunior/docx-core/dist/shared/validators/structural.js +110 -0
  248. package/node_modules/@usejunior/docx-core/dist/shared/validators/structural.js.map +1 -0
  249. package/node_modules/@usejunior/docx-core/package.json +26 -0
  250. package/node_modules/core-util-is/LICENSE +19 -0
  251. package/node_modules/core-util-is/README.md +3 -0
  252. package/node_modules/core-util-is/lib/util.js +107 -0
  253. package/node_modules/core-util-is/package.json +38 -0
  254. package/node_modules/diff-match-patch/LICENSE +202 -0
  255. package/node_modules/diff-match-patch/README.md +94 -0
  256. package/node_modules/diff-match-patch/index.js +2218 -0
  257. package/node_modules/diff-match-patch/package.json +22 -0
  258. package/node_modules/immediate/LICENSE.txt +20 -0
  259. package/node_modules/immediate/README.md +93 -0
  260. package/node_modules/immediate/dist/immediate.js +75 -0
  261. package/node_modules/immediate/dist/immediate.min.js +1 -0
  262. package/node_modules/immediate/lib/browser.js +69 -0
  263. package/node_modules/immediate/lib/index.js +73 -0
  264. package/node_modules/immediate/package.json +42 -0
  265. package/node_modules/inherits/LICENSE +16 -0
  266. package/node_modules/inherits/README.md +42 -0
  267. package/node_modules/inherits/inherits.js +9 -0
  268. package/node_modules/inherits/inherits_browser.js +27 -0
  269. package/node_modules/inherits/package.json +29 -0
  270. package/node_modules/isarray/.npmignore +1 -0
  271. package/node_modules/isarray/.travis.yml +4 -0
  272. package/node_modules/isarray/Makefile +6 -0
  273. package/node_modules/isarray/README.md +60 -0
  274. package/node_modules/isarray/component.json +19 -0
  275. package/node_modules/isarray/index.js +5 -0
  276. package/node_modules/isarray/package.json +45 -0
  277. package/node_modules/isarray/test.js +20 -0
  278. package/node_modules/jszip/.codeclimate.yml +16 -0
  279. package/node_modules/jszip/.editorconfig +8 -0
  280. package/node_modules/jszip/.eslintrc.js +43 -0
  281. package/node_modules/jszip/.github/workflows/pr.yaml +58 -0
  282. package/node_modules/jszip/.jekyll-metadata +0 -0
  283. package/node_modules/jszip/.travis.yml +17 -0
  284. package/node_modules/jszip/CHANGES.md +204 -0
  285. package/node_modules/jszip/LICENSE.markdown +651 -0
  286. package/node_modules/jszip/README.markdown +33 -0
  287. package/node_modules/jszip/deps.js +37 -0
  288. package/node_modules/jszip/dist/jszip.js +11577 -0
  289. package/node_modules/jszip/dist/jszip.min.js +13 -0
  290. package/node_modules/jszip/graph.svg +601 -0
  291. package/node_modules/jszip/index.d.ts +330 -0
  292. package/node_modules/jszip/lib/base64.js +106 -0
  293. package/node_modules/jszip/lib/compressedObject.js +74 -0
  294. package/node_modules/jszip/lib/compressions.js +14 -0
  295. package/node_modules/jszip/lib/crc32.js +77 -0
  296. package/node_modules/jszip/lib/defaults.js +11 -0
  297. package/node_modules/jszip/lib/external.js +18 -0
  298. package/node_modules/jszip/lib/flate.js +85 -0
  299. package/node_modules/jszip/lib/generate/ZipFileWorker.js +539 -0
  300. package/node_modules/jszip/lib/generate/index.js +57 -0
  301. package/node_modules/jszip/lib/index.js +55 -0
  302. package/node_modules/jszip/lib/license_header.js +11 -0
  303. package/node_modules/jszip/lib/load.js +88 -0
  304. package/node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +74 -0
  305. package/node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +42 -0
  306. package/node_modules/jszip/lib/nodejsUtils.js +57 -0
  307. package/node_modules/jszip/lib/object.js +384 -0
  308. package/node_modules/jszip/lib/readable-stream-browser.js +10 -0
  309. package/node_modules/jszip/lib/reader/ArrayReader.js +57 -0
  310. package/node_modules/jszip/lib/reader/DataReader.js +116 -0
  311. package/node_modules/jszip/lib/reader/NodeBufferReader.js +19 -0
  312. package/node_modules/jszip/lib/reader/StringReader.js +38 -0
  313. package/node_modules/jszip/lib/reader/Uint8ArrayReader.js +22 -0
  314. package/node_modules/jszip/lib/reader/readerFor.js +28 -0
  315. package/node_modules/jszip/lib/signature.js +7 -0
  316. package/node_modules/jszip/lib/stream/ConvertWorker.js +26 -0
  317. package/node_modules/jszip/lib/stream/Crc32Probe.js +24 -0
  318. package/node_modules/jszip/lib/stream/DataLengthProbe.js +29 -0
  319. package/node_modules/jszip/lib/stream/DataWorker.js +116 -0
  320. package/node_modules/jszip/lib/stream/GenericWorker.js +263 -0
  321. package/node_modules/jszip/lib/stream/StreamHelper.js +214 -0
  322. package/node_modules/jszip/lib/support.js +38 -0
  323. package/node_modules/jszip/lib/utf8.js +275 -0
  324. package/node_modules/jszip/lib/utils.js +501 -0
  325. package/node_modules/jszip/lib/zipEntries.js +261 -0
  326. package/node_modules/jszip/lib/zipEntry.js +293 -0
  327. package/node_modules/jszip/lib/zipObject.js +133 -0
  328. package/node_modules/jszip/package.json +67 -0
  329. package/node_modules/jszip/sponsors.md +21 -0
  330. package/node_modules/jszip/tsconfig.json +101 -0
  331. package/node_modules/jszip/vendor/FileSaver.js +247 -0
  332. package/node_modules/lie/README.md +62 -0
  333. package/node_modules/lie/dist/lie.js +350 -0
  334. package/node_modules/lie/dist/lie.min.js +1 -0
  335. package/node_modules/lie/dist/lie.polyfill.js +358 -0
  336. package/node_modules/lie/dist/lie.polyfill.min.js +1 -0
  337. package/node_modules/lie/lib/browser.js +273 -0
  338. package/node_modules/lie/lib/index.js +298 -0
  339. package/node_modules/lie/license.md +7 -0
  340. package/node_modules/lie/lie.d.ts +244 -0
  341. package/node_modules/lie/package.json +69 -0
  342. package/node_modules/lie/polyfill.js +4 -0
  343. package/node_modules/pako/LICENSE +21 -0
  344. package/node_modules/pako/README.md +191 -0
  345. package/node_modules/pako/dist/pako.js +6818 -0
  346. package/node_modules/pako/dist/pako.min.js +1 -0
  347. package/node_modules/pako/dist/pako_deflate.js +3997 -0
  348. package/node_modules/pako/dist/pako_deflate.min.js +1 -0
  349. package/node_modules/pako/dist/pako_inflate.js +3300 -0
  350. package/node_modules/pako/dist/pako_inflate.min.js +1 -0
  351. package/node_modules/pako/index.js +14 -0
  352. package/node_modules/pako/lib/deflate.js +400 -0
  353. package/node_modules/pako/lib/inflate.js +423 -0
  354. package/node_modules/pako/lib/utils/common.js +105 -0
  355. package/node_modules/pako/lib/utils/strings.js +187 -0
  356. package/node_modules/pako/lib/zlib/README +59 -0
  357. package/node_modules/pako/lib/zlib/adler32.js +51 -0
  358. package/node_modules/pako/lib/zlib/constants.js +68 -0
  359. package/node_modules/pako/lib/zlib/crc32.js +59 -0
  360. package/node_modules/pako/lib/zlib/deflate.js +1874 -0
  361. package/node_modules/pako/lib/zlib/gzheader.js +58 -0
  362. package/node_modules/pako/lib/zlib/inffast.js +345 -0
  363. package/node_modules/pako/lib/zlib/inflate.js +1556 -0
  364. package/node_modules/pako/lib/zlib/inftrees.js +343 -0
  365. package/node_modules/pako/lib/zlib/messages.js +32 -0
  366. package/node_modules/pako/lib/zlib/trees.js +1222 -0
  367. package/node_modules/pako/lib/zlib/zstream.js +47 -0
  368. package/node_modules/pako/package.json +44 -0
  369. package/node_modules/process-nextick-args/index.js +45 -0
  370. package/node_modules/process-nextick-args/license.md +19 -0
  371. package/node_modules/process-nextick-args/package.json +25 -0
  372. package/node_modules/process-nextick-args/readme.md +18 -0
  373. package/node_modules/readable-stream/.travis.yml +34 -0
  374. package/node_modules/readable-stream/CONTRIBUTING.md +38 -0
  375. package/node_modules/readable-stream/GOVERNANCE.md +136 -0
  376. package/node_modules/readable-stream/LICENSE +47 -0
  377. package/node_modules/readable-stream/README.md +58 -0
  378. package/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md +60 -0
  379. package/node_modules/readable-stream/duplex-browser.js +1 -0
  380. package/node_modules/readable-stream/duplex.js +1 -0
  381. package/node_modules/readable-stream/lib/_stream_duplex.js +131 -0
  382. package/node_modules/readable-stream/lib/_stream_passthrough.js +47 -0
  383. package/node_modules/readable-stream/lib/_stream_readable.js +1019 -0
  384. package/node_modules/readable-stream/lib/_stream_transform.js +214 -0
  385. package/node_modules/readable-stream/lib/_stream_writable.js +685 -0
  386. package/node_modules/readable-stream/lib/internal/streams/BufferList.js +78 -0
  387. package/node_modules/readable-stream/lib/internal/streams/destroy.js +84 -0
  388. package/node_modules/readable-stream/lib/internal/streams/stream-browser.js +1 -0
  389. package/node_modules/readable-stream/lib/internal/streams/stream.js +1 -0
  390. package/node_modules/readable-stream/package.json +52 -0
  391. package/node_modules/readable-stream/passthrough.js +1 -0
  392. package/node_modules/readable-stream/readable-browser.js +7 -0
  393. package/node_modules/readable-stream/readable.js +19 -0
  394. package/node_modules/readable-stream/transform.js +1 -0
  395. package/node_modules/readable-stream/writable-browser.js +1 -0
  396. package/node_modules/readable-stream/writable.js +8 -0
  397. package/node_modules/safe-buffer/LICENSE +21 -0
  398. package/node_modules/safe-buffer/README.md +584 -0
  399. package/node_modules/safe-buffer/index.d.ts +187 -0
  400. package/node_modules/safe-buffer/index.js +62 -0
  401. package/node_modules/safe-buffer/package.json +37 -0
  402. package/node_modules/setimmediate/LICENSE.txt +20 -0
  403. package/node_modules/setimmediate/package.json +30 -0
  404. package/node_modules/setimmediate/setImmediate.js +186 -0
  405. package/node_modules/string_decoder/.travis.yml +50 -0
  406. package/node_modules/string_decoder/LICENSE +48 -0
  407. package/node_modules/string_decoder/README.md +47 -0
  408. package/node_modules/string_decoder/lib/string_decoder.js +296 -0
  409. package/node_modules/string_decoder/package.json +31 -0
  410. package/node_modules/util-deprecate/History.md +16 -0
  411. package/node_modules/util-deprecate/LICENSE +24 -0
  412. package/node_modules/util-deprecate/README.md +53 -0
  413. package/node_modules/util-deprecate/browser.js +67 -0
  414. package/node_modules/util-deprecate/node.js +6 -0
  415. package/node_modules/util-deprecate/package.json +27 -0
  416. package/package.json +9 -4
  417. package/packages/docx-core/node_modules/@xmldom/xmldom/CHANGELOG.md +468 -0
  418. package/packages/docx-core/node_modules/@xmldom/xmldom/LICENSE +8 -0
  419. package/packages/docx-core/node_modules/@xmldom/xmldom/SECURITY.md +50 -0
  420. package/packages/docx-core/node_modules/@xmldom/xmldom/index.d.ts +43 -0
  421. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/.eslintrc.yml +2 -0
  422. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/conventions.js +203 -0
  423. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/dom-parser.js +322 -0
  424. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/dom.js +1879 -0
  425. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/entities.js +2166 -0
  426. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/index.js +4 -0
  427. package/packages/docx-core/node_modules/@xmldom/xmldom/lib/sax.js +662 -0
  428. package/packages/docx-core/node_modules/@xmldom/xmldom/package.json +71 -0
  429. package/packages/docx-core/node_modules/@xmldom/xmldom/readme.md +356 -0
@@ -0,0 +1,2279 @@
1
+ /**
2
+ * In-Place AST Modifier
3
+ *
4
+ * Modifies the revised document's AST in-place to add track changes markup.
5
+ * This replaces the reconstruction-based approach with direct tree manipulation.
6
+ *
7
+ * Key operations:
8
+ * - wrapAsInserted: Wrap run elements with <w:ins> for inserted content
9
+ * - insertDeletedContent: Clone and insert deleted content with <w:del> wrapper
10
+ * - wrapAsMoveFrom/wrapAsMoveTo: Add move tracking with range markers
11
+ * - addFormatChange: Add <w:rPrChange> for formatting differences
12
+ */
13
+ import { CorrelationStatus } from '../../core-types.js';
14
+ import { EMPTY_PARAGRAPH_TAG } from '../../atomizer.js';
15
+ import { getLeafText, childElements, findChildByTagName, insertAfterElement, wrapElement, unwrapElement, splitRunAtVisibleOffset, visibleLengthForEl, getDirectContentElements, } from '../../primitives/index.js';
16
+ import { areRunPropertiesEqual } from '../../format-detection.js';
17
+ import { enforceConsumerCompatibility } from './consumerCompatibility.js';
18
+ import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
19
+ import { warn } from './debug.js';
20
+ const SYNTHETIC_DOC = new DOMParser().parseFromString('<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>', 'application/xml');
21
+ const W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
22
+ /**
23
+ * Create a namespaced OOXML element with optional attributes.
24
+ * Uses SYNTHETIC_DOC so elements can be adopted by any document tree.
25
+ */
26
+ function createEl(tag, attrs) {
27
+ const el = SYNTHETIC_DOC.createElementNS(W_NS, tag);
28
+ if (attrs)
29
+ for (const [k, v] of Object.entries(attrs))
30
+ el.setAttribute(k, v);
31
+ return el;
32
+ }
33
+ function findAncestorByTag(atom, tagName) {
34
+ for (let i = atom.ancestorElements.length - 1; i >= 0; i--) {
35
+ const el = atom.ancestorElements[i];
36
+ if (el.tagName === tagName)
37
+ return el;
38
+ }
39
+ return undefined;
40
+ }
41
+ function attachSourceElementPointers(atoms) {
42
+ for (const atom of atoms) {
43
+ atom.sourceRunElement = findAncestorByTag(atom, 'w:r');
44
+ atom.sourceParagraphElement = findAncestorByTag(atom, 'w:p');
45
+ }
46
+ }
47
+ /**
48
+ * Determine whether an atom is "whitespace-only" for paragraph-level classification.
49
+ *
50
+ * We treat pure whitespace runs/tabs/breaks as ignorable noise, because LCS alignment
51
+ * can mark them Equal even when a whole paragraph was inserted/deleted. If we don't
52
+ * ignore them, Word can end up with a stub paragraph after Accept/Reject All.
53
+ */
54
+ function isWhitespaceAtom(atom) {
55
+ const el = atom.contentElement;
56
+ if (el.tagName === EMPTY_PARAGRAPH_TAG)
57
+ return true;
58
+ if (el.tagName === 'w:t')
59
+ return ((getLeafText(el) ?? '').trim() === '');
60
+ return el.tagName === 'w:tab' || el.tagName === 'w:br' || el.tagName === 'w:cr';
61
+ }
62
+ /**
63
+ * Returns true if every non-empty atom in this paragraph is of the specified status,
64
+ * ignoring whitespace-only atoms.
65
+ *
66
+ * Mirrors the rebuild reconstructor's whole-paragraph classification so that inplace
67
+ * output behaves the same under Word's Accept/Reject All.
68
+ */
69
+ function isEntireParagraphAtomsWithStatus(atoms, status) {
70
+ let sawAnyContent = false;
71
+ let sawTargetStatus = false;
72
+ for (const atom of atoms) {
73
+ const el = atom.contentElement;
74
+ if (el.tagName === EMPTY_PARAGRAPH_TAG)
75
+ continue;
76
+ sawAnyContent = true;
77
+ if (atom.correlationStatus === status) {
78
+ sawTargetStatus = true;
79
+ continue;
80
+ }
81
+ if (isWhitespaceAtom(atom))
82
+ continue;
83
+ return false;
84
+ }
85
+ return sawAnyContent && sawTargetStatus;
86
+ }
87
+ /**
88
+ * Create initial revision ID state.
89
+ */
90
+ function createRevisionIdState() {
91
+ return {
92
+ nextId: 1,
93
+ moveRangeIds: new Map(),
94
+ wrappedRuns: new Set(),
95
+ emittedSourceBookmarkMarkers: new Set(),
96
+ };
97
+ }
98
+ /**
99
+ * Allocate a new revision ID.
100
+ */
101
+ function allocateRevisionId(state) {
102
+ return state.nextId++;
103
+ }
104
+ /**
105
+ * Get or allocate move range IDs for a move name.
106
+ */
107
+ function getMoveRangeIds(state, moveName) {
108
+ let ids = state.moveRangeIds.get(moveName);
109
+ if (!ids) {
110
+ ids = {
111
+ sourceRangeId: allocateRevisionId(state),
112
+ destRangeId: allocateRevisionId(state),
113
+ };
114
+ state.moveRangeIds.set(moveName, ids);
115
+ }
116
+ return ids;
117
+ }
118
+ /**
119
+ * Format date for OOXML (ISO 8601 without milliseconds).
120
+ */
121
+ function formatDate(date) {
122
+ return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
123
+ }
124
+ /**
125
+ * Convert w:t elements to w:delText within an element tree.
126
+ *
127
+ * @param element - The element to process
128
+ */
129
+ function convertToDelText(element) {
130
+ if (element.tagName === 'w:t' || element.tagName === 'w:instrText') {
131
+ const newTag = element.tagName === 'w:t' ? 'w:delText' : 'w:delInstrText';
132
+ const newEl = createEl(newTag);
133
+ // Copy text content
134
+ while (element.firstChild)
135
+ newEl.appendChild(element.firstChild);
136
+ // Copy attributes
137
+ for (let i = 0; i < element.attributes.length; i++) {
138
+ const attr = element.attributes[i];
139
+ newEl.setAttribute(attr.name, attr.value);
140
+ }
141
+ element.parentNode?.replaceChild(newEl, element);
142
+ return;
143
+ }
144
+ for (const child of childElements(element)) {
145
+ convertToDelText(child);
146
+ }
147
+ }
148
+ /**
149
+ * Build the content elements that should be inserted for an atom.
150
+ *
151
+ * Collapsed field atoms use a synthetic w:t as their top-level contentElement,
152
+ * but retain the original field sequence in collapsedFieldAtoms. For insertion,
153
+ * we must replay the original sequence rather than the synthetic text.
154
+ *
155
+ * @param filterRun - When provided, only return content elements whose
156
+ * collapsed field atom belongs to this specific source run. Used by
157
+ * insertDeletedRun/insertMoveFromRun to emit one cloned run per original
158
+ * source run, preserving multi-run field structure.
159
+ */
160
+ function getInsertableAtomContentElements(atom, filterRun) {
161
+ if (atom.collapsedFieldAtoms && atom.collapsedFieldAtoms.length > 0) {
162
+ if (filterRun) {
163
+ return atom.collapsedFieldAtoms
164
+ .filter((fieldAtom) => {
165
+ const run = fieldAtom.sourceRunElement ?? findAncestorByTag(fieldAtom, 'w:r');
166
+ return run === filterRun;
167
+ })
168
+ .map((fieldAtom) => fieldAtom.contentElement);
169
+ }
170
+ return atom.collapsedFieldAtoms.map((fieldAtom) => fieldAtom.contentElement);
171
+ }
172
+ return [atom.contentElement];
173
+ }
174
+ /**
175
+ * Clone a source run and replace its non-rPr children with atom content.
176
+ *
177
+ * This keeps run-level formatting while allowing atom-level fragment insertion.
178
+ *
179
+ * @param filterRun - When provided, only include content elements belonging
180
+ * to this source run (for multi-run collapsed field replay).
181
+ */
182
+ function cloneRunWithAtomContent(sourceRun, atom, filterRun) {
183
+ const clonedRun = sourceRun.cloneNode(true);
184
+ const retainedChildren = [];
185
+ for (const child of childElements(clonedRun)) {
186
+ if (child.tagName === 'w:rPr') {
187
+ retainedChildren.push(child);
188
+ }
189
+ }
190
+ // Remove all current children from clonedRun
191
+ while (clonedRun.firstChild)
192
+ clonedRun.removeChild(clonedRun.firstChild);
193
+ // Re-append retained rPr children
194
+ for (const child of retainedChildren) {
195
+ clonedRun.appendChild(child);
196
+ }
197
+ for (const contentElement of getInsertableAtomContentElements(atom, filterRun)) {
198
+ const fragment = contentElement.cloneNode(true);
199
+ clonedRun.appendChild(fragment);
200
+ }
201
+ return clonedRun;
202
+ }
203
+ function cloneParagraphBoundaryBookmarkMarkers(sourceParagraph) {
204
+ const kids = sourceParagraph ? childElements(sourceParagraph) : [];
205
+ if (!sourceParagraph || kids.length === 0) {
206
+ return { leading: [], trailing: [], sourceLeading: [], sourceTrailing: [] };
207
+ }
208
+ const children = kids;
209
+ let firstRunIdx = -1;
210
+ let lastRunIdx = -1;
211
+ for (let i = 0; i < children.length; i++) {
212
+ if (children[i]?.tagName === 'w:r') {
213
+ if (firstRunIdx < 0)
214
+ firstRunIdx = i;
215
+ lastRunIdx = i;
216
+ }
217
+ }
218
+ const leading = [];
219
+ const trailing = [];
220
+ const sourceLeading = [];
221
+ const sourceTrailing = [];
222
+ for (let i = 0; i < children.length; i++) {
223
+ const child = children[i];
224
+ if (child.tagName === 'w:bookmarkStart') {
225
+ if (firstRunIdx < 0 || i < firstRunIdx) {
226
+ const cloned = child.cloneNode(true);
227
+ leading.push(cloned);
228
+ sourceLeading.push(child);
229
+ }
230
+ continue;
231
+ }
232
+ if (child.tagName === 'w:bookmarkEnd') {
233
+ if (lastRunIdx < 0 || i > lastRunIdx) {
234
+ const cloned = child.cloneNode(true);
235
+ trailing.push(cloned);
236
+ sourceTrailing.push(child);
237
+ }
238
+ }
239
+ }
240
+ return { leading, trailing, sourceLeading, sourceTrailing };
241
+ }
242
+ function insertLeadingMarkers(paragraph, markers) {
243
+ if (markers.length === 0)
244
+ return null;
245
+ const pPr = findChildByTagName(paragraph, 'w:pPr');
246
+ if (pPr) {
247
+ let anchor = pPr;
248
+ for (const marker of markers) {
249
+ insertAfterElement(anchor, marker);
250
+ anchor = marker;
251
+ }
252
+ return anchor;
253
+ }
254
+ for (let i = markers.length - 1; i >= 0; i--) {
255
+ paragraph.insertBefore(markers[i], paragraph.firstChild);
256
+ }
257
+ return markers[markers.length - 1] ?? null;
258
+ }
259
+ function isBookmarkMarkerTag(tagName) {
260
+ return tagName === 'w:bookmarkStart' || tagName === 'w:bookmarkEnd';
261
+ }
262
+ /**
263
+ * Collect direct paragraph bookmark markers adjacent to a source run.
264
+ *
265
+ * Markers between runs (or at paragraph boundaries) are represented as siblings
266
+ * of w:r under w:p. We clone nearby markers so reconstructed deleted/moveFrom
267
+ * fragments preserve bookmark names/IDs needed for Reject All parity.
268
+ */
269
+ function collectAdjacentSourceBookmarkMarkers(sourceRun) {
270
+ const paragraph = sourceRun.parentNode;
271
+ if (!paragraph || paragraph.tagName !== 'w:p') {
272
+ return [];
273
+ }
274
+ const children = childElements(paragraph);
275
+ const runIndex = children.indexOf(sourceRun);
276
+ if (runIndex < 0) {
277
+ return [];
278
+ }
279
+ const before = [];
280
+ for (let i = runIndex - 1; i >= 0; i--) {
281
+ const child = children[i];
282
+ if (!child)
283
+ break;
284
+ if (child.tagName === 'w:r')
285
+ break;
286
+ if (isBookmarkMarkerTag(child.tagName)) {
287
+ before.unshift(child);
288
+ }
289
+ }
290
+ const after = [];
291
+ for (let i = runIndex + 1; i < children.length; i++) {
292
+ const child = children[i];
293
+ if (!child)
294
+ break;
295
+ if (child.tagName === 'w:r')
296
+ break;
297
+ if (isBookmarkMarkerTag(child.tagName)) {
298
+ after.push(child);
299
+ }
300
+ }
301
+ return [...before, ...after];
302
+ }
303
+ function parentElement(node) {
304
+ const p = node.parentNode;
305
+ return p && p.nodeType === 1 ? p : null;
306
+ }
307
+ function findTreeRoot(node) {
308
+ let current = node;
309
+ let parent = parentElement(current);
310
+ while (parent) {
311
+ current = parent;
312
+ parent = parentElement(current);
313
+ }
314
+ return current;
315
+ }
316
+ function findAncestor(node, tagName) {
317
+ let current = node ?? null;
318
+ while (current) {
319
+ if (current.tagName === tagName)
320
+ return current;
321
+ current = parentElement(current);
322
+ }
323
+ return undefined;
324
+ }
325
+ function hasAncestorTag(node, tagNames) {
326
+ let current = node ? parentElement(node) : null;
327
+ while (current) {
328
+ if (tagNames.has(current.tagName)) {
329
+ return true;
330
+ }
331
+ current = parentElement(current);
332
+ }
333
+ return false;
334
+ }
335
+ function paragraphHasParaInsMarker(paragraph) {
336
+ if (!paragraph || paragraph.tagName !== 'w:p') {
337
+ return false;
338
+ }
339
+ const pPr = findChildByTagName(paragraph, 'w:pPr');
340
+ if (!pPr) {
341
+ return false;
342
+ }
343
+ return Array.from(pPr.getElementsByTagName('w:ins')).length > 0;
344
+ }
345
+ function markerSurvivesReject(marker, context) {
346
+ // Markers nested in inserted/move-to content are removed by Reject All.
347
+ if (hasAncestorTag(marker, new Set(['w:ins', 'w:moveTo']))) {
348
+ return false;
349
+ }
350
+ // Paragraph-level insertion markers remove whole paragraphs on Reject All.
351
+ const paragraph = findAncestor(marker, 'w:p');
352
+ if (paragraph && context?.isParagraphRemovedOnReject?.(paragraph)) {
353
+ return false;
354
+ }
355
+ if (paragraphHasParaInsMarker(paragraph)) {
356
+ return false;
357
+ }
358
+ return true;
359
+ }
360
+ function targetTreeHasEquivalentBookmarkMarker(targetParagraph, marker, context) {
361
+ const treeRoot = findTreeRoot(targetParagraph);
362
+ if (marker.tagName === 'w:bookmarkStart') {
363
+ const markerId = marker.getAttribute('w:id');
364
+ const markerName = marker.getAttribute('w:name');
365
+ for (const existing of Array.from(treeRoot.getElementsByTagName('w:bookmarkStart'))) {
366
+ if (!markerSurvivesReject(existing, context)) {
367
+ continue;
368
+ }
369
+ const existingName = existing.getAttribute('w:name');
370
+ const existingId = existing.getAttribute('w:id');
371
+ if (markerName && existingName === markerName)
372
+ return true;
373
+ if (!markerName && markerId && existingId === markerId)
374
+ return true;
375
+ }
376
+ return false;
377
+ }
378
+ if (marker.tagName === 'w:bookmarkEnd') {
379
+ const markerId = marker.getAttribute('w:id');
380
+ if (!markerId)
381
+ return false;
382
+ for (const existing of Array.from(treeRoot.getElementsByTagName('w:bookmarkEnd'))) {
383
+ if (!markerSurvivesReject(existing, context)) {
384
+ continue;
385
+ }
386
+ if (existing.getAttribute('w:id') === markerId)
387
+ return true;
388
+ }
389
+ }
390
+ return false;
391
+ }
392
+ function cloneUnemittedSourceBookmarkMarkers(sourceRun, targetParagraph, state, context) {
393
+ const markers = collectAdjacentSourceBookmarkMarkers(sourceRun);
394
+ const clones = [];
395
+ for (const marker of markers) {
396
+ if (state.emittedSourceBookmarkMarkers.has(marker)) {
397
+ continue;
398
+ }
399
+ if (targetTreeHasEquivalentBookmarkMarker(targetParagraph, marker, context)) {
400
+ state.emittedSourceBookmarkMarkers.add(marker);
401
+ continue;
402
+ }
403
+ state.emittedSourceBookmarkMarkers.add(marker);
404
+ const cloned = marker.cloneNode(true);
405
+ clones.push(cloned);
406
+ }
407
+ return clones;
408
+ }
409
+ function insertMarkersBeforeWrapper(wrapper, markers) {
410
+ const parent = wrapper.parentNode;
411
+ if (!parent)
412
+ return;
413
+ for (const marker of markers) {
414
+ if (!marker)
415
+ continue;
416
+ parent.insertBefore(marker, wrapper);
417
+ }
418
+ }
419
+ function filterEquivalentBookmarkMarkers(markers, targetNode, context) {
420
+ return markers.filter((marker) => !targetTreeHasEquivalentBookmarkMarker(targetNode, marker, context));
421
+ }
422
+ const TRACK_CHANGE_WRAPPERS = new Set([
423
+ 'w:ins',
424
+ 'w:del',
425
+ 'w:moveFrom',
426
+ 'w:moveTo',
427
+ ]);
428
+ /**
429
+ * Resolve the run associated with an atom boundary.
430
+ *
431
+ * For collapsed field atoms, sourceRunElement points at the first run in the
432
+ * field sequence. For insertion-point tracking we often need the trailing run,
433
+ * otherwise deleted/moved fragments can be inserted inside the field sequence.
434
+ */
435
+ function getAtomRunAtBoundary(atom, boundary) {
436
+ if (atom.collapsedFieldAtoms && atom.collapsedFieldAtoms.length > 0) {
437
+ const fieldAtoms = boundary === 'start'
438
+ ? atom.collapsedFieldAtoms
439
+ : [...atom.collapsedFieldAtoms].reverse();
440
+ for (const fieldAtom of fieldAtoms) {
441
+ const run = fieldAtom.sourceRunElement ?? findAncestorByTag(fieldAtom, 'w:r');
442
+ if (run)
443
+ return run;
444
+ }
445
+ }
446
+ return atom.sourceRunElement ?? findAncestorByTag(atom, 'w:r');
447
+ }
448
+ /**
449
+ * Resolve all run elements represented by an atom.
450
+ *
451
+ * For collapsed-field atoms, we must treat the entire field run sequence as a
452
+ * single logical unit. Wrapping only the first run leaves trailing field-code
453
+ * runs untracked, which can leak revised field text after Reject All.
454
+ */
455
+ function getAtomRuns(atom) {
456
+ if (!atom.collapsedFieldAtoms || atom.collapsedFieldAtoms.length === 0) {
457
+ const run = atom.sourceRunElement ?? findAncestorByTag(atom, 'w:r');
458
+ return run ? [run] : [];
459
+ }
460
+ const runs = [];
461
+ const seen = new Set();
462
+ for (const fieldAtom of atom.collapsedFieldAtoms) {
463
+ const run = fieldAtom.sourceRunElement ?? findAncestorByTag(fieldAtom, 'w:r');
464
+ if (!run || seen.has(run))
465
+ continue;
466
+ seen.add(run);
467
+ runs.push(run);
468
+ }
469
+ return runs;
470
+ }
471
+ /**
472
+ * Convert a run node to the correct insertion anchor.
473
+ *
474
+ * If the run is wrapped in a track-change container, the insertion anchor
475
+ * must be the wrapper (a paragraph child), not the nested run.
476
+ */
477
+ function getRunInsertionAnchor(run) {
478
+ const parent = parentElement(run);
479
+ if (parent && TRACK_CHANGE_WRAPPERS.has(parent.tagName)) {
480
+ return parent;
481
+ }
482
+ return run;
483
+ }
484
+ /**
485
+ * Wrap a run element with track change markup.
486
+ *
487
+ * This is the shared implementation for wrapAsInserted, wrapAsDeleted,
488
+ * and the inner wrapping logic of move operations.
489
+ *
490
+ * @param options - Wrapping options
491
+ * @returns true if wrapped, false if run was already wrapped or has no parent
492
+ */
493
+ function wrapRunWithTrackChange(options) {
494
+ const { run, tagName, author, dateStr, state, convertTextToDelText: convertText = false } = options;
495
+ // Skip if already wrapped
496
+ if (state.wrappedRuns.has(run)) {
497
+ return false;
498
+ }
499
+ // Skip if the run has no parent in the tree
500
+ if (!run.parentNode) {
501
+ return false;
502
+ }
503
+ // Convert w:t to w:delText if requested (for deleted content)
504
+ if (convertText) {
505
+ convertToDelText(run);
506
+ }
507
+ const id = allocateRevisionId(state);
508
+ const wrapper = createEl(tagName, {
509
+ 'w:id': String(id),
510
+ 'w:author': author,
511
+ 'w:date': dateStr,
512
+ });
513
+ wrapElement(run, wrapper);
514
+ state.wrappedRuns.add(run);
515
+ return true;
516
+ }
517
+ /**
518
+ * Ensure w:pPr/w:rPr exists and add a paragraph-mark revision marker (w:ins/w:del)
519
+ * in the paragraph properties.
520
+ *
521
+ * This is the critical piece for whole-paragraph insert/delete idempotency:
522
+ * - Reject All should remove inserted paragraphs entirely (no stub breaks)
523
+ * - Accept All should remove deleted paragraphs entirely
524
+ */
525
+ function addParagraphMarkRevisionMarker(paragraph, markerTag, author, dateStr, state) {
526
+ // Find or create pPr.
527
+ let pPr = findChildByTagName(paragraph, 'w:pPr');
528
+ if (!pPr) {
529
+ pPr = createEl('w:pPr');
530
+ // pPr should be the first child in a paragraph.
531
+ paragraph.insertBefore(pPr, paragraph.firstChild);
532
+ }
533
+ // Find or create rPr within pPr (paragraph mark properties).
534
+ let rPr = findChildByTagName(pPr, 'w:rPr');
535
+ if (!rPr) {
536
+ rPr = createEl('w:rPr');
537
+ // CT_PPr ordering: ... base props ..., w:rPr, w:sectPr?, w:pPrChange?
538
+ // Insert rPr in schema-correct position (before sectPr/pPrChange).
539
+ const sectPr = findChildByTagName(pPr, 'w:sectPr');
540
+ const pPrChange = findChildByTagName(pPr, 'w:pPrChange');
541
+ const insertBefore = sectPr ?? pPrChange ?? null;
542
+ if (insertBefore) {
543
+ pPr.insertBefore(rPr, insertBefore);
544
+ }
545
+ else {
546
+ pPr.appendChild(rPr);
547
+ }
548
+ }
549
+ // Avoid duplicating markers.
550
+ if (findChildByTagName(rPr, markerTag))
551
+ return;
552
+ const id = allocateRevisionId(state);
553
+ const marker = createEl(markerTag, {
554
+ 'w:id': String(id),
555
+ 'w:author': author,
556
+ 'w:date': dateStr,
557
+ });
558
+ // Insert marker at the start of rPr for consistency with Aspose/Word patterns.
559
+ rPr.insertBefore(marker, rPr.firstChild);
560
+ }
561
+ /**
562
+ * Wrap a run element with <w:ins> to mark it as inserted.
563
+ *
564
+ * @param run - The w:r element to wrap
565
+ * @param author - Author name for track changes
566
+ * @param dateStr - Formatted date string
567
+ * @param state - Revision ID state
568
+ * @returns true if wrapped, false if run was already wrapped or has no parent
569
+ */
570
+ export function wrapAsInserted(run, author, dateStr, state) {
571
+ return wrapRunWithTrackChange({
572
+ run,
573
+ tagName: 'w:ins',
574
+ author,
575
+ dateStr,
576
+ state,
577
+ });
578
+ }
579
+ /**
580
+ * Wrap a run element with <w:del> to mark it as deleted.
581
+ * Also converts w:t to w:delText within the run.
582
+ *
583
+ * @param run - The w:r element to wrap
584
+ * @param author - Author name for track changes
585
+ * @param dateStr - Formatted date string
586
+ * @param state - Revision ID state
587
+ * @returns true if wrapped, false if run was already wrapped or has no parent
588
+ */
589
+ export function wrapAsDeleted(run, author, dateStr, state) {
590
+ return wrapRunWithTrackChange({
591
+ run,
592
+ tagName: 'w:del',
593
+ author,
594
+ dateStr,
595
+ state,
596
+ convertTextToDelText: true,
597
+ });
598
+ }
599
+ /**
600
+ * Clone a deleted run from the original document and insert it into the revised document.
601
+ *
602
+ * @param deletedAtom - Atom with the deleted content
603
+ * @param insertAfterRun - The run to insert after (null to insert at beginning of paragraph)
604
+ * @param targetParagraph - The paragraph to insert into
605
+ * @param author - Author name
606
+ * @param dateStr - Formatted date
607
+ * @param state - Revision ID state
608
+ * @returns The inserted del element, or null if insertion failed
609
+ */
610
+ export function insertDeletedRun(deletedAtom, insertAfterRun, targetParagraph, author, dateStr, state, context) {
611
+ // Get the source run element from the deleted atom
612
+ const sourceRun = deletedAtom.sourceRunElement;
613
+ if (!sourceRun) {
614
+ return null;
615
+ }
616
+ // Create w:del wrapper
617
+ const id = allocateRevisionId(state);
618
+ const del = createEl('w:del', {
619
+ 'w:id': String(id),
620
+ 'w:author': author,
621
+ 'w:date': dateStr,
622
+ });
623
+ // For collapsed field atoms, replay one cloned run per original source run
624
+ // to preserve multi-run field structure. Without this, all field elements
625
+ // get packed into a single run, breaking Word's field parsing.
626
+ const runs = getAtomRuns(deletedAtom);
627
+ if (runs.length > 1) {
628
+ for (const run of runs) {
629
+ const clonedRun = cloneRunWithAtomContent(run, deletedAtom, run);
630
+ convertToDelText(clonedRun);
631
+ del.appendChild(clonedRun);
632
+ }
633
+ }
634
+ else {
635
+ const clonedRun = cloneRunWithAtomContent(sourceRun, deletedAtom);
636
+ convertToDelText(clonedRun);
637
+ del.appendChild(clonedRun);
638
+ }
639
+ // Insert at correct position
640
+ if (insertAfterRun) {
641
+ insertAfterElement(insertAfterRun, del);
642
+ }
643
+ else {
644
+ // Insert at the beginning of the paragraph (after pPr if present)
645
+ const pPr = findChildByTagName(targetParagraph, 'w:pPr');
646
+ if (pPr) {
647
+ insertAfterElement(pPr, del);
648
+ }
649
+ else {
650
+ targetParagraph.insertBefore(del, targetParagraph.firstChild);
651
+ }
652
+ }
653
+ const sourceMarkers = cloneUnemittedSourceBookmarkMarkers(sourceRun, targetParagraph, state, context);
654
+ if (sourceMarkers.length > 0)
655
+ insertMarkersBeforeWrapper(del, sourceMarkers);
656
+ return del;
657
+ }
658
+ /**
659
+ * Clone a moved-from run from the original document and insert it into the revised document.
660
+ *
661
+ * MovedSource atoms have their sourceRunElement in the ORIGINAL tree, but we need to
662
+ * insert the content into the REVISED tree. This function clones the run, wraps it with
663
+ * <w:moveFrom> and range markers, and inserts at the correct position.
664
+ *
665
+ * @param atom - Atom with the moved-from content
666
+ * @param moveName - Name for linking source and destination
667
+ * @param insertAfterRun - The run to insert after (null to insert at beginning of paragraph)
668
+ * @param targetParagraph - The paragraph to insert into
669
+ * @param author - Author name
670
+ * @param dateStr - Formatted date
671
+ * @param state - Revision ID state
672
+ * @returns The inserted moveFrom element, or null if insertion failed
673
+ */
674
+ export function insertMoveFromRun(atom, moveName, insertAfterRun, targetParagraph, author, dateStr, state, context) {
675
+ // Get the source run element from the atom (in original tree)
676
+ const sourceRun = atom.sourceRunElement;
677
+ if (!sourceRun) {
678
+ return null;
679
+ }
680
+ // For collapsed field atoms, replay one cloned run per original source run.
681
+ const runs = getAtomRuns(atom);
682
+ const clonedRuns = [];
683
+ if (runs.length > 1) {
684
+ for (const run of runs) {
685
+ const clonedRun = cloneRunWithAtomContent(run, atom, run);
686
+ convertToDelText(clonedRun);
687
+ clonedRuns.push(clonedRun);
688
+ }
689
+ }
690
+ else {
691
+ const clonedRun = cloneRunWithAtomContent(sourceRun, atom);
692
+ convertToDelText(clonedRun);
693
+ clonedRuns.push(clonedRun);
694
+ }
695
+ // Get or allocate move range IDs
696
+ const ids = getMoveRangeIds(state, moveName);
697
+ const moveId = allocateRevisionId(state);
698
+ // Create range start marker
699
+ const rangeStart = createEl('w:moveFromRangeStart', {
700
+ 'w:id': String(ids.sourceRangeId),
701
+ 'w:name': moveName,
702
+ 'w:author': author,
703
+ 'w:date': dateStr,
704
+ });
705
+ // Create moveFrom wrapper
706
+ const moveFrom = createEl('w:moveFrom', {
707
+ 'w:id': String(moveId),
708
+ 'w:author': author,
709
+ 'w:date': dateStr,
710
+ });
711
+ // Create range end marker
712
+ const rangeEnd = createEl('w:moveFromRangeEnd', {
713
+ 'w:id': String(ids.sourceRangeId),
714
+ });
715
+ // Add cloned run(s) as children of moveFrom
716
+ for (const clonedRun of clonedRuns) {
717
+ moveFrom.appendChild(clonedRun);
718
+ }
719
+ // Insert at correct position: rangeStart -> moveFrom(run) -> rangeEnd
720
+ if (insertAfterRun) {
721
+ insertAfterElement(insertAfterRun, rangeStart);
722
+ insertAfterElement(rangeStart, moveFrom);
723
+ insertAfterElement(moveFrom, rangeEnd);
724
+ }
725
+ else {
726
+ // Insert at the beginning of the paragraph (after pPr if present)
727
+ const pPr = findChildByTagName(targetParagraph, 'w:pPr');
728
+ if (pPr) {
729
+ insertAfterElement(pPr, rangeStart);
730
+ insertAfterElement(rangeStart, moveFrom);
731
+ insertAfterElement(moveFrom, rangeEnd);
732
+ }
733
+ else {
734
+ targetParagraph.insertBefore(rangeEnd, targetParagraph.firstChild);
735
+ targetParagraph.insertBefore(moveFrom, rangeEnd);
736
+ targetParagraph.insertBefore(rangeStart, moveFrom);
737
+ }
738
+ }
739
+ const sourceMarkers = cloneUnemittedSourceBookmarkMarkers(sourceRun, targetParagraph, state, context);
740
+ if (sourceMarkers.length > 0)
741
+ insertMarkersBeforeWrapper(moveFrom, sourceMarkers);
742
+ return moveFrom;
743
+ }
744
+ /**
745
+ * Clone a deleted paragraph from the original document and insert it.
746
+ *
747
+ * @param deletedAtom - Atom representing the deleted paragraph
748
+ * @param insertAfterParagraph - Paragraph to insert after (null to insert at body start)
749
+ * @param targetBody - The body element to insert into
750
+ * @param author - Author name
751
+ * @param dateStr - Formatted date
752
+ * @param state - Revision ID state
753
+ * @returns The inserted paragraph, or null if insertion failed
754
+ */
755
+ export function insertDeletedParagraph(deletedAtom, insertAfterParagraph, targetBody, author, dateStr, state) {
756
+ // Get the source paragraph from the deleted atom
757
+ const sourceParagraph = deletedAtom.sourceParagraphElement;
758
+ if (!sourceParagraph) {
759
+ return null;
760
+ }
761
+ // Clone the paragraph
762
+ const clonedParagraph = sourceParagraph.cloneNode(true);
763
+ // Wrap runs with w:del (wrapAsDeleted handles w:t -> w:delText conversion internally)
764
+ const runs = Array.from(clonedParagraph.getElementsByTagName('w:r'));
765
+ for (const run of runs) {
766
+ wrapAsDeleted(run, author, dateStr, state);
767
+ }
768
+ // Insert at correct position
769
+ if (insertAfterParagraph) {
770
+ insertAfterElement(insertAfterParagraph, clonedParagraph);
771
+ }
772
+ else {
773
+ targetBody.insertBefore(clonedParagraph, targetBody.firstChild);
774
+ }
775
+ return clonedParagraph;
776
+ }
777
+ const MOVE_CONFIG = {
778
+ from: {
779
+ wrapperTag: 'w:moveFrom',
780
+ rangeStartTag: 'w:moveFromRangeStart',
781
+ rangeEndTag: 'w:moveFromRangeEnd',
782
+ rangeIdKey: 'sourceRangeId',
783
+ convertTextToDelText: true, // Moved-from content appears as deleted
784
+ },
785
+ to: {
786
+ wrapperTag: 'w:moveTo',
787
+ rangeStartTag: 'w:moveToRangeStart',
788
+ rangeEndTag: 'w:moveToRangeEnd',
789
+ rangeIdKey: 'destRangeId',
790
+ convertTextToDelText: false, // Moved-to content keeps w:t
791
+ },
792
+ };
793
+ /**
794
+ * Wrap a run element with move tracking (shared implementation for moveFrom/moveTo).
795
+ *
796
+ * @param run - The w:r element to wrap
797
+ * @param moveName - Name for linking source and destination
798
+ * @param direction - 'from' for moveFrom, 'to' for moveTo
799
+ * @param author - Author name
800
+ * @param dateStr - Formatted date
801
+ * @param state - Revision ID state
802
+ * @returns true if wrapped
803
+ */
804
+ function wrapAsMove(run, moveName, direction, author, dateStr, state) {
805
+ if (state.wrappedRuns.has(run)) {
806
+ return false;
807
+ }
808
+ const parent = parentElement(run);
809
+ if (!parent) {
810
+ return false;
811
+ }
812
+ const config = MOVE_CONFIG[direction];
813
+ const ids = getMoveRangeIds(state, moveName);
814
+ const moveId = allocateRevisionId(state);
815
+ const rangeId = ids[config.rangeIdKey];
816
+ // Convert w:t to w:delText if needed (for moveFrom content)
817
+ if (config.convertTextToDelText) {
818
+ convertToDelText(run);
819
+ }
820
+ // Create range start marker
821
+ const rangeStart = createEl(config.rangeStartTag, {
822
+ 'w:id': String(rangeId),
823
+ 'w:name': moveName,
824
+ 'w:author': author,
825
+ 'w:date': dateStr,
826
+ });
827
+ // Create move wrapper
828
+ const moveWrapper = createEl(config.wrapperTag, {
829
+ 'w:id': String(moveId),
830
+ 'w:author': author,
831
+ 'w:date': dateStr,
832
+ });
833
+ // Create range end marker
834
+ const rangeEnd = createEl(config.rangeEndTag, {
835
+ 'w:id': String(rangeId),
836
+ });
837
+ // Insert: rangeStart -> moveWrapper(run) -> rangeEnd
838
+ run.parentNode.insertBefore(rangeStart, run);
839
+ wrapElement(run, moveWrapper);
840
+ insertAfterElement(moveWrapper, rangeEnd);
841
+ state.wrappedRuns.add(run);
842
+ return true;
843
+ }
844
+ /**
845
+ * Wrap a run element with <w:moveFrom> for moved-from content.
846
+ *
847
+ * @param run - The w:r element to wrap
848
+ * @param moveName - Name for linking source and destination
849
+ * @param author - Author name
850
+ * @param dateStr - Formatted date
851
+ * @param state - Revision ID state
852
+ * @returns true if wrapped
853
+ */
854
+ export function wrapAsMoveFrom(run, moveName, author, dateStr, state) {
855
+ return wrapAsMove(run, moveName, 'from', author, dateStr, state);
856
+ }
857
+ /**
858
+ * Wrap a run element with <w:moveTo> for moved-to content.
859
+ *
860
+ * @param run - The w:r element to wrap
861
+ * @param moveName - Name for linking source and destination
862
+ * @param author - Author name
863
+ * @param dateStr - Formatted date
864
+ * @param state - Revision ID state
865
+ * @returns true if wrapped
866
+ */
867
+ export function wrapAsMoveTo(run, moveName, author, dateStr, state) {
868
+ return wrapAsMove(run, moveName, 'to', author, dateStr, state);
869
+ }
870
+ /**
871
+ * Add format change tracking to a run's properties.
872
+ *
873
+ * @param run - The w:r element with changed formatting
874
+ * @param oldRunProperties - The original run properties (w:rPr)
875
+ * @param author - Author name
876
+ * @param dateStr - Formatted date
877
+ * @param state - Revision ID state
878
+ */
879
+ export function addFormatChange(run, oldRunProperties, author, dateStr, state) {
880
+ // Find or create w:rPr
881
+ let rPr = findChildByTagName(run, 'w:rPr');
882
+ if (!rPr) {
883
+ rPr = createEl('w:rPr');
884
+ // Insert rPr at the beginning of run's children
885
+ run.insertBefore(rPr, run.firstChild);
886
+ }
887
+ // Create rPrChange
888
+ const id = allocateRevisionId(state);
889
+ const rPrChange = createEl('w:rPrChange', {
890
+ 'w:id': String(id),
891
+ 'w:author': author,
892
+ 'w:date': dateStr,
893
+ });
894
+ // Clone old properties into a w:rPr wrapper inside rPrChange (OOXML spec requires
895
+ // rPrChange to contain a single w:rPr child holding the previous formatting).
896
+ if (oldRunProperties) {
897
+ const oldRPr = createEl('w:rPr');
898
+ for (const child of childElements(oldRunProperties)) {
899
+ const cloned = child.cloneNode(true);
900
+ oldRPr.appendChild(cloned);
901
+ }
902
+ rPrChange.appendChild(oldRPr);
903
+ }
904
+ // Add rPrChange to rPr
905
+ rPr.appendChild(rPrChange);
906
+ }
907
+ /**
908
+ * Add a paragraph property change element (w:pPrChange) to record the "before"
909
+ * state of paragraph properties. This is needed for Google Docs to display
910
+ * inserted paragraphs as tracked changes.
911
+ *
912
+ * The child `<w:pPr>` inside `w:pPrChange` must conform to CT_PPrBase — it
913
+ * MUST NOT contain w:rPr, w:sectPr, or w:pPrChange.
914
+ *
915
+ * @param paragraph - The w:p element
916
+ * @param author - Author name
917
+ * @param dateStr - Formatted date
918
+ * @param state - Revision ID state
919
+ */
920
+ export function addParagraphPropertyChange(paragraph, author, dateStr, state) {
921
+ let pPr = findChildByTagName(paragraph, 'w:pPr');
922
+ if (!pPr) {
923
+ pPr = createEl('w:pPr');
924
+ paragraph.insertBefore(pPr, paragraph.firstChild);
925
+ }
926
+ // Idempotent — don't add a second pPrChange.
927
+ if (findChildByTagName(pPr, 'w:pPrChange'))
928
+ return;
929
+ const id = allocateRevisionId(state);
930
+ const pPrChange = createEl('w:pPrChange', {
931
+ 'w:id': String(id),
932
+ 'w:author': author,
933
+ 'w:date': dateStr,
934
+ });
935
+ // Clone current pPr content as "before" snapshot.
936
+ // pPrChange child pPr must be CT_PPrBase — exclude rPr, rPrChange, sectPr, pPrChange.
937
+ const EXCLUDED = new Set(['w:rPr', 'w:rPrChange', 'w:pPrChange', 'w:sectPr']);
938
+ const oldPPr = createEl('w:pPr');
939
+ for (const child of childElements(pPr)) {
940
+ if (!EXCLUDED.has(child.tagName))
941
+ oldPPr.appendChild(child.cloneNode(true));
942
+ }
943
+ pPrChange.appendChild(oldPPr);
944
+ pPr.appendChild(pPrChange); // pPrChange goes last in pPr per schema
945
+ }
946
+ /**
947
+ * Tag names that represent visible content inside a w:r element.
948
+ * A run containing at least one of these is considered substantive (non-empty).
949
+ */
950
+ const RUN_VISIBLE_CONTENT_TAGS = new Set([
951
+ 'w:t', 'w:tab', 'w:br', 'w:cr', 'w:drawing', 'w:object', 'w:pict',
952
+ 'w:sym', 'w:fldChar', 'w:instrText',
953
+ ]);
954
+ /**
955
+ * Returns true if a w:r element contains at least one visible content child.
956
+ * Empty runs (containing only w:rPr or nothing) return false.
957
+ */
958
+ export function runHasVisibleContent(run) {
959
+ for (let i = 0; i < run.childNodes.length; i++) {
960
+ const child = run.childNodes[i];
961
+ if (child.nodeType === 1 && RUN_VISIBLE_CONTENT_TAGS.has(child.tagName)) {
962
+ return true;
963
+ }
964
+ }
965
+ return false;
966
+ }
967
+ /**
968
+ * Wrap an inserted empty paragraph with <w:ins>.
969
+ *
970
+ * For empty paragraphs (no content, only pPr), we wrap the entire paragraph.
971
+ *
972
+ * @param paragraph - The w:p element
973
+ * @param author - Author name
974
+ * @param dateStr - Formatted date
975
+ * @param state - Revision ID state
976
+ */
977
+ export function wrapParagraphAsInserted(paragraph, author, dateStr, state) {
978
+ // For paragraphs with substantive run content: skip the paragraph-mark marker.
979
+ // Google Docs ignores (or actively hides) w:ins-wrapped runs when they
980
+ // coexist with PPR-INS markers. Since individual runs are already wrapped
981
+ // with <w:ins>, the paragraph-level marker is redundant for non-empty
982
+ // paragraphs and omitting it maximises cross-application compatibility.
983
+ //
984
+ // For empty paragraphs (no runs, or only empty w:r shells): we MUST add
985
+ // the PPR-INS marker so that Reject All removes the paragraph. Without it,
986
+ // the empty paragraph shell survives reject, causing round-trip safety failures.
987
+ //
988
+ // Important: empty <w:r> elements (no w:t, w:tab, w:br, etc.) should NOT
989
+ // count as substantive content. They are empty shells that don't produce
990
+ // visible output and should not prevent PPR-INS from being added.
991
+ let hasSubstantiveContent = false;
992
+ for (const child of childElements(paragraph)) {
993
+ if (child.tagName === 'w:ins') {
994
+ // Check if the w:ins wrapper contains runs with visible content
995
+ for (let i = 0; i < child.childNodes.length; i++) {
996
+ const insChild = child.childNodes[i];
997
+ if (insChild.nodeType === 1 && insChild.tagName === 'w:r' &&
998
+ runHasVisibleContent(insChild)) {
999
+ hasSubstantiveContent = true;
1000
+ break;
1001
+ }
1002
+ }
1003
+ if (hasSubstantiveContent)
1004
+ break;
1005
+ }
1006
+ else if (child.tagName === 'w:r' && runHasVisibleContent(child)) {
1007
+ hasSubstantiveContent = true;
1008
+ break;
1009
+ }
1010
+ }
1011
+ if (hasSubstantiveContent) {
1012
+ return true;
1013
+ }
1014
+ addParagraphMarkRevisionMarker(paragraph, 'w:ins', author, dateStr, state);
1015
+ return true;
1016
+ }
1017
+ /**
1018
+ * Wrap a deleted empty paragraph with <w:del>.
1019
+ *
1020
+ * @param paragraph - The w:p element
1021
+ * @param author - Author name
1022
+ * @param dateStr - Formatted date
1023
+ * @param state - Revision ID state
1024
+ */
1025
+ export function wrapParagraphAsDeleted(paragraph, author, dateStr, state) {
1026
+ // See wrapParagraphAsInserted: represent paragraph deletion via a paragraph-mark
1027
+ // revision marker in w:pPr/w:rPr so Accept/Reject All behaves correctly.
1028
+ addParagraphMarkRevisionMarker(paragraph, 'w:del', author, dateStr, state);
1029
+ return true;
1030
+ }
1031
+ // Field-character tag names that should not be split.
1032
+ const FIELD_CHAR_TAG_NAMES = new Set([
1033
+ 'w:fldChar', 'w:instrText', 'w:delInstrText',
1034
+ ]);
1035
+ /**
1036
+ * Visible text length for an atom's contentElement.
1037
+ *
1038
+ * Atom contentElements created by the word-split atomizer use prefixed tagNames
1039
+ * (e.g. `"w:t"`) without namespace URIs, so we match on `tagName` rather than
1040
+ * `localName`/`namespaceURI` (which is what the DOM-level `visibleLengthForEl` does).
1041
+ */
1042
+ function atomContentVisibleLength(el) {
1043
+ const tag = el.tagName;
1044
+ if (tag === 'w:t')
1045
+ return (el.textContent ?? '').length;
1046
+ if (tag === 'w:tab' || tag === 'w:br')
1047
+ return 1;
1048
+ // w:cr is treated as zero-length (consistent with visibleLengthForEl which also returns 0).
1049
+ return 0;
1050
+ }
1051
+ /**
1052
+ * Pre-split revised-tree runs that contain atoms with mixed correlation statuses.
1053
+ *
1054
+ * Without this, `handleInserted` wraps the entire run with `<w:ins>`, destroying
1055
+ * Equal content in the same run. After splitting, each fragment is a separate
1056
+ * `<w:r>` and existing per-status handlers work without modification.
1057
+ *
1058
+ * Safety: wrapped in try/catch per run group. If any DOM operation fails, the
1059
+ * run is skipped and the existing fallback-to-rebuild architecture handles it.
1060
+ */
1061
+ export function preSplitMixedStatusRuns(mergedAtoms) {
1062
+ // Group atoms by their sourceRunElement (revised-tree runs only).
1063
+ const runGroups = new Map();
1064
+ for (const atom of mergedAtoms) {
1065
+ if (!atom.sourceRunElement)
1066
+ continue;
1067
+ // Skip original-tree atoms — Deleted/MovedSource runs are cloned, not wrapped.
1068
+ if (atom.correlationStatus === CorrelationStatus.Deleted ||
1069
+ atom.correlationStatus === CorrelationStatus.MovedSource)
1070
+ continue;
1071
+ // Skip collapsed field atoms (multi-run field sequences).
1072
+ if (atom.collapsedFieldAtoms && atom.collapsedFieldAtoms.length > 0)
1073
+ continue;
1074
+ // Skip field character elements — semantically fragile.
1075
+ if (FIELD_CHAR_TAG_NAMES.has(atom.contentElement.tagName))
1076
+ continue;
1077
+ const group = runGroups.get(atom.sourceRunElement);
1078
+ if (group) {
1079
+ group.push(atom);
1080
+ }
1081
+ else {
1082
+ runGroups.set(atom.sourceRunElement, [atom]);
1083
+ }
1084
+ }
1085
+ for (const [run, atoms] of runGroups) {
1086
+ // Early check: skip single-status runs before any DOM work.
1087
+ const statuses = new Set(atoms.map((a) => a.correlationStatus));
1088
+ if (statuses.size <= 1)
1089
+ continue;
1090
+ // Guard: skip runs already detached from the tree.
1091
+ if (!run.parentNode)
1092
+ continue;
1093
+ try {
1094
+ // Compute the run's actual visible length via DOM traversal.
1095
+ const contentEls = getDirectContentElements(run);
1096
+ let runVisibleLength = 0;
1097
+ for (const cel of contentEls) {
1098
+ runVisibleLength += visibleLengthForEl(cel);
1099
+ }
1100
+ // Cross-run safety: if sum of atom lengths exceeds run visible length,
1101
+ // this group contains a cross-run merged atom (passes 3/4). Skip it.
1102
+ let sumAtomLengths = 0;
1103
+ for (const atom of atoms) {
1104
+ sumAtomLengths += atomContentVisibleLength(atom.contentElement);
1105
+ }
1106
+ if (sumAtomLengths > runVisibleLength)
1107
+ continue;
1108
+ const spans = [];
1109
+ let offset = 0;
1110
+ for (const atom of atoms) {
1111
+ const len = atomContentVisibleLength(atom.contentElement);
1112
+ const lastSpan = spans[spans.length - 1];
1113
+ if (lastSpan && lastSpan.status === atom.correlationStatus) {
1114
+ lastSpan.length += len;
1115
+ lastSpan.atoms.push(atom);
1116
+ }
1117
+ else {
1118
+ spans.push({
1119
+ status: atom.correlationStatus,
1120
+ startOffset: offset,
1121
+ length: len,
1122
+ atoms: [atom],
1123
+ });
1124
+ }
1125
+ offset += len;
1126
+ }
1127
+ // If only one span after grouping, no split needed.
1128
+ if (spans.length <= 1)
1129
+ continue;
1130
+ // Collect split points: startOffset of each span after the first.
1131
+ const splitPoints = [];
1132
+ for (let i = 1; i < spans.length; i++) {
1133
+ const pt = spans[i].startOffset;
1134
+ // Filter out degenerate split points at boundaries.
1135
+ if (pt > 0 && pt < runVisibleLength) {
1136
+ splitPoints.push(pt);
1137
+ }
1138
+ }
1139
+ if (splitPoints.length === 0)
1140
+ continue;
1141
+ // Split DOM run right-to-left to keep earlier offsets valid.
1142
+ const rightFragments = [];
1143
+ for (let i = splitPoints.length - 1; i >= 0; i--) {
1144
+ const { right } = splitRunAtVisibleOffset(run, splitPoints[i]);
1145
+ rightFragments.push(right);
1146
+ }
1147
+ // Map fragments: [originalRun (leftmost), ...reverse(rightFragments)]
1148
+ // After R-to-L splits, rightFragments are in reverse document order.
1149
+ const fragments = [run, ...rightFragments.reverse()];
1150
+ // Update atom sourceRunElement pointers to the correct fragment.
1151
+ // Each span maps to one fragment in order.
1152
+ for (let i = 0; i < spans.length; i++) {
1153
+ const fragment = fragments[i];
1154
+ if (!fragment)
1155
+ continue;
1156
+ for (const atom of spans[i].atoms) {
1157
+ atom.sourceRunElement = fragment;
1158
+ }
1159
+ }
1160
+ }
1161
+ catch (_err) {
1162
+ // DOM operation failed — skip this run. The existing fallback-to-rebuild
1163
+ // architecture will handle it if the overall safety check fails.
1164
+ warn('preSplitMixedStatusRuns', `Skipping run split due to error: ${_err}`);
1165
+ }
1166
+ }
1167
+ }
1168
+ /**
1169
+ * Pre-split revised-tree runs where word-split Equal atoms from the same run
1170
+ * are interleaved with Deleted/MovedSource atoms in the merged atom list.
1171
+ *
1172
+ * `preSplitMixedStatusRuns` handles the case where a single run contains atoms
1173
+ * with DIFFERENT statuses (e.g., some Equal and some Inserted). But it cannot
1174
+ * handle the case where ALL atoms from a run are Equal yet Deleted atoms (from
1175
+ * the original tree) are interspersed between them in the merged list.
1176
+ *
1177
+ * Without this split, `handleEqual` sees all Equal atoms pointing to the same
1178
+ * run and skips position advancement (the `lastRevisedRunAnchor` optimization).
1179
+ * Subsequent `handleDeleted` calls then insert deleted content at the wrong
1180
+ * position because the cursor never advanced past the shared run.
1181
+ *
1182
+ * This function detects interleaved sequences and splits the DOM run so each
1183
+ * contiguous group of Equal atoms gets its own run fragment. The handlers then
1184
+ * advance the cursor correctly across fragments.
1185
+ */
1186
+ export function preSplitInterleavedWordRuns(mergedAtoms) {
1187
+ const runToGroups = new Map();
1188
+ // Track cumulative offset per run (sums visible lengths of atoms seen so far)
1189
+ const runToOffset = new Map();
1190
+ let lastRevisedRun = null;
1191
+ for (const atom of mergedAtoms) {
1192
+ // Skip atoms from the original tree (Deleted/MovedSource have runs in the
1193
+ // original tree, not the revised tree).
1194
+ if (atom.correlationStatus === CorrelationStatus.Deleted ||
1195
+ atom.correlationStatus === CorrelationStatus.MovedSource) {
1196
+ // A Deleted/MovedSource atom between Equal atoms from the same run
1197
+ // creates an interleaving gap. Mark this by clearing lastRevisedRun
1198
+ // so the next Equal atom from the same run starts a new group.
1199
+ lastRevisedRun = null;
1200
+ continue;
1201
+ }
1202
+ const run = atom.sourceRunElement;
1203
+ if (!run)
1204
+ continue;
1205
+ // Skip collapsed field atoms — multi-run field sequences.
1206
+ if (atom.collapsedFieldAtoms && atom.collapsedFieldAtoms.length > 0)
1207
+ continue;
1208
+ // Skip field character elements — semantically fragile.
1209
+ if (FIELD_CHAR_TAG_NAMES.has(atom.contentElement.tagName))
1210
+ continue;
1211
+ const atomLen = atomContentVisibleLength(atom.contentElement);
1212
+ const currentOffset = runToOffset.get(run) ?? 0;
1213
+ runToOffset.set(run, currentOffset + atomLen);
1214
+ const groups = runToGroups.get(run);
1215
+ if (!groups) {
1216
+ // First time seeing this run — create initial group.
1217
+ runToGroups.set(run, [{
1218
+ startOffset: currentOffset,
1219
+ length: atomLen,
1220
+ atoms: [atom],
1221
+ }]);
1222
+ lastRevisedRun = run;
1223
+ continue;
1224
+ }
1225
+ if (lastRevisedRun === run) {
1226
+ // Contiguous with the previous atom from the same run — extend group.
1227
+ const lastGroup = groups[groups.length - 1];
1228
+ lastGroup.length += atomLen;
1229
+ lastGroup.atoms.push(atom);
1230
+ }
1231
+ else {
1232
+ // Gap detected (a Deleted/MovedSource atom intervened). Start new group.
1233
+ groups.push({
1234
+ startOffset: currentOffset,
1235
+ length: atomLen,
1236
+ atoms: [atom],
1237
+ });
1238
+ }
1239
+ lastRevisedRun = run;
1240
+ }
1241
+ // Now split runs that have more than one group.
1242
+ for (const [run, groups] of runToGroups) {
1243
+ if (groups.length <= 1)
1244
+ continue;
1245
+ // Guard: skip runs already detached from the tree.
1246
+ if (!run.parentNode)
1247
+ continue;
1248
+ try {
1249
+ // Compute actual visible length of the DOM run.
1250
+ const contentEls = getDirectContentElements(run);
1251
+ let runVisibleLength = 0;
1252
+ for (const cel of contentEls) {
1253
+ runVisibleLength += visibleLengthForEl(cel);
1254
+ }
1255
+ // Safety: if the sum of atom lengths exceeds run visible length,
1256
+ // something is off (cross-run atoms, etc.). Skip.
1257
+ let sumAtomLengths = 0;
1258
+ for (const group of groups) {
1259
+ sumAtomLengths += group.length;
1260
+ }
1261
+ if (sumAtomLengths > runVisibleLength)
1262
+ continue;
1263
+ // Collect split points: the startOffset of each group after the first.
1264
+ const splitPoints = [];
1265
+ for (let i = 1; i < groups.length; i++) {
1266
+ const pt = groups[i].startOffset;
1267
+ if (pt > 0 && pt < runVisibleLength) {
1268
+ splitPoints.push(pt);
1269
+ }
1270
+ }
1271
+ if (splitPoints.length === 0)
1272
+ continue;
1273
+ // Split DOM run right-to-left to keep earlier offsets valid.
1274
+ const rightFragments = [];
1275
+ for (let i = splitPoints.length - 1; i >= 0; i--) {
1276
+ const { right } = splitRunAtVisibleOffset(run, splitPoints[i]);
1277
+ rightFragments.push(right);
1278
+ }
1279
+ // Map fragments: [originalRun (leftmost), ...reverse(rightFragments)]
1280
+ const fragments = [run, ...rightFragments.reverse()];
1281
+ // Update atom sourceRunElement pointers to the correct fragment.
1282
+ for (let i = 0; i < groups.length; i++) {
1283
+ const fragment = fragments[i];
1284
+ if (!fragment)
1285
+ continue;
1286
+ for (const atom of groups[i].atoms) {
1287
+ atom.sourceRunElement = fragment;
1288
+ }
1289
+ }
1290
+ }
1291
+ catch (_err) {
1292
+ warn('preSplitInterleavedWordRuns', `Skipping run split due to error: ${_err}`);
1293
+ }
1294
+ }
1295
+ }
1296
+ /**
1297
+ * Modify the revised document's AST in-place based on comparison results.
1298
+ *
1299
+ * @param revisedRoot - Root element of the revised document
1300
+ * @param mergedAtoms - Atoms with correlation status from comparison
1301
+ * @param options - Modification options
1302
+ * @returns The modified XML string
1303
+ */
1304
+ export function modifyRevisedDocument(revisedRoot, originalAtoms, revisedAtoms, mergedAtoms, options) {
1305
+ const { author, date } = options;
1306
+ const dateStr = formatDate(date);
1307
+ const state = createRevisionIdState();
1308
+ // In-place mode needs concrete AST node pointers for run/paragraph edits.
1309
+ // Populate these once up-front so handlers don't have to rescan ancestor chains.
1310
+ attachSourceElementPointers(originalAtoms);
1311
+ attachSourceElementPointers(revisedAtoms);
1312
+ preSplitMixedStatusRuns(mergedAtoms);
1313
+ preSplitInterleavedWordRuns(mergedAtoms);
1314
+ // Process atoms and apply track changes to the revised tree
1315
+ // Group atoms by paragraph for efficient processing
1316
+ const ctx = processAtoms(mergedAtoms, originalAtoms, revisedAtoms, author, dateStr, state, revisedRoot);
1317
+ // Add paragraph-mark revision markers for whole-paragraph insert/delete cases.
1318
+ // This is required for idempotency in Word:
1319
+ // - Reject All should remove inserted paragraphs entirely
1320
+ // - Accept All should remove deleted paragraphs entirely
1321
+ applyWholeParagraphRevisionMarkers(mergedAtoms, ctx);
1322
+ // Suppress field-adjacent no-op del/ins pairs (issue #42, Bug 1).
1323
+ // Must run BEFORE merge — after merge, pairwise comparison is impossible.
1324
+ suppressNoOpChangePairs(ctx.body);
1325
+ // Merge adjacent <w:ins>/<w:del> siblings to reduce revision fragmentation.
1326
+ mergeAdjacentTrackChangeSiblings(ctx.body);
1327
+ // Coalesce del/ins pair chains across whitespace (issue #42, Bug 2b).
1328
+ // Merges [del:A][ins:X][ws][del:B][ins:Y] → [del:A ws B][ins:X ws Y]
1329
+ coalesceDelInsPairChains(ctx.body);
1330
+ // Merge whitespace-bridged track change siblings (issue #42, Bug 2).
1331
+ // Runs AFTER coalesce — handles ins+ws+ins and moveTo+ws+moveTo bridging.
1332
+ mergeWhitespaceBridgedTrackChanges(ctx.body);
1333
+ // Apply strict post-render consumer compatibility pass
1334
+ enforceConsumerCompatibility(revisedRoot, () => allocateRevisionId(state));
1335
+ // Serialize the modified tree
1336
+ return new XMLSerializer().serializeToString(revisedRoot.ownerDocument || revisedRoot);
1337
+ }
1338
+ function isParagraphRemovedOnRejectInContext(paragraph, ctx) {
1339
+ if (paragraphHasParaInsMarker(paragraph)) {
1340
+ return true;
1341
+ }
1342
+ const unifiedIndex = ctx.revisedParagraphToUnifiedIndex.get(paragraph);
1343
+ return unifiedIndex !== undefined && ctx.fullyInsertedParagraphIndices.has(unifiedIndex);
1344
+ }
1345
+ /**
1346
+ * Handle Inserted atoms - wrap the run with <w:ins>.
1347
+ * Inserted atoms have sourceRunElement in the REVISED tree.
1348
+ */
1349
+ function handleInserted(atom, ctx) {
1350
+ const runs = getAtomRuns(atom);
1351
+ if (runs.length > 0) {
1352
+ for (const run of runs) {
1353
+ wrapAsInserted(run, ctx.author, ctx.dateStr, ctx.state);
1354
+ }
1355
+ const endRun = getAtomRunAtBoundary(atom, 'end') ?? runs[runs.length - 1];
1356
+ const insertionPoint = getRunInsertionAnchor(endRun);
1357
+ if (insertionPoint === ctx.lastRevisedRunAnchor) {
1358
+ return {
1359
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1360
+ newLastParagraphIndex: atom.paragraphIndex,
1361
+ };
1362
+ }
1363
+ return {
1364
+ newLastRun: insertionPoint,
1365
+ newLastRevisedRunAnchor: insertionPoint,
1366
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1367
+ newLastParagraphIndex: atom.paragraphIndex,
1368
+ };
1369
+ }
1370
+ else if (atom.isEmptyParagraph && atom.sourceParagraphElement) {
1371
+ // Empty inserted paragraph: mark paragraph properties instead of wrapping <w:p>.
1372
+ wrapParagraphAsInserted(atom.sourceParagraphElement, ctx.author, ctx.dateStr, ctx.state);
1373
+ return {
1374
+ newLastParagraph: atom.sourceParagraphElement,
1375
+ newLastParagraphIndex: atom.paragraphIndex,
1376
+ };
1377
+ }
1378
+ return {};
1379
+ }
1380
+ /**
1381
+ * Handle Deleted atoms - clone from original and insert with <w:del>.
1382
+ * Deleted atoms have sourceRunElement in the ORIGINAL tree.
1383
+ * We need to clone and insert into the REVISED tree.
1384
+ *
1385
+ * Paragraph placement logic:
1386
+ * 1. If the atom's unified paragraph exists in the revised document, insert there
1387
+ * 2. If we've already created a paragraph for this unified index, use it
1388
+ * 3. Otherwise, create a new paragraph and insert it at the correct position
1389
+ */
1390
+ function handleDeleted(atom, ctx) {
1391
+ const bookmarkSurvivalContext = {
1392
+ isParagraphRemovedOnReject: (paragraph) => isParagraphRemovedOnRejectInContext(paragraph, ctx),
1393
+ };
1394
+ // Handle empty deleted paragraphs specially
1395
+ if (atom.isEmptyParagraph && atom.sourceParagraphElement) {
1396
+ const createdPara = insertDeletedParagraph(atom, ctx.lastProcessedParagraph, ctx.body, ctx.author, ctx.dateStr, ctx.state);
1397
+ if (createdPara && atom.paragraphIndex !== undefined) {
1398
+ ctx.createdParagraphs.set(atom.paragraphIndex, createdPara);
1399
+ }
1400
+ if (createdPara) {
1401
+ wrapParagraphAsDeleted(createdPara, ctx.author, ctx.dateStr, ctx.state);
1402
+ }
1403
+ return {
1404
+ newLastParagraph: createdPara ?? ctx.lastProcessedParagraph,
1405
+ newLastParagraphIndex: atom.paragraphIndex,
1406
+ };
1407
+ }
1408
+ if (atom.sourceRunElement) {
1409
+ const unifiedPara = atom.paragraphIndex;
1410
+ let targetParagraph;
1411
+ let insertAfterRun = null;
1412
+ // Determine target paragraph and insertion point
1413
+ if (unifiedPara !== undefined) {
1414
+ // Check if this unified paragraph exists in the revised document
1415
+ const revisedPara = ctx.unifiedParaToElement.get(unifiedPara);
1416
+ const revisedParagraphRemovedOnReject = revisedPara !== undefined &&
1417
+ (ctx.fullyInsertedParagraphIndices.has(unifiedPara) || paragraphHasParaInsMarker(revisedPara));
1418
+ if (revisedPara && !revisedParagraphRemovedOnReject) {
1419
+ // Paragraph exists in revised and survives Reject All - insert into it.
1420
+ targetParagraph = revisedPara;
1421
+ // If this is the same paragraph we last processed, use lastProcessedRun
1422
+ if (ctx.lastParagraphIndex === unifiedPara) {
1423
+ insertAfterRun = ctx.lastProcessedRun;
1424
+ }
1425
+ // Otherwise, insert at the beginning of the paragraph (insertAfterRun = null)
1426
+ }
1427
+ else {
1428
+ // Paragraph is absent in revised OR will be removed on Reject All.
1429
+ // Route deleted content into a created paragraph so reject output keeps
1430
+ // original-order text and bookmark markers.
1431
+ const createdPara = ctx.createdParagraphs.get(unifiedPara);
1432
+ if (createdPara) {
1433
+ targetParagraph = createdPara;
1434
+ insertAfterRun = ctx.createdParagraphLastRun.get(unifiedPara) ?? null;
1435
+ }
1436
+ else {
1437
+ // Need to create a new paragraph for this deleted content
1438
+ const newPara = createEl('w:p');
1439
+ const boundaryMarkers = cloneParagraphBoundaryBookmarkMarkers(atom.sourceParagraphElement);
1440
+ for (const marker of [...boundaryMarkers.sourceLeading, ...boundaryMarkers.sourceTrailing]) {
1441
+ ctx.state.emittedSourceBookmarkMarkers.add(marker);
1442
+ }
1443
+ const leadingMarkers = filterEquivalentBookmarkMarkers(boundaryMarkers.leading, ctx.body, bookmarkSurvivalContext);
1444
+ const trailingMarkers = filterEquivalentBookmarkMarkers(boundaryMarkers.trailing, ctx.body, bookmarkSurvivalContext);
1445
+ // Preserve paragraph properties from the original paragraph for fidelity.
1446
+ const srcP = atom.sourceParagraphElement;
1447
+ const srcPPr = srcP ? findChildByTagName(srcP, 'w:pPr') : null;
1448
+ if (srcPPr) {
1449
+ const clonedPPr = srcPPr.cloneNode(true);
1450
+ newPara.appendChild(clonedPPr);
1451
+ }
1452
+ if (ctx.lastProcessedParagraph) {
1453
+ insertAfterElement(ctx.lastProcessedParagraph, newPara);
1454
+ }
1455
+ else {
1456
+ ctx.body.insertBefore(newPara, ctx.body.firstChild);
1457
+ }
1458
+ ctx.createdParagraphs.set(unifiedPara, newPara);
1459
+ const leadingTail = insertLeadingMarkers(newPara, leadingMarkers);
1460
+ if (leadingTail) {
1461
+ ctx.createdParagraphLastRun.set(unifiedPara, leadingTail);
1462
+ }
1463
+ if (trailingMarkers.length > 0) {
1464
+ ctx.createdParagraphTrailingBookmarks.set(unifiedPara, trailingMarkers);
1465
+ }
1466
+ targetParagraph = newPara;
1467
+ insertAfterRun = leadingTail;
1468
+ }
1469
+ }
1470
+ }
1471
+ // Fall back to last processed paragraph if we couldn't determine target
1472
+ if (!targetParagraph) {
1473
+ targetParagraph = ctx.lastProcessedParagraph ??
1474
+ childElements(ctx.body).find(c => c.tagName === 'w:p');
1475
+ }
1476
+ if (!targetParagraph) {
1477
+ warn('inPlaceModifier', 'Cannot insert deleted content: no target paragraph found', {
1478
+ atomText: atom.contentElement?.textContent,
1479
+ });
1480
+ return {};
1481
+ }
1482
+ const del = insertDeletedRun(atom, insertAfterRun, targetParagraph, ctx.author, ctx.dateStr, ctx.state, bookmarkSurvivalContext);
1483
+ if (del) {
1484
+ // Track last run in created paragraphs
1485
+ if (unifiedPara !== undefined && ctx.createdParagraphs.has(unifiedPara)) {
1486
+ ctx.createdParagraphLastRun.set(unifiedPara, del);
1487
+ }
1488
+ return {
1489
+ newLastRun: del,
1490
+ newLastParagraph: targetParagraph,
1491
+ newLastParagraphIndex: atom.paragraphIndex,
1492
+ };
1493
+ }
1494
+ }
1495
+ return {};
1496
+ }
1497
+ /**
1498
+ * Handle MovedSource atoms - clone from original and insert with <w:moveFrom>.
1499
+ *
1500
+ * MovedSource atoms have sourceRunElement pointing to the ORIGINAL tree.
1501
+ * We need to clone the content and insert it into the REVISED tree.
1502
+ *
1503
+ * Paragraph placement logic (same as handleDeleted):
1504
+ * 1. If the atom's unified paragraph exists in the revised document, insert there
1505
+ * 2. If we've already created a paragraph for this unified index, use it
1506
+ * 3. Otherwise, create a new paragraph and insert it at the correct position
1507
+ */
1508
+ function handleMovedSource(atom, ctx) {
1509
+ const bookmarkSurvivalContext = {
1510
+ isParagraphRemovedOnReject: (paragraph) => isParagraphRemovedOnRejectInContext(paragraph, ctx),
1511
+ };
1512
+ if (atom.sourceRunElement) {
1513
+ const unifiedPara = atom.paragraphIndex;
1514
+ let targetParagraph;
1515
+ let insertAfterRun = null;
1516
+ // Determine target paragraph and insertion point
1517
+ if (unifiedPara !== undefined) {
1518
+ // Check if this unified paragraph exists in the revised document
1519
+ const revisedPara = ctx.unifiedParaToElement.get(unifiedPara);
1520
+ const revisedParagraphRemovedOnReject = revisedPara !== undefined &&
1521
+ (ctx.fullyInsertedParagraphIndices.has(unifiedPara) || paragraphHasParaInsMarker(revisedPara));
1522
+ if (revisedPara && !revisedParagraphRemovedOnReject) {
1523
+ // Paragraph exists in revised and survives Reject All - insert into it.
1524
+ targetParagraph = revisedPara;
1525
+ // If this is the same paragraph we last processed, use lastProcessedRun
1526
+ if (ctx.lastParagraphIndex === unifiedPara) {
1527
+ insertAfterRun = ctx.lastProcessedRun;
1528
+ }
1529
+ // Otherwise, insert at the beginning of the paragraph (insertAfterRun = null)
1530
+ }
1531
+ else {
1532
+ // Paragraph is absent in revised OR will be removed on Reject All.
1533
+ // Route moved-from content into a created paragraph for reject fidelity.
1534
+ const createdPara = ctx.createdParagraphs.get(unifiedPara);
1535
+ if (createdPara) {
1536
+ targetParagraph = createdPara;
1537
+ insertAfterRun = ctx.createdParagraphLastRun.get(unifiedPara) ?? null;
1538
+ }
1539
+ else {
1540
+ // Need to create a new paragraph for this moved-from content
1541
+ const newPara = createEl('w:p');
1542
+ const boundaryMarkers = cloneParagraphBoundaryBookmarkMarkers(atom.sourceParagraphElement);
1543
+ for (const marker of [...boundaryMarkers.sourceLeading, ...boundaryMarkers.sourceTrailing]) {
1544
+ ctx.state.emittedSourceBookmarkMarkers.add(marker);
1545
+ }
1546
+ const leadingMarkers = filterEquivalentBookmarkMarkers(boundaryMarkers.leading, ctx.body, bookmarkSurvivalContext);
1547
+ const trailingMarkers = filterEquivalentBookmarkMarkers(boundaryMarkers.trailing, ctx.body, bookmarkSurvivalContext);
1548
+ // Preserve paragraph properties from the original paragraph for fidelity.
1549
+ const srcP = atom.sourceParagraphElement;
1550
+ const srcPPr = srcP ? findChildByTagName(srcP, 'w:pPr') : null;
1551
+ if (srcPPr) {
1552
+ const clonedPPr = srcPPr.cloneNode(true);
1553
+ newPara.appendChild(clonedPPr);
1554
+ }
1555
+ if (ctx.lastProcessedParagraph) {
1556
+ insertAfterElement(ctx.lastProcessedParagraph, newPara);
1557
+ }
1558
+ else {
1559
+ ctx.body.insertBefore(newPara, ctx.body.firstChild);
1560
+ }
1561
+ ctx.createdParagraphs.set(unifiedPara, newPara);
1562
+ const leadingTail = insertLeadingMarkers(newPara, leadingMarkers);
1563
+ if (leadingTail) {
1564
+ ctx.createdParagraphLastRun.set(unifiedPara, leadingTail);
1565
+ }
1566
+ if (trailingMarkers.length > 0) {
1567
+ ctx.createdParagraphTrailingBookmarks.set(unifiedPara, trailingMarkers);
1568
+ }
1569
+ targetParagraph = newPara;
1570
+ insertAfterRun = leadingTail;
1571
+ }
1572
+ }
1573
+ }
1574
+ // Fall back to last processed paragraph if we couldn't determine target
1575
+ if (!targetParagraph) {
1576
+ targetParagraph = ctx.lastProcessedParagraph ??
1577
+ childElements(ctx.body).find(c => c.tagName === 'w:p');
1578
+ }
1579
+ if (!targetParagraph) {
1580
+ warn('inPlaceModifier', 'Cannot insert moved-from content: no target paragraph found', {
1581
+ atomText: atom.contentElement?.textContent,
1582
+ });
1583
+ return {};
1584
+ }
1585
+ const moveFrom = insertMoveFromRun(atom, atom.moveName || 'move1', insertAfterRun, targetParagraph, ctx.author, ctx.dateStr, ctx.state, bookmarkSurvivalContext);
1586
+ if (moveFrom) {
1587
+ // Track last run in created paragraphs
1588
+ if (unifiedPara !== undefined && ctx.createdParagraphs.has(unifiedPara)) {
1589
+ ctx.createdParagraphLastRun.set(unifiedPara, moveFrom);
1590
+ }
1591
+ return {
1592
+ newLastRun: moveFrom,
1593
+ newLastParagraph: targetParagraph,
1594
+ newLastParagraphIndex: atom.paragraphIndex,
1595
+ };
1596
+ }
1597
+ }
1598
+ return {};
1599
+ }
1600
+ /**
1601
+ * Handle MovedDestination atoms - wrap with <w:moveTo>.
1602
+ * MovedDestination atoms have sourceRunElement in the REVISED tree.
1603
+ */
1604
+ function handleMovedDestination(atom, ctx) {
1605
+ const runs = getAtomRuns(atom);
1606
+ if (runs.length > 0) {
1607
+ for (const run of runs) {
1608
+ wrapAsMoveTo(run, atom.moveName || 'move1', ctx.author, ctx.dateStr, ctx.state);
1609
+ }
1610
+ const endRun = getAtomRunAtBoundary(atom, 'end') ?? runs[runs.length - 1];
1611
+ const insertionPoint = getRunInsertionAnchor(endRun);
1612
+ if (insertionPoint === ctx.lastRevisedRunAnchor) {
1613
+ return {
1614
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1615
+ newLastParagraphIndex: atom.paragraphIndex,
1616
+ };
1617
+ }
1618
+ return {
1619
+ newLastRun: insertionPoint,
1620
+ newLastRevisedRunAnchor: insertionPoint,
1621
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1622
+ newLastParagraphIndex: atom.paragraphIndex,
1623
+ };
1624
+ }
1625
+ return {};
1626
+ }
1627
+ /**
1628
+ * Handle FormatChanged atoms - add <w:rPrChange>.
1629
+ * FormatChanged atoms have sourceRunElement in the REVISED tree.
1630
+ */
1631
+ function handleFormatChanged(atom, ctx) {
1632
+ const run = getAtomRunAtBoundary(atom, 'start');
1633
+ if (run && atom.formatChange?.oldRunProperties) {
1634
+ addFormatChange(run, atom.formatChange.oldRunProperties, ctx.author, ctx.dateStr, ctx.state);
1635
+ const endRun = getAtomRunAtBoundary(atom, 'end') ?? run;
1636
+ const insertionPoint = getRunInsertionAnchor(endRun);
1637
+ if (insertionPoint === ctx.lastRevisedRunAnchor) {
1638
+ return {
1639
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1640
+ newLastParagraphIndex: atom.paragraphIndex,
1641
+ };
1642
+ }
1643
+ return {
1644
+ newLastRun: insertionPoint,
1645
+ newLastRevisedRunAnchor: insertionPoint,
1646
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1647
+ newLastParagraphIndex: atom.paragraphIndex,
1648
+ };
1649
+ }
1650
+ return {};
1651
+ }
1652
+ /**
1653
+ * Handle Equal/Unknown atoms - just track position.
1654
+ *
1655
+ * IMPORTANT: For inplace mode, we must track positions in the REVISED tree.
1656
+ * - Non-empty Equal atoms come from the revised tree (sourceRunElement/sourceParagraphElement point to revised)
1657
+ * - Empty paragraph Equal atoms come from the ORIGINAL tree (see createMergedAtomList)
1658
+ *
1659
+ * For empty paragraphs, we need to look up the corresponding revised paragraph
1660
+ * from unifiedParaToElement, not use the atom's sourceParagraphElement (which is from original tree).
1661
+ *
1662
+ * CRITICAL: When the paragraph index changes, we MUST reset newLastRun to null.
1663
+ * This ensures that subsequent content is not incorrectly inserted after a run
1664
+ * from a previous paragraph. See the "Gross Asset Value" bug fix.
1665
+ */
1666
+ function handleEqual(atom, ctx) {
1667
+ // For non-empty atoms, sourceRunElement points to revised tree - safe to use directly
1668
+ const run = getAtomRunAtBoundary(atom, 'end');
1669
+ if (run) {
1670
+ const insertionPoint = getRunInsertionAnchor(run);
1671
+ // BUG FIX: Don't move the insertion point backwards if we are still in the same run.
1672
+ // This prevents Deleted atoms inserted between words of the same run from being reversed.
1673
+ if (insertionPoint === ctx.lastRevisedRunAnchor) {
1674
+ return {
1675
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1676
+ newLastParagraphIndex: atom.paragraphIndex,
1677
+ };
1678
+ }
1679
+ return {
1680
+ newLastRun: insertionPoint,
1681
+ newLastRevisedRunAnchor: insertionPoint,
1682
+ newLastParagraph: atom.sourceParagraphElement ?? ctx.lastProcessedParagraph,
1683
+ newLastParagraphIndex: atom.paragraphIndex,
1684
+ };
1685
+ }
1686
+ // For empty paragraphs (no sourceRunElement), the atom comes from the ORIGINAL tree!
1687
+ // We must NOT use atom.sourceParagraphElement for position tracking in inplace mode.
1688
+ // Instead, look up the corresponding REVISED paragraph from unifiedParaToElement.
1689
+ if (atom.paragraphIndex !== undefined) {
1690
+ // Look up the revised paragraph for this unified paragraph index
1691
+ const revisedParagraph = ctx.unifiedParaToElement.get(atom.paragraphIndex);
1692
+ // IMPORTANT: When we move to a new paragraph (empty or not), we MUST reset
1693
+ // lastProcessedRun to null. Otherwise, subsequent inserts might use a stale
1694
+ // run from a previous paragraph, causing content to be inserted in the wrong place.
1695
+ // Setting newLastRun to null explicitly resets it.
1696
+ return {
1697
+ newLastRun: null, // Reset - we're in a new paragraph with no runs yet
1698
+ newLastRevisedRunAnchor: null,
1699
+ // Use the revised paragraph (not the original's sourceParagraphElement!)
1700
+ newLastParagraph: revisedParagraph ?? ctx.lastProcessedParagraph,
1701
+ newLastParagraphIndex: atom.paragraphIndex,
1702
+ };
1703
+ }
1704
+ return {};
1705
+ }
1706
+ /**
1707
+ * Strategy map for handling atoms by correlation status.
1708
+ * This pattern makes it easy to add new status types without modifying processAtoms.
1709
+ */
1710
+ const ATOM_HANDLERS = {
1711
+ [CorrelationStatus.Inserted]: handleInserted,
1712
+ [CorrelationStatus.Deleted]: handleDeleted,
1713
+ [CorrelationStatus.MovedSource]: handleMovedSource,
1714
+ [CorrelationStatus.MovedDestination]: handleMovedDestination,
1715
+ [CorrelationStatus.FormatChanged]: handleFormatChanged,
1716
+ [CorrelationStatus.Equal]: handleEqual,
1717
+ [CorrelationStatus.Unknown]: handleEqual,
1718
+ };
1719
+ const DELETION_LIKE_STATUSES = new Set([
1720
+ CorrelationStatus.Deleted,
1721
+ CorrelationStatus.MovedSource,
1722
+ ]);
1723
+ const INSERTION_LIKE_STATUSES = new Set([
1724
+ CorrelationStatus.Inserted,
1725
+ CorrelationStatus.MovedDestination,
1726
+ ]);
1727
+ /**
1728
+ * Reorder merged atoms so that within each contiguous block of non-equal atoms,
1729
+ * all deletion-like atoms come before all insertion-like atoms.
1730
+ *
1731
+ * This produces grouped tracked changes ("<del>old words</del><ins>new words</ins>")
1732
+ * instead of alternating word-by-word pairs ("<del>old1</del><ins>new1</ins><del>old2</del>...").
1733
+ */
1734
+ export function groupDeletionsBeforeInsertions(atoms) {
1735
+ const result = [];
1736
+ let i = 0;
1737
+ while (i < atoms.length) {
1738
+ const atom = atoms[i];
1739
+ const status = atom.correlationStatus;
1740
+ // Pass through equal/format-changed/unknown atoms unchanged
1741
+ if (!DELETION_LIKE_STATUSES.has(status) && !INSERTION_LIKE_STATUSES.has(status)) {
1742
+ result.push(atom);
1743
+ i++;
1744
+ continue;
1745
+ }
1746
+ // Collect a contiguous block of change atoms (deletions + insertions)
1747
+ const deletions = [];
1748
+ const insertions = [];
1749
+ while (i < atoms.length) {
1750
+ const s = atoms[i].correlationStatus;
1751
+ if (DELETION_LIKE_STATUSES.has(s)) {
1752
+ deletions.push(atoms[i]);
1753
+ }
1754
+ else if (INSERTION_LIKE_STATUSES.has(s)) {
1755
+ insertions.push(atoms[i]);
1756
+ }
1757
+ else {
1758
+ break;
1759
+ }
1760
+ i++;
1761
+ }
1762
+ // Emit all deletions first, then all insertions
1763
+ result.push(...deletions, ...insertions);
1764
+ }
1765
+ return result;
1766
+ }
1767
+ /**
1768
+ * Process atoms and apply track changes to the revised AST.
1769
+ *
1770
+ * Uses a strategy pattern with registered handlers for each correlation status,
1771
+ * making it easy to add new status types without modifying this function.
1772
+ */
1773
+ function processAtoms(mergedAtoms, _originalAtoms, revisedAtoms, author, dateStr, state, revisedRoot) {
1774
+ const bodyElements = Array.from(revisedRoot.getElementsByTagName('w:body'));
1775
+ const body = bodyElements[0];
1776
+ if (!body) {
1777
+ warn('inPlaceModifier', 'Cannot process atoms: no w:body element found');
1778
+ // Return a minimal context to avoid callers having to handle undefined.
1779
+ return {
1780
+ author,
1781
+ dateStr,
1782
+ state,
1783
+ body: revisedRoot,
1784
+ lastProcessedRun: null,
1785
+ lastRevisedRunAnchor: null,
1786
+ lastProcessedParagraph: null,
1787
+ lastParagraphIndex: undefined,
1788
+ unifiedParaToElement: new Map(),
1789
+ revisedParagraphToUnifiedIndex: new Map(),
1790
+ fullyInsertedParagraphIndices: new Set(),
1791
+ createdParagraphs: new Map(),
1792
+ createdParagraphLastRun: new Map(),
1793
+ createdParagraphTrailingBookmarks: new Map(),
1794
+ };
1795
+ }
1796
+ // Build map from unified paragraph index to revised paragraph element.
1797
+ // This tells us which paragraphs exist in the revised document.
1798
+ // Revised atoms have their paragraphIndex already set to unified indices
1799
+ // after assignUnifiedParagraphIndices was called.
1800
+ const unifiedParaToElement = new Map();
1801
+ const revisedParagraphToUnifiedIndex = new Map();
1802
+ for (const atom of revisedAtoms) {
1803
+ if (atom.paragraphIndex !== undefined && atom.sourceParagraphElement) {
1804
+ if (!unifiedParaToElement.has(atom.paragraphIndex)) {
1805
+ unifiedParaToElement.set(atom.paragraphIndex, atom.sourceParagraphElement);
1806
+ }
1807
+ if (!revisedParagraphToUnifiedIndex.has(atom.sourceParagraphElement)) {
1808
+ revisedParagraphToUnifiedIndex.set(atom.sourceParagraphElement, atom.paragraphIndex);
1809
+ }
1810
+ }
1811
+ }
1812
+ const atomsByPara = new Map();
1813
+ for (const atom of mergedAtoms) {
1814
+ if (atom.paragraphIndex === undefined)
1815
+ continue;
1816
+ const existing = atomsByPara.get(atom.paragraphIndex) ?? [];
1817
+ existing.push(atom);
1818
+ atomsByPara.set(atom.paragraphIndex, existing);
1819
+ }
1820
+ const fullyInsertedParagraphIndices = new Set();
1821
+ for (const [paraIdx, atoms] of atomsByPara.entries()) {
1822
+ if (isEntireParagraphAtomsWithStatus(atoms, CorrelationStatus.Inserted)) {
1823
+ fullyInsertedParagraphIndices.add(paraIdx);
1824
+ }
1825
+ }
1826
+ // Initialize processing context with position tracking
1827
+ const ctx = {
1828
+ author,
1829
+ dateStr,
1830
+ state,
1831
+ body,
1832
+ lastProcessedRun: null,
1833
+ lastRevisedRunAnchor: null,
1834
+ lastProcessedParagraph: null,
1835
+ lastParagraphIndex: undefined,
1836
+ unifiedParaToElement,
1837
+ revisedParagraphToUnifiedIndex,
1838
+ fullyInsertedParagraphIndices,
1839
+ createdParagraphs: new Map(),
1840
+ createdParagraphLastRun: new Map(),
1841
+ createdParagraphTrailingBookmarks: new Map(),
1842
+ };
1843
+ // Reorder atoms so consecutive deletions precede consecutive insertions.
1844
+ // This produces grouped tracked changes (all <w:del> then all <w:ins>)
1845
+ // instead of alternating word-by-word del/ins pairs.
1846
+ const reorderedAtoms = groupDeletionsBeforeInsertions(mergedAtoms);
1847
+ for (const atom of reorderedAtoms) {
1848
+ const handler = ATOM_HANDLERS[atom.correlationStatus];
1849
+ const result = handler(atom, ctx);
1850
+ // Update position tracking based on handler result
1851
+ if (result.newLastRun !== undefined) {
1852
+ ctx.lastProcessedRun = result.newLastRun;
1853
+ }
1854
+ if (result.newLastRevisedRunAnchor !== undefined) {
1855
+ ctx.lastRevisedRunAnchor = result.newLastRevisedRunAnchor;
1856
+ }
1857
+ if (result.newLastParagraph !== undefined) {
1858
+ ctx.lastProcessedParagraph = result.newLastParagraph;
1859
+ }
1860
+ if (result.newLastParagraphIndex !== undefined) {
1861
+ ctx.lastParagraphIndex = result.newLastParagraphIndex;
1862
+ }
1863
+ }
1864
+ finalizeCreatedParagraphTrailingBookmarks(ctx);
1865
+ return ctx;
1866
+ }
1867
+ function finalizeCreatedParagraphTrailingBookmarks(ctx) {
1868
+ for (const [paraIdx, markers] of ctx.createdParagraphTrailingBookmarks.entries()) {
1869
+ if (markers.length === 0)
1870
+ continue;
1871
+ const paragraph = ctx.createdParagraphs.get(paraIdx);
1872
+ if (!paragraph)
1873
+ continue;
1874
+ let anchor = ctx.createdParagraphLastRun.get(paraIdx) ?? null;
1875
+ if (!anchor) {
1876
+ const pPr = findChildByTagName(paragraph, 'w:pPr');
1877
+ const kids = childElements(paragraph);
1878
+ const leadingBookmark = [...kids]
1879
+ .reverse()
1880
+ .find((c) => c.tagName === 'w:bookmarkStart') ?? null;
1881
+ anchor = leadingBookmark ?? pPr;
1882
+ }
1883
+ if (!anchor) {
1884
+ for (const marker of markers) {
1885
+ paragraph.appendChild(marker);
1886
+ }
1887
+ continue;
1888
+ }
1889
+ let current = anchor;
1890
+ for (const marker of markers) {
1891
+ insertAfterElement(current, marker);
1892
+ current = marker;
1893
+ }
1894
+ ctx.createdParagraphLastRun.set(paraIdx, current);
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Apply whole-paragraph revision markers (w:pPr/w:rPr) based on merged atoms.
1899
+ *
1900
+ * This intentionally runs as a post-pass so the inplace algorithm can keep its
1901
+ * fine-grained run edits while still enforcing Word/Aspose paragraph invariants.
1902
+ */
1903
+ function applyWholeParagraphRevisionMarkers(mergedAtoms, ctx) {
1904
+ const atomsByPara = new Map();
1905
+ for (const atom of mergedAtoms) {
1906
+ if (atom.paragraphIndex === undefined)
1907
+ continue;
1908
+ const list = atomsByPara.get(atom.paragraphIndex) ?? [];
1909
+ list.push(atom);
1910
+ atomsByPara.set(atom.paragraphIndex, list);
1911
+ }
1912
+ for (const [paraIdx, atoms] of atomsByPara.entries()) {
1913
+ if (isEntireParagraphAtomsWithStatus(atoms, CorrelationStatus.Inserted)) {
1914
+ const para = ctx.unifiedParaToElement.get(paraIdx);
1915
+ if (para) {
1916
+ wrapParagraphAsInserted(para, ctx.author, ctx.dateStr, ctx.state);
1917
+ }
1918
+ continue;
1919
+ }
1920
+ if (isEntireParagraphAtomsWithStatus(atoms, CorrelationStatus.Deleted)) {
1921
+ const para = ctx.createdParagraphs.get(paraIdx) ?? ctx.unifiedParaToElement.get(paraIdx);
1922
+ if (para) {
1923
+ wrapParagraphAsDeleted(para, ctx.author, ctx.dateStr, ctx.state);
1924
+ }
1925
+ }
1926
+ }
1927
+ }
1928
+ /**
1929
+ * Merge adjacent sibling track-change wrappers (<w:ins>/<w:del>) to reduce
1930
+ * Word UI fragmentation (one accept/reject per word/run).
1931
+ *
1932
+ * We only merge wrappers that share the same author+date to avoid conflating
1933
+ * distinct revisions.
1934
+ */
1935
+ function mergeAdjacentTrackChangeSiblings(root) {
1936
+ function traverse(node) {
1937
+ const children = childElements(node);
1938
+ if (children.length < 2) {
1939
+ // Still recurse into children
1940
+ for (const child of childElements(node))
1941
+ traverse(child);
1942
+ return;
1943
+ }
1944
+ for (let i = 0; i < children.length - 1;) {
1945
+ const a = children[i];
1946
+ const b = children[i + 1];
1947
+ if (a.tagName === b.tagName && TRACK_CHANGE_WRAPPERS.has(a.tagName) &&
1948
+ a.getAttribute('w:author') === b.getAttribute('w:author') &&
1949
+ a.getAttribute('w:date') === b.getAttribute('w:date')) {
1950
+ // Absorb b's children into a
1951
+ while (b.firstChild)
1952
+ a.appendChild(b.firstChild);
1953
+ node.removeChild(b);
1954
+ // Remove b from our local children snapshot and don't increment i —
1955
+ // recheck a with its new next sibling.
1956
+ children.splice(i + 1, 1);
1957
+ continue;
1958
+ }
1959
+ i++;
1960
+ }
1961
+ // Recurse into current children (re-query after mutations)
1962
+ for (const child of childElements(node)) {
1963
+ traverse(child);
1964
+ }
1965
+ }
1966
+ traverse(root);
1967
+ }
1968
+ // =============================================================================
1969
+ // Bug 1: Suppress field-adjacent false no-op del/ins pairs (issue #42)
1970
+ // =============================================================================
1971
+ /**
1972
+ * Build a normalized content signature for a run's non-rPr children.
1973
+ * On the del side, maps w:delText → w:t and w:delInstrText → w:instrText
1974
+ * so that content from del wrappers can be compared to ins wrappers.
1975
+ */
1976
+ function normalizeRunContentSignature(run, isDelSide) {
1977
+ const parts = [];
1978
+ for (let i = 0; i < run.childNodes.length; i++) {
1979
+ const child = run.childNodes[i];
1980
+ if (child.nodeType !== 1)
1981
+ continue;
1982
+ const el = child;
1983
+ if (el.tagName === 'w:rPr')
1984
+ continue;
1985
+ let tag = el.tagName;
1986
+ if (isDelSide) {
1987
+ if (tag === 'w:delText')
1988
+ tag = 'w:t';
1989
+ else if (tag === 'w:delInstrText')
1990
+ tag = 'w:instrText';
1991
+ }
1992
+ const text = el.textContent ?? '';
1993
+ parts.push(`<${tag}>${text}</${tag}>`);
1994
+ }
1995
+ return parts.join('');
1996
+ }
1997
+ /**
1998
+ * Check if an adjacent w:del + w:ins pair is a no-op (identical text and formatting).
1999
+ * Both wrappers must contain the same number of runs with matching rPr and content.
2000
+ */
2001
+ export function isNoOpPair(del, ins) {
2002
+ const delRuns = childElements(del).filter(c => c.tagName === 'w:r');
2003
+ const insRuns = childElements(ins).filter(c => c.tagName === 'w:r');
2004
+ if (delRuns.length !== insRuns.length)
2005
+ return false;
2006
+ if (delRuns.length === 0)
2007
+ return false;
2008
+ for (let i = 0; i < delRuns.length; i++) {
2009
+ const delRun = delRuns[i];
2010
+ const insRun = insRuns[i];
2011
+ // Compare formatting via canonical rPr comparison
2012
+ const delRPr = findChildByTagName(delRun, 'w:rPr');
2013
+ const insRPr = findChildByTagName(insRun, 'w:rPr');
2014
+ if (!areRunPropertiesEqual(delRPr ?? null, insRPr ?? null))
2015
+ return false;
2016
+ // Compare content structure (text, tabs, breaks, field chars, etc.)
2017
+ const delSig = normalizeRunContentSignature(delRun, true);
2018
+ const insSig = normalizeRunContentSignature(insRun, false);
2019
+ if (delSig !== insSig)
2020
+ return false;
2021
+ }
2022
+ return true;
2023
+ }
2024
+ /**
2025
+ * Suppress no-op del/ins pairs — adjacent w:del + w:ins wrappers where the
2026
+ * content and formatting are identical. These arise from field-adjacent atoms
2027
+ * that are false-positive changes.
2028
+ *
2029
+ * When a no-op is detected, both wrappers are unwrapped, leaving the ins-side
2030
+ * runs as plain (non-tracked) children. The del-side runs are removed.
2031
+ */
2032
+ export function suppressNoOpChangePairs(root) {
2033
+ function traverse(node) {
2034
+ const children = childElements(node);
2035
+ for (let i = 0; i < children.length - 1;) {
2036
+ const a = children[i];
2037
+ const b = children[i + 1];
2038
+ if (a.tagName === 'w:del' && b.tagName === 'w:ins' && isNoOpPair(a, b)) {
2039
+ // Remove the del wrapper and its content entirely
2040
+ node.removeChild(a);
2041
+ // Unwrap the ins wrapper — promote its children to the parent
2042
+ unwrapElement(b);
2043
+ // Re-snapshot children after mutation
2044
+ children.splice(i, 2, ...childElements(node).slice(i));
2045
+ // Don't increment — recheck from same position
2046
+ continue;
2047
+ }
2048
+ i++;
2049
+ }
2050
+ // Recurse into current children (re-query after mutations)
2051
+ for (const child of childElements(node)) {
2052
+ traverse(child);
2053
+ }
2054
+ }
2055
+ traverse(root);
2056
+ }
2057
+ // =============================================================================
2058
+ // Bug 2: Merge whitespace-bridged track change siblings (issue #42)
2059
+ // =============================================================================
2060
+ /**
2061
+ * Narrow whitespace predicate for bridging: returns true only if a w:r element's
2062
+ * visible children are exclusively w:t elements with whitespace-only text content.
2063
+ * Excludes w:tab, w:br, w:cr which have layout significance.
2064
+ */
2065
+ function isInlineWhitespaceOnlyRun(run) {
2066
+ if (run.tagName !== 'w:r')
2067
+ return false;
2068
+ let hasVisibleChild = false;
2069
+ for (let i = 0; i < run.childNodes.length; i++) {
2070
+ const child = run.childNodes[i];
2071
+ if (child.nodeType !== 1)
2072
+ continue;
2073
+ const el = child;
2074
+ if (el.tagName === 'w:rPr')
2075
+ continue;
2076
+ // Only w:t with whitespace-only text is allowed
2077
+ if (el.tagName === 'w:t') {
2078
+ const text = el.textContent ?? '';
2079
+ if (text.length === 0 || !/^\s+$/.test(text))
2080
+ return false;
2081
+ hasVisibleChild = true;
2082
+ continue;
2083
+ }
2084
+ // Any other visible element (w:tab, w:br, w:cr, w:fldChar, etc.) disqualifies
2085
+ return false;
2086
+ }
2087
+ return hasVisibleChild;
2088
+ }
2089
+ /**
2090
+ * Merge track-change wrappers (w:del or w:ins) that are separated by a
2091
+ * whitespace-only run. This groups "word-by-word" tracked changes into
2092
+ * contiguous blocks for cleaner presentation.
2093
+ *
2094
+ * For w:del: clones the whitespace run, converts w:t→w:delText, and absorbs
2095
+ * both the whitespace and the second wrapper's children into the first wrapper.
2096
+ *
2097
+ * For w:ins: moves the whitespace run into the first wrapper, then absorbs
2098
+ * the second wrapper's children.
2099
+ *
2100
+ * Both projections (Accept All, Reject All) remain correct because each
2101
+ * wrapper independently contains the whitespace it needs.
2102
+ */
2103
+ export function mergeWhitespaceBridgedTrackChanges(root) {
2104
+ function traverse(node) {
2105
+ const children = childElements(node);
2106
+ for (let i = 0; i < children.length - 2;) {
2107
+ const a = children[i];
2108
+ const mid = children[i + 1];
2109
+ const b = children[i + 2];
2110
+ // Check: same track-change tag, same author/date, with whitespace-only run between.
2111
+ // Only bridge w:ins and w:moveTo — bridging w:del is unsafe because the
2112
+ // intervening whitespace is Equal content needed by the accept projection.
2113
+ const bridgeableTags = new Set(['w:ins', 'w:moveTo']);
2114
+ if (a.tagName === b.tagName &&
2115
+ bridgeableTags.has(a.tagName) &&
2116
+ a.getAttribute('w:author') === b.getAttribute('w:author') &&
2117
+ a.getAttribute('w:date') === b.getAttribute('w:date') &&
2118
+ isInlineWhitespaceOnlyRun(mid)) {
2119
+ // Move the whitespace run into the first wrapper, then absorb second's children
2120
+ a.appendChild(mid);
2121
+ while (b.firstChild)
2122
+ a.appendChild(b.firstChild);
2123
+ node.removeChild(b);
2124
+ // mid was moved into a, b removed from parent — splice both from snapshot
2125
+ children.splice(i + 1, 2);
2126
+ // Don't increment — recheck a with new next sibling
2127
+ continue;
2128
+ }
2129
+ i++;
2130
+ }
2131
+ // Recurse into current children (re-query after mutations)
2132
+ for (const child of childElements(node)) {
2133
+ traverse(child);
2134
+ }
2135
+ }
2136
+ traverse(root);
2137
+ }
2138
+ // =============================================================================
2139
+ // Bug 2b: Coalesce del/ins pair chains across whitespace (issue #42)
2140
+ // =============================================================================
2141
+ /**
2142
+ * Convert w:t → w:delText and w:instrText → w:delInstrText within a run,
2143
+ * preserving xml:space attributes. Used for cloning whitespace runs into
2144
+ * w:del wrappers during pair-chain coalescing.
2145
+ */
2146
+ function convertRunTextToDelText(run) {
2147
+ for (let i = 0; i < run.childNodes.length; i++) {
2148
+ const child = run.childNodes[i];
2149
+ if (child.nodeType !== 1)
2150
+ continue;
2151
+ const el = child;
2152
+ if (el.tagName === 'w:t' || el.tagName === 'w:instrText') {
2153
+ const newTag = el.tagName === 'w:t' ? 'w:delText' : 'w:delInstrText';
2154
+ const newEl = createEl(newTag);
2155
+ // Copy text content
2156
+ while (el.firstChild)
2157
+ newEl.appendChild(el.firstChild);
2158
+ // Copy attributes (including xml:space="preserve")
2159
+ for (let j = 0; j < el.attributes.length; j++) {
2160
+ const attr = el.attributes[j];
2161
+ newEl.setAttribute(attr.name, attr.value);
2162
+ }
2163
+ run.replaceChild(newEl, el);
2164
+ }
2165
+ }
2166
+ }
2167
+ /**
2168
+ * Coalesce alternating del/ins pair chains separated by whitespace-only runs
2169
+ * into single grouped del + ins wrappers.
2170
+ *
2171
+ * Pattern: [w:del, w:ins, ws-segment..., w:del, w:ins, ws-segment..., w:del, w:ins]
2172
+ *
2173
+ * For each whitespace segment between consecutive [del, ins] pairs:
2174
+ * 1. Clone each ws-run → convert to delText → append to first del
2175
+ * 2. Clone each ws-run → keep as w:t → append to first ins
2176
+ * 3. Move nextDel's children into first del
2177
+ * 4. Move nextIns's children into first ins
2178
+ * 5. Remove original ws-runs, empty nextDel, empty nextIns from parent
2179
+ *
2180
+ * Safety invariants:
2181
+ * - Only bridges when both del AND ins absorb the whitespace (both projections correct)
2182
+ * - Incomplete tail [del, ins, ws, del] (no trailing ins) → stop chain, don't bridge
2183
+ * - All wrappers in chain must share same w:author and w:date
2184
+ */
2185
+ export function coalesceDelInsPairChains(root) {
2186
+ function traverse(node) {
2187
+ const children = childElements(node);
2188
+ for (let i = 0; i < children.length - 1;) {
2189
+ const firstDel = children[i];
2190
+ const firstIns = children[i + 1];
2191
+ // Must start with a [del, ins] pair
2192
+ if (firstDel.tagName !== 'w:del' || firstIns.tagName !== 'w:ins') {
2193
+ i++;
2194
+ continue;
2195
+ }
2196
+ const author = firstDel.getAttribute('w:author');
2197
+ const date = firstDel.getAttribute('w:date');
2198
+ // All four must match author/date
2199
+ if (firstIns.getAttribute('w:author') !== author ||
2200
+ firstIns.getAttribute('w:date') !== date) {
2201
+ i++;
2202
+ continue;
2203
+ }
2204
+ // Try to extend the chain by absorbing subsequent [ws..., del, ins] triples
2205
+ let cursor = i + 2; // position after firstIns
2206
+ let chainExtended = false;
2207
+ while (cursor < children.length) {
2208
+ // Collect whitespace segment (1..N consecutive whitespace-only runs)
2209
+ const wsStart = cursor;
2210
+ while (cursor < children.length && isInlineWhitespaceOnlyRun(children[cursor])) {
2211
+ cursor++;
2212
+ }
2213
+ const wsEnd = cursor;
2214
+ const wsCount = wsEnd - wsStart;
2215
+ if (wsCount === 0)
2216
+ break; // No whitespace → end of chain
2217
+ // Must have a complete [del, ins] pair after the whitespace
2218
+ if (cursor + 1 >= children.length)
2219
+ break; // Not enough elements
2220
+ const nextDel = children[cursor];
2221
+ const nextIns = children[cursor + 1];
2222
+ if (nextDel.tagName !== 'w:del' || nextIns.tagName !== 'w:ins')
2223
+ break;
2224
+ // Author/date must match
2225
+ if (nextDel.getAttribute('w:author') !== author ||
2226
+ nextDel.getAttribute('w:date') !== date ||
2227
+ nextIns.getAttribute('w:author') !== author ||
2228
+ nextIns.getAttribute('w:date') !== date)
2229
+ break;
2230
+ // All conditions met — absorb this [ws..., del, ins] into the first pair
2231
+ // 1. Clone whitespace runs into del (as delText) and ins (as w:t)
2232
+ for (let w = wsStart; w < wsEnd; w++) {
2233
+ const wsRun = children[w];
2234
+ const delClone = wsRun.cloneNode(true);
2235
+ convertRunTextToDelText(delClone);
2236
+ firstDel.appendChild(delClone);
2237
+ const insClone = wsRun.cloneNode(true);
2238
+ firstIns.appendChild(insClone);
2239
+ }
2240
+ // 2. Move nextDel's children into firstDel
2241
+ while (nextDel.firstChild)
2242
+ firstDel.appendChild(nextDel.firstChild);
2243
+ // 3. Move nextIns's children into firstIns
2244
+ while (nextIns.firstChild)
2245
+ firstIns.appendChild(nextIns.firstChild);
2246
+ // 4. Remove ws-runs, nextDel, nextIns from parent
2247
+ for (let w = wsStart; w < wsEnd; w++) {
2248
+ node.removeChild(children[w]);
2249
+ }
2250
+ node.removeChild(nextDel);
2251
+ node.removeChild(nextIns);
2252
+ // 5. Splice removed elements from children snapshot
2253
+ // Remove wsCount + 2 elements starting at wsStart
2254
+ children.splice(wsStart, wsCount + 2);
2255
+ // Reset cursor to continue checking after firstIns
2256
+ cursor = wsStart;
2257
+ chainExtended = true;
2258
+ }
2259
+ // Advance past the (possibly extended) [del, ins] pair
2260
+ i += chainExtended ? 2 : 1;
2261
+ // If no chain was formed, we only skip the del (i++ already happened above
2262
+ // for the non-chain case), but if it was a chain we skip both del+ins.
2263
+ // Actually: if chain wasn't extended, we need to check if firstDel+firstIns
2264
+ // alone should advance by 2 or by 1. Since they ARE a del+ins pair but
2265
+ // no chain formed, skip both.
2266
+ if (!chainExtended) {
2267
+ i++; // skip the ins too (total i += 2 from the earlier i++)
2268
+ }
2269
+ }
2270
+ // Recurse into current children (re-query after mutations)
2271
+ for (const child of childElements(node)) {
2272
+ traverse(child);
2273
+ }
2274
+ }
2275
+ traverse(root);
2276
+ }
2277
+ // Re-export for convenience
2278
+ export { createRevisionIdState };
2279
+ //# sourceMappingURL=inPlaceModifier.js.map