@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
@@ -19,9 +19,35 @@ export declare const parseCopyOriginAncestors: (node: XmlElement) => CopyOriginA
19
19
  export declare const serializeResolutionJoins: (value: document_d_exports.Insertion["resolutionJoins"]) => string;
20
20
  export declare const serializeBoundaryJoins: (value: document_d_exports.RunPropertyChange["boundaryJoins"]) => string;
21
21
  export declare const serializeCopyOriginAncestors: (value: CopyOriginAncestorList | undefined) => string | undefined;
22
- /** Null carries an owned undefined depth; a missing attribute carries no field. */
23
- export declare const parseParagraphMarkResolutionJoin: (node: XmlElement) => Pick<document_d_exports.ParagraphMarkChange, "resolutionJoin">;
22
+ /**
23
+ * A paragraph mark's private review provenance: its rejection join depth
24
+ * (null carries an owned undefined depth) and the paragraph rejecting it
25
+ * keeps. A missing attribute carries no field.
26
+ */
27
+ export declare const parseParagraphMarkResolutionJoin: (node: XmlElement) => Pick<document_d_exports.ParagraphMarkChange, "resolutionJoin" | "survivor">;
24
28
  export declare const serializeParagraphMarkResolutionJoin: (mark: document_d_exports.ParagraphMarkChange) => string;
25
- /** Captured paragraph properties compose the same envelope into a parsed XML element. */
29
+ /** Captured paragraph properties compose the same envelopes into a parsed XML element. */
26
30
  export declare const paragraphMarkResolutionJoinAttributes: (mark: document_d_exports.ParagraphMarkChange) => Record<string, string>;
31
+ /**
32
+ * One piece of a tracked change written as several elements: a revision that
33
+ * holds a hyperlink is written with the revision inside the link, so a
34
+ * change spanning text and a link becomes one element per stretch. The first
35
+ * piece carries the whole change's resolution joins; every piece says which
36
+ * one it is, so a reader rebuilds the one change, and a change nested in it
37
+ * can be rebuilt in turn. It is its own attribute: a reader that does not know
38
+ * it drops the joins and keeps the revisions.
39
+ */
40
+ export type SplitResolutionPiece = {
41
+ piece: number;
42
+ pieces: number;
43
+ joins?: ResolutionJoins;
44
+ };
45
+ export declare const isSplitResolutionPiece: (value: unknown) => value is SplitResolutionPiece;
46
+ export declare const parseSplitResolutionPiece: (node: XmlElement) => SplitResolutionPiece | undefined;
47
+ export declare const serializeSplitResolutionPiece: (value: SplitResolutionPiece) => string;
48
+ /**
49
+ * Why the reader drops a provenance attribute's value, or `undefined` when it
50
+ * reads it (or does not read that attribute at all).
51
+ */
52
+ export declare const reviewProvenanceIssue: (attribute: string, encoded: string) => "invalid" | "unsupportedVersion" | undefined;
27
53
  export {};
@@ -23,7 +23,8 @@ const JOIN_FIELDS = {
23
23
  remove: true,
24
24
  retainedAfter: true,
25
25
  deferredRemove: true,
26
- acceptance: true
26
+ acceptance: true,
27
+ plainSides: true
27
28
  };
28
29
  const ACCEPTANCE_POLICIES = { "merge-plain-runs": true };
29
30
  const PARAGRAPH_MARK_FIELDS = {
@@ -32,6 +33,10 @@ const PARAGRAPH_MARK_FIELDS = {
32
33
  resolutionJoin: {
33
34
  type: "private",
34
35
  attribute: "resolutionJoin"
36
+ },
37
+ survivor: {
38
+ type: "private",
39
+ attribute: "rejectionSurvivor"
35
40
  }
36
41
  };
37
42
  const DEFERRED_REMOVAL_FIELDS = {
@@ -61,32 +66,56 @@ const deferredRemovals = (value) => {
61
66
  }));
62
67
  return new Set(groups).size === groups.length;
63
68
  };
64
- const isResolutionJoins = (value) => record(value) && Object.keys(value).every((key) => Object.hasOwn(JOIN_FIELDS, key)) && natural(value["before"]) && natural(value["after"]) && natural(value["remove"]) && (!Object.hasOwn(value, "acceptance") || typeof value["acceptance"] === "string" && Object.hasOwn(ACCEPTANCE_POLICIES, value["acceptance"])) && (value["retainedAfter"] === void 0 || retained(value["retainedAfter"])) && (!Object.hasOwn(value, "deferredRemove") || deferredRemovals(value["deferredRemove"]));
69
+ const isResolutionJoins = (value) => record(value) && Object.keys(value).every((key) => Object.hasOwn(JOIN_FIELDS, key)) && natural(value["before"]) && natural(value["after"]) && natural(value["remove"]) && (!Object.hasOwn(value, "acceptance") || typeof value["acceptance"] === "string" && Object.hasOwn(ACCEPTANCE_POLICIES, value["acceptance"])) && (value["retainedAfter"] === void 0 || retained(value["retainedAfter"])) && (!Object.hasOwn(value, "deferredRemove") || deferredRemovals(value["deferredRemove"])) && (!Object.hasOwn(value, "plainSides") || isBoundaryJoins(value["plainSides"]));
65
70
  const isParagraphMarkResolutionJoin = (value) => natural(value) && value <= MAX_REVISION_ID;
66
71
  const isEncodedParagraphMarkResolutionJoin = (value) => value === null || isParagraphMarkResolutionJoin(value);
