@stll/folio-core 0.72.0 → 0.74.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 (244) hide show
  1. package/README.md +12 -6
  2. package/dist/ai-edits/applyTypes.d.ts +85 -0
  3. package/dist/ai-edits/applyTypes.js +24 -0
  4. package/dist/ai-edits/clean-text.d.ts +7 -1
  5. package/dist/ai-edits/clean-text.js +23 -2
  6. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  7. package/dist/ai-edits/headless.d.ts +29 -147
  8. package/dist/ai-edits/headless.js +215 -1639
  9. package/dist/ai-edits/index.d.ts +3 -3
  10. package/dist/ai-edits/index.js +2 -3
  11. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  12. package/dist/ai-edits/pending-suggestions.js +183 -90
  13. package/dist/ai-edits/pendingJoin.js +6 -1
  14. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  15. package/dist/ai-edits/snapshot.js +9 -4
  16. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  17. package/dist/ai-edits/table-cell-mutations.js +2 -2
  18. package/dist/ai-edits/table-geometry.d.ts +1 -1
  19. package/dist/ai-edits/table-geometry.js +1 -1
  20. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  21. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  22. package/dist/ai-edits/tableNodes.d.ts +38 -0
  23. package/dist/ai-edits/tableNodes.js +86 -0
  24. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  25. package/dist/ai-edits/tracked-batch-fidelity.js +1 -1
  26. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  27. package/dist/canonical/batchCommentReferences.js +1 -0
  28. package/dist/canonical/canonicalInlineGaps.d.ts +56 -0
  29. package/dist/canonical/canonicalInlineGaps.js +118 -0
  30. package/dist/canonical/canonicalInlineProjection.d.ts +4 -13
  31. package/dist/canonical/canonicalInlineProjection.js +5 -27
  32. package/dist/canonical/canonicalProjectionBlocks.d.ts +4 -4
  33. package/dist/canonical/canonicalPublicOperations.js +282 -75
  34. package/dist/canonical/canonicalSelection.js +1 -1
  35. package/dist/canonical/canonicalSession.d.ts +9 -1
  36. package/dist/canonical/canonicalSession.js +106 -33
  37. package/dist/compare/compare.d.ts +1 -1
  38. package/dist/compare/inline-atoms-model.d.ts +1 -1
  39. package/dist/compare/inline-atoms.d.ts +2 -2
  40. package/dist/compare/inline-provenance-model.d.ts +1 -1
  41. package/dist/compare/inline-provenance.d.ts +2 -2
  42. package/dist/compat/eigenpal.d.ts +3 -3
  43. package/dist/compat/eigenpal.js +2 -3
  44. package/dist/controller/autocompleteSuggestion.js +1 -1
  45. package/dist/controller/canonicalClipboard.d.ts +13 -3
  46. package/dist/controller/canonicalClipboard.js +186 -50
  47. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  48. package/dist/controller/canonicalClipboardResources.js +22 -2
  49. package/dist/controller/canonicalComposition.js +1 -1
  50. package/dist/controller/canonicalInput.js +1 -1
  51. package/dist/controller/canonicalPresence.js +1 -1
  52. package/dist/controller/canonicalReview.d.ts +1 -1
  53. package/dist/controller/canonicalReview.js +1 -1
  54. package/dist/controller/canonicalRoomAuthority.js +1 -1
  55. package/dist/controller/canonicalRoomWire.js +1 -1
  56. package/dist/controller/canonicalStructure.js +1 -1
  57. package/dist/controller/canonicalTabRoom.js +1 -1
  58. package/dist/controller/canonicalWatermark.d.ts +10 -0
  59. package/dist/controller/canonicalWatermark.js +37 -0
  60. package/dist/controller/canonicalYjsRoom.js +1 -1
  61. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  62. package/dist/controller/hiddenEditorApi.js +2 -17
  63. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  64. package/dist/controller/hiddenEditorManager.js +79 -23
  65. package/dist/document-operations.d.ts +1 -14
  66. package/dist/document-operations.js +1 -278
  67. package/dist/docx/canonicalSave.d.ts +1 -1
  68. package/dist/docx/canonicalSave.js +1 -1
  69. package/dist/docx/canonicalSessionInput.js +1 -1
  70. package/dist/docx/containerChildren.js +1 -1
  71. package/dist/docx/createDocx.d.ts +4 -0
  72. package/dist/docx/createDocx.js +6 -0
  73. package/dist/docx/paragraphParser.js +2 -2
  74. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  75. package/dist/docx/parser.js +1 -1
  76. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  77. package/dist/docx/reviewResolutionProvenance.js +31 -8
  78. package/dist/docx/revisionIdNormalization.js +30 -7
  79. package/dist/docx/rezip.d.ts +1 -1
  80. package/dist/docx/rezip.js +1 -1
  81. package/dist/docx/serializer/tableSerializer.js +4 -36
  82. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  83. package/dist/docx/server/templatePlan/apply.js +658 -0
  84. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  85. package/dist/docx/server/templatePlan/blocks.js +355 -0
  86. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  87. package/dist/docx/server/templatePlan/builders.js +237 -0
  88. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  89. package/dist/docx/server/templatePlan/emit.js +466 -0
  90. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  91. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  92. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  93. package/dist/docx/server/templatePlan/inspect.js +230 -0
  94. package/dist/docx/server/templatePlan/labels.d.ts +45 -0
  95. package/dist/docx/server/templatePlan/labels.js +155 -0
  96. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  97. package/dist/docx/server/templatePlan/package.js +99 -0
  98. package/dist/docx/server/templatePlan/plan.d.ts +145 -0
  99. package/dist/docx/server/templatePlan/plan.js +875 -0
  100. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  101. package/dist/docx/server/templatePlan/planShape.js +180 -0
  102. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  103. package/dist/docx/server/templatePlan/resources.js +136 -0
  104. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  105. package/dist/docx/server/templatePlan/story.js +440 -0
  106. package/dist/docx/server/templatePlan/types.d.ts +442 -0
  107. package/dist/docx/server/templatePlan/types.js +29 -0
  108. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  109. package/dist/docx/server/templatePlan/verify.js +976 -0
  110. package/dist/docx/server/templatePlan/xml.d.ts +74 -0
  111. package/dist/docx/server/templatePlan/xml.js +125 -0
  112. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  113. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  114. package/dist/docx/structuralXmlPatch.js +9 -1
  115. package/dist/docx/tableGridXml.d.ts +30 -0
  116. package/dist/docx/tableGridXml.js +54 -0
  117. package/dist/docx/tableParser.js +7 -0
  118. package/dist/i18n/loadMessages.d.ts +5 -0
  119. package/dist/i18n/loadMessages.js +46 -0
  120. package/dist/i18n/locales.d.ts +3 -0
  121. package/dist/i18n/locales.js +17 -0
  122. package/dist/i18n/messages.d.ts +3 -2
  123. package/dist/i18n/messages.js +4 -16
  124. package/dist/index.d.ts +3 -3
  125. package/dist/index.js +2 -3
  126. package/dist/internal/clipboardTransformPlugin.d.ts +3 -0
  127. package/dist/internal/clipboardTransformPlugin.js +13 -0
  128. package/dist/internal/extensionRuntime.d.ts +7 -0
  129. package/dist/internal/extensionRuntime.js +28 -0
  130. package/dist/internal/starterKitExtensions.d.ts +20 -0
  131. package/dist/internal/starterKitExtensions.js +123 -0
  132. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  133. package/dist/managers/ContextMenuManager.js +2 -1
  134. package/dist/managers/editorShortcuts.d.ts +1 -1
  135. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  136. package/dist/prosemirror/attrs/index.js +1 -1
  137. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  138. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  139. package/dist/prosemirror/canonicalSelectionRange.js +1 -1
  140. package/dist/prosemirror/canonicalTableCommands.js +3 -3
  141. package/dist/prosemirror/commands/comments.js +4 -4
  142. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  143. package/dist/prosemirror/commands/contentControls.js +1 -1
  144. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  145. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  146. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  147. package/dist/prosemirror/commands/pastePlainText.js +2 -3
  148. package/dist/prosemirror/commands/replaceRangeText.js +1 -1
  149. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  150. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  151. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  152. package/dist/prosemirror/commentRecords.d.ts +1 -1
  153. package/dist/prosemirror/commentRecords.js +2 -2
  154. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  155. package/dist/prosemirror/conversion/fromProseDoc.d.ts +0 -5
  156. package/dist/prosemirror/conversion/fromProseDoc.js +2 -9
  157. package/dist/prosemirror/conversion/index.d.ts +2 -2
  158. package/dist/prosemirror/conversion/index.js +2 -2
  159. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  160. package/dist/prosemirror/documentStructureCounts.js +76 -0
  161. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  162. package/dist/prosemirror/extensions/ExtensionManager.js +4 -22
  163. package/dist/prosemirror/extensions/StarterKit.d.ts +4 -27
  164. package/dist/prosemirror/extensions/StarterKit.js +29 -115
  165. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  166. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  167. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  168. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  169. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +1 -1
  170. package/dist/prosemirror/extensions/features/ListExtension.js +7 -2
  171. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  172. package/dist/prosemirror/extensions/index.d.ts +2 -1
  173. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.js +8 -3
  174. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  175. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  176. package/dist/prosemirror/extensions/nodes/TableExtension.js +8 -41
  177. package/dist/prosemirror/extensions/types.d.ts +1 -1
  178. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  179. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  180. package/dist/prosemirror/hyperlinkRemoval.js +7 -2
  181. package/dist/prosemirror/index.d.ts +3 -3
  182. package/dist/prosemirror/index.js +3 -3
  183. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  184. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  185. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  186. package/dist/prosemirror/listNumbering.d.ts +1 -1
  187. package/dist/prosemirror/listNumbering.js +1 -1
  188. package/dist/prosemirror/lockedControls.d.ts +1 -1
  189. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  190. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  191. package/dist/prosemirror/noteReferenceOccurrences.js +1 -1
  192. package/dist/prosemirror/noteReferenceReview.d.ts +2 -56
  193. package/dist/prosemirror/noteReferenceReview.js +2 -243
  194. package/dist/prosemirror/{extensions/features/ParaIdAllocatorExtension.d.ts → paraIds.d.ts} +13 -23
  195. package/dist/prosemirror/paraIds.js +152 -0
  196. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  197. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  198. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  199. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  200. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  201. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  202. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  203. package/dist/prosemirror/plugins/documentNumbering.js +1 -1
  204. package/dist/prosemirror/plugins/documentStyles.js +1 -1
  205. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  206. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  207. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  208. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  209. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  210. package/dist/prosemirror/replacedAnnotations.js +17 -2
  211. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  212. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  213. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  214. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  215. package/dist/prosemirror/selectionBounds.js +22 -0
  216. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  217. package/dist/prosemirror/suggestionCommands.d.ts +47 -0
  218. package/dist/prosemirror/suggestionCommands.js +31 -0
  219. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  220. package/dist/prosemirror/tableCellPaste.js +1 -1
  221. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  222. package/dist/prosemirror/tableRunIn.js +1 -1
  223. package/dist/prosemirror/textInput.d.ts +1 -1
  224. package/dist/prosemirror/textInput.js +1 -1
  225. package/dist/server.d.ts +7 -2
  226. package/dist/server.js +6 -1
  227. package/dist/types/canonicalCapabilities.d.ts +13 -92
  228. package/dist/types/canonicalCapabilities.js +11 -85
  229. package/package.json +4 -4
  230. package/dist/ai-edits/apply.d.ts +0 -202
  231. package/dist/ai-edits/apply.js +0 -6759
  232. package/dist/ai-edits/note-story-inventory.d.ts +0 -5
  233. package/dist/ai-edits/note-story-inventory.js +0 -10
  234. package/dist/ai-edits/revisionStretches.d.ts +0 -32
  235. package/dist/ai-edits/revisionStretches.js +0 -147
  236. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +0 -18
  237. package/dist/prosemirror/extensions/core/HistoryExtension.js +0 -122
  238. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +0 -408
  239. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +0 -135
  240. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +0 -566
  241. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -92
  242. package/dist/prosemirror/plugins/suggestionMode.js +0 -1515
  243. package/dist/prosemirror/tablePositionedBookmarks.d.ts +0 -8
  244. package/dist/prosemirror/tablePositionedBookmarks.js +0 -80
