@stll/folio-core 0.74.0 → 0.76.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 (174) hide show
  1. package/dist/ai-edits/clean-text.d.ts +4 -1
  2. package/dist/ai-edits/clean-text.js +21 -7
  3. package/dist/ai-edits/headless.d.ts +7 -3
  4. package/dist/ai-edits/headless.js +36 -21
  5. package/dist/ai-edits/note-references.d.ts +1 -1
  6. package/dist/ai-edits/note-references.js +1 -1
  7. package/dist/ai-edits/pending-suggestions.d.ts +9 -7
  8. package/dist/ai-edits/pending-suggestions.js +135 -90
  9. package/dist/ai-edits/pendingJoin.d.ts +5 -1
  10. package/dist/ai-edits/pendingJoin.js +6 -2
  11. package/dist/ai-edits/read.js +9 -3
  12. package/dist/ai-edits/retired-comment-receipts.d.ts +2 -2
  13. package/dist/ai-edits/retired-comment-receipts.js +3 -18
  14. package/dist/ai-edits/tracked-batch-fidelity.d.ts +6 -10
  15. package/dist/ai-edits/tracked-batch-fidelity.js +3 -182
  16. package/dist/ai-edits/types.d.ts +9 -4
  17. package/dist/canonical/batchCommentReferences.js +2 -1
  18. package/dist/canonical/canonicalBatchReview.d.ts +4 -1
  19. package/dist/canonical/canonicalBatchReview.js +37 -22
  20. package/dist/canonical/canonicalComments.d.ts +6 -2
  21. package/dist/canonical/canonicalComments.js +16 -6
  22. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  23. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  24. package/dist/canonical/canonicalPublicOperations.js +231 -79
  25. package/dist/canonical/canonicalRefusalGrounds.d.ts +4 -0
  26. package/dist/canonical/canonicalRefusalGrounds.js +56 -0
  27. package/dist/canonical/canonicalSession.d.ts +12 -6
  28. package/dist/canonical/canonicalSession.js +119 -122
  29. package/dist/canonical/canonicalTrackedBatchFidelity.js +3 -3
  30. package/dist/compare/inline-atoms.d.ts +35 -41
  31. package/dist/compare/inline-atoms.js +2 -465
  32. package/dist/compare/section-boundary-properties.d.ts +3 -30
  33. package/dist/compare/section-boundary-properties.js +4 -72
  34. package/dist/controller/canonicalClipboard.d.ts +1 -1
  35. package/dist/controller/canonicalClipboard.js +110 -55
  36. package/dist/controller/canonicalComposition.d.ts +1 -1
  37. package/dist/controller/canonicalComposition.js +5 -5
  38. package/dist/controller/canonicalContentControlValue.js +7 -7
  39. package/dist/controller/canonicalInput.d.ts +4 -2
  40. package/dist/controller/canonicalInput.js +33 -16
  41. package/dist/controller/canonicalReview.d.ts +21 -0
  42. package/dist/controller/canonicalReview.js +44 -9
  43. package/dist/controller/canonicalStoryEditor.d.ts +2 -3
  44. package/dist/controller/canonicalStoryEditor.js +43 -25
  45. package/dist/controller/canonicalStructure.d.ts +19 -3
  46. package/dist/controller/canonicalStructure.js +182 -58
  47. package/dist/controller/deferredDisplayListPainter.d.ts +8 -0
  48. package/dist/controller/deferredDisplayListPainter.js +34 -0
  49. package/dist/controller/folioEditor.js +4 -2
  50. package/dist/controller/fontReadiness.js +50 -23
  51. package/dist/controller/headerFooterEditorManager.js +3 -17
  52. package/dist/controller/hiddenEditorApi.d.ts +24 -3
  53. package/dist/controller/hiddenEditorApi.js +2 -0
  54. package/dist/controller/hiddenEditorManager.js +135 -207
  55. package/dist/controller/layoutPipeline.d.ts +4 -86
  56. package/dist/controller/layoutPipeline.js +8 -727
  57. package/dist/controller/layoutPipelineExecution.d.ts +94 -0
  58. package/dist/controller/layoutPipelineExecution.js +730 -0
  59. package/dist/controller/noteEditorManager.js +3 -16
  60. package/dist/docx/blockContentParser.d.ts +1 -3
  61. package/dist/docx/blockContentParser.js +3 -10
  62. package/dist/docx/bulletMarkers.d.ts +8 -0
  63. package/dist/docx/bulletMarkers.js +9 -1
  64. package/dist/docx/canonicalSave.d.ts +4 -3
  65. package/dist/docx/canonicalSave.js +4 -3
  66. package/dist/docx/canonicalSessionInput.js +25 -11
  67. package/dist/docx/ensureParaIds.d.ts +31 -0
  68. package/dist/docx/ensureParaIds.js +57 -32
  69. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  70. package/dist/docx/ensureUniqueControlIds.js +47 -29
  71. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  72. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  73. package/dist/docx/listMarkerComputation.d.ts +24 -17
  74. package/dist/docx/listMarkerComputation.js +31 -60
  75. package/dist/docx/listModelNormalization.js +8 -15
  76. package/dist/docx/rezip.d.ts +16 -3
  77. package/dist/docx/rezip.js +35 -9
  78. package/dist/docx/selectiveSave.js +13 -5
  79. package/dist/docx/server/templatePlan/apply.js +96 -7
  80. package/dist/docx/server/templatePlan/blocks.d.ts +70 -3
  81. package/dist/docx/server/templatePlan/blocks.js +272 -10
  82. package/dist/docx/server/templatePlan/builders.d.ts +52 -2
  83. package/dist/docx/server/templatePlan/builders.js +224 -5
  84. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  85. package/dist/docx/server/templatePlan/effects.js +188 -0
  86. package/dist/docx/server/templatePlan/emit.d.ts +4 -1
  87. package/dist/docx/server/templatePlan/emit.js +46 -2
  88. package/dist/docx/server/templatePlan/inspect.js +39 -52
  89. package/dist/docx/server/templatePlan/labels.d.ts +7 -2
  90. package/dist/docx/server/templatePlan/labels.js +120 -23
  91. package/dist/docx/server/templatePlan/plan.d.ts +24 -3
  92. package/dist/docx/server/templatePlan/plan.js +54 -15
  93. package/dist/docx/server/templatePlan/planShape.js +76 -22
  94. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  95. package/dist/docx/server/templatePlan/revisions.js +407 -0
  96. package/dist/docx/server/templatePlan/story.d.ts +23 -1
  97. package/dist/docx/server/templatePlan/story.js +60 -2
  98. package/dist/docx/server/templatePlan/types.d.ts +354 -16
  99. package/dist/docx/server/templatePlan/verify.js +164 -14
  100. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  101. package/dist/docx/server/templatePlan/xml.js +4 -1
  102. package/dist/i18n/messages/ar.gen.js +1 -0
  103. package/dist/i18n/messages/catalogs.gen.d.ts +17 -0
  104. package/dist/i18n/messages/catalogs.gen.js +17 -0
  105. package/dist/i18n/messages/cs.gen.js +1 -0
  106. package/dist/i18n/messages/de.gen.js +1 -0
  107. package/dist/i18n/messages/en.gen.js +1 -0
  108. package/dist/i18n/messages/es.gen.js +1 -0
  109. package/dist/i18n/messages/et.gen.js +1 -0
  110. package/dist/i18n/messages/fr.gen.js +1 -0
  111. package/dist/i18n/messages/he.gen.js +1 -0
  112. package/dist/i18n/messages/hi.gen.js +1 -0
  113. package/dist/i18n/messages/hu.gen.js +1 -0
  114. package/dist/i18n/messages/lt.gen.js +1 -0
  115. package/dist/i18n/messages/lv.gen.js +1 -0
  116. package/dist/i18n/messages/messages.gen.d.ts +1 -0
  117. package/dist/i18n/messages/pl.gen.js +1 -0
  118. package/dist/i18n/messages/pt-BR.gen.js +1 -0
  119. package/dist/i18n/messages/sk.gen.js +1 -0
  120. package/dist/i18n/messages/tr.gen.js +1 -0
  121. package/dist/i18n/messages/zh-CN.gen.js +1 -0
  122. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  123. package/dist/internal/revisionResolutionStep.js +2 -171
  124. package/dist/layout-bridge/convert/toFlowBlocks.js +0 -12
  125. package/dist/layout-bridge/convert/topLevelConversion.js +1 -10
  126. package/dist/prosemirror/commands/comments.d.ts +6 -234
  127. package/dist/prosemirror/commands/comments.js +5 -2464
  128. package/dist/prosemirror/commands/index.d.ts +4 -2
  129. package/dist/prosemirror/commands/index.js +4 -2
  130. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  131. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  132. package/dist/prosemirror/extensions/features/ImagePasteExtension.js +1 -1
  133. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  134. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  135. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  136. package/dist/prosemirror/listMarker.d.ts +1 -6
  137. package/dist/prosemirror/listMarker.js +4 -56
  138. package/dist/prosemirror/paraIds.d.ts +1 -14
  139. package/dist/prosemirror/paraIds.js +1 -14
  140. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  141. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  142. package/dist/prosemirror/projectionReview.d.ts +49 -0
  143. package/dist/prosemirror/projectionReview.js +292 -0
  144. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  145. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  146. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  147. package/dist/prosemirror/replacedAnnotations.js +1 -10
  148. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  149. package/dist/prosemirror/revisionCarriers.js +15 -1
  150. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  151. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  152. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  153. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  154. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  155. package/dist/prosemirror/suggestionQueries.js +320 -0
  156. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  157. package/dist/prosemirror/tableGridMutation.js +1 -78
  158. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  159. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  160. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  161. package/dist/server.d.ts +2 -2
  162. package/dist/types/canonicalCapabilities.d.ts +40 -69
  163. package/dist/types/canonicalCapabilities.js +51 -65
  164. package/dist/types/canonicalComments.d.ts +2 -2
  165. package/dist/types/canonicalSections.d.ts +2 -2
  166. package/dist/utils/clipboard.d.ts +2 -28
  167. package/dist/utils/clipboard.js +1 -96
  168. package/dist/utils/clipboardFiles.d.ts +27 -0
  169. package/dist/utils/clipboardFiles.js +98 -0
  170. package/dist/utils/rulerControl.d.ts +1 -0
  171. package/dist/utils/rulerControl.js +2 -1
  172. package/package.json +2 -2
  173. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  174. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -1,10 +1,9 @@