67
72
  const isBoundaryJoins = (value) => Array.isArray(value) && value.length <= 2 && new Set(value).size === value.length && value.every((side) => side === "before" || side === "after");
68
73
  const ReviewResolutionProvenanceErrorBase = TaggedError("ReviewResolutionProvenanceError");
69
74
  var ReviewResolutionProvenanceError = class extends ReviewResolutionProvenanceErrorBase {};
70
- const parseAttribute = ({ node, attribute, valid }) => {
71
- const encoded = getAttributeByNamespaceUri(node, NAMESPACES, attribute);
72
- if (encoded === null) return void 0;
73
- const failed = (reason = "invalid") => new ReviewResolutionProvenanceError({
74
- attribute,
75
- message: `Invalid or unsupported ${attribute} review provenance.`,
76
- reason
77
- });
78
- if (encoded.length > 32768) throw failed();
75
+ const decodeProvenance = (encoded, valid) => {
76
+ if (encoded.length > 32768) return {
77
+ status: "dropped",
78
+ reason: "invalid"
79
+ };
79
80
  const parsed = Result.try({
80
81
  try: () => JSON.parse(encoded),
81
- catch: () => failed()
82
+ catch: () => void 0
82
83
  });
83
- if (parsed.isErr()) throw parsed.error;
84
+ if (parsed.isErr()) return {
85
+ status: "dropped",
86
+ reason: "invalid"
87
+ };
84
88
  const decoded = parsed.value;
85
- if (!record(decoded) || Object.keys(decoded).some((key) => key !== "version" && key !== "value")) throw failed();
89
+ if (!record(decoded) || Object.keys(decoded).some((key) => key !== "version" && key !== "value")) return {
90
+ status: "dropped",
91
+ reason: "invalid"
92
+ };
93
+ if (decoded["version"] !== VERSION) return {
94
+ status: "dropped",
95
+ reason: "unsupportedVersion"
96
+ };
86
97
  const value = decoded["value"];
87
- if (!valid(value)) throw failed();
88
- if (decoded["version"] !== VERSION) throw failed("unsupportedVersion");
89
- return value;
98
+ if (!valid(value)) return {
99
+ status: "dropped",
100
+ reason: "invalid"
101
+ };
102
+ return {
103
+ status: "read",
104
+ value
105
+ };
106
+ };
107
+ /**
108
+ * Read one provenance attribute. Provenance is advisory, ignorable metadata:
109
+ * a value folio cannot read (another version, a field it does not know, a
110
+ * malformed value) is dropped and the revisions it would annotate are read
111
+ * as they are; {@link reviewProvenanceIssues} reports what was dropped.
112
+ * What folio writes is validated strictly before it is written.
113
+ */
114
+ const parseAttribute = ({ node, attribute, valid }) => {
115
+ const encoded = getAttributeByNamespaceUri(node, NAMESPACES, attribute);
116
+ if (encoded === null) return void 0;
117
+ const decoded = decodeProvenance(encoded, valid);
118
+ return decoded.status === "read" ? decoded.value : void 0;
90
119
  };
91
120
  const encodeAttribute = ({ attribute, value, valid }) => {
92
121
  if (value === void 0) return void 0;
@@ -140,25 +169,81 @@ const serializeCopyOriginAncestors = (value) => encodeAttribute({
140
169
  value,
141
170
  valid: isCopyOriginAncestors
142
171
  });
143
- /** Null carries an owned undefined depth; a missing attribute carries no field. */
172
+ const isParagraphMarkSurvivor = (value) => value === "first";
173
+ /**
174
+ * A paragraph mark's private review provenance: its rejection join depth
175
+ * (null carries an owned undefined depth) and the paragraph rejecting it
176
+ * keeps. A missing attribute carries no field.
177
+ */
144
178
  const parseParagraphMarkResolutionJoin = (node) => {
145
179
  const value = parseAttribute({
146
180
  node,
147
181
  attribute: PARAGRAPH_MARK_FIELDS.resolutionJoin.attribute,
148
182
  valid: isEncodedParagraphMarkResolutionJoin
149
183
  });
150
- return value === void 0 ? {} : { resolutionJoin: value === null ? void 0 : value };
184
+ const survivor = parseAttribute({
185
+ node,
186
+ attribute: PARAGRAPH_MARK_FIELDS.survivor.attribute,
187
+ valid: isParagraphMarkSurvivor
188
+ });
189
+ return {
190
+ ...value === void 0 ? {} : { resolutionJoin: value === null ? void 0 : value },
191
+ ...survivor === void 0 ? {} : { survivor }
192
+ };
151
193
  };
194
+ const paragraphMarkSurvivorOptions = (mark) => ({
195
+ attribute: PARAGRAPH_MARK_FIELDS.survivor.attribute,
196
+ value: mark.survivor,
197
+ valid: isParagraphMarkSurvivor
198
+ });
152
199
  const paragraphMarkResolutionJoinOptions = (mark) => ({
153
200
  attribute: PARAGRAPH_MARK_FIELDS.resolutionJoin.attribute,
154
201
  value: Object.hasOwn(mark, "resolutionJoin") ? mark.resolutionJoin ?? null : void 0,
155
202
  valid: isEncodedParagraphMarkResolutionJoin
156
203
  });
157
- const serializeParagraphMarkResolutionJoin = (mark) => serializeAttribute(paragraphMarkResolutionJoinOptions(mark));
158
- /** Captured paragraph properties compose the same envelope into a parsed XML element. */
204
+ const serializeParagraphMarkResolutionJoin = (mark) => serializeAttribute(paragraphMarkResolutionJoinOptions(mark)) + serializeAttribute(paragraphMarkSurvivorOptions(mark));
205
+ /** Captured paragraph properties compose the same envelopes into a parsed XML element. */
159
206
  const paragraphMarkResolutionJoinAttributes = (mark) => {
160
- const options = paragraphMarkResolutionJoinOptions(mark);
161
- const encoded = encodeAttribute(options);
162
- return encoded === void 0 ? {} : { [`folio:${options.attribute}`]: encoded };
207
+ const attributes = {};
208
+ for (const options of [paragraphMarkResolutionJoinOptions(mark), paragraphMarkSurvivorOptions(mark)]) {
209
+ const encoded = encodeAttribute(options);
210
+ if (encoded !== void 0) attributes[`folio:${options.attribute}`] = encoded;
211
+ }
212
+ return attributes;
213
+ };
214
+ const SPLIT_PIECE_FIELDS = {
215
+ piece: true,
216
+ pieces: true,
217
+ joins: true
218
+ };
219
+ const isSplitResolutionPiece = (value) => record(value) && Object.keys(value).every((key) => Object.hasOwn(SPLIT_PIECE_FIELDS, key)) && natural(value["piece"]) && natural(value["pieces"]) && value["pieces"] >= 2 && value["piece"] < value["pieces"] && (!Object.hasOwn(value, "joins") || value["piece"] === 0 && isResolutionJoins(value["joins"]));
220
+ const parseSplitResolutionPiece = (node) => parseAttribute({
221
+ node,
222
+ attribute: "splitResolutionJoins",
223
+ valid: isSplitResolutionPiece
224
+ });
225
+ const serializeSplitResolutionPiece = (value) => serializeAttribute({
226
+ attribute: "splitResolutionJoins",
227
+ value,
228
+ valid: isSplitResolutionPiece
229
+ });
230
+ /** Every provenance attribute folio reads, with the shape its value must have. */
231
+ const PROVENANCE_VALUE_SHAPES = {
232
+ resolutionJoins: isResolutionJoins,
233
+ boundaryJoins: isBoundaryJoins,
234
+ [PARAGRAPH_MARK_FIELDS.resolutionJoin.attribute]: isEncodedParagraphMarkResolutionJoin,
235
+ copyOriginAncestors: isCopyOriginAncestors,
236
+ splitResolutionJoins: isSplitResolutionPiece,
237
+ [PARAGRAPH_MARK_FIELDS.survivor.attribute]: isParagraphMarkSurvivor
238
+ };
239
+ /**
240
+ * Why the reader drops a provenance attribute's value, or `undefined` when it
241
+ * reads it (or does not read that attribute at all).
242
+ */
243
+ const reviewProvenanceIssue = (attribute, encoded) => {
244
+ const shape = PROVENANCE_VALUE_SHAPES[attribute];
245
+ if (shape === void 0) return void 0;
246
+ const decoded = decodeProvenance(encoded, shape);
247
+ return decoded.status === "dropped" ? decoded.reason : void 0;
163
248
  };
164
- export { ReviewResolutionProvenanceError, isBoundaryJoins, isParagraphMarkResolutionJoin, isResolutionJoins, paragraphMarkResolutionJoinAttributes, parseBoundaryJoins, parseCopyOriginAncestors, parseParagraphMarkResolutionJoin, parseResolutionJoins, serializeBoundaryJoins, serializeCopyOriginAncestors, serializeParagraphMarkResolutionJoin, serializeResolutionJoins };
249
+ export { ReviewResolutionProvenanceError, isBoundaryJoins, isParagraphMarkResolutionJoin, isResolutionJoins, isSplitResolutionPiece, paragraphMarkResolutionJoinAttributes, parseBoundaryJoins, parseCopyOriginAncestors, parseParagraphMarkResolutionJoin, parseResolutionJoins, parseSplitResolutionPiece, reviewProvenanceIssue, serializeBoundaryJoins, serializeCopyOriginAncestors, serializeParagraphMarkResolutionJoin, serializeResolutionJoins, serializeSplitResolutionPiece };
@@ -55,6 +55,12 @@ export declare const assertSectionCarriersMatchModel: ({ doc, serializedSectionC
55
55
  doc: document_d_exports.Document;
56
56
  serializedSectionCount: number;
57
57
  }) => void;
58
+ /**
59
+ * A relationships part to add to. A package need not have one for a part that
60
+ * has no relationships yet, so a missing part reads as an empty one: adding to
61
+ * it must create it, never skip the relationship it was asked for.
62
+ */
63
+ export declare function readRelsOrStub(zip: ZipArchive, relsPath: string): Promise<string>;
58
64
  declare const CanonicalImageRelationshipRefusalErrorBase: TaggedErrorClass<"CanonicalImageRelationshipRefusalError">;
59
65
  export declare class CanonicalImageRelationshipRefusalError extends CanonicalImageRelationshipRefusalErrorBase<{
60
66
  message: string;
@@ -215,8 +215,8 @@ async function syncCommentsExtendedPart(plan, zip, compressionLevel) {
215
215
  /** Read a packaging file, apply a pure transform, and write it back if it changed. */
216
216
  async function transformPackagingFile(zip, path, transform, compressionLevel) {
217
217
  const file = zip.entry(path);
218
- if (!file) return;
219
- const xml = await file.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
218
+ if (!file && !path.endsWith(".rels")) return;
219
+ const xml = file ? await file.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true })) : await readRelsOrStub(zip, path);
220
220
  const next = transform(xml);
221
221
  if (next !== xml) zip.set(path, next, { level: compressionLevel });
222
222
  }
@@ -300,6 +300,11 @@ function collectDocxParts(doc, zip) {
300
300
  addNoteParts(doc.package.endnotes, "word/endnotes.xml");
301
301
  return parts;
302
302
  }
303
+ /**
304
+ * A relationships part to add to. A package need not have one for a part that
305
+ * has no relationships yet, so a missing part reads as an empty one: adding to
306
+ * it must create it, never skip the relationship it was asked for.
307
+ */
303
308
  async function readRelsOrStub(zip, relsPath) {
304
309
  const file = zip.entry(relsPath);
305
310
  return (file ? await file.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true })) : EMPTY_RELS_XML).replace(/<Relationships(?<attrs>[^>]*)\/>/u, "<Relationships$<attrs>></Relationships>");
