@stll/folio-core 0.75.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 (92) hide show
  1. package/dist/ai-edits/headless.d.ts +2 -1
  2. package/dist/ai-edits/headless.js +18 -12
  3. package/dist/ai-edits/pending-suggestions.js +2 -3
  4. package/dist/ai-edits/read.js +9 -3
  5. package/dist/ai-edits/types.d.ts +9 -4
  6. package/dist/canonical/batchCommentReferences.js +2 -1
  7. package/dist/canonical/canonicalBatchReview.js +5 -8
  8. package/dist/canonical/canonicalComments.js +8 -2
  9. package/dist/canonical/canonicalCompilerRefusal.d.ts +2 -4
  10. package/dist/canonical/canonicalCompilerRefusal.js +20 -14
  11. package/dist/canonical/canonicalPublicOperations.js +203 -71
  12. package/dist/canonical/canonicalSession.js +3 -1
  13. package/dist/controller/canonicalClipboard.d.ts +1 -1
  14. package/dist/controller/canonicalClipboard.js +71 -17
  15. package/dist/controller/canonicalContentControlValue.js +7 -7
  16. package/dist/controller/canonicalReview.d.ts +21 -0
  17. package/dist/controller/canonicalReview.js +44 -9
  18. package/dist/controller/canonicalStructure.d.ts +1 -2
  19. package/dist/controller/canonicalStructure.js +51 -24
  20. package/dist/controller/fontReadiness.js +50 -23
  21. package/dist/controller/hiddenEditorManager.js +5 -20
  22. package/dist/docx/bulletMarkers.d.ts +8 -0
  23. package/dist/docx/bulletMarkers.js +9 -1
  24. package/dist/docx/canonicalSessionInput.js +25 -11
  25. package/dist/docx/ensureParaIds.d.ts +31 -0
  26. package/dist/docx/ensureParaIds.js +57 -32
  27. package/dist/docx/ensureUniqueControlIds.d.ts +13 -0
  28. package/dist/docx/ensureUniqueControlIds.js +47 -29
  29. package/dist/docx/ensureUniqueRevisionIds.d.ts +13 -0
  30. package/dist/docx/ensureUniqueRevisionIds.js +52 -29
  31. package/dist/docx/server/templatePlan/apply.js +62 -8
  32. package/dist/docx/server/templatePlan/blocks.d.ts +55 -3
  33. package/dist/docx/server/templatePlan/blocks.js +182 -6
  34. package/dist/docx/server/templatePlan/builders.d.ts +16 -1
  35. package/dist/docx/server/templatePlan/builders.js +31 -3
  36. package/dist/docx/server/templatePlan/effects.d.ts +27 -0
  37. package/dist/docx/server/templatePlan/effects.js +188 -0
  38. package/dist/docx/server/templatePlan/emit.d.ts +2 -1
  39. package/dist/docx/server/templatePlan/emit.js +44 -2
  40. package/dist/docx/server/templatePlan/inspect.js +21 -1
  41. package/dist/docx/server/templatePlan/labels.js +16 -1
  42. package/dist/docx/server/templatePlan/plan.d.ts +12 -3
  43. package/dist/docx/server/templatePlan/plan.js +36 -12
  44. package/dist/docx/server/templatePlan/planShape.js +47 -22
  45. package/dist/docx/server/templatePlan/revisions.d.ts +46 -0
  46. package/dist/docx/server/templatePlan/revisions.js +407 -0
  47. package/dist/docx/server/templatePlan/story.d.ts +15 -1
  48. package/dist/docx/server/templatePlan/story.js +50 -2
  49. package/dist/docx/server/templatePlan/types.d.ts +217 -1
  50. package/dist/docx/server/templatePlan/verify.js +117 -8
  51. package/dist/docx/server/templatePlan/xml.d.ts +3 -0
  52. package/dist/docx/server/templatePlan/xml.js +4 -1
  53. package/dist/internal/revisionResolutionStep.d.ts +2 -31
  54. package/dist/internal/revisionResolutionStep.js +2 -171
  55. package/dist/prosemirror/commands/comments.d.ts +6 -234
  56. package/dist/prosemirror/commands/comments.js +5 -2464
  57. package/dist/prosemirror/commands/index.d.ts +4 -2
  58. package/dist/prosemirror/commands/index.js +4 -2
  59. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -11
  60. package/dist/prosemirror/commands/tableCellMergeResolution.js +3 -154
  61. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +6 -8
  62. package/dist/prosemirror/hyperlinkRemoval.d.ts +11 -8
  63. package/dist/prosemirror/hyperlinkRemoval.js +24 -15
  64. package/dist/prosemirror/paraIds.d.ts +1 -14
  65. package/dist/prosemirror/paraIds.js +1 -14
  66. package/dist/prosemirror/paragraphMarkJoin.d.ts +0 -16
  67. package/dist/prosemirror/paragraphMarkJoin.js +3 -46
  68. package/dist/prosemirror/projectionReview.d.ts +49 -0
  69. package/dist/prosemirror/projectionReview.js +292 -0
  70. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -13
  71. package/dist/prosemirror/rebaseParagraphRunFormatting.js +1 -16
  72. package/dist/prosemirror/replacedAnnotations.d.ts +2 -5
  73. package/dist/prosemirror/replacedAnnotations.js +1 -10
  74. package/dist/prosemirror/revisionCarriers.d.ts +9 -1
  75. package/dist/prosemirror/revisionCarriers.js +15 -1
  76. package/dist/prosemirror/revisionRangeQueries.d.ts +32 -0
  77. package/dist/prosemirror/revisionRangeQueries.js +76 -0
  78. package/dist/prosemirror/runFormattingMarkNames.d.ts +1 -1
  79. package/dist/prosemirror/runFormattingMarkNames.js +1 -1
  80. package/dist/prosemirror/suggestionQueries.d.ts +114 -0
  81. package/dist/prosemirror/suggestionQueries.js +320 -0
  82. package/dist/prosemirror/tableGridMutation.d.ts +1 -16
  83. package/dist/prosemirror/tableGridMutation.js +1 -78
  84. package/dist/prosemirror/tableRowRevisionOwnership.d.ts +18 -0
  85. package/dist/prosemirror/tableRowRevisionOwnership.js +7 -0
  86. package/dist/prosemirror/utils/extractTrackedChanges.js +14 -4
  87. package/dist/server.d.ts +2 -2
  88. package/dist/types/canonicalCapabilities.d.ts +1 -25
  89. package/dist/types/canonicalCapabilities.js +1 -23
  90. package/package.json +2 -2
  91. package/dist/internal/headlessRevisionResolutionGuard.d.ts +0 -3
  92. package/dist/internal/headlessRevisionResolutionGuard.js +0 -18