1
1
  import { CanonicalSessionError } from "../canonical/canonicalSession.js";
2
2
  import { isSeparatorEndnote, isSeparatorFootnote } from "../docx/footnoteParser.js";
3
3
  import { createNativeNavigationPlugin, createNativeSelectionRefreshPlugin } from "../prosemirror/nativeSelection.js";
4
- import { noteReferenceTransactionIssue } from "../prosemirror/noteReferenceOccurrences.js";
5
4
  import { createDocumentNumberingPlugin } from "../prosemirror/plugins/documentNumbering.js";
6
5
  import { createDocumentStyleContextPlugin } from "../prosemirror/plugins/documentStyles.js";
7
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
6
+ import { CANONICAL_CONDITION } from "../types/canonicalCapabilities.js";
8
7
  import { readModel } from "../types/documentModel.js";
9
8
  import { createCanonicalStoryEditor, refreshCanonicalStoryView } from "./canonicalStoryEditor.js";
10
9
  import { OP_STORIES } from "@stll/docx-core/ops";
@@ -80,7 +79,6 @@ const createNoteEditorManager = (deps) => {
80
79
  },
81
80
  getView: () => view,
82
81
  getApi: () => deps.getCanonicalApi?.() ?? null,
83
- enabled: () => true,
84
82
  onRefusal: deps.onSessionRefusal,
