@stll/folio-core 0.71.1 → 0.73.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 (213) hide show
  1. package/README.md +14 -8
  2. package/dist/ai-edits/apply.d.ts +6 -114
  3. package/dist/ai-edits/apply.js +9 -131
  4. package/dist/ai-edits/applyTypes.d.ts +85 -0
  5. package/dist/ai-edits/applyTypes.js +24 -0
  6. package/dist/ai-edits/clean-text.d.ts +7 -1
  7. package/dist/ai-edits/clean-text.js +23 -2
  8. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  9. package/dist/ai-edits/headless.d.ts +29 -147
  10. package/dist/ai-edits/headless.js +213 -1634
  11. package/dist/ai-edits/index.d.ts +3 -3
  12. package/dist/ai-edits/index.js +2 -3
  13. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  14. package/dist/ai-edits/pending-suggestions.js +183 -90
  15. package/dist/ai-edits/result-validation.js +1 -1
  16. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  17. package/dist/ai-edits/snapshot.js +8 -3
  18. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  19. package/dist/ai-edits/table-cell-mutations.js +1 -1
  20. package/dist/ai-edits/table-geometry.d.ts +1 -1
  21. package/dist/ai-edits/table-geometry.js +1 -1
  22. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  23. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  24. package/dist/ai-edits/tableNodes.d.ts +38 -0
  25. package/dist/ai-edits/tableNodes.js +86 -0
  26. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  27. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  28. package/dist/canonical/batchCommentReferences.js +1 -0
  29. package/dist/canonical/canonicalInlineProjection.js +1 -1
  30. package/dist/canonical/canonicalPublicOperations.js +228 -64
  31. package/dist/canonical/canonicalSession.d.ts +9 -1
  32. package/dist/canonical/canonicalSession.js +95 -15
  33. package/dist/compare/compare.d.ts +1 -1
  34. package/dist/compare/inline-atoms-model.d.ts +1 -1
  35. package/dist/compare/inline-atoms.d.ts +2 -2
  36. package/dist/compare/inline-provenance-model.d.ts +1 -1
  37. package/dist/compare/inline-provenance.d.ts +2 -2
  38. package/dist/compat/eigenpal.d.ts +3 -4
  39. package/dist/compat/eigenpal.js +2 -4
  40. package/dist/controller/canonicalClipboard.d.ts +13 -3
  41. package/dist/controller/canonicalClipboard.js +185 -49
  42. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  43. package/dist/controller/canonicalClipboardResources.js +22 -2
  44. package/dist/controller/canonicalReview.d.ts +1 -1
  45. package/dist/controller/canonicalReview.js +1 -1
  46. package/dist/controller/canonicalStructure.js +1 -1
  47. package/dist/controller/canonicalWatermark.d.ts +10 -0
  48. package/dist/controller/canonicalWatermark.js +37 -0
  49. package/dist/controller/canonicalYjsRoom.d.ts +1 -1
  50. package/dist/controller/headerFooterEditorManager.d.ts +11 -7
  51. package/dist/controller/headerFooterEditorManager.js +39 -151
  52. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  53. package/dist/controller/hiddenEditorManager.d.ts +6 -40
  54. package/dist/controller/hiddenEditorManager.js +173 -306
  55. package/dist/controller/noteEditorManager.d.ts +3 -10
  56. package/dist/controller/noteEditorManager.js +33 -206
  57. package/dist/document-operations-apply.d.ts +15 -0
  58. package/dist/document-operations-apply.js +280 -0
  59. package/dist/document-operations.d.ts +1 -14
  60. package/dist/document-operations.js +2 -279
  61. package/dist/docx/modelValidation.js +1 -1
  62. package/dist/docx/paragraphParser.js +2 -2
  63. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  64. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  65. package/dist/docx/reviewResolutionProvenance.js +32 -9
  66. package/dist/docx/revisionIdNormalization.js +30 -7
  67. package/dist/docx/rezip.js +1 -1
  68. package/dist/docx/serializer/borderSerializer.js +1 -1
  69. package/dist/docx/serializer/commentSerializer.js +1 -1
  70. package/dist/docx/serializer/documentSerializer.js +1 -1
  71. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  72. package/dist/docx/serializer/runSerializer.js +1 -1
  73. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  74. package/dist/docx/serializer/tableSerializer.js +5 -37
  75. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  76. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  77. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  78. package/dist/docx/server/templatePlan/apply.js +600 -0
  79. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  80. package/dist/docx/server/templatePlan/blocks.js +355 -0
  81. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  82. package/dist/docx/server/templatePlan/builders.js +237 -0
  83. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  84. package/dist/docx/server/templatePlan/emit.js +466 -0
  85. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  86. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  87. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  88. package/dist/docx/server/templatePlan/inspect.js +177 -0
  89. package/dist/docx/server/templatePlan/labels.d.ts +36 -0
  90. package/dist/docx/server/templatePlan/labels.js +126 -0
  91. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  92. package/dist/docx/server/templatePlan/package.js +99 -0
  93. package/dist/docx/server/templatePlan/plan.d.ts +143 -0
  94. package/dist/docx/server/templatePlan/plan.js +841 -0
  95. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  96. package/dist/docx/server/templatePlan/planShape.js +161 -0
  97. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  98. package/dist/docx/server/templatePlan/resources.js +136 -0
  99. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  100. package/dist/docx/server/templatePlan/story.js +440 -0
  101. package/dist/docx/server/templatePlan/types.d.ts +406 -0
  102. package/dist/docx/server/templatePlan/types.js +28 -0
  103. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  104. package/dist/docx/server/templatePlan/verify.js +968 -0
  105. package/dist/docx/server/templatePlan/xml.d.ts +69 -0
  106. package/dist/docx/server/templatePlan/xml.js +119 -0
  107. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  108. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  109. package/dist/docx/storyBlockReplay.js +1 -1
  110. package/dist/docx/structuralXmlPatch.js +9 -1
  111. package/dist/docx/tableGridXml.d.ts +30 -0
  112. package/dist/docx/tableGridXml.js +54 -0
  113. package/dist/docx/tableParser.js +7 -0
  114. package/dist/docx/xmlParser.js +1 -1
  115. package/dist/index.d.ts +3 -4
  116. package/dist/index.js +2 -4
  117. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  118. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  119. package/dist/managers/ContextMenuManager.js +2 -1
  120. package/dist/managers/DocumentLoaderManager.d.ts +0 -4
  121. package/dist/managers/DocumentLoaderManager.js +4 -12
  122. package/dist/managers/editorShortcuts.d.ts +1 -1
  123. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  124. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  125. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  126. package/dist/prosemirror/canonicalTableCommands.js +2 -2
  127. package/dist/prosemirror/commands/comments.js +3 -3
  128. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  129. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  130. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  131. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  132. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  133. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  134. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  135. package/dist/prosemirror/commentRecords.d.ts +1 -1
  136. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  137. package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
  138. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  139. package/dist/prosemirror/documentStructureCounts.js +76 -0
  140. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  141. package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
  142. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
  143. package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
  144. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  145. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  146. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  147. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  148. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
  149. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
  150. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
  151. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
  152. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  153. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  154. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  155. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  156. package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
  157. package/dist/prosemirror/extensions/types.d.ts +1 -1
  158. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  159. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  160. package/dist/prosemirror/index.d.ts +1 -1
  161. package/dist/prosemirror/index.js +1 -1
  162. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  163. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  164. package/dist/prosemirror/listNumbering.d.ts +1 -1
  165. package/dist/prosemirror/lockedControls.d.ts +1 -1
  166. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  167. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  168. package/dist/prosemirror/noteReferenceReview.js +1 -1
  169. package/dist/prosemirror/numberingAttr.d.ts +1 -2
  170. package/dist/prosemirror/numberingAttr.js +1 -2
  171. package/dist/prosemirror/outlineLevelAttr.d.ts +1 -2
  172. package/dist/prosemirror/outlineLevelAttr.js +1 -2
  173. package/dist/prosemirror/paraIds.d.ts +46 -0
  174. package/dist/prosemirror/paraIds.js +152 -0
  175. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  176. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  177. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  178. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  179. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  180. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  181. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  182. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  183. package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
  184. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  185. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  186. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  187. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  188. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  189. package/dist/prosemirror/replacedAnnotations.js +16 -1
  190. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  191. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  192. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  193. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  194. package/dist/prosemirror/selectionBounds.js +22 -0
  195. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  196. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  197. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  198. package/dist/prosemirror/textInput.d.ts +1 -1
  199. package/dist/server.d.ts +7 -5
  200. package/dist/server.js +6 -4
  201. package/dist/types/canonicalCapabilities.d.ts +8 -41
  202. package/dist/types/canonicalCapabilities.js +6 -34
  203. package/package.json +4 -6
  204. package/dist/controller/collaborationModules.d.ts +0 -3
  205. package/dist/controller/collaborationModules.js +0 -14
  206. package/dist/docx/server/materializeYjsDocx.d.ts +0 -30
  207. package/dist/docx/server/materializeYjsDocx.js +0 -96
  208. package/dist/docx/server/migrateYjsAttrSchema.d.ts +0 -53
  209. package/dist/docx/server/migrateYjsAttrSchema.js +0 -111
  210. package/dist/prosemirror/plugins/derivedFields.d.ts +0 -8
  211. package/dist/prosemirror/plugins/derivedFields.js +0 -52
  212. package/dist/prosemirror/yjsDocumentMetadata.d.ts +0 -89
  213. package/dist/prosemirror/yjsDocumentMetadata.js +0 -697