@@ -53,6 +53,8 @@ const isPlainText = (text) => {
53
53
  }
54
54
  return true;
55
55
  };
56
+ /** A font face as `w:rFonts` names one: plain text, not blank, of a sane length. */
57
+ const isFontName = (value) => isString(value) && value.trim() !== "" && value.length <= 64 && isPlainText(value);
56
58
  const numberingIssue = (value, where) => {
57
59
  if (value === void 0 || value === null) return null;
58
60
  if (!isObject(value)) return `${where} names a malformed list.`;
@@ -87,6 +89,38 @@ const sectionIssue = (section, where) => {
87
89
  "left"
88
90
  ].every((side) => isTwips(margins[side])) ? null : `${where} describes malformed page margins.`;
89
91
  };
92
+ const INDENT_KEYS = /* @__PURE__ */ new Set([
93
+ "left",
94
+ "hanging",
95
+ "firstLine"
96
+ ]);
97
+ /** The widest indent a plan may state: the widest page WordprocessingML allows. */
98
+ const MAX_INDENT = 31680;
99
+ /**
100
+ * Whether `value` is an indent a plan may state: at least one of
101
+ * `left`, `hanging` and `firstLine`, each a whole number of twentieths of a
102
+ * point, and not both a hanging and a first-line indent.
103
+ */
104
+ const isIndent = (value) => {
105
+ if (!isObject(value)) return false;
106
+ const keys = Object.keys(value);
107
+ return keys.length > 0 && keys.every((key) => INDENT_KEYS.has(key) && isCount(value[key]) && value[key] <= MAX_INDENT) && !(value["hanging"] !== void 0 && value["firstLine"] !== void 0);
108
+ };
109
+ /** The most tab stops a plan may give one paragraph. */
110
+ const MAX_TAB_STOPS = 8;
111
+ /**
112
+ * Whether `value` is a list of tab stops a plan may state: one to eight
113
+ * whole numbers of twentieths of a point, above zero and ascending.
114
+ */
115
+ const isTabStops = (value) => Array.isArray(value) && value.length > 0 && value.length <= MAX_TAB_STOPS && value.every((stop, index) => isCount(stop) && stop > 0 && stop <= MAX_INDENT && (index === 0 || stop > value[index - 1]));
116
+ const ALIGNMENTS = /* @__PURE__ */ new Set([
117
+ "left",
118
+ "center",
119
+ "right",
120
+ "both"
121
+ ]);
122
+ /** Whether `value` is an alignment a plan may give a paragraph. */
123
+ const isAlignment = (value) => isString(value) && ALIGNMENTS.has(value);
90
124
  const sourceItemIssue = (item, where) => {
91
125
  if (!isString(item["blockId"]) || !isString(item["hash"])) return `${where} names no source block and hash.`;
92
126
  for (const key of [
@@ -94,7 +128,15 @@ const sourceItemIssue = (item, where) => {
94
128
  "cellStyleId",
95
129
  "stripLabel"
96
130
  ]) if (!isOptionalString(item[key])) return `${where} carries a malformed ${key}.`;
97
- for (const key of ["labelAsText", "pageBreakBefore"]) if (!isOptionalBoolean(item[key])) return `${where} carries a malformed ${key}.`;
131
+ for (const key of [
132
+ "labelAsText",
133
+ "pageBreakBefore",
134
+ "keepNext",
135
+ "stripLabelBreak"
136
+ ]) if (!isOptionalBoolean(item[key])) return `${where} carries a malformed ${key}.`;
137
+ if (item["indent"] !== void 0 && !isIndent(item["indent"])) return `${where} carries a malformed indent.`;
138
+ if (item["tabStops"] !== void 0 && !isTabStops(item["tabStops"])) return `${where} carries malformed tab stops.`;
139
+ if (item["alignment"] !== void 0 && !isAlignment(item["alignment"])) return `${where} carries an unknown alignment.`;
98
140
  const merge = item["mergeNext"];
99
141
  if (merge !== void 0 && !(isString(merge) && MERGES.has(merge))) return `${where} names an unknown merge.`;
100
142
  const section = sectionIssue(item["endsSection"], where);
@@ -109,7 +151,7 @@ const sourceItemIssue = (item, where) => {
109
151
  if (!isObject(entry) || !isString(entry["blockId"])) return `${where} carries a nested placement without a block.`;
110
152
  if (seen.has(entry["blockId"])) return `${where} places nested block ${entry["blockId"]} twice.`;
111
153
  seen.add(entry["blockId"]);
112
- if (!isOptionalString(entry["styleId"]) || !isOptionalString(entry["stripLabel"]) || !isOptionalBoolean(entry["labelAsText"])) return `${where} carries a malformed nested placement.`;
154
+ if (!isOptionalString(entry["styleId"]) || !isOptionalString(entry["stripLabel"]) || !isOptionalBoolean(entry["labelAsText"]) || !isOptionalBoolean(entry["keepNext"]) || entry["indent"] !== void 0 && !isIndent(entry["indent"]) || entry["tabStops"] !== void 0 && !isTabStops(entry["tabStops"]) || entry["alignment"] !== void 0 && !isAlignment(entry["alignment"])) return `${where} carries a malformed nested placement.`;
113
155
  const nestedNumbering = numberingIssue(entry["numbering"], where);
114
156
  if (nestedNumbering !== null) return nestedNumbering;
115
157
  }
@@ -142,23 +184,6 @@ const omitIssue = (omit) => {
142
184
  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.";
143
185
  return null;
144
186
  };
145
- const INDENT_KEYS = /* @__PURE__ */ new Set([
146
- "left",
147
- "hanging",
148
- "firstLine"
149
- ]);
150
- /** The widest indent a patch may state: the widest page WordprocessingML allows. */
151
- const MAX_INDENT = 31680;
152
- /**
153
- * Whether `value` is a level indent a patch may state: at least one of
154
- * `left`, `hanging` and `firstLine`, each a whole number of twentieths of a
155
- * point, and not both a hanging and a first-line indent.
156
- */
157
- const isLevelIndent = (value) => {
158
- if (!isObject(value)) return false;
159
- const keys = Object.keys(value);
160
- return keys.length > 0 && keys.every((key) => INDENT_KEYS.has(key) && isCount(value[key]) && value[key] <= MAX_INDENT) && !(value["hanging"] !== void 0 && value["firstLine"] !== void 0);
161
- };
162
187
  const patchesIssue = (patches) => {
163
188
  if (patches === void 0) return null;
164
189
  if (!Array.isArray(patches)) return "The plan's numbering patches are malformed.";
@@ -168,8 +193,8 @@ const patchesIssue = (patches) => {
168
193
  const key = `${String(patch["abstractNumId"])}:${String(patch["ilvl"])}`;
169
194
  if (seen.has(key)) return `Two numbering patches change level ${String(patch["ilvl"])} of list definition ${String(patch["abstractNumId"])}.`;
170
195
  seen.add(key);
171
- const { numFmt, lvlText, start, suff, indent } = patch;
172
- 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)) || indent !== void 0 && !isLevelIndent(indent)) return "A numbering patch carries a malformed value.";
196
+ const { numFmt, lvlText, start, suff, indent, font } = patch;
197
+ if (font !== void 0 && !isFontName(font) || 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)) || indent !== void 0 && !isIndent(indent)) return "A numbering patch carries a malformed value.";
173
198
  }