@@ -0,0 +1,875 @@
1
+ import { parseFieldInstruction } from "../../fieldParser.js";
2
+ import { computeListRendering } from "../../numberingParser.js";
3
+ import { NAMESPACES } from "../../xmlParser.js";
4
+ import { bookmarkIdsOf, mintRefBookmarkName, refFieldInstruction } from "./builders.js";
5
+ import { emphasisDeviation, emphasisSignature, paragraphBaseline, readDirectEmphasis, withCharacterStyle, withOverride, withSignatureHighlight } from "./emphasis.js";
6
+ import { styleNumbering } from "./labels.js";
7
+ import { PLAN_HIGHLIGHT_COLORS, planShapeIssue } from "./planShape.js";
8
+ import { TemplatePlanError } from "./types.js";
9
+ import { isW, maxOf, wAttr, wChildVal, walkElements } from "./xml.js";
10
+ import { Result } from "better-result";
11
+ // src/docx/server/templatePlan/plan.ts
12
+ /**
13
+ * A template plan checked against its source and template and resolved into
14
+ * what the output must hold: per output paragraph the expected text and
15
+ * emphasis, derived from the source blocks alone. The writer emits it and the
16
+ * verifier compares the written package against it.
17
+ */
18
+ const refuse = ({ code, message, blockId }) => new TemplatePlanError({
19
+ code,
20
+ message,
21
+ ...blockId === void 0 ? {} : { blockId }
22
+ });
23
+ /** Where a label may end: at white space or a line break. */
24
+ const LABEL_END = /^[ \t\u00A0\n]$/u;
25
+ const MAX_LABEL_LENGTH = 40;
26
+ const ROMAN_NUMERAL = /^(?=.)M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})$/iu;
27
+ const LABEL_WORD = /^(?:\p{L}[\p{L}\p{M}]*\.?|§{1,2}|№|#)$/u;
28
+ const LABEL_DESIGNATOR = /^[([]?(?<core>\d+(?:[.\-\u2013]\d+)*[a-z]?|\p{L}+)[)\]]?[.:)]*$/u;
29
+ const LABEL_BULLET = /^[-\u2013\u2014\u2022\u00B7\u25AA\u25E6*]$/u;
30
+ const MAX_LABEL_WORDS = 3;
31
+ /**
32
+ * Whether `label` reads as a manual list label: up to three leading words
33
+ * ("Article", "§", "Annex No.") and one designator, a number, a roman numeral
34
+ * or a letter with its brackets and punctuation; or a single bullet. This is
35
+ * the only text a plan may have removed.
36
+ */
37
+ const isManualLabel = (label) => {
38
+ if (label === "" || label.length > MAX_LABEL_LENGTH) return false;
39
+ if (LABEL_BULLET.test(label)) return true;
40
+ const tokens = label.split(/[ \u00A0]/u);
41
+ const designator = tokens.at(-1) ?? "";
42
+ const words = tokens.slice(0, -1);
43
+ const core = LABEL_DESIGNATOR.exec(designator)?.groups?.["core"];
44
+ return core !== void 0 && words.length <= MAX_LABEL_WORDS && words.every((word) => LABEL_WORD.test(word)) && (/^\d/u.test(core) || core.length === 1 || ROMAN_NUMERAL.test(core));
45
+ };
46
+ const NOTES_OF_REFERENCE = {
47
+ footnoteReference: "footnotes",
48
+ endnoteReference: "endnotes"
49
+ };
50
+ const LABEL_SPACE = /^[ \t ]+/u;
51
+ const LEADING_SPACE = /^[ \t ]*/u;
52
+ /** Whether a block holds no text and no object. */
53
+ const isBlankBlock = ({ block }) => block.text.trim() === "" && block.inlineObjects === 0;
54
+ /** Whether a block, or a paragraph inside it, renders a list label. */
55
+ const showsLabel = ({ block }) => block.label !== null || (block.nested ?? []).some(({ label }) => label !== null);
56
+ const HYPERLINK_FIELD = "HYPERLINK";
57
+ const LOCATION_SWITCH = "l";
58
+ /** The link a HYPERLINK field makes: its address and the place in it, if any. */
59
+ const hyperlinkFieldLink = ({ instruction, kind }) => {
60
+ if (kind !== HYPERLINK_FIELD) return null;
61
+ const { argument, switches } = parseFieldInstruction(instruction);
62
+ if (argument === void 0 || argument === "") return null;
63
+ return {
64
+ kind: "url",
65
+ url: argument,
66
+ anchor: switches.find(({ switch: name }) => name.toLowerCase() === LOCATION_SWITCH)?.value ?? null
67
+ };
68
+ };
69
+ const NOTE_REFERENCE_KINDS = /* @__PURE__ */ new Set(["footnoteReference", "endnoteReference"]);
70
+ /** What a stripped label may consist of. */
71
+ const STRIPPABLE_KINDS = /* @__PURE__ */ new Set(["text", "tab"]);
72
+ /**
73
+ * Character styles that only give a link its look. The template supplies
74
+ * that look; any other character style inside a link is emphasis.
75
+ */
76
+ const LINK_STYLE_NAMES = /* @__PURE__ */ new Set([
77
+ "hyperlink",
78
+ "followedhyperlink",
79
+ "internet link",
80
+ "visited internet link"
81
+ ]);
82
+ /** The pieces of one source paragraph, each with the emphasis it states. */
83
+ const paragraphPieces = ({ read, context: { styles, defaultStyleId, defaultEmphasis }, origin, fields }) => {
84
+ const baseline = paragraphBaseline(styles.get(read.styleId ?? defaultStyleId ?? ""), defaultEmphasis);
85
+ return read.atoms.map((atom) => {
86
+ const fieldLink = atom.fields.map((index) => fields[index]).map((field) => field === void 0 ? null : hyperlinkFieldLink(field)).find((link) => link !== null);
87
+ const link = atom.link ?? fieldLink ?? null;
88
+ let signature = "";
89
+ if (!NOTE_REFERENCE_KINDS.has(atom.kind)) {
90
+ const characterStyle = styles.get(wChildVal(atom.runProperties, "rStyle") ?? "");
91
+ const isLinkLook = link !== null && LINK_STYLE_NAMES.has(characterStyle?.name?.toLowerCase() ?? "");
92
+ signature = emphasisSignature(emphasisDeviation(withOverride(isLinkLook ? baseline : withCharacterStyle(baseline, characterStyle), readDirectEmphasis(atom.runProperties)), baseline));
93
+ }
94
+ return {
95
+ kind: atom.kind,
96
+ text: atom.text,
97
+ signature,
98
+ link,
99
+ atom,
100
+ origin
101
+ };
102
+ });
103
+ };
104
+ const isHighSurrogate = (unit) => unit >= 55296 && unit <= 56319;
105
+ const isLowSurrogate = (unit) => unit >= 56320 && unit <= 57343;
106
+ /** Whether `offset` falls between the two units of one character. */
107
+ const splitsCharacter = (text, offset) => offset > 0 && offset < text.length && isHighSurrogate(text.charCodeAt(offset - 1)) && isLowSurrogate(text.charCodeAt(offset));
108
+ /**
109
+ * Split text pieces at the offsets in `cuts`. A cut inside a character, or
110
+ * inside a piece that is not text, is not made; the caller finds it missing
111
+ * among the boundaries.
112
+ */
113
+ const splitPieces = (pieces, cuts) => {
114
+ const out = [];
115
+ let offset = 0;
116
+ for (const piece of pieces) {
117
+ const start = offset;
118
+ const end = start + piece.text.length;
119
+ offset = end;
120
+ const inside = piece.kind === "text" ? cuts.filter((cut) => cut > start && cut < end && !splitsCharacter(piece.text, cut - start)) : [];
121
+ if (inside.length === 0) {
122
+ out.push({
123
+ piece,
124
+ start,
125
+ end
126
+ });
127
+ continue;
128
+ }
129
+ let cursor = start;
130
+ for (const cut of [...new Set(inside)].toSorted((a, b) => a - b)) {
131
+ out.push({
132
+ piece: {
133
+ ...piece,
134
+ text: piece.text.slice(cursor - start, cut - start)
135
+ },
136
+ start: cursor,
137
+ end: cut
138
+ });
139
+ cursor = cut;
140
+ }
141
+ out.push({
142
+ piece: {
143
+ ...piece,
144
+ text: piece.text.slice(cursor - start)
145
+ },
146
+ start: cursor,
147
+ end
148
+ });
149
+ }
150
+ return out;
151
+ };
152
+ const isSpanWithin = ({ start, end }, from, length) => Number.isInteger(start) && Number.isInteger(end) && start >= from && start < end && end <= length;
153
+ const spansOverlap = (spans) => {
154
+ const ordered = spans.toSorted((a, b) => a.start - b.start);
155
+ return ordered.some((span, index) => {
156
+ const previous = ordered[index - 1];
157
+ return previous !== void 0 && span.start < previous.end;
158
+ });
159
+ };
160
+ const partSegments = ({ block, pieces, strippedLength, references, highlights }) => {
161
+ const blockId = block.block.id;
162
+ const length = block.block.text.length;
163
+ const badReference = (message) => Result.err(refuse({
164
+ code: "reference-span-invalid",
165
+ message,
166
+ blockId
167
+ }));
168
+ const badHighlight = (message) => Result.err(refuse({
169
+ code: "highlight-span-invalid",
170
+ message,
171
+ blockId
172
+ }));
173
+ for (const reference of references) if (!isSpanWithin(reference, strippedLength, length)) return badReference(`Reference span ${reference.start}-${reference.end} lies outside block ${blockId}.`);
174
+ for (const highlight of highlights) if (!isSpanWithin(highlight, strippedLength, length) || !PLAN_HIGHLIGHT_COLORS.has(highlight.color)) return badHighlight(`Highlight ${highlight.start}-${highlight.end} (${highlight.color}) does not fit block ${blockId}.`);
175
+ if (spansOverlap(references)) return badReference(`Reference spans overlap in block ${blockId}.`);
176
+ if (spansOverlap(highlights)) return badHighlight(`Highlight spans overlap in block ${blockId}.`);
177
+ const ordered = references.toSorted((a, b) => a.start - b.start);
178
+ const split = splitPieces(pieces, [
179
+ strippedLength,
180
+ ...references.flatMap(({ start, end }) => [start, end]),
181
+ ...highlights.flatMap(({ start, end }) => [start, end])
182
+ ]);
183
+ const boundaries = /* @__PURE__ */ new Set([0, ...split.map(({ end }) => end)]);
184
+ if (!boundaries.has(strippedLength)) return Result.err(refuse({
185
+ code: "strip-label-mismatch",
186
+ message: `The label to strip from block ${blockId} ends inside a character or mark.`,
187
+ blockId
188
+ }));
189
+ for (const { start, end } of references) if (!boundaries.has(start) || !boundaries.has(end)) return badReference(`Reference span ${start}-${end} in block ${blockId} cuts a character or mark.`);
190
+ for (const { start, end } of highlights) if (!boundaries.has(start) || !boundaries.has(end)) return badHighlight(`Highlight ${start}-${end} in block ${blockId} cuts a character or mark.`);
191
+ const positioned = [];
192
+ for (const entry of split) {
193
+ const empty = entry.start === entry.end;
194
+ if (entry.end <= strippedLength && !empty) {
195
+ if (!STRIPPABLE_KINDS.has(entry.piece.kind)) return Result.err(refuse({
196
+ code: "strip-label-mismatch",
197
+ message: `The label to strip from block ${blockId} covers more than text.`,
198
+ blockId
199
+ }));
200
+ continue;
201
+ }
202
+ const highlight = highlights.find(({ start, end }) => entry.start >= start && entry.end <= end && !empty);
203
+ if (highlight !== void 0 && !NOTE_REFERENCE_KINDS.has(entry.piece.kind)) entry.piece = {
204
+ ...entry.piece,
205
+ signature: withSignatureHighlight(entry.piece.signature, highlight.color)
206
+ };
207
+ positioned.push(entry);
208
+ }
209
+ const segments = [];
210
+ let open;
211
+ const close = () => {
212
+ if (open === void 0) return Result.ok(void 0);
213
+ const replacedText = open.pieces.map(({ text }) => text).join("");
214
+ const first = open.pieces.at(0);
215
+ const { reference } = open;
216
+ if (first === void 0 || replacedText === reference.expectedText) segments.push({
217
+ kind: "reference",
218
+ reference,
219
+ replacedText,
220
+ pieces: open.pieces.map((piece) => ({
221
+ ...piece,
222
+ link: null
223
+ }))
224
+ });
225
+ else if (open.pieces.some(({ signature }) => signature !== first.signature)) return badReference(`Reference span ${reference.start}-${reference.end} in block ${blockId} changes text that is emphasised in part.`);
226
+ else segments.push({
227
+ kind: "reference",
228
+ reference,
229
+ replacedText,
230
+ pieces: [{
231
+ kind: "text",
232
+ text: reference.expectedText,
233
+ signature: first.signature,
234
+ link: null,
235
+ atom: null,
236
+ origin: first.origin
237
+ }]
238
+ });
239
+ open = void 0;
240
+ return Result.ok(void 0);
241
+ };
242
+ for (const { piece, start, end } of positioned) {
243
+ const empty = start === end;
244
+ const reference = ordered.find((candidate) => empty ? start > candidate.start && start < candidate.end : start >= candidate.start && end <= candidate.end);
245
+ if (reference === void 0) {
246
+ const closed = close();
247
+ if (Result.isError(closed)) return closed;
248
+ segments.push({
249
+ kind: "piece",
250
+ piece
251
+ });
252
+ continue;
253
+ }
254
+ if (piece.kind !== "text") return badReference(`Reference span ${reference.start}-${reference.end} in block ${blockId} covers more than text.`);
255
+ if (empty) continue;
256
+ if (open !== void 0 && open.reference !== reference) {
257
+ const closed = close();
258
+ if (Result.isError(closed)) return closed;
259
+ }
260
+ open ??= {
261
+ reference,
262
+ pieces: []
263
+ };
264
+ open.pieces.push(piece);
265
+ }
266
+ const closed = close();
267
+ return Result.isError(closed) ? closed : Result.ok(segments);
268
+ };
269
+ const SEPARATOR_PIECES = {
270
+ lineBreak: {
271
+ kind: "lineBreak",
272
+ text: "\n",
273
+ signature: "",
274
+ link: null,
275
+ atom: null,
276
+ origin: "document"
277
+ },
278
+ space: {
279
+ kind: "text",
280
+ text: " ",
281
+ signature: "",
282
+ link: null,
283
+ atom: null,
284
+ origin: "document"
285
+ },
286
+ none: null
287
+ };
288
+ /** The pieces of a segment list in order, reference results included. */
289
+ const segmentPieces = (segments) => segments.flatMap((segment) => segment.kind === "piece" ? [segment.piece] : segment.pieces);
290
+ /** The expected text and per-unit signatures of a piece list. */
291
+ const piecesContent = (pieces) => {
292
+ const signatures = [];
293
+ let text = "";
294
+ for (const piece of pieces) {
295
+ text += piece.text;
296
+ for (let unit = 0; unit < piece.text.length; unit += 1) signatures.push(piece.signature);
297
+ }
298
+ return {
299
+ text,
300
+ signatures
301
+ };
302
+ };
303
+ const plainPiece = (kind, text) => ({
304
+ kind,
305
+ text,
306
+ signature: "",
307
+ link: null,
308
+ atom: null,
309
+ origin: "document"
310
+ });
311
+ /** A label written as text: the label, then what its list puts after it. */
312
+ const labelPieces = ({ label, suffix }) => {
313
+ const pieces = [plainPiece("text", label)];
314
+ if (suffix === "tab") pieces.push(plainPiece("tab", " "));
315
+ else if (suffix === "space") pieces.push(plainPiece("text", " "));
316
+ return pieces;
317
+ };
318
+ const SHA256 = /^[0-9a-f]{64}$/u;
319
+ const TRANSITIONAL_WORDPROCESSINGML = NAMESPACES.w;
320
+ const groupByBlock = (entries) => {
321
+ const groups = /* @__PURE__ */ new Map();
322
+ for (const entry of entries) {
323
+ const group = groups.get(entry.blockId);
324
+ if (group === void 0) groups.set(entry.blockId, [entry]);
325
+ else group.push(entry);
326
+ }
327
+ return groups;
328
+ };
329
+ /**
330
+ * Check `plan` against the analysed source and template and resolve it.
331
+ * Every refusal the engine documents is decided here, before anything is written.
332
+ */
333
+ const resolvePlan = (source, template, plan) => {
334
+ const invalid = (message) => Result.err(refuse({
335
+ code: "plan-invalid",
336
+ message
337
+ }));
338
+ const unsupported = (message, blockId) => Result.err(refuse({
339
+ code: "unsupported-content",
340
+ message,
341
+ ...blockId === void 0 ? {} : { blockId }
342
+ }));
343
+ const shapeIssue = planShapeIssue(plan);
344
+ if (shapeIssue !== null) return invalid(shapeIssue);
345
+ if (!SHA256.test(plan.sourceSha256) || plan.sourceSha256 !== source.manifest.sha256) return Result.err(refuse({
346
+ code: "sha-mismatch",
347
+ message: "The plan was made for another source document."
348
+ }));
349
+ if (plan.templateSha256 !== template.manifest.sha256) return Result.err(refuse({
350
+ code: "sha-mismatch",
351
+ message: "The plan was made for another template."
352
+ }));
353
+ for (const [name, analyzed] of [["source", source], ["template", template]]) if (analyzed.document.root.namespaceUri !== TRANSITIONAL_WORDPROCESSINGML) return unsupported(`The ${name} is not a Transitional WordprocessingML package.`);
354
+ if (source.manifest.trackedChanges > 0) return Result.err(refuse({
355
+ code: "tracked-changes",
356
+ message: `The source holds ${source.manifest.trackedChanges} tracked change(s); resolve them first.`
357
+ }));
358
+ for (const state of [
359
+ source.story.state,
360
+ source.footnotes.state,
361
+ source.endnotes.state
362
+ ]) if (state.open.length > 0 || state.strayFieldEnds > 0) return unsupported("The source holds complex field marks that do not pair up.");
363
+ const unreadBlock = source.story.unreadBlocks.at(0);
364
+ if (unreadBlock !== void 0) return unsupported(`The source holds block-level ${unreadBlock} content that cannot be moved onto a template.`);
365
+ const references = plan.references ?? [];
366
+ const highlights = plan.highlights ?? [];
367
+ const freezeKinds = plan.fields?.freezeKinds ?? [];
368
+ const patches = plan.numberingPatches ?? [];
369
+ const templateNumbering = template.numbering;
370
+ const usedNumIds = (templateNumbering?.definitions.nums ?? []).map(({ numId }) => numId);
371
+ let nextNumId = maxOf(usedNumIds, 0) + 1;
372
+ const mints = /* @__PURE__ */ new Map();
373
+ const paragraphStyle = (styleId, blockId) => {
374
+ if (styleId === void 0) return Result.ok(null);
375
+ return template.styles.get(styleId)?.type === "paragraph" ? Result.ok(styleId) : Result.err(refuse({
376
+ code: "style-unknown",
377
+ message: `The template has no paragraph style ${styleId}.`,
378
+ blockId
379
+ }));
380
+ };
381
+ const resolveNumbering = ({ numbering, styleId, blockId, ordinal }) => {
382
+ if (numbering === void 0) return Result.ok({ kind: "style" });
383
+ if (numbering === null) return Result.ok({ kind: "none" });
384
+ const unknown = (message) => Result.err(refuse({
385
+ code: "numbering-unknown",
386
+ message,
387
+ blockId
388
+ }));
389
+ const { numId, ilvl, restartFrom, baseNumId, group } = numbering;
390
+ if (templateNumbering === null) return unknown("The template has no numbering definitions.");
391
+ if (!(numId === "new" || restartFrom !== void 0 || group !== void 0)) return computeListRendering({
392
+ numId,
393
+ ilvl
394
+ }, templateNumbering) === null ? unknown(`The template has no list ${numId} with level ${ilvl}.`) : Result.ok({
395
+ kind: "direct",
396
+ numId,
397
+ ilvl
398
+ });
399
+ let base = numId === "new" ? baseNumId : numId;
400
+ if (base === void 0) {
401
+ const bound = styleNumbering(styleId ?? template.defaultStyleId, template.styles, templateNumbering);
402
+ base = bound?.kind === "reference" ? bound.numId : void 0;
403
+ }
404
+ const abstractNumId = base === void 0 ? null : templateNumbering.getAbstractNumId(base);
405
+ const baseLevel = base === void 0 ? null : computeListRendering({
406
+ numId: base,
407
+ ilvl
408
+ }, templateNumbering);
409
+ if (base === void 0 || abstractNumId === null || baseLevel === null) return unknown(`Block ${blockId} starts a list the template does not define.`);
410
+ const key = group === void 0 ? `item:${ordinal}` : `group:${group}`;
411
+ let mint = mints.get(key);
412
+ if (mint === void 0) {
413
+ const patchedStart = patches.find((patch) => patch.abstractNumId === abstractNumId && patch.ilvl === ilvl)?.start;
414
+ mint = {
415
+ key,
416
+ numId: nextNumId,
417
+ baseNumId: base,
418
+ abstractNumId,
419
+ starts: /* @__PURE__ */ new Map([[ilvl, restartFrom ?? patchedStart ?? baseLevel.levelStarts?.at(ilvl) ?? 1]])
420
+ };
421
+ nextNumId += 1;
422
+ mints.set(key, mint);
423
+ return Result.ok({
424
+ kind: "direct",
425
+ numId: mint.numId,
426
+ ilvl
427
+ });
428
+ }
429
+ if (mint.baseNumId !== base) return invalid(`List group ${key} spans two lists.`);
430
+ if (restartFrom !== void 0) {
431
+ const known = mint.starts.get(ilvl);
432
+ if (known !== void 0 && known !== restartFrom) return invalid(`List group ${key} restarts level ${ilvl} from two different numbers.`);
433
+ mint.starts.set(ilvl, restartFrom);
434
+ }
435
+ return Result.ok({
436
+ kind: "direct",
437
+ numId: mint.numId,
438
+ ilvl
439
+ });
440
+ };
441
+ const referencesByBlock = groupByBlock(references);
442
+ const highlightsByBlock = groupByBlock(highlights);
443
+ const byBlockId = /* @__PURE__ */ new Map();
444
+ const placed = /* @__PURE__ */ new Set();
445
+ const place = (block) => {
446
+ const { id } = block.block;
447
+ if (placed.has(id)) return Result.err(refuse({
448
+ code: "block-placed-twice",
449
+ message: `Source block ${id} is placed more than once.`,
450
+ blockId: id
451
+ }));
452
+ placed.add(id);
453
+ return Result.ok(void 0);
454
+ };
455
+ const resolveParagraph = ({ parts, separators, styleId, numbering, placement, ordinal }) => {
456
+ const first = parts.at(0);
457
+ if (first === void 0) return invalid("A plan item names no source block.");
458
+ const firstId = first.block.block.id;
459
+ const style = paragraphStyle(styleId, firstId);
460
+ if (Result.isError(style)) return style;
461
+ const resolvedNumbering = resolveNumbering({
462
+ numbering,
463
+ styleId: style.value,
464
+ blockId: firstId,
465
+ ordinal
466
+ });
467
+ if (Result.isError(resolvedNumbering)) return resolvedNumbering;
468
+ const segments = [];
469
+ const resolvedParts = [];
470
+ for (const [index, planned] of parts.entries()) {
471
+ const { block, stripLabel } = planned;
472
+ const { id, text } = block.block;
473
+ if (block.read === null) return invalid(`Block ${id} is a table and cannot be joined or slotted.`);
474
+ const placedOnce = place(block);
475
+ if (Result.isError(placedOnce)) return placedOnce;
476
+ const unread = block.read.unsupported.at(0);
477
+ if (unread !== void 0) return unsupported(`Block ${id} holds ${unread} content that cannot be moved onto a template.`, id);
478
+ let strippedPrefix = "";
479
+ if (stripLabel !== void 0) {
480
+ const lead = LEADING_SPACE.exec(text)?.[0] ?? "";
481
+ const labelEnd = lead.length + stripLabel.length;
482
+ if (!isManualLabel(stripLabel) || !text.startsWith(stripLabel, lead.length) || !(labelEnd === text.length || LABEL_END.test(text.charAt(labelEnd)))) return Result.err(refuse({
483
+ code: "strip-label-mismatch",
484
+ message: `Block ${id} does not start with the label to strip.`,
485
+ blockId: id
486
+ }));
487
+ strippedPrefix = text.slice(0, labelEnd + (LABEL_SPACE.exec(text.slice(labelEnd))?.[0].length ?? 0));
488
+ }
489
+ const part = partSegments({
490
+ block,
491
+ pieces: paragraphPieces({
492
+ read: block.read,
493
+ context: source,
494
+ origin: "document",
495
+ fields: source.story.state.fields
496
+ }),
497
+ strippedLength: strippedPrefix.length,
498
+ references: referencesByBlock.get(id) ?? [],
499
+ highlights: highlightsByBlock.get(id) ?? []
500
+ });
501
+ if (Result.isError(part)) return part;
502
+ if (index > 0) {
503
+ const separator = SEPARATOR_PIECES[separators[index - 1] ?? "none"];
504
+ if (separator !== null) segments.push({
505
+ kind: "piece",
506
+ piece: separator
507
+ });
508
+ }
509
+ const written = planned.labelAsText ? block.label?.asText ?? null : null;
510
+ if (planned.labelAsText) {
511
+ if (written === null) return Result.err(refuse({
512
+ code: "label-not-writable",
513
+ message: `Block ${id} shows no automatic label that can be written as text.`,
514
+ blockId: id
515
+ }));
516
+ if (stripLabel !== void 0 || index === 0 && resolvedNumbering.value.kind !== "none") return invalid(`Block ${id} takes its label as text and can neither lose a typed label nor join a list.`);
517
+ segments.push(...labelPieces(written).map((piece) => ({
518
+ kind: "piece",
519
+ piece
520
+ })));
521
+ }
522
+ segments.push(...part.value);
523
+ resolvedParts.push({
524
+ block,
525
+ strippedPrefix,
526
+ labelAsText: written?.label ?? null
527
+ });
528
+ }
529
+ const pieces = segmentPieces(segments);
530
+ for (const piece of pieces) {
531
+ const notes = NOTES_OF_REFERENCE[piece.kind];
532
+ if (notes === void 0) continue;
533
+ const noteId = wAttr(piece.atom?.element, "id") ?? "";
534
+ const note = source[notes].byId.get(noteId);
535
+ if (note === void 0) return unsupported(`Block ${firstId} refers to note ${noteId}, which the source does not hold.`, firstId);
536
+ const unread = note.paragraphs.flatMap((read) => read.unsupported).at(0) ?? (note.hasOtherBlocks ? "table" : void 0);
537
+ if (unread !== void 0) return unsupported(`Note ${noteId} holds ${unread} content that cannot be moved onto a template.`, firstId);
538
+ }
539
+ const paragraph = {
540
+ parts: resolvedParts,
541
+ styleId: style.value,
542
+ numbering: resolvedNumbering.value,
543
+ segments,
544
+ ...piecesContent(pieces),
545
+ inlineObjects: pieces.filter(({ kind }) => kind === "object").length,
546
+ placement
547
+ };
548
+ for (const { block } of resolvedParts) byBlockId.set(block.block.id, paragraph);
549
+ return Result.ok(paragraph);
550
+ };
551
+ const sourceTopLevel = (id) => {
552
+ const block = source.story.byId.get(id);
553
+ if (block === void 0 || block.parentId !== null) return Result.err(refuse({
554
+ code: "unknown-block",
555
+ message: block === void 0 ? `The source has no block ${id}.` : `Block ${id} sits in a table and is placed with it.`,
556
+ blockId: id
557
+ }));
558
+ return Result.ok(block);
559
+ };
560
+ const resolveTable = (block, item, tableOrdinal) => {
561
+ const { id } = block.block;
562
+ if (item.mergeNext !== void 0 || item.stripLabel !== void 0 || item.labelAsText !== void 0 || item.numbering !== void 0) return invalid(`Table ${id} takes a style and nested placements only.`);
563
+ if (item.styleId !== void 0 && template.styles.get(item.styleId)?.type !== "table") return Result.err(refuse({
564
+ code: "style-unknown",
565
+ message: `The template has no table style ${item.styleId}.`,
566
+ blockId: id
567
+ }));
568
+ const placedOnce = place(block);
569
+ if (Result.isError(placedOnce)) return placedOnce;
570
+ const overrides = new Map((item.nested ?? []).map((nested) => [nested.blockId, nested]));
571
+ const cells = /* @__PURE__ */ new Map();
572
+ const nestedBlocks = source.story.order.filter((candidate) => candidate.topLevelId === id && candidate !== block);
573
+ for (const nested of nestedBlocks) {
574
+ if (nested.read === null) {
575
+ const placedTable = place(nested);
576
+ if (Result.isError(placedTable)) return placedTable;
577
+ continue;
578
+ }
579
+ const override = overrides.get(nested.block.id);
580
+ overrides.delete(nested.block.id);
581
+ const paragraph = resolveParagraph({
582
+ parts: [{
583
+ block: nested,
584
+ stripLabel: override?.stripLabel,
585
+ labelAsText: override?.labelAsText === true
586
+ }],
587
+ separators: [],
588
+ styleId: override?.styleId ?? item.cellStyleId,
589
+ numbering: override?.numbering,
590
+ placement: "nested",
591
+ ordinal: tableOrdinal * 1e6 + nested.block.index
592
+ });
593
+ if (Result.isError(paragraph)) return paragraph;
594
+ cells.set(nested.element, paragraph.value);
595
+ }
596
+ const stray = [...overrides.keys()].at(0);
597
+ if (stray !== void 0) return Result.err(refuse({
598
+ code: "unknown-block",
599
+ message: `Table ${id} holds no paragraph ${stray}.`,
600
+ blockId: stray
601
+ }));
602
+ return Result.ok({
603
+ kind: "table",
604
+ block,
605
+ styleId: item.styleId ?? null,
606
+ cells
607
+ });
608
+ };
609
+ const items = [];
610
+ const nestedSlots = [];
611
+ const keptTemplateBlocks = [];
612
+ const keptTemplateIds = /* @__PURE__ */ new Set();
613
+ const slottedTemplateIds = /* @__PURE__ */ new Set();
614
+ const pendingNestedSlots = [];
615
+ let ordinal = 0;
616
+ for (let index = 0; index < plan.body.length; index += 1) {
617
+ const item = plan.body[index];
618
+ ordinal += 1;
619
+ if (item === void 0) continue;
620
+ switch (item.kind) {
621
+ case "template":
622
+ for (const id of item.templateBlockIds) {
623
+ const block = template.story.byId.get(id);
624
+ if (block === void 0 || block.parentId !== null) return Result.err(refuse({
625
+ code: "unknown-block",
626
+ message: `The template has no top-level block ${id}.`,
627
+ blockId: id
628
+ }));
629
+ if (keptTemplateIds.has(id) || slottedTemplateIds.has(id)) return Result.err(refuse({
630
+ code: "block-placed-twice",
631
+ message: `Template block ${id} is placed more than once.`,
632
+ blockId: id
633
+ }));
634
+ keptTemplateIds.add(id);
635
+ keptTemplateBlocks.push(block);
636
+ items.push({
637
+ kind: "template",
638
+ block
639
+ });
640
+ }
641
+ break;
642
+ case "source": {
643
+ const block = sourceTopLevel(item.blockId);
644
+ if (Result.isError(block)) return block;
645
+ if (block.value.block.hash !== item.hash) return Result.err(refuse({
646
+ code: "hash-mismatch",
647
+ message: `Block ${item.blockId} does not have the hash the plan pins.`,
648
+ blockId: item.blockId
649
+ }));
650
+ if (block.value.read === null) {
651
+ const table = resolveTable(block.value, item, ordinal);
652
+ if (Result.isError(table)) return table;
653
+ items.push(table.value);
654
+ break;
655
+ }
656
+ const parts = [{
657
+ block: block.value,
658
+ stripLabel: item.stripLabel,
659
+ labelAsText: item.labelAsText === true
660
+ }];
661
+ const separators = [];
662
+ let merge = item.mergeNext;
663
+ while (merge !== void 0) {
664
+ const next = plan.body[index + 1];
665
+ const nextBlock = next?.kind === "source" ? sourceTopLevel(next.blockId) : void 0;
666
+ if (next?.kind !== "source" || nextBlock === void 0 || Result.isError(nextBlock) || nextBlock.value.read === null) return Result.err(refuse({
667
+ code: "merge-invalid",
668
+ message: `Block ${item.blockId} can only join a source paragraph placed right after it.`,
669
+ blockId: item.blockId
670
+ }));
671
+ if (nextBlock.value.block.hash !== next.hash) return Result.err(refuse({
672
+ code: "hash-mismatch",
673
+ message: `Block ${next.blockId} does not have the hash the plan pins.`,
674
+ blockId: next.blockId
675
+ }));
676
+ if (next.styleId !== void 0 || next.numbering !== void 0 || next.cellStyleId !== void 0 || next.nested !== void 0) return Result.err(refuse({
677
+ code: "merge-invalid",
678
+ message: `Block ${next.blockId} joins the paragraph before it and cannot carry a style or list of its own.`,
679
+ blockId: next.blockId
680
+ }));
681
+ separators.push(merge);
682
+ parts.push({
683
+ block: nextBlock.value,
684
+ stripLabel: next.stripLabel,
685
+ labelAsText: next.labelAsText === true
686
+ });
687
+ merge = next.mergeNext;
688
+ index += 1;
689
+ }
690
+ const paragraph = resolveParagraph({
691
+ parts,
692
+ separators,
693
+ styleId: item.styleId,
694
+ numbering: item.numbering,
695
+ placement: "body",
696
+ ordinal
697
+ });
698
+ if (Result.isError(paragraph)) return paragraph;
699
+ items.push({
700
+ kind: "paragraph",
701
+ paragraph: paragraph.value
702
+ });
703
+ break;
704
+ }
705
+ case "slot": {
706
+ const templateBlock = template.story.byId.get(item.templateBlockId);
707
+ if (templateBlock === void 0 || templateBlock.read === null || !Array.isArray(item.sourceBlockIds)) return Result.err(refuse({
708
+ code: "unknown-block",
709
+ message: `The template has no paragraph ${item.templateBlockId} to fill.`,
710
+ blockId: item.templateBlockId
711
+ }));
712
+ if (keptTemplateIds.has(item.templateBlockId) || slottedTemplateIds.has(item.templateBlockId)) return Result.err(refuse({
713
+ code: "block-placed-twice",
714
+ message: `Template block ${item.templateBlockId} is placed more than once.`,
715
+ blockId: item.templateBlockId
716
+ }));
717
+ slottedTemplateIds.add(item.templateBlockId);
718
+ const parts = [];
719
+ for (const id of item.sourceBlockIds) {
720
+ const block = sourceTopLevel(id);
721
+ if (Result.isError(block)) return block;
722
+ parts.push({
723
+ block: block.value,
724
+ stripLabel: void 0,
725
+ labelAsText: false
726
+ });
727
+ }
728
+ const paragraph = resolveParagraph({
729
+ parts,
730
+ separators: parts.slice(1).map(() => "lineBreak"),
731
+ styleId: void 0,
732
+ numbering: void 0,
733
+ placement: "slot",
734
+ ordinal
735
+ });
736
+ if (Result.isError(paragraph)) return paragraph;
737
+ const slot = {
738
+ templateBlock,
739
+ paragraph: paragraph.value
740
+ };
741
+ if (templateBlock.parentId === null) items.push({
742
+ kind: "slot",
743
+ ...slot
744
+ });
745
+ else pendingNestedSlots.push(slot);
746
+ break;
747
+ }
748
+ default: return invalid(`Body item ${index} has an unknown kind.`);
749
+ }
750
+ }
751
+ for (const slot of pendingNestedSlots) {
752
+ if (!keptTemplateIds.has(slot.templateBlock.topLevelId)) return Result.err(refuse({
753
+ code: "unknown-block",
754
+ message: `Slot ${slot.templateBlock.block.id} sits in a template table the plan does not keep.`,
755
+ blockId: slot.templateBlock.block.id
756
+ }));
757
+ nestedSlots.push(slot);
758
+ }
759
+ const keptPosition = /* @__PURE__ */ new Map();
760
+ for (const [position, item] of items.entries()) if (item.kind === "template") keptPosition.set(item.block.block.id, position);
761
+ const templateOrder = template.story.topLevel.map(({ block }) => block.id);
762
+ const slots = [...nestedSlots, ...items.flatMap((item) => item.kind === "slot" ? [item] : [])];
763
+ for (const field of template.story.state.fields) {
764
+ const lastOrdinal = field.closed ? field.endParagraphOrdinal : Number.POSITIVE_INFINITY;
765
+ if (lastOrdinal === field.paragraphOrdinal) continue;
766
+ const slotted = slots.find(({ templateBlock }) => {
767
+ const slotOrdinal = templateBlock.read?.ordinal ?? -1;
768
+ return slotOrdinal >= field.paragraphOrdinal && slotOrdinal <= lastOrdinal;
769
+ });
770
+ if (slotted !== void 0) return Result.err(refuse({
771
+ code: "plan-invalid",
772
+ message: `Slot ${slotted.templateBlock.block.id} lies inside a ${field.kind} field that runs over several paragraphs.`,
773
+ blockId: slotted.templateBlock.block.id
774
+ }));
775
+ const from = templateOrder.indexOf(template.story.paragraphs[field.paragraphOrdinal]?.topLevelId ?? "");
776
+ const to = field.closed ? templateOrder.indexOf(template.story.paragraphs[field.endParagraphOrdinal]?.topLevelId ?? "") : templateOrder.length - 1;
777
+ if (from === -1 || to <= from) continue;
778
+ const span = templateOrder.slice(from, to + 1);
779
+ if (!span.some((id) => keptPosition.has(id))) continue;
780
+ const first = keptPosition.get(span.at(0) ?? "");
781
+ if (first === void 0 || span.some((id, offset) => keptPosition.get(id) !== first + offset)) return Result.err(refuse({
782
+ code: "plan-invalid",
783
+ message: `Template blocks ${span.at(0) ?? ""} to ${span.at(-1) ?? ""} hold one ${field.kind} field; keep all of them together and in order, or none.`,
784
+ blockId: span.at(0) ?? ""
785
+ }));
786
+ }
787
+ const omitted = /* @__PURE__ */ new Map();
788
+ for (const entry of plan.omit) {
789
+ const block = sourceTopLevel(entry.blockId);
790
+ if (Result.isError(block)) return block;
791
+ if (placed.has(entry.blockId) || omitted.has(entry.blockId)) return Result.err(refuse({
792
+ code: "block-placed-twice",
793
+ message: `Block ${entry.blockId} is both placed and omitted, or omitted twice.`,
794
+ blockId: entry.blockId
795
+ }));
796
+ if (entry.reason === "empty" && !isBlankBlock(block.value)) return invalid(`Block ${entry.blockId} is omitted as empty and is not.`);
797
+ omitted.set(entry.blockId, entry.reason);
798
+ }
799
+ for (const block of source.story.topLevel) {
800
+ const { id } = block.block;
801
+ if (placed.has(id) || omitted.has(id)) continue;
802
+ if (!isBlankBlock(block) || showsLabel(block)) return Result.err(refuse({
803
+ code: "block-unplaced",
804
+ message: `Source block ${id} is neither placed nor omitted.`,
805
+ blockId: id
806
+ }));
807
+ omitted.set(id, "empty");
808
+ }
809
+ for (const [blockId] of [...referencesByBlock, ...highlightsByBlock]) if (!byBlockId.has(blockId)) return Result.err(refuse({
810
+ code: referencesByBlock.has(blockId) ? "reference-span-invalid" : "highlight-span-invalid",
811
+ message: `Block ${blockId} is not placed, so nothing can be marked in it.`,
812
+ blockId
813
+ }));
814
+ const takenNames = /* @__PURE__ */ new Set();
815
+ const takenIds = bookmarkIdsOf(template.document.root);
816
+ walkElements(template.document.root, (element) => {
817
+ if (isW(element, "bookmarkStart")) takenNames.add(wAttr(element, "name") ?? "");
818
+ });
819
+ let nextBookmarkId = maxOf(takenIds, 0) + 1;
820
+ const bookmarks = /* @__PURE__ */ new Map();
821
+ const resolvedReferences = [];
822
+ for (const reference of references) {
823
+ const paragraph = byBlockId.get(reference.blockId);
824
+ const target = byBlockId.get(reference.targetBlockId);
825
+ if (paragraph === void 0) return invalid(`Block ${reference.blockId} is not placed.`);
826
+ if (target === void 0) return Result.err(refuse({
827
+ code: "reference-target-unplaced",
828
+ message: `Reference target ${reference.targetBlockId} is not a placed paragraph.`,
829
+ blockId: reference.blockId
830
+ }));
831
+ if (paragraph === target) return Result.err(refuse({
832
+ code: "reference-span-invalid",
833
+ message: `A reference in ${reference.blockId} targets the paragraph it sits in.`,
834
+ blockId: reference.blockId
835
+ }));
836
+ let bookmark = bookmarks.get(target);
837
+ if (bookmark === void 0) {
838
+ bookmark = {
839
+ id: nextBookmarkId,
840
+ name: mintRefBookmarkName(`${source.manifest.sha256}:${target.parts.at(0)?.block.block.id ?? ""}`, takenNames)
841
+ };
842
+ nextBookmarkId += 1;
843
+ bookmarks.set(target, bookmark);
844
+ }
845
+ const instruction = refFieldInstruction(bookmark.name, reference.instruction);
846
+ if (instruction === null) return invalid(`A reference in ${reference.blockId} carries more than field switches.`);
847
+ const segment = paragraph.segments.find((candidate) => candidate.kind === "reference" && candidate.reference === reference);
848
+ resolvedReferences.push({
849
+ reference,
850
+ paragraph,
851
+ target,
852
+ replacedText: segment?.kind === "reference" ? segment.replacedText : "",
853
+ instruction
854
+ });
855
+ }
856
+ for (const patch of patches) {
857
+ const abstract = templateNumbering?.getAbstract(patch.abstractNumId);
858
+ if (abstract === null || abstract === void 0 || !abstract.levels.some(({ ilvl }) => ilvl === patch.ilvl)) return Result.err(refuse({
859
+ code: "numbering-unknown",
860
+ message: `The template has no level ${patch.ilvl} in list definition ${patch.abstractNumId}.`
861
+ }));
862
+ }
863
+ return Result.ok({
864
+ items,
865
+ nestedSlots,
866
+ byBlockId,
867
+ omitted,
868
+ mints: [...mints.values()],
869
+ bookmarks,
870
+ references: resolvedReferences,
871
+ freezeKinds: new Set(freezeKinds),
872
+ keptTemplateBlocks
873
+ });
874
+ };
875
+ export { hyperlinkFieldLink, isBlankBlock, isManualLabel, paragraphPieces, piecesContent, resolvePlan, segmentPieces };