@docx-editor.dev/core 0.0.1 → 2.1.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 (116) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +91 -2
  3. package/THIRD_PARTY_NOTICES.md +18 -0
  4. package/dist/automation.cjs +1 -0
  5. package/dist/automation.d.cts +74 -0
  6. package/dist/automation.d.ts +74 -0
  7. package/dist/automation.js +1 -0
  8. package/dist/binding.cjs +1 -0
  9. package/dist/binding.d.cts +88 -0
  10. package/dist/binding.d.ts +88 -0
  11. package/dist/binding.js +1 -0
  12. package/dist/chunk-2DTQDAN7.js +2 -0
  13. package/dist/chunk-3JKQE4QJ.cjs +2 -0
  14. package/dist/chunk-4WWEDTTE.js +2 -0
  15. package/dist/chunk-6WIIHJFY.js +1 -0
  16. package/dist/chunk-7VQ7YLW3.cjs +1 -0
  17. package/dist/chunk-BS554B6D.cjs +2 -0
  18. package/dist/chunk-BZK64YU3.cjs +10 -0
  19. package/dist/chunk-CZFUMACF.cjs +12 -0
  20. package/dist/chunk-GQQOL4PV.js +1 -0
  21. package/dist/chunk-HBL3NNH5.cjs +1 -0
  22. package/dist/chunk-JQFDLZXQ.cjs +2 -0
  23. package/dist/chunk-O2WQY7IT.cjs +5 -0
  24. package/dist/chunk-PC76F2HR.cjs +1 -0
  25. package/dist/chunk-QRAUDDVY.js +2 -0
  26. package/dist/chunk-REZUWYB7.js +1 -0
  27. package/dist/chunk-STCITBJK.js +12 -0
  28. package/dist/chunk-TBBXCC7D.js +5 -0
  29. package/dist/chunk-TSXT537P.cjs +12 -0
  30. package/dist/chunk-WOGYVM3W.js +12 -0
  31. package/dist/chunk-Y7TA7TPF.js +10 -0
  32. package/dist/content-control-walk-CbTqHq6O.d.cts +56 -0
  33. package/dist/content-control-walk-D06GijR0.d.ts +56 -0
  34. package/dist/contracts/document.cjs +1 -0
  35. package/dist/contracts/document.d.cts +246 -0
  36. package/dist/contracts/document.d.ts +246 -0
  37. package/dist/contracts/document.js +0 -0
  38. package/dist/contracts/editor.cjs +1 -0
  39. package/dist/contracts/editor.d.cts +11 -0
  40. package/dist/contracts/editor.d.ts +11 -0
  41. package/dist/contracts/editor.js +1 -0
  42. package/dist/contracts/interaction.cjs +1 -0
  43. package/dist/contracts/interaction.d.cts +11 -0
  44. package/dist/contracts/interaction.d.ts +11 -0
  45. package/dist/contracts/interaction.js +0 -0
  46. package/dist/contracts/modules.cjs +1 -0
  47. package/dist/contracts/modules.d.cts +117 -0
  48. package/dist/contracts/modules.d.ts +117 -0
  49. package/dist/contracts/modules.js +1 -0
  50. package/dist/contracts/types.cjs +1 -0
  51. package/dist/contracts/types.d.cts +452 -0
  52. package/dist/contracts/types.d.ts +452 -0
  53. package/dist/contracts/types.js +0 -0
  54. package/dist/custom-node-writes-YqISlSRl.d.cts +885 -0
  55. package/dist/custom-node-writes-ttKuYd0M.d.ts +885 -0
  56. package/dist/editor-B93PggnR.d.cts +1690 -0
  57. package/dist/editor-CFsSrxGR.d.ts +1690 -0
  58. package/dist/editor.cjs +1 -0
  59. package/dist/editor.css +7106 -0
  60. package/dist/editor.d.cts +271 -0
  61. package/dist/editor.d.ts +271 -0
  62. package/dist/editor.js +1 -0
  63. package/dist/hf-references-BdjsQNE_.d.ts +71 -0
  64. package/dist/hf-references-CgEOSw3i.d.cts +71 -0
  65. package/dist/image-resources-C_YnqPhn.d.ts +203 -0
  66. package/dist/image-resources-DwpNnTg3.d.cts +203 -0
  67. package/dist/index-BjZelfWL.d.cts +2532 -0
  68. package/dist/index-DP1yJJ3R.d.ts +2532 -0
  69. package/dist/index.cjs +1 -0
  70. package/dist/index.d.cts +22 -0
  71. package/dist/index.d.ts +22 -0
  72. package/dist/index.js +1 -0
  73. package/dist/layout.cjs +1 -0
  74. package/dist/layout.d.cts +2366 -0
  75. package/dist/layout.d.ts +2366 -0
  76. package/dist/layout.js +1 -0
  77. package/dist/note-nodes-BPSTVDMr.d.ts +108 -0
  78. package/dist/note-nodes-C6DLxlvj.d.cts +108 -0
  79. package/dist/ooxml-package-CR5us6ad.d.cts +354 -0
  80. package/dist/ooxml-package-D_CtywTW.d.ts +354 -0
  81. package/dist/ooxml-tree-BU0e3DVi.d.cts +871 -0
  82. package/dist/ooxml-tree-BU0e3DVi.d.ts +871 -0
  83. package/dist/output.cjs +1 -0
  84. package/dist/output.d.cts +158 -0
  85. package/dist/output.d.ts +158 -0
  86. package/dist/output.js +1 -0
  87. package/dist/protocol-BWVA3Q1p.d.ts +1255 -0
  88. package/dist/protocol-FAz_nPm_.d.cts +1255 -0
  89. package/dist/review-reads-CsoXSvUg.d.ts +401 -0
  90. package/dist/review-reads-qW0jvdF1.d.cts +401 -0
  91. package/dist/review-support-D64Wu236.d.cts +358 -0
  92. package/dist/review-support-nsLXC9jf.d.ts +358 -0
  93. package/dist/revision-projection-72ZApe-g.d.cts +84 -0
  94. package/dist/revision-projection-DHAkcD_L.d.ts +84 -0
  95. package/dist/semantic-cell-selection-D_8RbPII.d.ts +427 -0
  96. package/dist/semantic-cell-selection-DwLB71fF.d.cts +427 -0
  97. package/dist/semantic-interaction-CXH2wFqi.d.ts +187 -0
  98. package/dist/semantic-interaction-DqcEonqD.d.cts +187 -0
  99. package/dist/semantic-paint-drawings-B5Wk2so5.d.ts +21 -0
  100. package/dist/semantic-paint-drawings-x8g44lD_.d.cts +21 -0
  101. package/dist/semantic-records-COVFW5aS.d.cts +1505 -0
  102. package/dist/semantic-records-zTC0_1zi.d.ts +1505 -0
  103. package/dist/shaped-measurer-AFnFxoot.d.cts +613 -0
  104. package/dist/shaped-measurer-CZXL-a6v.d.ts +613 -0
  105. package/dist/store.cjs +1 -0
  106. package/dist/store.d.cts +2153 -0
  107. package/dist/store.d.ts +2153 -0
  108. package/dist/store.js +1 -0
  109. package/dist/tree-op-types-DWLCllG7.d.ts +1486 -0
  110. package/dist/tree-op-types-UOXlRUqQ.d.cts +1486 -0
  111. package/dist/tree-session-BtVFXsF6.d.ts +580 -0
  112. package/dist/tree-session-DxIOHUOD.d.cts +580 -0
  113. package/dist/tree-store-B1lEkdXc.d.cts +273 -0
  114. package/dist/tree-store-BscFPB7x.d.ts +273 -0
  115. package/package.json +110 -8
  116. package/index.js +0 -1