174
199
  return null;
175
200
  };
@@ -204,6 +229,6 @@ const compatIssue = (compat) => {
204
229
  /** Why `plan` is not a version 1 template plan, or null when it is one. */
205
230
  const planShapeIssue = (plan) => {
206
231
  if (!isObject(plan) || plan["version"] !== 1 || !isString(plan["sourceSha256"]) || !isString(plan["templateSha256"])) return "The plan is not a version 1 template plan.";
207
- return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]) ?? compatIssue(plan["compat"]) ?? sectionIssue(plan["lastSection"], "The plan's last section");
232
+ return bodyIssue(plan["body"]) ?? omitIssue(plan["omit"]) ?? patchesIssue(plan["numberingPatches"]) ?? spansIssue(plan) ?? fieldsIssue(plan["fields"]) ?? compatIssue(plan["compat"]) ?? (plan["trackedChanges"] === void 0 || plan["trackedChanges"] === "accept" || plan["trackedChanges"] === "reject" ? null : "The plan names an unknown view of tracked changes.") ?? sectionIssue(plan["lastSection"], "The plan's last section") ?? (plan["textEffects"] === void 0 || plan["textEffects"] === "normalize" || plan["textEffects"] === "keep" ? null : "The plan's choice for text effects is unknown.");
208
233
  };
