@stll/folio-core 0.72.0 → 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.
- package/README.md +12 -6
- package/dist/ai-edits/apply.d.ts +6 -114
- package/dist/ai-edits/apply.js +9 -131
- package/dist/ai-edits/applyTypes.d.ts +85 -0
- package/dist/ai-edits/applyTypes.js +24 -0
- package/dist/ai-edits/clean-text.d.ts +7 -1
- package/dist/ai-edits/clean-text.js +23 -2
- package/dist/ai-edits/finalSectionReview.d.ts +1 -1
- package/dist/ai-edits/headless.d.ts +29 -147
- package/dist/ai-edits/headless.js +213 -1634
- package/dist/ai-edits/index.d.ts +3 -3
- package/dist/ai-edits/index.js +2 -3
- package/dist/ai-edits/pending-suggestions.d.ts +14 -4
- package/dist/ai-edits/pending-suggestions.js +183 -90
- package/dist/ai-edits/result-validation.js +1 -1
- package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
- package/dist/ai-edits/snapshot.js +8 -3
- package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
- package/dist/ai-edits/table-cell-mutations.js +1 -1
- package/dist/ai-edits/table-geometry.d.ts +1 -1
- package/dist/ai-edits/table-geometry.js +1 -1
- package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
- package/dist/ai-edits/table-row-column-mutations.js +1 -1
- package/dist/ai-edits/tableNodes.d.ts +38 -0
- package/dist/ai-edits/tableNodes.js +86 -0
- package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
- package/dist/ai-edits/undefinedReferences.d.ts +7 -0
- package/dist/canonical/batchCommentReferences.js +1 -0
- package/dist/canonical/canonicalInlineProjection.js +1 -1
- package/dist/canonical/canonicalPublicOperations.js +228 -64
- package/dist/canonical/canonicalSession.d.ts +9 -1
- package/dist/canonical/canonicalSession.js +95 -15
- package/dist/compare/compare.d.ts +1 -1
- package/dist/compare/inline-atoms-model.d.ts +1 -1
- package/dist/compare/inline-atoms.d.ts +2 -2
- package/dist/compare/inline-provenance-model.d.ts +1 -1
- package/dist/compare/inline-provenance.d.ts +2 -2
- package/dist/compat/eigenpal.d.ts +3 -3
- package/dist/compat/eigenpal.js +2 -3
- package/dist/controller/canonicalClipboard.d.ts +13 -3
- package/dist/controller/canonicalClipboard.js +185 -49
- package/dist/controller/canonicalClipboardResources.d.ts +9 -1
- package/dist/controller/canonicalClipboardResources.js +22 -2
- package/dist/controller/canonicalReview.d.ts +1 -1
- package/dist/controller/canonicalReview.js +1 -1
- package/dist/controller/canonicalStructure.js +1 -1
- package/dist/controller/canonicalWatermark.d.ts +10 -0
- package/dist/controller/canonicalWatermark.js +37 -0
- package/dist/controller/hiddenEditorApi.d.ts +1 -1
- package/dist/controller/hiddenEditorManager.d.ts +4 -3
- package/dist/controller/hiddenEditorManager.js +75 -15
- package/dist/document-operations-apply.d.ts +15 -0
- package/dist/document-operations-apply.js +280 -0
- package/dist/document-operations.d.ts +1 -14
- package/dist/document-operations.js +2 -279
- package/dist/docx/modelValidation.js +1 -1
- package/dist/docx/paragraphParser.js +2 -2
- package/dist/docx/paragraphPropertySource.d.ts +1 -1
- package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
- package/dist/docx/reviewResolutionProvenance.js +32 -9
- package/dist/docx/revisionIdNormalization.js +30 -7
- package/dist/docx/rezip.js +1 -1
- package/dist/docx/serializer/borderSerializer.js +1 -1
- package/dist/docx/serializer/commentSerializer.js +1 -1
- package/dist/docx/serializer/documentSerializer.js +1 -1
- package/dist/docx/serializer/paragraphSerializer.js +3 -3
- package/dist/docx/serializer/runSerializer.js +1 -1
- package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
- package/dist/docx/serializer/tableSerializer.js +5 -37
- package/dist/docx/serializer/textFormattingSerializer.js +1 -1
- package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
- package/dist/docx/server/templatePlan/apply.d.ts +15 -0
- package/dist/docx/server/templatePlan/apply.js +600 -0
- package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
- package/dist/docx/server/templatePlan/blocks.js +355 -0
- package/dist/docx/server/templatePlan/builders.d.ts +72 -0
- package/dist/docx/server/templatePlan/builders.js +237 -0
- package/dist/docx/server/templatePlan/emit.d.ts +118 -0
- package/dist/docx/server/templatePlan/emit.js +466 -0
- package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
- package/dist/docx/server/templatePlan/emphasis.js +173 -0
- package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
- package/dist/docx/server/templatePlan/inspect.js +177 -0
- package/dist/docx/server/templatePlan/labels.d.ts +36 -0
- package/dist/docx/server/templatePlan/labels.js +126 -0
- package/dist/docx/server/templatePlan/package.d.ts +34 -0
- package/dist/docx/server/templatePlan/package.js +99 -0
- package/dist/docx/server/templatePlan/plan.d.ts +143 -0
- package/dist/docx/server/templatePlan/plan.js +841 -0
- package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
- package/dist/docx/server/templatePlan/planShape.js +161 -0
- package/dist/docx/server/templatePlan/resources.d.ts +41 -0
- package/dist/docx/server/templatePlan/resources.js +136 -0
- package/dist/docx/server/templatePlan/story.d.ts +128 -0
- package/dist/docx/server/templatePlan/story.js +440 -0
- package/dist/docx/server/templatePlan/types.d.ts +406 -0
- package/dist/docx/server/templatePlan/types.js +28 -0
- package/dist/docx/server/templatePlan/verify.d.ts +40 -0
- package/dist/docx/server/templatePlan/verify.js +968 -0
- package/dist/docx/server/templatePlan/xml.d.ts +69 -0
- package/dist/docx/server/templatePlan/xml.js +119 -0
- package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
- package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
- package/dist/docx/storyBlockReplay.js +1 -1
- package/dist/docx/structuralXmlPatch.js +9 -1
- package/dist/docx/tableGridXml.d.ts +30 -0
- package/dist/docx/tableGridXml.js +54 -0
- package/dist/docx/tableParser.js +7 -0
- package/dist/docx/xmlParser.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -3
- package/dist/internal/paragraphFormattingSerialization.js +1 -1
- package/dist/internal/wholeStoryRevisionResolution.js +1 -1
- package/dist/managers/ContextMenuManager.js +2 -1
- package/dist/managers/editorShortcuts.d.ts +1 -1
- package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
- package/dist/prosemirror/canonicalCommands.d.ts +1 -1
- package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
- package/dist/prosemirror/canonicalTableCommands.js +2 -2
- package/dist/prosemirror/commands/comments.js +3 -3
- package/dist/prosemirror/commands/contentControls.d.ts +1 -1
- package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
- package/dist/prosemirror/commands/formatting.d.ts +1 -1
- package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
- package/dist/prosemirror/commands/sectionBreak.js +1 -1
- package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
- package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
- package/dist/prosemirror/commentRecords.d.ts +1 -1
- package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
- package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
- package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
- package/dist/prosemirror/documentStructureCounts.js +76 -0
- package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
- package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
- package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
- package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
- package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
- package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
- package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
- package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
- package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
- package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
- package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
- package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
- package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
- package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
- package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
- package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
- package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
- package/dist/prosemirror/extensions/types.d.ts +1 -1
- package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
- package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
- package/dist/prosemirror/index.d.ts +1 -1
- package/dist/prosemirror/index.js +1 -1
- package/dist/prosemirror/insertionGaps.d.ts +1 -1
- package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
- package/dist/prosemirror/listNumbering.d.ts +1 -1
- package/dist/prosemirror/lockedControls.d.ts +1 -1
- package/dist/prosemirror/markupViewProjection.d.ts +1 -1
- package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
- package/dist/prosemirror/noteReferenceReview.js +1 -1
- package/dist/prosemirror/paraIds.d.ts +46 -0
- package/dist/prosemirror/paraIds.js +152 -0
- package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
- package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
- package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
- package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
- package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
- package/dist/prosemirror/pastedCommentCopies.js +1 -1
- package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
- package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
- package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
- package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
- package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
- package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
- package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
- package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
- package/dist/prosemirror/replacedAnnotations.js +16 -1
- package/dist/prosemirror/revisionCarriers.d.ts +1 -1
- package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
- package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
- package/dist/prosemirror/selectionBounds.d.ts +10 -0
- package/dist/prosemirror/selectionBounds.js +22 -0
- package/dist/prosemirror/storyListNumbering.d.ts +1 -1
- package/dist/prosemirror/tableCellPaste.d.ts +1 -1
- package/dist/prosemirror/tableGridMutation.d.ts +1 -1
- package/dist/prosemirror/textInput.d.ts +1 -1
- package/dist/server.d.ts +7 -2
- package/dist/server.js +6 -1
- package/dist/types/canonicalCapabilities.d.ts +8 -41
- package/dist/types/canonicalCapabilities.js +6 -34
- package/package.json +4 -4
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
import { registerContentTypeParts } from "../../contentTypeRegistry.js";
|
|
2
|
+
import { RELATIONSHIP_TYPES } from "../../relsParser.js";
|
|
3
|
+
import { spliceXml } from "../../selectiveXmlPatch.js";
|
|
4
|
+
import { NAMESPACES, getLocalName } from "../../xmlParser.js";
|
|
5
|
+
import { appendToXmlRoot } from "../../xmlRootInsertion.js";
|
|
6
|
+
import { analyzeDocument } from "./blocks.js";
|
|
7
|
+
import { freezeFields, setUpdateFieldsOnOpen, withoutContained } from "./builders.js";
|
|
8
|
+
import { createRelationshipsEditor, noteXml, paragraphContentXml, paragraphXml, tableXml, templateCharacterStyles } from "./emit.js";
|
|
9
|
+
import { readHeaderFooterParts } from "./inspect.js";
|
|
10
|
+
import { styleNumbering } from "./labels.js";
|
|
11
|
+
import { guarded, readPartText, relationshipsPathFor } from "./package.js";
|
|
12
|
+
import { resolvePlan } from "./plan.js";
|
|
13
|
+
import { readStoryResources } from "./resources.js";
|
|
14
|
+
import { TemplatePlanError } from "./types.js";
|
|
15
|
+
import { reportTemplatePlanOutput } from "./verify.js";
|
|
16
|
+
import { elementChildren, escapeXmlAttribute, innerRangeOf, integerOrNull, isW, maxOf, partPrefixes, rangeOf, readRawPart, sliceWithSplices, wAttr, wChild, wChildren, wName, walkElements } from "./xml.js";
|
|
17
|
+
import { Result } from "better-result";
|
|
18
|
+
import { ZipArchive } from "@stll/docx-core/zip";
|
|
19
|
+
// src/docx/server/templatePlan/apply.ts
|
|
20
|
+
/**
|
|
21
|
+
* Apply a source document onto a template from a plan: the output is the
|
|
22
|
+
* template's own package with a new main story. Parts the plan does not
|
|
23
|
+
* touch keep their bytes; the ones it does are spliced, not re-serialized.
|
|
24
|
+
*/
|
|
25
|
+
const CONTENT_TYPES_PATH = "[Content_Types].xml";
|
|
26
|
+
const WORDPROCESSINGML_CONTENT_TYPE_PREFIX = "application/vnd.openxmlformats-officedocument.wordprocessingml.";
|
|
27
|
+
const RELATIONSHIPS_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
|
|
28
|
+
const MEDIA_CONTENT_TYPES = {
|
|
29
|
+
png: "image/png",
|
|
30
|
+
jpg: "image/jpeg",
|
|
31
|
+
jpeg: "image/jpeg",
|
|
32
|
+
gif: "image/gif",
|
|
33
|
+
bmp: "image/bmp",
|
|
34
|
+
tif: "image/tiff",
|
|
35
|
+
tiff: "image/tiff",
|
|
36
|
+
emf: "image/x-emf",
|
|
37
|
+
wmf: "image/x-wmf",
|
|
38
|
+
svg: "image/svg+xml",
|
|
39
|
+
webp: "image/webp"
|
|
40
|
+
};
|
|
41
|
+
const NOTE_PARTS = {
|
|
42
|
+
footnote: {
|
|
43
|
+
origin: "footnotes",
|
|
44
|
+
fileName: "footnotes.xml",
|
|
45
|
+
root: "footnotes",
|
|
46
|
+
contentType: `${WORDPROCESSINGML_CONTENT_TYPE_PREFIX}footnotes+xml`,
|
|
47
|
+
relationshipType: RELATIONSHIP_TYPES.footnotes
|
|
48
|
+
},
|
|
49
|
+
endnote: {
|
|
50
|
+
origin: "endnotes",
|
|
51
|
+
fileName: "endnotes.xml",
|
|
52
|
+
root: "endnotes",
|
|
53
|
+
contentType: `${WORDPROCESSINGML_CONTENT_TYPE_PREFIX}endnotes+xml`,
|
|
54
|
+
relationshipType: RELATIONSHIP_TYPES.endnotes
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const unreadable = (part, message) => new TemplatePlanError({
|
|
58
|
+
code: "xml-unreadable",
|
|
59
|
+
message,
|
|
60
|
+
part
|
|
61
|
+
});
|
|
62
|
+
const directoryOf = (path) => {
|
|
63
|
+
const slash = path.lastIndexOf("/");
|
|
64
|
+
return slash === -1 ? "" : path.slice(0, slash + 1);
|
|
65
|
+
};
|
|
66
|
+
const RANGE_MARKERS = [["bookmarkStart", "bookmarkEnd"], ["commentRangeStart", "commentRangeEnd"]];
|
|
67
|
+
/**
|
|
68
|
+
* Splices removing range markers whose other half the output does not carry:
|
|
69
|
+
* a bookmark or comment range that started in a block the plan dropped.
|
|
70
|
+
*/
|
|
71
|
+
const orphanMarkerSplices = ({ kept, replaced }) => {
|
|
72
|
+
const splices = [];
|
|
73
|
+
for (const [startName, endName] of RANGE_MARKERS) {
|
|
74
|
+
const starts = /* @__PURE__ */ new Map();
|
|
75
|
+
const ends = /* @__PURE__ */ new Map();
|
|
76
|
+
for (const block of kept) walkElements(block, (element) => {
|
|
77
|
+
let side = null;
|
|
78
|
+
if (isW(element, startName)) side = starts;
|
|
79
|
+
else if (isW(element, endName)) side = ends;
|
|
80
|
+
const range = rangeOf(element);
|
|
81
|
+
const id = wAttr(element, "id");
|
|
82
|
+
if (side === null || range === null || id === null || replaced.some(({ start, end }) => range.start >= start && range.end <= end)) return;
|
|
83
|
+
side.set(id, [...side.get(id) ?? [], element]);
|
|
84
|
+
});
|
|
85
|
+
for (const [own, other] of [[starts, ends], [ends, starts]]) for (const [id, elements] of own) {
|
|
86
|
+
if (other.has(id)) continue;
|
|
87
|
+
for (const element of elements) {
|
|
88
|
+
const range = rangeOf(element);
|
|
89
|
+
if (range !== null) splices.push({
|
|
90
|
+
...range,
|
|
91
|
+
newXml: ""
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return splices;
|
|
97
|
+
};
|
|
98
|
+
const LEVEL_CHILD_ORDER = [
|
|
99
|
+
"start",
|
|
100
|
+
"numFmt",
|
|
101
|
+
"lvlRestart",
|
|
102
|
+
"pStyle",
|
|
103
|
+
"isLgl",
|
|
104
|
+
"suff",
|
|
105
|
+
"lvlText",
|
|
106
|
+
"lvlPicBulletId",
|
|
107
|
+
"legacy",
|
|
108
|
+
"lvlJc",
|
|
109
|
+
"pPr",
|
|
110
|
+
"rPr"
|
|
111
|
+
];
|
|
112
|
+
/** The template numbering part with level patches and new list instances. */
|
|
113
|
+
const editNumbering = (part, { patches, mints }) => {
|
|
114
|
+
const prefixes = partPrefixes(part.root);
|
|
115
|
+
if (prefixes === null) return Result.err(unreadable(part.path, "The numbering part binds no WordprocessingML prefix."));
|
|
116
|
+
const { w } = prefixes;
|
|
117
|
+
const splices = [];
|
|
118
|
+
const insertions = /* @__PURE__ */ new Map();
|
|
119
|
+
const insert = (offset, xml) => {
|
|
120
|
+
insertions.set(offset, [...insertions.get(offset) ?? [], xml]);
|
|
121
|
+
};
|
|
122
|
+
for (const patch of patches) {
|
|
123
|
+
const abstract = wChildren(part.root, "abstractNum").find((element) => integerOrNull(wAttr(element, "abstractNumId")) === patch.abstractNumId);
|
|
124
|
+
const level = wChildren(abstract, "lvl").find((element) => integerOrNull(wAttr(element, "ilvl")) === patch.ilvl);
|
|
125
|
+
const levelRange = level === void 0 ? null : rangeOf(level);
|
|
126
|
+
if (level === void 0 || levelRange === null) return Result.err(new TemplatePlanError({
|
|
127
|
+
code: "numbering-unknown",
|
|
128
|
+
message: `The numbering part has no level ${patch.ilvl} in list definition ${patch.abstractNumId}.`
|
|
129
|
+
}));
|
|
130
|
+
if (elementChildren(level).some((child) => wName(child) === null)) return Result.err(new TemplatePlanError({
|
|
131
|
+
code: "unsupported-content",
|
|
132
|
+
message: `Level ${patch.ilvl} of list definition ${patch.abstractNumId} holds markup a patch cannot change.`
|
|
133
|
+
}));
|
|
134
|
+
const values = {
|
|
135
|
+
...patch.start === void 0 ? {} : { start: String(patch.start) },
|
|
136
|
+
...patch.numFmt === void 0 ? {} : { numFmt: patch.numFmt },
|
|
137
|
+
...patch.suff === void 0 ? {} : { suff: patch.suff },
|
|
138
|
+
...patch.lvlText === void 0 ? {} : { lvlText: patch.lvlText }
|
|
139
|
+
};
|
|
140
|
+
const inner = innerRangeOf(part.xml, level);
|
|
141
|
+
for (const [index, name] of LEVEL_CHILD_ORDER.entries()) {
|
|
142
|
+
const value = values[name];
|
|
143
|
+
if (value === void 0) continue;
|
|
144
|
+
const xml = `<${w}:${name} ${w}:val="${escapeXmlAttribute(value)}"/>`;
|
|
145
|
+
const existing = wChild(level, name);
|
|
146
|
+
const existingRange = existing === null ? null : rangeOf(existing);
|
|
147
|
+
if (existingRange !== null) {
|
|
148
|
+
splices.push({
|
|
149
|
+
...existingRange,
|
|
150
|
+
newXml: xml
|
|
151
|
+
});
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (inner === null) {
|
|
155
|
+
insert(levelRange.end - 2, "");
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const later = LEVEL_CHILD_ORDER.slice(index + 1).map((following) => wChild(level, following)).find((element) => element !== null);
|
|
159
|
+
insert((later === void 0 || later === null ? null : rangeOf(later))?.start ?? inner.end, xml);
|
|
160
|
+
}
|
|
161
|
+
if (inner === null) {
|
|
162
|
+
const children = LEVEL_CHILD_ORDER.flatMap((name) => {
|
|
163
|
+
const value = values[name];
|
|
164
|
+
return value === void 0 ? [] : [`<${w}:${name} ${w}:val="${escapeXmlAttribute(value)}"/>`];
|
|
165
|
+
}).join("");
|
|
166
|
+
insertions.delete(levelRange.end - 2);
|
|
167
|
+
splices.push({
|
|
168
|
+
start: levelRange.end - 2,
|
|
169
|
+
end: levelRange.end,
|
|
170
|
+
newXml: `>${children}</${level.name ?? `${w}:lvl`}>`
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (mints.length > 0) {
|
|
175
|
+
const nums = wChildren(part.root, "num");
|
|
176
|
+
const markup = mints.map(({ numId, baseNumId, abstractNumId, starts }) => {
|
|
177
|
+
const base = nums.find((element) => integerOrNull(wAttr(element, "numId")) === baseNumId);
|
|
178
|
+
const inherited = /* @__PURE__ */ new Map();
|
|
179
|
+
for (const override of wChildren(base, "lvlOverride")) {
|
|
180
|
+
const level = integerOrNull(wAttr(override, "ilvl"));
|
|
181
|
+
if (level !== null) inherited.set(level, override);
|
|
182
|
+
}
|
|
183
|
+
const raw = (element) => {
|
|
184
|
+
const range = element === null || element === void 0 ? null : rangeOf(element);
|
|
185
|
+
return range === null ? "" : part.xml.slice(range.start, range.end);
|
|
186
|
+
};
|
|
187
|
+
const overrides = [.../* @__PURE__ */ new Set([...inherited.keys(), ...starts.keys()])].toSorted((left, right) => left - right).map((level) => {
|
|
188
|
+
const start = starts.get(level);
|
|
189
|
+
const kept = inherited.get(level);
|
|
190
|
+
if (start === void 0) return raw(kept);
|
|
191
|
+
const startOverride = (prefix) => `<${prefix}:startOverride ${prefix}:val="${start}"/>`;
|
|
192
|
+
const keptRange = kept === void 0 ? null : rangeOf(kept);
|
|
193
|
+
const keptInner = kept === void 0 ? null : innerRangeOf(part.xml, kept);
|
|
194
|
+
const keptPrefix = kept?.name?.includes(":") ? kept.name.slice(0, kept.name.indexOf(":")) : null;
|
|
195
|
+
if (kept === void 0 || keptRange === null || keptInner === null || keptPrefix === null) return `<${w}:lvlOverride ${w}:ilvl="${level}">${startOverride(w)}</${w}:lvlOverride>`;
|
|
196
|
+
const replaced = wChild(kept, "startOverride");
|
|
197
|
+
const replacedRange = replaced === null ? null : rangeOf(replaced);
|
|
198
|
+
const rest = replacedRange === null ? part.xml.slice(keptInner.start, keptInner.end) : part.xml.slice(keptInner.start, replacedRange.start) + part.xml.slice(replacedRange.end, keptInner.end);
|
|
199
|
+
return part.xml.slice(keptRange.start, keptInner.start) + startOverride(keptPrefix) + rest + part.xml.slice(keptInner.end, keptRange.end);
|
|
200
|
+
}).join("");
|
|
201
|
+
return `<${w}:num ${w}:numId="${numId}"><${w}:abstractNumId ${w}:val="${abstractNumId}"/>${overrides}</${w}:num>`;
|
|
202
|
+
}).join("");
|
|
203
|
+
const lastNum = nums.at(-1);
|
|
204
|
+
const cleanup = wChild(part.root, "numIdMacAtCleanup");
|
|
205
|
+
const inner = innerRangeOf(part.xml, part.root);
|
|
206
|
+
const at = (lastNum === void 0 ? null : rangeOf(lastNum)?.end) ?? (cleanup === null ? null : rangeOf(cleanup)?.start) ?? inner?.end;
|
|
207
|
+
if (at === void 0) return Result.err(unreadable(part.path, "The numbering part has no place for a new list."));
|
|
208
|
+
insert(at, markup);
|
|
209
|
+
}
|
|
210
|
+
for (const [offset, xmls] of insertions) splices.push({
|
|
211
|
+
start: offset,
|
|
212
|
+
end: offset,
|
|
213
|
+
newXml: xmls.join("")
|
|
214
|
+
});
|
|
215
|
+
const edited = spliceXml(part.xml, splices);
|
|
216
|
+
return edited === null ? Result.err(unreadable(part.path, "The numbering part could not be patched.")) : Result.ok(edited);
|
|
217
|
+
};
|
|
218
|
+
/** Write the output package for a resolved plan. */
|
|
219
|
+
const writeOutput = async ({ source, template, plan, resolved }) => {
|
|
220
|
+
const { pkg } = template;
|
|
221
|
+
const documentPrefixes = partPrefixes(template.document.root);
|
|
222
|
+
const bodyInner = innerRangeOf(template.document.xml, template.body);
|
|
223
|
+
if (documentPrefixes === null || bodyInner === null) return Result.err(unreadable(pkg.documentPath, "The template body cannot be rewritten."));
|
|
224
|
+
const documentDirectory = directoryOf(pkg.documentPath);
|
|
225
|
+
const parts = /* @__PURE__ */ new Map();
|
|
226
|
+
const readTemplateText = async (path) => await readPartText(pkg, path);
|
|
227
|
+
const sourceResources = await readStoryResources(source);
|
|
228
|
+
if (Result.isError(sourceResources)) return sourceResources;
|
|
229
|
+
const sourceMedia = /* @__PURE__ */ new Map();
|
|
230
|
+
for (const [path, bytes] of sourceResources.value.media) {
|
|
231
|
+
const dot = path.lastIndexOf(".");
|
|
232
|
+
sourceMedia.set(path, {
|
|
233
|
+
bytes,
|
|
234
|
+
extension: dot === -1 ? "" : path.slice(dot + 1).toLowerCase()
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const documentRelationshipsXml = await readTemplateText(pkg.documentRelationshipsPath);
|
|
238
|
+
if (Result.isError(documentRelationshipsXml)) return documentRelationshipsXml;
|
|
239
|
+
const documentRelationships = createRelationshipsEditor(pkg.documentRelationshipsPath, documentRelationshipsXml.value);
|
|
240
|
+
if (documentRelationships === null) return Result.err(unreadable(pkg.documentRelationshipsPath, "The template's relationships part is not a relationships part."));
|
|
241
|
+
const takenPaths = new Set([...pkg.paths].map((path) => path.toLowerCase()));
|
|
242
|
+
const notePartState = async (kind) => {
|
|
243
|
+
const existing = kind === "footnote" ? template.footnotes : template.endnotes;
|
|
244
|
+
const path = existing.path ?? `${documentDirectory}${NOTE_PARTS[kind].fileName}`;
|
|
245
|
+
const prefixes = existing.part === null ? documentPrefixes : partPrefixes(existing.part.root);
|
|
246
|
+
if (prefixes === null) return Result.err(unreadable(path, "The notes part binds no WordprocessingML prefix."));
|
|
247
|
+
const relationshipsPath = relationshipsPathFor(path);
|
|
248
|
+
const relationshipsXml = await readTemplateText(pkg.paths.has(relationshipsPath) ? relationshipsPath : null);
|
|
249
|
+
if (Result.isError(relationshipsXml)) return relationshipsXml;
|
|
250
|
+
const relationships = createRelationshipsEditor(relationshipsPath, relationshipsXml.value);
|
|
251
|
+
if (relationships === null) return Result.err(unreadable(relationshipsPath, "A notes relationships part is not a relationships part."));
|
|
252
|
+
return Result.ok({
|
|
253
|
+
kind,
|
|
254
|
+
path,
|
|
255
|
+
existing,
|
|
256
|
+
prefixes,
|
|
257
|
+
relationships,
|
|
258
|
+
nextId: maxOf(existing.usedIds, 0) + 1,
|
|
259
|
+
pathTaken: existing.path === null && takenPaths.has(path.toLowerCase()),
|
|
260
|
+
allocated: /* @__PURE__ */ new Map()
|
|
261
|
+
});
|
|
262
|
+
};
|
|
263
|
+
const footnoteState = await notePartState("footnote");
|
|
264
|
+
if (Result.isError(footnoteState)) return footnoteState;
|
|
265
|
+
const endnoteState = await notePartState("endnote");
|
|
266
|
+
if (Result.isError(endnoteState)) return endnoteState;
|
|
267
|
+
const noteParts = {
|
|
268
|
+
footnote: footnoteState.value,
|
|
269
|
+
endnote: endnoteState.value
|
|
270
|
+
};
|
|
271
|
+
const media = /* @__PURE__ */ new Map();
|
|
272
|
+
const mediaPaths = /* @__PURE__ */ new Set();
|
|
273
|
+
let unsupportedMedia = null;
|
|
274
|
+
let drawingId = 0;
|
|
275
|
+
const noteDrawingIds = (root) => {
|
|
276
|
+
walkElements(root, (element) => {
|
|
277
|
+
if (getLocalName(element.name) !== "docPr") return;
|
|
278
|
+
const id = integerOrNull(String(element.attributes?.["id"] ?? ""));
|
|
279
|
+
if (id !== null && id > drawingId) drawingId = id;
|
|
280
|
+
});
|
|
281
|
+
};
|
|
282
|
+
noteDrawingIds(template.document.root);
|
|
283
|
+
for (const notes of [template.footnotes, template.endnotes]) if (notes.part !== null) noteDrawingIds(notes.part.root);
|
|
284
|
+
const headersAndFooters = await readHeaderFooterParts(template);
|
|
285
|
+
if (Result.isError(headersAndFooters)) return headersAndFooters;
|
|
286
|
+
const headerFooterParts = headersAndFooters.value;
|
|
287
|
+
for (const part of headerFooterParts) noteDrawingIds(part.root);
|
|
288
|
+
const shared = {
|
|
289
|
+
styles: templateCharacterStyles(template),
|
|
290
|
+
sourceRelationships: sourceResources.value.relationships,
|
|
291
|
+
sourceMedia,
|
|
292
|
+
resolveSourceTarget: sourceResources.value.resolveTarget,
|
|
293
|
+
noteId: (kind, sourceId) => {
|
|
294
|
+
const state = noteParts[kind];
|
|
295
|
+
const known = state.allocated.get(sourceId);
|
|
296
|
+
if (known !== void 0) return known;
|
|
297
|
+
const id = state.nextId;
|
|
298
|
+
state.nextId += 1;
|
|
299
|
+
state.allocated.set(sourceId, id);
|
|
300
|
+
return id;
|
|
301
|
+
},
|
|
302
|
+
addMedia: (sourcePath, sourceItem) => {
|
|
303
|
+
let entry = media.get(sourcePath);
|
|
304
|
+
if (entry === void 0) {
|
|
305
|
+
if (MEDIA_CONTENT_TYPES[sourceItem.extension] === void 0) unsupportedMedia ??= sourcePath;
|
|
306
|
+
let index = media.size + 1;
|
|
307
|
+
let path = `${documentDirectory}media/placed${index}.${sourceItem.extension}`;
|
|
308
|
+
while (pkg.paths.has(path) || mediaPaths.has(path)) {
|
|
309
|
+
index += 1;
|
|
310
|
+
path = `${documentDirectory}media/placed${index}.${sourceItem.extension}`;
|
|
311
|
+
}
|
|
312
|
+
mediaPaths.add(path);
|
|
313
|
+
entry = {
|
|
314
|
+
path,
|
|
315
|
+
media: sourceItem
|
|
316
|
+
};
|
|
317
|
+
media.set(sourcePath, entry);
|
|
318
|
+
}
|
|
319
|
+
return `/${entry.path}`;
|
|
320
|
+
},
|
|
321
|
+
nextDrawingId: () => {
|
|
322
|
+
drawingId += 1;
|
|
323
|
+
return drawingId;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
const documentContext = {
|
|
327
|
+
...shared,
|
|
328
|
+
prefixes: documentPrefixes,
|
|
329
|
+
relationships: documentRelationships
|
|
330
|
+
};
|
|
331
|
+
const instructions = new Map(resolved.references.map(({ reference, instruction }) => [reference, instruction]));
|
|
332
|
+
const instructionOf = (segment) => segment.kind === "reference" ? instructions.get(segment.reference) ?? null : null;
|
|
333
|
+
const emitOf = (paragraph) => ({
|
|
334
|
+
paragraph,
|
|
335
|
+
bookmark: resolved.bookmarks.get(paragraph),
|
|
336
|
+
instructionOf,
|
|
337
|
+
styleBindsList: styleNumbering(paragraph.styleId ?? template.defaultStyleId, template.styles, template.numbering)?.kind === "reference"
|
|
338
|
+
});
|
|
339
|
+
const templateSplices = [...freezeFields(template.document, resolved.freezeKinds).splices];
|
|
340
|
+
const replaced = [];
|
|
341
|
+
const slots = [...resolved.nestedSlots, ...resolved.items.flatMap((item) => item.kind === "slot" ? [item] : [])];
|
|
342
|
+
for (const { templateBlock, paragraph } of slots) {
|
|
343
|
+
const content = paragraphContentXml(emitOf(paragraph), documentContext);
|
|
344
|
+
if (Result.isError(content)) return content;
|
|
345
|
+
const range = rangeOf(templateBlock.element);
|
|
346
|
+
if (range === null) return Result.err(unreadable(pkg.documentPath, "A slot paragraph has no source range."));
|
|
347
|
+
const inner = innerRangeOf(template.document.xml, templateBlock.element);
|
|
348
|
+
if (inner === null) {
|
|
349
|
+
const name = templateBlock.element.name ?? `${documentPrefixes.w}:p`;
|
|
350
|
+
templateSplices.push({
|
|
351
|
+
start: range.end - 2,
|
|
352
|
+
end: range.end,
|
|
353
|
+
newXml: `>${content.value}</${name}>`
|
|
354
|
+
});
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const properties = wChild(templateBlock.element, "pPr");
|
|
358
|
+
const start = (properties === null ? null : rangeOf(properties)?.end) ?? inner.start;
|
|
359
|
+
templateSplices.push({
|
|
360
|
+
start,
|
|
361
|
+
end: inner.end,
|
|
362
|
+
newXml: content.value
|
|
363
|
+
});
|
|
364
|
+
replaced.push({
|
|
365
|
+
start,
|
|
366
|
+
end: inner.end
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
const bodySection = wChild(template.body, "sectPr");
|
|
370
|
+
const keptElements = [
|
|
371
|
+
...resolved.keptTemplateBlocks.map(({ element }) => element),
|
|
372
|
+
...resolved.items.flatMap((item) => item.kind === "slot" ? [item.templateBlock.element] : []),
|
|
373
|
+
...bodySection === null ? [] : [bodySection]
|
|
374
|
+
];
|
|
375
|
+
templateSplices.push(...orphanMarkerSplices({
|
|
376
|
+
kept: keptElements,
|
|
377
|
+
replaced
|
|
378
|
+
}));
|
|
379
|
+
const documentSplices = withoutContained(templateSplices);
|
|
380
|
+
const keptXml = (element) => {
|
|
381
|
+
const range = rangeOf(element);
|
|
382
|
+
const xml = range === null ? null : sliceWithSplices(template.document.xml, range, documentSplices);
|
|
383
|
+
return xml === null ? Result.err(unreadable(pkg.documentPath, "A template block could not be carried over.")) : Result.ok(xml);
|
|
384
|
+
};
|
|
385
|
+
const body = [];
|
|
386
|
+
for (const item of resolved.items) {
|
|
387
|
+
let xml;
|
|
388
|
+
switch (item.kind) {
|
|
389
|
+
case "template":
|
|
390
|
+
xml = keptXml(item.block.element);
|
|
391
|
+
break;
|
|
392
|
+
case "slot":
|
|
393
|
+
xml = keptXml(item.templateBlock.element);
|
|
394
|
+
break;
|
|
395
|
+
case "paragraph":
|
|
396
|
+
xml = paragraphXml(emitOf(item.paragraph), documentContext);
|
|
397
|
+
break;
|
|
398
|
+
case "table":
|
|
399
|
+
xml = tableXml({
|
|
400
|
+
table: item.block.element,
|
|
401
|
+
styleId: item.styleId,
|
|
402
|
+
paragraphOf: (element) => {
|
|
403
|
+
const paragraph = item.cells.get(element);
|
|
404
|
+
return paragraph === void 0 ? Result.ok("") : paragraphXml(emitOf(paragraph), documentContext);
|
|
405
|
+
}
|
|
406
|
+
}, documentContext);
|
|
407
|
+
break;
|
|
408
|
+
default: return item;
|
|
409
|
+
}
|
|
410
|
+
if (Result.isError(xml)) return xml;
|
|
411
|
+
body.push(xml.value);
|
|
412
|
+
}
|
|
413
|
+
if (bodySection !== null) {
|
|
414
|
+
const section = keptXml(bodySection);
|
|
415
|
+
if (Result.isError(section)) return section;
|
|
416
|
+
body.push(section.value);
|
|
417
|
+
}
|
|
418
|
+
const documentXml = spliceXml(template.document.xml, [{
|
|
419
|
+
start: bodyInner.start,
|
|
420
|
+
end: bodyInner.end,
|
|
421
|
+
newXml: body.join("")
|
|
422
|
+
}]);
|
|
423
|
+
if (documentXml === null) return Result.err(unreadable(pkg.documentPath, "The new body could not be written."));
|
|
424
|
+
parts.set(pkg.documentPath, documentXml);
|
|
425
|
+
const newContentTypes = [];
|
|
426
|
+
for (const kind of ["footnote", "endnote"]) {
|
|
427
|
+
const state = noteParts[kind];
|
|
428
|
+
const definition = NOTE_PARTS[kind];
|
|
429
|
+
const sourceNotes = kind === "footnote" ? source.footnotes : source.endnotes;
|
|
430
|
+
const context = {
|
|
431
|
+
...shared,
|
|
432
|
+
prefixes: state.prefixes,
|
|
433
|
+
relationships: state.relationships
|
|
434
|
+
};
|
|
435
|
+
const { w } = state.prefixes;
|
|
436
|
+
const markup = [];
|
|
437
|
+
for (const [sourceId, id] of state.allocated) {
|
|
438
|
+
const note = sourceNotes.byId.get(sourceId);
|
|
439
|
+
const xml = note === void 0 ? Result.ok(`<${w}:${kind} ${w}:id="${id}"><${w}:p/></${w}:${kind}>`) : noteXml({
|
|
440
|
+
kind,
|
|
441
|
+
id,
|
|
442
|
+
note,
|
|
443
|
+
source,
|
|
444
|
+
fields: sourceNotes.state.fields
|
|
445
|
+
}, context);
|
|
446
|
+
if (Result.isError(xml)) return xml;
|
|
447
|
+
markup.push(xml.value);
|
|
448
|
+
}
|
|
449
|
+
let partXml = null;
|
|
450
|
+
if (state.existing.part !== null) {
|
|
451
|
+
const frozen = spliceXml(state.existing.part.xml, freezeFields(state.existing.part, resolved.freezeKinds).splices);
|
|
452
|
+
if (frozen === null) return Result.err(unreadable(state.path, "The notes part could not be rewritten."));
|
|
453
|
+
const appended = markup.length === 0 ? frozen : appendToXmlRoot(frozen, {
|
|
454
|
+
rootName: state.existing.part.root.name ?? "",
|
|
455
|
+
markup: markup.join("")
|
|
456
|
+
});
|
|
457
|
+
partXml = appended === state.existing.part.xml ? null : appended;
|
|
458
|
+
} else if (markup.length > 0) {
|
|
459
|
+
if (state.pathTaken) return Result.err(new TemplatePlanError({
|
|
460
|
+
code: "unsupported-content",
|
|
461
|
+
message: `The template keeps another part at ${state.path}, where its ${kind}s would go.`,
|
|
462
|
+
part: state.path
|
|
463
|
+
}));
|
|
464
|
+
const separators = [-1, 0].map((id, index) => `<${w}:${kind} ${w}:type="${index === 0 ? "separator" : "continuationSeparator"}" ${w}:id="${id}"><${w}:p><${w}:r><${w}:${index === 0 ? "separator" : "continuationSeparator"}/></${w}:r></${w}:p></${w}:${kind}>`).join("");
|
|
465
|
+
partXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><${w}:${definition.root} xmlns:${w}="${state.prefixes.wUri}" xmlns:${state.prefixes.r}="${RELATIONSHIPS_NAMESPACE}">${separators}${markup.join("")}</${w}:${definition.root}>`;
|
|
466
|
+
documentRelationships.add({
|
|
467
|
+
type: definition.relationshipType,
|
|
468
|
+
target: definition.fileName,
|
|
469
|
+
external: false
|
|
470
|
+
});
|
|
471
|
+
newContentTypes.push({
|
|
472
|
+
partName: `/${state.path}`,
|
|
473
|
+
contentType: definition.contentType
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
if (partXml !== null) parts.set(state.path, partXml);
|
|
477
|
+
const relationshipsXml = state.relationships.xml();
|
|
478
|
+
if (relationshipsXml !== null) parts.set(state.relationships.path, relationshipsXml);
|
|
479
|
+
}
|
|
480
|
+
if (unsupportedMedia !== null) return Result.err(new TemplatePlanError({
|
|
481
|
+
code: "unsupported-content",
|
|
482
|
+
message: "A picture of the source is in a format the output cannot declare.",
|
|
483
|
+
part: unsupportedMedia
|
|
484
|
+
}));
|
|
485
|
+
for (const { path, media: item } of media.values()) {
|
|
486
|
+
parts.set(path, item.bytes);
|
|
487
|
+
newContentTypes.push({
|
|
488
|
+
partName: `/${path}`,
|
|
489
|
+
contentType: MEDIA_CONTENT_TYPES[item.extension] ?? ""
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const documentRelationshipsOut = documentRelationships.xml();
|
|
493
|
+
if (documentRelationshipsOut !== null) parts.set(pkg.documentRelationshipsPath, documentRelationshipsOut);
|
|
494
|
+
if (newContentTypes.length > 0) {
|
|
495
|
+
const contentTypes = await readTemplateText(CONTENT_TYPES_PATH);
|
|
496
|
+
if (Result.isError(contentTypes)) return contentTypes;
|
|
497
|
+
if (contentTypes.value === null) return Result.err(new TemplatePlanError({
|
|
498
|
+
code: "part-missing",
|
|
499
|
+
message: "The template has no content-type registry.",
|
|
500
|
+
part: CONTENT_TYPES_PATH
|
|
501
|
+
}));
|
|
502
|
+
const typesRoot = readRawPart(CONTENT_TYPES_PATH, contentTypes.value)?.root;
|
|
503
|
+
if (typesRoot === void 0 || getLocalName(typesRoot.name) !== "Types" || typesRoot.namespaceUri !== NAMESPACES.ct) return Result.err(unreadable(CONTENT_TYPES_PATH, "The template's content-type registry is not one."));
|
|
504
|
+
parts.set(CONTENT_TYPES_PATH, registerContentTypeParts(contentTypes.value, newContentTypes));
|
|
505
|
+
}
|
|
506
|
+
const patches = plan.numberingPatches ?? [];
|
|
507
|
+
if (patches.length > 0 || resolved.mints.length > 0) {
|
|
508
|
+
const numberingPart = template.numberingPath === null || template.numberingXml === null ? null : readRawPart(template.numberingPath, template.numberingXml);
|
|
509
|
+
if (numberingPart === null) return Result.err(new TemplatePlanError({
|
|
510
|
+
code: "numbering-unknown",
|
|
511
|
+
message: "The template has no numbering part to patch."
|
|
512
|
+
}));
|
|
513
|
+
const numbering = editNumbering(numberingPart, {
|
|
514
|
+
patches,
|
|
515
|
+
mints: resolved.mints
|
|
516
|
+
});
|
|
517
|
+
if (Result.isError(numbering)) return numbering;
|
|
518
|
+
parts.set(numberingPart.path, numbering.value);
|
|
519
|
+
}
|
|
520
|
+
if (resolved.freezeKinds.size > 0) for (const part of headerFooterParts) {
|
|
521
|
+
const { splices } = freezeFields(part, resolved.freezeKinds);
|
|
522
|
+
if (splices.length === 0) continue;
|
|
523
|
+
const frozen = spliceXml(part.xml, splices);
|
|
524
|
+
if (frozen === null) return Result.err(unreadable(part.path, "A header or footer could not be rewritten."));
|
|
525
|
+
parts.set(part.path, frozen);
|
|
526
|
+
}
|
|
527
|
+
const updateOnOpen = plan.fields?.updateOnOpen;
|
|
528
|
+
if (updateOnOpen !== void 0) {
|
|
529
|
+
const settingsPath = pkg.partPath("settings");
|
|
530
|
+
const settingsXml = await readTemplateText(settingsPath);
|
|
531
|
+
if (Result.isError(settingsXml)) return settingsXml;
|
|
532
|
+
if (settingsPath === null || settingsXml.value === null) {
|
|
533
|
+
if (updateOnOpen) return Result.err(new TemplatePlanError({
|
|
534
|
+
code: "part-missing",
|
|
535
|
+
message: "The template has no settings part to set update-on-open in."
|
|
536
|
+
}));
|
|
537
|
+
} else {
|
|
538
|
+
const settings = setUpdateFieldsOnOpen(settingsXml.value, updateOnOpen);
|
|
539
|
+
if (settings === null) return Result.err(unreadable(settingsPath, "The settings part could not be updated."));
|
|
540
|
+
if (settings !== settingsXml.value) parts.set(settingsPath, settings);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return await Result.tryPromise({
|
|
544
|
+
try: async () => {
|
|
545
|
+
const zip = await ZipArchive.read(pkg.bytes);
|
|
546
|
+
for (const [path, content] of parts) {
|
|
547
|
+
const current = zip.entry(path);
|
|
548
|
+
zip.set(path, content, current === void 0 ? {} : { modified: current.modified });
|
|
549
|
+
}
|
|
550
|
+
return await zip.generate();
|
|
551
|
+
},
|
|
552
|
+
catch: (cause) => new TemplatePlanError({
|
|
553
|
+
code: "archive-unreadable",
|
|
554
|
+
message: "The output package could not be written.",
|
|
555
|
+
cause
|
|
556
|
+
})
|
|
557
|
+
});
|
|
558
|
+
};
|
|
559
|
+
const applyUnguarded = async ({ source, template, plan, options }) => {
|
|
560
|
+
const analyzedSource = await analyzeDocument(source);
|
|
561
|
+
if (Result.isError(analyzedSource)) return analyzedSource;
|
|
562
|
+
const analyzedTemplate = await analyzeDocument(template);
|
|
563
|
+
if (Result.isError(analyzedTemplate)) return analyzedTemplate;
|
|
564
|
+
const resolved = resolvePlan(analyzedSource.value, analyzedTemplate.value, plan);
|
|
565
|
+
if (Result.isError(resolved)) return resolved;
|
|
566
|
+
const written = await writeOutput({
|
|
567
|
+
source: analyzedSource.value,
|
|
568
|
+
template: analyzedTemplate.value,
|
|
569
|
+
plan,
|
|
570
|
+
resolved: resolved.value
|
|
571
|
+
});
|
|
572
|
+
if (Result.isError(written)) return written;
|
|
573
|
+
const report = await reportTemplatePlanOutput({
|
|
574
|
+
source: analyzedSource.value,
|
|
575
|
+
template: analyzedTemplate.value,
|
|
576
|
+
output: written.value,
|
|
577
|
+
plan,
|
|
578
|
+
resolved: resolved.value,
|
|
579
|
+
options
|
|
580
|
+
});
|
|
581
|
+
if (Result.isError(report)) return report;
|
|
582
|
+
if (!report.value.ok) return Result.err(new TemplatePlanError({
|
|
583
|
+
code: "verification-failed",
|
|
584
|
+
message: `The output failed verification: ${report.value.issues.slice(0, 3).map(({ message }) => message).join(" ")}`,
|
|
585
|
+
report: report.value
|
|
586
|
+
}));
|
|
587
|
+
return Result.ok({
|
|
588
|
+
docx: written.value,
|
|
589
|
+
report: report.value
|
|
590
|
+
});
|
|
591
|
+
};
|
|
592
|
+
/**
|
|
593
|
+
* Apply `source` onto `template` as `plan` says and verify the result.
|
|
594
|
+
*
|
|
595
|
+
* The plan names blocks by id and pins them by hash; the text itself always
|
|
596
|
+
* comes from the source. The output is refused, with the report attached,
|
|
597
|
+
* unless every placed block reads back identical.
|
|
598
|
+
*/
|
|
599
|
+
const applyTemplatePlan = async (input) => await guarded(async () => await applyUnguarded(input));
|
|
600
|
+
export { applyTemplatePlan };
|