@@ -1047,9 +1052,7 @@ async function ensureCommentsContentType(zip, compressionLevel) {
1047
1052
  */
1048
1053
  async function ensureCommentsRelationship(zip, compressionLevel) {
1049
1054
  const relsPath = "word/_rels/document.xml.rels";
1050
- const relsFile = zip.entry(relsPath);
1051
- if (!relsFile) return;
1052
- let relsXml = await relsFile.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
1055
+ let relsXml = await readRelsOrStub(zip, relsPath);
1053
1056
  if (relsXml.toLowerCase().includes("comments.xml")) return;
1054
1057
  const commentsPartPath = findZipEntryCaseInsensitive(zip, "word/comments.xml")?.path ?? "word/comments.xml";
1055
1058
  const newRId = `rId${findMaxRId(relsXml) + 1}`;
@@ -1122,9 +1125,7 @@ async function applyUpdatesToZip(zip, updates, options = {}) {
1122
1125
  async function addRelationship(originalBuffer, relationship) {
1123
1126
  const zip = await ZipArchive.read(originalBuffer);
1124
1127
  const relsPath = "word/_rels/document.xml.rels";
1125
- const relsFile = zip.entry(relsPath);
1126
- if (!relsFile) panic("document.xml.rels not found in DOCX");
1127
- const relsXml = await relsFile.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
1128
+ const relsXml = await readRelsOrStub(zip, relsPath);
1128
1129
  const newRId = `rId${findMaxRId(relsXml) + 1}`;
1129
1130
  const targetModeAttr = relationship.targetMode === "External" ? " TargetMode=\"External\"" : "";
1130
1131
  const newRelElement = `<Relationship Id="${newRId}" Type="${relationship.type}" Target="${escapeXmlAttribute(relationship.target)}"${targetModeAttr}/>`;
@@ -1501,8 +1502,16 @@ async function serializeNotesToZip({ doc, originalZip, newZip, compressionLevel,
1501
1502
  if (originalFootnotes) await patchNotePartIntoZip({
1502
1503
  conventionalLowerPath: "word/footnotes.xml",
1503
1504
  currentXml: serializeFootnotes(footnotes),
1504
- replacementXml: serializeNewFootnotesPart(footnotes, doc),
1505
- baselineFrom: (xml) => serializeFootnotes(parseFootnotes(xml).getNormalFootnotes()),
1505
+ fromOriginal: (xml) => {
1506
+ const source = parseFootnotes(xml).getNormalFootnotes();
1507
+ return {
1508
+ baselineXml: serializeFootnotes(source),
1509
+ replacementXml: serializeNewFootnotesPart(footnotes, {
1510
+ document: doc,
1511
+ sourceNoteIds: new Set(source.map(({ id }) => id))
1512
+ })
1513
+ };
1514
+ },
1506
1515
  elementName: "footnote",
1507
1516
  changedNoteParaIds,
1508
1517
  originalZip,
@@ -1514,7 +1523,7 @@ async function serializeNotesToZip({ doc, originalZip, newZip, compressionLevel,
1514
1523
  newZip,
1515
1524
  partPath: "word/footnotes.xml",
1516
1525
  relationshipType: RELATIONSHIP_TYPES.footnotes,
1517
- serializedPart: serializeNewFootnotesPart(footnotes, doc),
1526
+ serializedPart: serializeNewFootnotesPart(footnotes, { document: doc }),
1518
1527
  compressionLevel
1519
1528
  });
1520
1529
  }
@@ -1524,8 +1533,16 @@ async function serializeNotesToZip({ doc, originalZip, newZip, compressionLevel,
1524
1533
  if (originalEndnotes) await patchNotePartIntoZip({
1525
1534
  conventionalLowerPath: "word/endnotes.xml",
1526
1535
  currentXml: serializeEndnotes(endnotes),
1527
- replacementXml: serializeNewEndnotesPart(endnotes, doc),
1528
- baselineFrom: (xml) => serializeEndnotes(parseEndnotes(xml).getNormalEndnotes()),
1536
+ fromOriginal: (xml) => {
1537
+ const source = parseEndnotes(xml).getNormalEndnotes();
1538
+ return {
1539
+ baselineXml: serializeEndnotes(source),
1540
+ replacementXml: serializeNewEndnotesPart(endnotes, {
1541
+ document: doc,
1542
+ sourceNoteIds: new Set(source.map(({ id }) => id))
1543
+ })
1544
+ };
1545
+ },
1529
1546
  elementName: "endnote",
1530
1547
  changedNoteParaIds,
1531
1548
  originalZip,
@@ -1537,24 +1554,24 @@ async function serializeNotesToZip({ doc, originalZip, newZip, compressionLevel,
1537
1554
  newZip,
1538
1555
  partPath: "word/endnotes.xml",
1539
1556
  relationshipType: RELATIONSHIP_TYPES.endnotes,
1540
- serializedPart: serializeNewEndnotesPart(endnotes, doc),
1557
+ serializedPart: serializeNewEndnotesPart(endnotes, { document: doc }),
1541
1558
  compressionLevel
1542
1559
  });
1543
1560
  }
1544
1561
  }
1545
1562
  async function materializeNewNotePart({ contentType, newZip, partPath, relationshipType, serializedPart, compressionLevel }) {
1546
1563
  const contentTypesFile = findNotePartEntry(newZip, "[content_types].xml");
1547
- const relationshipsFile = findNotePartEntry(newZip, "word/_rels/document.xml.rels");
1548
- if (!contentTypesFile || !relationshipsFile) throw new DocxPackageFidelityError(`Cannot create ${partPath}: the DOCX package is missing content types or document relationships`);
1564
+ if (!contentTypesFile) throw new DocxPackageFidelityError(`Cannot create ${partPath}: the DOCX package is missing content types`);
1565
+ const relationshipsPath = findNotePartEntry(newZip, "word/_rels/document.xml.rels")?.path ?? "word/_rels/document.xml.rels";
1549
1566
  const compressionOptions = { level: compressionLevel };
1550
1567
  const contentTypesXml = await contentTypesFile.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
1551
1568
  const partName = `/${partPath}`;
1552
1569
  if (!contentTypesXml.toLowerCase().includes(partName.toLowerCase())) newZip.set(contentTypesFile.path, contentTypesXml.replace("</Types>", () => `<Override PartName="${partName}" ContentType="${contentType}"/></Types>`), compressionOptions);
1553
- const relationshipsXml = await relationshipsFile.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
1570
+ const relationshipsXml = await readRelsOrStub(newZip, relationshipsPath);
1554
1571
  if (!relationshipsXml.includes(relationshipType)) {
1555
1572
  const relationshipId = `rId${findMaxRId(relationshipsXml) + 1}`;
1556
1573
  const target = partPath.slice(5);
1557
- newZip.set(relationshipsFile.path, relationshipsXml.replace("</Relationships>", () => `<Relationship Id="${relationshipId}" Type="${relationshipType}" Target="${target}"/></Relationships>`), compressionOptions);
1574
+ newZip.set(relationshipsPath, relationshipsXml.replace("</Relationships>", () => `<Relationship Id="${relationshipId}" Type="${relationshipType}" Target="${target}"/></Relationships>`), compressionOptions);
1558
1575
  }
1559
1576
  newZip.set(partPath, serializedPart, compressionOptions);
1560
1577
  }
@@ -1799,11 +1816,11 @@ const notePartXmlFor = ({ patch, originalXml, replacementXml, hasDirtyParagraph,
1799
1816
  default: return panic("Unhandled note-part patch", { patch });
1800
1817
  }
1801
1818
  };
1802
- async function patchNotePartIntoZip({ conventionalLowerPath, currentXml, replacementXml, baselineFrom, elementName, changedNoteParaIds, originalZip, newZip, compressionLevel }) {
1819
+ async function patchNotePartIntoZip({ conventionalLowerPath, currentXml, fromOriginal, elementName, changedNoteParaIds, originalZip, newZip, compressionLevel }) {
1803
1820
  const file = findNotePartEntry(originalZip, conventionalLowerPath);
1804
1821
  if (!file) return;
1805
1822
  const originalXml = await file.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
1806
- const baselineXml = baselineFrom(originalXml);
1823
+ const { baselineXml, replacementXml } = fromOriginal(originalXml);
1807
1824
  const effectiveChangedNoteParaIds = changedNoteParaIds ?? collectChangedNoteParaIds(baselineXml, currentXml);
1808
1825
  const currentParaIds = collectParaIds(currentXml);
1809
1826
  const patchedXml = notePartXmlFor({
@@ -2078,4 +2095,4 @@ const assertStyleNumberingReferences = (doc) => {
2078
2095
  if (!numberingInstanceResolves(definitions, numId)) panic(`Numbering definition ${numId} defines no level`);
2079
2096
  }
2080
2097
  };
2081
- export { COMMENTS_CONTENT_TYPE, COMMENTS_EXTENDED_CONTENT_TYPE, COMMENTS_EXTENDED_PART, COMMENTS_EXTENDED_PART_LOWER, CanonicalImageRelationshipRefusalError, DocxDuplicateSectionCarrierError, DocxPackageFidelityError, addCommentsExtendedOverride, addCommentsExtendedRelationship, addMedia, addRelationship, applyUpdatesToZip, assertSectionCarriersMatchModel, collectHeaderFooterUpdates, collectHyperlinksWithoutRId, createDocx, createEmptyDocx, findMaxRId, hasModelDrivenPictureWatermark, hasUnmaterializedHeaderFooter, hasUnmaterializedHyperlinkBindings, hasUnmaterializedInlineResources, isDocxBuffer, notePartRelsPath, planAddedStyles, publishCanonicalImageResources, removeCommentsExtendedOverride, removeCommentsExtendedRelationship, repackDocx, repackDocxFromRaw, updateCoreProperties, updateDocumentXml, updateMultipleFiles, updateXmlFile, validateDocx, withoutAttachedTemplate };
2098
+ export { COMMENTS_CONTENT_TYPE, COMMENTS_EXTENDED_CONTENT_TYPE, COMMENTS_EXTENDED_PART, COMMENTS_EXTENDED_PART_LOWER, CanonicalImageRelationshipRefusalError, DocxDuplicateSectionCarrierError, DocxPackageFidelityError, addCommentsExtendedOverride, addCommentsExtendedRelationship, addMedia, addRelationship, applyUpdatesToZip, assertSectionCarriersMatchModel, collectHeaderFooterUpdates, collectHyperlinksWithoutRId, createDocx, createEmptyDocx, findMaxRId, hasModelDrivenPictureWatermark, hasUnmaterializedHeaderFooter, hasUnmaterializedHyperlinkBindings, hasUnmaterializedInlineResources, isDocxBuffer, notePartRelsPath, planAddedStyles, publishCanonicalImageResources, readRelsOrStub, removeCommentsExtendedOverride, removeCommentsExtendedRelationship, repackDocx, repackDocxFromRaw, updateCoreProperties, updateDocumentXml, updateMultipleFiles, updateXmlFile, validateDocx, withoutAttachedTemplate };
@@ -8,7 +8,7 @@ import { parseNumbering } from "./numberingParser.js";
8
8
  import { normalizeImportedNumericIds } from "./numericIdNormalization.js";
9
9
  import { isUnsafePackagePath } from "./packageParts.js";
10
10
  import { RELATIONSHIP_TYPES } from "./relsParser.js";
11
- import { COMMENTS_CONTENT_TYPE, COMMENTS_EXTENDED_PART_LOWER, addCommentsExtendedOverride, addCommentsExtendedRelationship, applyUpdatesToZip, collectHeaderFooterUpdates, findMaxRId, hasModelDrivenPictureWatermark, hasUnmaterializedHeaderFooter, hasUnmaterializedHyperlinkBindings, hasUnmaterializedInlineResources, planAddedStyles, publishCanonicalImageResources, updateCoreProperties, withoutAttachedTemplate } from "./rezip.js";
11
+ import { COMMENTS_CONTENT_TYPE, COMMENTS_EXTENDED_PART_LOWER, addCommentsExtendedOverride, addCommentsExtendedRelationship, applyUpdatesToZip, collectHeaderFooterUpdates, findMaxRId, hasModelDrivenPictureWatermark, hasUnmaterializedHeaderFooter, hasUnmaterializedHyperlinkBindings, hasUnmaterializedInlineResources, planAddedStyles, publishCanonicalImageResources, readRelsOrStub, updateCoreProperties, withoutAttachedTemplate } from "./rezip.js";
12
12
  import "./selectiveSaveFlags.js";
13
13
  import { buildPatchedDocumentXml, buildPatchedNoteXml, collectAddedNumberingDefs, collectParaIds, patchNumberingDefinitions } from "./selectiveXmlPatch.js";
14
14
  import { canReplayCommentsPart, hasOwnedCommentsPart, planCommentParts, serializeComments, serializeCommentsExtended } from "./serializer/commentSerializer.js";
@@ -112,8 +112,7 @@ async function ensureCommentsExtendedPackaging(zip, updates) {
112
112
  const nextCt = addCommentsExtendedOverride(ctXml);
113
113
  if (nextCt !== ctXml) updates.set(ctPath, nextCt);
114
114
  const relsPath = "word/_rels/document.xml.rels";
115
- const relsXml = updates.get(relsPath) ?? await zip.entry(relsPath)?.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
116
- if (relsXml === void 0) return false;
115
+ const relsXml = updates.get(relsPath) ?? await readRelsOrStub(zip, relsPath);
117
116
  const nextRels = addCommentsExtendedRelationship(relsXml);
118
117
  if (nextRels !== relsXml) updates.set(relsPath, nextRels);
119
118
  return true;
@@ -274,13 +273,10 @@ async function attemptSelectiveSave(doc, originalBuffer, options) {
274
273
  if (!ctXml.toLowerCase().includes("/word/comments.xml")) updates.set("[Content_Types].xml", ctXml.replace("</Types>", `<Override PartName="/${commentsPartPath}" ContentType="${COMMENTS_CONTENT_TYPE}"/></Types>`));
275
274
  }
276
275
  const relsPath = "word/_rels/document.xml.rels";
277
- const relsFile = zip.entry(relsPath);
278
- if (relsFile) {
279
- const relsXml = await relsFile.bytes().then((bytes) => decodeText(bytes, { ignoreBOM: true }));
280
- if (!relsXml.toLowerCase().includes("comments.xml")) {
281
- const maxId = findMaxRId(relsXml);
282
- updates.set(relsPath, relsXml.replace("</Relationships>", `<Relationship Id="rId${maxId + 1}" Type="${RELATIONSHIP_TYPES.comments}" Target="${commentsPartPath.slice(5)}"/></Relationships>`));
283
- }
276
+ const relsXml = await readRelsOrStub(zip, relsPath);
277
+ if (!relsXml.toLowerCase().includes("comments.xml")) {
278
+ const maxId = findMaxRId(relsXml);
279
+ updates.set(relsPath, relsXml.replace("</Relationships>", `<Relationship Id="rId${maxId + 1}" Type="${RELATIONSHIP_TYPES.comments}" Target="${commentsPartPath.slice(5)}"/></Relationships>`));
284
280
  }
285
281
  }
286
282
  if (!commentsUnchanged && !await patchCommentsExtended(zip, commentPlan, updates)) return null;
@@ -215,8 +215,8 @@ export type NotePartPatch = {
215
215
  * dirty paragraphs. A tracked paragraph-break resolution can change that
216
216
  * shape, so it replaces the one affected note. Separator notes, unrelated
217
217
  * notes, and unaffected equal-shape paragraphs remain byte-exact.
218
- * `replacementXml` also supplies synthesized automatic note-reference marks,
219
- * which the parsed model intentionally omits.
218
+ * `replacementXml` gives a note new to the part its automatic reference mark;
219
+ * a note the part already has carries its own, or none, in the model.
220
220
  *
221
221
  * A comment can be anchored on a note's own text, so its range spans that
222
222
  * note's paragraphs and an edit inside the span moves a range half from one
@@ -263,8 +263,9 @@ export declare const patchNumberingDefinitions: ({ originalXml, baselineXml, cur
263
263
  /**
264
264
  * Append added `w:abstractNum` / `w:num` definitions from `currentXml` to
265
265
  * `xml`. ECMA-376 §17.9 orders every `w:abstractNum` before the first `w:num`,
266
- * so abstract definitions go right before the first `<w:num ` (or the root
267
- * close when the part has none) and instances before the root close. A
266
+ * and `w:numIdMacAtCleanup` after the last, so abstract definitions go right
267
+ * before the first `<w:num ` and instances right before that marker, or the
268
+ * root close when the part has neither. A
268
269
  * synthetic numFmt in an added abstract is restored from the original
269
270
  * definition it was cloned from (the one with an identical body), so a custom
270
271
  * format survives cloning. Returns null when an added id cannot be extracted
@@ -792,8 +792,8 @@ const collectChangedNoteParaIds = (baselineXml, currentXml) => {
792
792
  * dirty paragraphs. A tracked paragraph-break resolution can change that
793
793
  * shape, so it replaces the one affected note. Separator notes, unrelated
794
794
  * notes, and unaffected equal-shape paragraphs remain byte-exact.
795
- * `replacementXml` also supplies synthesized automatic note-reference marks,
796
- * which the parsed model intentionally omits.
795
+ * `replacementXml` gives a note new to the part its automatic reference mark;
796
+ * a note the part already has carries its own, or none, in the model.
797
797
  *
798
798
  * A comment can be anchored on a note's own text, so its range spans that
799
799
  * note's paragraphs and an edit inside the span moves a range half from one
@@ -1220,6 +1220,7 @@ function collectAddedNumberingDefs(baselineXml, currentXml) {
1220
1220
  };
1221
1221
  }
1222
1222
  const NUMBERING_CLOSE_ROOT = "</w:numbering>";
1223
+ const NUMBERING_CLEANUP_MARKER = "<w:numIdMacAtCleanup";
1223
1224
  const numberingDefinitionIdentity = (element) => {
1224
1225
  if (!WORDPROCESSINGML_NAMESPACE_URIS.has(getNamespaceUri(element) ?? "")) return null;
1225
1226
  const kind = getLocalName(element.name);
@@ -1283,8 +1284,9 @@ const patchNumberingDefinitions = ({ originalXml, baselineXml, currentXml }) =>
1283
1284
  /**
1284
1285
  * Append added `w:abstractNum` / `w:num` definitions from `currentXml` to
1285
1286
  * `xml`. ECMA-376 §17.9 orders every `w:abstractNum` before the first `w:num`,
1286
- * so abstract definitions go right before the first `<w:num ` (or the root
1287
- * close when the part has none) and instances before the root close. A
1287
+ * and `w:numIdMacAtCleanup` after the last, so abstract definitions go right
1288
+ * before the first `<w:num ` and instances right before that marker, or the
1289
+ * root close when the part has neither. A
1288
1290
  * synthetic numFmt in an added abstract is restored from the original
1289
1291
  * definition it was cloned from (the one with an identical body), so a custom
1290
1292
  * format survives cloning. Returns null when an added id cannot be extracted
@@ -1307,10 +1309,12 @@ function appendNumberingDefs(xml, currentXml, added) {
1307
1309
  numXmls.push(def);
1308
1310
  }
1309
1311
  const firstNum = findFirstElement(xml, NUMBERING_OPEN_LITERAL.num, NUMBERING_CLOSE_TAG.num);
1310
- const abstractInsertAt = firstNum ? firstNum.start : rootClose;
1312
+ const cleanupMarker = xml.indexOf(NUMBERING_CLEANUP_MARKER);
1313
+ const instancesEnd = cleanupMarker < 0 ? rootClose : cleanupMarker;
1314
+ const abstractInsertAt = firstNum ? firstNum.start : instancesEnd;
1311
1315
  const head = xml.slice(0, abstractInsertAt);
1312
- const middle = xml.slice(abstractInsertAt, rootClose);
1313
- const tail = xml.slice(rootClose);
1316
+ const middle = xml.slice(abstractInsertAt, instancesEnd);
1317
+ const tail = xml.slice(instancesEnd);
1314
1318
  return head + abstractXmls.join("") + middle + numXmls.join("") + tail;
1315
1319
  }
1316
1320
  /**
@@ -2,7 +2,7 @@ import { getDocumentSourceBaseline } from "../headerFooterVerbatim.js";
2
2
  import { buildDocumentBlockReplay, canReplayDocumentSource } from "../storyBlockReplay.js";
3
3
  import { serializeBlockCustomXml } from "./blockCustomXmlSerializer.js";
4
4
  import { serializeBlockSdt } from "./blockSdtSerializer.js";
5
- import { serializeBookmarkMarker, serializeMoveRangeMarker } from "./markupRangeAttributes.js";
5
+ import { serializeBookmarkMarker, serializeCommentRangeMarker, serializeMoveRangeMarker } from "./markupRangeAttributes.js";
6
6
  import { serializeParagraph } from "./paragraphSerializer.js";
7
7
  import { serializePartElement } from "./partNamespaces.js";
8
8
  import { resetAutoIdCounter } from "./runSerializer.js";
@@ -68,6 +68,8 @@ function serializeBlockContent(block) {
68
68
  case "moveFromRangeEnd":
69
69
  case "moveToRangeStart":
70
70
  case "moveToRangeEnd": return serializeMoveRangeMarker(block);
71
+ case "commentRangeStart":
72
+ case "commentRangeEnd": return serializeCommentRangeMarker(block);
71
73
  default: return block;
72
74
  }
73
75
  }
@@ -5,7 +5,7 @@ import { captureVerbatimXml } from "../verbatimCapture.js";
5
5
  import { getLocalName, parseXmlDocument } from "../xmlParser.js";
6
6
  import { serializeBlockCustomXml } from "./blockCustomXmlSerializer.js";
7
7
  import { serializeBlockSdt } from "./blockSdtSerializer.js";
8
- import { serializeBookmarkMarker, serializeMoveRangeMarker } from "./markupRangeAttributes.js";
8
+ import { serializeBookmarkMarker, serializeCommentRangeMarker, serializeMoveRangeMarker } from "./markupRangeAttributes.js";
9
9
  import { serializeParagraph } from "./paragraphSerializer.js";
10
10
  import { serializePartElement } from "./partNamespaces.js";
11
11
  import { serializeTable } from "./tableSerializer.js";
@@ -51,6 +51,8 @@ function serializeBlock(block) {
51
51
  case "moveFromRangeEnd":
52
52
  case "moveToRangeStart":
53
53
  case "moveToRangeEnd": return serializeMoveRangeMarker(block);
54
+ case "commentRangeStart":
55
+ case "commentRangeEnd": return serializeCommentRangeMarker(block);
54
56
  default: return block;
55
57
  }
56
58
  }
@@ -16,4 +16,9 @@ export declare const moveBookmarkAttributes: (marker: document_d_exports.MoveFro
16
16
  * One move range marker, wherever it stands: a paragraph child or a block, so
17
17
  * the serializers share one writer as they do for bookmarks.
18
18
  */
19
- export declare const serializeMoveRangeMarker: (marker: document_d_exports.MoveFromRangeStart | document_d_exports.MoveFromRangeEnd | document_d_exports.MoveToRangeStart | document_d_exports.MoveToRangeEnd) => string;
19
+ export declare const serializeMoveRangeMarker: (marker: document_d_exports.MoveFromRangeStart | document_d_exports.MoveFromRangeEnd | document_d_exports.MoveToRangeStart | document_d_exports.MoveToRangeEnd) => string;
20
+ /**
21
+ * One comment range marker, wherever it stands: a paragraph child or a block,
22
+ * so the serializers share one writer as they do for bookmarks and moves.
23
+ */
24
+ export declare const serializeCommentRangeMarker: (marker: document_d_exports.CommentRangeStart | document_d_exports.CommentRangeEnd) => string;
@@ -55,4 +55,9 @@ const serializeMoveRangeMarker = (marker) => {
55
55
  default: return marker;
56
56
  }
57
57
  };
58
- export { bookmarkRangeAttributes, markupRangeAttributes, moveBookmarkAttributes, serializeBookmarkMarker, serializeMoveRangeMarker };
58
+ /**
59
+ * One comment range marker, wherever it stands: a paragraph child or a block,
60
+ * so the serializers share one writer as they do for bookmarks and moves.
61
+ */
62
+ const serializeCommentRangeMarker = (marker) => `<w:${marker.type} ${markupRangeAttributes(marker).join(" ")}/>`;
63
+ export { bookmarkRangeAttributes, markupRangeAttributes, moveBookmarkAttributes, serializeBookmarkMarker, serializeCommentRangeMarker, serializeMoveRangeMarker };
@@ -1,4 +1,15 @@
1
1
  import { document_d_exports } from "../../types/document.js";
2
+ /** What a new note part is written for. */
3
+ export type NewNotePartContext = {
4
+ /** The document the notes belong to, which says whether a note's reference shows a custom mark. */
5
+ document?: document_d_exports.Document;
6
+ /**
7
+ * Notes the source package already has. Their content says whether they
8
+ * show a reference mark, as read, edited and resolved; only a note new to
9
+ * the package is given one.
10
+ */
11
+ sourceNoteIds?: ReadonlySet<number>;
12
+ };
2
13
  /**
3
14
  * Serialize footnotes to a complete word/footnotes.xml string.
4
15
  *
@@ -14,8 +25,10 @@ export declare function serializeFootnotes(footnotes: readonly document_d_export
14
25
  */
15
26
  export declare function serializeEndnotes(endnotes: readonly document_d_exports.Endnote[]): string;
16
27
  /** Serialize a brand-new footnote part, including Word's required separators
17
- * and the automatic reference mark at the start of every normal note. */
18
- export declare function serializeNewFootnotesPart(footnotes: readonly document_d_exports.Footnote[], document?: document_d_exports.Document): string;
28
+ * and the automatic reference mark at the start of every normal note new to
29
+ * the package. */
30
+ export declare function serializeNewFootnotesPart(footnotes: readonly document_d_exports.Footnote[], context?: NewNotePartContext): string;
19
31
  /** Serialize a brand-new endnote part, including Word's required separators
20
- * and the automatic reference mark at the start of every normal note. */
21
- export declare function serializeNewEndnotesPart(endnotes: readonly document_d_exports.Endnote[], document?: document_d_exports.Document): string;
32
+ * and the automatic reference mark at the start of every normal note new to
33
+ * the package. */
34
+ export declare function serializeNewEndnotesPart(endnotes: readonly document_d_exports.Endnote[], context?: NewNotePartContext): string;