209
234
  export { OMIT_REASONS, PLAN_HIGHLIGHT_COLORS, isPlainText, planShapeIssue };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Tracked changes resolved to one view.
3
+ *
4
+ * A document with tracked changes is two texts at once: what it reads with
5
+ * every change accepted, and what it reads with every change rejected. A
6
+ * plan is made for one of them. This module rewrites the story parts of a
7
+ * package into the chosen view: no insertion, deletion, move or recorded
8
+ * formatting change is left, and nothing else of the parts changes.
9
+ *
10
+ * - Accepted: inserted content stays and loses its wrapper, deleted content
11
+ * goes. Rejected: the reverse, and deleted text is ordinary text again.
12
+ * - A paragraph mark that the view removes (deleted and accepted, inserted
13
+ * and rejected) joins its paragraph to the next one of the same container,
14
+ * whose mark, and with it whose properties, the joined paragraph keeps.
15
+ * - A table row that the view removes goes whole; so does a cell.
16
+ * - A recorded formatting change is dropped when accepted. Rejected, the
17
+ * properties it recorded come back.
18
+ */
19
+ import { DocxTrackedChanges, TemplatePlanError, TemplatePlanTrackedView } from "./types.js";
20
+ import { Result } from "better-result";
21
+ type Tally = {
22
+ insertions: number;
23
+ deletions: number;
24
+ moves: number;
25
+ paragraphMarks: number;
26
+ tableRows: number;
27
+ formattingChanges: number;
28
+ authors: Set<string>;
29
+ first: string | null;
30
+ last: string | null;
31
+ };
32
+ /** One part in the chosen view, or null when it cannot be read whole. */
33
+ export declare const resolvePartRevisions: (path: string, xml: string, view: TemplatePlanTrackedView) => {
34
+ xml: string;
35
+ tally: Tally;
36
+ } | null;
37
+ /**
38
+ * A package with the tracked changes of its main document and its notes
39
+ * resolved to `view`, and what was resolved. The bytes are the source's own
40
+ * when it tracks nothing.
41
+ */
42
+ export declare const resolveTrackedChanges: (docx: Uint8Array, view: TemplatePlanTrackedView) => Promise<Result<{
43
+ docx: Uint8Array;
44
+ resolved: DocxTrackedChanges;
45
+ }, TemplatePlanError>>;
46
+ export {};
@@ -0,0 +1,407 @@
1
+ import { spliceXml } from "../../selectiveXmlPatch.js";
2
+ import { loadPackage } from "./package.js";
3
+ import { TemplatePlanError } from "./types.js";
4
+ import { elementChildren, innerRangeOf, rangeOf, readRawPart, wAttr, wChild, wName } from "./xml.js";
5
+ import { Result } from "better-result";
6
+ import { ZipArchive } from "@stll/docx-core/zip";
7
+ // src/docx/server/templatePlan/revisions.ts
8
+ /**
9
+ * Tracked changes resolved to one view.
10
+ *
11
+ * A document with tracked changes is two texts at once: what it reads with
12
+ * every change accepted, and what it reads with every change rejected. A
13
+ * plan is made for one of them. This module rewrites the story parts of a
14
+ * package into the chosen view: no insertion, deletion, move or recorded
15
+ * formatting change is left, and nothing else of the parts changes.
16
+ *
17
+ * - Accepted: inserted content stays and loses its wrapper, deleted content
18
+ * goes. Rejected: the reverse, and deleted text is ordinary text again.
19
+ * - A paragraph mark that the view removes (deleted and accepted, inserted
20
+ * and rejected) joins its paragraph to the next one of the same container,
21
+ * whose mark, and with it whose properties, the joined paragraph keeps.
22
+ * - A table row that the view removes goes whole; so does a cell.
23
+ * - A recorded formatting change is dropped when accepted. Rejected, the
24
+ * properties it recorded come back.
25
+ */
26
+ const INSERTED = /* @__PURE__ */ new Set(["ins", "moveTo"]);
27
+ const DELETED = /* @__PURE__ */ new Set(["del", "moveFrom"]);
28
+ const MOVE_MARKS = /* @__PURE__ */ new Set([
29
+ "moveFromRangeStart",
30
+ "moveFromRangeEnd",
31
+ "moveToRangeStart",
32
+ "moveToRangeEnd"
33
+ ]);
34
+ /** A recorded change of properties, by the properties element it sits in. */
35
+ const PROPERTY_CHANGES = /* @__PURE__ */ new Map([
36
+ ["rPrChange", "rPr"],
37
+ ["pPrChange", "pPr"],
38
+ ["sectPrChange", "sectPr"],
39
+ ["tblPrChange", "tblPr"],
40
+ ["tblGridChange", "tblGrid"],
41
+ ["tblPrExChange", "tblPrEx"],
42
+ ["trPrChange", "trPr"],
43
+ ["tcPrChange", "tcPr"]
44
+ ]);
45
+ const CELL_MARKS = /* @__PURE__ */ new Set([
46
+ "cellIns",
47
+ "cellDel",
48
+ "cellMerge"
49
+ ]);
50
+ const OWN_PROPERTIES = /* @__PURE__ */ new Map([["pPr", /* @__PURE__ */ new Set(["rPr", "sectPr"])], ["sectPr", /* @__PURE__ */ new Set(["headerReference", "footerReference"])]]);
51
+ /** Marks of a range that outlive content a view removes around them: a
52
+ * bookmark or a comment that begins inside a deletion ends outside it. */
53
+ const RANGE_MARKS = /* @__PURE__ */ new Set([
54
+ "bookmarkStart",
55
+ "bookmarkEnd",
56
+ "commentRangeStart",
57
+ "commentRangeEnd",
58
+ "permStart",
59
+ "permEnd"
60
+ ]);
61
+ /** Every element name this module acts on, to skip a subtree without one. */
62
+ const REVISION_NAMES = [
63
+ ...INSERTED,
64
+ ...DELETED,
65
+ ...MOVE_MARKS,
66
+ ...PROPERTY_CHANGES.keys(),
67
+ ...CELL_MARKS,
68
+ "numberingChange",
69
+ "delText",
70
+ "delInstrText"
71
+ ];
72
+ const newTally = () => ({
73
+ insertions: 0,
74
+ deletions: 0,
75
+ moves: 0,
76
+ paragraphMarks: 0,
77
+ tableRows: 0,
78
+ formattingChanges: 0,
79
+ authors: /* @__PURE__ */ new Set(),
80
+ first: null,
81
+ last: null
82
+ });
83
+ /**
84
+ * What a part tracks, whatever view is taken of it: every insertion,
85
+ * deletion, move and recorded formatting change, with who made it and
86
+ * when. A change inside content the view removes is counted all the same.
87
+ */
88
+ const tallyPart = (root, tally) => {
89
+ const stack = [root];
90
+ for (let element = stack.pop(); element !== void 0; element = stack.pop()) {
91
+ const name = wName(element);
92
+ let counted = true;
93
+ if (name === "ins") tally.insertions += 1;
94
+ else if (name === "del") tally.deletions += 1;
95
+ else if (name === "moveFrom" || name === "moveTo") tally.moves += 1;
96
+ else if (name !== null && (PROPERTY_CHANGES.has(name) || CELL_MARKS.has(name) || name === "numberingChange")) tally.formattingChanges += 1;
97
+ else counted = false;
98
+ if (counted) {
99
+ const author = wAttr(element, "author");
100
+ const date = wAttr(element, "date");
101
+ if (author !== null && author !== "") tally.authors.add(author);
102
+ if (date !== null && date !== "") {
103
+ tally.first = tally.first === null || date < tally.first ? date : tally.first;
104
+ tally.last = tally.last === null || date > tally.last ? date : tally.last;
105
+ }
106
+ }
107
+ stack.push(...elementChildren(element));
108
+ }
109
+ };
110
+ const mayHoldRevision = (text) => REVISION_NAMES.some((name) => text.includes(`:${name}`));
111
+ /** The element's source text; the walk is unsound without its range. */
112
+ const sourceOf = (walk, element) => {
113
+ const range = rangeOf(element);
114
+ if (range === null) {
115
+ walk.sound = false;
116
+ return "";
117
+ }
118
+ return walk.xml.slice(range.start, range.end);
119
+ };
120
+ /** The range marks inside content a view removes, as they stand. */
121
+ const rangeMarksIn = (walk, element) => {
122
+ let marks = "";
123
+ const stack = [...elementChildren(element)].toReversed();
124
+ for (let next = stack.pop(); next !== void 0; next = stack.pop()) if (RANGE_MARKS.has(wName(next) ?? "")) marks += sourceOf(walk, next);
125
+ else stack.push(...elementChildren(next).toReversed());
126
+ return marks;
127
+ };
128
+ /** Whether the chosen view keeps content marked `name`. */
129
+ const keeps = (walk, name) => INSERTED.has(name) ? walk.view === "accept" : walk.view === "reject";
130
+ /** Deleted text read as text again: the names of its elements. */
131
+ const asLiveText = (xml) => xml.replaceAll(/<(\/?)([A-Za-z0-9]+:)delText\b/gu, "<$1$2t").replaceAll(/<(\/?)([A-Za-z0-9]+:)delInstrText\b/gu, "<$1$2instrText");
132
+ /** Whether the view removes the paragraph's mark. */
133
+ const losesMark = (walk, paragraph) => {
134
+ const mark = wChild(wChild(paragraph, "pPr"), "rPr");
135
+ return (walk.view === "accept" ? ["del", "moveFrom"] : ["ins", "moveTo"]).some((name) => wChild(mark, name) !== null);
136
+ };
137
+ /** Whether the view removes the row: the marker of `w:trPr`. */
138
+ const losesRow = (walk, row) => {
139
+ const properties = wChild(row, "trPr");
140
+ return wChild(properties, walk.view === "accept" ? "del" : "ins") !== null;
141
+ };
142
+ const losesCell = (walk, cell) => wChild(wChild(cell, "tcPr"), walk.view === "accept" ? "cellDel" : "cellIns") !== null;
143
+ /**
144
+ * The children of `container` in the chosen view, with the text between
145
+ * them as it stands. A paragraph whose mark goes hands its content to the
146
+ * next paragraph of the container.
147
+ */
148
+ const resolveChildren = (walk, container) => {
149
+ const inner = innerRangeOf(walk.xml, container);
150
+ if (inner === null) return "";
151
+ const pieces = [];
152
+ let cursor = inner.start;
153
+ const visit = (element) => {
154
+ const range = rangeOf(element);
155
+ if (range === null) {
156
+ walk.sound = false;
157
+ return;
158
+ }
159
+ pieces.push(walk.xml.slice(cursor, range.start));
160
+ cursor = range.end;
161
+ const name = wName(element);
162
+ if (name !== null && (INSERTED.has(name) || DELETED.has(name))) {
163
+ if (keeps(walk, name)) {
164
+ const kept = resolveChildren(walk, element);
165
+ pieces.push(DELETED.has(name) ? asLiveText(kept) : kept);
166
+ } else pieces.push(rangeMarksIn(walk, element));
167
+ return;
168
+ }
169
+ if (name !== null && MOVE_MARKS.has(name)) return;
170
+ if (name === "numberingChange" || name !== null && CELL_MARKS.has(name)) return;
171
+ if (name !== null && PROPERTY_CHANGES.has(name)) return;
172
+ if (name === "tr" && losesRow(walk, element)) {
173
+ walk.tally.tableRows += 1;
174
+ pieces.push(rangeMarksIn(walk, element));
175
+ return;
176
+ }
177
+ if (name === "tc" && losesCell(walk, element)) {
178
+ pieces.push(rangeMarksIn(walk, element));
179
+ return;
180
+ }
181
+ if (name === "p") {
182
+ pieces.push({
183
+ xml: resolveElement(walk, element),
184
+ paragraph: element,
185
+ carried: losesMark(walk, element)
186
+ });
187
+ return;
188
+ }
189
+ pieces.push(resolveElement(walk, element));
190
+ };
191
+ for (const child of elementChildren(container)) visit(child);
192
+ pieces.push(walk.xml.slice(cursor, inner.end));
193
+ return joinParagraphs(walk, pieces);
194
+ };
195
+ /** The content of a resolved paragraph without its properties. */
196
+ const contentOf = (paragraphXml) => {
197
+ const open = paragraphXml.indexOf(">") + 1;
198
+ const close = paragraphXml.lastIndexOf("</");
199
+ if (paragraphXml.endsWith("/>") || close < open) return "";
200
+ const body = paragraphXml.slice(open, close);
201
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b/u.exec(body) === null) return body;
202
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b[^>]*\/>/u.test(body)) return body.slice(body.indexOf("/>") + 2);
203
+ const end = /<\/([A-Za-z0-9]+:)?pPr>/u.exec(body);
204
+ return end === null ? body : body.slice(end.index + end[0].length);
205
+ };
206
+ /** `content` put in front of what a resolved paragraph holds. */
207
+ const withLeadingContent = (paragraphXml, content) => {
208
+ if (content === "") return paragraphXml;
209
+ if (paragraphXml.endsWith("/>")) {
210
+ const name = /^<([^\s/>]+)/u.exec(paragraphXml)?.[1] ?? "w:p";
211
+ return `${paragraphXml.slice(0, -2)}>${content}</${name}>`;
212
+ }
213
+ const open = paragraphXml.indexOf(">") + 1;
214
+ const body = paragraphXml.slice(open);
215
+ const selfClosed = /^\s*<([A-Za-z0-9]+:)?pPr\b[^>]*\/>/u.exec(body);
216
+ if (selfClosed !== null) {
217
+ const at = open + selfClosed[0].length;
218
+ return `${paragraphXml.slice(0, at)}${content}${paragraphXml.slice(at)}`;
219
+ }
220
+ if (/^\s*<([A-Za-z0-9]+:)?pPr\b/u.test(body)) {
221
+ const end = /<\/([A-Za-z0-9]+:)?pPr>/u.exec(body);
222
+ if (end !== null) {
223
+ const at = open + end.index + end[0].length;
224
+ return `${paragraphXml.slice(0, at)}${content}${paragraphXml.slice(at)}`;
225
+ }
226
+ }
227
+ return `${paragraphXml.slice(0, open)}${content}${body}`;
228
+ };
229
+ const joinParagraphs = (walk, pieces) => {
230
+ let out = "";
231
+ /** Content of paragraphs whose mark went, waiting for the next one. */
232
+ let carried = "";
233
+ /** The last such paragraph, kept whole when no paragraph follows. */
234
+ let held = null;
235
+ const flush = () => {
236
+ if (held !== null) {
237
+ out += withLeadingContent(held, carried);
238
+ carried = "";
239
+ held = null;
240
+ }
241
+ };
242
+ for (const piece of pieces) {
243
+ if (typeof piece === "string") {
244
+ out += piece;
245
+ continue;
246
+ }
247
+ if (piece.paragraph === null) {
248
+ flush();
249
+ out += piece.xml;
250
+ continue;
251
+ }
252
+ if (piece.carried) {
253
+ walk.tally.paragraphMarks += 1;
254
+ if (held !== null) carried += contentOf(held);
255
+ held = piece.xml;
256
+ continue;
257
+ }
258
+ if (held !== null) {
259
+ carried += contentOf(held);
260
+ held = null;
261
+ }
262
+ out += withLeadingContent(piece.xml, carried);
263
+ carried = "";
264
+ }
265
+ flush();
266
+ return out;
267
+ };
268
+ /** The properties a recorded change gives back, inside `properties`. */
269
+ const restoredProperties = (walk, properties, name) => {
270
+ const changeName = [...PROPERTY_CHANGES].find(([, owner]) => owner === name)?.[0];
271
+ const change = changeName === void 0 ? null : wChild(properties, changeName);
272
+ if (change === null || walk.view !== "reject") return null;
273
+ const recorded = wChild(change, name);
274
+ const outer = rangeOf(properties);
275
+ const inner = innerRangeOf(walk.xml, properties);
276
+ if (outer === null || inner === null) return null;
277
+ const recordedInner = recorded === null ? null : innerRangeOf(walk.xml, recorded);
278
+ const old = recordedInner === null ? "" : walk.xml.slice(recordedInner.start, recordedInner.end);
279
+ const own = OWN_PROPERTIES.get(name) ?? null;
280
+ const kept = own === null ? "" : elementChildren(properties).filter((child) => own.has(wName(child) ?? "")).map((child) => resolveElement(walk, child)).join("");
281
+ const head = walk.xml.slice(outer.start, inner.start);
282
+ const tail = walk.xml.slice(inner.end, outer.end);
283
+ return name === "sectPr" ? `${head}${kept}${old}${tail}` : `${head}${old}${kept}${tail}`;
284
+ };
285
+ /** `element` in the chosen view; its own text when it holds no revision. */
286
+ const resolveElement = (walk, element) => {
287
+ const source = sourceOf(walk, element);
288
+ if (!mayHoldRevision(source)) return source;
289
+ const name = wName(element);
290
+ if (name !== null && [...PROPERTY_CHANGES.values()].includes(name)) {
291
+ const restored = restoredProperties(walk, element, name);
292
+ if (restored !== null) return restored;
293
+ }
294
+ const outer = rangeOf(element);
295
+ const inner = innerRangeOf(walk.xml, element);
296
+ if (outer === null) {
297
+ walk.sound = false;
298
+ return source;
299
+ }
300
+ if (inner === null) return source;
301
+ const content = resolveChildren(walk, element);
302
+ return `${walk.xml.slice(outer.start, inner.start)}${content}${walk.xml.slice(inner.end, outer.end)}`;
303
+ };
304
+ const summaryOf = (tally) => ({
305
+ insertions: tally.insertions,
306
+ deletions: tally.deletions,
307
+ moves: tally.moves,
308
+ paragraphMarks: tally.paragraphMarks,
309
+ tableRows: tally.tableRows,
310
+ formattingChanges: tally.formattingChanges,
311
+ authors: [...tally.authors].toSorted(),
312
+ first: tally.first,
313
+ last: tally.last
314
+ });
315
+ /** One part in the chosen view, or null when it cannot be read whole. */
316
+ const resolvePartRevisions = (path, xml, view) => {
317
+ const part = readRawPart(path, xml);
318
+ if (part === null) return null;
319
+ const walk = {
320
+ xml,
321
+ view,
322
+ tally: newTally(),
323
+ sound: true
324
+ };
325
+ const outer = rangeOf(part.root);
326
+ if (outer === null) return null;
327
+ tallyPart(part.root, walk.tally);
328
+ const resolved = resolveElement(walk, part.root);
329
+ if (!walk.sound) return null;
330
+ const rewritten = spliceXml(xml, [{
331
+ ...outer,
332
+ newXml: resolved
333
+ }]);
334
+ return rewritten === null ? null : {
335
+ xml: rewritten,
336
+ tally: walk.tally
337
+ };
338
+ };
339
+ const mergeTallies = (tallies) => {
340
+ const total = newTally();
341
+ for (const tally of tallies) {
342
+ total.insertions += tally.insertions;
343
+ total.deletions += tally.deletions;
344
+ total.moves += tally.moves;
345
+ total.paragraphMarks += tally.paragraphMarks;
346
+ total.tableRows += tally.tableRows;
347
+ total.formattingChanges += tally.formattingChanges;
348
+ for (const author of tally.authors) total.authors.add(author);
349
+ for (const date of [tally.first, tally.last]) if (date !== null) {
350
+ total.first = total.first === null || date < total.first ? date : total.first;
351
+ total.last = total.last === null || date > total.last ? date : total.last;
352
+ }
353
+ }
354
+ return total;
355
+ };
356
+ /**
357
+ * A package with the tracked changes of its main document and its notes
358
+ * resolved to `view`, and what was resolved. The bytes are the source's own
359
+ * when it tracks nothing.
360
+ */
361
+ const resolveTrackedChanges = async (docx, view) => {
362
+ const loaded = await loadPackage(docx);
363
+ if (loaded.isErr()) return Result.err(loaded.error);
364
+ const pkg = loaded.value;
365
+ const paths = [
366
+ pkg.documentPath,
367
+ pkg.partPath("footnotes"),
368
+ pkg.partPath("endnotes")
369
+ ].filter((path) => path !== null);
370
+ const rewritten = /* @__PURE__ */ new Map();
371
+ const tallies = [];
372
+ for (const path of paths) {
373
+ const xml = path === pkg.documentPath ? pkg.documentXml : await pkg.readText(path);
374
+ if (xml === null || !mayHoldRevision(xml)) continue;
375
+ const resolved = resolvePartRevisions(path, xml, view);
376
+ if (resolved === null) return Result.err(new TemplatePlanError({
377
+ code: "xml-unreadable",
378
+ message: `The tracked changes of ${path} could not be resolved.`
379
+ }));
380
+ tallies.push(resolved.tally);
381
+ if (resolved.xml !== xml) rewritten.set(path, resolved.xml);
382
+ }
383
+ const resolved = summaryOf(mergeTallies(tallies));
384
+ if (rewritten.size === 0) return Result.ok({
385
+ docx,
386
+ resolved
387
+ });
388
+ return await Result.tryPromise({
389
+ try: async () => {
390
+ const zip = await ZipArchive.read(docx);
391
+ for (const [path, content] of rewritten) {
392
+ const current = zip.entry(path);
393
+ zip.set(path, content, current === void 0 ? {} : { modified: current.modified });
394
+ }
395
+ return {
396
+ docx: await zip.generate(),
397
+ resolved
398
+ };
399
+ },
400
+ catch: (cause) => new TemplatePlanError({
401
+ code: "archive-unreadable",
402
+ message: "The package could not be rewritten without its tracked changes.",
403
+ cause
404
+ })
405
+ });
406
+ };
407
+ export { resolvePartRevisions, resolveTrackedChanges };
@@ -7,7 +7,7 @@ import { XmlElement } from "../../xmlParser.js";
7
7
  import { ParagraphNumberingOverride } from "@stll/docx-core/model";
