@stll/folio-core 0.67.0 → 0.68.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 (251) hide show
  1. package/dist/ai-edits/apply.d.ts +9 -1
  2. package/dist/ai-edits/apply.js +94 -8
  3. package/dist/ai-edits/headless.d.ts +36 -21
  4. package/dist/ai-edits/headless.js +104 -34
  5. package/dist/ai-edits/index.d.ts +2 -2
  6. package/dist/ai-edits/note-references.d.ts +6 -0
  7. package/dist/ai-edits/note-references.js +7 -1
  8. package/dist/ai-edits/read.d.ts +19 -0
  9. package/dist/ai-edits/snapshot.d.ts +6 -0
  10. package/dist/ai-edits/snapshot.js +8 -3
  11. package/dist/ai-edits/types.d.ts +9 -1
  12. package/dist/ai-suggestions/apply.js +13 -4
  13. package/dist/compare/compare.js +2 -1
  14. package/dist/compare/inserted-resource-snapshot.d.ts +4 -1
  15. package/dist/compare/inserted-resource-snapshot.js +7 -3
  16. package/dist/controller/canonicalClipboard.js +29 -12
  17. package/dist/controller/canonicalComposition.js +1 -1
  18. package/dist/controller/canonicalInlineProjection.d.ts +35 -10
  19. package/dist/controller/canonicalInlineProjection.js +192 -28
  20. package/dist/controller/canonicalInput.d.ts +2 -1
  21. package/dist/controller/canonicalInput.js +28 -1
  22. package/dist/controller/canonicalListRendering.d.ts +2 -1
  23. package/dist/controller/canonicalListRendering.js +1 -1
  24. package/dist/controller/canonicalLockGuard.d.ts +8 -0
  25. package/dist/controller/canonicalLockGuard.js +88 -0
  26. package/dist/controller/canonicalPublicOperations.d.ts +12 -4
  27. package/dist/controller/canonicalPublicOperations.js +274 -20
  28. package/dist/controller/canonicalSession.d.ts +87 -7
  29. package/dist/controller/canonicalSession.js +327 -73
  30. package/dist/controller/canonicalStoryEditor.d.ts +3 -2
  31. package/dist/controller/canonicalStoryEditor.js +4 -3
  32. package/dist/controller/canonicalStructure.d.ts +2 -1
  33. package/dist/controller/canonicalStructure.js +129 -7
  34. package/dist/controller/contentControlWidgetController.d.ts +5 -0
  35. package/dist/controller/contentControlWidgetController.js +13 -1
  36. package/dist/controller/folioEditor.js +1 -0
  37. package/dist/controller/headerFooterEditorManager.d.ts +2 -2
  38. package/dist/controller/headerFooterEditorManager.js +5 -5
  39. package/dist/controller/hiddenEditorApi.d.ts +6 -0
  40. package/dist/controller/hiddenEditorApi.js +1 -0
  41. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  42. package/dist/controller/hiddenEditorManager.js +91 -37
  43. package/dist/controller/layoutPipeline.js +48 -15
  44. package/dist/controller/noteEditorManager.d.ts +2 -2
  45. package/dist/controller/noteEditorManager.js +5 -5
  46. package/dist/display-list/build/pageFurniture.js +41 -19
  47. package/dist/display-list/build/tablePrimitives.js +23 -4
  48. package/dist/display-list/dom/renderDisplayListToDom.js +4 -4
  49. package/dist/document-operations.d.ts +8 -0
  50. package/dist/document-operations.js +4 -3
  51. package/dist/docx/blockContentParser.d.ts +7 -3
  52. package/dist/docx/blockContentParser.js +2 -3
  53. package/dist/docx/blockPlainText.js +2 -0
  54. package/dist/docx/bookmarkRangeJoin.d.ts +6 -0
  55. package/dist/docx/bookmarkRangeJoin.js +43 -0
  56. package/dist/docx/canonicalSave.js +5 -1
  57. package/dist/docx/canonicalSessionInput.d.ts +5 -1
  58. package/dist/docx/canonicalSessionInput.js +7 -2
  59. package/dist/docx/commentAnchorIndex.d.ts +21 -5
  60. package/dist/docx/commentAnchorIndex.js +39 -11
  61. package/dist/docx/commentRangeIntegrity.js +30 -24
  62. package/dist/docx/commentRangeJoin.d.ts +4 -0
  63. package/dist/docx/commentRangeJoin.js +26 -12
  64. package/dist/docx/commentReferenceCompletion.js +5 -4
  65. package/dist/docx/commentReferenceNormalization.js +40 -18
  66. package/dist/docx/compatibility.js +9 -2
  67. package/dist/docx/containerChildren.js +22 -1
  68. package/dist/docx/encryption/compoundFile.js +9 -1
  69. package/dist/docx/encryption/encryptionInfo.js +16 -2
  70. package/dist/docx/ensureParaIds.js +46 -7
  71. package/dist/docx/ensureUniqueControlIds.d.ts +25 -0
  72. package/dist/docx/ensureUniqueControlIds.js +110 -0
  73. package/dist/docx/headerFooterVerbatim.d.ts +7 -0
  74. package/dist/docx/headerFooterVerbatim.js +13 -2
  75. package/dist/docx/hostCommentThreads.d.ts +17 -0
  76. package/dist/docx/hostCommentThreads.js +49 -0
  77. package/dist/docx/hyperlinkParser.js +9 -2
  78. package/dist/docx/inlineWrapperContent.d.ts +8 -1
  79. package/dist/docx/inlineWrapperContent.js +9 -2
  80. package/dist/docx/listMarkerComputation.d.ts +35 -1
  81. package/dist/docx/listMarkerComputation.js +39 -1
  82. package/dist/docx/listModelNormalization.d.ts +44 -1
  83. package/dist/docx/listModelNormalization.js +227 -96
  84. package/dist/docx/markupRangeMarker.d.ts +14 -0
  85. package/dist/docx/markupRangeMarker.js +15 -1
  86. package/dist/docx/metadataPrivacy.js +43 -22
  87. package/dist/docx/normalizeBaseDirection.js +3 -1
  88. package/dist/docx/paragraphParser.js +159 -48
  89. package/dist/docx/paragraphPropertySource.d.ts +7 -0
  90. package/dist/docx/paragraphPropertySource.js +22 -1
  91. package/dist/docx/paragraphTextBoxEnrichment.js +2 -1
  92. package/dist/docx/paragraphTraversal.js +2 -0
  93. package/dist/docx/parseWarningMessage.js +2 -1
  94. package/dist/docx/parser.js +6 -0
  95. package/dist/docx/renderedPageBreakNormalization.js +1 -1
  96. package/dist/docx/reviewProvenanceDiagnostics.d.ts +7 -0
  97. package/dist/docx/reviewProvenanceDiagnostics.js +39 -0
  98. package/dist/docx/reviewResolutionProvenance.d.ts +29 -3
  99. package/dist/docx/reviewResolutionProvenance.js +110 -25
  100. package/dist/docx/rezip.d.ts +6 -0
  101. package/dist/docx/rezip.js +38 -21
  102. package/dist/docx/selectiveSave.js +6 -10
  103. package/dist/docx/selectiveXmlPatch.d.ts +5 -4
  104. package/dist/docx/selectiveXmlPatch.js +11 -7
  105. package/dist/docx/serializer/documentSerializer.js +3 -1
  106. package/dist/docx/serializer/headerFooterSerializer.js +3 -1
  107. package/dist/docx/serializer/markupRangeAttributes.d.ts +6 -1
  108. package/dist/docx/serializer/markupRangeAttributes.js +6 -1
  109. package/dist/docx/serializer/noteSerializer.d.ts +17 -4
  110. package/dist/docx/serializer/noteSerializer.js +23 -16
  111. package/dist/docx/serializer/paragraphSerializer.js +56 -12
  112. package/dist/docx/serializer/runSerializer.d.ts +1 -3
  113. package/dist/docx/serializer/runSerializer.js +2 -2
  114. package/dist/docx/serializer/tableSerializer.d.ts +4 -0
  115. package/dist/docx/serializer/tableSerializer.js +4 -2
  116. package/dist/docx/server/applyDocxXmlPatchProposal.js +8 -4
  117. package/dist/docx/server/createBilingualDocument.js +27 -5
  118. package/dist/docx/server/migrateYjsAttrSchema.js +4 -0
  119. package/dist/docx/sessionListPruning.d.ts +2 -0
  120. package/dist/docx/sessionListPruning.js +50 -0
  121. package/dist/docx/splitRevisionPieces.d.ts +10 -0
  122. package/dist/docx/splitRevisionPieces.js +14 -0
  123. package/dist/docx/storyBlockReplay.js +4 -0
  124. package/dist/docx/structuralXmlPatch.js +19 -7
  125. package/dist/docx/tableParser.d.ts +6 -2
  126. package/dist/docx/tableParser.js +2 -3
  127. package/dist/docx/textBoxContentParser.d.ts +11 -0
  128. package/dist/docx/textBoxContentParser.js +51 -0
  129. package/dist/docx/textBoxParser.d.ts +0 -5
  130. package/dist/docx/textBoxParser.js +1 -23
  131. package/dist/docx/verticalMergeProjection.js +1 -1
  132. package/dist/fonts/fontsourceFaces.d.ts +2 -8
  133. package/dist/fonts/fontsourceFaces.js +1 -7
  134. package/dist/i18n/messages/ar.gen.js +2 -0
  135. package/dist/i18n/messages/catalogs.gen.d.ts +34 -0
  136. package/dist/i18n/messages/catalogs.gen.js +34 -0
  137. package/dist/i18n/messages/cs.gen.js +2 -0
  138. package/dist/i18n/messages/de.gen.js +2 -0
  139. package/dist/i18n/messages/en.gen.js +2 -0
  140. package/dist/i18n/messages/es.gen.js +2 -0
  141. package/dist/i18n/messages/et.gen.js +2 -0
  142. package/dist/i18n/messages/fr.gen.js +2 -0
  143. package/dist/i18n/messages/he.gen.js +2 -0
  144. package/dist/i18n/messages/hi.gen.js +2 -0
  145. package/dist/i18n/messages/hu.gen.js +2 -0
  146. package/dist/i18n/messages/lt.gen.js +2 -0
  147. package/dist/i18n/messages/lv.gen.js +2 -0
  148. package/dist/i18n/messages/messages.gen.d.ts +2 -0
  149. package/dist/i18n/messages/pl.gen.js +2 -0
  150. package/dist/i18n/messages/pt-BR.gen.js +2 -0
  151. package/dist/i18n/messages/sk.gen.js +2 -0
  152. package/dist/i18n/messages/tr.gen.js +2 -0
  153. package/dist/i18n/messages/zh-CN.gen.js +2 -0
  154. package/dist/internal/acceptedBlockProjection.js +2 -0
  155. package/dist/internal/pageBreakRunSourceDescendantIndex.d.ts +5 -0
  156. package/dist/internal/pageBreakRunSourceDescendantIndex.js +5 -0
  157. package/dist/internal/revisionResolutionInline.js +1 -2
  158. package/dist/layout-bridge/convert/tableConversion.js +19 -8
  159. package/dist/layout-bridge/engine/blockIndex.d.ts +7 -0
  160. package/dist/layout-bridge/engine/blockIndex.js +12 -0
  161. package/dist/layout-bridge/engine/hitTest.js +9 -10
  162. package/dist/layout-bridge/engine/selectionRects.js +6 -6
  163. package/dist/layout-engine/footnoteContinuation.d.ts +36 -0
  164. package/dist/layout-engine/footnoteContinuation.js +210 -0
  165. package/dist/layout-engine/index.d.ts +2 -2
  166. package/dist/layout-engine/index.js +7 -2
  167. package/dist/layout-engine/measure/cache.js +10 -5
  168. package/dist/layout-engine/measure/measureParagraph.js +1 -1
  169. package/dist/layout-engine/tableLayout.js +29 -5
  170. package/dist/layout-engine/tableRowBreak.d.ts +36 -0
  171. package/dist/layout-engine/tableRowBreak.js +43 -1
  172. package/dist/layout-engine/types.d.ts +36 -1
  173. package/dist/layout-painter/renderPage.d.ts +4 -4
  174. package/dist/layout-painter/renderPage.js +46 -17
  175. package/dist/layout-painter/renderTable.js +7 -4
  176. package/dist/managers/AutoSaveManager.d.ts +5 -1
  177. package/dist/managers/FindReplaceManager.js +3 -10
  178. package/dist/markdown/escape.d.ts +20 -1
  179. package/dist/markdown/escape.js +43 -1
  180. package/dist/markdown/renderBlock.js +4 -1
  181. package/dist/markdown/renderParagraph.js +13 -27
  182. package/dist/markdown/renderTable.js +6 -2
  183. package/dist/markdown/trailers.js +1 -0
  184. package/dist/pdf/images.d.ts +17 -1
  185. package/dist/pdf/images.js +22 -4
  186. package/dist/pdf/writePdf.js +4 -2
  187. package/dist/prosemirror/attrs/index.js +1 -0
  188. package/dist/prosemirror/canonicalCommands.d.ts +39 -1
  189. package/dist/prosemirror/canonicalTableCommands.d.ts +28 -0
  190. package/dist/prosemirror/canonicalTableCommands.js +362 -0
  191. package/dist/prosemirror/commands/comments.d.ts +25 -0
  192. package/dist/prosemirror/commands/comments.js +102 -11
  193. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  194. package/dist/prosemirror/commands/index.d.ts +1 -1
  195. package/dist/prosemirror/commentIdAllocator.js +2 -2
  196. package/dist/prosemirror/commentRangeBoundaryAttrs.d.ts +6 -0
  197. package/dist/prosemirror/commentRangeBoundaryAttrs.js +9 -3
  198. package/dist/prosemirror/commentReferenceIntegrity.js +3 -4
  199. package/dist/prosemirror/conversion/fromProseDoc.d.ts +2 -0
  200. package/dist/prosemirror/conversion/fromProseDoc.js +76 -31
  201. package/dist/prosemirror/conversion/index.d.ts +1 -1
  202. package/dist/prosemirror/conversion/toProseDoc.d.ts +128 -1
  203. package/dist/prosemirror/conversion/toProseDoc.js +319 -51
  204. package/dist/prosemirror/extensions/StarterKit.js +2 -0
  205. package/dist/prosemirror/extensions/core/DocExtension.js +1 -1
  206. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.d.ts +1 -1
  207. package/dist/prosemirror/extensions/features/JoinedRunStyleExtension.d.ts +1 -1
  208. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +1 -1
  209. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +1 -1
  210. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +5 -4
  211. package/dist/prosemirror/extensions/marks/CommentExtension.js +6 -3
  212. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.d.ts +4 -0
  213. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.js +49 -0
  214. package/dist/prosemirror/extensions/nodes/ImageExtension.js +12 -3
  215. package/dist/prosemirror/extensions/nodes/TableExtension.js +32 -31
  216. package/dist/prosemirror/extensions/nodes/TextBoxExtension.js +1 -1
  217. package/dist/prosemirror/index.d.ts +2 -2
  218. package/dist/prosemirror/listLabels.js +3 -2
  219. package/dist/prosemirror/listNumbering.d.ts +6 -0
  220. package/dist/prosemirror/listNumbering.js +12 -9
  221. package/dist/prosemirror/lockedControls.d.ts +13 -0
  222. package/dist/prosemirror/lockedControls.js +106 -0
  223. package/dist/prosemirror/markupViewProjection.js +1 -1
  224. package/dist/prosemirror/noteReferenceReview.js +2 -2
  225. package/dist/prosemirror/plugins/documentNumbering.js +4 -1
  226. package/dist/prosemirror/plugins/suggestionMode.js +20 -9
  227. package/dist/prosemirror/plugins/templatePreviewValues.js +16 -1
  228. package/dist/prosemirror/rebaseParagraphRuns.js +1 -1
  229. package/dist/prosemirror/replacedAnnotations.js +1 -0
  230. package/dist/prosemirror/runFormattingFromMarks.d.ts +0 -1
  231. package/dist/prosemirror/runFormattingFromMarks.js +2 -4
  232. package/dist/prosemirror/runFormattingReconciliation.js +2 -2
  233. package/dist/prosemirror/runPropertyChangeResolution.js +1 -2
  234. package/dist/prosemirror/runStyleFormatting.d.ts +14 -4
  235. package/dist/prosemirror/runStyleFormatting.js +16 -13
  236. package/dist/prosemirror/schema/marks.d.ts +6 -0
  237. package/dist/prosemirror/styles/paragraphStyleCascade.js +2 -2
  238. package/dist/prosemirror/validation.js +1 -0
  239. package/dist/redline.js +23 -9
  240. package/dist/server.d.ts +2 -2
  241. package/dist/style-sets/extract.js +2 -2
  242. package/dist/types/canonicalCapabilities.d.ts +29 -8
  243. package/dist/types/canonicalCapabilities.js +13 -9
  244. package/dist/utils/cssString.d.ts +7 -0
  245. package/dist/utils/cssString.js +9 -0
  246. package/dist/utils/fontResolver.js +4 -1
  247. package/dist/utils/replaceText.d.ts +11 -0
  248. package/dist/utils/replaceText.js +39 -7
  249. package/dist/version-comparison.d.ts +9 -1
  250. package/dist/version-comparison.js +11 -5
  251. package/package.json +2 -2