85
83
  onSelectionChange: () => deps.onTransaction?.({
86
84
  ...storyKey,
@@ -110,18 +108,7 @@ const createNoteEditorManager = (deps) => {
110
108
  ]
111
109
  }),
112
110
  dispatchTransaction(transaction) {
113
- if (canonical.dispatch(transaction)) return;
114
- const nextState = view.state.apply(transaction);
115
- const docChanged = !nextState.doc.eq(view.state.doc);
116
- view.updateState(nextState);
117
- const noteIssue = noteReferenceTransactionIssue(transaction);
118
- if (noteIssue) deps.onSessionRefusal?.(noteIssue.message, { gap: CANONICAL_GAP.dispatch }, noteIssue);
119
- deps.onTransaction?.({
120
- ...storyKey,
121
- docChanged,
122
- selectionChanged: transaction.selectionSet,
123
- view
124
- });
111
+ canonical.dispatch(transaction);
125
112
  }
126
113
  });
127
114
  mounted.set(key, {
@@ -155,7 +142,7 @@ const createNoteEditorManager = (deps) => {
155
142
  const canonical = deps.getCanonicalApi?.()?.getCanonicalDocument();
156
143
  if (canonical) return canonical;
157
144
  throw new CanonicalSessionError({
158
- ground: { gap: CANONICAL_GAP.authorityRouting },
145
+ ground: { condition: CANONICAL_CONDITION.notReady },
159
146
  reason: "refused",
160
147
  message: "Canonical story snapshot is unavailable."
161
148
  });
@@ -9,7 +9,6 @@
9
9
  import { document_d_exports } from "../types/document.js";
10
10
  import { DeepReadonly } from "../types/documentModel.js";
11
11
  import { OwnedElsewhere } from "./containerChildren.js";
12
- import { PreviousListState } from "./listMarkerComputation.js";
13
12
  import { NumberingMap } from "./numberingParser.js";
14
13
  import { ParseContext } from "./parseContext.js";
15
14
  import { PreviewLedger } from "./previewBudget.js";
@@ -28,8 +27,7 @@ type BlockContentScope = ParseBlockContentOptions & {
28
27
  type ParseBlockContentState = {
29
28
  listCounters: Map<number, number[]>;
30
29
  abstractCounters: Map<number, number[]>;
31
- restartedNumIds: Set<number>;
32
- previousList: PreviousListState;
30
+ startedLevels: Set<number>;
33
31
  options: BlockContentScope;
34
32
  };
35
33
  export declare const parseBlockContent: (parent: XmlElement, styles: StyleMap | null, theme: DeepReadonly<document_d_exports.Theme> | null, numbering: NumberingMap | null, rels: document_d_exports.RelationshipMap | null, media: Map<string, document_d_exports.MediaFile> | null, options?: ParseBlockContentOptions) => document_d_exports.BlockContent[];
@@ -55,12 +55,7 @@ const countContainedListMarkers = (blocks, counters) => {
55
55
  const parseBlockContent = (parent, styles, theme, numbering, rels, media, options) => parseBlockContentWithState(parent, styles, theme, numbering, rels, media, {
56
56
  listCounters: /* @__PURE__ */ new Map(),
57
57
  abstractCounters: /* @__PURE__ */ new Map(),
58
- restartedNumIds: /* @__PURE__ */ new Set(),
59
- previousList: {
60
- abstractNumId: null,
61
- fromStyle: false,
62
- numId: null
63
- },
58
+ startedLevels: /* @__PURE__ */ new Set(),
64
59
  options: {
65
60
  ...options,
66
61
  rootXmlns: mergeXmlnsDeclarations(options?.rootXmlns ?? {}, parent),
@@ -90,8 +85,7 @@ const BLOCK_CONTENT_HANDLERS = {
90
85
  numbering,
91
86
  listCounters: state.listCounters,
92
87
  abstractCounters: state.abstractCounters,
93
- restartedNumIds: state.restartedNumIds,
94
- previousList: state.previousList
88
+ startedLevels: state.startedLevels
95
89
  });
96
90
  modelled.push(paragraph);
97
91
  },
@@ -105,8 +99,7 @@ const BLOCK_CONTENT_HANDLERS = {
105
99
  numbering,
106
100
  listCounters: state.listCounters,
107
101
  abstractCounters: state.abstractCounters,
108
- restartedNumIds: state.restartedNumIds,
109
- previousList: state.previousList
102
+ startedLevels: state.startedLevels
110
103
  });
111
104
  modelled.push(table);
112
105
  },
@@ -20,4 +20,12 @@ export declare const bulletMarkerFontName: (formatting: {
20
20
  * symbol-font code.
21
21
  */
22
22
  export declare const convertBulletToUnicode: (bulletChar: string, fontName?: string) => string;
23
+ /**
24
+ * The text face a bullet level's mark is a character of, when it is one: the
25
+ * mark then looks as it does only in that face (the customary `o` of a
26
+ * monospace face). Undefined for a level that names no face, for a symbol
27
+ * face, and for a code a text face has no character for, which is read as
28
+ * the shape it stands in for.
29
+ */
30
+ export declare const bulletTextFace: (bulletChar: string, fontName: string | undefined) => string | undefined;
23
31
  export {};
@@ -23,4 +23,12 @@ const convertBulletToUnicode = (bulletChar, fontName) => {
23
23
  if (charCode < 32 || charCode >= 127 && charCode < 160) return "•";
24
24
  return bulletChar;
25
25
  };
26
- export { bulletMarkerFontName, convertBulletToUnicode };
26
+ /**
27
+ * The text face a bullet level's mark is a character of, when it is one: the
28
+ * mark then looks as it does only in that face (the customary `o` of a
29
+ * monospace face). Undefined for a level that names no face, for a symbol
30
+ * face, and for a code a text face has no character for, which is read as
31
+ * the shape it stands in for.
32
+ */
33
+ const bulletTextFace = (bulletChar, fontName) => fontName !== void 0 && !isOoxmlSymbolFont(fontName) && bulletChar !== "" && convertBulletToUnicode(bulletChar, fontName) === bulletChar ? fontName : void 0;
34
+ export { bulletMarkerFontName, bulletTextFace, convertBulletToUnicode };
@@ -1,4 +1,3 @@
1
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
2
1
  import { CanonicalSaveSnapshot } from "../types/canonicalSave.js";
3
2
  import { FolioDocxSerializationPath, FolioGetDocxOptions } from "../types/docxSerialization.js";
4
3
  import { SaveDiagnostic } from "./saveDiagnostics.js";
@@ -7,10 +6,12 @@ import { TripwireResult } from "./selectiveSaveTripwire.js";
7
6
  import { TaggedErrorClass } from "better-result";
8
7
  import { Document } from "@stll/docx-core";
9
8
  declare const CanonicalSaveDiagnosticErrorBase: TaggedErrorClass<"CanonicalSaveDiagnosticError">;
10
- /** Forward a fidelity fallback through the adapters' existing error channel. */
9
+ /**
10
+ * Forward a fidelity fallback through the adapters' existing error channel:
11
+ * the save succeeded, by a path that rewrote more of the package.
12
+ */
11
13
  export declare class CanonicalSaveDiagnosticError extends CanonicalSaveDiagnosticErrorBase<{
12
14
  message: string;
13
- gap: typeof CANONICAL_GAP.saveSerialization;
14
15
  diagnostic: SaveDiagnostic;
15
16
  }> {}
16
17
  /** The adapters' error channel for one fidelity fallback. */
@@ -1,5 +1,4 @@
1
1
  import { withoutUnreferencedNotes } from "../prosemirror/noteReferenceReview.js";
2
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
3
2
  import { FOLIO_DOCX_SERIALIZATION_MODE } from "../types/docxSerialization.js";
4
3
  import { canonicalJson } from "../utils/canonicalJson.js";
5
4
  import { repackWithCanonicalStoryRemovals } from "./canonicalStoryRepack.js";
@@ -12,11 +11,13 @@ import { Result, TaggedError } from "better-result";
12
11
  import { idKey, packageParagraphIds, withoutPendingSuggestions } from "@stll/docx-core/ops";
13
12
  // src/docx/canonicalSave.ts
14
13
  const CanonicalSaveDiagnosticErrorBase = TaggedError("CanonicalSaveDiagnosticError");
15
- /** Forward a fidelity fallback through the adapters' existing error channel. */
14
+ /**
15
+ * Forward a fidelity fallback through the adapters' existing error channel:
16
+ * the save succeeded, by a path that rewrote more of the package.
17
+ */
16
18
  var CanonicalSaveDiagnosticError = class extends CanonicalSaveDiagnosticErrorBase {};
17
19
  /** The adapters' error channel for one fidelity fallback. */
18
20
  const canonicalSaveDiagnosticError = (diagnostic) => new CanonicalSaveDiagnosticError({
19
- gap: CANONICAL_GAP.saveSerialization,
20
21
  diagnostic,
21
22
  message: `Canonical save used a fidelity fallback: ${diagnostic.type} (${diagnostic.part}).`
22
23
  });
@@ -1,8 +1,8 @@
1
1
  import { toArrayBuffer } from "../utils/docxInput.js";
2
2
  import { DOCX_CONTAINER_TYPES, detectDocxContainerType } from "./encryption/containerFormat.js";
3
- import { ensureParaIds } from "./ensureParaIds.js";
4
- import { ensureUniqueControlIds } from "./ensureUniqueControlIds.js";
5
- import { ensureUniqueRevisionIds } from "./ensureUniqueRevisionIds.js";
3
+ import { isDigitallySignedPackage, planPackageParaIds, signedPackageMutationError, writePackageParts } from "./ensureParaIds.js";
4
+ import { uniqueControlIdUpdates } from "./ensureUniqueControlIds.js";
5
+ import { uniqueRevisionIdUpdates } from "./ensureUniqueRevisionIds.js";
6
6
  import { keepNormalizedSourceParts } from "./normalizedSourceParts.js";
7
7
  import { MalformedPackageRelationshipsError } from "./packageRelationshipsRoot.js";
8
8
  import { parseDocx } from "./parser.js";
@@ -30,6 +30,27 @@ const prepareCanonicalDocxInput = async (input) => {
30
30
  const source = await prepareCanonicalDocxSource(input);
31
31
  return source.isErr() ? Result.err(source.error) : Result.ok(source.value.docx);
32
32
  };
33
+ /**
34
+ * Every id normalization of a package over one read of its parts: paragraph
35
+ * ids, then content control ids, then revision ids, each pass reading the
36
+ * texts the one before wrote. The package is written once, if at all.
37
+ */
38
+ const normalizeCanonicalPackage = async (bytes) => {
39
+ const paragraphs = await planPackageParaIds(bytes);
40
+ const signed = isDigitallySignedPackage(paragraphs.entries);
41
+ if (signed && paragraphs.updates.size > 0) throw signedPackageMutationError();
42
+ const texts = new Map(paragraphs.partTexts);
43
+ const updates = new Map(paragraphs.updates);
44
+ for (const [path, text] of updates) texts.set(path, text);
45
+ if (!signed) for (const pass of [uniqueControlIdUpdates, uniqueRevisionIdUpdates]) for (const [path, text] of pass(texts)?.updates ?? []) {
46
+ texts.set(path, text);
47
+ updates.set(path, text);
48
+ }
49
+ return {
50
+ docx: updates.size === 0 ? new Uint8Array(bytes) : await writePackageParts(bytes, updates),
51
+ mintedParaIds: new Set(paragraphs.mintedParaIds)
52
+ };
53
+ };
33
54
  /** {@link prepareCanonicalDocxInput}, with the paragraph ids it minted. */
34
55
  const prepareCanonicalDocxSource = async (input) => {
35
56
  const bytes = await Result.tryPromise({
@@ -42,14 +63,7 @@ const prepareCanonicalDocxSource = async (input) => {
42
63
  if (bytes.isErr()) return Result.err(bytes.error);
43
64
  if (detectDocxContainerType(bytes.value) === DOCX_CONTAINER_TYPES.CFB) return Result.err(new CanonicalDocxInputError({ message: "Password-protected documents are unavailable in the experimental canonical session." }));
44
65
  return Result.tryPromise({
45
- try: async () => {
46
- const paragraphs = await ensureParaIds(bytes.value);
47
- const { docx } = await ensureUniqueRevisionIds((await ensureUniqueControlIds(paragraphs.docx)).docx);
48
- return {
49
- docx,
50
- mintedParaIds: new Set(paragraphs.mintedParaIds)
51
- };
52
- },
66
+ try: () => normalizeCanonicalPackage(bytes.value),
53
67
  catch: (cause) => malformedPartCause(cause) ?? new CanonicalDocxInputError({
54
68
  message: cause instanceof Error ? cause.message : "Canonical document normalization failed.",
55
69
  cause
@@ -74,6 +74,8 @@ export declare const paragraphMintKeys: (xml: string) => readonly string[] | und
74
74
  * keyed on the ordinal alone.
75
75
  */
76
76
  export declare const mintParaId: (context: MintContext, partPath: string, ordinal: number, keys: readonly string[] | undefined) => string;
77
+ /** Whether a package with these part paths carries a digital signature. */
78
+ export declare const isDigitallySignedPackage: (entries: readonly string[]) => boolean;
77
79
  type PackageStoryPartsOptions = {
78
80
  documentPartName: string;
79
81
  /** The main part's relationships part, when the package has one. */
@@ -108,6 +110,35 @@ export type UnnamedParagraphIds = {
108
110
  * it. A repeated authored id is left for its readers to judge.
109
111
  */
110
112
  export declare const assignPackageParaIds: (options: AssignPackageParaIdsOptions) => ReadonlyMap<string, UnnamedParagraphIds>;
113
+ /**
114
+ * A package's XML parts as one bounded read decoded them, and the texts that
115
+ * write the paragraph ids {@link ensureParaIds} would write.
116
+ */
117
+ export type PackageParaIdPlan = {
118
+ /** The package's part paths. */
119
+ entries: readonly string[];
120
+ /** Each XML part the read decoded, by path, as the package holds it. */
121
+ partTexts: ReadonlyMap<string, string>;
122
+ /** The part texts that write the ids, by path. */
123
+ updates: ReadonlyMap<string, string>;
124
+ /** Every id the texts write, in scan order. */
125
+ mintedParaIds: readonly string[];
126
+ assigned: number;
127
+ deduplicated: number;
128
+ };
129
+ /**
130
+ * Read a `.docx` buffer's XML parts once and plan the paragraph ids
131
+ * {@link ensureParaIds} writes, without writing them. Failures are surfaced
132
+ * as {@link EnsureParaIdsError}, as {@link ensureParaIds} surfaces them.
133
+ */
134
+ export declare const planPackageParaIds: (docx: Uint8Array | ArrayBuffer) => Promise<PackageParaIdPlan>;
135
+ /** The error for a normalization that would invalidate a package's signatures. */
136
+ export declare const signedPackageMutationError: () => EnsureParaIdsError;
137
+ /**
138
+ * `docx` with each part of `updates` written as its text, in one write of the
139
+ * package. Every other entry keeps its stored bytes.
140
+ */
141
+ export declare const writePackageParts: (docx: Uint8Array | ArrayBuffer, updates: ReadonlyMap<string, string>) => Promise<Uint8Array>;
111
142
  /**
112
143
  * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. All package,
113
144
  * XML, and compression failures are surfaced as {@link EnsureParaIdsError}.
@@ -538,7 +538,8 @@ const relatedStoryParts = (rels, relsPath, entries) => {
538
538
  /** OPC part names are case-insensitive; compare lowercased. */
539
539
  const matchesTargetPattern = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
540
540
  const toUint8Array = (docx) => docx instanceof Uint8Array ? docx : new Uint8Array(docx);
541
- const hasDigitalSignatureParts = (zip) => zip.entries().some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
541
+ /** Whether a package with these part paths carries a digital signature. */
542
+ const isDigitallySignedPackage = (entries) => entries.some((path) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
542
543
  /** The parts besides the main one whose paragraphs get ids. */
543
544
  const packageStoryParts = ({ documentPartName, documentRels, entries }) => {
544
545
  const storyParts = relatedStoryParts(documentRels, relationshipsPathFor(documentPartName), entries);
@@ -618,12 +619,7 @@ const packageParaIdUpdates = (partTexts, parts) => {
618
619
  deduplicated
619
620
  };
620
621
  };
621
- /**
622
- * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. See the
623
- * module doc for the exact contract. Throws {@link EnsureParaIdsError} when
624
- * the buffer is not a WordprocessingML package or a part is malformed.
625
- */
626
- const ensureParaIdsInternal = async (docx, options) => {
622
+ const planPackageParaIdsInternal = async (docx) => {
627
623
  const archive = await loadDocxArchive(docx);
628
624
  const relsPath = archive.entries.find((name) => name.toLowerCase() === PACKAGE_RELATIONSHIPS_PART);
629
625
  const rels = relsPath === void 0 ? null : await archive.readEntryString(relsPath);
@@ -646,30 +642,67 @@ const ensureParaIdsInternal = async (docx, options) => {
646
642
  const text = await archive.readEntryString(name);
647
643
  if (text !== null) partTexts.set(name, text);
648
644
  }
649
- const { updates, mintedParaIds, assigned, deduplicated } = packageParaIdUpdates(partTexts, scanPackageParaIds({
645
+ return {
646
+ entries: archive.entries,
650
647
  partTexts,
651
- documentPartName,
652
- isTargetPart
653
- }));
654
- if (updates.size === 0) return {
655
- docx: toUint8Array(docx),
656
- assigned: 0,
657
- deduplicated: 0,
658
- alreadyComplete: true,
659
- mintedParaIds: []
648
+ ...packageParaIdUpdates(partTexts, scanPackageParaIds({
649
+ partTexts,
650
+ documentPartName,
651
+ isTargetPart
652
+ }))
660
653
  };
654
+ };
655
+ /** Run `normalize`, surfacing every failure as an {@link EnsureParaIdsError}. */
656
+ const withEnsureParaIdsErrors = async (normalize) => {
657
+ try {
658
+ return await normalize();
659
+ } catch (error) {
660
+ if (error instanceof EnsureParaIdsError) throw error;
661
+ const message = error instanceof Error ? error.message : String(error);
662
+ throw createEnsureParaIdsError(`Failed to normalize paragraph IDs: ${message}`, error);
663
+ }
664
+ };
665
+ /**
666
+ * Read a `.docx` buffer's XML parts once and plan the paragraph ids
667
+ * {@link ensureParaIds} writes, without writing them. Failures are surfaced
668
+ * as {@link EnsureParaIdsError}, as {@link ensureParaIds} surfaces them.
669
+ */
670
+ const planPackageParaIds = (docx) => withEnsureParaIdsErrors(() => planPackageParaIdsInternal(docx));
671
+ /** The error for a normalization that would invalidate a package's signatures. */
672
+ const signedPackageMutationError = () => new EnsureParaIdsError({
673
+ reason: ENSURE_PARA_IDS_REASONS.SIGNED_PACKAGE,
674
+ message: "Refusing to normalize a digitally signed package because rewriting OOXML invalidates its signatures. Warn the user and pass allowSignedPackageMutation only if invalidation is acceptable."
675
+ });
676
+ /**
677
+ * `docx` with each part of `updates` written as its text, in one write of the
678
+ * package. Every other entry keeps its stored bytes.
679
+ */
680
+ const writePackageParts = async (docx, updates) => {
661
681
  const zip = await ZipArchive.read(docx);
662
- if (hasDigitalSignatureParts(zip) && options.allowSignedPackageMutation !== true) throw new EnsureParaIdsError({
663
- reason: ENSURE_PARA_IDS_REASONS.SIGNED_PACKAGE,
664
- message: "Refusing to normalize a digitally signed package because rewriting OOXML invalidates its signatures. Warn the user and pass allowSignedPackageMutation only if invalidation is acceptable."
665
- });
666
682
  for (const [partPath, content] of updates) {
667
683
  const sourceEntry = zip.entry(partPath);
668
684
  if (sourceEntry === void 0) throw createEnsureParaIdsError(`Package part disappeared during normalization: ${partPath}`);
669
685
  zip.set(partPath, content, { modified: sourceEntry.modified });
670
686
  }
687
+ return await zip.generate({ level: 6 });
688
+ };
689
+ /**
690
+ * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. See the
691
+ * module doc for the exact contract. Throws {@link EnsureParaIdsError} when
692
+ * the buffer is not a WordprocessingML package or a part is malformed.
693
+ */
694
+ const ensureParaIdsInternal = async (docx, options) => {
695
+ const { entries, updates, mintedParaIds, assigned, deduplicated } = await planPackageParaIdsInternal(docx);
696
+ if (updates.size === 0) return {
697
+ docx: toUint8Array(docx),
698
+ assigned: 0,
699
+ deduplicated: 0,
700
+ alreadyComplete: true,
701
+ mintedParaIds: []
702
+ };
703
+ if (isDigitallySignedPackage(entries) && options.allowSignedPackageMutation !== true) throw signedPackageMutationError();
671
704
  return {
672
- docx: await zip.generate({ level: 6 }),
705
+ docx: await writePackageParts(docx, updates),
673
706
  assigned,
674
707
  deduplicated,
675
708
  alreadyComplete: false,
@@ -680,13 +713,5 @@ const ensureParaIdsInternal = async (docx, options) => {
680
713
  * Backfill `w14:paraId` on every paragraph of a `.docx` buffer. All package,
681
714
  * XML, and compression failures are surfaced as {@link EnsureParaIdsError}.
682
715
  */
683
- const ensureParaIds = async (docx, options = {}) => {
684
- try {
685
- return await ensureParaIdsInternal(docx, options);
686
- } catch (error) {
687
- if (error instanceof EnsureParaIdsError) throw error;
688
- const message = error instanceof Error ? error.message : String(error);
689
- throw createEnsureParaIdsError(`Failed to normalize paragraph IDs: ${message}`, error);
690
- }
691
- };
692
- export { ENSURE_PARA_IDS_REASONS, EnsureParaIdsError, assignPackageParaIds, collectExistingParaIds, ensureParaIds, isWordprocessingElement, mintParaId, packageStoryParts, paragraphMintKeys, storyParagraphSlots };
716
+ const ensureParaIds = (docx, options = {}) => withEnsureParaIdsErrors(() => ensureParaIdsInternal(docx, options));
717
+ export { ENSURE_PARA_IDS_REASONS, EnsureParaIdsError, assignPackageParaIds, collectExistingParaIds, ensureParaIds, isDigitallySignedPackage, isWordprocessingElement, mintParaId, packageStoryParts, paragraphMintKeys, planPackageParaIds, signedPackageMutationError, storyParagraphSlots, writePackageParts };
@@ -12,6 +12,19 @@
12
12
  * under the same ids for older readers, and the parser reads one of the two,
13
13
  * so a fallback's ids are reserved but never counted as a repeat.
14
14
  */
15
+ /** Part texts that renumber repeated ids, and how many they renumber. */
16
+ export type PackageControlIdUpdates = {
17
+ /** The rewritten text of each part that repeats an id, by path. */
18
+ updates: Map<string, string>;
19
+ reminted: number;
20
+ };
21
+ /**
22
+ * The part texts that give each content control after the first carrying an
23
+ * id an id of its own; `undefined` when a part does not scan, since it may
24
+ * hold ids a new one would repeat. The body's controls win the
25
+ * first-occurrence rule.
26
+ */
27
+ export declare const uniqueControlIdUpdates: (partTexts: ReadonlyMap<string, string>) => PackageControlIdUpdates | undefined;
15
28
  export type EnsureUniqueControlIdsResult = {
16
29
  /** The normalized `.docx`; the input bytes when nothing repeated. */
17
30
  docx: Uint8Array;
@@ -46,33 +46,25 @@ const controlIdsIn = (xml) => {
46
46
  }
47
47
  }).status === "scanned" ? out : void 0;
48
48
  };
49
+ /** The story parts of `paths`, the body first, then the rest in a fixed order. */
50
+ const storyPartsInOrder = (paths) => [...paths].filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
51
+ const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
52
+ return body(a) - body(b) || a.localeCompare(b);
53
+ });
49
54
  /**
50
- * Give each content control after the first carrying an id an id of its own.
51
- * A signed package, or a part that does not scan, is left as it is.
55
+ * The part texts that give each content control after the first carrying an
56
+ * id an id of its own; `undefined` when a part does not scan, since it may
57
+ * hold ids a new one would repeat. The body's controls win the
58
+ * first-occurrence rule.
52
59
  */
53
- const ensureUniqueControlIds = async (docx) => {
54
- const zip = await ZipArchive.read(docx);
55
- const entries = zip.entries();
56
- if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
57
- docx,
58
- reminted: 0
59
- };
60
- const parts = entries.map(({ path }) => path).filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
61
- const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
62
- return body(a) - body(b) || a.localeCompare(b);
63
- });
64
- const texts = /* @__PURE__ */ new Map();
60
+ const uniqueControlIdUpdates = (partTexts) => {
65
61
  const ids = /* @__PURE__ */ new Map();
66
62
  const taken = /* @__PURE__ */ new Set();
67
- for (const path of parts) {
68
- const xml = await zip.entry(path)?.text();
69
- if (xml === void 0 || !xml.includes("sdtPr")) continue;
63
+ for (const path of storyPartsInOrder(partTexts.keys())) {
64
+ const xml = partTexts.get(path);
65
+ if (!xml.includes("sdtPr")) continue;
70
66
  const found = controlIdsIn(xml);
71
- if (found === void 0) return {
72
- docx,
73
- reminted: 0
74
- };
75
- texts.set(path, xml);
67
+ if (found === void 0) return void 0;
76
68
  ids.set(path, found);
77
69
  for (const { value } of found) taken.add(value);
78
70
  }
@@ -83,6 +75,7 @@ const ensureUniqueControlIds = async (docx) => {
83
75
  return next;
84
76
  };
85
77
  const seen = /* @__PURE__ */ new Set();
78
+ const updates = /* @__PURE__ */ new Map();
86
79
  let reminted = 0;
87
80
  for (const [path, found] of ids) {
88
81
  const edits = [];
@@ -99,19 +92,44 @@ const ensureUniqueControlIds = async (docx) => {
99
92
  });
100
93
  }
101
94
  if (edits.length === 0) continue;
102
- const patched = spliceXml(texts.get(path), edits);
95
+ const patched = spliceXml(partTexts.get(path), edits);
103
96
  if (patched === null) continue;
104
- const source = zip.entry(path);
105
- zip.set(path, patched, source ? { modified: source.modified } : {});
97
+ updates.set(path, patched);
106
98
  reminted += edits.length;
107
99
  }
108
- if (reminted === 0) return {
109
- docx,
100
+ return {
101
+ updates,
110
102
  reminted
111
103
  };
104
+ };
105
+ /**
106
+ * Give each content control after the first carrying an id an id of its own.
107
+ * A signed package, or a part that does not scan, is left as it is.
108
+ */
109
+ const ensureUniqueControlIds = async (docx) => {
110
+ const zip = await ZipArchive.read(docx);
111
+ const entries = zip.entries();
112
+ if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
113
+ docx,
114
+ reminted: 0
115
+ };
116
+ const texts = /* @__PURE__ */ new Map();
117
+ for (const path of storyPartsInOrder(entries.map((entry) => entry.path))) {
118
+ const xml = await zip.entry(path)?.text();
119
+ if (xml !== void 0) texts.set(path, xml);
120
+ }
121
+ const found = uniqueControlIdUpdates(texts);
122
+ if (found === void 0 || found.reminted === 0) return {
123
+ docx,
124
+ reminted: 0
125
+ };
126
+ for (const [path, patched] of found.updates) {
127
+ const source = zip.entry(path);
128
+ zip.set(path, patched, source ? { modified: source.modified } : {});
129
+ }
112
130
  return {
113
131
  docx: await zip.generate({ level: 6 }),
114
- reminted
132
+ reminted: found.reminted
115
133
  };
116
134
  };
117
- export { ensureUniqueControlIds };
135
+ export { ensureUniqueControlIds, uniqueControlIdUpdates };
@@ -15,6 +15,19 @@
15
15
  * under the same ids for older readers, and the parser reads one of the two,
16
16
  * so a fallback's ids are reserved but never counted as a repeat.
17
17
  */
18
+ /** Part texts that renumber repeated ids, and how many they renumber. */
19
+ export type PackageRevisionIdUpdates = {
20
+ /** The rewritten text of each part that repeats an id, by path. */
21
+ updates: Map<string, string>;
22
+ reminted: number;
23
+ };
24
+ /**
25
+ * The part texts that give each revision record after the first carrying an
26
+ * id an id of its own; `undefined` when a part does not scan, since it may
27
+ * hold ids a new one would repeat. The body's records win the
28
+ * first-occurrence rule.
29
+ */
30
+ export declare const uniqueRevisionIdUpdates: (partTexts: ReadonlyMap<string, string>) => PackageRevisionIdUpdates | undefined;
18
31
  export type EnsureUniqueRevisionIdsResult = {
19
32
  /** The normalized `.docx`; the input bytes when nothing repeated. */
20
33
  docx: Uint8Array;