8
8
  /** The mark a footnote or endnote reference leaves in a block's text. */
9
9
  export declare const NOTE_REFERENCE_MARK = "";
10
- export type AtomKind = "text" | "tab" | "lineBreak" | "pageBreak" | "noBreakHyphen" | "softHyphen" | "symbol" | "footnoteReference" | "endnoteReference" | "object";
10
+ export type AtomKind = "text" | "tab" | "lineBreak" | "pageBreak" | "noBreakHyphen" | "softHyphen" | "symbol" | "footnoteReference" | "endnoteReference" | "selfNumber" | "object";
11
11
  export type AtomLink =
12
12
  /** A link through a relationship; `anchor` is the fragment its element adds. */
13
13
  {
@@ -35,7 +35,11 @@ export type InlineAtom = {
35
35
  element: XmlElement | null;
36
36
  /** Fields whose result the atom is part of, outermost first. */
37
37
  fields: readonly number[];
38
+ /** The code of the field a `selfNumber` atom stands for. */
39
+ instruction?: string;
38
40
  };
41
+ /** Whether a field kind prints a number of its own and caches no text. */
42
+ export declare const isSelfNumberingField: (kind: string) => boolean;
39
43
  export type StoryField = {
40
44
  /** Position among the fields of the story, in begin order. */
41
45
  index: number;
@@ -110,6 +114,16 @@ export type ParagraphRead = {
110
114
  pageBreakBefore: boolean | null;
111
115
  /** `w:jc` as the paragraph itself states it, or null. */
112
116
  alignment: string | null;
117
+ /** The sides of `w:ind` the paragraph itself states, in twentieths of a
118
+ * point: where its lines start, and what its first line adds to that
119
+ * (negative for a hanging indent). Null for a side it does not state. */
120
+ indent: {
121
+ left: number | null;
122
+ firstLine: number | null;
123
+ };
124
+ /** Whether the paragraph states an indent in characters, which stands
125
+ * over the measured one and cannot be given in twentieths of a point. */
126
+ indentInCharacters: boolean;
113
127
  /** Whether the paragraph mark is a tracked insertion or deletion. */
114
128
  hasTrackedMark: boolean;
115
129
  };