@@ -0,0 +1,9 @@
1
+ export declare const OMIT_REASONS: ReadonlySet<string>;
2
+ export declare const PLAN_HIGHLIGHT_COLORS: ReadonlySet<string>;
3
+ /**
4
+ * Whether `text` is plain text a `w:t` holds as written: no control
5
+ * characters, no tab or line end, and no half of a surrogate pair.
6
+ */
7
+ export declare const isPlainText: (text: string) => boolean;
8
+ /** Why `plan` is not a version 1 template plan, or null when it is one. */
9
+ export declare const planShapeIssue: (plan: unknown) => string | null;
@@ -0,0 +1,161 @@
1
+ import { HIGHLIGHT_COLOR_VALUES, NUMBER_FORMAT_VALUES } from "../../../types/documentEnumValues.js";
2
+ // src/docx/server/templatePlan/planShape.ts
3
+ /**
4
+ * The shape of a template plan as it arrives: parsed JSON nobody has typed
5
+ * yet. Everything the resolver later reads off a plan is checked here, so a
6
+ * malformed plan is a `plan-invalid` refusal and never an exception.
7
+ */
8
+ const OMIT_REASONS = /* @__PURE__ */ new Set([
9
+ "empty",
10
+ "sourceToc",
11
+ "pageArtifact",
12
+ "duplicateLabel"
13
+ ]);
14
+ const MERGES = /* @__PURE__ */ new Set([
15
+ "lineBreak",
16
+ "space",
17
+ "none"
18
+ ]);
19
+ const SUFFIXES = /* @__PURE__ */ new Set([
20
+ "tab",
21
+ "space",
22
+ "nothing"
23
+ ]);
24
+ const NUMBER_FORMATS = new Set(NUMBER_FORMAT_VALUES);
25
+ /** The highlight a plan may add; clearing one is not a mark. */
26
+ const CLEARED_HIGHLIGHT = "none";
27
+ const PLAN_HIGHLIGHT_COLORS = new Set(HIGHLIGHT_COLOR_VALUES.filter((color) => color !== CLEARED_HIGHLIGHT));
28
+ const FIELD_KIND = /^[A-Z][A-Z0-9]*$/u;
29
+ const MAX_LIST_LEVEL = 8;
30
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ const isString = (value) => typeof value === "string";
32
+ const isOptionalString = (value) => value === void 0 || isString(value);
33
+ const isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
34
+ /** A list id a plan may name: the first real one is 1. */
35
+ const isListId = (value) => isCount(value) && value >= 1;
36
+ const isLevel = (value) => isCount(value) && value <= MAX_LIST_LEVEL;
37
+ /**
38
+ * Whether `text` is plain text a `w:t` holds as written: no control
39
+ * characters, no tab or line end, and no half of a surrogate pair.
40
+ */
41
+ const isPlainText = (text) => {
42
+ for (let index = 0; index < text.length; index += 1) {
43
+ const unit = text.charCodeAt(index);
44
+ if (unit < 32 || unit === 127 || unit === 65534 || unit === 65535) return false;
45
+ const high = unit >= 55296 && unit <= 56319;
46
+ const low = unit >= 56320 && unit <= 57343;
47
+ if (high) {
48
+ const next = text.charCodeAt(index + 1);
49
+ if (!(next >= 56320 && next <= 57343)) return false;
50
+ index += 1;
51
+ } else if (low) return false;
52
+ }
53
+ return true;
54
+ };
55
+ const numberingIssue = (value, where) => {
56
+ if (value === void 0 || value === null) return null;
57
+ if (!isObject(value)) return `${where} names a malformed list.`;
58
+ const { numId, ilvl, restartFrom, baseNumId, group } = value;
59
+ if (numId !== "new" && !isListId(numId)) return `${where} names a list that is neither an id nor "new".`;
60
+ if (!isLevel(ilvl)) return `${where} names a list level outside 0 to ${MAX_LIST_LEVEL}.`;
61
+ if (restartFrom !== void 0 && !isCount(restartFrom)) return `${where} restarts a list from a value that is not a count.`;
62
+ if (baseNumId !== void 0 && !isListId(baseNumId)) return `${where} bases a list on a malformed id.`;
63
+ if (group !== void 0 && !(isString(group) && group !== "")) return `${where} names a malformed list group.`;
64
+ return null;
65
+ };
66
+ const sourceItemIssue = (item, where) => {
67
+ if (!isString(item["blockId"]) || !isString(item["hash"])) return `${where} names no source block and hash.`;
68
+ for (const key of [
69
+ "styleId",
70
+ "cellStyleId",
71
+ "stripLabel"
72
+ ]) if (!isOptionalString(item[key])) return `${where} carries a malformed ${key}.`;
73
+ const merge = item["mergeNext"];
74
+ if (merge !== void 0 && !(isString(merge) && MERGES.has(merge))) return `${where} names an unknown merge.`;
75
+ const numbering = numberingIssue(item["numbering"], where);
76
+ if (numbering !== null) return numbering;
77
+ const nested = item["nested"];
78
+ if (nested === void 0) return null;
79
+ if (!Array.isArray(nested)) return `${where} carries malformed nested placements.`;
80
+ const seen = /* @__PURE__ */ new Set();
81
+ for (const entry of nested) {
82
+ if (!isObject(entry) || !isString(entry["blockId"])) return `${where} carries a nested placement without a block.`;
83
+ if (seen.has(entry["blockId"])) return `${where} places nested block ${entry["blockId"]} twice.`;
84
+ seen.add(entry["blockId"]);
85
+ if (!isOptionalString(entry["styleId"]) || !isOptionalString(entry["stripLabel"])) return `${where} carries a malformed nested placement.`;
86
+ const nestedNumbering = numberingIssue(entry["numbering"], where);
87
+ if (nestedNumbering !== null) return nestedNumbering;
88
+ }
89
+ return null;
90
+ };
91
+ const bodyIssue = (body) => {
92
+ if (!Array.isArray(body)) return "The plan has no body.";
93
+ for (const [index, item] of body.entries()) {
94
+ const where = `Body item ${index}`;
95
+ if (!isObject(item)) return `${where} is malformed.`;
96
+ switch (item["kind"]) {
97
+ case "template":
98
+ if (!Array.isArray(item["templateBlockIds"]) || !item["templateBlockIds"].every(isString)) return `${where} names no template blocks.`;
99
+ break;
100
+ case "source": {
101
+ const issue = sourceItemIssue(item, where);
102
+ if (issue !== null) return issue;
103
+ break;
104
+ }
105
+ case "slot":
106
+ if (!isString(item["templateBlockId"]) || !Array.isArray(item["sourceBlockIds"]) || item["sourceBlockIds"].length === 0 || !item["sourceBlockIds"].every(isString)) return `${where} is a slot without a template paragraph or source blocks.`;
107
+ break;
108
+ default: return `${where} has an unknown kind.`;
109
+ }
110
+ }
111
+ return null;
112
+ };
113
+ const omitIssue = (omit) => {
114
+ if (!Array.isArray(omit)) return "The plan has no omit list.";
115
+ for (const entry of omit) if (!isObject(entry) || !isString(entry["blockId"]) || !isString(entry["reason"]) || !OMIT_REASONS.has(entry["reason"])) return "The plan omits a block without an id or for an unknown reason.";
116
+ return null;
117
+ };
118
+ const patchesIssue = (patches) => {
119
+ if (patches === void 0) return null;
120
+ if (!Array.isArray(patches)) return "The plan's numbering patches are malformed.";
121
+ const seen = /* @__PURE__ */ new Set();
122
+ for (const patch of patches) {
123
+ if (!isObject(patch) || !isCount(patch["abstractNumId"]) || !isLevel(patch["ilvl"])) return "A numbering patch names no list definition and level.";
124
+ const key = `${String(patch["abstractNumId"])}:${String(patch["ilvl"])}`;
125
+ if (seen.has(key)) return `Two numbering patches change level ${String(patch["ilvl"])} of list definition ${String(patch["abstractNumId"])}.`;
126
+ seen.add(key);
127
+ const { numFmt, lvlText, start, suff } = patch;
128
+ if (numFmt !== void 0 && !(isString(numFmt) && NUMBER_FORMATS.has(numFmt)) || lvlText !== void 0 && !(isString(lvlText) && isPlainText(lvlText)) || start !== void 0 && !isCount(start) || suff !== void 0 && !(isString(suff) && SUFFIXES.has(suff))) return "A numbering patch carries a malformed value.";
129
+ }
130
+ return null;
131
+ };
132
+ const spansIssue = (plan) => {
133
+ const { references, highlights } = plan;
134
+ if (references !== void 0) {
135
+ if (!Array.isArray(references)) return "The plan's references are malformed.";
136
+ for (const reference of references) {
137
+ if (!isObject(reference) || !isString(reference["blockId"]) || !isString(reference["targetBlockId"]) || !isCount(reference["start"]) || !isCount(reference["end"]) || !isString(reference["instruction"])) return "A reference is malformed.";
138
+ const expected = reference["expectedText"];
139
+ if (!isString(expected) || expected === "" || !isPlainText(expected)) return `A reference in ${reference["blockId"]} has no plain cached text.`;
140
+ }
141
+ }
142
+ if (highlights !== void 0) {
143
+ if (!Array.isArray(highlights)) return "The plan's highlights are malformed.";
144
+ for (const highlight of highlights) if (!isObject(highlight) || !isString(highlight["blockId"]) || !isCount(highlight["start"]) || !isCount(highlight["end"]) || !isString(highlight["color"]) || !isOptionalString(highlight["note"])) return "A highlight is malformed.";
145
+ }
146
+ return null;
147
+ };
148
+ const fieldsIssue = (fields) => {
149
+ if (fields === void 0) return null;
150
+ if (!isObject(fields)) return "The plan's field choices are malformed.";
151
+ const { freezeKinds, updateOnOpen } = fields;
152
+ if (freezeKinds !== void 0 && !(Array.isArray(freezeKinds) && freezeKinds.every((kind) => isString(kind) && FIELD_KIND.test(kind)))) return "The plan freezes field kinds that are not field names.";
153
+ if (updateOnOpen !== void 0 && typeof updateOnOpen !== "boolean") return "The plan's update-on-open choice is not a boolean.";
154
+ return null;
155
+ };
156
+ /** Why `plan` is not a version 1 template plan, or null when it is one. */
157
+ const planShapeIssue = (plan) => {
158
+ if (!isObject(plan) || plan["version"] !== 1 || !isString(plan["sourceSha256"]) || !isString(plan["templateSha256"])) return "The plan is not a version 1 template plan.";
159
+ return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]);
160
+ };
161
+ export { OMIT_REASONS, PLAN_HIGHLIGHT_COLORS, isPlainText, planShapeIssue };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What the stories of a package point at outside their own markup: the
3
+ * relationships of the main document and of the note parts, the media those
4
+ * name, and a fingerprint for an object that travels whole.
5
+ */
6
+ import { document_d_exports } from "../../../types/document.js";
7
+ import { XmlElement } from "../../xmlParser.js";
8
+ import { AnalyzedDocument } from "./blocks.js";
9
+ import { TemplatePlanError } from "./types.js";
10
+ import { Result } from "better-result";
11
+ /** The part a piece of content was read from. */
12
+ export type StoryOrigin = "document" | "footnotes" | "endnotes";
13
+ export declare const STORY_ORIGINS: readonly StoryOrigin[];
14
+ export type StoryResources = {
15
+ relationships: Record<StoryOrigin, document_d_exports.RelationshipMap>;
16
+ /**
17
+ * The package path a relationship of `origin` targets. A target that is
18
+ * percent-encoded or spelled in another case than its entry still resolves.
19
+ */
20
+ resolveTarget: (origin: StoryOrigin, target: string) => string;
21
+ /** SHA-256 of every picture the stories embed, by package path. */
22
+ mediaDigests: ReadonlyMap<string, string>;
23
+ /** The bytes of those pictures, by package path. */
24
+ media: ReadonlyMap<string, Uint8Array>;
25
+ };
26
+ /** Read the relationships and embedded pictures of a package's stories. */
27
+ export declare const readStoryResources: (analyzed: AnalyzedDocument) => Promise<Result<StoryResources, TemplatePlanError>>;
28
+ /** The relationship ids an element and its descendants name, in document order. */
29
+ export declare const relationshipIdsOf: (element: XmlElement) => string[];
30
+ /**
31
+ * A digest of an object's markup that stays the same when the object moves
32
+ * to another package: relationship ids, the drawing id and namespace
33
+ * declarations are left out, everything else counts.
34
+ */
35
+ export declare const objectFingerprint: (element: XmlElement) => string;
36
+ /**
37
+ * What an object's relationships lead to, as strings two packages can be
38
+ * compared by: a picture by the digest of its bytes, an external target by
39
+ * its address.
40
+ */
41
+ export declare const objectTargets: (element: XmlElement, origin: StoryOrigin, resources: StoryResources) => string[];
@@ -0,0 +1,136 @@
1
+ import { RELATIONSHIP_TYPES, parseRelationships, resolveRelativePath } from "../../relsParser.js";
2
+ import { OFFICE_RELATIONSHIP_NAMESPACE_URIS, getLocalName } from "../../xmlParser.js";
3
+ import { readPartText, relationshipsPathFor, sha256Hex } from "./package.js";
4
+ import { TemplatePlanError } from "./types.js";
5
+ import { Result } from "better-result";
6
+ import { resolveNamespaceUri } from "@stll/docx-core/xml/namespaces";
7
+ // src/docx/server/templatePlan/resources.ts
8
+ /**
9
+ * What the stories of a package point at outside their own markup: the
10
+ * relationships of the main document and of the note parts, the media those
11
+ * name, and a fingerprint for an object that travels whole.
12
+ */
13
+ const STORY_ORIGINS = [
14
+ "document",
15
+ "footnotes",
16
+ "endnotes"
17
+ ];
18
+ const percentDecoded = (path) => {
19
+ const decoded = Result.try({
20
+ try: () => decodeURIComponent(path),
21
+ catch: () => null
22
+ });
23
+ return Result.isError(decoded) ? path : decoded.value;
24
+ };
25
+ /** Read the relationships and embedded pictures of a package's stories. */
26
+ const readStoryResources = async (analyzed) => {
27
+ const { pkg } = analyzed;
28
+ const partPath = {
29
+ document: pkg.documentPath,
30
+ footnotes: analyzed.footnotes.path,
31
+ endnotes: analyzed.endnotes.path
32
+ };
33
+ const relationships = {
34
+ document: pkg.documentRelationships,
35
+ footnotes: /* @__PURE__ */ new Map(),
36
+ endnotes: /* @__PURE__ */ new Map()
37
+ };
38
+ for (const origin of ["footnotes", "endnotes"]) {
39
+ const path = partPath[origin];
40
+ const relationshipsPath = path === null ? null : relationshipsPathFor(path);
41
+ if (relationshipsPath === null || !pkg.paths.has(relationshipsPath)) continue;
42
+ const xml = await readPartText(pkg, relationshipsPath);
43
+ if (Result.isError(xml)) return xml;
44
+ relationships[origin] = parseRelationships(xml.value ?? "");
45
+ }
46
+ const byLowerCase = new Map([...pkg.paths].map((path) => [path.toLowerCase(), path]));
47
+ const resolveTarget = (origin, target) => {
48
+ const exact = resolveRelativePath(relationshipsPathFor(partPath[origin] ?? pkg.documentPath), target);
49
+ if (pkg.paths.has(exact)) return exact;
50
+ const decoded = percentDecoded(exact);
51
+ return byLowerCase.get(decoded.toLowerCase()) ?? byLowerCase.get(exact.toLowerCase()) ?? exact;
52
+ };
53
+ const media = /* @__PURE__ */ new Map();
54
+ const mediaDigests = /* @__PURE__ */ new Map();
55
+ for (const origin of STORY_ORIGINS) for (const relationship of relationships[origin].values()) {
56
+ if (relationship.type !== RELATIONSHIP_TYPES.image || relationship.targetMode === "External") continue;
57
+ const path = resolveTarget(origin, relationship.target);
58
+ if (media.has(path) || !pkg.paths.has(path)) continue;
59
+ const bytes = await Result.tryPromise({
60
+ try: async () => await pkg.readBytes(path),
61
+ catch: (cause) => new TemplatePlanError({
62
+ code: "archive-unreadable",
63
+ message: `The part ${path} could not be read.`,
64
+ part: path,
65
+ cause
66
+ })
67
+ });
68
+ if (Result.isError(bytes)) return bytes;
69
+ if (bytes.value !== null) {
70
+ media.set(path, bytes.value);
71
+ mediaDigests.set(path, sha256Hex(bytes.value));
72
+ }
73
+ }
74
+ return Result.ok({
75
+ relationships,
76
+ resolveTarget,
77
+ mediaDigests,
78
+ media
79
+ });
80
+ };
81
+ const isRelationshipAttribute = (element, name) => {
82
+ const colon = name.indexOf(":");
83
+ return colon !== -1 && !name.startsWith("xmlns:") && OFFICE_RELATIONSHIP_NAMESPACE_URIS.has(resolveNamespaceUri(element.namespaceScope, name.slice(0, colon)) ?? "");
84
+ };
85
+ /** The relationship ids an element and its descendants name, in document order. */
86
+ const relationshipIdsOf = (element) => {
87
+ const ids = [];
88
+ const visit = (node) => {
89
+ if (node.type !== "element") return;
90
+ for (const [name, value] of Object.entries(node.attributes ?? {})) if (value !== void 0 && isRelationshipAttribute(node, name)) ids.push(String(value));
91
+ for (const child of node.elements ?? []) visit(child);
92
+ };
93
+ visit(element);
94
+ return ids;
95
+ };
96
+ const DRAWING_PROPERTIES = "docPr";
97
+ /**
98
+ * A digest of an object's markup that stays the same when the object moves
99
+ * to another package: relationship ids, the drawing id and namespace
100
+ * declarations are left out, everything else counts.
101
+ */
102
+ const objectFingerprint = (element) => {
103
+ const parts = [];
104
+ const visit = (node) => {
105
+ if (node.type === "text") {
106
+ parts.push(JSON.stringify(["text", String(node.text ?? "")]));
107
+ return;
108
+ }
109
+ if (node.type !== "element") return;
110
+ const local = getLocalName(node.name);
111
+ const attributes = Object.entries(node.attributes ?? {}).filter(([name, value]) => value !== void 0 && name !== "xmlns" && !name.startsWith("xmlns:") && !isRelationshipAttribute(node, name) && !(local === DRAWING_PROPERTIES && name === "id")).map(([name, value]) => [getLocalName(name), String(value)]).toSorted(([leftName, leftValue], [rightName, rightValue]) => leftName.localeCompare(rightName) || leftValue.localeCompare(rightValue));
112
+ parts.push(JSON.stringify([
113
+ "open",
114
+ node.namespaceUri ?? "",
115
+ local,
116
+ attributes
117
+ ]));
118
+ for (const child of node.elements ?? []) visit(child);
119
+ parts.push(JSON.stringify(["close"]));
120
+ };
121
+ visit(element);
122
+ return sha256Hex(parts.join("\0"));
123
+ };
124
+ /**
125
+ * What an object's relationships lead to, as strings two packages can be
126
+ * compared by: a picture by the digest of its bytes, an external target by
127
+ * its address.
128
+ */
129
+ const objectTargets = (element, origin, resources) => relationshipIdsOf(element).map((id) => {
130
+ const relationship = resources.relationships[origin].get(id);
131
+ if (relationship === void 0) return "missing";
132
+ if (relationship.targetMode === "External") return `external:${relationship.type}:${relationship.target}`;
133
+ const digest = resources.mediaDigests.get(resources.resolveTarget(origin, relationship.target));
134
+ return digest === void 0 ? `part:${relationship.type}` : `picture:${digest}`;
135
+ });
136
+ export { STORY_ORIGINS, objectFingerprint, objectTargets, readStoryResources, relationshipIdsOf };
@@ -0,0 +1,128 @@
1
+ /**
2
+ * One reader for the inline content of a paragraph, shared by the analysis,
3
+ * the run transfer and the verification, so all three agree on what a block's
4
+ * text is and where an offset into it lands.
5
+ */
6
+ import { XmlElement } from "../../xmlParser.js";
7
+ import { ParagraphNumberingOverride } from "@stll/docx-core/model";
8
+ /** The mark a footnote or endnote reference leaves in a block's text. */
9
+ export declare const NOTE_REFERENCE_MARK = "";
10
+ export type AtomKind = "text" | "tab" | "lineBreak" | "pageBreak" | "noBreakHyphen" | "softHyphen" | "symbol" | "footnoteReference" | "endnoteReference" | "object";
11
+ export type AtomLink =
12
+ /** A link through a relationship; `anchor` is the fragment its element adds. */
13
+ {
14
+ kind: "relationship";
15
+ relationshipId: string;
16
+ anchor: string | null;
17
+ } | {
18
+ kind: "url";
19
+ url: string;
20
+ anchor: string | null;
21
+ } |
22
+ /** A link to a bookmark of the same document. */
23
+ {
24
+ kind: "anchor";
25
+ anchor: string;
26
+ };
27
+ /** A piece of inline content with the text it contributes to its block. */
28
+ export type InlineAtom = {
29
+ kind: AtomKind;
30
+ text: string;
31
+ /** `w:rPr` of the run the atom came from. */
32
+ runProperties: XmlElement | null;
33
+ link: AtomLink | null;
34
+ /** The run child itself: the note reference, symbol, break or object. */
35
+ element: XmlElement | null;
36
+ /** Fields whose result the atom is part of, outermost first. */
37
+ fields: readonly number[];
38
+ };
39
+ export type StoryField = {
40
+ /** Position among the fields of the story, in begin order. */
41
+ index: number;
42
+ instruction: string;
43
+ kind: string;
44
+ result: string;
45
+ /** Text offset in the block the result starts at; -1 before a result starts. */
46
+ resultStart: number;
47
+ /** Paragraph ordinal within the story the field begins in. */
48
+ paragraphOrdinal: number;
49
+ /** Paragraph ordinal the field ends in; the begin's until the end is seen. */
50
+ endParagraphOrdinal: number;
51
+ /** Whether both ends were seen. */
52
+ closed: boolean;
53
+ /** Whether the field sits in the code of another field. */
54
+ nestedInCode: boolean;
55
+ };
56
+ type OpenField = {
57
+ field: StoryField;
58
+ phase: "code" | "result";
59
+ };
60
+ /** Field and revision state that outlives one paragraph of a story. */
61
+ export type StoryState = {
62
+ fields: StoryField[];
63
+ open: OpenField[];
64
+ paragraphOrdinal: number;
65
+ comments: number;
66
+ trackedChanges: number;
67
+ formattingRevisions: number;
68
+ /** Field separators and ends met with no field open to take them. */
69
+ strayFieldEnds: number;
70
+ };
71
+ export declare const createStoryState: () => StoryState;
72
+ /** A bookmark start, with how many atoms of its paragraph come before it. */
73
+ /**
74
+ * Close a story at its end: a field still open there never closes, and must
75
+ * not swallow the text of the story read next with the same state.
76
+ */
77
+ export declare const endStory: (state: StoryState) => void;
78
+ export type ParagraphBookmark = {
79
+ name: string;
80
+ id: string;
81
+ atomIndex: number;
82
+ };
83
+ /** A bookmark end, with how many atoms of its paragraph come before it. */
84
+ export type ParagraphBookmarkEnd = {
85
+ id: string;
86
+ atomIndex: number;
87
+ };
88
+ export type ParagraphRead = {
89
+ element: XmlElement;
90
+ ordinal: number;
91
+ styleId: string | null;
92
+ numPr: ParagraphNumberingOverride | undefined;
93
+ paraId: string | null;
94
+ outlineLevel: number | null;
95
+ atoms: InlineAtom[];
96
+ text: string;
97
+ /** Indices into `StoryState.fields` of the fields beginning here. */
98
+ fieldIndices: number[];
99
+ /** Fields of earlier paragraphs still open where this one starts. */
100
+ openFieldsAtStart: number;
101
+ bookmarks: ParagraphBookmark[];
102
+ bookmarkEnds: ParagraphBookmarkEnd[];
103
+ inlineObjects: number;
104
+ /** Names of content the reader has no text for and the transfer cannot carry. */
105
+ unsupported: string[];
106
+ hasSectionBreak: boolean;
107
+ /** Whether the paragraph mark is a tracked insertion or deletion. */
108
+ hasTrackedMark: boolean;
109
+ };
110
+ /** Read one `w:p`, advancing the story's field and revision state. */
111
+ export declare const readParagraph: (element: XmlElement, state: StoryState) => ParagraphRead;
112
+ export type StoryBlockVisitor = {
113
+ paragraph: (element: XmlElement, depth: number) => void;
114
+ /** Return the walker for the table's cells; called before its rows are read. */
115
+ tableStart: (element: XmlElement, depth: number) => void;
116
+ cellStart: (row: number, col: number) => void;
117
+ tableEnd: (element: XmlElement) => void;
118
+ /** A block-level element the walk does not read. */
119
+ unread: (element: XmlElement) => void;
120
+ /** A tracked insertion, deletion or move of a block, row or cell. */
121
+ tracked: (element: XmlElement) => void;
122
+ };
123
+ /**
124
+ * Visit the blocks under a story container (`w:body`, `w:tc`, a note, a
125
+ * header) in document order. Block content controls are read through.
126
+ */
127
+ export declare const walkBlocks: (container: XmlElement, visitor: StoryBlockVisitor, depth?: number) => void;
128
+ export {};