@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
@@ -69,33 +69,30 @@ const revisionIdsIn = (xml) => {
69
69
  }).status === "scanned" ? out : void 0;
70
70
  };
71
71
  /**
72
- * Give each revision record after the first carrying an id an id of its own.
73
- * A signed package, or a part that does not scan, is left as it is.
72
+ * A start tag naming a revision record under any prefix. A part none matches
73
+ * holds no record, so it needs no scan.
74
74
  */
75
- const ensureUniqueRevisionIds = async (docx) => {
76
- const zip = await ZipArchive.read(docx);
77
- const entries = zip.entries();
78
- if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
79
- docx,
80
- reminted: 0
81
- };
82
- const parts = entries.map(({ path }) => path).filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
83
- const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
84
- return body(a) - body(b) || a.localeCompare(b);
85
- });
86
- const texts = /* @__PURE__ */ new Map();
75
+ const REVISION_RECORD_TAG = new RegExp(`<(?:[^\\s/>:]+:)?(?:${[...REVISION_RECORDS].join("|")})[\\s/>]`, "u");
76
+ /** The story parts of `paths`, the body first, then the rest in a fixed order. */
77
+ const storyPartsInOrder = (paths) => [...paths].filter((path) => STORY_PART_PATTERN.test(path)).sort((a, b) => {
78
+ const body = (path) => path.toLowerCase() === "word/document.xml" ? 0 : 1;
79
+ return body(a) - body(b) || a.localeCompare(b);
80
+ });
81
+ /**
82
+ * The part texts that give each revision record after the first carrying an
83
+ * id an id of its own; `undefined` when a part does not scan, since it may
84
+ * hold ids a new one would repeat. The body's records win the
85
+ * first-occurrence rule.
86
+ */
87
+ const uniqueRevisionIdUpdates = (partTexts) => {
87
88
  const ids = /* @__PURE__ */ new Map();
88
89
  const taken = /* @__PURE__ */ new Set();
89
- for (const path of parts) {
90
- const xml = await zip.entry(path)?.text();
91
- if (xml === void 0) continue;
90
+ for (const path of storyPartsInOrder(partTexts.keys())) {
91
+ const xml = partTexts.get(path);
92
+ if (!REVISION_RECORD_TAG.test(xml)) continue;
92
93
  const found = revisionIdsIn(xml);
93
- if (found === void 0) return {
94
- docx,
95
- reminted: 0
96
- };
94
+ if (found === void 0) return void 0;
97
95
  if (found.length === 0) continue;
98
- texts.set(path, xml);
99
96
  ids.set(path, found);
100
97
  for (const { value } of found) taken.add(value);
101
98
  }
@@ -106,6 +103,7 @@ const ensureUniqueRevisionIds = async (docx) => {
106
103
  return next;
107
104
  };
108
105
  const seen = /* @__PURE__ */ new Set();
106
+ const updates = /* @__PURE__ */ new Map();
109
107
  let reminted = 0;
110
108
  for (const [path, found] of ids) {
111
109
  const edits = [];
@@ -122,19 +120,44 @@ const ensureUniqueRevisionIds = async (docx) => {
122
120
  });
123
121
  }
124
122
  if (edits.length === 0) continue;
125
- const patched = spliceXml(texts.get(path), edits);
123
+ const patched = spliceXml(partTexts.get(path), edits);
126
124
  if (patched === null) continue;
127
- const source = zip.entry(path);
128
- zip.set(path, patched, source ? { modified: source.modified } : {});
125
+ updates.set(path, patched);
129
126
  reminted += edits.length;
130
127
  }
131
- if (reminted === 0) return {
132
- docx,
128
+ return {
129
+ updates,
133
130
  reminted
134
131
  };
132
+ };
133
+ /**
134
+ * Give each revision record after the first carrying an id an id of its own.
135
+ * A signed package, or a part that does not scan, is left as it is.
136
+ */
137
+ const ensureUniqueRevisionIds = async (docx) => {
138
+ const zip = await ZipArchive.read(docx);
139
+ const entries = zip.entries();
140
+ if (entries.some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX))) return {
141
+ docx,
142
+ reminted: 0
143
+ };
144
+ const texts = /* @__PURE__ */ new Map();
145
+ for (const path of storyPartsInOrder(entries.map((entry) => entry.path))) {
146
+ const xml = await zip.entry(path)?.text();
147
+ if (xml !== void 0) texts.set(path, xml);
148
+ }
149
+ const found = uniqueRevisionIdUpdates(texts);
150
+ if (found === void 0 || found.reminted === 0) return {
151
+ docx,
152
+ reminted: 0
153
+ };
154
+ for (const [path, patched] of found.updates) {
155
+ const source = zip.entry(path);
156
+ zip.set(path, patched, source ? { modified: source.modified } : {});
157
+ }
135
158
  return {
136
159
  docx: await zip.generate({ level: 6 }),
137
- reminted
160
+ reminted: found.reminted
138
161
  };