@@ -21,8 +21,10 @@ const normalizeCommentReferences = ({ documentBody, comments, headers, footers,
21
21
  return;
22
22
  }
23
23
  if (isCommentRangeMarker(item)) rangeMarkers.push({
24
- content,
25
- index,
24
+ slot: {
25
+ content,
26
+ index
27
+ },
26
28
  id: item.id,
27
29
  type: item.type
28
30
  });
@@ -32,19 +34,40 @@ const normalizeCommentReferences = ({ documentBody, comments, headers, footers,
32
34
  for (const row of table.rows) for (const cell of row.cells) normalizeBlocks(cell.content);
33
35
  };
34
36
  const normalizeBlock = (block) => {
35
- if (block.type === "paragraph") {
36
- normalizeParagraph(block);
37
- return;
38
- }
39
- if (block.type === "table") {
40
- normalizeTable(block);
41
- return;
37
+ switch (block.type) {
38
+ case "commentRangeStart":
39
+ case "commentRangeEnd":
40
+ if (validCommentIds.has(block.id)) rangeMarkers.push({
41
+ id: block.id,
42
+ type: block.type
43
+ });
44
+ return;
45
+ case "paragraph":
46
+ normalizeParagraph(block);
47
+ return;
48
+ case "table":
49
+ normalizeTable(block);
50
+ return;
51
+ case "blockSdt":
52
+ case "blockCustomXml":
53
+ normalizeBlocks(block.content);
54
+ return;
55
+ case "preservedBlock":
56
+ case "bookmarkStart":
57
+ case "bookmarkEnd":
58
+ case "moveFromRangeStart":
59
+ case "moveFromRangeEnd":
60
+ case "moveToRangeStart":
61
+ case "moveToRangeEnd": return;
62
+ default: return block;
42
63
  }
43
- if (block.type !== "blockSdt" && block.type !== "blockCustomXml") return;
44
- normalizeBlocks(block.content);
45
64
  };
46
65
  const normalizeBlocks = (blocks) => {
47
66
  for (const block of blocks) normalizeBlock(block);
67
+ for (const [index, block] of blocks.entries()) if ((block.type === "commentRangeStart" || block.type === "commentRangeEnd") && !validCommentIds.has(block.id)) blocks[index] = {
68
+ type: "preservedBlock",
69
+ xml: `<w:${block.type} w:id="${String(block.id)}"${block.displacedByCustomXml === void 0 ? "" : ` w:displacedByCustomXml="${block.displacedByCustomXml}"`}/>`
70
+ };
48
71
  };
49
72
  normalizeBlocks(documentBody.content);
50
73
  for (const header of headers?.values() ?? []) normalizeBlocks(header.content);
@@ -75,32 +98,31 @@ const reanchorUnbalancedCommentRanges = (rangeMarkers) => {
75
98
  for (const marker of markers) {
76
99
  if (marker.type === "commentRangeStart") {
77
100
  if (openStart) {
78
- reanchorCommentRangeMarker(marker);
79
- reanchoredCount += 1;
101
+ if (reanchorCommentRangeMarker(marker)) reanchoredCount += 1;
80
102
  continue;
81
103
  }
82
104
  openStart = marker;
83
105
  continue;
84
106
  }
85
107
  if (!openStart) {
86
- reanchorCommentRangeMarker(marker);
87
- reanchoredCount += 1;
108
+ if (reanchorCommentRangeMarker(marker)) reanchoredCount += 1;
88
109
  continue;
89
110
  }
90
111
  openStart = null;
91
112
  }
92
113
  if (openStart) {
93
- reanchorCommentRangeMarker(openStart);
94
- reanchoredCount += 1;
114
+ if (reanchorCommentRangeMarker(openStart)) reanchoredCount += 1;
95
115
  }
96
116
  }
97
117
  return reanchoredCount;
98
118
  };
99
119
  const reanchorCommentRangeMarker = (marker) => {
100
- marker.content[marker.index] = {
120
+ if (!marker.slot) return false;
121
+ marker.slot.content[marker.slot.index] = {
101
122
  type: "commentReference",
102
123
  id: marker.id
103
124
  };
125
+ return true;
104
126
  };
105
127
  const isCommentMarker = (content) => content.type === "commentRangeStart" || content.type === "commentRangeEnd" || content.type === "commentReference";
106
128
  const isCommentRangeMarker = (content) => content.type === "commentRangeStart" || content.type === "commentRangeEnd";
@@ -190,9 +190,16 @@ function inspectHyperlink(hyperlink, context) {
190
190
  });
191
191
  continue;
192
192
  }
193
- if (child.type === "inlineWrapper") inspectParagraphContent(child.content, {
193
+ if (child.type === "inlineWrapper") {
194
+ inspectParagraphContent(child.content, {
195
+ ...context,
196
+ path: `${path}.content`
197
+ });
198
+ continue;
199
+ }
200
+ if (child.type === "complexField") inspectParagraphContent([child], {
194
201
  ...context,
195
- path: `${path}.content`
202
+ path
196
203
  });
197
204
  }
198
205
  }
@@ -1,6 +1,7 @@
1
1
  import { TRANSITIONAL_NAMESPACE_BY_STRICT_URI } from "./strictValueEncodings.gen.js";
2
2
  import { captureVerbatimXml } from "./verbatimCapture.js";
3
3
  import { WORDPROCESSINGML_NAMESPACE_URIS, getChildElements, getLocalName, getNamespaceUri } from "./xmlParser.js";
4
+ import { OOXML_NS } from "@stll/docx-utils";
4
5
  import { SEQUENCE_CHILDREN } from "@stll/docx-core/schema";
5
6
  // src/docx/containerChildren.ts
6
7
  /** Keep this child's markup verbatim, in place. */
@@ -167,13 +168,33 @@ const sequenceOrdinals = (container) => {
167
168
  SEQUENCE_ORDINALS.set(container, ordinals);
168
169
  return ordinals;
169
170
  };
171
+ /**
172
+ * Where a container's schema puts the children of its extension namespaces.
173
+ *
174
+ * The neighbour rule cannot hold for these: an edit that adds a declared
175
+ * property after the source's last one would land it behind the extension
176
+ * child, out of the order the extended schema requires. `CT_RPr` appends the
177
+ * `w14` run effects (`w14:ligatures`, `w14:textFill` and the rest) after
178
+ * every base property and before `w:rPrChange`, so they take the place of the
179
+ * declared child before that record.
180
+ */
181
+ const EXTENSION_PLACEMENT = { "run-properties": {
182
+ namespaces: /* @__PURE__ */ new Set([OOXML_NS.w14]),
183
+ after: "oMath"
184
+ } };
170
185
  const computeSequencePositions = (container, element) => {
171
186
  const ordinals = sequenceOrdinals(container);
187
+ const extension = EXTENSION_PLACEMENT[container];
188
+ const extensionAt = extension === void 0 ? -1 : ordinals.get(extension.after) ?? -1;
172
189
  const positions = /* @__PURE__ */ new Map();
173
190
  let previous = -1;
174
191
  for (const child of getChildElements(element)) {
175
192
  const namespace = getNamespaceUri(child);
176
- const at = namespace === void 0 || WORDPROCESSINGML_NAMESPACE_URIS.has(namespace) ? ordinals.get(getLocalName(child.name)) ?? -1 : -1;
193
+ const isDeclaredNamespace = namespace === void 0 || WORDPROCESSINGML_NAMESPACE_URIS.has(namespace);
194
+ const isExtension = namespace !== void 0 && extension?.namespaces.has(namespace) === true && extensionAt !== -1;
195
+ let at = -1;
196
+ if (isDeclaredNamespace) at = ordinals.get(getLocalName(child.name)) ?? -1;
197
+ else if (isExtension) at = extensionAt;
177
198
  if (at !== -1) previous = at;
178
199
  positions.set(child, at === -1 ? previous : at);
179
200
  }
@@ -83,6 +83,8 @@ const loadSector = (file, header, sectorId) => {
83
83
  return file.subarray(offset, offset + header.sectorBytes);
84
84
  };
85
85
  const loadFatSectorIds = (file, header) => {
86
+ const physicalSectors = Math.floor(file.length / header.sectorBytes) - 1;
87
+ if (header.fatSectorCount > physicalSectors) throw new Error(`Declared FAT sector count ${header.fatSectorCount} exceeds the ${physicalSectors} sectors in the file`);
86
88
  const ids = [...header.headerDifat];
87
89
  const maxDifatSectors = Math.ceil(file.length / header.sectorBytes);
88
90
  const stepLimit = Math.min(header.difatSectorCount, maxDifatSectors);
@@ -102,7 +104,13 @@ const loadFatSectorIds = (file, header) => {
102
104
  chain = u32(view, header.sectorBytes - 4);
103
105
  }
104
106
  if (ids.length < header.fatSectorCount) throw new Error("DIFAT chain shorter than declared FAT sector count");
105
- return ids.slice(0, header.fatSectorCount);
107
+ const fatSectorIds = ids.slice(0, header.fatSectorCount);
108
+ const listed = /* @__PURE__ */ new Set();
109
+ for (const id of fatSectorIds) {
110
+ if (listed.has(id)) throw new Error(`FAT sector ${id} listed more than once`);
111
+ listed.add(id);
112
+ }
113
+ return fatSectorIds;
106
114
  };
107
115
  const loadFat = (file, header) => {
108
116
  const table = [];
@@ -85,6 +85,20 @@ const requireSpinCount = (attrs, element) => {
85
85
  });
86
86
  return spinCount;
87
87
  };
88
+ /**
89
+ * Agile decryption here is AES-CBC only, whose block is always 16 bytes.
90
+ * The block size also sizes the padded verifier and segment IVs, so any
91
+ * other declared value is refused while parsing.
92
+ */
93
+ const AES_BLOCK_BYTES = 16;
94
+ const requireAesBlockSize = (attrs, element) => {
95
+ const blockSize = requireInt(attrs, "blockSize", element);
96
+ if (blockSize !== AES_BLOCK_BYTES) throw new DocxEncryptionError({
97
+ code: DOCX_ENCRYPTION_ERROR_CODES.DECRYPTION_FAILED,
98
+ message: `EncryptionInfo <${element}> attribute "blockSize" must be ${AES_BLOCK_BYTES}: ${blockSize}`
99
+ });
100
+ return blockSize;
101
+ };
88
102
  const parseAgileXml = (xmlBytes) => {
89
103
  const xml = decodeText(xmlBytes, { encoding: "utf-8" });
90
104
  const keyDataTag = findElement(xml, "keyData");
@@ -102,14 +116,14 @@ const parseAgileXml = (xmlBytes) => {
102
116
  packageKeyBits: requireInt(keyData, "keyBits", "keyData"),
103
117
  packageHash: requireAttr(keyData, "hashAlgorithm", "keyData"),
104
118
  packageHashBytes: requireInt(keyData, "hashSize", "keyData"),
105
- cipherBlockBytes: requireInt(keyData, "blockSize", "keyData"),
119
+ cipherBlockBytes: requireAesBlockSize(keyData, "keyData"),
106
120
  cipherName: requireAttr(keyData, "cipherAlgorithm", "keyData"),
107
121
  cipherMode: requireAttr(keyData, "cipherChaining", "keyData"),
108
122
  passwordIterations: requireSpinCount(encryptedKey, "encryptedKey"),
109
123
  passwordSalt: requireBase64(encryptedKey, "saltValue", "encryptedKey"),
110
124
  passwordHash: requireAttr(encryptedKey, "hashAlgorithm", "encryptedKey"),
111
125
  passwordKeyBits: requireInt(encryptedKey, "keyBits", "encryptedKey"),
112
- passwordBlockBytes: requireInt(encryptedKey, "blockSize", "encryptedKey"),
126
+ passwordBlockBytes: requireAesBlockSize(encryptedKey, "encryptedKey"),
113
127
  encryptedVerifierInput: requireBase64(encryptedKey, "encryptedVerifierHashInput", "encryptedKey"),
114
128
  encryptedVerifierDigest: requireBase64(encryptedKey, "encryptedVerifierHashValue", "encryptedKey"),
115
129
  encryptedIntermediateKey: requireBase64(encryptedKey, "encryptedKeyValue", "encryptedKey"),
@@ -1,4 +1,4 @@
1
- import { deterministicHexId } from "../utils/hexId.js";
1
+ import { deterministicHexId, isValidHexId } from "../utils/hexId.js";
2
2
  import { resolvePackageRelationshipTarget } from "./packageParts.js";
3
3
  import { spliceXml } from "./selectiveXmlPatch.js";
4
4
  import { loadDocxArchive } from "./server/boundedArchive.js";
@@ -29,7 +29,9 @@ import { ZipArchive } from "@stll/docx-core/zip";
29
29
  * so documents carrying features folio's parser does not model come back
30
30
  * with those features byte-identical. Contract:
31
31
  *
32
- * - Parts covered: the officeDocument relationship target, `word/header*.xml`, `word/footer*.xml`,
32
+ * - Parts covered: the officeDocument relationship target, the header,
33
+ * footer, footnotes, and endnotes parts its relationships name (wherever
34
+ * they live), and `word/header*.xml`, `word/footer*.xml`,
33
35
  * `word/footnotes.xml`, `word/endnotes.xml`. Paragraphs nested in table
34
36
  * cells and in `mc:Choice` text boxes are plain `<w:p>` elements inside
35
37
  * those parts and are covered by the same scan. The comments part mints its
@@ -38,8 +40,9 @@ import { ZipArchive } from "@stll/docx-core/zip";
38
40
  * - Paragraphs inside `mc:Fallback` are never modified: Word regenerates the
39
41
  * fallback branch (duplicating the `mc:Choice` ids) on save, so stamping or
40
42
  * deduplicating there would churn on every Word round-trip.
41
- * - Existing ids are preserved. Only three cases get a fresh id: a missing
43
+ * - Existing ids are preserved. Only these cases get a fresh id: a missing
42
44
  * `paraId`, the reserved all-zero value (Word reads `00000000` as "no id"),
45
+ * a value that is not eight hex digits (the parser drops it as no id),
43
46
  * and a duplicate of an id already seen earlier in the scan (first
44
47
  * occurrence keeps it — the same rule `ParaIdAllocatorExtension` applies in
45
48
  * the editor). `w14:textId` is written alongside a newly minted `paraId`
@@ -78,6 +81,13 @@ const DIGITAL_SIGNATURE_PART_PREFIX = "_xmlsignatures/";
78
81
  /** Word reads an all-zero `w14:paraId` as "no id assigned". */
79
82
  const RESERVED_ZERO_ID_PATTERN = /^0*$/u;
80
83
  const PACKAGE_RELATIONSHIP_URI = "http://schemas.openxmlformats.org/package/2006/relationships";
84
+ /** Relationship types, under each office namespace, whose targets are editable stories. */
85
+ const STORY_RELATIONSHIP_TYPES = [
86
+ "header",
87
+ "footer",
88
+ "footnotes",
89
+ "endnotes"
90
+ ];
81
91
  const TARGET_PART_PATTERNS = [
82
92
  /^word\/header\d*\.xml$/u,
83
93
  /^word\/footer\d*\.xml$/u,
@@ -241,7 +251,7 @@ const scanPart = ({ partPath, spelling, context, seen }) => {
241
251
  continue;
242
252
  }
243
253
  const value = paraId.value.toUpperCase();
244
- const unassigned = RESERVED_ZERO_ID_PATTERN.test(value);
254
+ const unassigned = !isValidHexId(value) || RESERVED_ZERO_ID_PATTERN.test(value);
245
255
  if (!unassigned && !seen.has(value)) {
246
256
  seen.add(value);
247
257
  continue;
@@ -316,8 +326,33 @@ const mainDocumentPart = (rels, entries) => {
316
326
  if (name === void 0) throw createEnsureParaIdsError("officeDocument part not found");
317
327
  return name;
318
328
  };
329
+ /** The `.rels` part that holds `partName`'s relationships. */
330
+ const relationshipsPathFor = (partName) => {
331
+ const slash = partName.lastIndexOf("/");
332
+ return `${partName.slice(0, slash + 1)}_rels/${partName.slice(slash + 1)}.rels`;
333
+ };
334
+ /**
335
+ * The header, footer, and note parts the main part's relationships name.
336
+ * The parser follows these relationships, so a story at a custom path
337
+ * (`word/custom/defaultHeader.xml`) is as editable as `word/header1.xml`.
338
+ */
339
+ const relatedStoryParts = (rels, relsPath, entries) => {
340
+ const parts = /* @__PURE__ */ new Set();
341
+ const root = rels === null ? null : parseXmlDocument(rels);
342
+ if (root === null || getLocalName(root.name ?? "") !== "Relationships" || getNamespaceUri(root) !== PACKAGE_RELATIONSHIP_URI) return parts;
343
+ const storyTypes = /* @__PURE__ */ new Set();
344
+ for (const uri of OFFICE_RELATIONSHIP_NAMESPACE_URIS) for (const type of STORY_RELATIONSHIP_TYPES) storyTypes.add(`${uri}/${type}`);
345
+ for (const element of getChildElements(root)) {
346
+ if (getLocalName(element.name ?? "") !== "Relationship" || getNamespaceUri(element) !== PACKAGE_RELATIONSHIP_URI || !storyTypes.has(getAttribute(element, null, "Type") ?? "") || getAttribute(element, null, "TargetMode") === "External") continue;
347
+ const target = getAttribute(element, null, "Target");
348
+ const partPath = target === null ? void 0 : resolvePackageRelationshipTarget(target, relsPath);
349
+ const name = partPath === void 0 ? void 0 : entries.find((entry) => entry.toLowerCase() === partPath);
350
+ if (name !== void 0) parts.add(name);
351
+ }
352
+ return parts;
353
+ };
319
354
  /** OPC part names are case-insensitive; compare lowercased. */
320
- const isTargetPart = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
355
+ const matchesTargetPattern = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
321
356
  const toUint8Array = (docx) => docx instanceof Uint8Array ? docx : new Uint8Array(docx);
322
357
  const hasDigitalSignatureParts = (zip) => zip.entries().some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
323
358
  /**
@@ -331,7 +366,11 @@ const ensureParaIdsInternal = async (docx, options) => {
331
366
  const rels = relsPath === void 0 ? null : await archive.readEntryString(relsPath);
332
367
  if (rels === null) throw createEnsureParaIdsError("Package relationships not found");
333
368
  const documentPartName = mainDocumentPart(rels, archive.entries);
334
- const xmlPartNames = archive.entries.filter((name) => name.toLowerCase().endsWith(".xml") || name === documentPartName);
369
+ const documentRelsPath = relationshipsPathFor(documentPartName);
370
+ const documentRelsName = archive.entries.find((name) => name.toLowerCase() === documentRelsPath.toLowerCase());
371
+ const storyParts = relatedStoryParts(documentRelsName === void 0 ? null : await archive.readEntryString(documentRelsName), documentRelsPath, archive.entries);
372
+ const isTargetPart = (name) => name !== documentPartName && (storyParts.has(name) || matchesTargetPattern(name));
373
+ const xmlPartNames = archive.entries.filter((name) => name.toLowerCase().endsWith(".xml") || name === documentPartName || storyParts.has(name));
335
374
  const partTexts = /* @__PURE__ */ new Map();
336
375
  for (const name of xmlPartNames) {
337
376
  const text = await archive.readEntryString(name);
@@ -345,7 +384,7 @@ const ensureParaIdsInternal = async (docx, options) => {
345
384
  taken,
346
385
  docKey: deterministicHexId(documentXml)
347
386
  };
348
- const targetParts = [documentPartName, ...xmlPartNames.filter((name) => name !== documentPartName && isTargetPart(name)).sort((a, b) => a.localeCompare(b))];
387
+ const targetParts = [documentPartName, ...xmlPartNames.filter((name) => isTargetPart(name)).sort((a, b) => a.localeCompare(b))];
349
388
  const spellings = /* @__PURE__ */ new Map();
350
389
  const seen = /* @__PURE__ */ new Set();
351
390
  for (const [partPath, xml] of partTexts) if (partPath === documentPartName || isTargetPart(partPath)) {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Headless `w:sdtPr/w:id` normalization for a `.docx` buffer.
3
+ *
4
+ * A content control names itself by `w:id`, and the package model holds
5
+ * every control by that id. A package can repeat one: a producer that copied
6
+ * a control, or merged two documents, wrote the same id twice. The first
7
+ * control in document order keeps its id; each later control carrying it gets
8
+ * an id the package does not use. Every control is kept, and so is everything
9
+ * else in the part.
10
+ *
11
+ * Alternate content (`mc:Fallback`) restates the controls of its `mc:Choice`
12
+ * under the same ids for older readers, and the parser reads one of the two,
13
+ * so a fallback's ids are reserved but never counted as a repeat.
14
+ */
15
+ export type EnsureUniqueControlIdsResult = {
16
+ /** The normalized `.docx`; the input bytes when nothing repeated. */
17
+ docx: Uint8Array;
18
+ /** Controls given a new id. */
19
+ reminted: number;
20
+ };
21
+ /**
22
+ * Give each content control after the first carrying an id an id of its own.
23
+ * A signed package, or a part that does not scan, is left as it is.
24
+ */
25
+ export declare const ensureUniqueControlIds: (docx: Uint8Array) => Promise<EnsureUniqueControlIdsResult>;
@@ -0,0 +1,110 @@
1
+ import { spliceXml } from "./selectiveXmlPatch.js";
2
+ import { WORDPROCESSINGML_NAMESPACE_URIS, getLocalName, getNamespaceUri, resolveAttributeNamespaceUri } from "./xmlParser.js";
3
+ import { scanStreamingXmlElements } from "@stll/docx-core/xml";
4
+ import { ZipArchive } from "@stll/docx-core/zip";
5
+ // src/docx/ensureUniqueControlIds.ts
6
+ /**
7
+ * Headless `w:sdtPr/w:id` normalization for a `.docx` buffer.
8
+ *
9
+ * A content control names itself by `w:id`, and the package model holds
10
+ * every control by that id. A package can repeat one: a producer that copied
11
+ * a control, or merged two documents, wrote the same id twice. The first
12
+ * control in document order keeps its id; each later control carrying it gets
13
+ * an id the package does not use. Every control is kept, and so is everything
14
+ * else in the part.
15
+ *
16
+ * Alternate content (`mc:Fallback`) restates the controls of its `mc:Choice`
17
+ * under the same ids for older readers, and the parser reads one of the two,
18
+ * so a fallback's ids are reserved but never counted as a repeat.
19
+ */
20
+ const MC_NAMESPACE_URI = "http://schemas.openxmlformats.org/markup-compatibility/2006";
21
+ const DIGITAL_SIGNATURE_PART_PREFIX = "_xmlsignatures/";
22
+ /** The story parts: the body, headers, footers, notes and comments. */
23
+ const STORY_PART_PATTERN = /^word\/[^/]+\.xml$/iu;
24
+ const isWordprocessing = (element, localName) => getLocalName(element.name ?? "") === localName && WORDPROCESSINGML_NAMESPACE_URIS.has(getNamespaceUri(element) ?? "");
25
+ /** Every control id a part carries, in document order. */
26
+ const controlIdsIn = (xml) => {
27
+ const out = [];
28
+ const fallbacks = /* @__PURE__ */ new WeakSet();
29
+ return scanStreamingXmlElements(xml, ({ element, attributeValueSpans, parent }) => {
30
+ const inFallback = parent !== void 0 && fallbacks.has(parent) || getLocalName(element.name ?? "") === "Fallback" && getNamespaceUri(element) === MC_NAMESPACE_URI;
31
+ if (inFallback) fallbacks.add(element);
32
+ if (parent === void 0 || !isWordprocessing(element, "id") || !isWordprocessing(parent, "sdtPr")) return;
33
+ for (const [name, span] of attributeValueSpans) {
34
+ if (getLocalName(name) !== "val" || !WORDPROCESSINGML_NAMESPACE_URIS.has(resolveAttributeNamespaceUri(element, name) ?? "")) continue;
35
+ const value = Number(element.attributes?.[name]);
36
+ if (Number.isInteger(value)) out.push({
37
+ start: span.start,
38
+ end: span.end,
39
+ value,
40
+ inFallback
41
+ });
42
+ }
43
+ }).status === "scanned" ? out : void 0;
44
+ };
45
+ /**
46
+ * Give each content control after the first carrying an id an id of its own.
47
+ * A signed package, or a part that does not scan, is left as it is.
48
+ */
49
+ const ensureUniqueControlIds = async (docx) => {
50
+ const zip = await ZipArchive.read(docx);
51
+ const entries = zip.entries();
52
+ if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
53
+ docx,
54
+ reminted: 0
55
+ };
56
+ const parts = entries.map(({ path }) => path).filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
57
+ const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
58
+ return body(a) - body(b) || a.localeCompare(b);
59
+ });
60
+ const texts = /* @__PURE__ */ new Map();
61
+ const ids = /* @__PURE__ */ new Map();
62
+ const taken = /* @__PURE__ */ new Set();
63
+ for (const path of parts) {
64
+ const xml = await zip.entry(path)?.text();
65
+ if (xml === void 0 || !xml.includes("sdtPr")) continue;
66
+ const found = controlIdsIn(xml);
67
+ if (found === void 0) continue;
68
+ texts.set(path, xml);
69
+ ids.set(path, found);
70
+ for (const { value } of found) taken.add(value);
71
+ }
72
+ let next = 1;
73
+ const fresh = () => {
74
+ while (taken.has(next)) next += 1;
75
+ taken.add(next);
76
+ return next;
77
+ };
78
+ const seen = /* @__PURE__ */ new Set();
79
+ let reminted = 0;
80
+ for (const [path, found] of ids) {
81
+ const edits = [];
82
+ for (const { start, end, value, inFallback } of found) {
83
+ if (inFallback) continue;
84
+ if (!seen.has(value)) {
85
+ seen.add(value);
86
+ continue;
87
+ }
88
+ edits.push({
89
+ start,
90
+ end,
91
+ newXml: String(fresh())
92
+ });
93
+ }
94
+ if (edits.length === 0) continue;
95
+ const patched = spliceXml(texts.get(path), edits);
96
+ if (patched === null) continue;
97
+ const source = zip.entry(path);
98
+ zip.set(path, patched, source ? { modified: source.modified } : {});
99
+ reminted += edits.length;
100
+ }
101
+ if (reminted === 0) return {
102
+ docx,
103
+ reminted
104
+ };
105
+ return {
106
+ docx: await zip.generate({ level: 6 }),
107
+ reminted
108
+ };
109
+ };
110
+ export { ensureUniqueControlIds };
@@ -26,6 +26,13 @@ export declare const refreshHeaderFooterVerbatimFingerprint: (hf: document_d_exp
26
26
  export declare const clearHeaderFooterVerbatimXml: (hf: document_d_exports.HeaderFooter) => void;
27
27
  /** Capture parsed resources on the same trusted handle, including an absent main part. */
28
28
  export declare const captureDocumentSourceBaseline: (document: document_d_exports.Document, xml: string | undefined) => void;
29
+ /** The numbering instance and abstract definition ids the source package had. */
30
+ export type SourceNumberingIds = {
31
+ readonly nums: ReadonlySet<number>;
32
+ readonly abstractNums: ReadonlySet<number>;
33
+ };
34
+ /** The numbering ids the parsed source had, or `undefined` without a capture. */
35
+ export declare const getDocumentSourceNumberingIds: (document: document_d_exports.Document) => SourceNumberingIds | undefined;
29
36
  /** Read the identity-stable, deeply frozen stylesheet without cloning or body comparison. */
30
37
  export declare const getDocumentSourceStyles: (document: document_d_exports.Document, liveStyles?: document_d_exports.Document["package"]["styles"]) => {
31
38
  readonly type: "missing";
@@ -160,11 +160,16 @@ const captureDocumentSourceBaseline = (document, xml) => {
160
160
  const resourceStyles = structuredClone(document.package.styles);
161
161
  freezeSourceStyles(resourceStyles);
162
162
  const styleIds = new Set(resourceStyles?.styles.map(({ styleId }) => styleId));
163
+ const numberingIds = {
164
+ nums: new Set(document.package.numbering?.nums.map(({ numId }) => numId)),
165
+ abstractNums: new Set(document.package.numbering?.abstractNums.map(({ abstractNumId }) => abstractNumId))
166
+ };
163
167
  if (xml === void 0) contentBaselines.set(handle, {
164
168
  type: "body",
165
169
  kind: "noMainPart",
166
170
  resourceStyles,
167
- styleIds
171
+ styleIds,
172
+ numberingIds
168
173
  });
169
174
  else contentBaselines.set(handle, {
170
175
  type: "body",
@@ -174,6 +179,7 @@ const captureDocumentSourceBaseline = (document, xml) => {
174
179
  body: structuredClone(document.package.document),
175
180
  resourceStyles,
176
181
  styleIds,
182
+ numberingIds,
177
183
  resourceRelationships: structuredClone(document.package.relationships),
178
184
  resourceMedia: new Map([...document.package.media ?? []].map(([path, media]) => [path, {
179
185
  data: media.data,
@@ -203,6 +209,11 @@ const readDocumentSourceCapture = (document) => {
203
209
  baseline
204
210
  };
205
211
  };
212
+ /** The numbering ids the parsed source had, or `undefined` without a capture. */
213
+ const getDocumentSourceNumberingIds = (document) => {
214
+ const source = readDocumentSourceCapture(document);
215
+ return source.type === "captured" ? source.baseline.numberingIds : void 0;
216
+ };
206
217
  /** Read the identity-stable, deeply frozen stylesheet without cloning or body comparison. */
207
218
  const getDocumentSourceStyles = (document, liveStyles) => {
208
219
  const source = readDocumentSourceCapture(document);
@@ -239,4 +250,4 @@ const getDocumentSourceBaseline = (document) => {
239
250
  resourceMedia: baseline.resourceMedia
240
251
  };
241
252
  };
242
- export { assignHeaderFooterVerbatimXml, canReplayHeaderFooterBlocks, canReplayHeaderFooterVerbatim, captureDocumentSourceBaseline, captureHeaderFooterPackageBaselines, clearHeaderFooterVerbatimXml, copyHeaderFooterBaselineHandles, copyHeaderFooterPackageBaselines, getDocumentSourceBaseline, getDocumentSourceStyles, getHeaderFooterSourceBaseline, getHeaderFooterVerbatimXml, refreshHeaderFooterVerbatimFingerprint };
253
+ export { assignHeaderFooterVerbatimXml, canReplayHeaderFooterBlocks, canReplayHeaderFooterVerbatim, captureDocumentSourceBaseline, captureHeaderFooterPackageBaselines, clearHeaderFooterVerbatimXml, copyHeaderFooterBaselineHandles, copyHeaderFooterPackageBaselines, getDocumentSourceBaseline, getDocumentSourceNumberingIds, getDocumentSourceStyles, getHeaderFooterSourceBaseline, getHeaderFooterVerbatimXml, refreshHeaderFooterVerbatimFingerprint };
@@ -0,0 +1,17 @@
1
+ import { document_d_exports } from "../types/document.js";
2
+ import { Comment } from "../types/content.js";
3
+ export declare function getCommentParentId(comment: Comment): number | null | undefined;
4
+ /**
5
+ * The comments whose reply chain reaches a top-level comment.
6
+ *
7
+ * Every top-level comment is kept, whether or not its anchor survives:
8
+ * documents without reply-thread metadata deliver replies as top-level
9
+ * comments, and dropping unanchored ones would drop those replies. Replies
10
+ * whose parent chain does not reach a kept top-level comment are dropped.
11
+ */
12
+ export declare function pruneOrphanedComments(comments: readonly Comment[], _referencedIds?: ReadonlySet<number>): Comment[];
13
+ /**
14
+ * `document` with its body's comment threads replaced by the host's. The body
15
+ * and package are copied, so the document passed in is left as it was.
16
+ */
17
+ export declare function withHostCommentThreads(document: document_d_exports.Document, comments: readonly Comment[]): document_d_exports.Document;
@@ -0,0 +1,49 @@
1
+ import { setDocumentBodyComments } from "./canonicalModel.js";
2
+ // src/docx/hostCommentThreads.ts
3
+ function getCommentParentId(comment) {
4
+ return comment.parentId;
5
+ }
6
+ /**
7
+ * The comments whose reply chain reaches a top-level comment.
8
+ *
9
+ * Every top-level comment is kept, whether or not its anchor survives:
10
+ * documents without reply-thread metadata deliver replies as top-level
11
+ * comments, and dropping unanchored ones would drop those replies. Replies
12
+ * whose parent chain does not reach a kept top-level comment are dropped.
13
+ */
14
+ function pruneOrphanedComments(comments, _referencedIds) {
15
+ const keptIds = /* @__PURE__ */ new Set();
16
+ for (const comment of comments) {
17
+ const parentId = getCommentParentId(comment);
18
+ if (parentId === null || parentId === void 0) keptIds.add(comment.id);
19
+ }
20
+ let addedThisPass = true;
21
+ while (addedThisPass) {
22
+ addedThisPass = false;
23
+ for (const comment of comments) {
24
+ if (keptIds.has(comment.id)) continue;
25
+ const parentId = getCommentParentId(comment);
26
+ if (parentId !== null && parentId !== void 0 && keptIds.has(parentId)) {
27
+ keptIds.add(comment.id);
28
+ addedThisPass = true;
29
+ }
30
+ }
31
+ }
32
+ return comments.filter((comment) => keptIds.has(comment.id));
33
+ }
34
+ /**
35
+ * `document` with its body's comment threads replaced by the host's. The body
36
+ * and package are copied, so the document passed in is left as it was.
37
+ */
38
+ function withHostCommentThreads(document, comments) {
39
+ const body = { ...document.package.document };
40
+ setDocumentBodyComments(body, pruneOrphanedComments(comments));
41
+ return {
42
+ ...document,
43
+ package: {
44
+ ...document.package,
45
+ document: body
46
+ }
47
+ };
48
+ }
49
+ export { getCommentParentId, pruneOrphanedComments, withHostCommentThreads };
@@ -8,6 +8,7 @@ import { standalonePreviewLedger } from "./previewBudget.js";
8
8
  import { RELATIONSHIP_TYPES, resolveRelationshipIdOfType } from "./relsParser.js";
9
9
  import { parseRun } from "./runParser.js";
10
10
  import { runHoldsPayload } from "./runPayload.js";
11
+ import { tagSplitPiece } from "./splitRevisionPieces.js";
11
12
  import { WORDPROCESSINGML_NAMESPACE_URIS, findChildren, getAttribute, getAttributeByNamespaceUri, mergeXmlnsDeclarations, parseNumericAttribute, parseOnOffAttribute } from "./xmlParser.js";
12
13
  import { isValidOoxmlNumericId } from "@stll/docx-core";
13
14
  // src/docx/hyperlinkParser.ts
@@ -278,7 +279,9 @@ const parseLinkedInlineWrapper = (element, node, context) => {
278
279
  }
279
280
  }
280
281
  });
281
- return inlineWrapperOf(element, node, withPreservedChildren(content, preserved, preservedInlineCapture));
282
+ const wrapper = inlineWrapperOf(element, node, withPreservedChildren(content, preserved, preservedInlineCapture));
283
+ tagSplitPiece(node, wrapper);
284
+ return wrapper;
282
285
  };
283
286
  /**
284
287
  * Get the display text of a hyperlink
@@ -353,7 +356,11 @@ function getHyperlinkRuns(hyperlink) {
353
356
  runs.push(item);
354
357
  continue;
355
358
  }
356
- if (item.type === "inlineWrapper") collect(item.content);
359
+ if (item.type === "inlineWrapper") {
360
+ collect(item.content);
361
+ continue;
362
+ }
363
+ if (item.type === "complexField") runs.push(...item.fieldResult);
357
364
  }
358
365
  };
359
366
  collect(hyperlink.children);
@@ -110,7 +110,7 @@ export declare const HYPERLINK_CONTENT: {
110
110
  readonly inlineWrapper: true;
111
111
  readonly preservedInline: true;
112
112
  readonly run: true;
113
- readonly complexField: false;
113
+ readonly complexField: true;
114
114
  readonly deletion: false;
115
115
  readonly hyperlink: false;
116
116
  readonly inlineSdt: false;
@@ -155,6 +155,13 @@ export declare const SIMPLE_FIELD_CONTENT: {
155
155
  readonly moveToRangeStart: false;
156
156
  readonly simpleField: false;
157
157
  };
158
+ /**
159
+ * Every paragraph content kind is a tracked change child. The reader keeps a
160
+ * tracked change whole on this: its resolution joins describe the one wrapper.
161
+ * A model kind outside `TrackedRunContent` turns this type to `never`, so the
162
+ * build fails until reading such a change is designed.
163
+ */
164
+ export declare const EVERY_PARAGRAPH_CONTENT_IS_TRACKED_CHILD: (typeof TRACKED_CHANGE_WRAPPER_CONTENT)[document_d_exports.ParagraphContent["type"]] extends true ? true : never;
158
165
  /**
159
166
  * Whether a revision wrapper keeps this content inside itself.
160
167
  *