@@ -0,0 +1,2153 @@
1
+ import { e as ResourceLimits } from './image-resources-DwpNnTg3.cjs';
2
+ export { C as CreateImageResourceCacheOptions, D as DEFAULT_IMAGE_RESOURCE_LIMITS, f as DEFAULT_LIMITS, H as HARD_CEILINGS, g as IMAGE_RESOURCE_HARD_CEILINGS, b as ImageDecodePort, c as ImageResourceLimits, h as ImageResourceLookup, I as ImageResourceState, M as MAX_SVG_SNIFF_BYTES, P as PreservedImageMime, S as SupportedImageMime, i as ValidatedRasterHeader, j as createImageResourceCache, k as hasBoundedSvgRoot, l as imageResourceLookupFor, m as liveDrawingReferenceCount, r as resolveImageResourceLimits, n as resolveLimits, s as sniffImageMime, o as validateGifHeader, p as validateJpegHeader, q as validatePngHeader, v as validateRasterHeader } from './image-resources-DwpNnTg3.cjs';
3
+ import { O as OoxmlPackage, R as RelationshipRecord } from './ooxml-package-CR5us6ad.cjs';
4
+ export { C as ContentTypeError, c as ContentTypeIndex, d as ContentTypeRecords, D as DEFAULT_OOXML_PACKAGE_LIMITS, e as DEFAULT_ZIP_LIMITS, f as DefaultRecord, I as IMAGE_RELATIONSHIP_TYPE, g as ImageRelationshipResolution, h as IndexResult, N as NameRejection, i as NameResult, j as OoxmlExternalTarget, a as OoxmlPackageLimits, b as OoxmlPackageRejection, k as OoxmlPackageResult, l as OverrideRecord, m as RelationshipError, n as RelationshipSetResult, o as ResolveResult, p as ResolvedRelationship, T as TargetMode, Z as ZipLimits, q as ZipReadResult, r as ZipRejection, s as asciiFold, t as buildContentTypeIndex, u as buildRelationshipSet, v as detectDuplicateNames, w as extensionKey, x as isValidMime, y as normalizePartName, z as partNameKey, A as readOoxmlPackage, B as readZip, E as resolveContentType, F as resolveImageRelationship, G as resolveInternalTarget, H as resolveRelationship, J as validateExternalTarget, K as withPart, L as writeOoxmlPackage, M as writeZip } from './ooxml-package-CR5us6ad.cjs';
5
+ import { e as OoxmlPart, O as OoxmlNode, r as OoxmlInvariantResult, a as OoxmlElement, s as OoxmlInvariantIssue, t as OoxmlHardBreakNode, f as OoxmlParagraphNode, u as OoxmlFldCharNode, v as OoxmlFldSimpleNode, w as OoxmlInstrTextNode, x as OoxmlAttribute } from './ooxml-tree-BU0e3DVi.cjs';
6
+ export { y as OOXML_NODE_IDENTITY_RULES, z as OoxmlBodyNode, A as OoxmlBookmarkEndNode, B as OoxmlBookmarkStartNode, C as OoxmlContentControlCalendarNode, D as OoxmlContentControlCheckboxNode, E as OoxmlContentControlCheckedNode, F as OoxmlContentControlCheckedStateNode, G as OoxmlContentControlComboBoxNode, d as OoxmlContentControlContentNode, H as OoxmlContentControlDataBindingNode, I as OoxmlContentControlDateFormatNode, J as OoxmlContentControlDateNode, K as OoxmlContentControlDropDownListNode, p as OoxmlContentControlEndPropertiesNode, L as OoxmlContentControlLidNode, M as OoxmlContentControlListItemNode, b as OoxmlContentControlNode, q as OoxmlContentControlPropertiesNode, N as OoxmlContentControlStoreMappedDataAsNode, P as OoxmlContentControlTextNode, Q as OoxmlContentControlUncheckedStateNode, h as OoxmlContinuationSeparatorNode, R as OoxmlDocumentNode, i as OoxmlEndnotesNode, j as OoxmlFootnotesNode, c as OoxmlGenericElementNode, S as OoxmlGenericExtensionAttribute, T as OoxmlHyperlinkNode, U as OoxmlInvariantIssueCode, V as OoxmlKnownNodeAttribute, W as OoxmlNamespaceBinding, Y as OoxmlNodeId, Z as OoxmlNodeIdentityRules, g as OoxmlNoteNode, k as OoxmlNoteRefNode, l as OoxmlNoteReferenceNode, _ as OoxmlParagraphPropertiesNode, $ as OoxmlPartMetadata, n as OoxmlReadRejection, a0 as OoxmlReadResult, a1 as OoxmlRunNode, a2 as OoxmlRunPropertiesNode, m as OoxmlSeparatorNode, a3 as OoxmlTabNode, a4 as OoxmlTextElementNode, a5 as OoxmlTextNode, a6 as OoxmlWmlValAttribute, a7 as OoxmlXmlSpaceAttribute, a8 as WML_NAMESPACE_URI, a9 as XMLNS_NAMESPACE_URI, aa as XML_NAMESPACE_URI, X as XmlLimits, ab as XmlNode, ac as XmlRejection, ad as XmlResult, ae as childElements, af as findElement, ag as isContentRevisionKind, ah as isRangeMarkerKind, ai as readOnOffChild, aj as readOoxmlPart, ak as readXml, al as textContent } from './ooxml-tree-BU0e3DVi.cjs';
7
+ export { e as BookmarkAnchor, B as BookmarkIndex, f as CascadeDeletedNoteReferencesOptions, g as CustomNodePayloadRead, h as CustomNodePayloadWrite, b as CustomNodeSweepOutcome, i as CustomNodeSweepResult, j as CustomNodeWriteRejection, C as CustomNodeWriteResult, k as DEFAULT_MAX_EDITABLE_STORY_PARTS, D as DocumentTrackingSettings, l as DrawingPropertyIdResult, E as EmbeddedFont, F as FontStyleKey, H as HeaderFooterLifecycleImpact, m as HeaderFooterLifecycleOp, n as HeaderFooterLifecycleRejection, o as HeaderFooterLifecycleResult, I as InsertCustomNodeWrite, L as ListKind, M as MAX_CUSTOM_NODE_LABEL_LENGTH, p as MAX_CUSTOM_NODE_PAYLOAD_LENGTH, q as MAX_NOTE_REFERENCE_PARTS, r as MAX_NOTE_REFERENCE_SCAN, N as NO_TRACKING_SETTINGS, s as NoteDiagnostic, t as NoteDiagnosticCode, u as NoteLifecycleImpact, v as NoteLifecycleOp, w as NoteLifecycleOptions, x as NoteLifecycleRejection, y as NoteLifecycleResult, z as NoteReferenceHit, G as NoteReferenceScanBudget, P as PackageTransactResult, J as ReadEmbeddedFontsOptions, K as StoryResolveResult, S as StoryScope, a as StoryTargetRejection, T as TreePackageStore, O as TreePackageStoreOptions, Q as allocateDrawingPropertyId, U as applyHeaderFooterLifecycleOp, V as applyNoteLifecycleOp, W as buildBookmarkIndex, X as cascadeDeletedNoteReferences, Y as collectNoteReferences, Z as collectPackageNoteReferences, _ as createNoteReferenceScanBudget, $ as customNodePayloadsByControl, a0 as customNodePayloadsOf, a1 as deobfuscateFont, a2 as diagnoseNoteReferences, a3 as ensureListDefinition, a4 as ensureNumberingLevel, a5 as insertCustomNodeWrite, a6 as isHeaderFooterLifecycleOp, a7 as isNoteLifecycleOp, a8 as normalNoteIds, a9 as notesPartHasId, aa as readEmbeddedFonts, ab as readTrackingSettings, ac as removeCustomNodeWrite, ad as resolveNotesPart, ae as sweepCustomNodePayloads, af as withBinaryPart, ag as withEmbeddedImage, ah as withoutUnreferencedImagePart } from './custom-node-writes-YqISlSRl.cjs';
8
+ export { c as HeaderFooterKind, a as HeaderFooterParts, b as HeaderFooterSectionResolution, d as HeaderFooterSlotMeta, H as HeaderFooterVariant, e as collectSectionPropertyNodes, r as resolveHeaderFooterParts, f as resolveHeaderFooterPartsBySection, g as resolveHeaderFooterResolutionBySection } from './hf-references-CgEOSw3i.cjs';
9
+ export { c as collectFlowBlocks, d as contentControlContentOf, i as isContentControl, b as isContentControlContent, w as walkAllStoryParagraphs, e as walkParagraphInline, f as walkStoryBlocks } from './content-control-walk-CbTqHq6O.cjs';
10
+ import { T as TreeDocOp, a as TreeOpRejection, q as TreeOpResult, O as OoxmlProperty, m as DrawingTreeDocOp, I as ImpactClass, b as ImageWrapTarget } from './tree-op-types-UOXlRUqQ.cjs';
11
+ export { A as ACCEPTED_PARAGRAPH_PROPERTIES, r as ACCEPTED_RUN_PROPERTIES, s as CONTENT_CONTROL_ID_MAX, t as CONTENT_CONTROL_PROPERTY_ORDER, u as ContentControlCheckbox, v as ContentControlCheckboxState, p as ContentControlDataBinding, w as ContentControlDateFormat, x as ContentControlEntry, C as ContentControlKind, n as ContentControlLevel, y as ContentControlListItem, o as ContentControlLock, z as ContentControlProperties, c as DrawingKind, e as DrawingLocks, d as DrawingPositionInput, H as HYPERLINK_RELATIONSHIP_TYPE, B as HyperlinkKind, E as HyperlinkTarget, i as IMAGE_WRAP_TARGETS, M as MAX_CONTENT_CONTROLS_PER_PART, F as MAX_CONTENT_CONTROL_NESTING, G as OFFICE_RELATIONSHIP_NAMESPACE_URI, J as RelationshipTargetResolver, R as RevisionAddress, S as SourceCrop, K as TABLE_BORDER_STYLES, L as TREE_DOC_OP_KINDS, l as TableBorderStyle, N as TreeDocOpKind, P as TreeOpEffect, Q as allocateContentControlId, U as contentControlContentChildren, W as contentControlContentNodeOf, X as contentControlEndPropertiesNodeOf, Y as contentControlLevelOf, Z as contentControlPropertiesNodeOf, _ as contentControlPropertiesOf, $ as contentControlTextOf, a0 as contentControlsIn, a1 as findContentControl, a2 as flattenContentControls, a3 as hyperlinkAnchorOf, a4 as hyperlinkRelationshipIdOf, a5 as hyperlinkTargetOf, a6 as isContentControlContentNode, a7 as isContentControlNode, a8 as isContentControlWrapper, a9 as isHyperlinkNode, aa as lockForbidsEdit, ab as lockForbidsRemoval, ac as orderedContentControlProperties, ad as parseContentControlId, ae as projectDrawing, af as resolveContentControlLock } from './tree-op-types-UOXlRUqQ.cjs';
12
+ export { A as AtomicNoteSpan, M as MAX_NOTES_PER_PART, a as NOTE_ATOM_CHAR, b as NOTE_CONTINUATION_SEPARATOR_ID, c as NOTE_ID_MAX, d as NOTE_ID_MIN, e as NOTE_SEPARATOR_ID, N as NoteKind, f as NoteType, g as allocateNoteId, h as atomicNoteSpansOf, i as customMarkFollows, j as findNoteById, k as formatNoteScopeId, l as isContinuationSeparatorNode, m as isEndnotesNode, o as isFootnotesNode, p as isNormalNote, q as isNoteAtomNode, r as isNoteNode, s as isNoteRefNode, t as isNoteReferenceNode, u as isSeparatorNode, v as noteAtomText, w as noteIdOf, x as noteKindOf, y as noteRefKindOf, z as noteReferenceKindOf, n as noteTypeOf, B as notesOf, C as parseNoteId, D as parseNoteScopeId } from './note-nodes-C6DLxlvj.cjs';
13
+ export { A as AuthoredNoteProperties, C as CommentAnchor, b as CommentPosition, c as CommentRecord, d as CommentThreadState, D as DEFAULT_ENDNOTE_PROPERTIES, e as DEFAULT_FOOTNOTE_PROPERTIES, E as EndnotePosition, F as FootnotePosition, L as LinkableReviewItem, N as NoteNumRestart, a as ResolvedEndnoteProperties, R as ResolvedFootnoteProperties, f as ReviewCommentItem, g as ReviewItem, h as ReviewModelInput, i as ReviewPosition, j as ReviewRange, k as ReviewRevisionItem, l as ReviewRevisionKind, W as W15_NAMESPACE_URI, m as authoredDocumentEndnoteProperties, n as authoredDocumentFootnoteProperties, o as authoredEndnotePropertiesFromSectPr, q as authoredFootnotePropertiesFromSectPr, r as collectReviewItems, s as commentAnchorsOfStory, t as commentBodyText, u as commentInitials, v as commentItemsOf, w as commentsOfPart, x as deepParagraphOrderOfPart, y as firstReviewRange, z as isLegalEndnotePosition, B as isLegalFootnotePosition, G as isLegalNumRestart, H as linkRevisionReplies, p as paragraphOrderOfPart, I as parseAuthoredNoteProperties, J as resolveEndnoteProperties, K as resolveFootnoteProperties, M as reviewItemKey, O as reviewItemRanges, P as revisionItemsOf, Q as settingsPartOf, S as threadStateOfPart } from './review-reads-qW0jvdF1.cjs';
14
+ import { T as TreeModelChange, b as TreeDocumentStore } from './tree-store-B1lEkdXc.cjs';
15
+ export { S as SelectionMark, f as TreeDocumentStoreOptions, a as TreeStoryRef, d as TreeTransactOptions, g as TreeTransactResult, c as TreeTransactionContext } from './tree-store-B1lEkdXc.cjs';
16
+
17
+ /**
18
+ * Every kind of thing the registry gives a stable identity to.
19
+ *
20
+ * Identity is `(kind, id)` plus version and NEVER registration order, so two bundles contributing
21
+ * the same command resolve deterministically regardless of which loaded first.
22
+ */
23
+ declare const ID_KINDS: readonly ["extension", "capability", "command", "query", "schema", "dependencyKey", "runtimePort", "result", "origin"];
24
+ /** One of {@link ID_KINDS}. */
25
+ /** One of {@link ID_KINDS} — which sort of thing an identifier names. */
26
+ type IdKind = (typeof ID_KINDS)[number];
27
+ /**
28
+ * Whether a string is a well-formed identifier in either accepted grammar.
29
+ *
30
+ * Reverse-domain (`dev.docx-editor.core.command.insert-text`) or package-owned
31
+ * (`@docx-editor.dev/engine-core#command/insert-text`). Ids are opaque once validated.
32
+ */
33
+ declare function isValidId(id: string): boolean;
34
+ /**
35
+ * Validate an identifier, throwing when it is malformed.
36
+ *
37
+ * Throws rather than returning: a bad id is an author mistake at registration time, not file
38
+ * input, and accepting it would produce a registry whose identities silently collide.
39
+ */
40
+ declare function assertValidId(id: string, kind?: IdKind): void;
41
+ /** A validated (kind, id, version) triple — the registry's unit of identity. */
42
+ interface CapabilityId {
43
+ readonly kind: IdKind;
44
+ readonly id: string;
45
+ readonly version: string;
46
+ }
47
+
48
+ /** A parsed semantic version. Only the three numeric components — no pre-release or build. */
49
+ interface SemVer {
50
+ readonly major: number;
51
+ readonly minor: number;
52
+ readonly patch: number;
53
+ }
54
+ /**
55
+ * Parse a semantic version, rejecting anything the registry's rules do not need.
56
+ *
57
+ * Deliberately narrow: an unsupported range form is refused rather than accepted, so a malformed
58
+ * range can never masquerade as "compatible".
59
+ */
60
+ declare function parseSemVer(input: string): SemVer;
61
+ /** Order two versions: negative, zero or positive, by major then minor then patch. */
62
+ declare function compareSemVer(a: SemVer, b: SemVer): -1 | 0 | 1;
63
+ /**
64
+ * Whether `version` satisfies `range`. Supported range grammar:
65
+ * - `*` any version
66
+ * - `1.2.3` exact
67
+ * - `^1.2.3` caret: same major, and >= the floor (major 0 pins the minor)
68
+ * - `>=1.2.3 <2.0.0` a single lower (inclusive) + upper (exclusive) bound pair
69
+ * Any other shape throws — an unparseable range is a registration error, not a pass.
70
+ */
71
+ declare function satisfies(version: string, range: string): boolean;
72
+
73
+ /**
74
+ * Why registry resolution failed.
75
+ *
76
+ * Every code names a declaration conflict a bundle author can fix — a missing dependency, an
77
+ * unsatisfied version range, a duplicate contribution with no replacement policy.
78
+ */
79
+ type RegistryErrorCode = 'invalid-id' | 'invalid-version' | 'duplicate-extension' | 'id-collision' | 'replacement-target-missing' | 'unauthorized-replacement' | 'replacement-version-mismatch' | 'ambiguous-replacement' | 'missing-dependency' | 'dependency-cycle' | 'conflict' | 'missing-port';
80
+ /**
81
+ * A resolution failure naming every responsible party.
82
+ *
83
+ * Thrown rather than returned: an unresolvable registry is a build-time composition mistake, and
84
+ * an engine running with a half-resolved registry would fail later in ways that do not point back
85
+ * to the bundle that caused it.
86
+ */
87
+ declare class RegistryError extends Error {
88
+ readonly code: RegistryErrorCode;
89
+ /** Stable identities responsible for the failure (extensions, ids). */
90
+ readonly responsible: readonly string[];
91
+ constructor(code: RegistryErrorCode, message: string,
92
+ /** Stable identities responsible for the failure (extensions, ids). */
93
+ responsible?: readonly string[]);
94
+ }
95
+ /** How a base contribution permits replacement by other bundles. */
96
+ type ReplacementPolicy = {
97
+ readonly kind: 'none';
98
+ } | {
99
+ readonly kind: 'single';
100
+ } | {
101
+ readonly kind: 'priority';
102
+ };
103
+ /** One thing a bundle contributes: a command, a query, a schema, a port, keyed by `(kind, id)`. */
104
+ interface Contribution {
105
+ readonly kind: Exclude<IdKind, 'extension' | 'origin' | 'result'>;
106
+ readonly id: string;
107
+ readonly version: string;
108
+ /** If set, this contribution replaces an existing base contribution. */
109
+ readonly replaces?: {
110
+ readonly targetId: string;
111
+ readonly targetRange: string;
112
+ readonly priority?: number;
113
+ };
114
+ /** Policy this contribution exposes to would-be replacers (default `none`). */
115
+ readonly replaceable?: ReplacementPolicy;
116
+ readonly payload?: unknown;
117
+ }
118
+ /**
119
+ * A unit of engine functionality: its identity, version, dependencies, conflicts, required ports,
120
+ * and contributions.
121
+ *
122
+ * The registry's whole input. Everything a bundle needs and everything it offers is DECLARED, so
123
+ * resolution can be deterministic and order-independent.
124
+ */
125
+ interface FeatureBundle {
126
+ readonly id: string;
127
+ readonly version: string;
128
+ readonly dependencies?: readonly string[];
129
+ readonly conflicts?: readonly string[];
130
+ readonly requiredPorts?: readonly string[];
131
+ readonly contributions: readonly Contribution[];
132
+ }
133
+ /** The resolved result: every contribution selected, indexed by `(kind, id)`. */
134
+ interface ResolvedRegistry {
135
+ readonly extensions: ReadonlyMap<string, FeatureBundle>;
136
+ readonly contributions: ReadonlyMap<string, Contribution>;
137
+ get(kind: Contribution['kind'], id: string): Contribution | undefined;
138
+ }
139
+ /** How resolution treats optional bundles and replacement policies. */
140
+ interface ResolveOptions {
141
+ /** Runtime port ids available in this environment (design D9 / task 0.3). */
142
+ readonly availablePorts?: readonly string[];
143
+ }
144
+ /**
145
+ * Resolve a set of bundles into one registry, or throw.
146
+ *
147
+ * Deterministic and registration-order independent: selection is by `(kind, id)` plus version,
148
+ * and ties break only on declared policy. Array order never decides anything.
149
+ *
150
+ * @throws RegistryError naming every bundle responsible for the failure.
151
+ */
152
+ declare function resolve(bundles: readonly FeatureBundle[], options?: ResolveOptions): ResolvedRegistry;
153
+
154
+ /**
155
+ * Typed-origin domains (design D5 / ADR-S5). `mutation.*` are the canonical
156
+ * write origins; `projection` and `awareness` MUST NOT enter history, audit,
157
+ * snapshots, or replication.
158
+ */
159
+ declare const ORIGIN_IDS: {
160
+ readonly mutationHuman: "dev.docx-editor.core.origin.mutation.human";
161
+ readonly mutationAgent: "dev.docx-editor.core.origin.mutation.agent";
162
+ readonly mutationRemote: "dev.docx-editor.core.origin.mutation.remote";
163
+ readonly mutationUndo: "dev.docx-editor.core.origin.mutation.undo";
164
+ readonly mutationRedo: "dev.docx-editor.core.origin.mutation.redo";
165
+ readonly mutationMigration: "dev.docx-editor.core.origin.mutation.migration";
166
+ readonly mutationRepair: "dev.docx-editor.core.origin.mutation.repair";
167
+ readonly mutationServer: "dev.docx-editor.core.origin.mutation.server";
168
+ readonly projection: "dev.docx-editor.core.origin.projection";
169
+ readonly awareness: "dev.docx-editor.core.origin.awareness";
170
+ };
171
+ /** Canonical writes carry a mutation origin; these are the undoable-eligibility inputs. */
172
+ declare const CANONICAL_MUTATION_ORIGINS: readonly string[];
173
+ /** Origins that never enter authored state / history / audit / snapshot / replication. */
174
+ declare const NON_CANONICAL_ORIGINS: readonly string[];
175
+ /**
176
+ * Result taxonomy (design D8 / task 7.8). A transport/protocol failure that
177
+ * prevents a valid envelope is a typed exception, not a member here.
178
+ */
179
+ declare const RESULT_IDS: {
180
+ readonly applied: "dev.docx-editor.core.result.applied";
181
+ readonly validation: "dev.docx-editor.core.result.validation";
182
+ readonly conflict: "dev.docx-editor.core.result.conflict";
183
+ readonly resource: "dev.docx-editor.core.result.resource";
184
+ readonly authorization: "dev.docx-editor.core.result.authorization";
185
+ readonly aborted: "dev.docx-editor.core.result.aborted";
186
+ };
187
+ /** Runtime ports (extensions-and-runtime-ports spec; design D9). */
188
+ declare const RUNTIME_PORT_IDS: {
189
+ readonly fonts: "dev.docx-editor.core.port.fonts";
190
+ readonly shaping: "dev.docx-editor.core.port.shaping";
191
+ readonly images: "dev.docx-editor.core.port.images";
192
+ readonly clock: "dev.docx-editor.core.port.clock";
193
+ readonly identity: "dev.docx-editor.core.port.identity";
194
+ readonly persistence: "dev.docx-editor.core.port.persistence";
195
+ readonly transport: "dev.docx-editor.core.port.transport";
196
+ readonly scheduling: "dev.docx-editor.core.port.scheduling";
197
+ readonly audit: "dev.docx-editor.core.port.audit";
198
+ readonly authorization: "dev.docx-editor.core.port.authorization";
199
+ readonly resourceAccounting: "dev.docx-editor.core.port.resource-accounting";
200
+ readonly cancellation: "dev.docx-editor.core.port.cancellation";
201
+ readonly externalResourceConsent: "dev.docx-editor.core.port.external-resource-consent";
202
+ };
203
+ /** Layout dependency keys (design D6 / task 8.2). */
204
+ declare const DEPENDENCY_KEY_IDS: {
205
+ readonly style: "dev.docx-editor.core.dep.style";
206
+ readonly numbering: "dev.docx-editor.core.dep.numbering";
207
+ readonly section: "dev.docx-editor.core.dep.section";
208
+ readonly story: "dev.docx-editor.core.dep.story";
209
+ readonly font: "dev.docx-editor.core.dep.font";
210
+ readonly image: "dev.docx-editor.core.dep.image";
211
+ readonly table: "dev.docx-editor.core.dep.table";
212
+ readonly field: "dev.docx-editor.core.dep.field";
213
+ readonly note: "dev.docx-editor.core.dep.note";
214
+ readonly headerFooter: "dev.docx-editor.core.dep.header-footer";
215
+ readonly annotation: "dev.docx-editor.core.dep.annotation";
216
+ };
217
+ /** Every frozen id as a flat list, for the immutability / uniqueness gate. */
218
+ declare const ALL_FROZEN_IDS: readonly string[];
219
+
220
+ /**
221
+ * A counter's limit was reached. Carries the label, the limit, and what was attempted.
222
+ *
223
+ * Thrown at the N → N+1 boundary, so the increment that would have crossed the limit never
224
+ * happens rather than being detected afterwards.
225
+ */
226
+ declare class LimitExceededError extends Error {
227
+ readonly label: string;
228
+ readonly limit: number;
229
+ readonly attempted: number;
230
+ constructor(label: string, limit: number, attempted: number);
231
+ }
232
+ /**
233
+ * Overflow-safe counting against a fixed limit.
234
+ *
235
+ * Never silently wraps: it rejects the increment that would cross its limit AND any arithmetic
236
+ * that would exceed `Number.MAX_SAFE_INTEGER`. That second guard is the point — a file-supplied
237
+ * count must never be trusted into an allocation, and a wrapped counter reads as small.
238
+ */
239
+ declare class BoundedCounter {
240
+ readonly label: string;
241
+ readonly limit: number;
242
+ private value;
243
+ constructor(label: string, limit: number);
244
+ get current(): number;
245
+ /** Remaining headroom before the limit. */
246
+ get remaining(): number;
247
+ /**
248
+ * Add `n` (default 1). Throws LimitExceededError if the result would exceed the
249
+ * limit (so `limit` itself is reachable but `limit + 1` is not) or overflow the
250
+ * safe-integer range. On rejection the counter is unchanged.
251
+ */
252
+ add(n?: number): number;
253
+ /** Whether adding `n` would be accepted, without mutating. */
254
+ canAdd(n?: number): boolean;
255
+ release(n: number): void;
256
+ }
257
+
258
+ /** A budget was misused: over-carved, over-reserved, or disposed with children outstanding. */
259
+ declare class BudgetError extends Error {
260
+ constructor(message: string);
261
+ }
262
+ /**
263
+ * Capacity claimed BEFORE it is allocated.
264
+ *
265
+ * Reserve-then-allocate rather than allocate-then-check: discovering the overrun after the
266
+ * allocation has already happened defeats the point of having a budget.
267
+ */
268
+ interface Reservation {
269
+ readonly amount: number;
270
+ readonly released: boolean;
271
+ release(): void;
272
+ }
273
+ /**
274
+ * One node in the hierarchical resource budget tree.
275
+ *
276
+ * An operation owns a root budget; parsers, extensions, workers, layout, transport and output
277
+ * carve children from it, so no subsystem can consume more than the operation as a whole allows.
278
+ *
279
+ * `dispose()` REFUSES while children or reservations are outstanding, then runs registered
280
+ * cleanups LIFO — spill files, worker termination — even if one throws. A leaked child budget is a
281
+ * leaked worker, so the refusal is the diagnostic.
282
+ */
283
+ declare class Budget {
284
+ readonly label: string;
285
+ readonly capacity: number;
286
+ private readonly used;
287
+ private readonly children;
288
+ private activeReservations;
289
+ private readonly cleanups;
290
+ private disposed;
291
+ private carveAmount;
292
+ private parent?;
293
+ constructor(label: string, capacity: number);
294
+ get inUse(): number;
295
+ get available(): number;
296
+ get isDisposed(): boolean;
297
+ /** Reserve `amount` from this budget. Throws if it would exceed capacity. */
298
+ reserve(amount: number): Reservation;
299
+ /** Carve a child budget of `capacity` out of this budget's headroom. */
300
+ child(label: string, capacity: number): Budget;
301
+ /** Register cleanup for a spill file, worker, or queue tied to this budget. */
302
+ onRelease(cleanup: () => void): void;
303
+ /**
304
+ * Release this budget. Refuses while any child budget or reservation is
305
+ * outstanding (children must finish first). Runs cleanups LIFO, returns the
306
+ * carve-out to the parent, and marks disposed. Cleanup errors are collected and
307
+ * rethrown after every cleanup has run.
308
+ */
309
+ dispose(): void;
310
+ private assertLive;
311
+ }
312
+
313
+ /**
314
+ * Which side of the point of no return an operation is on.
315
+ *
316
+ * Canonical publication is that point. Cancelling BEFORE it rolls the whole operation back;
317
+ * cancelling after it leaves the commit standing and cancels only derived work — layout, export,
318
+ * caches.
319
+ */
320
+ type CancellationPhase = 'pre-publication' | 'post-publication';
321
+ /** Thrown from a `checkpoint()` when the operation has been cancelled. */
322
+ declare class CancellationError extends Error {
323
+ /** True when the commit is already published and only derived work is cancelled. */
324
+ readonly derivedOnly: boolean;
325
+ constructor(
326
+ /** True when the commit is already published and only derived work is cancelled. */
327
+ derivedOnly: boolean, reason?: string);
328
+ }
329
+ /**
330
+ * The read side of cancellation, handed to cooperative work.
331
+ *
332
+ * Cooperative rather than pre-emptive: long work calls `checkpoint()` at declared intervals, which
333
+ * is what lets an operation unwind promptly without the engine having to interrupt it mid-mutation.
334
+ */
335
+ interface CancellationToken {
336
+ readonly isCancelled: boolean;
337
+ readonly phase: CancellationPhase;
338
+ /** True only when cancelled AND the commit is already published. */
339
+ readonly derivedOnly: boolean;
340
+ /** Throws CancellationError if cancelled; call at declared checkpoint intervals. */
341
+ checkpoint(): void;
342
+ }
343
+ /**
344
+ * The write side of cancellation, and the owner of the phase.
345
+ *
346
+ * Whoever starts an operation holds this; everything it calls gets only the token.
347
+ */
348
+ declare class CancellationController {
349
+ private _cancelled;
350
+ private _phase;
351
+ private _reason?;
352
+ cancel(reason?: string): void;
353
+ /** Mark canonical publication — the point of no return. */
354
+ markPublished(): void;
355
+ get isCancelled(): boolean;
356
+ get phase(): CancellationPhase;
357
+ get isPublished(): boolean;
358
+ /** Cancelled after publication -> full rollback is no longer possible. */
359
+ get derivedOnly(): boolean;
360
+ get token(): CancellationToken;
361
+ }
362
+
363
+ /** Injectable time source — the engine never calls Date.now directly (determinism). */
364
+ interface ClockPort {
365
+ now(): number;
366
+ }
367
+ /** Stable id minting for sessions, commits, and allocator seeds. */
368
+ interface IdentityPort {
369
+ newId(): string;
370
+ }
371
+ /** Cooperative scheduling of deferred work. */
372
+ interface SchedulingPort {
373
+ schedule(task: () => void): void;
374
+ }
375
+ /** Redacted observability sink (raw text never enters here — design D5). */
376
+ interface AuditPort {
377
+ record(entry: {
378
+ readonly kind: string;
379
+ readonly at: number;
380
+ readonly meta?: Record<string, unknown>;
381
+ }): void;
382
+ }
383
+ /** Read/write/export authorization decisions. */
384
+ interface AuthorizationPort {
385
+ authorize(action: string, subject?: string): boolean;
386
+ }
387
+ /** Explicit consent gate for any remote/external resource (no zero-click fetch). */
388
+ interface ExternalResourceConsentPort {
389
+ requestConsent(target: string): boolean;
390
+ }
391
+ /** Cancellation source for the current operation. */
392
+ interface CancellationPort {
393
+ readonly token: CancellationToken;
394
+ }
395
+ /** Where documents are stored and retrieved. Opaque marker until its milestone. */
396
+ interface PersistencePort {
397
+ readonly kind: 'persistence';
398
+ }
399
+ /** How the engine talks to a remote peer. Opaque marker until its milestone. */
400
+ interface TransportPort {
401
+ readonly kind: 'transport';
402
+ }
403
+ /** Where font bytes come from. Opaque marker until its milestone. */
404
+ interface FontPort {
405
+ readonly kind: 'font';
406
+ }
407
+ /** Which shaping backend measures text. Opaque marker until its milestone. */
408
+ interface ShapingPort {
409
+ readonly kind: 'shaping';
410
+ }
411
+ /** How image bytes are decoded. Opaque marker until its milestone. */
412
+ interface ImagePort {
413
+ readonly kind: 'image';
414
+ }
415
+ /** Where resource consumption is reported. Opaque marker until its milestone. */
416
+ interface ResourceAccountingPort {
417
+ readonly kind: 'resource-accounting';
418
+ }
419
+ /**
420
+ * A required port the runtime did not provide.
421
+ *
422
+ * Thrown rather than falling back: silently reaching for a browser global when a worker or server
423
+ * adapter did not supply a port is exactly the coupling ports exist to prevent.
424
+ */
425
+ declare class PortResolutionError extends Error {
426
+ readonly portId: string;
427
+ constructor(portId: string);
428
+ }
429
+ /**
430
+ * The environment-dependent services an engine instance may reach.
431
+ *
432
+ * Everything outside pure computation — the clock, identity minting, scheduling, fonts, images —
433
+ * is reached only through here, which is what lets browser, worker and server adapters supply
434
+ * only what their runtime actually offers.
435
+ */
436
+ declare class PortRegistry {
437
+ private readonly ports;
438
+ provide(portId: string, port: unknown): this;
439
+ has(portId: string): boolean;
440
+ /** Resolve a port by id or throw. */
441
+ resolve<T>(portId: string): T;
442
+ /** Assert every id in `portIds` is present; returns the missing ones (empty if all present). */
443
+ missing(portIds: readonly string[]): string[];
444
+ /** The provided port ids (for bridging to registry.resolve availablePorts). */
445
+ availablePorts(): string[];
446
+ clock(): ClockPort;
447
+ identity(): IdentityPort;
448
+ }
449
+ /** Deterministic clock: starts at `start` and advances by `step` each call. */
450
+ declare class DeterministicClock implements ClockPort {
451
+ private readonly step;
452
+ private t;
453
+ constructor(start?: number, step?: number);
454
+ now(): number;
455
+ }
456
+ /** Sequential identity for tests and deterministic fixtures. */
457
+ declare class SequentialIdentity implements IdentityPort {
458
+ private readonly prefix;
459
+ private n;
460
+ constructor(prefix?: string);
461
+ newId(): string;
462
+ }
463
+
464
+ /** What one operation is started with. Only `ports` is required. */
465
+ interface OperationInit {
466
+ readonly ports: PortRegistry;
467
+ readonly limits?: Partial<ResourceLimits>;
468
+ readonly config?: Readonly<Record<string, unknown>>;
469
+ /** Root budget capacity in abstract units (default: the byte decompression limit). */
470
+ readonly capacity?: number;
471
+ /** Operation identity (from IdentityPort in production); defaulted for tests. */
472
+ readonly id?: string;
473
+ }
474
+ /**
475
+ * The frozen environment of one operation: its limits, config, ports, root budget and
476
+ * cancellation controller.
477
+ *
478
+ * IMMUTABLE for the operation's lifetime, which is what lets cache reuse and replica agreement
479
+ * key on it. A new operation always gets a fresh snapshot rather than observing a mutated one.
480
+ */
481
+ interface OperationContext {
482
+ readonly id: string;
483
+ readonly limits: ResourceLimits;
484
+ readonly config: Readonly<Record<string, unknown>>;
485
+ readonly ports: PortRegistry;
486
+ readonly budget: Budget;
487
+ readonly cancellation: CancellationController;
488
+ }
489
+ /**
490
+ * Begin an operation, capturing its immutable environment snapshot.
491
+ *
492
+ * Resolves and freezes limits and configuration, carves the root budget, and creates the
493
+ * cancellation controller — everything downstream work needs, fixed for the operation's duration.
494
+ */
495
+ declare function beginOperation(init: OperationInit): OperationContext;
496
+ /** Release the operation's root budget (requires every child/reservation released). */
497
+ declare function endOperation(ctx: OperationContext): void;
498
+
499
+ /** What a limit counts. Typed so a byte cap and a depth cap cannot be compared by accident. */
500
+ type LimitUnit = 'bytes' | 'count' | 'depth' | 'ratio' | 'passes';
501
+ /**
502
+ * Where a limit is enforced.
503
+ *
504
+ * Declared per limit so enforcement happens at the boundary that can still refuse cheaply — a zip
505
+ * cap checked during layout has already let the bomb decompress.
506
+ */
507
+ type EnforcementPhase = 'package-read' | 'xml-parse' | 'layout' | 'output';
508
+ /** One limit's unit and enforcement phase — the metadata that makes limits testable uniformly. */
509
+ interface LimitSpec {
510
+ readonly unit: LimitUnit;
511
+ readonly phase: EnforcementPhase;
512
+ }
513
+ /** Unit + enforcement phase for every resource limit. */
514
+ declare const LIMIT_SPECS: Readonly<Record<keyof ResourceLimits, LimitSpec>>;
515
+ /** Every limit name, for iterating the specs and asserting each has a unit and phase. */
516
+ declare const LIMIT_KEYS: (keyof ResourceLimits)[];
517
+ /** A phase-scoped overflow-safe counter for one limit. */
518
+ declare function makeLimitCounter(limits: ResourceLimits, key: keyof ResourceLimits): BoundedCounter;
519
+ /**
520
+ * Deterministic memory substitute. Tracks current and peak "allocated" units
521
+ * against a hard byte ceiling; `allocate` fails closed (LimitExceededError) past
522
+ * the limit. Used in place of process RSS so memory-limit tests are reproducible
523
+ * and cancellation/cleanup can be asserted without a real allocator.
524
+ */
525
+ declare class DeterministicMemoryMeter {
526
+ private readonly counter;
527
+ private current;
528
+ private peak;
529
+ constructor(limitBytes: number);
530
+ allocate(bytes: number): void;
531
+ free(bytes: number): void;
532
+ get currentBytes(): number;
533
+ get peakBytes(): number;
534
+ /** Release everything (cancellation/cleanup path). */
535
+ reset(): void;
536
+ }
537
+ /** Assert the finite-default / hard-ceiling invariant holds for every limit. */
538
+ declare function assertLimitInvariants(): void;
539
+
540
+ /** Any JSON value. The domain canonicalization and stable hashing operate over. */
541
+ type Json = null | boolean | number | string | Json[] | {
542
+ [k: string]: Json;
543
+ };
544
+ /**
545
+ * Produce a canonical string for `value`, dropping any object key whose name is
546
+ * in `ephemera` at any depth. Numbers are emitted losslessly; -0 normalizes to 0;
547
+ * non-finite numbers are rejected (they must never enter a comparator input).
548
+ */
549
+ declare function canonicalize(value: unknown, ephemera?: ReadonlySet<string>): string;
550
+ /** 64-bit FNV-1a over the canonical form, returned as a 16-char hex string. */
551
+ declare function stableHash(value: unknown, ephemera?: ReadonlySet<string>): string;
552
+
553
+ /**
554
+ * How one artifact class is compared.
555
+ *
556
+ * Frozen per artifact: nothing here invents a tolerance for an artifact the spec requires to
557
+ * match exactly.
558
+ */
559
+ type ComparatorMode = 'canonical-exact' | 'exact' | 'tolerance' | 'sync-optimization-only';
560
+ /** One artifact class's comparison mode and its declared ephemera — fields excluded from equality. */
561
+ interface ComparatorDescriptor {
562
+ readonly id: string;
563
+ readonly mode: ComparatorMode;
564
+ /** Object keys excluded from canonical-exact comparison (declared ephemera). */
565
+ readonly ephemera: readonly string[];
566
+ readonly note: string;
567
+ }
568
+ /** The frozen artifact comparator set. */
569
+ declare const COMPARATORS: {
570
+ readonly authoredState: {
571
+ readonly id: "dev.docx-editor.core.comparator.authored-state";
572
+ readonly mode: "canonical-exact";
573
+ readonly ephemera: readonly ["revision", "provenance", "producedAt", "commitId"];
574
+ readonly note: "canonical normalized authored records; ephemera excluded";
575
+ };
576
+ readonly anchor: {
577
+ readonly id: "dev.docx-editor.core.comparator.anchor";
578
+ readonly mode: "exact";
579
+ readonly ephemera: readonly [];
580
+ readonly note: "internal anchor identity/affinity compares exactly";
581
+ };
582
+ readonly yjsStateVector: {
583
+ readonly id: "dev.docx-editor.core.comparator.yjs-state-vector";
584
+ readonly mode: "sync-optimization-only";
585
+ readonly ephemera: readonly [];
586
+ readonly note: "exchange optimization only; never proves update or delete-set coverage";
587
+ };
588
+ readonly shapedRun: {
589
+ readonly id: "dev.docx-editor.core.comparator.shaped-run";
590
+ readonly mode: "exact";
591
+ readonly ephemera: readonly [];
592
+ readonly note: "glyph ids, clusters, and fixed-point advances compare exactly";
593
+ };
594
+ readonly paginationFingerprint: {
595
+ readonly id: "dev.docx-editor.core.comparator.pagination-fingerprint";
596
+ readonly mode: "exact";
597
+ readonly ephemera: readonly [];
598
+ readonly note: "page/column boundaries, break causes, fixed-point geometry compare exactly";
599
+ };
600
+ readonly semanticTree: {
601
+ readonly id: "dev.docx-editor.core.comparator.semantic-tree";
602
+ readonly mode: "exact";
603
+ readonly ephemera: readonly [];
604
+ readonly note: "reading order, roles, headings, alt text compare exactly";
605
+ };
606
+ readonly hitTest: {
607
+ readonly id: "dev.docx-editor.core.comparator.hit-test";
608
+ readonly mode: "exact";
609
+ readonly ephemera: readonly [];
610
+ readonly note: "resolved hit target and cluster affinity compare exactly";
611
+ };
612
+ readonly pdfSemantics: {
613
+ readonly id: "dev.docx-editor.core.comparator.pdf-semantics";
614
+ readonly mode: "canonical-exact";
615
+ readonly ephemera: readonly ["objectNumber", "producer", "creationDate", "modDate", "subsetTag"];
616
+ readonly note: "canonical semantic PDF objects; container ephemera excluded";
617
+ };
618
+ readonly rasterCheckpoint: {
619
+ readonly id: "dev.docx-editor.core.comparator.raster-checkpoint";
620
+ readonly mode: "tolerance";
621
+ readonly ephemera: readonly [];
622
+ readonly note: "documented unavoidable raster comparison; explicit tolerance only";
623
+ };
624
+ readonly benchmarkEvidence: {
625
+ readonly id: "dev.docx-editor.core.comparator.benchmark-evidence";
626
+ readonly mode: "sync-optimization-only";
627
+ readonly ephemera: readonly [];
628
+ readonly note: "diagnostic evidence, not an equivalence basis";
629
+ };
630
+ };
631
+ /** Which frozen comparator to use. */
632
+ type ComparatorName = keyof typeof COMPARATORS;
633
+ /** Whether two artifacts matched, and where they diverged when they did not. */
634
+ interface ComparisonResult {
635
+ readonly equal: boolean;
636
+ /** Canonical forms when unequal (diagnostic). */
637
+ readonly left?: string;
638
+ readonly right?: string;
639
+ }
640
+ /**
641
+ * Compare two artifacts under a named comparator. `canonical-exact` and `exact`
642
+ * compare canonical forms (exact drops no ephemera). `tolerance` requires an
643
+ * epsilon and compares finite numbers structurally. `sync-optimization-only`
644
+ * throws — such artifacts are never an equivalence basis.
645
+ */
646
+ declare function compareArtifacts(name: ComparatorName, left: unknown, right: unknown, opts?: {
647
+ epsilon?: number;
648
+ }): ComparisonResult;
649
+ /** Fingerprint an artifact under a named comparator's canonicalization policy. */
650
+ declare function fingerprint(name: ComparatorName, value: unknown): string;
651
+
652
+ /** Whether a recorded conformance step was expected to commit or be refused. */
653
+ type FixtureOutcome = 'applied' | 'aborted' | 'validation' | 'conflict' | 'resource' | 'authorization';
654
+ /** The change one step produced, summarized to what a fixture can compare across runtimes. */
655
+ interface ModelChangeSummary {
656
+ readonly fromRevision: number;
657
+ readonly toRevision: number;
658
+ readonly origin: string;
659
+ readonly dirty: readonly string[];
660
+ readonly dependencyKeys: readonly string[];
661
+ }
662
+ /** Where anchors sat after a step — how a fixture proves positions survived an edit. */
663
+ interface AnchorSnapshot {
664
+ readonly anchorId: string;
665
+ readonly story: string;
666
+ readonly block: string;
667
+ readonly affinity: 'before' | 'after';
668
+ }
669
+ /** What one step must produce: its outcome, its change summary, and its authored-state hash. */
670
+ interface FixtureExpectation {
671
+ readonly outcome: FixtureOutcome;
672
+ /** Present iff outcome === 'applied'; MUST be > baseRevision. */
673
+ readonly committedRevision?: number;
674
+ readonly modelChange?: ModelChangeSummary;
675
+ /** 16-hex authored-state fingerprint (comparator 0.4). */
676
+ readonly authoredStateHash?: string;
677
+ readonly outputHash?: string;
678
+ readonly anchors?: readonly AnchorSnapshot[];
679
+ }
680
+ /** One recorded operation and what it was expected to do. */
681
+ interface FixtureStep {
682
+ readonly baseRevision: number;
683
+ readonly origin: string;
684
+ /** Opaque DocOp payloads (schema owned by section 4). */
685
+ readonly ops: readonly unknown[];
686
+ readonly expect: FixtureExpectation;
687
+ }
688
+ /** Opaque encoded backend bytes (snapshot or replication update). */
689
+ interface EncodedEnvelope {
690
+ readonly kind: 'snapshot' | 'update';
691
+ readonly protocolVersion: number;
692
+ readonly schemaVersion: number;
693
+ readonly documentId: string;
694
+ readonly byteLength: number;
695
+ /** Hex-encoded opaque bytes; length MUST equal byteLength. */
696
+ readonly bytesHex: string;
697
+ }
698
+ /** Which implementation recorded a fixture — local store, Yjs, or a binding. */
699
+ type FixtureSource = {
700
+ readonly kind: 'create';
701
+ } | {
702
+ readonly kind: 'docx';
703
+ readonly sha256: string;
704
+ readonly bytesRef: string;
705
+ };
706
+ /**
707
+ * The frozen conformance container: revisions, origins, operations, changes, snapshots and
708
+ * hashes.
709
+ *
710
+ * The CONTAINER is what is frozen — field names, origin membership, revision monotonicity, hash
711
+ * format. The op and change payloads travel opaquely, so their schemas can evolve without
712
+ * invalidating every recorded fixture.
713
+ */
714
+ interface ConformanceFixture {
715
+ readonly formatVersion: 1;
716
+ readonly documentId: string;
717
+ readonly source: FixtureSource;
718
+ readonly steps: readonly FixtureStep[];
719
+ readonly snapshots?: readonly EncodedEnvelope[];
720
+ readonly updates?: readonly EncodedEnvelope[];
721
+ }
722
+ /** Whether a fixture is well-formed, listing every structural violation. */
723
+ interface ValidationResult {
724
+ readonly valid: boolean;
725
+ readonly errors: readonly string[];
726
+ }
727
+ /** Structurally validate a fixture against the frozen format rules. */
728
+ declare function validateFixture(fixture: ConformanceFixture): ValidationResult;
729
+
730
+ /** The outcome a store reports for one replayed step. */
731
+ interface ReplayOutcome {
732
+ readonly outcome: FixtureOutcome;
733
+ readonly committedRevision?: number;
734
+ /** Canonical authored-state value AFTER the step (hashed via comparator 0.4). */
735
+ readonly authoredState?: unknown;
736
+ }
737
+ /** The interface a conformance runtime implements so one fixture can drive every backend. */
738
+ interface ReplayStore {
739
+ /** Initialize from the fixture source; return the initial revision (0 for create). */
740
+ init(fixture: ConformanceFixture): number;
741
+ /** Apply one step and report what happened. */
742
+ applyStep(step: FixtureStep): ReplayOutcome;
743
+ }
744
+ /** What replaying a fixture produced: per-step outcomes and where they diverged. */
745
+ interface ReplayReport {
746
+ readonly ok: boolean;
747
+ readonly mismatches: readonly string[];
748
+ }
749
+ /**
750
+ * Replay a fixture against a store and check every step's outcome, committed
751
+ * revision, and authored-state fingerprint against the fixture's expectations.
752
+ */
753
+ declare function replayFixture(fixture: ConformanceFixture, store: ReplayStore): ReplayReport;
754
+ /** Hash a store's authored state, so two runtimes replaying one fixture can be compared. */
755
+ declare function hashAuthored(authoredState: unknown): string;
756
+
757
+ /**
758
+ * Keys that must never be assigned from file data.
759
+ *
760
+ * XML attribute names become object keys, and a document controls those names — assigning
761
+ * `__proto__` into an ordinary object is the prototype-pollution hazard this engine audits for.
762
+ */
763
+ declare const DANGEROUS_KEYS: readonly string[];
764
+ /** A file-derived key that would pollute a prototype. Refused, never sanitized-and-accepted. */
765
+ declare class DangerousKeyError extends Error {
766
+ readonly key: string;
767
+ readonly path: string;
768
+ constructor(key: string, path: string);
769
+ }
770
+ /** Whether a key is one of {@link DANGEROUS_KEYS}. */
771
+ declare function isDangerousKey(key: string): boolean;
772
+ /** A fresh null-prototype record — the only object shape parser intermediates use. */
773
+ declare function nullRecord<T = unknown>(): Record<string, T>;
774
+ /**
775
+ * Recursively convert `value` into null-prototype records, rejecting any
776
+ * dangerous object key. Arrays and primitives pass through (arrays rebuilt so no
777
+ * inherited prototype pollution survives). Throws DangerousKeyError on the first
778
+ * unsafe key, naming its path. Cyclic inputs are rejected.
779
+ */
780
+ declare function toSafeRecord(value: unknown, path?: string): unknown;
781
+
782
+ /**
783
+ * Serialize normalized XML from a canonical part using repository-controlled
784
+ * prefixes and validated, escaped names and values. This does not yet replace
785
+ * writeDocx; package integration belongs to the subsequent migration pass.
786
+ */
787
+ declare function serializeOoxmlPart(part: OoxmlPart): string;
788
+ /** Repository-owned namespace-aware semantic XML oracle. */
789
+ declare function canonicalOoxmlFingerprint(value: OoxmlPart | OoxmlNode): string;
790
+ /**
791
+ * Structural equality of two canonical trees, ignoring node ids.
792
+ *
793
+ * Ids differ between two parses of the same bytes, so comparing them would report every reopen as
794
+ * a change. This compares what the document SAYS.
795
+ */
796
+ declare function ooxmlTreesEqual(left: OoxmlPart | OoxmlNode, right: OoxmlPart | OoxmlNode): boolean;
797
+
798
+ /**
799
+ * Validate a parser-created or copy-modified immutable part before publication.
800
+ * Future tree-edit primitives can retain shared nodes and their IDs, while any
801
+ * replacement chooses explicitly whether to retain or allocate identity.
802
+ */
803
+ declare function validateOoxmlPart(part: OoxmlPart): OoxmlInvariantResult;
804
+
805
+ /** Locate `[Content_Types].xml` bytes regardless of zip key spelling. */
806
+ declare function contentTypesPartBytes(pkg: OoxmlPackage): {
807
+ readonly storageKey: string;
808
+ readonly bytes: Uint8Array;
809
+ } | null;
810
+ /**
811
+ * What a package-level invariant walk found wrong.
812
+ *
813
+ * Package invariants are cross-PART: a relationship pointing at a part that does not exist, or a
814
+ * part no content-type record covers. Neither is visible from inside a single part's tree.
815
+ */
816
+ type PackageInvariantCode = 'dangling-relationship' | 'missing-content-type'
817
+ /** A part occupies a name OPC reserves for package infrastructure. */
818
+ | 'reserved-part-name'
819
+ /** Two parts whose names differ only by case, which OPC treats as one part. */
820
+ | 'duplicate-part-name'
821
+ /** A part name the OPC screens refuse; `writeZip` would throw on save. */
822
+ | 'unsafe-part-name';
823
+ /** One package invariant violation, located by part name and relationship id. */
824
+ interface PackageInvariantIssue {
825
+ readonly code: PackageInvariantCode;
826
+ /** The part the issue is about: the missing target, or the part with no type. */
827
+ readonly partName: string;
828
+ /** For a dangling relationship, the owner that points at nothing. */
829
+ readonly ownerPart?: string;
830
+ }
831
+ /** Whether a package satisfies its cross-part invariants, listing every violation otherwise. */
832
+ type PackageInvariantResult = {
833
+ readonly ok: true;
834
+ } | {
835
+ readonly ok: false;
836
+ readonly issues: readonly PackageInvariantIssue[];
837
+ };
838
+ /** Relationship records owned by one part, in authored order. */
839
+ declare function relationshipsOf(pkg: OoxmlPackage, ownerPart: string): readonly RelationshipRecord[];
840
+ /** The content type that resolves for a part name, or null when nothing declares one. */
841
+ declare function resolveContentTypeOf(pkg: OoxmlPackage, partName: string): string | null;
842
+ /** The `.rels` part that owns a part's relationships, by OPC convention. */
843
+ declare function relsPartNameFor(partName: string): string;
844
+ /**
845
+ * Declare a content type for a part, by upserting an `<Override>` in the content-types tree.
846
+ *
847
+ * A no-op when the part already resolves to the same type, so repeating a write does not append
848
+ * a duplicate entry. Resolving to a DIFFERENT type replaces the existing Override in place.
849
+ * `forceOverride` writes an explicit Override even when a Default already matches.
850
+ */
851
+ declare function withContentTypeOverride(pkg: OoxmlPackage, partName: string, contentType: string, options?: {
852
+ readonly forceOverride?: boolean;
853
+ }): OoxmlPackage;
854
+ /** What {@link withoutPart} answers: `ok: false` leaves the package exactly as it was. */
855
+ interface WithoutPartResult {
856
+ readonly pkg: OoxmlPackage;
857
+ readonly ok: boolean;
858
+ }
859
+ /** Add or replace one relationship on a part, returning a new package. */
860
+ declare function withRelationship(pkg: OoxmlPackage, ownerPart: string, type: string, rawTarget: string): {
861
+ readonly pkg: OoxmlPackage;
862
+ readonly relationshipId: string;
863
+ readonly ok: boolean;
864
+ };
865
+ /**
866
+ * Add a part that does not exist yet, with the content-type override it needs to be openable.
867
+ *
868
+ * Deliberately does NOT create a relationship: a part is reachable because something points at
869
+ * it, and which part points at it is the caller's decision. Creating one here would guess.
870
+ */
871
+ declare function withNewPart(pkg: OoxmlPackage, partName: string, root: OoxmlElement, contentType: string): OoxmlPackage;
872
+ /**
873
+ * The two invariants a package must satisfy before it is published.
874
+ *
875
+ * Both describe the half-written state that splitting a multi-part write across transactions
876
+ * produces, and both make a package Word refuses to open:
877
+ *
878
+ * - a relationship pointing at a part nobody created;
879
+ * - a part with no content type, which is unopenable even though the XML is well formed.
880
+ *
881
+ * Checked at the commit boundary rather than inside each primitive, for the same reason part
882
+ * validation moved there: a transaction is allowed to pass through an inconsistent intermediate
883
+ * as long as nothing can observe it.
884
+ */
885
+ declare function validatePackageInvariants(pkg: OoxmlPackage): PackageInvariantResult;
886
+
887
+ /** Whether a string is a valid XML NCName — a name with no colon. */
888
+ declare function isValidNCName(name: string): boolean;
889
+ /** A QName is an optional `prefix:` (both NCNames) — never attacker-derived. */
890
+ declare function isValidQName(name: string): boolean;
891
+ /**
892
+ * Validate a qualified name, throwing when it is malformed.
893
+ *
894
+ * Guards the serializer: an invalid QName written into XML produces a file Word cannot open, so
895
+ * it fails here rather than at save.
896
+ */
897
+ declare function assertValidQName(name: string): void;
898
+ /**
899
+ * Controlled namespace-prefix allocation: deterministic, collision-free prefixes
900
+ * for namespace URIs. A known URI always yields the same registered prefix; new
901
+ * URIs get a generated `ns{n}` prefix, never one derived from file content.
902
+ */
903
+ declare class PrefixAllocator {
904
+ private readonly byUri;
905
+ private readonly usedPrefixes;
906
+ private counter;
907
+ constructor(known?: Readonly<Record<string, string>>);
908
+ prefixFor(namespaceUri: string): string;
909
+ /** The declared bindings, for emitting xmlns declarations. */
910
+ bindings(): {
911
+ prefix: string;
912
+ uri: string;
913
+ }[];
914
+ }
915
+
916
+ /**
917
+ * A hyperlink target projected for a RUNTIME sink, or the reason it was withheld.
918
+ *
919
+ * The authored target stays authored — the record layer keeps it verbatim and escapes it into
920
+ * owned OOXML, which is not a runtime sink. Only this allowlist-sanitized projection reaches DOM,
921
+ * CSS, navigation or fetch, so `javascript:`, `data:` and `vbscript:` never leave the boundary.
922
+ */
923
+ type HrefProjection = {
924
+ readonly ok: true;
925
+ readonly href: string;
926
+ } | {
927
+ readonly ok: false;
928
+ readonly inert: true;
929
+ };
930
+ /**
931
+ * Project a file-derived URL for a DOM/navigation sink. Strips embedded
932
+ * tab/LF/CR (used to smuggle `java\nscript:`), allows relative URLs and the
933
+ * scheme allowlist, and renders everything else inert. Never fetches.
934
+ */
935
+ declare function sanitizeHref(raw: string): HrefProjection;
936
+ /** XML-escape a value for validated serialization back into owned OOXML. */
937
+ declare function escapeXml(value: string): string;
938
+ /**
939
+ * CSS string-escape a file-derived value (e.g. an `@font-face` family name or an
940
+ * inline style value). Emits `\<hex> ` escapes for quotes, backslash, and
941
+ * controls so the value cannot break out of its CSS string.
942
+ */
943
+ declare function escapeCssString(value: string): string;
944
+ /** Whether a file-derived CSS fragment contains a `url()` or `@import` (must be rejected). */
945
+ declare function containsCssFetch(value: string): boolean;
946
+ /**
947
+ * Content that must never execute or auto-resolve: OLE objects, macros, DDE and `INCLUDE*` field
948
+ * instructions.
949
+ *
950
+ * Rendered INERT by default rather than stripped — removing it would be a lossless-preservation
951
+ * failure, so it is carried and never acted on.
952
+ */
953
+ declare const INERT_EXECUTABLE_KINDS: readonly ["field-dde", "field-include", "macro", "activex", "ole", "embedded-object", "executable-relationship"];
954
+ /** One of {@link INERT_EXECUTABLE_KINDS}. */
955
+ /** One of {@link INERT_EXECUTABLE_KINDS} — content carried but never executed. */
956
+ type InertExecutableKind = (typeof INERT_EXECUTABLE_KINDS)[number];
957
+ /** Whether a content kind is one this engine refuses to execute or auto-resolve. */
958
+ declare function isInertExecutable(kind: string): boolean;
959
+ /** Whether a field instruction's leading keyword is safe to evaluate. */
960
+ declare function isEvaluableField(instruction: string): boolean;
961
+ /** One item a scrub pass considers: its kind, and where in the package it sits. */
962
+ interface ContentItem {
963
+ readonly id: string;
964
+ readonly kind: string;
965
+ }
966
+ /**
967
+ * What an explicit scrub removed.
968
+ *
969
+ * A scrub DECLARES ITSELF non-lossless: removing executable content changes the file, which is a
970
+ * choice a caller makes deliberately rather than a default the engine applies.
971
+ */
972
+ interface ScrubResult {
973
+ readonly kept: readonly ContentItem[];
974
+ readonly removed: readonly ContentItem[];
975
+ /** A scrub that removes anything is non-lossless by definition. */
976
+ readonly nonLossless: boolean;
977
+ }
978
+ /** Explicit scrub export: remove inert executable classes, report removals. */
979
+ declare function scrubExport(items: readonly ContentItem[]): ScrubResult;
980
+
981
+ /** An edited part, or the invariant violations that rejected the edit. */
982
+ type OoxmlEditResult = {
983
+ readonly ok: true;
984
+ readonly part: OoxmlPart;
985
+ } | {
986
+ readonly ok: false;
987
+ readonly issues: readonly OoxmlInvariantIssue[];
988
+ };
989
+ /**
990
+ * How an edit primitive validates its result.
991
+ *
992
+ * By default every primitive runs the full-part invariant validation before handing its
993
+ * result back — the safe reading for an isolated call. A TRANSACTION applying many ops pays
994
+ * that full-tree walk once per primitive, which is what made a hundred-paragraph paste
995
+ * quadratic; it defers instead, and runs the same validation ONCE on the final tree before
996
+ * anything is published. Deferring is only sound for a caller that owns a commit boundary:
997
+ * nothing may escape between the unvalidated intermediate and the validated result.
998
+ */
999
+ interface EditOptions {
1000
+ readonly deferValidation?: boolean;
1001
+ }
1002
+ /** Every node id currently present in the part. */
1003
+ declare function collectNodeIds(part: OoxmlPart): Set<string>;
1004
+ /**
1005
+ * Mint ids for nodes an edit introduces.
1006
+ *
1007
+ * Deterministic and collision-checked against the whole part: a structural-path id from the
1008
+ * original parse (`/word/document.xml#0.1.2`) and a minted one (`/word/document.xml#new:3`)
1009
+ * can never coincide, and the counter skips anything already taken so repeated edits in one
1010
+ * session stay unique.
1011
+ *
1012
+ * Checks the part's node index directly rather than copying every id into a fresh set: the
1013
+ * copy was O(document) per op, and an allocator is created for every op.
1014
+ */
1015
+ declare function createNodeIdAllocator(part: OoxmlPart): () => string;
1016
+ /** Whether a node id exists in the part. */
1017
+ declare function hasNode(part: OoxmlPart, nodeId: string): boolean;
1018
+ /** Read a node back out of a part by id. */
1019
+ declare function findNode(part: OoxmlPart, nodeId: string): OoxmlNode | null;
1020
+ /** The element that holds a node, or null for the root and for unknown ids. */
1021
+ declare function parentNodeOf(part: OoxmlPart, nodeId: string): OoxmlElement | null;
1022
+ /** Replace one node's children wholesale. */
1023
+ declare function replaceChildren(part: OoxmlPart, nodeId: string, children: readonly OoxmlNode[], options?: EditOptions): OoxmlEditResult;
1024
+ /** Insert children into a node at `index` (clamped to the child list). */
1025
+ declare function insertChildren(part: OoxmlPart, nodeId: string, index: number, children: readonly OoxmlNode[], options?: EditOptions): OoxmlEditResult;
1026
+ /** Replace one node with another, keeping its position among its siblings. */
1027
+ declare function replaceNode(part: OoxmlPart, nodeId: string, replacement: OoxmlNode, options?: EditOptions): OoxmlEditResult;
1028
+ /** Remove a node and its subtree. */
1029
+ declare function removeNode(part: OoxmlPart, nodeId: string, options?: EditOptions): OoxmlEditResult;
1030
+ /**
1031
+ * Apply several primitives as ONE atomic step.
1032
+ *
1033
+ * Each edit runs against the result of the previous one, and the whole sequence is
1034
+ * validated once at the end. If any step fails, the ORIGINAL part is what the caller keeps
1035
+ * — there is no partially-edited intermediate to publish. This is the shape a multi-`DocOp`
1036
+ * store transaction needs.
1037
+ */
1038
+ declare function applyEdits(part: OoxmlPart, edits: readonly ((current: OoxmlPart) => OoxmlEditResult)[], options?: EditOptions): OoxmlEditResult;
1039
+
1040
+ /** UTF-16 placeholder for a page break in paragraph text projections. */
1041
+ declare const PAGE_BREAK_CHAR = "\f";
1042
+ /** What a `w:br` breaks. `other` covers values this engine does not model, kept losslessly. */
1043
+ type HardBreakKind = 'line' | 'page' | 'column' | 'other';
1044
+ /** Read the semantic break kind from a typed `w:br` node. */
1045
+ declare function hardBreakKind(node: OoxmlHardBreakNode): HardBreakKind;
1046
+ /** Whether a node is a `w:br` with `w:type="page"`. */
1047
+ declare function isPageBreakNode(node: OoxmlNode): node is OoxmlHardBreakNode;
1048
+ /** Text projection for a `w:br` node — one UTF-16 code unit per break. */
1049
+ declare function hardBreakText(node: OoxmlHardBreakNode): string;
1050
+ /** Attributes for a newly authored `w:br`. */
1051
+ declare function hardBreakAttributes(kind: 'line' | 'page'): OoxmlHardBreakNode['attributes'];
1052
+
1053
+ /** UTF-16 placeholder for one atomic field unit in `paragraphTextOf` / segments. */
1054
+ declare const FIELD_ATOM_CHAR = "\uFFFC";
1055
+ /**
1056
+ * Which part of a complex field a `w:fldChar` marks.
1057
+ *
1058
+ * A complex field spans many runs: `begin`, the instruction, `separate`, the cached result, then
1059
+ * `end` — which is why a field is one logical unit across several nodes.
1060
+ */
1061
+ type FldCharType = 'begin' | 'separate' | 'end';
1062
+ /** Read `@w:fldCharType` when present and schema-legal. */
1063
+ declare function fldCharType(node: OoxmlNode): FldCharType | null;
1064
+ /** Whether a node is a `w:fldChar` field boundary marker. */
1065
+ declare function isFldCharNode(node: OoxmlNode): node is OoxmlFldCharNode;
1066
+ /**
1067
+ * Whether a node is `w:instrText` — a field's instruction.
1068
+ *
1069
+ * Instructions are never EXECUTED or auto-resolved: `DDE` and `INCLUDE*` render inert.
1070
+ */
1071
+ declare function isInstrTextNode(node: OoxmlNode): node is OoxmlInstrTextNode;
1072
+ /** Whether a node is `w:fldSimple` — a field whose instruction and result are one element. */
1073
+ declare function isFldSimpleNode(node: OoxmlNode): node is OoxmlFldSimpleNode;
1074
+ /** Typed or generic `w:fldChar` with the given type. */
1075
+ declare function isFldChar(node: OoxmlNode, type: FldCharType): boolean;
1076
+ /** Typed or generic `w:instrText`. */
1077
+ declare function isInstrText(node: OoxmlNode): boolean;
1078
+ /** Typed or generic `w:fldSimple`. */
1079
+ declare function isFldSimple(node: OoxmlNode): boolean;
1080
+ /** Concatenated text descendants of `w:instrText` (instruction only — never executed). */
1081
+ declare function instrTextValue(node: OoxmlNode): string;
1082
+ /** `@w:instr` on `w:fldSimple`, or undefined when absent. */
1083
+ declare function fldSimpleInstr(node: OoxmlNode): string | undefined;
1084
+ /**
1085
+ * Read an on/off WML attribute (`dirty` / `fldLock`).
1086
+ *
1087
+ * Returns `undefined` when absent, otherwise the OOXML on/off interpretation
1088
+ * (present without val, or val not explicitly off → true).
1089
+ */
1090
+ declare function fieldOnOffAttribute(node: OoxmlNode, localName: 'dirty' | 'fldLock'): boolean | undefined;
1091
+ /** Model text contributed by one atomic field unit. */
1092
+ declare function fieldAtomText(): typeof FIELD_ATOM_CHAR;
1093
+ /**
1094
+ * True when a node is field chrome that never contributes its own model text outside
1095
+ * an atomic span (markers + instruction). Cached result `w:t` is separate.
1096
+ */
1097
+ declare function isFieldChrome(node: OoxmlNode): boolean;
1098
+ /**
1099
+ * One atomic field span inside a paragraph for caret / delete / selection.
1100
+ *
1101
+ * `removeNodeIds` lists every node that must leave with the unit (begin…end chrome and
1102
+ * cached-result content for complex fields; the `fldSimple` element for simple fields).
1103
+ *
1104
+ * `formatRunIds` lists the runs whose `w:rPr` owns displayed result formatting — result-phase
1105
+ * runs with measurable cache text for complex fields, child `w:r`s for `fldSimple`, or the
1106
+ * separate/begin run when the result is empty. Delete / caret addressing still uses `runId`
1107
+ * (the begin / simple node); formatting must not rewrite chrome-only begin runs when the
1108
+ * painted glyphs come from a different result run.
1109
+ */
1110
+ interface AtomicFieldSpan {
1111
+ readonly kind: 'complex' | 'simple';
1112
+ /** Addressable segment node (begin `fldChar` or `fldSimple`). */
1113
+ readonly node: OoxmlNode;
1114
+ /** Run that owns the begin marker; empty string for paragraph-level `fldSimple`. */
1115
+ readonly runId: string;
1116
+ readonly removeNodeIds: readonly string[];
1117
+ /** Runs that own displayed result formatting (may differ from `runId`). */
1118
+ readonly formatRunIds: readonly string[];
1119
+ }
1120
+ /**
1121
+ * Collect well-formed atomic field spans in document order.
1122
+ *
1123
+ * Demotion (no span emitted — callers surface interior text normally):
1124
+ * - `end` without matching `begin`
1125
+ * - orphan `instrText` outside an open field
1126
+ * - missing `end` before paragraph end
1127
+ * - nesting deeper than `maxNesting`
1128
+ * - instruction longer than `maxInstructionChars` (still forms a span when begin/end
1129
+ * pair closes, but callers may treat evaluation as inert; addressing stays atomic)
1130
+ *
1131
+ * Cross-paragraph fields never form: this walk is per paragraph.
1132
+ */
1133
+ declare function atomicFieldSpansOf(paragraph: OoxmlParagraphNode, options?: {
1134
+ readonly maxNesting?: number;
1135
+ readonly maxInstructionChars?: number;
1136
+ }): readonly AtomicFieldSpan[];
1137
+ /** Whether `fldCharType` is a legal ST_FldCharType value (used by tests / guards). */
1138
+ declare function isLegalFldCharType(value: string): boolean;
1139
+
1140
+ /** Parsed TOC instruction. Unknown switches are ignored for generation but left on the wire. */
1141
+ interface TocInstruction {
1142
+ readonly keyword: 'TOC';
1143
+ /** Include hyperlinks (`\\h`). */
1144
+ readonly hyperlink: boolean;
1145
+ /** Omit page numbers (`\\n`). */
1146
+ readonly omitPageNumbers: boolean;
1147
+ /** Inclusive 1-based outline levels from `\\o "n-m"`. Defaults 1–9. */
1148
+ readonly outlineStart: number;
1149
+ readonly outlineEnd: number;
1150
+ readonly raw: string;
1151
+ }
1152
+ /** Longest TOC field instruction read. Instructions come from a file; the parse is bounded. */
1153
+ declare const TOC_MAX_INSTRUCTION_CHARS = 256;
1154
+ /** Most entries one generated table of contents may hold. */
1155
+ declare const TOC_MAX_ENTRIES = 512;
1156
+ /** Most bookmarks minted during one TOC refresh. */
1157
+ declare const TOC_MAX_BOOKMARKS_PER_REFRESH = 512;
1158
+ /** Deepest nested field instruction followed. Caps recursion on file-supplied structure. */
1159
+ declare const TOC_MAX_FIELD_NESTING = 4;
1160
+ /**
1161
+ * Most layout passes a TOC refresh runs before settling.
1162
+ *
1163
+ * Page numbers change the TOC's own height, which changes page numbers — bounded so a
1164
+ * non-converging document stops rather than looping.
1165
+ */
1166
+ declare const TOC_MAX_PAGE_PASSES = 3;
1167
+ /**
1168
+ * Parse a TOC field instruction string.
1169
+ *
1170
+ * Returns null when the leading keyword is not TOC, the string is over-long, or the
1171
+ * outline range is hostile. Does not evaluate or fetch anything.
1172
+ */
1173
+ declare function parseTocInstruction(raw: string): TocInstruction | null;
1174
+
1175
+ /** A table of contents found in a document, whether wrapped in an SDT or a bare field. */
1176
+ interface DetectedToc {
1177
+ /** Enclosing control id when it identifies one TOC, otherwise the begin fldChar id. */
1178
+ readonly id: string;
1179
+ readonly beginNodeId: string;
1180
+ readonly beginParagraphId: string;
1181
+ readonly endParagraphId: string;
1182
+ readonly resultParagraphIds: readonly string[];
1183
+ /** Direct parent whose paragraph children delimit the cached result. */
1184
+ readonly containerId: string;
1185
+ readonly contentControlId?: string;
1186
+ readonly instruction: TocInstruction;
1187
+ }
1188
+ /** Discover refreshable body TOCs without evaluating any field instruction. */
1189
+ declare function detectBodyTocs(part: OoxmlPart): readonly DetectedToc[];
1190
+ /** Locate the table of contents containing a position, or null. */
1191
+ declare function findDetectedToc(tocs: readonly DetectedToc[], tocId: string): DetectedToc | null;
1192
+
1193
+ /** Outline heading shape consumed by TOC planning (mirrors DocumentOutlineEntry). */
1194
+ interface TocOutlineHeading {
1195
+ readonly text: string;
1196
+ readonly level: number;
1197
+ readonly blockId: string;
1198
+ }
1199
+
1200
+ /** Left-indent step between TOC levels, in twips (matches `scripts/demo-doc/toc-block.xml`). */
1201
+ declare const TOC_LEVEL_INDENT_TWIPS = 240;
1202
+ /** Bounded left-indent twips for a TOC entry level (0-based heading depth). */
1203
+ declare function tocLeftIndentTwips(level: number): number;
1204
+ /** One planned TOC entry: its level, its text, and the heading it points at. */
1205
+ interface TocEntryPlan {
1206
+ readonly level: number;
1207
+ readonly text: string;
1208
+ readonly headingParagraphId: string;
1209
+ readonly bookmarkName: string;
1210
+ readonly pageNumberText: string;
1211
+ }
1212
+ /** Build one TOC entry paragraph node. */
1213
+ declare function buildTocEntryParagraph(mint: () => string, entry: TocEntryPlan, instruction: TocInstruction, paragraphPropertiesTemplate?: OoxmlNode): OoxmlNode;
1214
+ /** Build an SDT-wrapped complex TOC field with an already planned cached result. */
1215
+ declare function buildTocContentControl(mint: () => string, entries: readonly TocEntryPlan[], instruction: TocInstruction, alias: string): OoxmlNode;
1216
+ /**
1217
+ * Word flattens manual line/tab breaks from a heading into spaces in its TOC cache.
1218
+ * Carrying them verbatim makes a short title wrap even when the row has ample room, and the
1219
+ * same normalization is what lets a cached row be matched back to the heading it came from.
1220
+ */
1221
+ declare function tocEntryText(text: string): string;
1222
+ /**
1223
+ * Plan TOC entries from the outline and existing bookmarks.
1224
+ */
1225
+ declare function planTocEntries(part: OoxmlPart, outline: readonly TocOutlineHeading[], instruction: TocInstruction, pageNumberByParagraphId: ReadonlyMap<string, string>, excludeParagraphIds: ReadonlySet<string>): {
1226
+ readonly entries: readonly TocEntryPlan[];
1227
+ readonly bookmarksToCreate: readonly {
1228
+ paragraphId: string;
1229
+ name: string;
1230
+ }[];
1231
+ };
1232
+ /** Create bookmarkStart/End pair nodes for insertion at the start of a paragraph. */
1233
+ declare function bookmarkPairNodes(mint: () => string, name: string, id: string): {
1234
+ readonly start: OoxmlNode;
1235
+ readonly end: OoxmlNode;
1236
+ };
1237
+
1238
+ /**
1239
+ * The heading each cached result row stands for, aligned with `toc.resultParagraphIds`.
1240
+ *
1241
+ * `null` for a row that names no heading this document still has — a stale row, or the
1242
+ * chrome/blank paragraphs a cached result can carry. Callers leave those alone rather than
1243
+ * writing another row's number into them.
1244
+ */
1245
+ declare function resolveTocRowHeadings(part: OoxmlPart, toc: DetectedToc, outline: readonly TocOutlineHeading[], excludeParagraphIds: ReadonlySet<string>): readonly (string | null)[];
1246
+
1247
+ /** One paragraph in the index: its node id, its story, and its position. */
1248
+ interface ParagraphIndexEntry {
1249
+ /** Canonical tree node id — the stable identity operations address. */
1250
+ readonly nodeId: string;
1251
+ /** Position among the story's paragraphs, in document order. */
1252
+ readonly ordinal: number;
1253
+ /** Concatenated text content, with tabs and breaks mapped as the model reads them. */
1254
+ readonly text: string;
1255
+ /** Node ids of the paragraph's runs, in order. */
1256
+ readonly runIds: readonly string[];
1257
+ }
1258
+ /** One story root — body, a header/footer variant, or a note part. */
1259
+ interface StoryIndexEntry {
1260
+ /** The part the story lives in. */
1261
+ readonly partName: string;
1262
+ /** The `w:body` (or story root) node id. */
1263
+ readonly rootId: string;
1264
+ readonly paragraphs: readonly ParagraphIndexEntry[];
1265
+ }
1266
+ /** One style definition, indexed by the id content references it under. */
1267
+ interface StyleIndexEntry {
1268
+ readonly styleId: string;
1269
+ readonly type: string;
1270
+ readonly nodeId: string;
1271
+ readonly name: string | null;
1272
+ readonly basedOn: string | null;
1273
+ /** Whether the part marks this the default style for its type (`w:default="1"`). */
1274
+ readonly isDefault: boolean;
1275
+ }
1276
+ /**
1277
+ * The derived lookups over a part: paragraphs, stories and styles by id.
1278
+ *
1279
+ * Diff-patched on commit rather than rebuilt — rebuilding every index per keystroke is what made
1280
+ * typing scale with document length.
1281
+ */
1282
+ interface OoxmlIndexes {
1283
+ /** The tree revision these projections were derived from. */
1284
+ readonly revision: number;
1285
+ /** Body story first, then any other story parts, keyed by part name. */
1286
+ readonly stories: ReadonlyMap<string, StoryIndexEntry>;
1287
+ /** Every paragraph across every story, keyed by node id. */
1288
+ readonly paragraphs: ReadonlyMap<string, ParagraphIndexEntry>;
1289
+ readonly relationships: ReadonlyMap<string, readonly RelationshipRecord[]>;
1290
+ readonly styles: ReadonlyMap<string, StyleIndexEntry>;
1291
+ }
1292
+ /** Style definitions, read out of the generic `w:styles` tree. */
1293
+ declare function indexStyles(part: OoxmlPart | undefined): Map<string, StyleIndexEntry>;
1294
+ /** The package's style definitions part, if it has one. */
1295
+ declare function stylesPartOf(pkg: OoxmlPackage): OoxmlPart | undefined;
1296
+ /**
1297
+ * Derive every index from one canonical package revision.
1298
+ *
1299
+ * Pure: the same package and revision always produce the same index, which is what makes
1300
+ * "rebuild rather than mutate" a safe invalidation strategy.
1301
+ */
1302
+ declare function deriveOoxmlIndexes(pkg: OoxmlPackage, revision: number): OoxmlIndexes;
1303
+
1304
+ /** One paragraph's meaning, independent of how it was spelled in XML. */
1305
+ interface ParagraphDigest {
1306
+ /** Ordinal identity within its story. Node ids are NOT used: a reopened package
1307
+ * legitimately re-derives them, and requiring them to match would test the id scheme
1308
+ * rather than the content. */
1309
+ readonly ordinal: number;
1310
+ /**
1311
+ * Where the paragraph SITS: the element path from the story root, so a paragraph that
1312
+ * moves out of the table cell it was written in is a difference rather than a paragraph
1313
+ * with the same ordinal and the same text.
1314
+ */
1315
+ readonly path: string;
1316
+ /**
1317
+ * `w14:paraId`, uppercase-normalized (matching is case-insensitive), or null. This is
1318
+ * MANAGED identity — the agent contract anchors on it and comment threading references
1319
+ * it — so a serializer silently dropping it must be a digest difference. Other paragraph
1320
+ * attributes (`w:rsidR` …) stay deliberately undigested: they are revision noise.
1321
+ */
1322
+ readonly paraId: string | null;
1323
+ /** Text content, including tabs and hard breaks as their characters. */
1324
+ readonly text: string;
1325
+ /** Accepted paragraph properties, as sorted tokens including nested children. */
1326
+ readonly paragraphProperties: readonly string[];
1327
+ /** Per-run accepted properties, in run order. */
1328
+ readonly runProperties: readonly (readonly string[])[];
1329
+ /** Fingerprints of every generic (unknown) subtree, in document order. */
1330
+ readonly genericStructure: readonly string[];
1331
+ }
1332
+ /** One story reduced to its semantic content, ignoring everything a normalized re-emit changes. */
1333
+ interface StoryDigest {
1334
+ readonly partName: string;
1335
+ readonly paragraphs: readonly ParagraphDigest[];
1336
+ /**
1337
+ * Every block-level element of the part OUTSIDE a paragraph, in document order, as
1338
+ * `path name(attributes)` — the tables, rows, cells, sections, content controls and
1339
+ * their property children, each at the position that says what contains it.
1340
+ *
1341
+ * A paragraph's own internals are not here (they are its `ParagraphDigest`), which keeps
1342
+ * this list proportional to a document's STRUCTURE rather than its text.
1343
+ */
1344
+ readonly structure: readonly string[];
1345
+ }
1346
+ /**
1347
+ * The whole document's semantic content — one of the D9 losslessness oracles.
1348
+ *
1349
+ * What a save/reopen round-trip is compared on. Byte identity applies only to non-XML parts;
1350
+ * modelled parts re-emit normalized, so equality is asserted HERE rather than on bytes.
1351
+ */
1352
+ interface SemanticDigest {
1353
+ readonly stories: readonly StoryDigest[];
1354
+ }
1355
+ /** Where two digests diverge — the diagnostic when a round-trip loses something. */
1356
+ type DigestDifference = {
1357
+ readonly path: string;
1358
+ readonly before: string;
1359
+ readonly after: string;
1360
+ };
1361
+ /** Digest one part: its paragraphs, and the structure that holds them. */
1362
+ declare function digestPart(part: OoxmlPart): StoryDigest | null;
1363
+ /** Digest every part, in the given order. */
1364
+ declare function semanticDigest(parts: Iterable<OoxmlPart>): SemanticDigest;
1365
+ /**
1366
+ * Every way two digests differ, as readable paths.
1367
+ *
1368
+ * Returns the differences rather than a boolean because "the round trip lost something" is
1369
+ * useless without saying what — the failure this oracle exists to catch is a silent drop,
1370
+ * and a bare `false` reproduces the silence.
1371
+ */
1372
+ declare function diffSemanticDigests(before: SemanticDigest, after: SemanticDigest): DigestDifference[];
1373
+
1374
+ /** Valid per MS-DOCX: 8 hex digits, non-zero, below 0x80000000. */
1375
+ declare function isValidParaId(value: string): boolean;
1376
+ /** The authored `w14:paraId` value of an element, verbatim, or null. */
1377
+ declare function paraIdOf(node: OoxmlNode): string | null;
1378
+ /** FNV-1a over UTF-16 code units — the deterministic mint every id derivation shares. */
1379
+ declare function fnv1a32(value: string): number;
1380
+ /**
1381
+ * Deterministic 8-hex mint in (0x00000000, 0x80000000), collision-free against
1382
+ * `used` (uppercase hex). Same seed + same used-set → same value, which is what
1383
+ * keeps `splitParagraphMany` byte-identical to its equivalent single splits and
1384
+ * a reopened save identical to the session that produced it.
1385
+ */
1386
+ declare function mintParaId(seed: string, used: ReadonlySet<string>): string;
1387
+ /** Every valid `w14:paraId` in the tree, uppercased. Memoized per root object. */
1388
+ declare function usedParaIds(root: OoxmlElement): ReadonlySet<string>;
1389
+ /**
1390
+ * The non-empty prefix the part ROOT binds to the w14 namespace, or null.
1391
+ *
1392
+ * Minted attributes require an in-scope binding (the invariant validator reports
1393
+ * `invalid-qname` otherwise, and the serializer would allocate an `nsN` alias).
1394
+ * Only the root binding counts: a binding authored on some descendant does not
1395
+ * cover paragraphs elsewhere in the tree.
1396
+ */
1397
+ declare function w14RootPrefix(root: OoxmlElement): string | null;
1398
+ /** The minted `[w14:paraId, w14:textId]` pair. `textId` mirrors `paraId`: it has no uniqueness requirement, no consumer reads it, and one allocator is simpler than two — but Word writes both, so we write both. */
1399
+ declare function mintedParagraphIdentityAttributes(prefix: string, value: string): readonly OoxmlAttribute[];
1400
+ /**
1401
+ * Load-time paragraph-identity normalization for a session's main part.
1402
+ *
1403
+ * Keeps every valid, first-seen paraId verbatim; mints (deterministically, seeded
1404
+ * by the paragraph's structural node id) for paragraphs whose id is missing,
1405
+ * malformed, zero, out of range, or a duplicate. Adds the root `xmlns` binding
1406
+ * the minted attributes need. Returns the INPUT PART REFERENCE when there is
1407
+ * nothing to do — a document Word saved yesterday re-serializes byte-identical.
1408
+ *
1409
+ * Attribute-only rebuilds move no child, so every node keeps its structural-path
1410
+ * id; the copy respreads only the ancestors of changed paragraphs.
1411
+ *
1412
+ * Fail-open: if the rebuilt part does not validate (a bug, or a pathology the
1413
+ * prefix choice could not defuse), the original part is returned — a document
1414
+ * must never become unopenable over an identity enhancement.
1415
+ */
1416
+ declare function normalizeParagraphIdentity(part: OoxmlPart): OoxmlPart;
1417
+
1418
+ /** The package with a hyperlink relationship guaranteed present, and that relationship's id. */
1419
+ interface EnsuredHyperlinkRelationship {
1420
+ readonly pkg: OoxmlPackage;
1421
+ readonly relationshipId: string;
1422
+ }
1423
+ /**
1424
+ * The target this engine would write for `url`, or null when it would write none.
1425
+ *
1426
+ * The VALIDATION half of {@link ensureHyperlinkRelationship}, exported so a caller that must decide
1427
+ * "would this be authored?" before it is allowed to change the package can ask without changing it.
1428
+ * A relationship outlives a refusal — it lives beside the trees, outside the undo stack — so a
1429
+ * caller planning a batch that may yet be refused has to ask this and mint later.
1430
+ *
1431
+ * Same rules, one implementation: `sanitizeHref`'s allowlist, a bound on the length, XML-writable
1432
+ * text, and the absolute-URI gate the READ side applies. There is no legitimate reason for this
1433
+ * engine to author a scheme it would refuse to open.
1434
+ */
1435
+ declare function authorableHyperlinkTarget(url: string): string | null;
1436
+ /**
1437
+ * The external hyperlink relationship for `url` on `ownerPart` (default: main document),
1438
+ * reusing an existing one with the same target, or `null` when the URL is not something to
1439
+ * write.
1440
+ *
1441
+ * REUSE IS BY EXACT TARGET, matching Word: linking twice to the same address produces one
1442
+ * relationship. It is safe because a hyperlink relationship carries nothing but its target —
1443
+ * two links sharing one are indistinguishable from two links with identical targets, and
1444
+ * retargeting one always mints rather than rewriting (see the edit op).
1445
+ *
1446
+ * Ownership follows the story that holds the `w:hyperlink`: a header/footer or notes part
1447
+ * mints into that part's `.rels`, never into `document.xml.rels`. Passing an owner the
1448
+ * package does not declare fails closed (`null`) so a scoped insert cannot leave a stray
1449
+ * body relationship behind.
1450
+ *
1451
+ * The URL is refused unless `sanitizeHref` admits it. Storing a `javascript:` target that a
1452
+ * FILE authored is required — round-tripping never rewrites a document — but AUTHORING one
1453
+ * here is not: there is no legitimate reason for this engine to write a scheme it would then
1454
+ * refuse to open, and writing it would hand the next reader a live target this reader made.
1455
+ */
1456
+ declare function ensureHyperlinkRelationship(pkg: OoxmlPackage, url: string, ownerPart?: string): EnsuredHyperlinkRelationship | null;
1457
+ /**
1458
+ * What a part's relationships answer for one `r:id`, over both maps.
1459
+ *
1460
+ * `relationships` holds the internal records and `externalTargets` the external ones, so a
1461
+ * resolver reading only the first sees every hyperlink as dangling.
1462
+ */
1463
+ declare function relationshipTargetIn(pkg: OoxmlPackage, ownerPart: string, relationshipId: string): {
1464
+ readonly target: string;
1465
+ readonly external: boolean;
1466
+ readonly sinkSafe?: boolean;
1467
+ } | null;
1468
+
1469
+ /**
1470
+ * Delete a comment thread outright: body, thread state and story markers.
1471
+ *
1472
+ * Returns the package unchanged when the id names no comment, and null when a removal was
1473
+ * refused — a caller inside a transaction rolls back rather than committing a package whose
1474
+ * comment is half gone.
1475
+ */
1476
+ declare function deleteCommentThread(pkg: OoxmlPackage, commentId: string): OoxmlPackage | null;
1477
+ /**
1478
+ * Delete every comment the edit between `before` and `after` emptied.
1479
+ *
1480
+ * The shape `cascadeDeletedNoteReferences` established: a before/after diff rather than a rule
1481
+ * inside each op, because the ops that can empty a range are several (`deleteText`,
1482
+ * `deleteBlock`, a row deletion, accepting a tracked deletion) and a rule written into each one
1483
+ * drifts.
1484
+ *
1485
+ * THE TEST, exactly. A comment dies when the words it covered are gone and nothing still
1486
+ * places it: either every marker naming it went with them, or its markers are all still there
1487
+ * with no characters left between them. What it deliberately does NOT do is read "no usable
1488
+ * range" as "emptied" — a comment whose `w:commentRangeStart` was carried off by a deleted
1489
+ * block still has its reference and its end, and Word keeps it, because the reference is the
1490
+ * element that anchors a comment. Reaping there deleted a remark whose text was still on
1491
+ * screen, which is the one mistake worse than leaving a stale card.
1492
+ *
1493
+ * SKIPS rather than refuses when the package is too large to scan. Returning null there made
1494
+ * `transact` roll the edit back, so on a package past the part cap every keystroke in a
1495
+ * commented paragraph was silently refused and the document read as frozen. A skipped reap
1496
+ * leaves a stale card — recoverable, visible, and the behaviour before any of this existed.
1497
+ * Null is reserved for a removal that actually failed, which the caller must roll back.
1498
+ */
1499
+ declare function cascadeEmptiedComments(before: OoxmlPackage, after: OoxmlPackage): OoxmlPackage | null;
1500
+ /** Whether the package holds any comment record at all — the cheap gate before a reap. */
1501
+ declare function hasAnyComment(pkg: OoxmlPackage): boolean;
1502
+
1503
+ /** How deep block-level content controls may nest before the walk stops descending. */
1504
+ declare const MAX_STORY_SDT_NESTING = 32;
1505
+ /** Which kind of story a root is. Layout walks all four the same way. */
1506
+ type OoxmlStoryKind = 'body' | 'header' | 'footer' | 'note';
1507
+ /** One story root and the blocks under it, with block-level SDTs already flattened. */
1508
+ interface OoxmlStoryRoot {
1509
+ readonly kind: OoxmlStoryKind;
1510
+ /** The `w:body` / `w:hdr` / `w:ftr` / `w:footnote` element that holds the blocks. */
1511
+ readonly root: OoxmlNode;
1512
+ }
1513
+ /**
1514
+ * Every story root in a part, in document order.
1515
+ *
1516
+ * Does not descend INTO a story: a story's blocks are the walk below, and a story root never
1517
+ * contains another story root.
1518
+ */
1519
+ declare function storyRootsOf(part: OoxmlPart): readonly OoxmlStoryRoot[];
1520
+ /** The main body story of a part, or null when the part holds none. */
1521
+ declare function bodyStoryRoot(part: OoxmlPart): OoxmlNode | null;
1522
+ /**
1523
+ * Every paragraph of one story, in reading order.
1524
+ *
1525
+ * Descends through tables (rows, cells, nested tables) and flattens block-level content
1526
+ * controls. The returned nodes are paragraph elements; a caller addresses them by `id`.
1527
+ */
1528
+ declare function storyParagraphs(root: OoxmlNode): readonly OoxmlNode[];
1529
+ /**
1530
+ * The block walk itself, appending into `out`.
1531
+ *
1532
+ * Exported so `allParagraphs` in the binding lane is the same traversal rather than a second
1533
+ * copy of it.
1534
+ */
1535
+ declare function collectStoryParagraphs(children: readonly OoxmlNode[], out: OoxmlNode[], sdtDepth: number): void;
1536
+
1537
+ /** Relationship from the story to one data part. */
1538
+ declare const CUSTOM_XML_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
1539
+ /** Relationship from a data part to the properties that carry its `ds:itemID`. */
1540
+ declare const CUSTOM_XML_PROPS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps";
1541
+ /** `itemPropsN.xml` needs an Override; `itemN.xml` rides the package's `xml` default. */
1542
+ declare const CUSTOM_XML_PROPS_TYPE = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";
1543
+ /** The datastore namespace `ds:datastoreItem` lives in. */
1544
+ declare const DATASTORE_NAMESPACE_URI = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";
1545
+ /** A data part located in a package: where it lives, and the GUID an SDT binds to. */
1546
+ interface CustomXmlDataPart {
1547
+ /** Canonical part name, e.g. `/customXml/item1.xml`. */
1548
+ readonly partName: string;
1549
+ /** Part name of its properties, e.g. `/customXml/itemProps1.xml`. */
1550
+ readonly propsPartName: string;
1551
+ /** `ds:itemID`, braced and upper-case, as `w:storeItemID` must spell it. */
1552
+ readonly itemId: string;
1553
+ /** Namespace URI of the payload root, which is what identifies one store among several. */
1554
+ readonly namespaceUri: string;
1555
+ }
1556
+ /**
1557
+ * A `ds:itemID` derived from the seed rather than drawn at random.
1558
+ *
1559
+ * Exported so a caller that authors a store OUTSIDE a package — a template engine splicing
1560
+ * markup it will assemble into a `.docx` later — mints the id the same way this does, rather
1561
+ * than inventing a second GUID shape Word has to be tolerant of.
1562
+ *
1563
+ * The store is a pure function of what it is asked to write: the same document written twice
1564
+ * has to produce the same bytes, or a save/reopen/save round trip stops being a fixed point
1565
+ * and every digest taken over saved bytes moves. A GUID's job here is uniqueness within one
1566
+ * package, not unguessability, so four FNV-1a passes over a salted seed carry it.
1567
+ */
1568
+ declare function datastoreItemIdFor(seed: string): string;
1569
+ /**
1570
+ * The data parts a story relates to, in relationship order.
1571
+ *
1572
+ * Reads the relationships rather than scanning `/customXml/` by name: a part nothing relates
1573
+ * to is not part of the document, and a package from a hostile sender can hold as many
1574
+ * plausibly-named files as it likes.
1575
+ */
1576
+ declare function customXmlDataParts(pkg: OoxmlPackage, storyPartName: string): CustomXmlDataPart[];
1577
+ /** The data part carrying this namespace, or null when the document has none yet. */
1578
+ declare function findCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): CustomXmlDataPart | null;
1579
+ /** What {@link withCustomXmlDataPart} answers. */
1580
+ interface CustomXmlDataPartResult {
1581
+ readonly pkg: OoxmlPackage;
1582
+ /** Null when the part could not be authored; the package then comes back unchanged. */
1583
+ readonly part: CustomXmlDataPart | null;
1584
+ }
1585
+ /**
1586
+ * Ensure the document carries a data part for this namespace, creating it and everything it
1587
+ * needs — properties, both relationships, the properties content type — when it does not.
1588
+ *
1589
+ * Idempotent: a package that already has one for the namespace comes back untouched, so a
1590
+ * second node added to the same store does not author a second store.
1591
+ *
1592
+ * @param storyPartName - Whose relationships the store hangs off. Word enumerates its data
1593
+ * store from the MAIN DOCUMENT part, so a store authored off a header or footer is one Word
1594
+ * never sees.
1595
+ */
1596
+ declare function withCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string, rootLocalName: string): CustomXmlDataPartResult;
1597
+ /**
1598
+ * Remove a store from a document: both parts, both relationships, the Override.
1599
+ *
1600
+ * PACKAGE ONLY. It does not touch the body, so a `w:sdt` bound to the store keeps its
1601
+ * `w:dataBinding`, its `w:storeItemID` and its `w:tag`, and Word then opens a control bound to
1602
+ * a store that is not there. Stripping those is the export path's job and is not built; this
1603
+ * is the half that removes the payload, which is the half a caller can rely on.
1604
+ *
1605
+ * `ok: false` means nothing was removed and the package is unchanged — most often because an
1606
+ * owner's `.rels` was never parsed into a tree, which {@link withoutPart} refuses to work
1607
+ * around. A caller exporting a document has to treat that as a failure to export rather than
1608
+ * as a document with nothing to strip, or it ships the payload it meant to remove.
1609
+ */
1610
+ declare function withoutCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): WithoutPartResult;
1611
+
1612
+ /** One node in a store: its id, the bound text, and the payload beside it. */
1613
+ interface CustomXmlNode {
1614
+ readonly id: string;
1615
+ /** Text a `w:dataBinding` resolves to. Untrusted file input. */
1616
+ readonly label: string;
1617
+ /** Payload as authored, JSON by convention and unparsed here. Untrusted file input. */
1618
+ readonly data: string;
1619
+ }
1620
+ /** Every node a store holds, in document order. */
1621
+ declare function customXmlNodes(pkg: OoxmlPackage, partName: string): CustomXmlNode[];
1622
+ /** One node by id, or null. */
1623
+ declare function readCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): CustomXmlNode | null;
1624
+ /**
1625
+ * Write a node, replacing one that already has the id.
1626
+ *
1627
+ * Replace rather than append: a second node with the same id makes the binding xpath ambiguous,
1628
+ * and Word resolves an ambiguous xpath to the first match — so an "update" that appended would
1629
+ * leave the control showing its old text forever.
1630
+ */
1631
+ declare function withCustomXmlNode(pkg: OoxmlPackage, partName: string, node: CustomXmlNode): OoxmlPackage;
1632
+ /** Drop one node by id. A store that never held it comes back unchanged. */
1633
+ declare function withoutCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): OoxmlPackage;
1634
+ /**
1635
+ * Drop every node no longer referenced, given the ids the document still binds.
1636
+ *
1637
+ * This is the whole deletion story. Deleting a control in THIS editor can remove its node
1638
+ * directly, but a control deleted in Word leaves the node behind — Word has no lifecycle link
1639
+ * between the two and no way to run our code. Reconciling against what the story actually binds
1640
+ * collects both, and is the only thing that can collect the second.
1641
+ *
1642
+ * Takes the referenced ids rather than reading the story itself: the caller already walked it,
1643
+ * and a sweep that guessed at which controls exist would delete a payload on a mistake.
1644
+ */
1645
+ declare function withoutOrphanCustomXmlNodes(pkg: OoxmlPackage, partName: string, referencedIds: ReadonlySet<string>): {
1646
+ readonly pkg: OoxmlPackage;
1647
+ readonly removed: readonly string[];
1648
+ };
1649
+ /**
1650
+ * The `w:xpath` a binding uses to reach a node's label, or null when the id cannot be addressed.
1651
+ *
1652
+ * Word needs a prefix for the payload namespace even when the store declares it as a default —
1653
+ * an unprefixed step in an XPath means "no namespace", so `/docxEditor/node` would match
1654
+ * nothing in a namespaced store. The prefix is declared in `w:prefixMappings` beside it.
1655
+ */
1656
+ declare function customXmlLabelXPath(prefix: string, rootLocalName: string, nodeId: string): string | null;
1657
+ /** The `w:prefixMappings` value declaring that prefix, or null when it cannot be written.
1658
+ * The namespace sits inside single quotes inside a double-quoted attribute, so a namespace
1659
+ * carrying either quote character has no representation here. */
1660
+ declare function customXmlPrefixMappings(prefix: string, namespaceUri: string): string | null;
1661
+
1662
+ /** The prefix every binding this library authors declares and quotes. */
1663
+ declare const CUSTOM_NODE_XPATH_PREFIX = "ns0";
1664
+ /** The three attributes a `w:dataBinding` carries. */
1665
+ interface CustomNodeBinding {
1666
+ readonly prefixMappings: string;
1667
+ readonly xpath: string;
1668
+ readonly storeItemId: string;
1669
+ }
1670
+ /**
1671
+ * The binding for one node in one store, or null when the id cannot be addressed by an XPath.
1672
+ *
1673
+ * Refuses rather than escapes: XPath 1.0 has no escape for a quote inside a literal, so an id
1674
+ * carrying one could close the predicate and append an expression of the sender's choosing.
1675
+ * The ids are minted by a host, so refusing is honest — see `ADDRESSABLE_ID`.
1676
+ */
1677
+ declare function customNodeBinding(part: CustomXmlDataPart, rootLocalName: string, nodeId: string): CustomNodeBinding | null;
1678
+ /**
1679
+ * Every node id the story's controls bind to in one store, in document order.
1680
+ *
1681
+ * This is the input the orphan sweep takes: a node whose id is not in here is one no control
1682
+ * names, whether it was deleted in this editor or in Word. Reading it from the STORY rather than
1683
+ * from a host's bookkeeping is what makes the two cases one mechanism.
1684
+ */
1685
+ declare function boundCustomXmlNodeIds(part: OoxmlPart, storeItemId: string): Set<string>;
1686
+ /**
1687
+ * Every node id ANY story in the package binds, in one store.
1688
+ *
1689
+ * THE WHOLE PACKAGE, not one story. A payload is reachable from a header as easily as from the
1690
+ * body — Word enumerates its data store from the main part, but nothing stops a control
1691
+ * elsewhere quoting the same `w:storeItemID` — and the two callers that decide what is an orphan
1692
+ * both destroy data when they are wrong. The sweep would collect a payload a header still paints;
1693
+ * the export would strip a store a header still names, which is a document Word offers to repair.
1694
+ *
1695
+ * Costs one walk per story per store, on open and on export. Neither is a keystroke.
1696
+ */
1697
+ declare function boundCustomXmlNodeIdsInPackage(pkg: OoxmlPackage, storeItemId: string): Set<string>;
1698
+ /** The node id one control binds to in the named store, or null when it binds to nothing there. */
1699
+ declare function boundCustomXmlNodeIdOf(control: OoxmlNode, storeItemId: string): string | null;
1700
+
1701
+ /** What happens to one control when the document is exported. */
1702
+ type CustomNodeExportPolicy = 'keep' | 'text' | 'remove';
1703
+ /** How {@link withExportedCustomNodes} decides, and which stores it may tidy afterwards. */
1704
+ interface CustomNodeExportRequest {
1705
+ /** The story whose controls are policed, and whose relationships the stores hang off. */
1706
+ readonly storyPartName: string;
1707
+ /**
1708
+ * Payload namespaces the caller CLAIMS.
1709
+ *
1710
+ * The store cleanup runs only over these. Word's own Cover Page Properties store rides in most
1711
+ * templates, and an export that tidied every customXml part would be deleting from documents it
1712
+ * was only asked to strip its own markup from.
1713
+ */
1714
+ readonly namespaces: readonly string[];
1715
+ /** The fate of a control carrying this `w:tag`. A control with no tag is never touched. */
1716
+ readonly decide: (tag: string) => CustomNodeExportPolicy;
1717
+ }
1718
+ /**
1719
+ * The export, or the reason there is no export.
1720
+ *
1721
+ * A refusal answers no package on purpose. "Stripping failed, here is the document anyway" is the
1722
+ * one outcome that must not be possible: a caller would ship the markup it asked to remove and
1723
+ * have been told the export succeeded.
1724
+ */
1725
+ type CustomNodeExportResult = {
1726
+ readonly ok: true;
1727
+ readonly pkg: OoxmlPackage;
1728
+ /** Controls unwrapped (`text`) and controls removed (`remove`). */
1729
+ readonly unwrapped: number;
1730
+ readonly removed: number;
1731
+ } | {
1732
+ readonly ok: false;
1733
+ readonly reason: string;
1734
+ };
1735
+ /**
1736
+ * Apply the policy, then take the payloads and the stores the policy orphaned.
1737
+ *
1738
+ * Order matters and is the reverse of the write's. The BODY goes first, so the sweep that follows
1739
+ * sees the controls that actually survive; the stores go last, once nothing binds them. Doing it
1740
+ * the other way would strip a store while a control still quoted its `w:storeItemID`, which is a
1741
+ * document Word opens and offers to repair.
1742
+ */
1743
+ declare function withExportedCustomNodes(pkg: OoxmlPackage, request: CustomNodeExportRequest): CustomNodeExportResult;
1744
+
1745
+ /** One addressable unit of paragraph text: text, tab, hard break, or atomic field. */
1746
+ interface Segment {
1747
+ readonly runId: string;
1748
+ readonly node: OoxmlNode;
1749
+ readonly start: number;
1750
+ readonly end: number;
1751
+ /**
1752
+ * When set, deleting this segment removes every listed node id in one step (atomic
1753
+ * field begin→end or `fldSimple`). Absent for ordinary text/tab/break segments.
1754
+ */
1755
+ readonly removeNodeIds?: readonly string[];
1756
+ /**
1757
+ * When set, run formatting for this atom targets these runs (field result ownership),
1758
+ * not necessarily `runId`. Absent for ordinary text/tab/break segments.
1759
+ */
1760
+ readonly formatRunIds?: readonly string[];
1761
+ }
1762
+ /**
1763
+ * Flatten a paragraph into UTF-16 addressable segments, in document order.
1764
+ *
1765
+ * A HYPERLINK's runs are addressed too. `w:hyperlink` is a run container, not a leaf, and
1766
+ * the characters inside a link are ordinary paragraph text: the user selects them, types
1767
+ * over them and deletes them like any other. Skipping the container — which is what
1768
+ * iterating only direct `w:r` children did — left every link's text with no offsets at all,
1769
+ * so `paragraphTextOf` read "Visit or ." for a sentence that says "Visit Example.com or
1770
+ * Anthropic's website." and layout, selection and the ops all agreed on the wrong string.
1771
+ *
1772
+ * Inline CONTENT CONTROLS are the same class of wrapper: their `w:sdtContent` runs join the
1773
+ * paragraph's offset stream with no break opportunity at the boundary. Nesting is bounded
1774
+ * (`MAX_CONTENT_CONTROL_NESTING`); beyond the bound the wrapper is opaque so recursion
1775
+ * cannot exhaust the stack.
1776
+ *
1777
+ * `runId` stays the id of the run the content actually lives in, at whatever depth: the
1778
+ * appliers resolve it with `findNode` and rebuild that run's children, so nesting costs them
1779
+ * nothing.
1780
+ */
1781
+ declare function segmentsOf(paragraph: OoxmlParagraphNode): Segment[];
1782
+ /** Half-open `[start, end)` of one node in its paragraph's model offset space. */
1783
+ interface OffsetSpan {
1784
+ readonly start: number;
1785
+ readonly end: number;
1786
+ }
1787
+ /**
1788
+ * Every node's place in the paragraph's model offset space, from the SAME walk `segmentsOf`
1789
+ * uses.
1790
+ *
1791
+ * The offset model has exactly one authority, and this is how a caller borrows it. Three
1792
+ * private walkers used to re-derive it — one in the tracked-change writer, one in the comment
1793
+ * anchor reader, one in the review queue — and all three disagreed with `segmentsOf` and with
1794
+ * each other: none gave a note reference or an atomic field its length of one, one counted a
1795
+ * field's instruction text as visible characters, and one never descended into `w:hyperlink`
1796
+ * at all. The consequences were an anchor short by a link's length, two unrelated comments
1797
+ * threaded onto one zero-width offset, and a tracked insert landing a character out in any
1798
+ * paragraph carrying a footnote. Patching each walker only resets the clock on the next drift.
1799
+ *
1800
+ * A node the walk never reaches — content under a `generic` container, or past the nesting cap
1801
+ * — has NO span, and {@link ParagraphOffsetIndex.lengthOf} reports zero for it. That is the
1802
+ * same answer `segmentsOf` gives: it contributes no addressable characters.
1803
+ */
1804
+ interface ParagraphOffsetIndex {
1805
+ /** The paragraph's own length, identical to {@link paragraphLength}. */
1806
+ readonly length: number;
1807
+ readonly segments: readonly Segment[];
1808
+ /** Where a node sits, or null when the offset walk never reached it. */
1809
+ spanOf(node: OoxmlNode | string): OffsetSpan | null;
1810
+ /** A node's model length: `end - start` of its span, and 0 when it has none. */
1811
+ lengthOf(node: OoxmlNode | string): number;
1812
+ }
1813
+ /**
1814
+ * THE paragraph offset authority: maps a paragraph's UTF-16 offsets to the nodes holding them.
1815
+ *
1816
+ * One authority on purpose. An atomic field spans many nodes but is ONE unit to an offset, and a
1817
+ * second implementation that disagreed would place edits inside content that cannot be split.
1818
+ */
1819
+ declare function paragraphOffsetIndex(paragraph: OoxmlParagraphNode): ParagraphOffsetIndex;
1820
+ /** One inline content control's identity and the UTF-16 span its content covers. */
1821
+ interface InlineControlSpan {
1822
+ readonly controlId: string;
1823
+ readonly start: number;
1824
+ readonly end: number;
1825
+ }
1826
+ /**
1827
+ * The innermost inline content control whose content ends exactly at `offset` — the caret
1828
+ * at its right outer edge. What Backspace consults to delete the node as ONE unit
1829
+ * (pro-review-and-custom-nodes 4.6): deleting its last character from outside would either
1830
+ * strip one letter from a content-locked label (refused, so the key looks dead) or leave a
1831
+ * half-deleted chip whose tag still claims the full payload.
1832
+ */
1833
+ declare function inlineControlEndingAt(paragraph: OoxmlParagraphNode, offset: number): InlineControlSpan | null;
1834
+ /** The forward-delete mirror: the control whose content STARTS exactly at `offset`. */
1835
+ declare function inlineControlStartingAt(paragraph: OoxmlParagraphNode, offset: number): InlineControlSpan | null;
1836
+
1837
+ /** Structural validation, run before any tree work so a rejection changes nothing. */
1838
+ declare function validateTreeOp(part: OoxmlPart, op: TreeDocOp): TreeOpRejection | null;
1839
+
1840
+ /**
1841
+ * Apply one validated op to a part.
1842
+ *
1843
+ * Validation runs first and returns before any tree work, so a rejected op is a true no-op:
1844
+ * the caller keeps the part it passed in, unchanged and still frozen.
1845
+ *
1846
+ * `options.deferValidation` passes through to the edit primitives: a transaction applying
1847
+ * many ops re-validates the whole part once at its commit boundary rather than after every
1848
+ * primitive, which is the difference between a paste that is linear and one that is
1849
+ * quadratic in document size.
1850
+ */
1851
+ declare function applyTreeOp(part: OoxmlPart, op: TreeDocOp, options?: EditOptions): TreeOpResult;
1852
+ /** Paragraph text as the ops address it, for tests and callers computing offsets. */
1853
+ declare function paragraphTextOf(part: OoxmlPart, paragraphId: string): string | null;
1854
+
1855
+ /** Where a comment is anchored, in the model offset space of one story. */
1856
+ interface CommentAnchorRequest {
1857
+ readonly paragraphId: string;
1858
+ readonly start: number;
1859
+ /** May sit in the same paragraph or a later one; `endParagraphId` names it when it differs. */
1860
+ readonly end: number;
1861
+ readonly endParagraphId?: string;
1862
+ }
1863
+ /**
1864
+ * What adding a comment needs: where it anchors, who wrote it, and its body.
1865
+ *
1866
+ * `author` is required because `CT_Comment` makes `@w:author` mandatory — a comment without one
1867
+ * writes invalid XML, so the write is refused rather than filled with an empty attribute.
1868
+ */
1869
+ interface AddCommentRequest {
1870
+ readonly anchor: CommentAnchorRequest;
1871
+ /** Required by `CT_TrackChange`. A comment without one writes invalid XML. */
1872
+ readonly author: string;
1873
+ readonly initials?: string;
1874
+ /** ISO-8601. Absent writes no `@w:date`, because inventing one is a content change. */
1875
+ readonly date?: string;
1876
+ readonly text: string;
1877
+ /** The comment this replies to. Its thread link is written to `commentsExtended.xml`. */
1878
+ readonly replyToCommentId?: string;
1879
+ }
1880
+ /** The new comment's id and the story change, or the reason the write was refused. */
1881
+ type AddCommentResult = {
1882
+ readonly ok: true;
1883
+ readonly commentId: string;
1884
+ /**
1885
+ * The story transaction's own change, so the coordinator can publish it.
1886
+ *
1887
+ * A comment write commits straight on the story store rather than through
1888
+ * `applyTreeOps`, and the change is what carries the dirty anchor paragraphs and the
1889
+ * `text-local` impact. Dropping it here left the caller with nothing precise to
1890
+ * publish and no way to tell a committed write from an identity no-op.
1891
+ */
1892
+ readonly change: TreeModelChange | null;
1893
+ } | {
1894
+ readonly ok: false;
1895
+ readonly reason: TreeOpRejection | 'invalid-author';
1896
+ };
1897
+ /**
1898
+ * Add a comment, or a reply, in ONE transaction.
1899
+ *
1900
+ * The comment id and the `w14:paraId` are computed before the transaction opens, because the
1901
+ * story markers have to carry the same id the body does and deriving each separately is how the
1902
+ * two come to disagree.
1903
+ *
1904
+ * `w14:paraId` is minted here and only here: on a comment WRITE. Allocating on load would
1905
+ * rewrite a document nobody edited and break fingerprint equality on an untouched round trip.
1906
+ */
1907
+ declare function addComment(store: TreeDocumentStore, request: AddCommentRequest): AddCommentResult;
1908
+ /** Whether resolving a thread applied. Marks the comment AND every reply to it, as Word does. */
1909
+ type SetCommentResolvedResult = {
1910
+ readonly ok: true;
1911
+ readonly changed: boolean;
1912
+ /** The story transaction's change, for the coordinator to publish — see {@link AddCommentResult}. */
1913
+ readonly change: TreeModelChange | null;
1914
+ } | {
1915
+ readonly ok: false;
1916
+ readonly reason: TreeOpRejection | 'unknown-comment';
1917
+ };
1918
+ /**
1919
+ * Mark a comment thread resolved, or reopen it.
1920
+ *
1921
+ * A THREAD, not one remark: Word resolves a conversation, and its own pane greys the replies with
1922
+ * the comment they answer. Resolving only the parent would leave a file whose reply still reads as
1923
+ * open under a closed remark — a state Word does not produce and no reader would draw sensibly.
1924
+ *
1925
+ * `@w15:done` lives in `commentsExtended.xml`, which many documents do not have: a file with no
1926
+ * reply has no thread state to record. So the part is created when it is missing, exactly as
1927
+ * {@link addComment} creates it, and every comment being resolved gets an entry — a comment with
1928
+ * no `w14:paraId` gets one minted, because the state is keyed by it and there is nothing else to
1929
+ * key it by.
1930
+ *
1931
+ * ONE package transaction: the part, its relationship, its content-type override and the entries
1932
+ * commit together, so a resolved thread is never half-recorded.
1933
+ */
1934
+ declare function setCommentResolved(store: TreeDocumentStore, commentId: string, resolved: boolean): SetCommentResolvedResult;
1935
+ /** A comment part exists and declares the comment content type. */
1936
+ declare function hasCommentPart(pkg: OoxmlPackage, storyPartName: string): boolean;
1937
+ /** Exposed so a surface can tell "no comment part yet" from "no comments". */
1938
+ declare function commentPartNameOf(pkg: OoxmlPackage, storyPartName: string): string;
1939
+ /**
1940
+ * The `commentsExtended.xml` a story points at.
1941
+ *
1942
+ * Exported for the same reason as {@link commentPartNameOf}: the READER has to resolve the
1943
+ * same name the writer does. Hardcoding `/word/comments.xml` on one side and following the
1944
+ * relationship on the other is a split that shows up as a comment written and never read back.
1945
+ */
1946
+ declare function commentsExtendedPartNameOf(pkg: OoxmlPackage, storyPartName: string): string;
1947
+
1948
+ /** The D8 paragraph op vocabulary. */
1949
+ declare const AUTHORABLE_PARAGRAPH_PROPERTIES: ReadonlySet<string>;
1950
+ /** The D8 run op vocabulary, for `w:rPr` on a run and on the paragraph mark alike. */
1951
+ declare const AUTHORABLE_RUN_PROPERTIES: ReadonlySet<string>;
1952
+ /**
1953
+ * Whether an op may name this run property at all.
1954
+ *
1955
+ * The stored-marks lane needs this AT ARM TIME. Every other write reaches the store in the same
1956
+ * turn as the press, so a name the store refuses surfaces immediately; an ARMED property is not
1957
+ * applied until the user types, and it rides the keystroke's own transaction — a name outside the
1958
+ * vocabulary would take the typed characters down with it, silently, on every keystroke until the
1959
+ * caret moved.
1960
+ */
1961
+ declare function isAuthorableRunProperty(localName: string): boolean;
1962
+ /**
1963
+ * A node's own property container (`w:pPr`, `w:rPr`) among its children.
1964
+ *
1965
+ * A container the canonical read demoted to generic is still the node's own properties —
1966
+ * matching only the typed kind lost the whole set.
1967
+ */
1968
+ declare function propertyContainer(parent: OoxmlNode | null | undefined, kind: 'paragraphProperties' | 'runProperties', localName: 'pPr' | 'rPr'): OoxmlNode | undefined;
1969
+ /** What a container itself authors, narrowed to the names an op is allowed to carry. */
1970
+ declare function authoredProperties(container: OoxmlNode | undefined, authorable: ReadonlySet<string>): readonly OoxmlProperty[];
1971
+ /**
1972
+ * What a paragraph itself authors: its own `w:pPr`, narrowed to what an op can express.
1973
+ *
1974
+ * Properties outside the vocabulary are dropped from the OP, not from the paragraph: the applier
1975
+ * keeps every `w:pPr` child an op cannot name (the mark, `w:sectPr`, `w:pBdr`, `w:outlineLvl`)
1976
+ * exactly as authored.
1977
+ */
1978
+ declare function directParagraphProperties(part: OoxmlPart, paragraphId: string): readonly OoxmlProperty[];
1979
+ /**
1980
+ * What a paragraph MARK itself authors: `w:pPr/w:rPr`, narrowed to the run vocabulary.
1981
+ *
1982
+ * Same rule as a run's own `w:rPr`, for the same reason — the mark is a run property container,
1983
+ * and `setParagraphMarkProperties` rewrites the names its op carries.
1984
+ */
1985
+ declare function directParagraphMarkProperties(part: OoxmlPart, paragraphId: string): readonly OoxmlProperty[];
1986
+ /**
1987
+ * Merge properties into a set, replacing any entry with the same name.
1988
+ *
1989
+ * `setRunProperties` and `setParagraphProperties` REPLACE the whole container, so sending one
1990
+ * property alone deleted every other: pressing Bold stripped a run's font, size and colour, and
1991
+ * pressing Centre stripped a paragraph's style, numbering and indents.
1992
+ *
1993
+ * Takes one property or a list, because a toolbar press carries one and an object-model
1994
+ * formatting write carries several at once — and applying several one at a time would be the
1995
+ * same fold written at every call site.
1996
+ */
1997
+ declare function mergedProperties(existing: readonly OoxmlProperty[], incoming: OoxmlProperty | readonly OoxmlProperty[]): OoxmlProperty[];
1998
+ /** Per-run UTF-16 ranges from `segmentsOf` (fields/notes collapse to one unit on begin). */
1999
+ declare function runAddressRanges(paragraph: Extract<OoxmlNode, {
2000
+ kind: 'paragraph';
2001
+ }>): Map<string, {
2002
+ start: number;
2003
+ end: number;
2004
+ }>;
2005
+ /** Runs that own field-result formatting for atoms in this paragraph. */
2006
+ declare function formatOwnedRunIds(paragraph: Extract<OoxmlNode, {
2007
+ kind: 'paragraph';
2008
+ }>): ReadonlySet<string>;
2009
+ /** One run's share of a range edit: the slice it covers and the properties to write there. */
2010
+ interface RunPropertyEdit {
2011
+ readonly start: number;
2012
+ readonly end: number;
2013
+ readonly properties: readonly OoxmlProperty[];
2014
+ /**
2015
+ * When set, `setRunProperties` formats only these runs (field result ownership). Needed when
2016
+ * several result runs share one atom offset so each keeps its own merged bag.
2017
+ */
2018
+ readonly targetRunIds?: readonly string[];
2019
+ }
2020
+ /**
2021
+ * A range run-property change, split into ONE edit per run it covers, each merged over that
2022
+ * run's own `w:rPr`.
2023
+ *
2024
+ * Neither half of that is optional. The base MUST be the run's own properties (see this file's
2025
+ * header). And the split MUST be per run: the op REPLACES the properties it names across its
2026
+ * whole range, so one op carrying one run's bag over a mixed selection homogenised it — bolding
2027
+ * `hello ` + `Georgia` rewrote the second run's `w:rFonts` with the first's. Runs are addressed by
2028
+ * offset rather than by id because these edits apply in sequence and the applier splits runs at
2029
+ * the range edges; offsets are unmoved by a property write, ids are not.
2030
+ */
2031
+ declare function runPropertyEdits(part: OoxmlPart, paragraphId: string, start: number, end: number, incoming: OoxmlProperty | readonly OoxmlProperty[]): readonly RunPropertyEdit[];
2032
+ /**
2033
+ * Every run that contributes at least one character of `[start, end)`, in document order.
2034
+ *
2035
+ * A COLLAPSED range answers the run it sits inside, which is what a caret reads. Callers that
2036
+ * want the empty answer for a collapsed range check the offsets themselves.
2037
+ */
2038
+ declare function runsCovering(part: OoxmlPart, paragraphId: string, start: number, end: number): readonly OoxmlNode[];
2039
+
2040
+ interface RevisionSite {
2041
+ readonly node: OoxmlElement;
2042
+ readonly parent: OoxmlElement | null;
2043
+ /** True when this site cannot be resolved and the whole op must refuse. */
2044
+ readonly refused: boolean;
2045
+ /** True for `w:pPr/w:rPr/w:ins|w:del` — the paragraph MARK, not content. */
2046
+ readonly paragraphMark: boolean;
2047
+ /** True for `w:rPrChange` / `w:pPrChange`. */
2048
+ readonly propertyChange: boolean;
2049
+ }
2050
+ /**
2051
+ * Every revision-bearing element in the part, with the classification that decides whether it
2052
+ * can be resolved.
2053
+ *
2054
+ * One walk, so accept-all does not pay a traversal per revision — and paragraphs the last
2055
+ * commit did not touch are answered from {@link paragraphSitesCache} rather than re-walked.
2056
+ */
2057
+ declare function collectRevisionSites(part: OoxmlPart): RevisionSite[];
2058
+
2059
+ /** The `w:p` a node sits inside, and the model offset it starts at within that paragraph. */
2060
+ interface SiteLocation {
2061
+ readonly paragraphId: string;
2062
+ readonly start: number;
2063
+ readonly end: number;
2064
+ }
2065
+ /**
2066
+ * Locate every revision site in one walk.
2067
+ *
2068
+ * One walk rather than a lookup per site: `resolveRevisions` learned the same lesson the hard
2069
+ * way, where a per-site tree walk inside a per-site loop made accept-all quadratic.
2070
+ *
2071
+ * Offsets come from `paragraphOffsetIndex`, which is `segmentsOf`'s walk. A private one here
2072
+ * measured a run by summing its text and gave a note reference, an atomic field and a field's
2073
+ * instruction text the wrong lengths, so every card in a paragraph holding one reported a
2074
+ * range the caret and the ops disagreed with.
2075
+ */
2076
+ declare function locateSites(part: OoxmlPart): ReadonlyMap<string, SiteLocation>;
2077
+
2078
+ /**
2079
+ * Longest accepted query. A query is host input rather than file content, but the scan is
2080
+ * proportional to it and there is no legitimate find phrase this long.
2081
+ */
2082
+ declare const SEARCH_QUERY_MAX = 256;
2083
+ /**
2084
+ * Most matches one search returns. A single-character query against a long document would
2085
+ * otherwise allocate an entry per character; the scan stops here instead. A caller showing a
2086
+ * count treats a full result as "at least this many".
2087
+ */
2088
+ declare const SEARCH_MATCH_LIMIT = 2000;
2089
+ /** How a text search is narrowed. Options the engine cannot honour are refused, never ignored. */
2090
+ interface TextMatchOptions {
2091
+ readonly matchCase?: boolean;
2092
+ readonly wholeWord?: boolean;
2093
+ /**
2094
+ * Report only matches lying wholly inside `[from, to)`.
2095
+ *
2096
+ * A WINDOW ON THE TEXT, not a slice of it: the whole-word test still reads the characters on
2097
+ * either side of the window, so scanning the first three characters of `category` for `cat`
2098
+ * finds nothing when whole words were asked for. Slicing first would answer a match, because
2099
+ * the `e` that disqualifies it would have been cut off — the window is where a caller is
2100
+ * looking, not what the paragraph says.
2101
+ */
2102
+ readonly from?: number;
2103
+ readonly to?: number;
2104
+ }
2105
+ /** One occurrence, as UTF-16 offsets into the text that was scanned. */
2106
+ interface TextOccurrence {
2107
+ readonly start: number;
2108
+ readonly length: number;
2109
+ }
2110
+ /** Where a phrase occurs in a story, as paragraph-plus-offset ranges. */
2111
+ interface TextOccurrences {
2112
+ readonly matches: readonly TextOccurrence[];
2113
+ /** The scan stopped at `limit` with occurrences still ahead of it. */
2114
+ readonly truncated: boolean;
2115
+ }
2116
+ /**
2117
+ * Lower-case `text` WITHOUT changing its length.
2118
+ *
2119
+ * `String.prototype.toLowerCase` can expand (Turkish dotted capital I lowercases to two code
2120
+ * units), and an expansion mid-paragraph would slide every offset after it — the match would
2121
+ * be reported at the wrong place. The per-unit fallback folds only the characters that stay
2122
+ * one unit, so an expanding character simply compares case-sensitively. That is a real
2123
+ * degradation and it is the safe direction: a missed case-insensitive match beats a match
2124
+ * reported at an offset an editor then selects.
2125
+ */
2126
+ declare function foldCase(text: string): string;
2127
+ /** Whether a match at `[start, end)` in `text` stands alone as a word. */
2128
+ declare function isWholeWord(text: string, start: number, end: number): boolean;
2129
+ /** Whether a query is one this module will scan for at all. */
2130
+ declare function isSearchableQuery(query: unknown): query is string;
2131
+ /**
2132
+ * Every occurrence of `query` in `text`, in order, NON-OVERLAPPING.
2133
+ *
2134
+ * Non-overlapping is what a find dialog counts: `aa` in `aaaa` is two, not three. `limit` is
2135
+ * the caller's remaining budget, so a caller scanning many paragraphs enforces ONE global cap
2136
+ * rather than one per paragraph.
2137
+ */
2138
+ declare function findOccurrences(text: string, query: string, limit: number, options?: TextMatchOptions): TextOccurrences;
2139
+
2140
+ /** Impact class for a drawing op — metadata/locks are text-local; geometry/wrap are flow-structural. */
2141
+ declare function drawingOpImpact(op: DrawingTreeDocOp): ImpactClass;
2142
+ /** Validate a drawing op's extents, crops and positions before it reaches the store. */
2143
+ declare function validateDrawingOp(part: OoxmlPart, op: DrawingTreeDocOp): TreeOpRejection | null;
2144
+ /** Map the nine wrap targets to anchor wrap element + behindDoc. */
2145
+ declare function wrapTargetToAnchorSpec(target: ImageWrapTarget): {
2146
+ readonly behindDocument: boolean;
2147
+ readonly wrapLocalName: 'wrapNone' | 'wrapSquare' | 'wrapTight' | 'wrapThrough' | 'wrapTopAndBottom';
2148
+ readonly wrapText?: 'bothSides' | 'left' | 'right' | 'largest';
2149
+ };
2150
+ /** Whether an op is one of the drawing ops. Narrows the type. */
2151
+ declare function isDrawingTreeDocOp(op: TreeDocOp): op is DrawingTreeDocOp;
2152
+
2153
+ export { ALL_FROZEN_IDS, AUTHORABLE_PARAGRAPH_PROPERTIES, AUTHORABLE_RUN_PROPERTIES, type AddCommentRequest, type AddCommentResult, type AnchorSnapshot, type AtomicFieldSpan, type AuditPort, type AuthorizationPort, BoundedCounter, Budget, BudgetError, CANONICAL_MUTATION_ORIGINS, COMPARATORS, CUSTOM_NODE_XPATH_PREFIX, CUSTOM_XML_PROPS_REL, CUSTOM_XML_PROPS_TYPE, CUSTOM_XML_REL, CancellationController, CancellationError, type CancellationPhase, type CancellationPort, type CancellationToken, type CapabilityId, type ClockPort, type CommentAnchorRequest, type ComparatorDescriptor, type ComparatorMode, type ComparatorName, type ComparisonResult, type ConformanceFixture, type ContentItem, type Contribution, type CustomNodeBinding, type CustomNodeExportPolicy, type CustomNodeExportRequest, type CustomNodeExportResult, type CustomXmlDataPart, type CustomXmlDataPartResult, type CustomXmlNode, DANGEROUS_KEYS, DATASTORE_NAMESPACE_URI, DEPENDENCY_KEY_IDS, DangerousKeyError, type DetectedToc, DeterministicClock, DeterministicMemoryMeter, type DigestDifference, DrawingTreeDocOp, type EditOptions, type EncodedEnvelope, type EnforcementPhase, type EnsuredHyperlinkRelationship, type ExternalResourceConsentPort, FIELD_ATOM_CHAR, type FeatureBundle, type FixtureExpectation, type FixtureOutcome, type FixtureSource, type FixtureStep, type FldCharType, type FontPort, type HardBreakKind, type HrefProjection, ID_KINDS, INERT_EXECUTABLE_KINDS, type IdKind, type IdentityPort, type ImagePort, ImageWrapTarget, ImpactClass, type InertExecutableKind, type InlineControlSpan, type Json, LIMIT_KEYS, LIMIT_SPECS, LimitExceededError, type LimitSpec, type LimitUnit, MAX_STORY_SDT_NESTING, type ModelChangeSummary, NON_CANONICAL_ORIGINS, ORIGIN_IDS, type OffsetSpan, OoxmlAttribute, type OoxmlEditResult, OoxmlElement, OoxmlFldCharNode, OoxmlFldSimpleNode, OoxmlHardBreakNode, type OoxmlIndexes, OoxmlInstrTextNode, OoxmlInvariantIssue, OoxmlInvariantResult, OoxmlNode, OoxmlPackage, OoxmlParagraphNode, OoxmlPart, OoxmlProperty, type OoxmlStoryKind, type OoxmlStoryRoot, type OperationContext, type OperationInit, PAGE_BREAK_CHAR, type PackageInvariantCode, type PackageInvariantIssue, type PackageInvariantResult, type ParagraphDigest, type ParagraphIndexEntry, type ParagraphOffsetIndex, type PersistencePort, PortRegistry, PortResolutionError, PrefixAllocator, RESULT_IDS, RUNTIME_PORT_IDS, RegistryError, type RegistryErrorCode, RelationshipRecord, type ReplacementPolicy, type ReplayOutcome, type ReplayReport, type ReplayStore, type Reservation, type ResolveOptions, type ResolvedRegistry, type ResourceAccountingPort, ResourceLimits, type RunPropertyEdit, SEARCH_MATCH_LIMIT, SEARCH_QUERY_MAX, type SchedulingPort, type ScrubResult, type Segment, type SemVer, type SemanticDigest, SequentialIdentity, type SetCommentResolvedResult, type ShapingPort, type StoryDigest, type StoryIndexEntry, type StyleIndexEntry, TOC_LEVEL_INDENT_TWIPS, TOC_MAX_BOOKMARKS_PER_REFRESH, TOC_MAX_ENTRIES, TOC_MAX_FIELD_NESTING, TOC_MAX_INSTRUCTION_CHARS, TOC_MAX_PAGE_PASSES, type TextMatchOptions, type TextOccurrence, type TextOccurrences, type TocEntryPlan, type TocInstruction, type TocOutlineHeading, type TransportPort, TreeDocOp, TreeDocumentStore, TreeModelChange, TreeOpRejection, TreeOpResult, type ValidationResult, addComment, applyEdits, applyTreeOp, assertLimitInvariants, assertValidId, assertValidQName, atomicFieldSpansOf, authorableHyperlinkTarget, authoredProperties, beginOperation, bodyStoryRoot, bookmarkPairNodes, boundCustomXmlNodeIdOf, boundCustomXmlNodeIds, boundCustomXmlNodeIdsInPackage, buildTocContentControl, buildTocEntryParagraph, canonicalOoxmlFingerprint, canonicalize, cascadeEmptiedComments, collectNodeIds, collectRevisionSites, collectStoryParagraphs, commentPartNameOf, commentsExtendedPartNameOf, compareArtifacts, compareSemVer, containsCssFetch, contentTypesPartBytes, createNodeIdAllocator, customNodeBinding, customXmlDataParts, customXmlLabelXPath, customXmlNodes, customXmlPrefixMappings, datastoreItemIdFor, deleteCommentThread, deriveOoxmlIndexes, detectBodyTocs, diffSemanticDigests, digestPart, directParagraphMarkProperties, directParagraphProperties, drawingOpImpact, endOperation, ensureHyperlinkRelationship, escapeCssString, escapeXml, fieldAtomText, fieldOnOffAttribute, findCustomXmlDataPart, findDetectedToc, findNode, findOccurrences, fingerprint, fldCharType, fldSimpleInstr, fnv1a32, foldCase, formatOwnedRunIds, hardBreakAttributes, hardBreakKind, hardBreakText, hasAnyComment, hasCommentPart, hasNode, hashAuthored, indexStyles, inlineControlEndingAt, inlineControlStartingAt, insertChildren, instrTextValue, isAuthorableRunProperty, isDangerousKey, isDrawingTreeDocOp, isEvaluableField, isFieldChrome, isFldChar, isFldCharNode, isFldSimple, isFldSimpleNode, isInertExecutable, isInstrText, isInstrTextNode, isLegalFldCharType, isPageBreakNode, isSearchableQuery, isValidId, isValidNCName, isValidParaId, isValidQName, isWholeWord, locateSites, makeLimitCounter, mergedProperties, mintParaId, mintedParagraphIdentityAttributes, normalizeParagraphIdentity, nullRecord, ooxmlTreesEqual, paraIdOf, paragraphOffsetIndex, paragraphTextOf, parentNodeOf, parseSemVer, parseTocInstruction, planTocEntries, propertyContainer, readCustomXmlNode, relationshipTargetIn, relationshipsOf, relsPartNameFor, removeNode, replaceChildren, replaceNode, replayFixture, resolve, resolveContentTypeOf, resolveTocRowHeadings, runAddressRanges, runPropertyEdits, runsCovering, sanitizeHref, satisfies, scrubExport, segmentsOf, semanticDigest, serializeOoxmlPart, setCommentResolved, stableHash, storyParagraphs, storyRootsOf, stylesPartOf, toSafeRecord, tocEntryText, tocLeftIndentTwips, usedParaIds, validateDrawingOp, validateFixture, validateOoxmlPart, validatePackageInvariants, validateTreeOp, w14RootPrefix, withContentTypeOverride, withCustomXmlDataPart, withCustomXmlNode, withExportedCustomNodes, withNewPart, withRelationship, withoutCustomXmlDataPart, withoutCustomXmlNode, withoutOrphanCustomXmlNodes, wrapTargetToAnchorSpec };