139
162
  };
140
- export { ensureUniqueRevisionIds };
163
+ export { ensureUniqueRevisionIds, uniqueRevisionIdUpdates };
@@ -1,17 +1,25 @@
1
1
  import { document_d_exports } from "../types/document.js";
2
2
  import { NumberingMap } from "./numberingParser.js";
3
- export type PreviousListState = {
4
- abstractNumId: number | null;
5
- fromStyle: boolean;
6
- numId: number | null;
7
- };
8
3
  export type ComputeListMarkerOptions = {
9
4
  numbering: NumberingMap | null;
5
+ /** The counters each list instance counts on. */
10
6
  listCounters: Map<number, number[]>;
7
+ /**
8
+ * The counters of each list definition. Every instance of a definition
9
+ * counts on these: a list goes on where the last paragraph of its
10
+ * definition stands, whichever instance that paragraph named.
11
+ */
11
12
  abstractCounters: Map<number, number[]>;
12
- restartedNumIds: Set<number>;
13
- previousList: PreviousListState;
13
+ /**
14
+ * The levels of list instances a paragraph has used, as
15
+ * {@link startedLevelKey}. An instance's start override sets a level's
16
+ * number the first time the instance is used on that level, and never
17
+ * again.
18
+ */
19
+ startedLevels: Set<number>;
14
20
  };
21
+ /** One level of one list instance, as a member of `startedLevels`. */
22
+ export declare const startedLevelKey: (numId: number, level: number) => number;
15
23
  /**
16
24
  * What each field of the marker counters depends on: the package alone, or
17
25
  * the paragraphs of the story before the current one. Total over the fields:
@@ -22,8 +30,7 @@ declare const LIST_COUNTER_DEPENDENCY: {
22
30
  readonly numbering: "package";
23
31
  readonly listCounters: "story";
24
32
  readonly abstractCounters: "story";
25
- readonly restartedNumIds: "story";
26
- readonly previousList: "story";
33
+ readonly startedLevels: "story";
27
34
  };
28
35
  type CounterDependency = typeof LIST_COUNTER_DEPENDENCY;
29
36
  type StoryCounterField = { [K in keyof CounterDependency]: CounterDependency[K] extends "story" ? K : never; }[keyof CounterDependency];
@@ -39,8 +46,7 @@ export type ListCounterSnapshot = {
39
46
  readonly cells: ReadonlyMap<number, readonly number[]>;
40
47
  readonly listCounters: readonly (readonly [number, number])[];
41
48
  readonly abstractCounters: readonly (readonly [number, number])[];
42
- readonly restartedNumIds: readonly number[];
43
- readonly previousList: Readonly<PreviousListState>;
49
+ readonly startedLevels: readonly number[];
44
50
  } & Record<StoryCounterField, unknown>;
45
51
  export declare const snapshotListCounters: (counters: ComputeListMarkerOptions) => ListCounterSnapshot;
46
52
  /** Put the story half of `counters` back as the snapshot copied it. */
@@ -48,33 +54,34 @@ export declare const restoreListCounters: (counters: ComputeListMarkerOptions, s
48
54
  /**
49
55
  * The counter arrays one paragraph advanced: the array bound to its list
50
56
  * instance and abstract list after it, and those bound to them before it.
51
- * Besides these the paragraph changes only the previous-list state and
52
- * whether its instance restarted.
57
+ * Besides these the paragraph changes only which level of its instance has
58
+ * been used.
53
59
  */
54
60
  export type ListCounterAdvance = {
55
61
  readonly numId: number;
56
62
  readonly abstractNumId: number | null;
63
+ /** The level the paragraph counted on. */
64
+ readonly level: number;
57
65
  readonly counters: number[];
58
66
  readonly listBefore: number[] | undefined;
59
67
  readonly abstractBefore: number[] | undefined;
60
68
  };
61
69
  /** What one paragraph's marker computation left in the story half of the counters. */
62
70
  export type ListCounterStep = {
63
- readonly previousList: Readonly<PreviousListState>;
64
71
  readonly advanced: {
65
72
  readonly numId: number;
66
73
  readonly abstractNumId: number | null;
74
+ readonly level: number;
67
75
  readonly cell: number;
68
76
  readonly values: readonly number[];
69
- readonly restarted: boolean;
70
77
  } | undefined;
71
78
  };
72
79
  /** The step a paragraph just took, `advance` being what its computation returned. */
73
- export declare const listCounterStep: (counters: ComputeListMarkerOptions, advance: ListCounterAdvance | null) => ListCounterStep;
80
+ export declare const listCounterStep: (advance: ListCounterAdvance | null) => ListCounterStep;
74
81
  /**
75
82
  * Take `step` again from the counters it was first taken from: the counters
76
83
  * end as the paragraph's computation left them, without the paragraph.
77
84
  */
78
85
  export declare const replayListCounterStep: (counters: ComputeListMarkerOptions, step: ListCounterStep) => ListCounterAdvance | null;
79
- export declare const computeListMarker: (paragraph: document_d_exports.Paragraph, { numbering, listCounters, abstractCounters, restartedNumIds, previousList }: ComputeListMarkerOptions) => ListCounterAdvance | null;
86
+ export declare const computeListMarker: (paragraph: document_d_exports.Paragraph, { numbering, listCounters, abstractCounters, startedLevels }: ComputeListMarkerOptions) => ListCounterAdvance | null;
80
87
  export {};
@@ -4,6 +4,9 @@ import { isNumberingReference } from "./numberingReference.js";
4
4
  import { panic } from "better-result";
5
5
  // src/docx/listMarkerComputation.ts
6
6
  /** Marker counters shared by parsing and canonical model normalization. */
7
+ const LEVELS_PER_INSTANCE = 16;
8
+ /** One level of one list instance, as a member of `startedLevels`. */
9
+ const startedLevelKey = (numId, level) => numId * LEVELS_PER_INSTANCE + level;
7
10
  /**
8
11
  * Counter arrays by the list instance that made them: an array is made when
9
12
  * its instance's first paragraph is met, once per story run, so the numId
@@ -29,8 +32,7 @@ const snapshotListCounters = (counters) => {
29
32
  listCounters: [...counters.listCounters].map(([numId, values]) => [numId, cellOf(values)]),
30
33
  abstractCounters: [...counters.abstractCounters].map(([abstractNumId, values]) => [abstractNumId, cellOf(values)]),
31
34
  cells,
32
- restartedNumIds: [...counters.restartedNumIds],
33
- previousList: { ...counters.previousList }
35
+ startedLevels: [...counters.startedLevels]
34
36
  };
35
37
  };
36
38
  /** Put the story half of `counters` back as the snapshot copied it. */
@@ -40,83 +42,58 @@ const restoreListCounters = (counters, snapshot) => {
40
42
  const story = {
41
43
  listCounters: new Map(snapshot.listCounters.map(([numId, cell]) => [numId, arrayOf(cell)])),
42
44
  abstractCounters: new Map(snapshot.abstractCounters.map(([abstractNumId, cell]) => [abstractNumId, arrayOf(cell)])),
43
- restartedNumIds: new Set(snapshot.restartedNumIds),
44
- previousList: { ...snapshot.previousList }
45
+ startedLevels: new Set(snapshot.startedLevels)
45
46
  };
46
47
  Object.assign(counters, story);
47
48
  };
48
49
  /** The step a paragraph just took, `advance` being what its computation returned. */
49
- const listCounterStep = (counters, advance) => ({
50
- previousList: { ...counters.previousList },
51
- advanced: advance === null ? void 0 : {
52
- numId: advance.numId,
53
- abstractNumId: advance.abstractNumId,
54
- cell: counterCellOf(advance.counters),
55
- values: [...advance.counters],
56
- restarted: counters.restartedNumIds.has(advance.numId)
57
- }
58
- });
50
+ const listCounterStep = (advance) => ({ advanced: advance === null ? void 0 : {
51
+ numId: advance.numId,
52
+ abstractNumId: advance.abstractNumId,
53
+ level: advance.level,
54
+ cell: counterCellOf(advance.counters),
55
+ values: [...advance.counters]
56
+ } });
59
57
  /**
60
58
  * Take `step` again from the counters it was first taken from: the counters
61
59
  * end as the paragraph's computation left them, without the paragraph.
62
60
  */
63
61
  const replayListCounterStep = (counters, step) => {
64
- Object.assign(counters.previousList, step.previousList);
65
62
  const advanced = step.advanced;
66
63
  if (advanced === void 0) return null;
67
- const { numId, abstractNumId, cell, values, restarted } = advanced;
64
+ const { numId, abstractNumId, level, cell, values } = advanced;
68
65
  const listBefore = counters.listCounters.get(numId);
69
66
  const abstractBefore = abstractNumId === null ? void 0 : counters.abstractCounters.get(abstractNumId);
70
- const array = [listBefore, abstractBefore].find((bound) => bound !== void 0 && counterCellOf(bound) === cell) ?? cellArray(cell, values);
71
- for (let level = 0; level < values.length; level += 1) array[level] = values[level] ?? NaN;
67
+ const array = [abstractBefore, listBefore].find((bound) => bound !== void 0 && counterCellOf(bound) === cell) ?? cellArray(cell, values);
68
+ for (let index = 0; index < values.length; index += 1) array[index] = values[index] ?? NaN;
72
69
  counters.listCounters.set(numId, array);
73
70
  if (abstractNumId !== null) counters.abstractCounters.set(abstractNumId, array);
74
- if (restarted) counters.restartedNumIds.add(numId);
71
+ counters.startedLevels.add(startedLevelKey(numId, level));
75
72
  return {
76
73
  numId,
77
74
  abstractNumId,
75
+ level,
78
76
  counters: array,
79
77
  listBefore,
80
78
  abstractBefore
81
79
  };
82
80
  };
83
- const computeListMarker = (paragraph, { numbering, listCounters, abstractCounters, restartedNumIds, previousList }) => {
81
+ const computeListMarker = (paragraph, { numbering, listCounters, abstractCounters, startedLevels }) => {
84
82
  const listRendering = paragraph.listRendering;
85
- if (!listRendering || !numbering) {
86
- previousList.abstractNumId = null;
87
- previousList.fromStyle = false;
88
- previousList.numId = null;
89
- return null;
90
- }
83
+ if (!listRendering || !numbering) return null;
91
84
  const { numId, level } = listRendering;
92
- if (!isNumberingReference(numId)) {
93
- previousList.abstractNumId = null;
94
- previousList.fromStyle = false;
95
- previousList.numId = null;
96
- return null;
97
- }
85
+ if (!isNumberingReference(numId)) return null;
98
86
  const listBefore = listCounters.get(numId);
99
- const firstEncounter = listBefore === void 0;
100
- let counters = listBefore ?? cellArray(numId, UNSET_COUNTERS);
101
- if (firstEncounter) listCounters.set(numId, counters);
102
87
  const abstractNumId = numbering.getAbstractNumId(numId);
103
- const styleNumbering = paragraph.formatting?.numPr?.kind !== "reference" && paragraph.formatting?.numPrFromStyle?.kind === "reference";
104
- const resumesRestartedInstance = firstEncounter && listRendering.startOverride === void 0 && abstractNumId !== null && previousList.abstractNumId === abstractNumId && previousList.numId !== null && previousList.numId !== numId && restartedNumIds.has(previousList.numId);
105
- const resumesStyleInstance = firstEncounter && !styleNumbering && listRendering.startOverride === void 0 && abstractNumId !== null && previousList.abstractNumId === abstractNumId && previousList.fromStyle === true;
106
- if (abstractNumId !== null && (styleNumbering || resumesRestartedInstance || resumesStyleInstance)) {
107
- const latestAbstractCounters = abstractCounters.get(abstractNumId);
108
- if (latestAbstractCounters) {
109
- counters = latestAbstractCounters;
110
- listCounters.set(numId, counters);
111
- }
112
- }
113
- if (listRendering.startOverride !== void 0 || resumesRestartedInstance || previousList.numId === numId && restartedNumIds.has(numId)) restartedNumIds.add(numId);
114
- if (abstractNumId !== null && level > 0) {
115
- const latestAbstractCounters = abstractCounters.get(abstractNumId);
116
- if (counters.slice(0, level).every(Number.isNaN)) for (let i = 0; i < level; i += 1) {
117
- const latestCounter = latestAbstractCounters?.[i];
118
- counters[i] = latestCounter !== void 0 && !Number.isNaN(latestCounter) ? latestCounter : numbering.getLevel(numId, i)?.start ?? 1;
119
- }
88
+ const abstractBefore = abstractNumId === null ? void 0 : abstractCounters.get(abstractNumId);
89
+ const counters = abstractBefore ?? listBefore ?? cellArray(numId, UNSET_COUNTERS);
90
+ listCounters.set(numId, counters);
91
+ const startedKey = startedLevelKey(numId, level);
92
+ const startsLevel = !startedLevels.has(startedKey);
93
+ startedLevels.add(startedKey);
94
+ if (startsLevel && listRendering.startOverride !== void 0) counters[level] = listRendering.startOverride - 1;
95
+ if (abstractNumId !== null) {
96
+ for (let i = 0; i < level; i += 1) if (Number.isNaN(counters[i])) counters[i] = numbering.getLevel(numId, i)?.start ?? 1;
120
97
  }
121
98
  if (Number.isNaN(counters[level])) counters[level] = (numbering.getLevel(numId, level)?.start ?? 1) - 1;
122
99
  counters[level] = (counters[level] ?? 0) + 1;
@@ -126,24 +103,18 @@ const computeListMarker = (paragraph, { numbering, listCounters, abstractCounter
126
103
  const childCounter = counters[level + 1];
127
104
  counters[level + 1] = (childCounter === void 0 || Number.isNaN(childCounter) ? 0 : childCounter) + childAdvances;
128
105
  }
129
- const abstractBefore = abstractNumId === null ? void 0 : abstractCounters.get(abstractNumId);
130
106
  if (abstractNumId !== null) abstractCounters.set(abstractNumId, counters);
131
107
  const advance = {
132
108
  numId,
133
109
  abstractNumId,
110
+ level,
134
111
  counters,
135
112
  listBefore,
136
113
  abstractBefore
137
114
  };
138
- previousList.abstractNumId = abstractNumId;
139
- previousList.fromStyle = Boolean(styleNumbering);
140
- previousList.numId = numId;
141
115
  const pattern = listRendering.marker;
142
116
  if (listRendering.isBullet) {
143
117
  listRendering.marker = convertBulletToUnicode(pattern || "", bulletMarkerFontName(listRendering.markerFormatting));
144
- previousList.abstractNumId = null;
145
- previousList.fromStyle = false;
146
- previousList.numId = null;
147
118
  return advance;
148
119
  }
149
120
  const currentLevelInfo = numbering.getLevel(numId, level);
@@ -155,4 +126,4 @@ const computeListMarker = (paragraph, { numbering, listCounters, abstractCounter
155
126
  });
156
127
  return advance;
157
128
  };
158
- export { computeListMarker, counterCellOf, listCounterStep, replayListCounterStep, restoreListCounters, snapshotListCounters };
129
+ export { computeListMarker, counterCellOf, listCounterStep, replayListCounterStep, restoreListCounters, snapshotListCounters, startedLevelKey };
@@ -4,7 +4,7 @@ import { listIndentationProvenancePatch } from "../prosemirror/styles/resolvedSt
4
4
  import { createStyleResolver } from "../prosemirror/styles/styleResolver.js";
5
5
  import { canonicalJson } from "../utils/canonicalJson.js";
6
6
  import { foldListNumberFields, planParagraphListNumberFold, unfoldedListNumberContent } from "./foldedListNumberFields.js";
7
- import { computeListMarker, counterCellOf, listCounterStep, replayListCounterStep, restoreListCounters, snapshotListCounters } from "./listMarkerComputation.js";
7
+ import { computeListMarker, counterCellOf, listCounterStep, replayListCounterStep, restoreListCounters, snapshotListCounters, startedLevelKey } from "./listMarkerComputation.js";
8
8
  import { listRenderingDefinitionsMatch } from "./listRendering.js";
9
9
  import { computeListRendering, getCachedNumberingMap } from "./numberingParser.js";
10
10
  import { assignParagraphIndentationProjection, cloneParagraphWithPropertySource, paragraphFormattingWithAuthoredIndentation, sameParagraphIndentationProjection, sealParagraphFacts, withStatedIndentationBaseline } from "./paragraphPropertySource.js";
@@ -56,12 +56,7 @@ const freshCounters = (numbering) => ({
56
56
  numbering,
57
57
  listCounters: /* @__PURE__ */ new Map(),
58
58
  abstractCounters: /* @__PURE__ */ new Map(),
59
- restartedNumIds: /* @__PURE__ */ new Set(),
60
- previousList: {
61
- abstractNumId: null,
62
- fromStyle: false,
63
- numId: null
64
- }
59
+ startedLevels: /* @__PURE__ */ new Set()
65
60
  });
66
61
  /**
67
62
  * The counters before block `index` of a run, from the nearest kept
@@ -127,12 +122,11 @@ const cellOrNone = (values) => values === void 0 ? void 0 : counterCellOf(values
127
122
  const samePart = (part, left, right) => {
128
123
  const l = left.counters;
129
124
  const r = right.counters;
130
- if (part === "p") return l.previousList.abstractNumId === r.previousList.abstractNumId && l.previousList.fromStyle === r.previousList.fromStyle && l.previousList.numId === r.previousList.numId;
131
125
  const id = Number(part.slice(1));
132
126
  switch (part[0]) {
133
127
  case "n": return cellOrNone(l.listCounters.get(id)) === cellOrNone(r.listCounters.get(id));
134
128
  case "a": return cellOrNone(l.abstractCounters.get(id)) === cellOrNone(r.abstractCounters.get(id));
135
- case "r": return l.restartedNumIds.has(id) === r.restartedNumIds.has(id);
129
+ case "s": return l.startedLevels.has(id) === r.startedLevels.has(id);
136
130
  default: {
137
131
  const a = left.cell(id);
138
132
  const b = right.cell(id);
@@ -143,11 +137,10 @@ const samePart = (part, left, right) => {
143
137
  };
144
138
  /** The parts a step can have changed. */
145
139
  const partsOf = (advance) => {
146
- if (advance === null) return ["p"];
140
+ if (advance === null) return [];
147
141
  const parts = [
148
- "p",
149
142
  `n${String(advance.numId)}`,
150
- `r${String(advance.numId)}`,
143
+ `s${String(startedLevelKey(advance.numId, advance.level))}`,
151
144
  `c${String(counterCellOf(advance.counters))}`
152
145
  ];
153
146
  if (advance.abstractNumId !== null) parts.push(`a${String(advance.abstractNumId)}`);
@@ -157,11 +150,11 @@ const partsOf = (advance) => {
157
150
  };
158
151
  /** Every part in which two states differ. */
159
152
  const differingParts = (left, right) => {
160
- const parts = /* @__PURE__ */ new Set(["p"]);
153
+ const parts = /* @__PURE__ */ new Set();
161
154
  for (const view of [left, right]) {
162
155
  for (const numId of view.counters.listCounters.keys()) parts.add(`n${String(numId)}`);
163
156
  for (const abstractNumId of view.counters.abstractCounters.keys()) parts.add(`a${String(abstractNumId)}`);
164
- for (const numId of view.counters.restartedNumIds) parts.add(`r${String(numId)}`);
157
+ for (const started of view.counters.startedLevels) parts.add(`s${String(started)}`);
165
158
  for (const cell of view.cells()) parts.add(`c${String(cell)}`);
166
159
  }
167
160
  for (const part of parts) if (samePart(part, left, right)) parts.delete(part);
@@ -228,7 +221,7 @@ var ListNormalizationCache = class {
228
221
  const steps = [];
229
222
  const { output, settled } = normalize(block, (advance) => {
230
223
  advances.push(advance);
231
- steps.push(listCounterStep(counters, advance));
224
+ steps.push(listCounterStep(advance));
232
225
  });
233
226
  sinceCheckpoint += 1;
234
227
  normalized += 1;
@@ -1,4 +1,3 @@
1
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
2
1
  import { BlockContent, Hyperlink } from "../types/content.js";
3
2
  import { document_d_exports } from "../types/document.js";
4
3
  import { SaveDiagnosticOptions } from "./saveDiagnostics.js";
@@ -59,20 +58,34 @@ export declare const assertSectionCarriersMatchModel: ({ doc, serializedSectionC
59
58
  */
60
59
  export declare function readRelsOrStub(zip: ZipArchive, relsPath: string): Promise<string>;
61
60
  declare const CanonicalImageRelationshipRefusalErrorBase: TaggedErrorClass<"CanonicalImageRelationshipRefusalError">;
61
+ /**
62
+ * A picture the save cannot publish: the model and the package disagree on its
63
+ * relationship (`conflict` in the main document part, `unresolved`), its
64
+ * bytes are missing, or its target is unsafe.
65
+ */
62
66
  export declare class CanonicalImageRelationshipRefusalError extends CanonicalImageRelationshipRefusalErrorBase<{
63
67
  message: string;
64
- gap: typeof CANONICAL_GAP.saveSerialization;
65
68
  part: string;
66
69
  relationshipId: string;
67
70
  reason: "conflict" | "unresolved" | "missingMedia" | "unsafeTarget";
68
71
  }> {}
69
72
  type PublishCanonicalImageResourcesOptions = {
73
+ /**
74
+ * The save's own copy of the document: a copied picture whose id another
75
+ * binding in its header, footer or note part already holds is published
76
+ * under a fresh id in that part, written onto this copy's picture.
77
+ */
70
78
  document: document_d_exports.Document;
71
79
  zip: ZipArchive;
72
80
  compressionLevel: number;
81
+ /**
82
+ * Whether the caller may rebind such a picture. A caller that cannot passes
83
+ * false and receives the parts that need it, to save another way.
84
+ */
85
+ rebind: boolean;
73
86
  };
74
87
  /** Publish allocated pictures into each owning story without rebinding canonical ids. */
75
- export declare const publishCanonicalImageResources: ({ document, zip, compressionLevel }: PublishCanonicalImageResourcesOptions) => Promise<void>;
88
+ export declare const publishCanonicalImageResources: ({ document, zip, compressionLevel, rebind }: PublishCanonicalImageResourcesOptions) => Promise<readonly string[]>;
76
89
  /** Newly authored text links; the census shares the complete owning-part traversal. */
77
90
  export declare function collectHyperlinksWithoutRId(blocks: BlockContent[]): Hyperlink[];
78
91
  /** The selective save boundary must use the same resource census as full repack. */
@@ -1,6 +1,5 @@
1
1
  import { consumeTrackedSectionEndpointRemoval } from "../internal/sectionEndpointResolution.js";
2
2
  import { consumeSectionReferenceResolution } from "../internal/sectionReferenceResolution.js";
3
- import { CANONICAL_GAP } from "../types/canonicalCapabilities.js";
4
3
  import { canonicalJson } from "../utils/canonicalJson.js";
5
4
  import { base64ToBytes, decodeText, encodeUtf8 } from "../utils/textEncoding.js";
6
5
  import { isAllowedExternalWatermarkImageUrl } from "../watermark/index.js";
@@ -451,6 +450,11 @@ const materializeEmbeddedMedia = async ({ document, zip, compressionLevel }) =>
451
450
  await registerImageExtensions(zip, extensions, compressionLevel);
452
451
  };
453
452
  const CanonicalImageRelationshipRefusalErrorBase = TaggedError("CanonicalImageRelationshipRefusalError");
453
+ /**
454
+ * A picture the save cannot publish: the model and the package disagree on its
455
+ * relationship (`conflict` in the main document part, `unresolved`), its
456
+ * bytes are missing, or its target is unsafe.
457
+ */
454
458
  var CanonicalImageRelationshipRefusalError = class extends CanonicalImageRelationshipRefusalErrorBase {};
455
459
  /**
456
460
  * Write the media a canonical session replaced or removed since the package
@@ -504,7 +508,8 @@ const publishCanonicalMediaReplacements = async ({ document, zip, compressionLev
504
508
  zip.set(registry.path, xml, { level: compressionLevel });
505
509
  };
506
510
  /** Publish allocated pictures into each owning story without rebinding canonical ids. */
507
- const publishCanonicalImageResources = async ({ document, zip, compressionLevel }) => {
511
+ const publishCanonicalImageResources = async ({ document, zip, compressionLevel, rebind }) => {
512
+ const rebindingParts = [];
508
513
  await publishCanonicalMediaReplacements({
509
514
  document,
510
515
  zip,
@@ -525,19 +530,25 @@ const publishCanonicalImageResources = async ({ document, zip, compressionLevel
525
530
  const local = parseRelationships(xml);
526
531
  const partPath = relsPath.replace("/_rels/", "/").replace(/\.rels$/u, "");
527
532
  let changed = false;
533
+ const rebound = /* @__PURE__ */ new Map();
528
534
  for (const image of images) {
529
- const id = image.rId;
530
- if (id === void 0) continue;
535
+ const rootId = image.rId;
536
+ if (rootId === void 0) continue;
537
+ const reboundId = rebound.get(rootId);
538
+ if (reboundId !== void 0) {
539
+ image.rId = reboundId;
540
+ continue;
541
+ }
542
+ let id = rootId;
531
543
  const refuse = (reason, message) => {
532
544
  throw new CanonicalImageRelationshipRefusalError({
533
545
  message,
534
- gap: CANONICAL_GAP.saveSerialization,
535
546
  part: relsPath,
536
547
  relationshipId: id,
537
548
  reason
538
549
  });
539
550
  };
540
- const source = local.get(id);
551
+ let source = local.get(id);
541
552
  const allocated = document.package.relationships?.get(id);
542
553
  const allocatedMediaPath = allocated?.targetMode === "External" || allocated?.type !== RELATIONSHIP_TYPES.image ? void 0 : resolveRelativePath("word/_rels/document.xml.rels", allocated.target);
543
554
  const allocatedMedia = allocatedMediaPath === void 0 ? void 0 : document.package.media?.get(allocatedMediaPath);
@@ -550,7 +561,19 @@ const publishCanonicalImageResources = async ({ document, zip, compressionLevel
550
561
  if (absolute !== void 0 && isUnsafePackagePath(absolute)) return refuse("unsafeTarget", "A canonical inline picture has an unsafe media target.");
551
562
  if (source) {
552
563
  const sourceAbsolute = source.targetMode === "External" ? void 0 : resolveRelativePath(relsPath, source.target);
553
- if (source.type !== RELATIONSHIP_TYPES.image || source.targetMode === "External" !== (desired.targetMode === "External") || (absolute === void 0 ? source.target !== desired.target : sourceAbsolute !== absolute)) return refuse("conflict", "A canonical inline picture relationship conflicts with its owning source binding.");
564
+ if (source.type !== RELATIONSHIP_TYPES.image || source.targetMode === "External" !== (desired.targetMode === "External") || (absolute === void 0 ? source.target !== desired.target : sourceAbsolute !== absolute)) {
565
+ if (desired !== allocated || relsPath === "word/_rels/document.xml.rels") return refuse("conflict", "A canonical inline picture relationship conflicts with its owning source binding.");
566
+ if (!rebind) {
567
+ if (!rebindingParts.includes(partPath)) rebindingParts.push(partPath);
568
+ continue;
569
+ }
570
+ let index = 1;
571
+ while (local.has(`rId${index}`)) index += 1;
572
+ id = mintRelationshipId(index);
573
+ rebound.set(rootId, id);
574
+ image.rId = id;
575
+ source = void 0;
576
+ }
554
577
  }
555
578
  if (absolute !== void 0 && !findZipEntryCaseInsensitive(zip, absolute.toLowerCase())) {
556
579
  const media = document.package.media?.get(absolute);
@@ -581,6 +604,7 @@ const publishCanonicalImageResources = async ({ document, zip, compressionLevel
581
604
  }
582
605
  if (changed) zip.set(relsPath, xml, { level: compressionLevel });
583
606
  }
607
+ return rebindingParts;
584
608
  };
585
609
  const collectExternalHyperlinkResources = (blocks) => {
586
610
  const resources = [];
@@ -853,7 +877,8 @@ const finishRepack = async ({ document: sourceDocument, originalZip, outputZip,
853
877
  if (bodyAuthority === "canonical") await publishCanonicalImageResources({
854
878
  document,
855
879
  zip: outputZip,
856
- compressionLevel
880
+ compressionLevel,
881
+ rebind: true
857
882
  });
858
883
  const parts = collectDocxParts(document, outputZip);
859
884
  normalizeExportDrawingIds(document);
@@ -975,7 +1000,8 @@ async function repackDocxFromRaw(doc, rawContent, options = {}) {
975
1000
  if (options.bodyAuthority === "canonical") await publishCanonicalImageResources({
976
1001
  document: exportDocument,
977
1002
  zip: newZip,
978
- compressionLevel
1003
+ compressionLevel,
1004
+ rebind: true
979
1005
  });
980
1006
  const parts = collectDocxParts(exportDocument, newZip);
981
1007
  normalizeExportDrawingIds(exportDocument);
@@ -346,11 +346,19 @@ async function writeChangedParts({ doc, originalBuffer, options, collectDiagnost
346
346
  }
347
347
  for (const [path, xml] of normalizeImportedNumericIds(sourceParts)) if (xml !== sourceParts.get(path)) zip.set(path, xml);
348
348
  }
349
- if (options.bodyAuthority === "canonical") await publishCanonicalImageResources({
350
- document: doc,
351
- zip,
352
- compressionLevel: 6
353
- });
349
+ if (options.bodyAuthority === "canonical") {
350
+ const part = (await publishCanonicalImageResources({
351
+ document: doc,
352
+ zip,
353
+ compressionLevel: 6,
354
+ rebind: false
355
+ })).at(0);
356
+ if (part !== void 0) return decline({
357
+ scope: "part",
358
+ part,
359
+ reason: "unmaterializedStoryResource"
360
+ });
361
+ }
354
362
  const updates = /* @__PURE__ */ new Map();
355
363
  if (changedParaIds.size > 0 || structuralChange) {
356
364
  const docXmlFile = zip.entry("word/document.xml");