@office-open/docx 0.10.15 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -17
- package/dist/index.d.mts +3774 -33
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +16469 -530
- package/dist/index.mjs.map +1 -1
- package/package.json +17 -34
- package/dist/chart.d.mts +0 -1
- package/dist/chart.mjs +0 -2
- package/dist/comments-D_flVfxw.mjs +0 -8509
- package/dist/comments-D_flVfxw.mjs.map +0 -1
- package/dist/context-DLmSgNzb.mjs +0 -4536
- package/dist/context-DLmSgNzb.mjs.map +0 -1
- package/dist/core-properties-BLnZI4Tr.d.mts +0 -4004
- package/dist/core-properties-BLnZI4Tr.d.mts.map +0 -1
- package/dist/document-attributes-C6PDT-ap.mjs +0 -60
- package/dist/document-attributes-C6PDT-ap.mjs.map +0 -1
- package/dist/drawingml.d.mts +0 -1
- package/dist/drawingml.mjs +0 -2
- package/dist/generate-BNjgksa0.mjs +0 -535
- package/dist/generate-BNjgksa0.mjs.map +0 -1
- package/dist/generate.d.mts +0 -10
- package/dist/generate.d.mts.map +0 -1
- package/dist/generate.mjs +0 -2
- package/dist/parse-CgAxzk5K.mjs +0 -2115
- package/dist/parse-CgAxzk5K.mjs.map +0 -1
- package/dist/parse.d.mts +0 -2
- package/dist/parse.mjs +0 -2
- package/dist/patch/index.d.mts +0 -47
- package/dist/patch/index.d.mts.map +0 -1
- package/dist/patch/index.mjs +0 -416
- package/dist/patch/index.mjs.map +0 -1
- package/dist/smartart.d.mts +0 -1
- package/dist/smartart.mjs +0 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["createWrapPolygon"],"sources":["../src/parts/paragraph/formatting/break.ts","../src/parts/paragraph/formatting/tab-stop.ts","../src/parts/paragraph/properties.ts","../src/parts/paragraph/run/properties.ts","../src/parts/paragraph/run/underline.ts","../src/parts/paragraph/run/emphasis-mark.ts","../src/parts/paragraph/run/positional-tab.ts","../src/parts/paragraph/run/ruby.ts","../src/parts/paragraph/run/proof-error.ts","../src/parts/paragraph/links/hyperlink.ts","../src/parts/paragraph/links/numbered-item-ref.ts","../src/parts/paragraph/frame/frame-properties.ts","../src/parts/table/table-properties/table-float-properties.ts","../src/parts/table/table-properties/table-layout.ts","../src/parts/table/table-properties/table-borders.ts","../src/parts/table/table-row/table-row-height.ts","../src/parts/drawing/text-wrap/wrap-tight.ts","../src/parts/drawing/text-wrap/wrap-through.ts","../src/parts/drawing/floating/horizontal-position.ts","../src/parts/drawing/floating/vertical-position.ts","../src/parts/document/body/section-properties/properties/doc-grid.ts","../src/parts/document/body/section-properties/properties/page-borders.ts","../src/parts/document/body/section-properties/properties/page-margin.ts","../src/parts/document/body/section-properties/properties/line-number.ts","../src/parts/document/body/section-properties/properties/section-type.ts","../src/parts/document/body/section-properties/properties/header-footer-reference.ts","../src/parts/table-of-contents/table-of-contents-properties.ts","../src/parts/table-of-contents/sdt-properties.ts","../src/parts/footnotes/footnote/footnote.ts","../src/parts/endnotes/endnote/endnote.ts","../src/parts/perm-start.ts","../src/parts/fonts/font.ts","../src/parts/relationships.ts","../src/shared/track-revision/track-revision-components/cell-merge.ts","../src/shared/vertical-align.ts"],"sourcesContent":["/**\n * Break type values for WordprocessingML documents.\n *\n * @module\n */\n\n/**\n * Break type constants.\n * @internal\n */\nexport const BreakType = {\n /** Column break */\n COLUMN: \"column\",\n /** Page break */\n PAGE: \"page\",\n} as const;\n\nexport type BreakTypeValue = (typeof BreakType)[keyof typeof BreakType];\n","/**\n * Tab stop module for WordprocessingML documents.\n *\n * This module provides tab stop definitions for paragraphs.\n *\n * Reference: http://officeopenxml.com/WPtab.php\n *\n * @module\n */\n\n/**\n * Definition for a single tab stop.\n *\n * @see {@link TabStop}\n */\nexport interface TabStopDefinition {\n /** The type of tab stop alignment */\n type: (typeof TabStopType)[keyof typeof TabStopType];\n /** The position of the tab stop in twips */\n position: number | (typeof TabStopPosition)[keyof typeof TabStopPosition];\n /** Optional leader character to fill space before the tab */\n leader?: (typeof LeaderType)[keyof typeof LeaderType];\n}\n\n/**\n * Tab stop alignment types.\n *\n * Specifies the type of tab stop and how text aligns to it.\n *\n * @publicApi\n */\nexport const TabStopType = {\n /** Left-aligned tab stop */\n LEFT: \"left\",\n /** Right-aligned tab stop */\n RIGHT: \"right\",\n /** Center-aligned tab stop */\n CENTER: \"center\",\n /** Bar tab stop - inserts a vertical bar at the position */\n BAR: \"bar\",\n /** Clears a tab stop at the specified position */\n CLEAR: \"clear\",\n /** Decimal-aligned tab stop - aligns on decimal point */\n DECIMAL: \"decimal\",\n /** End-aligned tab stop (right-to-left equivalent) */\n END: \"end\",\n /** List tab stop for numbered lists */\n NUM: \"num\",\n /** Start-aligned tab stop (left-to-right equivalent) */\n START: \"start\",\n} as const;\n\n/**\n * Tab stop leader character types.\n *\n * Specifies the character used to fill the space before the tab stop.\n *\n * @publicApi\n */\nexport const LeaderType = {\n /** Dot leader (....) */\n DOT: \"dot\",\n /** Heavy leader */\n HEAVY: \"heavy\",\n /** Hyphen leader (----) */\n HYPHEN: \"hyphen\",\n /** Middle dot leader (····) */\n MIDDLE_DOT: \"middleDot\",\n /** No leader */\n NONE: \"none\",\n /** Underscore leader (____) */\n UNDERSCORE: \"underscore\",\n} as const;\n\n/**\n * Predefined tab stop positions.\n *\n * @publicApi\n */\nexport const TabStopPosition = {\n /** Maximum tab stop position (right margin) */\n MAX: 9026,\n} as const;\n","import type { ShadingProperties } from \"@shared/shading\";\n/**\n * Paragraph properties types for WordprocessingML documents.\n *\n * Reference: http://officeopenxml.com/WPparagraphProperties.php\n *\n * @module\n */\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport type { AlignmentType } from \"./formatting/alignment\";\nimport type { BordersOptions } from \"./formatting/border\";\nimport type { CnfConditionalOptions } from \"./formatting/cnf-style\";\nimport type { IndentProperties } from \"./formatting/indent\";\nimport type { SpacingProperties } from \"./formatting/spacing\";\nimport type { HeadingLevel } from \"./formatting/style\";\nimport type { TabStopDefinition } from \"./formatting/tab-stop\";\nimport type { FrameOptions } from \"./frame/frame-properties\";\nimport type { ParagraphRunOptions } from \"./run/run\";\n\n/**\n * Vertical text alignment types for paragraphs.\n *\n * Specifies the vertical alignment of text within the paragraph.\n *\n * @publicApi\n */\nexport const TextAlignmentType = {\n /** Align text to the top */\n TOP: \"top\",\n /** Align text to the center */\n CENTER: \"center\",\n /** Align text to the baseline */\n BASELINE: \"baseline\",\n /** Align text to the bottom */\n BOTTOM: \"bottom\",\n /** Automatically determine vertical alignment */\n AUTO: \"auto\",\n} as const;\n\n/**\n * Textbox tight wrap types for paragraphs.\n *\n * Specifies how tightly text wraps around a textbox.\n *\n * @publicApi\n */\nexport const TextboxTightWrapType = {\n /** No tight wrapping */\n NONE: \"none\",\n /** Tight wrap on all lines */\n ALL_LINES: \"allLines\",\n /** Tight wrap on first and last lines */\n FIRST_AND_LAST_LINE: \"firstAndLastLine\",\n /** Tight wrap on first line only */\n FIRST_LINE_ONLY: \"firstLineOnly\",\n /** Tight wrap on last line only */\n LAST_LINE_ONLY: \"lastLineOnly\",\n} as const;\n\n/**\n * Paragraph style properties for numbering levels.\n *\n * These properties are used when defining paragraph styles within numbering level definitions.\n */\nexport interface LevelParagraphStylePropertiesOptions {\n /** Paragraph text alignment (left, right, center, justified, etc.) */\n alignment?: (typeof AlignmentType)[keyof typeof AlignmentType];\n /** Whether to render text right-to-left for bidirectional languages */\n bidirectional?: boolean;\n /** Whether to insert a page break before this paragraph */\n pageBreakBefore?: boolean;\n /** Custom tab stop positions and alignments */\n tabStops?: TabStopDefinition[];\n /** Whether to display a horizontal line (thematic break) below the paragraph */\n thematicBreak?: boolean;\n /** Whether to prevent single lines at top/bottom of page (widow/orphan control), defaults to true */\n widowControl?: boolean;\n /** Whether to ignore spacing before/after when adjacent paragraphs have the same style */\n contextualSpacing?: boolean;\n /** Position in twips for a right-aligned tab stop */\n rightTabStop?: number;\n /** Position in twips for a left-aligned tab stop */\n leftTabStop?: number;\n /** Indentation settings for the paragraph */\n indent?: IndentProperties;\n /** Spacing before/after paragraph and between lines */\n spacing?: SpacingProperties;\n /**\n * Specifies that the paragraph (or at least part of it) should be rendered on the same page as the next paragraph when possible. If multiple paragraphs are to be kept together but they exceed a page, then the set of paragraphs begin on a new page and page breaks are used thereafter as needed.\n */\n keepNext?: boolean;\n /**\n * Specifies that all lines of the paragraph are to be kept on a single page when possible.\n */\n keepLines?: boolean;\n /** Frame properties for positioning the paragraph */\n frame?: FrameOptions;\n /** Whether to suppress line numbers for this paragraph */\n suppressLineNumbers?: boolean;\n /** Whether to allow word wrapping */\n wordWrap?: boolean;\n /** Whether to allow punctuation to extend beyond text margins */\n overflowPunctuation?: boolean;\n /**\n * This element specifies whether inter-character spacing shall automatically be adjusted between regions of numbers and regions of East Asian text in the current paragraph. These regions shall be determined by the Unicode character values of the text content within the paragraph.\n * This only works in Microsoft Word. It is not part of the ECMA-376 OOXML standard.\n */\n autoSpaceEastAsianText?: boolean;\n /** Whether to prevent text frames from overlapping */\n suppressOverlap?: boolean;\n /** Whether to disable automatic hyphenation for this paragraph */\n suppressAutoHyphens?: boolean;\n /** Whether to automatically adjust right indent for document grid */\n adjustRightInd?: boolean;\n /** Whether to snap the current paragraph to the document grid */\n snapToGrid?: boolean;\n /** Whether to swap left and right indent positions on odd pages for mirrored layouts */\n mirrorIndents?: boolean;\n /** Whether to use Kinsoku forbidden character overflow rules */\n kinsoku?: boolean;\n /** Whether to compress punctuation at the start of a line */\n topLinePunct?: boolean;\n /** Whether to automatically add space between East Asian and Latin text */\n autoSpaceDE?: boolean;\n /** Vertical text alignment within the paragraph */\n textAlignment?: (typeof TextAlignmentType)[keyof typeof TextAlignmentType];\n /** Textbox tight wrap setting */\n textboxTightWrap?: (typeof TextboxTightWrapType)[keyof typeof TextboxTightWrapType];\n /** Text direction for the paragraph (lr, rl, tb, tbV, rlV, lrV) */\n textDirection?: \"lr\" | \"rl\" | \"tb\" | \"tbV\" | \"rlV\" | \"lrV\";\n /** Outline level for table of contents and document outline (0-9) */\n outlineLevel?: number;\n /** HTML div ID reference */\n divId?: number;\n /** Conditional formatting style for table rows/cells */\n cnfStyle?: CnfConditionalOptions;\n}\n\n/**\n * Paragraph style properties options.\n *\n * These properties are used when defining paragraph styles and include\n * border, shading, and numbering options in addition to level properties.\n */\nexport type ParagraphStylePropertiesOptions = {\n /** Border settings for the paragraph */\n border?: BordersOptions;\n /** Background shading/fill color for the paragraph */\n shading?: ShadingProperties;\n /** Numbering configuration for lists, or false to remove numbering */\n numbering?:\n | {\n /** Reference ID of the numbering definition to use */\n reference: string;\n /** Level in the numbering hierarchy (0-8) */\n level: number;\n /** Instance number for multiple lists with same reference */\n instance?: number;\n /** Whether this is a custom numbering definition */\n custom?: boolean;\n /** Numbering change tracking (CT_TrackChangeNumbering) */\n numberingChange?: {\n /** Original numbering value */\n original: string;\n /** Revision ID */\n id: string;\n /** Author of the change */\n author: string;\n /** Date of the change */\n date?: string;\n };\n }\n | false;\n} & LevelParagraphStylePropertiesOptions;\n\nexport type ParagraphPropertiesOptionsBase = {\n /** Heading level (Heading1, Heading2, etc.) - applies predefined heading style */\n heading?: (typeof HeadingLevel)[keyof typeof HeadingLevel];\n /** Style ID to apply to this paragraph */\n style?: string;\n /** Bullet list configuration */\n bullet?: {\n /** Indentation level for the bullet (0-8) */\n level: number;\n };\n /**\n * Run properties to apply to all runs in the paragraph.\n * Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.3.1.29.\n */\n run?: ParagraphRunOptions;\n} & ParagraphStylePropertiesOptions;\n\nexport type ParagraphPropertiesChangeOptions = ChangedProperties & ParagraphPropertiesOptionsBase;\n\n/**\n * Options for configuring paragraph properties.\n *\n * These options control all aspects of paragraph formatting including\n * alignment, spacing, indentation, borders, numbering, and more.\n *\n * Reference: http://officeopenxml.com/WPparagraphProperties.php\n */\nexport type ParagraphPropertiesOptions = {\n revision?: ParagraphPropertiesChangeOptions;\n includeIfEmpty?: boolean;\n} & ParagraphPropertiesOptionsBase;\n","/**\n * Run properties module for WordprocessingML documents.\n *\n * This module provides the run properties (rPr) element which specifies\n * the formatting applied to a run of text.\n *\n * Reference: https://www.ecma-international.org/wp-content/uploads/ECMA-376-1_5th_edition_december_2016.zip\n * Section 17.3.2.21 (page 297)\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { BorderOptions } from \"@shared/border\";\nimport type { ShadingProperties } from \"@shared/shading\";\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport type { EastAsianLayoutOptions } from \"./east-asian-layout\";\nimport type { EmphasisMarkType } from \"./emphasis-mark\";\nimport type { ColorOptions } from \"./formatting\";\nimport type { LanguageOptions } from \"./language\";\nimport type { FontProperties } from \"./run-fonts\";\nimport type { UnderlineType } from \"./underline\";\n\ninterface RunFontReference {\n name: string;\n hint?: string;\n}\n\n/**\n * Text animation effect types.\n *\n * Reference: http://officeopenxml.com/WPtextFormatting.php\n *\n * @publicApi\n */\nexport const TextEffect = {\n /** Blinking background animation */\n BLINK_BACKGROUND: \"blinkBackground\",\n /** Lights animation effect */\n LIGHTS: \"lights\",\n /** Black marching ants animation */\n ANTS_BLACK: \"antsBlack\",\n /** Red marching ants animation */\n ANTS_RED: \"antsRed\",\n /** Shimmer animation effect */\n SHIMMER: \"shimmer\",\n /** Sparkle animation effect */\n SPARKLE: \"sparkle\",\n /** No text effect */\n NONE: \"none\",\n} as const;\n\n/**\n * Highlight color values for text highlighting.\n *\n * Reference: http://officeopenxml.com/WPtextShading.php\n */\nexport const HighlightColor = {\n /** Black highlight */\n BLACK: \"black\",\n /** Blue highlight */\n BLUE: \"blue\",\n /** Cyan highlight */\n CYAN: \"cyan\",\n /** Dark blue highlight */\n DARK_BLUE: \"darkBlue\",\n /** Dark cyan highlight */\n DARK_CYAN: \"darkCyan\",\n /** Dark gray highlight */\n DARK_GRAY: \"darkGray\",\n /** Dark green highlight */\n DARK_GREEN: \"darkGreen\",\n /** Dark magenta highlight */\n DARK_MAGENTA: \"darkMagenta\",\n /** Dark red highlight */\n DARK_RED: \"darkRed\",\n /** Dark yellow highlight */\n DARK_YELLOW: \"darkYellow\",\n /** Green highlight */\n GREEN: \"green\",\n /** Light gray highlight */\n LIGHT_GRAY: \"lightGray\",\n /** Magenta highlight */\n MAGENTA: \"magenta\",\n /** No highlight */\n NONE: \"none\",\n /** Red highlight */\n RED: \"red\",\n /** White highlight */\n WHITE: \"white\",\n /** Yellow highlight */\n YELLOW: \"yellow\",\n} as const;\n\n/**\n * Run style properties options.\n *\n * These properties define the formatting that can be applied to a run of text,\n * including font, size, bold, italic, underline, color, and other character formatting.\n *\n * Reference: http://officeopenxml.com/WPtextFormatting.php\n */\nexport interface RunStylePropertiesOptions {\n noProof?: boolean;\n bold?: boolean;\n boldComplexScript?: boolean;\n italic?: boolean;\n italicComplexScript?: boolean;\n underline?: {\n color?: string;\n type?: (typeof UnderlineType)[keyof typeof UnderlineType];\n };\n effect?: (typeof TextEffect)[keyof typeof TextEffect];\n emphasisMark?: {\n type?: (typeof EmphasisMarkType)[keyof typeof EmphasisMarkType];\n };\n color?: string | ColorOptions;\n kern?: number;\n position?: string;\n /** Font size in points. Internally stored as half-points in XML (×2). */\n size?: number;\n /** Complex-script font size in points (w:szCs). Independent from {@link size}. */\n sizeComplexScript?: number;\n rightToLeft?: boolean;\n smallCaps?: boolean;\n allCaps?: boolean;\n strike?: boolean;\n doubleStrike?: boolean;\n subScript?: boolean;\n superScript?: boolean;\n font?: string | RunFontReference | FontProperties;\n highlight?: (typeof HighlightColor)[keyof typeof HighlightColor];\n /** Complex-script highlight color (w:highlightCs). Independent from {@link highlight}. */\n highlightComplexScript?: string;\n characterSpacing?: number | UniversalMeasure;\n shading?: ShadingProperties;\n emboss?: boolean;\n imprint?: boolean;\n revision?: RunPropertiesChangeOptions;\n language?: LanguageOptions;\n border?: BorderOptions;\n snapToGrid?: boolean;\n vanish?: boolean;\n specVanish?: boolean;\n scale?: number;\n math?: boolean;\n outline?: boolean;\n shadow?: boolean;\n webHidden?: boolean;\n fitText?: number;\n complexScript?: boolean;\n eastAsianLayout?: EastAsianLayoutOptions;\n /** Relationship ID for a content part (w:contentPart with r:id) */\n contentPartRId?: string;\n /**\n * Raw XML for w14:* text-effect children (glow/shadow/reflection/props3d/...)\n * located in the EG_RPrBase extension slot at the end of rPr. Low-frequency\n * complex subtrees kept verbatim for round-trip fidelity; the rPr backbone\n * stays structured and editable.\n */\n w14RawXml?: string;\n}\n\n/**\n * Options for configuring run properties.\n *\n * Extends RunStylePropertiesOptions with a style reference.\n */\nexport type RunPropertiesOptions = {\n /** Reference to a character style by name */\n style?: string;\n} & RunStylePropertiesOptions;\n\n/**\n * Options for run properties change tracking.\n *\n * Used for revision tracking when run properties have been modified.\n */\nexport type RunPropertiesChangeOptions = {} & RunPropertiesOptions & ChangedProperties;\n\nexport type ParagraphRunPropertiesOptions = {\n insertion?: ChangedProperties;\n deletion?: ChangedProperties;\n} & RunPropertiesOptions;\n","/**\n * Underline module for WordprocessingML documents.\n *\n * This module provides support for underlining text with various styles and colors.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * @module\n */\n\n/**\n * Underline style types for text.\n *\n * Defines the various underline patterns that can be applied to text runs.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Underline\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"single\"/>\n * <xsd:enumeration value=\"words\"/>\n * <xsd:enumeration value=\"double\"/>\n * <xsd:enumeration value=\"thick\"/>\n * <xsd:enumeration value=\"dotted\"/>\n * <xsd:enumeration value=\"dottedHeavy\"/>\n * <xsd:enumeration value=\"dash\"/>\n * <xsd:enumeration value=\"dashedHeavy\"/>\n * <xsd:enumeration value=\"dashLong\"/>\n * <xsd:enumeration value=\"dashLongHeavy\"/>\n * <xsd:enumeration value=\"dotDash\"/>\n * <xsd:enumeration value=\"dashDotHeavy\"/>\n * <xsd:enumeration value=\"dotDotDash\"/>\n * <xsd:enumeration value=\"dashDotDotHeavy\"/>\n * <xsd:enumeration value=\"wave\"/>\n * <xsd:enumeration value=\"wavyHeavy\"/>\n * <xsd:enumeration value=\"wavyDouble\"/>\n * <xsd:enumeration value=\"none\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const UnderlineType = {\n /** Single underline */\n SINGLE: \"single\",\n /** Underline words only (not spaces) */\n WORDS: \"words\",\n /** Double underline */\n DOUBLE: \"double\",\n /** Thick single underline */\n THICK: \"thick\",\n /** Dotted underline */\n DOTTED: \"dotted\",\n /** Heavy dotted underline */\n DOTTEDHEAVY: \"dottedHeavy\",\n /** Dashed underline */\n DASH: \"dash\",\n /** Heavy dashed underline */\n DASHEDHEAVY: \"dashedHeavy\",\n /** Long dashed underline */\n DASHLONG: \"dashLong\",\n /** Heavy long dashed underline */\n DASHLONGHEAVY: \"dashLongHeavy\",\n /** Dot-dash underline */\n DOTDASH: \"dotDash\",\n /** Heavy dot-dash underline */\n DASHDOTHEAVY: \"dashDotHeavy\",\n /** Dot-dot-dash underline */\n DOTDOTDASH: \"dotDotDash\",\n /** Heavy dot-dot-dash underline */\n DASHDOTDOTHEAVY: \"dashDotDotHeavy\",\n /** Wave underline */\n WAVE: \"wave\",\n /** Heavy wave underline */\n WAVYHEAVY: \"wavyHeavy\",\n /** Double wave underline */\n WAVYDOUBLE: \"wavyDouble\",\n /** No underline */\n NONE: \"none\",\n} as const;\n","/**\n * Emphasis mark module for WordprocessingML run properties.\n *\n * This module provides support for East Asian emphasis marks, which are\n * characters placed above or below text to emphasize it.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * @module\n */\n\n/**\n * Emphasis mark types.\n *\n * Defines the types of emphasis marks that can be applied to text.\n * Emphasis marks are commonly used in East Asian typography.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Em\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"none\"/>\n * <xsd:enumeration value=\"dot\"/>\n * <xsd:enumeration value=\"comma\"/>\n * <xsd:enumeration value=\"circle\"/>\n * <xsd:enumeration value=\"underDot\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const EmphasisMarkType = {\n /** No emphasis mark */\n NONE: \"none\",\n /** Comma emphasis mark */\n COMMA: \"comma\",\n /** Circle emphasis mark */\n CIRCLE: \"circle\",\n /** Dot emphasis mark */\n DOT: \"dot\",\n /** Under dot emphasis mark */\n UNDER_DOT: \"underDot\",\n} as const;\n","/**\n * Positional tab types for WordprocessingML documents.\n *\n * @module\n */\n\nexport const PositionalTabAlignment = {\n LEFT: \"left\",\n CENTER: \"center\",\n RIGHT: \"right\",\n} as const;\n\nexport const PositionalTabRelativeTo = {\n MARGIN: \"margin\",\n INDENT: \"indent\",\n} as const;\n\nexport const PositionalTabLeader = {\n NONE: \"none\",\n DOT: \"dot\",\n HYPHEN: \"hyphen\",\n UNDERSCORE: \"underscore\",\n MIDDLE_DOT: \"middleDot\",\n} as const;\n\nexport interface PositionalTabOptions {\n alignment: (typeof PositionalTabAlignment)[keyof typeof PositionalTabAlignment];\n relativeTo: (typeof PositionalTabRelativeTo)[keyof typeof PositionalTabRelativeTo];\n leader: (typeof PositionalTabLeader)[keyof typeof PositionalTabLeader];\n}\n","/**\n * Ruby annotation module for WordprocessingML documents.\n *\n * Ruby annotations are small text rendered above or below base text,\n * commonly used for pronunciation guides in East Asian languages (furigana\n * in Japanese, pinyin in Chinese, etc.).\n *\n * Used via the JSON API: `{ ruby: { text: \"かな\", base: \"漢字\" } }` as a\n * paragraph or run child.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_Ruby\n *\n * @module\n */\n\n/**\n * Ruby alignment options.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_RubyAlign\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"center\"/>\n * <xsd:enumeration value=\"distributeLetter\"/>\n * <xsd:enumeration value=\"distributeSpace\"/>\n * <xsd:enumeration value=\"left\"/>\n * <xsd:enumeration value=\"right\"/>\n * <xsd:enumeration value=\"rightVertical\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const RubyAlign = {\n /** Center alignment */\n CENTER: \"center\",\n /** Distribute letters evenly */\n DISTRIBUTE_LETTER: \"distributeLetter\",\n /** Distribute space evenly */\n DISTRIBUTE_SPACE: \"distributeSpace\",\n /** Left alignment */\n LEFT: \"left\",\n /** Right alignment */\n RIGHT: \"right\",\n /** Right vertical alignment */\n RIGHT_VERTICAL: \"rightVertical\",\n} as const;\n\n/**\n * Options for a Ruby annotation.\n *\n * Used as `{ ruby: RubyOptions }` in paragraph or run children.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Ruby\">\n * <xsd:sequence>\n * <xsd:element name=\"rubyPr\" type=\"CT_RubyPr\"/>\n * <xsd:element name=\"rt\" type=\"CT_RubyContent\"/>\n * <xsd:element name=\"rubyBase\" type=\"CT_RubyContent\"/>\n * </xsd:sequence>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Japanese furigana\n * { ruby: {\n * text: \"かな\",\n * base: \"漢字\",\n * alignment: \"center\",\n * fontSize: 20,\n * languageId: \"ja-JP\",\n * }}\n * ```\n */\nexport interface RubyOptions {\n /** Ruby annotation text (e.g., furigana, pinyin) */\n text: string;\n /** Base text being annotated */\n base: string;\n /** Ruby alignment (defaults to \"center\"). */\n alignment?: (typeof RubyAlign)[keyof typeof RubyAlign];\n /**\n * Font size for the ruby annotation text in points (e.g., 10 = 10pt).\n * Defaults to half the base text size if not specified.\n */\n fontSize?: number;\n /**\n * Vertical offset for the ruby annotation in points.\n * How far the annotation is raised above (or below) the base text.\n */\n raise?: number;\n /**\n * Font size for the base text in points.\n * Used to calculate the ruby annotation positioning.\n */\n baseFontSize?: number;\n /** Language identifier for the ruby annotation (e.g., \"ja-JP\"). */\n languageId?: string;\n /** Whether the ruby annotation is dirty (needs recalculation). */\n dirty?: boolean;\n}\n","/**\n * Proof error types for WordprocessingML documents.\n *\n * @module\n */\n\nexport const ProofErrorType = {\n SPELL_START: \"spellStart\",\n SPELL_END: \"spellEnd\",\n GRAM_START: \"gramStart\",\n GRAM_END: \"gramEnd\",\n} as const;\n\nexport type ProofErrorTypeValue = (typeof ProofErrorType)[keyof typeof ProofErrorType];\n","/**\n * Hyperlink types for WordprocessingML documents.\n *\n * @module\n */\n\n/**\n * Hyperlink type enumeration.\n * @publicApi\n */\nexport const HyperlinkType = {\n /** Internal hyperlink to a bookmark within the document */\n INTERNAL: \"INTERNAL\",\n /** External hyperlink to a URL outside the document */\n EXTERNAL: \"EXTERNAL\",\n} as const;\n\n/**\n * Options for creating an internal hyperlink.\n */\nexport interface InternalHyperlinkOptions {\n /** Name of the bookmark to link to within the document */\n anchor: string;\n /** Screen tip text shown when hovering over the hyperlink */\n tooltip?: string;\n}\n\n/**\n * Options for creating an external hyperlink.\n */\nexport interface ExternalHyperlinkOptions {\n /** URL to link to outside the document */\n link: string;\n /** Screen tip text shown when hovering over the hyperlink */\n tooltip?: string;\n /** Target frame for the hyperlink (e.g., \"_blank\", \"_self\") */\n tgtFrame?: string;\n}\n","/**\n * Numbered item reference module for WordprocessingML documents.\n *\n * This module provides cross-references to numbered items (such as\n * numbered paragraphs, list items, or headings) within a document.\n *\n * Reference: https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oi29500/7088a8ce-e784-49d4-94b8-cba6ef8fce78\n *\n * @module\n */\n\n/**\n * Format options for numbered item references.\n *\n * Specifies how the paragraph number should be displayed when referenced.\n */\nexport enum NumberedItemReferenceFormat {\n NONE = \"none\",\n /**\n * \\r option - inserts the paragraph number of the bookmarked paragraph in relative context, or relative to its position in the numbering scheme\n */\n RELATIVE = \"relative\",\n /**\n * \\n option - causes the field result to be the paragraph number without trailing periods. No information about prior numbered levels is displayed unless it is included as part of the current level.\n */\n NO_CONTEXT = \"no_context\",\n /**\n * \\w option - causes the field result to be the entire paragraph number without trailing periods, regardless of the location of the REF field.\n */\n FULL_CONTEXT = \"full_context\",\n}\n\nexport interface NumberedItemReferenceOptions {\n /**\n * \\h option - Creates a hyperlink to the bookmarked paragraph.\n * @default true\n */\n hyperlink?: boolean;\n /**\n * Which switch to use for the reference format\n * @default NumberedItemReferenceFormat.FULL_CONTEXT\n */\n referenceFormat?: NumberedItemReferenceFormat;\n}\n","/**\n * Frame properties module for paragraph text frames in WordprocessingML documents.\n *\n * Frames allow paragraphs to be positioned absolutely on the page, enabling text wrapping\n * and drop cap effects. They are commonly used for floating text boxes and decorative elements.\n *\n * Reference: http://officeopenxml.com/WPparagraph-textFrames.php\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { HeightRule } from \"@parts/table\";\nimport type { HorizontalPositionAlign, VerticalPositionAlign } from \"@shared/constants\";\n\n/**\n * Drop cap types for paragraph frames.\n */\nexport const DropCapType = {\n /** No drop cap effect */\n NONE: \"none\",\n /** Drop cap that drops down into the paragraph text */\n DROP: \"drop\",\n /** Drop cap that extends into the margin */\n MARGIN: \"margin\",\n} as const;\n\n/**\n * Frame anchor types specifying what the frame should be anchored relative to.\n */\nexport const FrameAnchorType = {\n /** Anchor relative to the page margin */\n MARGIN: \"margin\",\n /** Anchor relative to the page edge */\n PAGE: \"page\",\n /** Anchor relative to the text column */\n TEXT: \"text\",\n} as const;\n\n/**\n * Text wrapping types for frames.\n */\nexport const FrameWrap = {\n /** Wrap text around the frame on all sides */\n AROUND: \"around\",\n /** Automatic wrapping based on available space */\n AUTO: \"auto\",\n /** No text wrapping */\n NONE: \"none\",\n /** Do not allow text beside the frame */\n NOT_BESIDE: \"notBeside\",\n /** Allow text to flow through the frame */\n THROUGH: \"through\",\n /** Wrap text tightly around the frame */\n TIGHT: \"tight\",\n} as const;\n\n/**\n * Base options shared by all frame types.\n */\ninterface BaseFrameOptions {\n /** Lock the anchor position to prevent it from moving */\n anchorLock?: boolean;\n /** Drop cap effect type */\n dropCap?: (typeof DropCapType)[keyof typeof DropCapType];\n /** Frame width in twips or universal measure (e.g., \"1cm\", \"0.5in\") */\n width: number | UniversalMeasure;\n /** Frame height in twips or universal measure (e.g., \"1cm\", \"0.5in\") */\n height: number | UniversalMeasure;\n /** Text wrapping behavior around the frame */\n wrap?: (typeof FrameWrap)[keyof typeof FrameWrap];\n /** Number of lines for drop cap effect */\n lines?: number;\n /** Anchor reference points for horizontal and vertical positioning */\n anchor: {\n /** Horizontal anchor reference point */\n horizontal: (typeof FrameAnchorType)[keyof typeof FrameAnchorType];\n /** Vertical anchor reference point */\n vertical: (typeof FrameAnchorType)[keyof typeof FrameAnchorType];\n };\n /** Spacing between frame and surrounding text in twips */\n space?: {\n /** Horizontal spacing in twips or universal measure */\n horizontal: number | UniversalMeasure;\n /** Vertical spacing in twips or universal measure */\n vertical: number | UniversalMeasure;\n };\n /** Height rule determining how frame height is calculated */\n rule?: (typeof HeightRule)[keyof typeof HeightRule];\n}\n\n/**\n * Options for frames positioned using absolute X/Y coordinates.\n */\nexport type XYFrameOptions = {\n /** Must be \"absolute\" for coordinate-based positioning */\n type: \"absolute\";\n /** Absolute X and Y coordinates in twips */\n position: {\n /** Horizontal position in twips or universal measure from the anchor point */\n x: number | UniversalMeasure;\n /** Vertical position in twips or universal measure from the anchor point */\n y: number | UniversalMeasure;\n };\n} & BaseFrameOptions;\n\n/**\n * Options for frames positioned using alignment values.\n */\nexport type AlignmentFrameOptions = {\n /** Must be \"alignment\" for alignment-based positioning */\n type: \"alignment\";\n /** Horizontal and vertical alignment values */\n alignment: {\n /** Horizontal alignment relative to the anchor */\n x: (typeof HorizontalPositionAlign)[keyof typeof HorizontalPositionAlign];\n /** Vertical alignment relative to the anchor */\n y: (typeof VerticalPositionAlign)[keyof typeof VerticalPositionAlign];\n };\n} & BaseFrameOptions;\n\n/**\n * Union type for all frame positioning options.\n */\nexport type FrameOptions = XYFrameOptions | AlignmentFrameOptions;\n","/**\n * Table float properties module for WordprocessingML documents.\n *\n * This module provides floating table positioning options, allowing tables\n * to float with text wrapping around them.\n *\n * Reference: http://officeopenxml.com/WPtableFloating.php\n *\n * @module\n */\n\n/**\n * Anchor types for floating table positioning.\n *\n * Specifies the base object from which positioning is determined.\n */\nexport const TableAnchorType = {\n MARGIN: \"margin\",\n PAGE: \"page\",\n TEXT: \"text\",\n} as const;\n\n/**\n * Relative horizontal position values for floating tables.\n */\nexport const RelativeHorizontalPosition = {\n CENTER: \"center\",\n INSIDE: \"inside\",\n LEFT: \"left\",\n OUTSIDE: \"outside\",\n RIGHT: \"right\",\n} as const;\n\n/**\n * Relative vertical position values for floating tables.\n */\nexport const RelativeVerticalPosition = {\n BOTTOM: \"bottom\",\n CENTER: \"center\",\n INLINE: \"inline\",\n INSIDE: \"inside\",\n OUTSIDE: \"outside\",\n TOP: \"top\",\n} as const;\n\n/**\n * Table overlap behavior types.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_TblOverlap\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"never\"/>\n * <xsd:enumeration value=\"overlap\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const OverlapType = {\n NEVER: \"never\",\n OVERLAP: \"overlap\",\n} as const;\n\nexport interface TableFloatOptions {\n /* CSpell:disable */\n horizontalAnchor?: (typeof TableAnchorType)[keyof typeof TableAnchorType];\n absoluteHorizontalPosition?: number;\n relativeHorizontalPosition?: (typeof RelativeHorizontalPosition)[keyof typeof RelativeHorizontalPosition];\n verticalAnchor?: (typeof TableAnchorType)[keyof typeof TableAnchorType];\n absoluteVerticalPosition?: number;\n relativeVerticalPosition?: (typeof RelativeVerticalPosition)[keyof typeof RelativeVerticalPosition];\n bottomFromText?: number;\n topFromText?: number;\n leftFromText?: number;\n rightFromText?: number;\n overlap?: (typeof OverlapType)[keyof typeof OverlapType];\n /* CSpell:enable */\n}\n","/**\n * Table layout module for WordprocessingML documents.\n *\n * This module provides table layout algorithm settings.\n *\n * @module\n */\n\n/**\n * Table layout algorithm types.\n *\n * Specifies how the table width is calculated.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_TblLayoutType\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"fixed\"/>\n * <xsd:enumeration value=\"autofit\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const TableLayoutType = {\n /** Auto-fit layout - column widths are adjusted based on content */\n AUTOFIT: \"autofit\",\n /** Fixed layout - column widths are fixed as specified */\n FIXED: \"fixed\",\n} as const;\n","/**\n * Table borders module for WordprocessingML documents.\n *\n * This module provides border options for tables.\n *\n * Reference: http://officeopenxml.com/WPtableBorders.php\n *\n * @module\n */\nimport { BorderStyle } from \"@shared/border\";\nimport type { BorderOptions } from \"@shared/border\";\n\n/**\n * Options for configuring table borders.\n *\n * Borders can be applied to the outside edges (top, bottom, left, right)\n * and inside lines (insideHorizontal, insideVertical) of the table.\n */\nexport interface TableBordersOptions {\n top?: BorderOptions;\n bottom?: BorderOptions;\n left?: BorderOptions;\n right?: BorderOptions;\n insideHorizontal?: BorderOptions;\n insideVertical?: BorderOptions;\n}\n\nconst NONE_BORDER: BorderOptions = {\n color: \"auto\",\n size: 0,\n style: BorderStyle.NONE,\n};\n\nexport const TABLE_BORDERS_NONE: TableBordersOptions = {\n bottom: NONE_BORDER,\n insideHorizontal: NONE_BORDER,\n insideVertical: NONE_BORDER,\n left: NONE_BORDER,\n right: NONE_BORDER,\n top: NONE_BORDER,\n};\n","/**\n * Table row height module for WordprocessingML documents.\n *\n * This module provides row height configuration including rules for how height should be applied.\n *\n * Reference: http://officeopenxml.com/WPtableRow.php\n *\n * @module\n */\n\n/**\n * Height rules for table rows.\n *\n * Specifies how the height value should be interpreted.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_HeightRule\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"auto\"/>\n * <xsd:enumeration value=\"exact\"/>\n * <xsd:enumeration value=\"atLeast\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const HeightRule = {\n /** Height is determined based on the content, so value is ignored. */\n AUTO: \"auto\",\n /** At least the value specified */\n ATLEAST: \"atLeast\",\n /** Exactly the value specified */\n EXACT: \"exact\",\n} as const;\n","/**\n * Wrap Tight module for DrawingML text wrapping.\n *\n * This module provides tight text wrapping for floating drawings\n * where text wraps closely around the image shape.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nimport type { Margins } from \"../floating\";\nimport { TextWrappingSide } from \"./text-wrapping\";\nimport type { TextWrapping } from \"./text-wrapping\";\n\n/**\n * Creates a default rectangular wrap polygon matching the image extent.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapPath\">\n * <xsd:sequence>\n * <xsd:element name=\"start\" type=\"a:CT_Point2D\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * <xsd:element name=\"lineTo\" type=\"a:CT_Point2D\" minOccurs=\"2\" maxOccurs=\"unbounded\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"edited\" type=\"xsd:boolean\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n */\nconst createWrapPolygon = (cx: number, cy: number): string =>\n element(\"wp:wrapPolygon\", { edited: \"0\" }, [\n `<wp:start x=\"0\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"0\"/>`,\n ]);\n\n/**\n * Creates tight text wrapping for a floating drawing.\n *\n * WrapTight causes text to wrap closely around the contours\n * of the drawing rather than its rectangular bounding box.\n * A default rectangular wrap polygon matching the image extent is generated.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapTight\">\n * <xsd:sequence>\n * <xsd:element name=\"wrapPolygon\" type=\"CT_WrapPath\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"wrapText\" type=\"ST_WrapText\" use=\"required\"/>\n * <xsd:attribute name=\"distL\" type=\"ST_WrapDistance\"/>\n * <xsd:attribute name=\"distR\" type=\"ST_WrapDistance\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createWrapTight = (\n textWrapping: TextWrapping,\n margins: Margins = {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n extent: { x: number; y: number },\n): string =>\n element(\n \"wp:wrapTight\",\n {\n distL: margins.left,\n distR: margins.right,\n wrapText: textWrapping.side || TextWrappingSide.BOTH_SIDES,\n },\n [createWrapPolygon(extent.x, extent.y)],\n );\n","/**\n * Wrap Through module for DrawingML text wrapping.\n *\n * This module provides \"through\" text wrapping for floating drawings\n * where text wraps through the image contours, filling any concave areas.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nimport type { Margins } from \"../floating\";\nimport { TextWrappingSide } from \"./text-wrapping\";\nimport type { TextWrapping } from \"./text-wrapping\";\n\n/**\n * Creates a default rectangular wrap polygon matching the image extent.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapPath\">\n * <xsd:sequence>\n * <xsd:element name=\"start\" type=\"a:CT_Point2D\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * <xsd:element name=\"lineTo\" type=\"a:CT_Point2D\" minOccurs=\"2\" maxOccurs=\"unbounded\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"edited\" type=\"xsd:boolean\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n */\nconst createWrapPolygon = (cx: number, cy: number): string =>\n element(\"wp:wrapPolygon\", { edited: \"0\" }, [\n `<wp:start x=\"0\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"0\"/>`,\n ]);\n\n/**\n * Creates \"through\" text wrapping for a floating drawing.\n *\n * WrapThrough is similar to WrapTight but allows text to wrap through\n * the concave portions of the drawing shape (e.g., the inside of the letter \"O\").\n * A default rectangular wrap polygon matching the image extent is generated.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapThrough\">\n * <xsd:sequence>\n * <xsd:element name=\"wrapPolygon\" type=\"CT_WrapPath\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"wrapText\" type=\"ST_WrapText\" use=\"required\"/>\n * <xsd:attribute name=\"distL\" type=\"ST_WrapDistance\"/>\n * <xsd:attribute name=\"distR\" type=\"ST_WrapDistance\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createWrapThrough = (\n textWrapping: TextWrapping,\n margins: Margins = {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n extent: { x: number; y: number },\n): string =>\n element(\n \"wp:wrapThrough\",\n {\n distL: margins.left,\n distR: margins.right,\n wrapText: textWrapping.side || TextWrappingSide.BOTH_SIDES,\n },\n [createWrapPolygon(extent.x, extent.y)],\n );\n","/**\n * Horizontal position module for floating drawings in WordprocessingML documents.\n *\n * This module provides horizontal positioning for floating drawing objects,\n * specifying the horizontal placement relative to a base element.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-position.php\n *\n * @module\n */\nimport { convertToEmu } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\nimport { HorizontalPositionAlign, HorizontalPositionRelativeFrom } from \"./floating-position\";\nimport type { HorizontalPositionOptions } from \"./floating-position\";\n\n/**\n * Creates a horizontal position element for floating drawings.\n *\n * The positionH element specifies the horizontal positioning of a floating\n * object relative to a base element (page, margin, column, etc.).\n *\n * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionH-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PosH\">\n * <xsd:choice>\n * <xsd:element name=\"align\" type=\"ST_AlignH\"/>\n * <xsd:element name=\"posOffset\" type=\"ST_PositionOffset\"/>\n * </xsd:choice>\n * <xsd:attribute name=\"relativeFrom\" type=\"ST_RelFromH\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @param options - Horizontal position configuration\n * @returns The positionH XML string\n *\n * @example\n * ```typescript\n * // Align to the left of the page\n * createHorizontalPosition({\n * relative: HorizontalPositionRelativeFrom.PAGE,\n * align: HorizontalPositionAlign.LEFT,\n * });\n *\n * // Offset from the margin\n * createHorizontalPosition({\n * relative: HorizontalPositionRelativeFrom.MARGIN,\n * offset: 914400, // 1 inch in EMUs\n * });\n * ```\n */\nexport const createHorizontalPosition = ({\n relative,\n align,\n offset,\n}: HorizontalPositionOptions): string => {\n const child = align\n ? `<wp:align>${align}</wp:align>`\n : offset !== undefined\n ? `<wp:posOffset>${convertToEmu(offset)}</wp:posOffset>`\n : `<wp:align>${HorizontalPositionAlign.LEFT}</wp:align>`;\n\n return element(\n \"wp:positionH\",\n {\n relativeFrom: relative ?? HorizontalPositionRelativeFrom.PAGE,\n },\n [child],\n );\n};\n","/**\n * Vertical position module for floating drawings in WordprocessingML documents.\n *\n * This module provides vertical positioning for floating drawing objects,\n * specifying the vertical placement relative to a base element.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-position.php\n *\n * @module\n */\nimport { convertToEmu } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\nimport { VerticalPositionAlign, VerticalPositionRelativeFrom } from \"./floating-position\";\nimport type { VerticalPositionOptions } from \"./floating-position\";\n\n/**\n * Creates a vertical position element for floating drawings.\n *\n * The positionV element specifies the vertical positioning of a floating\n * object relative to a base element (page, margin, paragraph, line, etc.).\n *\n * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionV-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PosV\">\n * <xsd:choice>\n * <xsd:element name=\"align\" type=\"ST_AlignV\"/>\n * <xsd:element name=\"posOffset\" type=\"ST_PositionOffset\"/>\n * </xsd:choice>\n * <xsd:attribute name=\"relativeFrom\" type=\"ST_RelFromV\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @param options - Vertical position configuration\n * @returns The positionV XML string\n *\n * @example\n * ```typescript\n * // Align to the top of the page\n * createVerticalPosition({\n * relative: VerticalPositionRelativeFrom.PAGE,\n * align: VerticalPositionAlign.TOP,\n * });\n *\n * // Offset from the paragraph\n * createVerticalPosition({\n * relative: VerticalPositionRelativeFrom.PARAGRAPH,\n * offset: 457200, // 0.5 inch in EMUs\n * });\n * ```\n */\nexport const createVerticalPosition = ({\n relative,\n align,\n offset,\n}: VerticalPositionOptions): string => {\n const child = align\n ? `<wp:align>${align}</wp:align>`\n : offset !== undefined\n ? `<wp:posOffset>${convertToEmu(offset)}</wp:posOffset>`\n : `<wp:align>${VerticalPositionAlign.TOP}</wp:align>`;\n\n return element(\n \"wp:positionV\",\n {\n relativeFrom: relative ?? VerticalPositionRelativeFrom.PAGE,\n },\n [child],\n );\n};\n","import { decimalNumber } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\n/**\n * Specifies the type of the current document grid, which defines the grid behavior.\n *\n * The grid can define a grid which snaps all East Asian characters to grid positions, but leaves Latin text with its default spacing; a grid which adds the specified character pitch to all characters on each row; or a grid which affects only the line pitch for the current section.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_DocGrid_topic_ID0ELYP2.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_DocGrid\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"default\"/>\n * <xsd:enumeration value=\"lines\"/>\n * <xsd:enumeration value=\"linesAndChars\"/>\n * <xsd:enumeration value=\"snapToChars\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const DocumentGridType = {\n /**\n * Specifies that no document grid shall be applied to the contents of the current section in the document.\n */\n DEFAULT: \"default\",\n /**\n * Specifies that the parent section shall have additional line pitch added to each line within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain the specified number of lines per page.\n */\n LINES: \"lines\",\n /**\n * Specifies that the parent section shall have both the additional line pitch and character pitch added to each line and character within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain a specific number of lines per page and characters per line.\n *\n * When this value is set, the input specified via the user interface may be allowed in exact number of line/character pitch units. */\n LINES_AND_CHARS: \"linesAndChars\",\n /**\n * Specifies that the parent section shall have both the additional line pitch and character pitch added to each line and character within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain a specific number of lines per page and characters per line.\n *\n * When this value is set, the input specified via the user interface may be restricted to the number of lines per page and characters per line, with the consumer or producer translating this information based on the current font data to get the resulting line and character pitch values\n */\n SNAP_TO_CHARS: \"snapToChars\",\n} as const;\n\nexport interface DocGridProperties {\n /**\n * Specifies the type of the current document grid, which defines the grid behavior.\n *\n * The grid can define a grid which snaps all East Asian characters to grid positions, but leaves Latin text with its default spacing; a grid which adds the specified character pitch to each character on each row; or a grid which affects only the line pitch for the current section.\n */\n type?: (typeof DocumentGridType)[keyof typeof DocumentGridType];\n /**\n * Specifies the number of lines to be allowed on the document grid for the current page assuming all lines have equal line pitch applied to them. This line pitch shall not be added to any line which appears within a table cell unless the <adjustLineHeightInTable> element (§2.15.3.1) is present in the document's compatibility settings.\n *\n * This attribute is specified in twentieths of a point, and defines the pitch for each line of text on this page such that the desired number of single spaced lines of text fits on the current page.\n *\n * ```xml\n * <w:docGrid w:linePitch=\"684\" …/>\n * ```\n *\n * The `linePitch` attribute specifies that 34.2 points is to the amount of pitch allowed for each line on this page in order to maintain the specific document grid. ]\n *\n * Individual paragraphs can override the line pitch information specified for the document grid by either:\n *\n * Specifying an exact line spacing value using the `lineRule` attribute of value exact on the <spacing> element (§2.3.1.33).\n *\n * Specifying that the paragraph text shall not snap to the document grid via the <snapToGrid> element (§2.3.1.32).\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n linePitch: number;\n /**\n * Specifies the number of characters to be allowed on the document grid for each line in this section.\n *\n * This attribute's value shall be specified by multiplying the difference between the desired character pitch and the character pitch for that character in the font size of the Normal font by 4096.\n *\n * This value shall then be used to add the character pitch for the specified point size to each character in the section [: This results in text in the Normal style having a specific number of characters per line. ]\n *\n * ```xml\n * <w:docGrid w:charSize=\"40960\" …/>\n * ```\n * The `charSpace` attribute specifies a value of 40960, which means that the delta between the character pitch of each character in the grid and the Normal font is 10 points, resulting in a character pitch of 11+10 = 21 points for all characters in this section. ]\n *\n * Individual runs of text can override the line pitch information specified for the document grid by specifying that the run text shall not snap to the document grid via the <snapToGrid> element (§2.3.2.32).\n *\n * The possible values for this attribute are defined by the `ST_DecimalNumber` simple type (§2.18.16).\n */\n charSpace?: number;\n}\n\n/**\n * This element specifies the settings for the document grid, which enables precise layout of full-width East Asian language characters within a document by specifying the desired number of characters per line and lines per page for all East Asian text content in this section.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_docGrid_topic_ID0EHU5S.html\n *\n * ```xml\n * <xsd:complexType name=\"CT_DocGrid\">\n * <xsd:attribute name=\"type\" type=\"ST_DocGrid\"/>\n * <xsd:attribute name=\"linePitch\" type=\"ST_DecimalNumber\"/>\n * <xsd:attribute name=\"charSpace\" type=\"ST_DecimalNumber\"/>\n * </xsd:complexType>\n * ```\n * @returns\n */\nexport const createDocumentGrid = ({ type, linePitch, charSpace }: DocGridProperties): string =>\n element(\"w:docGrid\", {\n \"w:charSpace\": charSpace ? decimalNumber(charSpace) : undefined,\n \"w:linePitch\": decimalNumber(linePitch),\n \"w:type\": type,\n });\n","/**\n * Page borders module for WordprocessingML section properties.\n *\n * Defines borders around pages in a document section.\n *\n * Reference: http://officeopenxml.com/WPsectionBorders.php\n *\n * @module\n */\nimport type { BorderOptions } from \"@shared/border\";\n\n/**\n * Specifies which pages display the page border.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderDisplay\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"allPages\"/>\n * <xsd:enumeration value=\"firstPage\"/>\n * <xsd:enumeration value=\"notFirstPage\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderDisplay = {\n /** Display border on all pages */\n ALL_PAGES: \"allPages\",\n /** Display border only on first page */\n FIRST_PAGE: \"firstPage\",\n /** Display border on all pages except first page */\n NOT_FIRST_PAGE: \"notFirstPage\",\n} as const;\n\n/**\n * Specifies whether page border is positioned relative to page edge or text.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderOffset\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"page\"/>\n * <xsd:enumeration value=\"text\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderOffsetFrom = {\n /** Position border relative to page edge */\n PAGE: \"page\",\n /** Position border relative to text (default) */\n TEXT: \"text\",\n} as const;\n\n/**\n * Specifies z-order of page border relative to intersecting objects.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderZOrder\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"front\"/>\n * <xsd:enumeration value=\"back\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderZOrder = {\n /** Display border behind page contents */\n BACK: \"back\",\n /** Display border in front of page contents (default) */\n FRONT: \"front\",\n} as const;\n\n/**\n * Options for configuring page borders.\n *\n * @property display - Which pages display the border\n * @property offsetFrom - Whether border is positioned relative to page or text\n * @property zOrder - Whether border appears in front or behind page contents\n * @property top - Top border styling\n * @property right - Right border styling\n * @property bottom - Bottom border styling\n * @property left - Left border styling\n */\nexport interface PageBordersOptions {\n /** Which pages display the border */\n display?: (typeof PageBorderDisplay)[keyof typeof PageBorderDisplay];\n /** Whether border is positioned relative to page or text (default: text) */\n offsetFrom?: (typeof PageBorderOffsetFrom)[keyof typeof PageBorderOffsetFrom];\n /** Whether border appears in front or behind page contents (default: front) */\n zOrder?: (typeof PageBorderZOrder)[keyof typeof PageBorderZOrder];\n /** Top border styling */\n top?: BorderOptions;\n /** Right border styling */\n right?: BorderOptions;\n /** Bottom border styling */\n bottom?: BorderOptions;\n /** Left border styling */\n left?: BorderOptions;\n}\n","/**\n * Page margin module for WordprocessingML section properties.\n *\n * Defines page margins for document sections.\n *\n * Reference: http://officeopenxml.com/WPsectionPr.php\n *\n * @module\n */\nimport { signedTwipsMeasureValue, twipsMeasureValue } from \"@office-open/core\";\nimport type { PositiveUniversalMeasure, UniversalMeasure } from \"@office-open/core\";\n\n/**\n * Options for configuring page margins.\n *\n * All measurements are in twips (1/20th of a point) or universal measure.\n *\n * @property top - Top margin\n * @property right - Right margin\n * @property bottom - Bottom margin\n * @property left - Left margin\n * @property header - Header margin (distance from top of page to header)\n * @property footer - Footer margin (distance from bottom of page to footer)\n * @property gutter - Gutter margin for binding\n */\nexport interface PageMarginProperties {\n /** Top margin in twips or universal measure */\n top?: number | UniversalMeasure;\n /** Right margin in twips or universal measure */\n right?: number | PositiveUniversalMeasure;\n /** Bottom margin in twips or universal measure */\n bottom?: number | UniversalMeasure;\n /** Left margin in twips or universal measure */\n left?: number | PositiveUniversalMeasure;\n /** Header margin (distance from top of page to header) in twips or universal measure */\n header?: number | PositiveUniversalMeasure;\n /** Footer margin (distance from bottom of page to footer) in twips or universal measure */\n footer?: number | PositiveUniversalMeasure;\n /** Gutter margin for binding in twips or universal measure */\n gutter?: number | PositiveUniversalMeasure;\n}\n\n/**\n * Creates page margins (pgMar) for a document section.\n *\n * This element specifies the page margins for all pages in a section,\n * including top, bottom, left, right, header, footer, and gutter margins.\n *\n * Reference: http://officeopenxml.com/WPsectionPr.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PageMar\">\n * <xsd:attribute name=\"top\" type=\"ST_SignedTwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"right\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"bottom\" type=\"ST_SignedTwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"left\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"header\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"footer\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"gutter\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Create page margins with 1 inch margins (1440 twips = 1 inch)\n * createPageMargin(1440, 1440, 1440, 1440, 720, 720, 0);\n * ```\n */\nexport const createPageMargin = (\n top: number | UniversalMeasure,\n right: number | PositiveUniversalMeasure,\n bottom: number | UniversalMeasure,\n left: number | PositiveUniversalMeasure,\n header: number | PositiveUniversalMeasure,\n footer: number | PositiveUniversalMeasure,\n gutter: number | PositiveUniversalMeasure,\n): string =>\n `<w:pgMar w:bottom=\"${signedTwipsMeasureValue(bottom)}\" w:footer=\"${twipsMeasureValue(footer)}\" w:gutter=\"${twipsMeasureValue(gutter)}\" w:header=\"${twipsMeasureValue(header)}\" w:left=\"${twipsMeasureValue(left)}\" w:right=\"${twipsMeasureValue(right)}\" w:top=\"${signedTwipsMeasureValue(top)}\"/>`;\n","import { decimalNumber, twipsMeasureValue } from \"@office-open/core\";\nimport type { PositiveUniversalMeasure } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\n/**\n * This simple type specifies when the line numbering in the parent section shall be reset to its restart value. The line numbering increments for each line (even if the line number itself is not displayed) until it reaches the restart point specified by this element.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_LineNumberRestart_topic_ID0EUS42.html\n *\n * ## XSD Schema\n *\n * ```xml\n * <xsd:simpleType name=\"ST_LineNumberRestart\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"newPage\"/>\n * <xsd:enumeration value=\"newSection\"/>\n * <xsd:enumeration value=\"continuous\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const LineNumberRestartFormat = {\n /**\n * ## Restart Line Numbering on Each Page\n *\n * Specifies that line numbering for the parent section shall restart to the starting value whenever a new page is displayed.\n */\n NEW_PAGE: \"newPage\",\n /**\n * ## Restart Line Numbering for Each Section\n *\n * Specifies that line numbering for the parent section shall restart to the starting value whenever the parent begins.\n */\n NEW_SECTION: \"newSection\",\n /**\n * ## Continue Line Numbering From Previous Section\n *\n * Specifies that line numbering for the parent section shall continue from the line numbering from the end of the previous section, if any.\n */\n CONTINUOUS: \"continuous\",\n} as const;\n\nexport interface LineNumberProperties {\n /**\n * Specifies the line number increments to be displayed in the current document.\n *\n * Although each line has an associated line number, only lines which are an even multiple of this value shall be displayed.\n *\n * ### Example\n *\n * ```xml\n * <w:lnNumType … w:countBy=\"5\"/>\n * ```\n *\n * This setting ensures that only lines whose number is a multiple of (e.g. 5, 10, and 15) will have a line number displayed. ]\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n countBy?: number;\n /**\n * ## Line Numbering Starting Value\n *\n * Specifies the starting value used for the first line whenever the line numbering is restarted by use of the `restart` attribute.\n *\n * ### Example\n *\n * ```xml\n * <w:lnNumType w:start=\"3\" w:countBy=\"5\"/>\n * ```\n *\n * The `start` attribute specifies that line numbers shall be counted starting from the number 3.\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n start?: number;\n /**\n * ## Line Numbering Restart Setting\n *\n * Specifies when the line numbering in this section shall be reset to the line number specified by the `start` attribute's value.\n *\n * The line numbering increments for each line (even if it is not displayed) until it reaches the restart point specified by this element.\n *\n * ### Example\n *\n * ```xml\n * <w:sectPr>\n * ...\n * <w:lnNumType w:restart=\"newPage\" ... />\n * </w:sectPr>\n * ```\n *\n * The value of `newPage` specifies that the line numbers shall restart at the top of each page to the value specified by the `start` attribute. In this case, `newPage` is the default, so this value could have been omitted entirely.\n *\n * The possible values for this attribute are defined by the ST_LineNumberRestart simple type (§2.18.54).\n */\n restart?: (typeof LineNumberRestartFormat)[keyof typeof LineNumberRestartFormat];\n /**\n * Specifies the distance between the text margin and the edge of any line numbers appearing in that section.\n *\n * ```xml\n * <w:lnNumType ... w:distance=\"720\"/>\n * ```\n *\n * The possible values for this attribute are defined by the ST_TwipsMeasure simple type (§2.18.105).\n */\n distance?: number | PositiveUniversalMeasure;\n}\n\n/**\n * This element specifies the settings for line numbering to be displayed before each column of text in this section in the document.\n *\n * References:\n * - https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_lnNumType_topic_ID0EVRAT.html\n * - http://officeopenxml.com/WPsectionLineNumbering.php\n *\n * ## XSD Schema\n *\n * ```xml\n * <xsd:complexType name=\"CT_LineNumber\">\n * <xsd:attribute name=\"countBy\" type=\"ST_DecimalNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"start\" type=\"ST_DecimalNumber\" use=\"optional\" default=\"1\"/>\n * <xsd:attribute name=\"distance\" type=\"s:ST_TwipsMeasure\" use=\"optional\"/>\n * <xsd:attribute name=\"restart\" type=\"ST_LineNumberRestart\" use=\"optional\" default=\"newPage\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createLineNumberType = ({\n countBy,\n start,\n restart,\n distance,\n}: LineNumberProperties): string =>\n element(\"w:lnNumType\", {\n \"w:countBy\": countBy === undefined ? undefined : decimalNumber(countBy),\n \"w:distance\": distance === undefined ? undefined : twipsMeasureValue(distance),\n \"w:restart\": restart,\n \"w:start\": start === undefined ? undefined : decimalNumber(start),\n });\n","/**\n * Section type module for WordprocessingML section properties.\n *\n * Defines how a section begins relative to the previous section.\n *\n * Reference: http://officeopenxml.com/WPsection.php\n *\n * @module\n */\n/**\n * Specifies the type of section break.\n *\n * This determines where the section begins relative to the previous section.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_SectionMark\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"nextPage\"/>\n * <xsd:enumeration value=\"nextColumn\"/>\n * <xsd:enumeration value=\"continuous\"/>\n * <xsd:enumeration value=\"evenPage\"/>\n * <xsd:enumeration value=\"oddPage\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const SectionType = {\n /** Section begins on the next page */\n NEXT_PAGE: \"nextPage\",\n /** Section begins on the next column */\n NEXT_COLUMN: \"nextColumn\",\n /** Section begins immediately following the previous section */\n CONTINUOUS: \"continuous\",\n /** Section begins on the next even-numbered page */\n EVEN_PAGE: \"evenPage\",\n /** Section begins on the next odd-numbered page */\n ODD_PAGE: \"oddPage\",\n} as const;\n\n/**\n * Creates section type (type) for a document section.\n *\n * This element specifies the type of section break, which determines\n * where the new section begins relative to the previous section.\n *\n * Reference: http://officeopenxml.com/WPsection.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_SectType\">\n * <xsd:attribute name=\"val\" type=\"ST_SectionMark\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Create a continuous section (no page break)\n * createSectionType(SectionType.CONTINUOUS);\n *\n * // Create a section that starts on next odd page\n * createSectionType(SectionType.ODD_PAGE);\n * ```\n */\nexport const createSectionType = (value: (typeof SectionType)[keyof typeof SectionType]): string =>\n `<w:type w:val=\"${value}\"/>`;\n","/**\n * This simple type specifies the possible types of headers and footers which may be specified for a given header or footer reference in a document. This value determines the page(s) on which the current header or footer shall be displayed.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_HdrFtr_topic_ID0E2UW2.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_HdrFtr\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"even\"/>\n * <xsd:enumeration value=\"default\"/>\n * <xsd:enumeration value=\"first\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const HeaderFooterReferenceType = {\n /** Specifies that this header or footer shall appear on every page in this section which is not overridden with a specific `even` or `first` page header/footer. In a section with all three types specified, this type shall be used on all odd numbered pages (counting from the `first` page in the section, not the section numbering). */\n DEFAULT: \"default\",\n /** Specifies that this header or footer shall appear on the first page in this section. The appearance of this header or footer is contingent on the setting of the `titlePg` element (§2.10.6). */\n FIRST: \"first\",\n /** Specifies that this header or footer shall appear on all even numbered pages in this section (counting from the first page in the section, not the section numbering). The appearance of this header or footer is contingent on the setting of the `evenAndOddHeaders` element (§2.10.1). */\n EVEN: \"even\",\n} as const;\n\n// <xsd:group name=\"EG_HdrFtrReferences\">\n// <xsd:choice>\n// <xsd:element name=\"headerReference\" type=\"CT_HdrFtrRef\" minOccurs=\"0\"/>\n// <xsd:element name=\"footerReference\" type=\"CT_HdrFtrRef\" minOccurs=\"0\"/>\n// </xsd:choice>\n// </xsd:group>\n\n// <xsd:complexType name=\"CT_HdrFtrRef\">\n// <xsd:complexContent>\n// <xsd:extension base=\"CT_Rel\">\n// <xsd:attribute name=\"type\" type=\"ST_HdrFtr\" use=\"required\"/>\n// </xsd:extension>\n// </xsd:complexContent>\n\n// <xsd:complexType name=\"CT_Rel\">\n// <xsd:attribute ref=\"r:id\" use=\"required\"/>\n// </xsd:complexType>\n\nexport interface HeaderFooterReferenceOptions {\n type?: (typeof HeaderFooterReferenceType)[keyof typeof HeaderFooterReferenceType];\n id?: number;\n}\n\nexport const HeaderFooterType = {\n FOOTER: \"w:footerReference\",\n HEADER: \"w:headerReference\",\n} as const;\n\nexport const createHeaderFooterReference = (\n type: (typeof HeaderFooterType)[keyof typeof HeaderFooterType],\n options: HeaderFooterReferenceOptions,\n): string =>\n `<${type} r:id=\"rId${options.id}\" w:type=\"${options.type || HeaderFooterReferenceType.DEFAULT}\"/>`;\n","/**\n * Table of Contents Properties module.\n *\n * This module defines configuration options for table of contents generation,\n * including field switches and style mappings.\n *\n * Reference: http://officeopenxml.com/WPtableOfContents.php\n *\n * @module\n */\n\nimport type { SectionChild } from \"@shared/section\";\n\n/**\n * Represents a style-to-level mapping for table of contents entries.\n *\n * StyleLevel associates a paragraph style name with a TOC level, allowing\n * custom styles to be included in the table of contents at specific levels.\n *\n * @publicApi\n */\nexport class StyleLevel {\n /** The name of the paragraph style. */\n public styleName: string;\n /** The TOC level (1-9) to assign to this style. */\n public level: number;\n\n public constructor(styleName: string, level: number) {\n this.styleName = styleName;\n this.level = level;\n }\n}\n\n/**\n * Options for configuring a Table of Contents.\n *\n * These options control which content is included in the TOC and how it is formatted.\n * Options correspond to field switches in the TOC field code.\n *\n * Reference:\n * - https://www.ecma-international.org/publications/standards/Ecma-376.htm (Part 1, Page 1251)\n * - http://officeopenxml.com/WPtableOfContents.php\n */\nexport interface TableOfContentsOptions {\n /**\n * \\a option - Includes captioned items, but omits caption labels and numbers.\n * The identifier designated by text in this switch's field-argument corresponds to the caption label.\n * Use captionLabelIncludingNumbers (\\c) to build a table of captions with labels and numbers.\n */\n captionLabel?: string;\n\n /**\n * \\b option - Includes entries only from the portion of the document marked by\n * the bookmark named by text in this switch's field-argument.\n */\n entriesFromBookmark?: string;\n\n /**\n * \\c option - Includes figures, tables, charts, and other items that are numbered\n * by a SEQ field (§17.16.5.56). The sequence identifier designated by text in this switch's\n * field-argument, which corresponds to the caption label, shall match the identifier in the\n * corresponding SEQ field.\n */\n captionLabelIncludingNumbers?: string;\n\n /**\n * \\d option - When used with \\s, the text in this switch's field-argument defines\n * the separator between sequence and page numbers. The default separator is a hyphen (-).\n */\n sequenceAndPageNumbersSeparator?: string;\n\n /**\n * \\f option - Includes only those TC fields whose identifier exactly matches the\n * text in this switch's field-argument (which is typically a letter).\n */\n tcFieldIdentifier?: string;\n\n /**\n * \\h option - Makes the table of contents entries hyperlinks.\n */\n hyperlink?: boolean;\n\n /**\n * \\l option - Includes TC fields that assign entries to one of the levels specified\n * by text in this switch's field-argument as a range having the form startLevel-endLevel,\n * where startLevel and endLevel are integers, and startLevel has a value equal-to or less-than endLevel.\n * TC fields that assign entries to lower levels are skipped.\n */\n tcFieldLevelRange?: string;\n\n /**\n * \\n option - Without field-argument, omits page numbers from the table of contents.\n * Page numbers are omitted from all levels unless a range of entry levels is specified by\n * text in this switch's field-argument. A range is specified as for \\l.\n */\n pageNumbersEntryLevelsRange?: string;\n\n /**\n * \\o option - Uses paragraphs formatted with all or the specified range of builtin\n * heading styles. Headings in a style range are specified by text in this switch's\n * field-argument using the notation specified as for \\l, where each integer corresponds\n * to the style with a style ID of HeadingX (e.g. 1 corresponds to Heading1).\n * If no heading range is specified, all heading levels used in the document are listed.\n */\n headingStyleRange?: string;\n\n /**\n * \\p option - Text in this switch's field-argument specifies a sequence of characters\n * that separate an entry and its page number. The default is a tab with leader dots.\n */\n entryAndPageNumberSeparator?: string;\n\n /**\n * \\s option - For entries numbered with a SEQ field (§17.16.5.56), adds a prefix to the page number.\n * The prefix depends on the type of entry. text in this switch's field-argument shall match the\n * identifier in the SEQ field.\n */\n seqFieldIdentifierForPrefix?: string;\n\n /**\n * \\t field-argument Uses paragraphs formatted with styles other than the built-in heading styles.\n * Text in this switch's field-argument specifies those styles as a set of comma-separated doublets,\n * with each doublet being a comma-separated set of style name and table of content level.\n * \\t can be combined with \\o.\n */\n stylesWithLevels?: StyleLevel[];\n\n /**\n * \\u Uses the applied paragraph outline level.\n */\n useAppliedParagraphOutlineLevel?: boolean;\n\n /**\n * \\w Preserves tab entries within table entries.\n */\n preserveTabInEntries?: boolean;\n\n /**\n * \\x Preserves newline characters within table entries.\n */\n preserveNewLineInEntries?: boolean;\n\n /**\n * \\z Hides tab leader and page numbers in web page view (§17.18.102).\n */\n hideTabAndPageNumbersInWebView?: boolean;\n\n /**\n * Rendered TOC entries — the paragraph content between the field's `separate`\n * and `end` markers. Round-tripped structurally (each entry is a TOC-style\n * paragraph carrying a HYPERLINK field, tab leader, and PAGEREF page number)\n * so both MS Office and WPS display the existing TOC without regenerating.\n *\n * Omit on fresh generation — the field is then emitted `dirty` so the\n * consuming application builds the entries from headings on open.\n */\n entries?: SectionChild[];\n}\n","/**\n * Structured Document Tag Properties module.\n *\n * Represents CT_SdtPr — the properties of a structured document tag (content control).\n * Supports all SDT types defined in the OOXML specification: comboBox, dropDownList,\n * date, text, equation,richText, picture, citation, group, bibliography, docPartObj,\n * docPartList.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_SdtPr\n *\n * @module\n */\n\n// ─── Lock ───────────────────────────────────────────────────────────────────\n\n/**\n * SDT lock type (ST_Lock).\n */\nexport const SdtLock = {\n /** Lock the SDT itself (cannot delete the control) */\n SDT_LOCKED: \"sdtLocked\",\n /** Lock the content (cannot edit content within the control) */\n CONTENT_LOCKED: \"contentLocked\",\n /** No locking */\n UNLOCKED: \"unlocked\",\n /** Lock both SDT and content */\n SDT_CONTENT_LOCKED: \"sdtContentLocked\",\n} as const;\n\n// ─── Supporting Types ───────────────────────────────────────────────────────\n\n/**\n * A list item for comboBox or dropDownList SDTs (CT_SdtListItem).\n */\nexport interface SdtListItem {\n /** Display text shown in the UI */\n displayText?: string;\n /** Underlying value */\n value?: string;\n}\n\n/**\n * Options for comboBox SDT type (CT_SdtComboBox).\n */\nexport interface SdtComboBoxOptions {\n /** List items */\n items?: SdtListItem[];\n /** Last selected value */\n lastValue?: string;\n}\n\n/**\n * Options for dropDownList SDT type (CT_SdtDropDownList).\n */\nexport interface SdtDropDownListOptions {\n /** List items */\n items?: SdtListItem[];\n /** Last selected value */\n lastValue?: string;\n}\n\n/**\n * Date mapping type (ST_SdtDateMappingType).\n */\nexport const SdtDateMappingType = {\n TEXT: \"text\",\n DATE: \"date\",\n DATE_TIME: \"dateTime\",\n} as const;\n\n/**\n * Options for date SDT type (CT_SdtDate).\n */\nexport interface SdtDateOptions {\n /** Date format string (e.g., \"yyyy-MM-dd\") */\n dateFormat?: string;\n /** Language ID (e.g., \"en-US\") */\n languageId?: string;\n /** How the date value is stored */\n storeMappedDataAs?: (typeof SdtDateMappingType)[keyof typeof SdtDateMappingType];\n /** Calendar type */\n calendar?: string;\n /** Full date value (ISO 8601) */\n fullDate?: string;\n}\n\n/**\n * Options for plain text SDT type (CT_SdtText).\n */\nexport interface SdtTextOptions {\n /** Whether the text control supports multiple lines */\n multiLine?: boolean;\n}\n\n/**\n * Symbol for a checkbox content control state (CT_SdtCheckboxSymbol).\n *\n * `val` is a hex Unicode code point (e.g., \"2612\" for ☒); `font` defaults to\n * \"MS Gothic\" per the OOXML specification.\n */\nexport interface SdtCheckboxSymbol {\n /** Hex Unicode code point of the symbol (e.g., \"2612\") */\n val: string;\n /** Font face; defaults to \"MS Gothic\" */\n font?: string;\n}\n\n/**\n * Options for a checkbox content control (CT_SdtCheckbox, w14:checkbox).\n *\n * Word 2010+ content control checkbox. When present, the SDT renders the\n * current state symbol instead of its declared children.\n */\nexport interface SdtCheckboxOptions {\n /** Whether the checkbox is checked (default: false) */\n checked?: boolean;\n /** Symbol for the checked state (default: ☒ 0x2612, MS Gothic) */\n checkedState?: SdtCheckboxSymbol;\n /** Symbol for the unchecked state (default: ☐ 0x2610, MS Gothic) */\n uncheckedState?: SdtCheckboxSymbol;\n}\n\n/**\n * Data binding options (CT_DataBinding).\n */\nexport interface SdtDataBindingOptions {\n /** XML namespace prefix mappings */\n prefixMappings?: string;\n /** XPath expression (required) */\n xpath: string;\n /** Custom XML store item ID (required) */\n storeItemID: string;\n}\n\n/**\n * Options for CT_SdtPr — structured document tag properties.\n */\nexport interface SdtPropertiesOptions {\n /** Display name */\n alias?: string;\n /** Application-specific tag */\n tag?: string;\n /** Unique ID */\n id?: number;\n /** Lock behavior */\n lock?: (typeof SdtLock)[keyof typeof SdtLock];\n /** Whether the control is temporary */\n temporary?: boolean;\n /** Whether the placeholder text is currently shown */\n showingPlaceholder?: boolean;\n /** Data binding to custom XML */\n dataBinding?: SdtDataBindingOptions;\n /** Numeric label */\n label?: number;\n /** Tab order index */\n tabIndex?: number;\n\n // ─── Type discriminators (xsd:choice, at most one) ───\n\n /** Equation SDT */\n equation?: boolean;\n /** ComboBox SDT (allows free-text entry) */\n comboBox?: SdtComboBoxOptions;\n /** Date SDT */\n date?: SdtDateOptions;\n /** Document part object SDT */\n docPartObj?: {\n gallery?: string;\n category?: string;\n unique?: boolean;\n };\n /** Document part list SDT */\n docPartList?: {\n gallery?: string;\n category?: string;\n unique?: boolean;\n };\n /** DropDownList SDT (selection only) */\n dropDownList?: SdtDropDownListOptions;\n /** Picture SDT */\n picture?: boolean;\n /** Rich text SDT */\n richText?: boolean;\n /** Plain text SDT */\n text?: SdtTextOptions;\n /** Citation SDT */\n citation?: boolean;\n /** Group SDT */\n group?: boolean;\n /** Bibliography SDT */\n bibliography?: boolean;\n /** Checkbox content control SDT (Word 2010+, w14:checkbox) */\n checkbox?: SdtCheckboxOptions;\n}\n","/**\n * Footnote module for WordprocessingML documents.\n *\n * This module provides support for footnotes that appear at the bottom\n * of the page referenced from the main document text.\n *\n * Reference: http://officeopenxml.com/WPfootnotes.php\n *\n * @module\n */\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\n\n/**\n * Enumeration of footnote types.\n *\n * Reference: http://officeopenxml.com/WPfootnotes.php\n *\n * @publicApi\n */\nexport const FootnoteType = {\n /** Separator line between body text and footnotes */\n SEPERATOR: \"separator\",\n /** Continuation separator for footnotes spanning pages */\n CONTINUATION_SEPERATOR: \"continuationSeparator\",\n} as const;\n\n/**\n * Options for creating a Footnote.\n *\n * @property id - Unique numeric identifier for this footnote\n * @property type - Type of footnote (separator, continuationSeparator, or normal)\n * @property children - Array of paragraphs that make up the footnote content\n *\n * @see {@link Footnote}\n */\nexport interface FootnoteOptions {\n /** Unique numeric identifier for this footnote */\n id: number;\n /** Type of footnote (separator or continuation separator) */\n type?: (typeof FootnoteType)[keyof typeof FootnoteType];\n /** Content of the footnote (paragraphs, tables, etc.) */\n children: (ParagraphOptions | string)[];\n}\n","/**\n * Endnote module for WordprocessingML documents.\n *\n * @module\n */\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\n\nexport const EndnoteType = {\n CONTINUATION_SEPARATOR: \"continuationSeparator\",\n\n SEPARATOR: \"separator\",\n} as const;\n\nexport interface EndnoteOptions {\n id: number;\n type?: (typeof EndnoteType)[keyof typeof EndnoteType];\n children: (ParagraphOptions | string)[];\n}\n","/**\n * Permission range markers for WordprocessingML document protection.\n *\n * These elements mark editable ranges within a protected document.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_PermStart, CT_PermEnd\n *\n * @module\n */\n\n/**\n * Editing group values for permission ranges.\n *\n * Defines who can edit within a permission range.\n *\n * Reference: ISO/IEC 29500-4, ST_EdGrp\n */\nexport const EditGroupType = {\n NONE: \"none\",\n EVERYONE: \"everyone\",\n ADMINISTRATORS: \"administrators\",\n CONTRIBUTORS: \"contributors\",\n EDITORS: \"editors\",\n OWNERS: \"owners\",\n CURRENT: \"current\",\n} as const;\n\nexport type EditGroup = (typeof EditGroupType)[keyof typeof EditGroupType];\n\n/**\n * Options for creating a permission start marker.\n */\nexport interface PermStartOptions {\n /** Unique identifier for this permission range (typically a number) */\n id: string | number;\n /** Editing group that can edit this range */\n edGroup?: EditGroup;\n /** Individual user who can edit this range */\n ed?: string;\n /** First column this range covers (for table cells) */\n colFirst?: number;\n /** Last column this range covers (for table cells) */\n colLast?: number;\n}\n","/**\n * Font module for WordprocessingML documents.\n *\n * Provides support for font definitions and embedded fonts.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nconst createStringElement = (name: string, value: string): string =>\n element(name, { \"w:val\": value });\n\n/**\n * Options for a font relationship (embedded font).\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html\n *\n * @property id - Relationship to Part\n * @property fontKey - Embedded Font Obfuscation Key (GUID)\n * @property subsetted - Whether the embedded font is subsetted\n */\nexport interface FontRelationshipOptions {\n /** Relationship to Part */\n id: string;\n /** Embedded Font Obfuscation Key (GUID) */\n fontKey?: string;\n /** Whether the embedded font is subsetted */\n subsetted?: boolean;\n}\n\n/**\n * Character set constants for font definitions.\n * Maps character set names to their hexadecimal identifiers.\n *\n * @publicApi\n */\nexport const CharacterSet = {\n ANSI: \"00\",\n ARABIC: \"B2\",\n BALTIC: \"BA\",\n CHINESEBIG5: \"88\",\n DEFAULT: \"01\",\n EASTEUROPE: \"EE\",\n GB_2312: \"86\",\n GREEK: \"A1\",\n HANGUL: \"81\",\n HEBREW: \"B1\",\n JIS: \"80\",\n JOHAB: \"82\",\n MAC: \"4D\",\n OEM: \"FF\",\n RUSSIAN: \"CC\",\n SYMBOL: \"02\",\n THAI: \"DE\",\n TURKISH: \"A2\",\n VIETNAMESE: \"A3\",\n} as const;\n\n/**\n * Options for defining a font in the document.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * @property name - Font name (required)\n * @property altName - Alternative font name\n * @property panose1 - PANOSE-1 classification\n * @property charset - Character set identifier\n * @property family - Font family\n * @property notTrueType - Whether this is not a TrueType font\n * @property pitch - Font pitch\n * @property sig - Font signature (Unicode and code page ranges)\n * @property embedRegular - Embedded regular font relationship\n * @property embedBold - Embedded bold font relationship\n * @property embedItalic - Embedded italic font relationship\n * @property embedBoldItalic - Embedded bold-italic font relationship\n */\nexport interface FontEntry {\n /** Font name (required) */\n name: string;\n /** Alternative font name */\n altName?: string;\n /** PANOSE-1 classification */\n panose1?: string;\n /** Character set identifier */\n charset?: (typeof CharacterSet)[keyof typeof CharacterSet];\n /** Font family */\n family?: string;\n /** Whether this is not a TrueType font */\n notTrueType?: boolean;\n /** Font pitch */\n pitch?: string;\n /** Font signature (Unicode and code page ranges) */\n sig?: {\n /** Unicode Subset Bitfield 0 */\n usb0: string;\n /** Unicode Subset Bitfield 1 */\n usb1: string;\n /** Unicode Subset Bitfield 2 */\n usb2: string;\n /** Unicode Subset Bitfield 3 */\n usb3: string;\n /** Code Page Bitfield 0 */\n csb0: string;\n /** Code Page Bitfield 1 */\n csb1: string;\n };\n /** Embedded regular font relationship */\n embedRegular?: FontRelationshipOptions;\n /** Embedded bold font relationship */\n embedBold?: FontRelationshipOptions;\n /** Embedded italic font relationship */\n embedItalic?: FontRelationshipOptions;\n /** Embedded bold-italic font relationship */\n embedBoldItalic?: FontRelationshipOptions;\n}\n\n/**\n * Creates a font relationship element for embedding fonts.\n */\nconst createFontRelationship = (\n { id, fontKey, subsetted }: FontRelationshipOptions,\n name: string,\n): string => {\n const attrs: Record<string, string | undefined> = { \"r:id\": id };\n if (fontKey) {\n attrs[\"w:fontKey\"] = `{${fontKey}}`;\n }\n const children = subsetted ? [`<w:subsetted/>`] : undefined;\n return element(name, attrs, children);\n};\n\n/**\n * Creates a font element with the specified options.\n *\n * This function builds a complete font definition including optional embedded font files,\n * font signature, character set, and other font properties.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Font\">\n * <xsd:sequence>\n * <xsd:element name=\"altName\" type=\"CT_String\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"panose1\" type=\"CT_Panose\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"charset\" type=\"CT_Charset\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"family\" type=\"CT_FontFamily\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"notTrueType\" type=\"CT_OnOff\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"pitch\" type=\"CT_Pitch\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"sig\" type=\"CT_FontSig\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedRegular\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedBold\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedItalic\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedBoldItalic\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"name\" type=\"s:ST_String\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * const font = createFont({\n * name: \"Arial\",\n * family: \"swiss\",\n * pitch: \"variable\",\n * charset: CharacterSet.ANSI\n * });\n * ```\n */\nexport const createFont = ({\n name,\n altName,\n panose1,\n charset,\n family,\n notTrueType,\n pitch,\n sig,\n embedRegular,\n embedBold,\n embedItalic,\n embedBoldItalic,\n}: FontEntry): string => {\n const children: string[] = [];\n\n // http://www.datypic.com/sc/ooxml/e-w_altName-1.html\n if (altName) children.push(createStringElement(\"w:altName\", altName));\n // http://www.datypic.com/sc/ooxml/e-w_panose1-1.html\n if (panose1) children.push(createStringElement(\"w:panose1\", panose1));\n // http://www.datypic.com/sc/ooxml/e-w_charset-1.html\n if (charset) children.push(createStringElement(\"w:charset\", charset));\n // http://www.datypic.com/sc/ooxml/e-w_family-1.html\n if (family) children.push(createStringElement(\"w:family\", family));\n // http://www.datypic.com/sc/ooxml/e-w_notTrueType-1.html\n if (notTrueType) children.push(`<w:notTrueType/>`);\n if (pitch) children.push(createStringElement(\"w:pitch\", pitch));\n // http://www.datypic.com/sc/ooxml/e-w_sig-1.html\n if (sig) {\n children.push(\n `<w:sig w:csb0=\"${sig.csb0}\" w:csb1=\"${sig.csb1}\" w:usb0=\"${sig.usb0}\" w:usb1=\"${sig.usb1}\" w:usb2=\"${sig.usb2}\" w:usb3=\"${sig.usb3}\"/>`,\n );\n }\n // http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html\n if (embedRegular) children.push(createFontRelationship(embedRegular, \"w:embedRegular\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedBold-1.html\n if (embedBold) children.push(createFontRelationship(embedBold, \"w:embedBold\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedItalic-1.html\n if (embedItalic) children.push(createFontRelationship(embedItalic, \"w:embedItalic\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedBoldItalic-1.html\n if (embedBoldItalic) children.push(createFontRelationship(embedBoldItalic, \"w:embedBoldItalic\"));\n\n return element(\"w:font\", { \"w:name\": name }, children);\n};\n","/**\n * Relationships descriptor — produces .rels XML files.\n *\n * Reference: OPC, Relationships.xsd\n *\n * @module\n */\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { escapeXml } from \"@office-open/xml\";\n\nexport interface RelationshipEntry {\n id: number | string;\n type: string;\n target: string;\n targetMode?: string;\n}\n\nexport interface RelationshipsInput {\n relationships: RelationshipEntry[];\n}\n\nexport const relationshipsDesc: CustomDescriptor<RelationshipsInput> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n const p: string[] = [\n '<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">',\n ];\n for (const rel of opts.relationships) {\n const targetModeAttr = rel.targetMode ? ` TargetMode=\"${escapeXml(rel.targetMode)}\"` : \"\";\n p.push(\n `<Relationship Id=\"rId${rel.id}\" Type=\"${escapeXml(rel.type)}\" Target=\"${escapeXml(rel.target)}\"${targetModeAttr}/>`,\n );\n }\n p.push(\"</Relationships>\");\n return p.join(\"\");\n },\n\n parse(el, _ctx) {\n const relationships: RelationshipEntry[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const id = child.attributes?.[\"Id\"];\n const type = child.attributes?.[\"Type\"];\n const target = child.attributes?.[\"Target\"];\n const targetMode = child.attributes?.[\"TargetMode\"];\n if (id && type && target) {\n const numId = String(id).replace(\"rId\", \"\");\n relationships.push({\n id: Number(numId) || id,\n type: String(type),\n target: String(target),\n targetMode: targetMode ? String(targetMode) : undefined,\n });\n }\n }\n return { relationships };\n },\n};\n","/**\n * Cell merge track revision component.\n *\n * @module\n */\n\nimport type { ChangedProperties } from \"../track-revision\";\n\n/**\n * Vertical merge revision types.\n */\nexport const VerticalMergeRevisionType = {\n /**\n * Cell that is merged with upper one.\n */\n CONTINUE: \"continue\",\n /**\n * Cell that is starting the vertical merge.\n */\n RESTART: \"restart\",\n} as const;\n\nexport type CellMergeAttributes = ChangedProperties & {\n verticalMerge?: (typeof VerticalMergeRevisionType)[keyof typeof VerticalMergeRevisionType];\n verticalMergeOriginal?: (typeof VerticalMergeRevisionType)[keyof typeof VerticalMergeRevisionType];\n};\n","/**\n * Vertical alignment module for WordprocessingML documents.\n *\n * This module provides vertical alignment options for table cells and sections.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_VerticalJc\">\n * <xsd:attribute name=\"val\" type=\"ST_VerticalJc\" use=\"required\"/>\n * </xsd:complexType>\n *\n * <xsd:simpleType name=\"ST_VerticalJc\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"both\"/>\n * <xsd:enumeration value=\"top\"/>\n * <xsd:enumeration value=\"center\"/>\n * <xsd:enumeration value=\"bottom\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @module\n */\n/**\n * Enumeration for table-cell vertical alignment. Only `top`, `center`, `bottom`\n * are valid according to ECMA-376 (§17.18.87 ST_VerticalJc within `<w:tcPr>`).\n *\n * @publicApi\n */\nexport const VerticalAlignTable = {\n BOTTOM: \"bottom\",\n CENTER: \"center\",\n TOP: \"top\",\n} as const;\n\n/**\n * Enumeration for section (<w:sectPr>) vertical alignment. Adds `both` on top of\n * the table-cell set (§17.18.87 ST_VerticalJc within <w:sectPr>).\n *\n * @publicApi\n */\nexport const VerticalAlignSection = {\n ...VerticalAlignTable,\n BOTH: \"both\",\n} as const;\n\nexport type TableVerticalAlign = (typeof VerticalAlignTable)[keyof typeof VerticalAlignTable];\n\nexport type SectionVerticalAlign = (typeof VerticalAlignSection)[keyof typeof VerticalAlignSection];\n\n/**\n * Creates a vertical alignment element in a WordprocessingML document.\n *\n * Used in table cells and sections to control vertical text positioning.\n *\n * @example\n * ```typescript\n * createVerticalAlign(VerticalAlignTable.CENTER);\n * ```\n */\nexport const createVerticalAlign = (value: TableVerticalAlign | SectionVerticalAlign): string =>\n `<w:vAlign w:val=\"${value}\"/>`;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUA,MAAa,YAAY;;CAEvB,QAAQ;;CAER,MAAM;AACR;;;;;;;;;;ACgBA,MAAa,cAAc;;CAEzB,MAAM;;CAEN,OAAO;;CAEP,QAAQ;;CAER,KAAK;;CAEL,OAAO;;CAEP,SAAS;;CAET,KAAK;;CAEL,KAAK;;CAEL,OAAO;AACT;;;;;;;;AASA,MAAa,aAAa;;CAExB,KAAK;;CAEL,OAAO;;CAEP,QAAQ;;CAER,YAAY;;CAEZ,MAAM;;CAEN,YAAY;AACd;;;;;;AAOA,MAAa,kBAAkB;;AAE7B,KAAK,KACP;;;;;;;;;;ACvDA,MAAa,oBAAoB;;CAE/B,KAAK;;CAEL,QAAQ;;CAER,UAAU;;CAEV,QAAQ;;CAER,MAAM;AACR;;;;;;;;AASA,MAAa,uBAAuB;;CAElC,MAAM;;CAEN,WAAW;;CAEX,qBAAqB;;CAErB,iBAAiB;;CAEjB,gBAAgB;AAClB;;;;;;;;;;ACvBA,MAAa,aAAa;;CAExB,kBAAkB;;CAElB,QAAQ;;CAER,YAAY;;CA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qBAAqB;CAChC,QAAQ;CACR,QAAQ;CACR,KAAK;AACP;;;;;;;AAQA,MAAa,uBAAuB;CAClC,GAAG;CACH,MAAM;AACR;;;;;;;;;;;AAgBA,MAAa,uBAAuB,UAClC,oBAAoB,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["coreCreateBodyProperties","xmlChildren","THEME_COLORS","onOff","cnfStyleStr","onOff","xmlChildren","parseBodyChildren","createWrapPolygon","readOnOff","readNum","BORDER_STYLES","THEME_COLORS","parseCnfStyle","md","onOff","NS","NS","encoder"],"sources":["../src/parts/paragraph/formatting/alignment.ts","../src/parts/paragraph/formatting/break.ts","../src/parts/paragraph/formatting/spacing.ts","../src/parts/paragraph/formatting/style.ts","../src/parts/paragraph/formatting/tab-stop.ts","../src/parts/paragraph/properties.ts","../src/parts/paragraph/run/run.ts","../src/parts/paragraph/run/properties.ts","../src/shared/media/media.ts","../src/parts/paragraph/run/picture-run.ts","../src/parts/drawing/inline/graphic/graphic-data/wps/body-properties.ts","../src/parts/paragraph/run/underline.ts","../src/parts/paragraph/run/emphasis-mark.ts","../src/parts/paragraph/run/positional-tab.ts","../src/parts/paragraph/run/ruby.ts","../src/parts/paragraph/run/form-field.ts","../src/parts/paragraph/run/proof-error.ts","../src/parts/paragraph/links/hyperlink.ts","../src/parts/paragraph/frame/frame-properties.ts","../src/parts/table/table-cell/table-cell-components.ts","../src/parts/table/table-properties/table-float-properties.ts","../src/parts/table/table-properties/table-layout.ts","../src/shared/border.ts","../src/parts/table/table-properties/table-borders.ts","../src/parts/table/table-row/table-row-height.ts","../src/parts/table/table-width.ts","../src/parts/object/object-element.ts","../src/shared/shading.ts","../src/parts/paragraph/run/run-parse.ts","../src/parts/paragraph/stringify.ts","../src/parts/bodychildren.ts","../src/parts/drawing/text-wrap/text-wrapping.ts","../src/parts/drawing/text-wrap/wrap-tight.ts","../src/parts/drawing/text-wrap/wrap-through.ts","../src/shared/constants.ts","../src/parts/drawing/floating/floating-position.ts","../src/parts/drawing/floating/horizontal-position.ts","../src/parts/drawing/floating/vertical-position.ts","../src/parts/document/body/section-properties/properties/page-number.ts","../src/parts/document/body/section-properties/properties/page-size.ts","../src/parts/document/body/section-properties/properties/page-text-direction.ts","../src/parts/document/body/section-properties/section-properties.ts","../src/parts/document/body/section-properties/descriptor.ts","../src/parts/document/document-attributes.ts","../src/parts/fonts/font-wrapper.ts","../src/parts/sdt/sdt-parse.ts","../src/parts/table-of-contents/descriptor.ts","../src/parts/paragraph/math/stringify.ts","../src/util/replace-media-placeholders.ts","../src/body.ts","../src/parts/drawing/drawing-parse.ts","../src/parts/drawing/descriptor.ts","../src/parts/paragraph/run/field.ts","../src/parts/inline.ts","../src/parts/table/stringify.ts","../src/parts/table/descriptor.ts","../src/parts/numbering/level.ts","../src/parts/numbering/numbering.ts","../src/parts/document/body/section-properties/properties/doc-grid.ts","../src/parts/document/body/section-properties/properties/page-borders.ts","../src/parts/document/body/section-properties/properties/page-margin.ts","../src/parts/document/body/section-properties/properties/line-number.ts","../src/parts/document/body/section-properties/properties/section-type.ts","../src/parts/styles/factory.ts","../src/parts/styles/styles.ts","../src/parts/settings/descriptor.ts","../src/parts/table-of-contents/table-of-contents-properties.ts","../src/parts/table-of-contents/sdt-properties.ts","../src/parts/table-of-contents/toc-parse.ts","../src/parts/footnotes/descriptor.ts","../src/parts/endnotes/descriptor.ts","../src/parts/perm-start.ts","../src/parts/alt-chunk/alt-chunk-collection.ts","../src/parts/sub-doc/sub-doc-collection.ts","../src/parts/fonts/font.ts","../src/parts/fonts/descriptor.ts","../src/parts/bibliography.ts","../src/parts/glossary-document.ts","../src/parts/comments.ts","../src/parts/core-properties.ts","../src/parts/web-settings.ts","../src/shared/track-revision/track-revision-components/cell-merge.ts","../src/shared/vertical-align.ts","../src/patch/from-docx.ts","../src/patch/patch-detector.ts","../src/parts/styles/external-styles-factory.ts","../src/context.ts","../src/parts/alt-chunk/alt-chunk-parse.ts","../src/parts/custom-xml/custom-xml-parse.ts","../src/parts/sub-doc/sub-doc-parse.ts","../src/parts/textbox/textbox-parse.ts","../src/parse/body.ts","../src/parse.ts","../src/parts/fonts/obfuscate-ttf-to-odttf.ts","../src/parts/header-footer.ts","../src/compiler.ts","../src/generate.ts"],"sourcesContent":["/**\n * Paragraph and table alignment module for WordprocessingML documents.\n *\n * This module provides justification (alignment) options for paragraphs and tables.\n *\n * Reference: http://officeopenxml.com/WPalignment.php\n *\n * @see http://officeopenxml.com/WPtableAlignment.php\n * @see http://www.datypic.com/sc/ooxml/t-w_ST_Jc.html\n *\n * @module\n */\n/**\n * Paragraph justification (alignment) types.\n *\n * Specifies the horizontal alignment of text within a paragraph.\n *\n * Reference: http://officeopenxml.com/WPalignment.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Jc\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"start\"/>\n * <xsd:enumeration value=\"center\"/>\n * <xsd:enumeration value=\"end\"/>\n * <xsd:enumeration value=\"both\"/>\n * <xsd:enumeration value=\"mediumKashida\"/>\n * <xsd:enumeration value=\"distribute\"/>\n * <xsd:enumeration value=\"numTab\"/>\n * <xsd:enumeration value=\"highKashida\"/>\n * <xsd:enumeration value=\"lowKashida\"/>\n * <xsd:enumeration value=\"thaiDistribute\"/>\n * <xsd:enumeration value=\"left\"/>\n * <xsd:enumeration value=\"right\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const AlignmentType = {\n /** Align Start */\n START: \"start\",\n /** Align Center */\n CENTER: \"center\",\n /** End */\n END: \"end\",\n /** Justified */\n BOTH: \"both\",\n /** Medium Kashida Length */\n MEDIUM_KASHIDA: \"mediumKashida\",\n /** Distribute All Characters Equally */\n DISTRIBUTE: \"distribute\",\n /** Align to List Tab */\n NUM_TAB: \"numTab\",\n /** Widest Kashida Length */\n HIGH_KASHIDA: \"highKashida\",\n /** Low Kashida Length */\n LOW_KASHIDA: \"lowKashida\",\n /** Thai Language Justification */\n THAI_DISTRIBUTE: \"thaiDistribute\",\n /** Align Left */\n LEFT: \"left\",\n /** Align Right */\n RIGHT: \"right\",\n /** Justified */\n JUSTIFIED: \"both\",\n} as const;\n","/**\n * Break type values for WordprocessingML documents.\n *\n * @module\n */\n\n/**\n * Break type constants.\n * @internal\n */\nexport const BreakType = {\n /** Column break */\n COLUMN: \"column\",\n /** Page break */\n PAGE: \"page\",\n} as const;\n\nexport type BreakTypeValue = (typeof BreakType)[keyof typeof BreakType];\n","/**\n * Paragraph spacing module for WordprocessingML documents.\n *\n * This module provides spacing options for paragraphs including space before,\n * space after, and line spacing.\n *\n * Reference: http://officeopenxml.com/WPspacing.php\n *\n * @module\n */\nimport type { PositiveUniversalMeasure } from \"@office-open/core\";\n\n/**\n * Line spacing rule types.\n *\n * Specifies how the line height is calculated.\n *\n * @publicApi\n */\nexport const LineRuleType = {\n /** Line spacing is at least the specified value */\n AT_LEAST: \"atLeast\",\n /** Line spacing is exactly the specified value */\n EXACTLY: \"exactly\",\n /** Line spacing is exactly the specified value (alias for EXACTLY) */\n EXACT: \"exact\",\n /** Line spacing is automatically determined based on content */\n AUTO: \"auto\",\n} as const;\n\n/**\n * Properties for configuring paragraph spacing.\n *\n * All values are in twips (twentieths of a point) unless otherwise specified.\n */\nexport interface SpacingProperties {\n /** Spacing after the paragraph in twips or as a PositiveUniversalMeasure */\n after?: number | PositiveUniversalMeasure;\n /** Spacing before the paragraph in twips or as a PositiveUniversalMeasure */\n before?: number | PositiveUniversalMeasure;\n /** Line spacing value in twips or as a PositiveUniversalMeasure (depends on lineRule) */\n line?: number | PositiveUniversalMeasure;\n /** How to interpret the line spacing value */\n lineRule?: (typeof LineRuleType)[keyof typeof LineRuleType];\n /** Use automatic spacing before the paragraph */\n beforeAutoSpacing?: boolean;\n /** Use automatic spacing after the paragraph */\n afterAutoSpacing?: boolean;\n /** Spacing before the paragraph in line units */\n beforeLines?: number;\n /** Spacing after the paragraph in line units */\n afterLines?: number;\n}\n","/**\n * Paragraph style module for WordprocessingML documents.\n *\n * This module provides paragraph style references including heading levels.\n *\n * @module\n */\n/**\n * Built-in heading level styles.\n *\n * These are the standard heading styles available in Word documents.\n *\n * @publicApi\n */\nexport const HeadingLevel = {\n /** Heading 1 style */\n HEADING_1: \"Heading1\",\n /** Heading 2 style */\n HEADING_2: \"Heading2\",\n /** Heading 3 style */\n HEADING_3: \"Heading3\",\n /** Heading 4 style */\n HEADING_4: \"Heading4\",\n /** Heading 5 style */\n HEADING_5: \"Heading5\",\n /** Heading 6 style */\n HEADING_6: \"Heading6\",\n /** Title style */\n TITLE: \"Title\",\n} as const;\n","/**\n * Tab stop module for WordprocessingML documents.\n *\n * This module provides tab stop definitions for paragraphs.\n *\n * Reference: http://officeopenxml.com/WPtab.php\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\n\n/**\n * Definition for a single tab stop.\n *\n * @see {@link TabStop}\n */\nexport interface TabStopDefinition {\n /** The type of tab stop alignment */\n type: (typeof TabStopType)[keyof typeof TabStopType];\n /** The position of the tab stop in twips (number) or UniversalMeasure (mm/cm/in/pt/pc/pi). */\n position: number | UniversalMeasure;\n /** Optional leader character to fill space before the tab */\n leader?: (typeof LeaderType)[keyof typeof LeaderType];\n}\n\n/**\n * Tab stop alignment types.\n *\n * Specifies the type of tab stop and how text aligns to it.\n *\n * @publicApi\n */\nexport const TabStopType = {\n /** Left-aligned tab stop */\n LEFT: \"left\",\n /** Right-aligned tab stop */\n RIGHT: \"right\",\n /** Center-aligned tab stop */\n CENTER: \"center\",\n /** Bar tab stop - inserts a vertical bar at the position */\n BAR: \"bar\",\n /** Clears a tab stop at the specified position */\n CLEAR: \"clear\",\n /** Decimal-aligned tab stop - aligns on decimal point */\n DECIMAL: \"decimal\",\n /** End-aligned tab stop (right-to-left equivalent) */\n END: \"end\",\n /** List tab stop for numbered lists */\n NUM: \"num\",\n /** Start-aligned tab stop (left-to-right equivalent) */\n START: \"start\",\n} as const;\n\n/**\n * Tab stop leader character types.\n *\n * Specifies the character used to fill the space before the tab stop.\n *\n * @publicApi\n */\nexport const LeaderType = {\n /** Dot leader (....) */\n DOT: \"dot\",\n /** Heavy leader */\n HEAVY: \"heavy\",\n /** Hyphen leader (----) */\n HYPHEN: \"hyphen\",\n /** Middle dot leader (····) */\n MIDDLE_DOT: \"middleDot\",\n /** No leader */\n NONE: \"none\",\n /** Underscore leader (____) */\n UNDERSCORE: \"underscore\",\n} as const;\n\n/**\n * Predefined tab stop positions.\n *\n * @publicApi\n */\nexport const TabStopPosition = {\n /** Maximum tab stop position (right margin) */\n MAX: 9026,\n} as const;\n","import type { ShadingProperties } from \"@shared/shading\";\n/**\n * Paragraph properties types for WordprocessingML documents.\n *\n * Reference: http://officeopenxml.com/WPparagraphProperties.php\n *\n * @module\n */\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport type { AlignmentType } from \"./formatting/alignment\";\nimport type { BordersOptions } from \"./formatting/border\";\nimport type { CnfConditionalOptions } from \"./formatting/cnf-style\";\nimport type { IndentProperties } from \"./formatting/indent\";\nimport type { SpacingProperties } from \"./formatting/spacing\";\nimport type { HeadingLevel } from \"./formatting/style\";\nimport type { TabStopDefinition } from \"./formatting/tab-stop\";\nimport type { FrameOptions } from \"./frame/frame-properties\";\nimport type { ParagraphRunOptions } from \"./run/run\";\n\n/**\n * Vertical text alignment types for paragraphs.\n *\n * Specifies the vertical alignment of text within the paragraph.\n *\n * @publicApi\n */\nexport const TextAlignmentType = {\n /** Align text to the top */\n TOP: \"top\",\n /** Align text to the center */\n CENTER: \"center\",\n /** Align text to the baseline */\n BASELINE: \"baseline\",\n /** Align text to the bottom */\n BOTTOM: \"bottom\",\n /** Automatically determine vertical alignment */\n AUTO: \"auto\",\n} as const;\n\n/**\n * Textbox tight wrap types for paragraphs.\n *\n * Specifies how tightly text wraps around a textbox.\n *\n * @publicApi\n */\nexport const TextboxTightWrapType = {\n /** No tight wrapping */\n NONE: \"none\",\n /** Tight wrap on all lines */\n ALL_LINES: \"allLines\",\n /** Tight wrap on first and last lines */\n FIRST_AND_LAST_LINE: \"firstAndLastLine\",\n /** Tight wrap on first line only */\n FIRST_LINE_ONLY: \"firstLineOnly\",\n /** Tight wrap on last line only */\n LAST_LINE_ONLY: \"lastLineOnly\",\n} as const;\n\n/**\n * Paragraph style properties for numbering levels.\n *\n * These properties are used when defining paragraph styles within numbering level definitions.\n */\nexport interface LevelParagraphStylePropertiesOptions {\n /** Paragraph text alignment (left, right, center, justified, etc.) */\n alignment?: (typeof AlignmentType)[keyof typeof AlignmentType];\n /** Whether to render text right-to-left for bidirectional languages */\n bidirectional?: boolean;\n /** Whether to insert a page break before this paragraph */\n pageBreakBefore?: boolean;\n /** Custom tab stop positions and alignments */\n tabStops?: TabStopDefinition[];\n /** Whether to display a horizontal line (thematic break) below the paragraph */\n thematicBreak?: boolean;\n /** Whether to prevent single lines at top/bottom of page (widow/orphan control), defaults to true */\n widowControl?: boolean;\n /** Whether to ignore spacing before/after when adjacent paragraphs have the same style */\n contextualSpacing?: boolean;\n /** Position in twips for a right-aligned tab stop */\n rightTabStop?: number;\n /** Position in twips for a left-aligned tab stop */\n leftTabStop?: number;\n /** Indentation settings for the paragraph */\n indent?: IndentProperties;\n /** Spacing before/after paragraph and between lines */\n spacing?: SpacingProperties;\n /**\n * Specifies that the paragraph (or at least part of it) should be rendered on the same page as the next paragraph when possible. If multiple paragraphs are to be kept together but they exceed a page, then the set of paragraphs begin on a new page and page breaks are used thereafter as needed.\n */\n keepNext?: boolean;\n /**\n * Specifies that all lines of the paragraph are to be kept on a single page when possible.\n */\n keepLines?: boolean;\n /** Frame properties for positioning the paragraph */\n frame?: FrameOptions;\n /** Whether to suppress line numbers for this paragraph */\n suppressLineNumbers?: boolean;\n /** Whether to allow word wrapping */\n wordWrap?: boolean;\n /** Whether to allow punctuation to extend beyond text margins */\n overflowPunctuation?: boolean;\n /**\n * This element specifies whether inter-character spacing shall automatically be adjusted between regions of numbers and regions of East Asian text in the current paragraph. These regions shall be determined by the Unicode character values of the text content within the paragraph.\n * This only works in Microsoft Word. It is not part of the ECMA-376 OOXML standard.\n */\n autoSpaceEastAsianText?: boolean;\n /** Whether to prevent text frames from overlapping */\n suppressOverlap?: boolean;\n /** Whether to disable automatic hyphenation for this paragraph */\n suppressAutoHyphens?: boolean;\n /** Whether to automatically adjust right indent for document grid */\n adjustRightInd?: boolean;\n /** Whether to snap the current paragraph to the document grid */\n snapToGrid?: boolean;\n /** Whether to swap left and right indent positions on odd pages for mirrored layouts */\n mirrorIndents?: boolean;\n /** Whether to use Kinsoku forbidden character overflow rules */\n kinsoku?: boolean;\n /** Whether to compress punctuation at the start of a line */\n topLinePunct?: boolean;\n /** Whether to automatically add space between East Asian and Latin text */\n autoSpaceDE?: boolean;\n /** Vertical text alignment within the paragraph */\n textAlignment?: (typeof TextAlignmentType)[keyof typeof TextAlignmentType];\n /** Textbox tight wrap setting */\n textboxTightWrap?: (typeof TextboxTightWrapType)[keyof typeof TextboxTightWrapType];\n /** Text direction for the paragraph (lr, rl, tb, tbV, rlV, lrV) */\n textDirection?: \"lr\" | \"rl\" | \"tb\" | \"tbV\" | \"rlV\" | \"lrV\";\n /** Outline level for table of contents and document outline (0-9) */\n outlineLevel?: number;\n /** HTML div ID reference */\n divId?: number;\n /** Conditional formatting style for table rows/cells */\n cnfStyle?: CnfConditionalOptions;\n}\n\n/**\n * Paragraph style properties options.\n *\n * These properties are used when defining paragraph styles and include\n * border, shading, and numbering options in addition to level properties.\n */\nexport type ParagraphStylePropertiesOptions = {\n /** Referenced style inside the style's own pPr (w:pStyle). */\n style?: string;\n /** Heading shorthand for the referenced style (w:pStyle val=\"HeadingN\"). */\n heading?: (typeof HeadingLevel)[keyof typeof HeadingLevel];\n /** Border settings for the paragraph */\n border?: BordersOptions;\n /** Background shading/fill color for the paragraph */\n shading?: ShadingProperties;\n /** Numbering configuration for lists, or false to remove numbering */\n numbering?:\n | {\n /** Reference ID of the numbering definition to use */\n reference: string;\n /** Level in the numbering hierarchy (0-8) */\n level: number;\n /** Instance number for multiple lists with same reference */\n instance?: number;\n /** Whether this is a custom numbering definition */\n custom?: boolean;\n /** Numbering change tracking (CT_TrackChangeNumbering) */\n numberingChange?: {\n /** Original numbering value */\n original: string;\n /** Revision ID */\n id: string;\n /** Author of the change */\n author: string;\n /** Date of the change */\n date?: string;\n };\n }\n | false;\n} & LevelParagraphStylePropertiesOptions;\n\nexport type ParagraphPropertiesOptionsBase = {\n /** Heading level (Heading1, Heading2, etc.) - applies predefined heading style */\n heading?: (typeof HeadingLevel)[keyof typeof HeadingLevel];\n /** Style ID to apply to this paragraph */\n style?: string;\n /** Bullet list configuration */\n bullet?: {\n /** Indentation level for the bullet (0-8) */\n level: number;\n };\n /**\n * Run properties to apply to all runs in the paragraph.\n * Reference: ECMA-376, 3rd Edition (June, 2011), Fundamentals and Markup Language Reference § 17.3.1.29.\n */\n run?: ParagraphRunOptions;\n} & ParagraphStylePropertiesOptions;\n\nexport type ParagraphPropertiesChangeOptions = ChangedProperties & ParagraphPropertiesOptionsBase;\n\n/**\n * Options for configuring paragraph properties.\n *\n * These options control all aspects of paragraph formatting including\n * alignment, spacing, indentation, borders, numbering, and more.\n *\n * Reference: http://officeopenxml.com/WPparagraphProperties.php\n */\nexport type ParagraphPropertiesOptions = {\n revision?: ParagraphPropertiesChangeOptions;\n includeIfEmpty?: boolean;\n} & ParagraphPropertiesOptionsBase;\n","import type { ObjectElementOptions } from \"@parts/object\";\n\n/**\n * Run module for WordprocessingML documents.\n *\n * A run is a region of text with a common set of properties. It is the primary\n * unit of inline content in a paragraph.\n *\n * Reference: http://officeopenxml.com/WPtext.php\n *\n * @module\n */\nimport type { ParagraphRunPropertiesOptions, RunPropertiesOptions } from \"./properties\";\n\n/** w:br/@w:clear values (ST_BrClear) — clears floating content on the given side(s). */\nexport type BreakClear = \"none\" | \"left\" | \"right\" | \"all\";\n\n/** Options for a line break with optional float-clearing (CT_Br). */\nexport interface BreakOptions {\n /** Number of `<w:br/>` elements (defaults to 1). */\n count?: number;\n /** Clear floating content (w:br/@w:clear). */\n clear?: BreakClear;\n}\n\n/**\n * Serialize a break option (count shorthand or structured with clear) to one or\n * more `<w:br/>` tags.\n */\nexport function breakXml(breakOpt: number | BreakOptions | undefined): string {\n if (!breakOpt) return \"\";\n const count = typeof breakOpt === \"number\" ? breakOpt : (breakOpt.count ?? 1);\n if (count <= 0) return \"\";\n const clear = typeof breakOpt === \"object\" ? breakOpt.clear : undefined;\n const one = clear ? `<w:br w:clear=\"${clear}\"/>` : \"<w:br/>\";\n return count === 1 ? one : one.repeat(count);\n}\n\n/**\n * Empty EG_RunInnerContent elements — self-closing XML with no attributes.\n * Shared by the body run stringifier and the inline (footnote/endnote) run\n * stringifier so both emit them identically. Keyed by the RunOptions child\n * property name (e.g. `{ separator: true }` → `separator`).\n *\n * XSD reference: EG_RunInnerContent group in wml.xsd.\n */\nexport const EMPTY_RUN_ELEMENTS: Record<string, string> = {\n noBreakHyphen: \"<w:noBreakHyphen/>\",\n softHyphen: \"<w:softHyphen/>\",\n dayShort: \"<w:dayShort/>\",\n monthShort: \"<w:monthShort/>\",\n yearShort: \"<w:yearShort/>\",\n dayLong: \"<w:dayLong/>\",\n monthLong: \"<w:monthLong/>\",\n yearLong: \"<w:yearLong/>\",\n annotationRef: \"<w:annotationRef/>\",\n footnoteRef: \"<w:footnoteRef/>\",\n endnoteRef: \"<w:endnoteRef/>\",\n separator: \"<w:separator/>\",\n continuationSeparator: \"<w:continuationSeparator/>\",\n pgNum: \"<w:pgNum/>\",\n carriageReturn: \"<w:cr/>\",\n lastRenderedPageBreak: \"<w:lastRenderedPageBreak/>\",\n};\n\ninterface RunOptionsBase {\n /**\n * Inline content children (EG_RunInnerContent plus the JSON-dispatch drawing\n * and content children). The empty run elements are single-key markers\n * (`{ tab: true }`, `{ noBreakHyphen: true }`, …) emitted via\n * {@link EMPTY_RUN_ELEMENTS}.\n */\n children?: (\n | (typeof PageNumber)[keyof typeof PageNumber]\n | string\n | { tab: true }\n | { noBreakHyphen: true }\n | { softHyphen: true }\n | { dayShort: true }\n | { monthShort: true }\n | { yearShort: true }\n | { dayLong: true }\n | { monthLong: true }\n | { yearLong: true }\n | { annotationRef: true }\n | { footnoteRef: true }\n | { endnoteRef: true }\n | { separator: true }\n | { continuationSeparator: true }\n | { pgNum: true }\n | { carriageReturn: true }\n | { lastRenderedPageBreak: true }\n | { object: ObjectElementOptions }\n | Record<string, unknown>\n )[];\n break?: number | BreakOptions;\n text?: string;\n}\n\n/**\n * Options for creating a Run element.\n *\n * The run element specifies a region of text with a common set of properties.\n * The children property can contain various inline content elements.\n *\n * @see {@link Run}\n */\nexport type RunOptions = RunOptionsBase &\n RunPropertiesOptions & {\n /** Revision save ID for the run (w:rsidR, hex string e.g. \"00123456\"). */\n rsid?: string;\n /** Revision save ID for run properties (w:rsidRPr, hex string). */\n runPropertiesRsid?: string;\n /** Revision save ID when run was deleted (w:rsidDel, hex string). */\n deletionRsid?: string;\n };\n\nexport type ParagraphRunOptions = RunOptionsBase & ParagraphRunPropertiesOptions;\n\n/**\n * Constants for page number field types.\n *\n * These values are used to insert dynamic page number fields into a document.\n *\n * Reference: http://officeopenxml.com/WPfields.php\n *\n * @publicApi\n */\nexport const PageNumber = {\n /** Inserts the current page number */\n CURRENT: \"CURRENT\",\n /** Inserts the total number of pages in the document */\n TOTAL_PAGES: \"TOTAL_PAGES\",\n /** Inserts the total number of pages in the current section */\n TOTAL_PAGES_IN_SECTION: \"TOTAL_PAGES_IN_SECTION\",\n /** Inserts the current section number */\n CURRENT_SECTION: \"SECTION\",\n} as const;\n","/**\n * Run properties module for WordprocessingML documents.\n *\n * This module provides the run properties (rPr) element which specifies\n * the formatting applied to a run of text.\n *\n * Reference: https://www.ecma-international.org/wp-content/uploads/ECMA-376-1_5th_edition_december_2016.zip\n * Section 17.3.2.21 (page 297)\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { BorderOptions } from \"@shared/border\";\nimport type { ShadingProperties } from \"@shared/shading\";\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport type { EastAsianLayoutOptions } from \"./east-asian-layout\";\nimport type { EmphasisMarkType } from \"./emphasis-mark\";\nimport type { ColorOptions } from \"./formatting\";\nimport type { LanguageOptions } from \"./language\";\nimport type { FontProperties } from \"./run-fonts\";\nimport type { UnderlineType } from \"./underline\";\n\ninterface RunFontReference {\n name: string;\n hint?: string;\n}\n\n/**\n * Text animation effect types.\n *\n * Reference: http://officeopenxml.com/WPtextFormatting.php\n *\n * @publicApi\n */\nexport const TextEffect = {\n /** Blinking background animation */\n BLINK_BACKGROUND: \"blinkBackground\",\n /** Lights animation effect */\n LIGHTS: \"lights\",\n /** Black marching ants animation */\n ANTS_BLACK: \"antsBlack\",\n /** Red marching ants animation */\n ANTS_RED: \"antsRed\",\n /** Shimmer animation effect */\n SHIMMER: \"shimmer\",\n /** Sparkle animation effect */\n SPARKLE: \"sparkle\",\n /** No text effect */\n NONE: \"none\",\n} as const;\n\n/**\n * Highlight color values for text highlighting.\n *\n * Reference: http://officeopenxml.com/WPtextShading.php\n */\nexport const HighlightColor = {\n /** Black highlight */\n BLACK: \"black\",\n /** Blue highlight */\n BLUE: \"blue\",\n /** Cyan highlight */\n CYAN: \"cyan\",\n /** Dark blue highlight */\n DARK_BLUE: \"darkBlue\",\n /** Dark cyan highlight */\n DARK_CYAN: \"darkCyan\",\n /** Dark gray highlight */\n DARK_GRAY: \"darkGray\",\n /** Dark green highlight */\n DARK_GREEN: \"darkGreen\",\n /** Dark magenta highlight */\n DARK_MAGENTA: \"darkMagenta\",\n /** Dark red highlight */\n DARK_RED: \"darkRed\",\n /** Dark yellow highlight */\n DARK_YELLOW: \"darkYellow\",\n /** Green highlight */\n GREEN: \"green\",\n /** Light gray highlight */\n LIGHT_GRAY: \"lightGray\",\n /** Magenta highlight */\n MAGENTA: \"magenta\",\n /** No highlight */\n NONE: \"none\",\n /** Red highlight */\n RED: \"red\",\n /** White highlight */\n WHITE: \"white\",\n /** Yellow highlight */\n YELLOW: \"yellow\",\n} as const;\n\n/**\n * Run style properties options.\n *\n * These properties define the formatting that can be applied to a run of text,\n * including font, size, bold, italic, underline, color, and other character formatting.\n *\n * Reference: http://officeopenxml.com/WPtextFormatting.php\n */\nexport interface RunStylePropertiesOptions {\n noProof?: boolean;\n bold?: boolean;\n boldComplexScript?: boolean;\n italic?: boolean;\n italicComplexScript?: boolean;\n underline?: {\n color?: string;\n type?: (typeof UnderlineType)[keyof typeof UnderlineType];\n };\n effect?: (typeof TextEffect)[keyof typeof TextEffect];\n emphasisMark?: {\n type?: (typeof EmphasisMarkType)[keyof typeof EmphasisMarkType];\n };\n color?: string | ColorOptions;\n /** Kerning threshold in points. */\n kern?: number;\n position?: string;\n /** Font size in points. Internally stored as half-points in XML (×2). */\n size?: number;\n /** Complex-script font size in points (w:szCs). Independent from {@link size}. */\n sizeComplexScript?: number;\n rightToLeft?: boolean;\n smallCaps?: boolean;\n allCaps?: boolean;\n strike?: boolean;\n doubleStrike?: boolean;\n subScript?: boolean;\n superScript?: boolean;\n font?: string | RunFontReference | FontProperties;\n highlight?: (typeof HighlightColor)[keyof typeof HighlightColor];\n /** Complex-script highlight color (w:highlightCs). Independent from {@link highlight}. */\n highlightComplexScript?: string;\n characterSpacing?: number | UniversalMeasure;\n shading?: ShadingProperties;\n emboss?: boolean;\n imprint?: boolean;\n revision?: RunPropertiesChangeOptions;\n language?: LanguageOptions;\n border?: BorderOptions;\n snapToGrid?: boolean;\n vanish?: boolean;\n specVanish?: boolean;\n scale?: number;\n math?: boolean;\n outline?: boolean;\n shadow?: boolean;\n webHidden?: boolean;\n fitText?: number;\n complexScript?: boolean;\n eastAsianLayout?: EastAsianLayoutOptions;\n /** Relationship ID for a content part (w:contentPart with r:id) */\n contentPartRId?: string;\n /**\n * Raw XML for w14:* text-effect children (glow/shadow/reflection/props3d/...)\n * located in the EG_RPrBase extension slot at the end of rPr. Low-frequency\n * complex subtrees kept verbatim for round-trip fidelity; the rPr backbone\n * stays structured and editable.\n */\n w14RawXml?: string;\n}\n\n/**\n * Options for configuring run properties.\n *\n * Extends RunStylePropertiesOptions with a style reference.\n */\nexport type RunPropertiesOptions = {\n /** Reference to a character style by name */\n style?: string;\n} & RunStylePropertiesOptions;\n\n/**\n * Options for run properties change tracking.\n *\n * Used for revision tracking when run properties have been modified.\n */\nexport type RunPropertiesChangeOptions = {} & RunPropertiesOptions & ChangedProperties;\n\nexport type ParagraphRunPropertiesOptions = {\n insertion?: ChangedProperties;\n deletion?: ChangedProperties;\n} & RunPropertiesOptions;\n","import type { UniversalMeasure } from \"@office-open/core\";\nimport { convertEmuToPixels, convertToEmu } from \"@office-open/core\";\n\n/**\n * Media module for WordprocessingML documents.\n *\n * Provides transformation helpers for embedded media (images). The deduplicated\n * media collection itself ({@link Media}) lives in @office-open/core and is\n * re-exported from this package's index so every format package shares one\n * content-based dedup implementation.\n *\n * @module\n */\nimport type { MediaDataTransformation } from \"./data\";\n\n/**\n * Transformation options for media display.\n *\n * Specifies how an image should be transformed when displayed in the document.\n * Width and height can be specified as numbers (in EMUs) or as universal measures\n * (e.g., \"100mm\", \"2in\").\n */\nexport interface MediaTransformation {\n offset?: {\n top?: number | UniversalMeasure;\n left?: number | UniversalMeasure;\n };\n width: number | UniversalMeasure;\n /** Display height in EMUs or universal measure */\n height: number | UniversalMeasure;\n /** Optional flip transformations */\n flip?: {\n /** Whether to flip the image vertically */\n vertical?: boolean;\n /** Whether to flip the image horizontally */\n horizontal?: boolean;\n };\n /** Optional rotation angle in degrees */\n rotation?: number;\n /** Effect extent (wp:effectExtent) in raw EMUs — passed through verbatim. */\n effectExtent?: { l: number; t: number; r: number; b: number };\n}\n\n/**\n * Converts user-facing transformation options (EMU or universal measure) to internal\n * transformation data (pixels + EMUs).\n *\n * @param options - User-facing transformation in EMU or universal measure\n * @returns Internal transformation data with both pixel and EMU values\n */\nexport const createTransformation = (options: MediaTransformation): MediaDataTransformation => {\n const widthEmu = convertToEmu(options.width);\n const heightEmu = convertToEmu(options.height);\n const offsetLeftEmu = convertToEmu(options.offset?.left ?? 0);\n const offsetTopEmu = convertToEmu(options.offset?.top ?? 0);\n return {\n emus: { x: widthEmu, y: heightEmu },\n flip: options.flip,\n offset: {\n emus: { x: offsetLeftEmu, y: offsetTopEmu },\n pixels: {\n x: Math.round(convertEmuToPixels(offsetLeftEmu)),\n y: Math.round(convertEmuToPixels(offsetTopEmu)),\n },\n },\n pixels: {\n x: Math.round(convertEmuToPixels(widthEmu)),\n y: Math.round(convertEmuToPixels(heightEmu)),\n },\n rotation: options.rotation,\n ...(options.effectExtent ? { effectExtent: options.effectExtent } : {}),\n };\n};\n","import type { DataType } from \"@office-open/core\";\nimport type {\n BlipEffectsOptions,\n EffectListOptions,\n FillOptions,\n OutlineOptions,\n SourceRectangleOptions,\n TileOptions,\n} from \"@office-open/core/drawing\";\n/**\n * Picture (pic:pic) run types for WordprocessingML documents.\n *\n * This module provides support for inserting pictures into documents.\n *\n * Reference: http://officeopenxml.com/drwPicInline.php\n *\n * @module\n */\nimport type { DocPropertiesOptions } from \"@parts/drawing/doc-properties/doc-properties\";\nimport type { RunPropertiesOptions } from \"@parts/paragraph/run/properties\";\nimport type { MediaTransformation } from \"@shared/media\";\nimport { createTransformation } from \"@shared/media\";\nimport type { MediaData, NonVisualPropertiesOptions } from \"@shared/media/data\";\n\nimport type { Floating } from \"../../drawing\";\nimport type { GraphicFrameLocksOptions } from \"../../drawing/descriptor\";\n\n/**\n * Core options for picture configuration.\n */\ninterface CorePictureOptions {\n transformation: MediaTransformation;\n floating?: Floating;\n altText?: DocPropertiesOptions;\n outline?: OutlineOptions;\n fill?: FillOptions;\n effects?: EffectListOptions;\n blipEffects?: BlipEffectsOptions;\n sourceRectangle?: SourceRectangleOptions;\n tile?: TileOptions;\n /** Picture non-visual properties (pic:cNvPr) — populated by parse */\n nonVisualProperties?: NonVisualPropertiesOptions;\n /** Structured run properties of the wrapping w:r (round-trip) — emitted before the drawing. */\n runProperties?: RunPropertiesOptions;\n /** Graphic frame locks (wp:cNvGraphicFramePr) for round-trip. */\n graphicFrameLocks?: GraphicFrameLocksOptions | null;\n /** Blip rendering hint `a14:useLocalDpi` (round-trip). */\n useLocalDpi?: boolean;\n}\n\ninterface RegularPictureOptions {\n type: \"jpg\" | \"png\" | \"gif\" | \"bmp\" | \"tif\" | \"ico\" | \"emf\" | \"wmf\";\n data: DataType;\n}\n\ninterface SvgMediaOptions {\n type: \"svg\";\n data: DataType;\n /**\n * Required in case the Word processor does not support SVG.\n */\n fallback: RegularPictureOptions;\n}\n\n/**\n * Options for an inline/anchored picture (pic:pic).\n */\nexport type PictureOptions = (RegularPictureOptions | SvgMediaOptions) & CorePictureOptions;\n\nexport const createPictureData = (\n data: Uint8Array,\n transformation: MediaTransformation,\n key: string,\n sourceRectangle?: SourceRectangleOptions,\n nonVisualProperties?: NonVisualPropertiesOptions,\n): Pick<\n MediaData,\n \"data\" | \"fileName\" | \"transformation\" | \"sourceRectangle\" | \"nonVisualProperties\"\n> => ({\n data,\n fileName: key,\n sourceRectangle,\n nonVisualProperties,\n transformation: createTransformation(transformation),\n});\n","/**\n * Text body properties — re-exported from core DrawingML.\n *\n * DOCX wraps bodyPr in wps:bodyPr (WordprocessingML drawing namespace); this\n * module re-exports core's CT_TextBodyProperties implementation and fixes the\n * tag at wps:bodyPr for DOCX callers.\n *\n * Reference: ISO/IEC 29500-4, dml-main.xsd, CT_TextBodyProperties\n *\n * @module\n */\n\nexport {\n type TextVertOverflow,\n type TextHorzOverflow,\n type TextVertical,\n type TextBodyWrapping,\n parseBodyProperties,\n bodyPropertiesDesc,\n} from \"@office-open/core/drawing\";\nexport type {\n VerticalAnchor,\n NormalAutofitOptions,\n PresetTextShapeOptions,\n FlatTextOptions,\n BodyPropertiesOptions,\n} from \"@office-open/core/drawing\";\n\nimport type { BodyPropertiesOptions } from \"@office-open/core/drawing\";\nimport { createBodyProperties as coreCreateBodyProperties } from \"@office-open/core/drawing\";\n\n/**\n * Create a wps:bodyPr element. DOCX uses the wps: prefix (WordprocessingML\n * drawing); core's default is a:bodyPr (PPTX/XLSX).\n */\nexport const createBodyProperties = (options: BodyPropertiesOptions = {}): string =>\n coreCreateBodyProperties(options, \"wps:bodyPr\");\n","/**\n * Underline module for WordprocessingML documents.\n *\n * This module provides support for underlining text with various styles and colors.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * @module\n */\n\n/**\n * Underline style types for text.\n *\n * Defines the various underline patterns that can be applied to text runs.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Underline\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"single\"/>\n * <xsd:enumeration value=\"words\"/>\n * <xsd:enumeration value=\"double\"/>\n * <xsd:enumeration value=\"thick\"/>\n * <xsd:enumeration value=\"dotted\"/>\n * <xsd:enumeration value=\"dottedHeavy\"/>\n * <xsd:enumeration value=\"dash\"/>\n * <xsd:enumeration value=\"dashedHeavy\"/>\n * <xsd:enumeration value=\"dashLong\"/>\n * <xsd:enumeration value=\"dashLongHeavy\"/>\n * <xsd:enumeration value=\"dotDash\"/>\n * <xsd:enumeration value=\"dashDotHeavy\"/>\n * <xsd:enumeration value=\"dotDotDash\"/>\n * <xsd:enumeration value=\"dashDotDotHeavy\"/>\n * <xsd:enumeration value=\"wave\"/>\n * <xsd:enumeration value=\"wavyHeavy\"/>\n * <xsd:enumeration value=\"wavyDouble\"/>\n * <xsd:enumeration value=\"none\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const UnderlineType = {\n /** Single underline */\n SINGLE: \"single\",\n /** Underline words only (not spaces) */\n WORDS: \"words\",\n /** Double underline */\n DOUBLE: \"double\",\n /** Thick single underline */\n THICK: \"thick\",\n /** Dotted underline */\n DOTTED: \"dotted\",\n /** Heavy dotted underline */\n DOTTEDHEAVY: \"dottedHeavy\",\n /** Dashed underline */\n DASH: \"dash\",\n /** Heavy dashed underline */\n DASHEDHEAVY: \"dashedHeavy\",\n /** Long dashed underline */\n DASHLONG: \"dashLong\",\n /** Heavy long dashed underline */\n DASHLONGHEAVY: \"dashLongHeavy\",\n /** Dot-dash underline */\n DOTDASH: \"dotDash\",\n /** Heavy dot-dash underline */\n DASHDOTHEAVY: \"dashDotHeavy\",\n /** Dot-dot-dash underline */\n DOTDOTDASH: \"dotDotDash\",\n /** Heavy dot-dot-dash underline */\n DASHDOTDOTHEAVY: \"dashDotDotHeavy\",\n /** Wave underline */\n WAVE: \"wave\",\n /** Heavy wave underline */\n WAVYHEAVY: \"wavyHeavy\",\n /** Double wave underline */\n WAVYDOUBLE: \"wavyDouble\",\n /** No underline */\n NONE: \"none\",\n} as const;\n","/**\n * Emphasis mark module for WordprocessingML run properties.\n *\n * This module provides support for East Asian emphasis marks, which are\n * characters placed above or below text to emphasize it.\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * @module\n */\n\n/**\n * Emphasis mark types.\n *\n * Defines the types of emphasis marks that can be applied to text.\n * Emphasis marks are commonly used in East Asian typography.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Em\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"none\"/>\n * <xsd:enumeration value=\"dot\"/>\n * <xsd:enumeration value=\"comma\"/>\n * <xsd:enumeration value=\"circle\"/>\n * <xsd:enumeration value=\"underDot\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const EmphasisMarkType = {\n /** No emphasis mark */\n NONE: \"none\",\n /** Comma emphasis mark */\n COMMA: \"comma\",\n /** Circle emphasis mark */\n CIRCLE: \"circle\",\n /** Dot emphasis mark */\n DOT: \"dot\",\n /** Under dot emphasis mark */\n UNDER_DOT: \"underDot\",\n} as const;\n","/**\n * Positional tab types for WordprocessingML documents.\n *\n * @module\n */\n\nexport const PositionalTabAlignment = {\n LEFT: \"left\",\n CENTER: \"center\",\n RIGHT: \"right\",\n} as const;\n\nexport const PositionalTabRelativeTo = {\n MARGIN: \"margin\",\n INDENT: \"indent\",\n} as const;\n\nexport const PositionalTabLeader = {\n NONE: \"none\",\n DOT: \"dot\",\n HYPHEN: \"hyphen\",\n UNDERSCORE: \"underscore\",\n MIDDLE_DOT: \"middleDot\",\n} as const;\n\nexport interface PositionalTabOptions {\n alignment: (typeof PositionalTabAlignment)[keyof typeof PositionalTabAlignment];\n relativeTo: (typeof PositionalTabRelativeTo)[keyof typeof PositionalTabRelativeTo];\n leader: (typeof PositionalTabLeader)[keyof typeof PositionalTabLeader];\n}\n","/**\n * Ruby annotation module for WordprocessingML documents.\n *\n * Ruby annotations are small text rendered above or below base text,\n * commonly used for pronunciation guides in East Asian languages (furigana\n * in Japanese, pinyin in Chinese, etc.).\n *\n * Used via the JSON API: `{ ruby: { text: \"かな\", base: \"漢字\" } }` as a\n * paragraph or run child.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_Ruby\n *\n * @module\n */\n\n/**\n * Ruby alignment options.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_RubyAlign\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"center\"/>\n * <xsd:enumeration value=\"distributeLetter\"/>\n * <xsd:enumeration value=\"distributeSpace\"/>\n * <xsd:enumeration value=\"left\"/>\n * <xsd:enumeration value=\"right\"/>\n * <xsd:enumeration value=\"rightVertical\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const RubyAlign = {\n /** Center alignment */\n CENTER: \"center\",\n /** Distribute letters evenly */\n DISTRIBUTE_LETTER: \"distributeLetter\",\n /** Distribute space evenly */\n DISTRIBUTE_SPACE: \"distributeSpace\",\n /** Left alignment */\n LEFT: \"left\",\n /** Right alignment */\n RIGHT: \"right\",\n /** Right vertical alignment */\n RIGHT_VERTICAL: \"rightVertical\",\n} as const;\n\n/**\n * Options for a Ruby annotation.\n *\n * Used as `{ ruby: RubyOptions }` in paragraph or run children.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Ruby\">\n * <xsd:sequence>\n * <xsd:element name=\"rubyPr\" type=\"CT_RubyPr\"/>\n * <xsd:element name=\"rt\" type=\"CT_RubyContent\"/>\n * <xsd:element name=\"rubyBase\" type=\"CT_RubyContent\"/>\n * </xsd:sequence>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Japanese furigana\n * { ruby: {\n * text: \"かな\",\n * base: \"漢字\",\n * alignment: \"center\",\n * fontSize: 20,\n * languageId: \"ja-JP\",\n * }}\n * ```\n */\nexport interface RubyOptions {\n /** Ruby annotation text (e.g., furigana, pinyin) */\n text: string;\n /** Base text being annotated */\n base: string;\n /** Ruby alignment (defaults to \"center\"). */\n alignment?: (typeof RubyAlign)[keyof typeof RubyAlign];\n /**\n * Font size for the ruby annotation text in points (e.g., 10 = 10pt).\n * Defaults to half the base text size if not specified.\n */\n fontSize?: number;\n /**\n * Vertical offset for the ruby annotation in points.\n * How far the annotation is raised above (or below) the base text.\n */\n raise?: number;\n /**\n * Font size for the base text in points.\n * Used to calculate the ruby annotation positioning.\n */\n baseFontSize?: number;\n /** Language identifier for the ruby annotation (e.g., \"ja-JP\"). */\n languageId?: string;\n /** Whether the ruby annotation is dirty (needs recalculation). */\n dirty?: boolean;\n}\n","/**\n * Form field module for WordprocessingML documents.\n *\n * Form fields allow creating interactive controls (checkboxes, dropdown lists,\n * text inputs) within a document. Each form field is wrapped in a field code\n * region delimited by fldChar elements (begin/separate/end), with ffData\n * attached to the begin fldChar.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_FFData, CT_FFCheckBox, CT_FFDDList, CT_FFTextInput\n *\n * @module\n */\nimport {\n attr,\n attrBool,\n attrNum,\n children as xmlChildren,\n element,\n findChild,\n} from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\n/**\n * Text input field type (ST_FFTextType).\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_FFTextType\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"regular\"/>\n * <xsd:enumeration value=\"number\"/>\n * <xsd:enumeration value=\"date\"/>\n * <xsd:enumeration value=\"currentTime\"/>\n * <xsd:enumeration value=\"currentDate\"/>\n * <xsd:enumeration value=\"calculated\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const FormFieldTextType = {\n /** Regular text input */\n REGULAR: \"regular\",\n /** Numeric input */\n NUMBER: \"number\",\n /** Date input */\n DATE: \"date\",\n /** Current time */\n CURRENT_TIME: \"currentTime\",\n /** Current date */\n CURRENT_DATE: \"currentDate\",\n /** Calculated value */\n CALCULATED: \"calculated\",\n} as const;\n\n/**\n * Options for a checkbox form field.\n */\nexport interface CheckBoxOptions {\n /**\n * Checkbox size in points.\n *\n * Mutually exclusive with `sizeAuto`.\n */\n size?: number;\n /**\n * Whether to auto-size the checkbox to match surrounding text.\n *\n * Mutually exclusive with `size`.\n */\n sizeAuto?: boolean;\n /** Default checked state */\n default?: boolean;\n /** Current checked state */\n checked?: boolean;\n}\n\n/**\n * Options for a dropdown list form field.\n */\nexport interface DropDownListOptions {\n /** Items in the dropdown list */\n entries: string[];\n /** Index of the currently selected entry */\n result?: number;\n /** Index of the default entry */\n default?: number;\n}\n\n/**\n * Options for a text input form field.\n */\nexport interface TextInputOptions {\n /** Text input type */\n type?: (typeof FormFieldTextType)[keyof typeof FormFieldTextType];\n /**\n * Default text value (placeholder / initial state, serialized as `w:default`\n * inside `w:ffData`).\n */\n default?: string;\n /**\n * Current value the user typed into the field (the result-run text between\n * the `separate` and `end` fldChars).\n *\n * Unlike {@link default} this is NOT stored in `w:ffData`; it is captured on\n * parse for round-trip fidelity. On stringify it is rendered as the field\n * result, falling back to {@link default} when unset.\n */\n value?: string;\n /** Maximum character length */\n maxLength?: number;\n /** Format string */\n format?: string;\n}\n\n/**\n * Help or status text options.\n */\nexport interface FormFieldTextOptions {\n /** Text type: \"text\" for custom text, \"autoText\" for auto text reference */\n type: \"text\" | \"autoText\";\n /** The text value */\n value: string;\n}\n\n/**\n * Common options for all form field types.\n */\nexport interface FormFieldCommonOptions {\n /** Field name (max 65 characters) */\n name?: string;\n /** Numeric label */\n label?: number;\n /** Tab order index */\n tabIndex?: number;\n /** Whether the field is enabled */\n enabled?: boolean;\n /** Recalculate fields when exiting */\n calcOnExit?: boolean;\n /** Entry macro name */\n entryMacro?: string;\n /** Exit macro name */\n exitMacro?: string;\n /** Help text shown when the user presses F1 */\n helpText?: FormFieldTextOptions;\n /** Status bar text */\n statusText?: FormFieldTextOptions;\n}\n\n/**\n * Options for a form field definition (CT_FFData).\n *\n * Exactly one of `checkBox`, `dropDownList`, or `textInput` must be specified.\n */\nexport interface FormFieldOptions extends FormFieldCommonOptions {\n /** Checkbox form field */\n checkBox?: CheckBoxOptions;\n /** Dropdown list form field */\n dropDownList?: DropDownListOptions;\n /** Text input form field */\n textInput?: TextInputOptions;\n}\n\n/** Build a w:val-style element with a single attribute. */\nconst valElement = (name: string, val: string | number): string => `<${name} w:val=\"${val}\"/>`;\n\n/**\n * Creates a help or status text element.\n */\nconst createFormFieldText = (name: string, options: FormFieldTextOptions): string =>\n `<${name} w:type=\"${options.type}\" w:val=\"${options.value}\"/>`;\n\n/**\n * Creates a checkbox form field element (w:checkBox).\n */\nconst createCheckBox = (options: CheckBoxOptions): string => {\n const children: string[] = [];\n\n if (options.size !== undefined) {\n children.push(valElement(\"w:size\", options.size * 2));\n } else if (options.sizeAuto !== undefined) {\n children.push(`<w:sizeAuto/>`);\n }\n\n // <w:default> is the reset/initial state Word renders the box in. Word will\n // not render the box without it, so derive it from `checked` when omitted.\n const defaultVal = options.default ?? options.checked;\n if (defaultVal !== undefined) {\n children.push(defaultVal ? `<w:default/>` : `<w:default w:val=\"0\"/>`);\n }\n if (options.checked !== undefined) {\n children.push(options.checked ? `<w:checked/>` : `<w:checked w:val=\"0\"/>`);\n }\n\n return element(\"w:checkBox\", undefined, children);\n};\n\n/**\n * Creates a dropdown list form field element (w:ddList).\n */\nconst createDropDownList = (options: DropDownListOptions): string => {\n const children: string[] = [];\n\n if (options.result !== undefined) {\n children.push(valElement(\"w:result\", options.result));\n }\n if (options.default !== undefined) {\n children.push(valElement(\"w:default\", options.default));\n }\n for (const entry of options.entries) {\n children.push(valElement(\"w:listEntry\", entry));\n }\n\n return element(\"w:ddList\", undefined, children);\n};\n\n/**\n * Creates a text input form field element (w:textInput).\n */\nconst createTextInput = (options: TextInputOptions): string => {\n const children: string[] = [];\n\n if (options.type !== undefined) {\n children.push(valElement(\"w:type\", options.type));\n }\n if (options.default !== undefined) {\n children.push(valElement(\"w:default\", options.default));\n }\n if (options.maxLength !== undefined) {\n children.push(valElement(\"w:maxLength\", options.maxLength));\n }\n if (options.format !== undefined) {\n children.push(valElement(\"w:format\", options.format));\n }\n\n return element(\"w:textInput\", undefined, children);\n};\n\n/**\n * Creates a form field data element (w:ffData).\n *\n * This element contains the definition for an interactive form field\n * (checkbox, dropdown list, or text input) within a document.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_FFData\">\n * <xsd:choice maxOccurs=\"unbounded\">\n * <xsd:element name=\"name\" type=\"CT_FFName\"/>\n * <xsd:element name=\"label\" type=\"CT_DecimalNumber\"/>\n * <xsd:element name=\"tabIndex\" type=\"CT_UnsignedDecimalNumber\"/>\n * <xsd:element name=\"enabled\" type=\"CT_OnOff\"/>\n * <xsd:element name=\"calcOnExit\" type=\"CT_OnOff\"/>\n * <xsd:element name=\"entryMacro\" type=\"CT_MacroName\"/>\n * <xsd:element name=\"exitMacro\" type=\"CT_MacroName\"/>\n * <xsd:element name=\"helpText\" type=\"CT_FFHelpText\"/>\n * <xsd:element name=\"statusText\" type=\"CT_FFStatusText\"/>\n * <xsd:choice>\n * <xsd:element name=\"checkBox\" type=\"CT_FFCheckBox\"/>\n * <xsd:element name=\"ddList\" type=\"CT_FFDDList\"/>\n * <xsd:element name=\"textInput\" type=\"CT_FFTextInput\"/>\n * </xsd:choice>\n * </xsd:choice>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Checkbox\n * createFormFieldData({\n * name: \"Check1\",\n * checkBox: { checked: true, sizeAuto: true },\n * });\n *\n * // Dropdown\n * createFormFieldData({\n * name: \"DropDown1\",\n * dropDownList: { entries: [\"Option A\", \"Option B\", \"Option C\"], result: 0 },\n * });\n *\n * // Text input\n * createFormFieldData({\n * name: \"Text1\",\n * textInput: { type: \"regular\", default: \"Enter text here\" },\n * });\n * ```\n */\nexport const createFormFieldData = (options: FormFieldOptions): string => {\n const children: string[] = [];\n\n if (options.name !== undefined) {\n children.push(valElement(\"w:name\", options.name));\n }\n if (options.label !== undefined) {\n children.push(valElement(\"w:label\", options.label));\n }\n if (options.tabIndex !== undefined) {\n children.push(valElement(\"w:tabIndex\", options.tabIndex));\n }\n // Word requires an explicit <w:enabled/> to render the field; default true.\n // (Previously emitted a val-less tag even for enabled:false, which is \"true\".)\n const enabled = options.enabled ?? true;\n children.push(enabled ? `<w:enabled/>` : `<w:enabled w:val=\"0\"/>`);\n // <w:calcOnExit> defaults to false (Word's standard).\n const calcOnExit = options.calcOnExit ?? false;\n children.push(calcOnExit ? `<w:calcOnExit/>` : `<w:calcOnExit w:val=\"0\"/>`);\n if (options.entryMacro !== undefined) {\n children.push(valElement(\"w:entryMacro\", options.entryMacro));\n }\n if (options.exitMacro !== undefined) {\n children.push(valElement(\"w:exitMacro\", options.exitMacro));\n }\n if (options.helpText) {\n children.push(createFormFieldText(\"w:helpText\", options.helpText));\n }\n if (options.statusText) {\n children.push(createFormFieldText(\"w:statusText\", options.statusText));\n }\n\n // Exactly one of the three mutually exclusive form field types\n if (options.checkBox) {\n children.push(createCheckBox(options.checkBox));\n } else if (options.dropDownList) {\n children.push(createDropDownList(options.dropDownList));\n } else if (options.textInput) {\n children.push(createTextInput(options.textInput));\n }\n\n return element(\"w:ffData\", undefined, children);\n};\n\n/**\n * Parse a w:ffData element back into FormFieldOptions.\n *\n * Inverse of {@link createFormFieldData}. Reads the common form-field metadata\n * (name, label, tabIndex, enabled, calcOnExit) and exactly one of\n * checkBox / dropDownList / textInput.\n */\nexport function parseFormFieldData(el: Element): FormFieldOptions {\n const opts: FormFieldOptions = {};\n\n const name = findChild(el, \"w:name\");\n if (name) opts.name = attr(name, \"w:val\");\n const label = findChild(el, \"w:label\");\n if (label) {\n const v = attrNum(label, \"w:val\");\n if (v !== undefined) opts.label = v;\n }\n const tabIndex = findChild(el, \"w:tabIndex\");\n if (tabIndex) {\n const v = attrNum(tabIndex, \"w:val\");\n if (v !== undefined) opts.tabIndex = v;\n }\n const enabled = findChild(el, \"w:enabled\");\n if (enabled) opts.enabled = attrBool(enabled, \"w:val\") ?? true;\n const calcOnExit = findChild(el, \"w:calcOnExit\");\n if (calcOnExit) opts.calcOnExit = attrBool(calcOnExit, \"w:val\") ?? true;\n\n const checkBox = findChild(el, \"w:checkBox\");\n if (checkBox) {\n const cb: CheckBoxOptions = {};\n if (findChild(checkBox, \"w:sizeAuto\")) cb.sizeAuto = true;\n const size = findChild(checkBox, \"w:size\");\n if (size) {\n const v = attrNum(size, \"w:val\");\n if (v !== undefined) cb.size = v / 2;\n }\n const def = findChild(checkBox, \"w:default\");\n if (def) cb.default = attrBool(def, \"w:val\") ?? true;\n const checked = findChild(checkBox, \"w:checked\");\n if (checked) cb.checked = attrBool(checked, \"w:val\") ?? true;\n opts.checkBox = cb as CheckBoxOptions;\n } else {\n const ddList = findChild(el, \"w:ddList\");\n if (ddList) {\n const entries: string[] = [];\n for (const li of xmlChildren(ddList, \"w:listEntry\")) {\n entries.push(attr(li, \"w:val\") ?? \"\");\n }\n const ddl: DropDownListOptions = { entries };\n const result = findChild(ddList, \"w:result\");\n if (result) {\n const v = attrNum(result, \"w:val\");\n if (v !== undefined) ddl.result = v;\n }\n const def = findChild(ddList, \"w:default\");\n if (def) {\n const v = attrNum(def, \"w:val\");\n if (v !== undefined) ddl.default = v;\n }\n opts.dropDownList = ddl as DropDownListOptions;\n } else {\n const textInput = findChild(el, \"w:textInput\");\n if (textInput) {\n const ti: TextInputOptions = {};\n const type = findChild(textInput, \"w:type\");\n if (type) ti.type = attr(type, \"w:val\") as TextInputOptions[\"type\"];\n const def = findChild(textInput, \"w:default\");\n if (def) ti.default = attr(def, \"w:val\");\n const maxLength = findChild(textInput, \"w:maxLength\");\n if (maxLength) {\n const v = attrNum(maxLength, \"w:val\");\n if (v !== undefined) ti.maxLength = v;\n }\n const format = findChild(textInput, \"w:format\");\n if (format) ti.format = attr(format, \"w:val\");\n opts.textInput = ti as TextInputOptions;\n }\n }\n }\n\n return opts as FormFieldOptions;\n}\n","/**\n * Proof error types for WordprocessingML documents.\n *\n * @module\n */\n\nexport const ProofErrorType = {\n SPELL_START: \"spellStart\",\n SPELL_END: \"spellEnd\",\n GRAM_START: \"gramStart\",\n GRAM_END: \"gramEnd\",\n} as const;\n\nexport type ProofErrorTypeValue = (typeof ProofErrorType)[keyof typeof ProofErrorType];\n","/**\n * Hyperlink types for WordprocessingML documents.\n *\n * @module\n */\n\n/**\n * Hyperlink type enumeration.\n * @publicApi\n */\nexport const HyperlinkType = {\n /** Internal hyperlink to a bookmark within the document */\n INTERNAL: \"INTERNAL\",\n /** External hyperlink to a URL outside the document */\n EXTERNAL: \"EXTERNAL\",\n} as const;\n\n/**\n * Options for creating an internal hyperlink.\n */\nexport interface InternalHyperlinkOptions {\n /** Name of the bookmark to link to within the document */\n anchor: string;\n /** Screen tip text shown when hovering over the hyperlink */\n tooltip?: string;\n}\n\n/**\n * Options for creating an external hyperlink.\n */\nexport interface ExternalHyperlinkOptions {\n /** URL to link to outside the document */\n url: string;\n /** Screen tip text shown when hovering over the hyperlink */\n tooltip?: string;\n /** Target frame for the hyperlink (e.g., \"_blank\", \"_self\") */\n targetFrame?: string;\n}\n","/**\n * Frame properties module for paragraph text frames in WordprocessingML documents.\n *\n * Frames allow paragraphs to be positioned absolutely on the page, enabling text wrapping\n * and drop cap effects. They are commonly used for floating text boxes and decorative elements.\n *\n * Reference: http://officeopenxml.com/WPparagraph-textFrames.php\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { HeightRule } from \"@parts/table\";\nimport type { HorizontalPositionAlign, VerticalPositionAlign } from \"@shared/constants\";\n\n/**\n * Drop cap types for paragraph frames.\n */\nexport const DropCapType = {\n /** No drop cap effect */\n NONE: \"none\",\n /** Drop cap that drops down into the paragraph text */\n DROP: \"drop\",\n /** Drop cap that extends into the margin */\n MARGIN: \"margin\",\n} as const;\n\n/**\n * Frame anchor types specifying what the frame should be anchored relative to.\n */\nexport const FrameAnchorType = {\n /** Anchor relative to the page margin */\n MARGIN: \"margin\",\n /** Anchor relative to the page edge */\n PAGE: \"page\",\n /** Anchor relative to the text column */\n TEXT: \"text\",\n} as const;\n\n/**\n * Text wrapping types for frames.\n */\nexport const FrameWrap = {\n /** Wrap text around the frame on all sides */\n AROUND: \"around\",\n /** Automatic wrapping based on available space */\n AUTO: \"auto\",\n /** No text wrapping */\n NONE: \"none\",\n /** Do not allow text beside the frame */\n NOT_BESIDE: \"notBeside\",\n /** Allow text to flow through the frame */\n THROUGH: \"through\",\n /** Wrap text tightly around the frame */\n TIGHT: \"tight\",\n} as const;\n\n/**\n * Base options shared by all frame types.\n */\ninterface BaseFrameOptions {\n /** Lock the anchor position to prevent it from moving */\n anchorLock?: boolean;\n /** Drop cap effect type */\n dropCap?: (typeof DropCapType)[keyof typeof DropCapType];\n /** Frame width in twips or universal measure (e.g., \"1cm\", \"0.5in\") */\n width?: number | UniversalMeasure;\n /** Frame height in twips or universal measure (e.g., \"1cm\", \"0.5in\") */\n height?: number | UniversalMeasure;\n /** Text wrapping behavior around the frame */\n wrap?: (typeof FrameWrap)[keyof typeof FrameWrap];\n /** Number of lines for drop cap effect */\n lines?: number;\n /** Anchor reference points for horizontal and vertical positioning */\n anchor?: {\n /** Horizontal anchor reference point */\n horizontal: (typeof FrameAnchorType)[keyof typeof FrameAnchorType];\n /** Vertical anchor reference point */\n vertical: (typeof FrameAnchorType)[keyof typeof FrameAnchorType];\n };\n /** Spacing between frame and surrounding text in twips */\n space?: {\n /** Horizontal spacing in twips or universal measure */\n horizontal: number | UniversalMeasure;\n /** Vertical spacing in twips or universal measure */\n vertical: number | UniversalMeasure;\n };\n /** Height rule determining how frame height is calculated */\n rule?: (typeof HeightRule)[keyof typeof HeightRule];\n}\n\n/**\n * Options for frames positioned using absolute X/Y coordinates.\n */\nexport type XYFrameOptions = {\n /** Must be \"absolute\" for coordinate-based positioning */\n type: \"absolute\";\n /** Absolute X and Y coordinates in twips */\n position: {\n /** Horizontal position in twips or universal measure from the anchor point */\n x: number | UniversalMeasure;\n /** Vertical position in twips or universal measure from the anchor point */\n y: number | UniversalMeasure;\n };\n} & BaseFrameOptions;\n\n/**\n * Options for frames positioned using alignment values.\n */\nexport type AlignmentFrameOptions = {\n /** Must be \"alignment\" for alignment-based positioning */\n type: \"alignment\";\n /** Horizontal and vertical alignment values */\n alignment: {\n /** Horizontal alignment relative to the anchor */\n x: (typeof HorizontalPositionAlign)[keyof typeof HorizontalPositionAlign];\n /** Vertical alignment relative to the anchor */\n y: (typeof VerticalPositionAlign)[keyof typeof VerticalPositionAlign];\n };\n} & BaseFrameOptions;\n\n/**\n * Union type for all frame positioning options.\n */\nexport type FrameOptions = XYFrameOptions | AlignmentFrameOptions;\n","/**\n * Table cell components module for WordprocessingML documents.\n *\n * This module provides types and constants for table cell properties including borders,\n * grid span (column span), vertical merge, and text direction.\n *\n * Reference: http://officeopenxml.com/WPtableCell.php\n *\n * @module\n */\nimport type { BorderOptions } from \"@shared/border\";\n\n/**\n * Options for configuring table cell borders.\n *\n * Defines border settings for individual edges of a table cell.\n */\nexport interface TableCellBordersOptions {\n /** Border for the top edge of the cell */\n top?: BorderOptions;\n /** Border for the start edge (left in LTR, right in RTL) */\n start?: BorderOptions;\n /** Border for the left edge of the cell */\n left?: BorderOptions;\n /** Border for the bottom edge of the cell */\n bottom?: BorderOptions;\n /** Border for the end edge (right in LTR, left in RTL) */\n end?: BorderOptions;\n /** Border for the right edge of the cell */\n right?: BorderOptions;\n /** Inside horizontal border (CT_TcBorders/insideH) */\n insideHorizontal?: BorderOptions;\n /** Inside vertical border (CT_TcBorders/insideV) */\n insideVertical?: BorderOptions;\n /** Diagonal border from top-left to bottom-right */\n topLeftToBottomRight?: BorderOptions;\n /** Diagonal border from top-right to bottom-left */\n topRightToBottomLeft?: BorderOptions;\n}\n\n/**\n * Vertical merge types for table cells.\n *\n * Defines the merge behavior for vertically merged cells (row span).\n */\nexport const VerticalMergeType = {\n /**\n * Cell that is merged with upper one.\n */\n CONTINUE: \"continue\",\n /**\n * Cell that is starting the vertical merge.\n */\n RESTART: \"restart\",\n} as const;\n\n/**\n * Text direction values for table cells.\n *\n * Specifies the direction in which text flows within a table cell.\n */\nexport const TextDirection = {\n /** Text flows from bottom to top, left to right */\n BOTTOM_TO_TOP_LEFT_TO_RIGHT: \"btLr\",\n /** Text flows from left to right, top to bottom (default) */\n LEFT_TO_RIGHT_TOP_TO_BOTTOM: \"lrTb\",\n /** Text flows from top to bottom, right to left */\n TOP_TO_BOTTOM_RIGHT_TO_LEFT: \"tbRl\",\n} as const;\n","/**\n * Table float properties module for WordprocessingML documents.\n *\n * This module provides floating table positioning options, allowing tables\n * to float with text wrapping around them.\n *\n * Reference: http://officeopenxml.com/WPtableFloating.php\n *\n * @module\n */\n\n/**\n * Anchor types for floating table positioning.\n *\n * Specifies the base object from which positioning is determined.\n */\nexport const TableAnchorType = {\n MARGIN: \"margin\",\n PAGE: \"page\",\n TEXT: \"text\",\n} as const;\n\n/**\n * Relative horizontal position values for floating tables.\n */\nexport const RelativeHorizontalPosition = {\n CENTER: \"center\",\n INSIDE: \"inside\",\n LEFT: \"left\",\n OUTSIDE: \"outside\",\n RIGHT: \"right\",\n} as const;\n\n/**\n * Relative vertical position values for floating tables.\n */\nexport const RelativeVerticalPosition = {\n BOTTOM: \"bottom\",\n CENTER: \"center\",\n INLINE: \"inline\",\n INSIDE: \"inside\",\n OUTSIDE: \"outside\",\n TOP: \"top\",\n} as const;\n\n/**\n * Table overlap behavior types.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_TblOverlap\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"never\"/>\n * <xsd:enumeration value=\"overlap\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const OverlapType = {\n NEVER: \"never\",\n OVERLAP: \"overlap\",\n} as const;\n\nexport interface TableFloatOptions {\n /* CSpell:disable */\n horizontalAnchor?: (typeof TableAnchorType)[keyof typeof TableAnchorType];\n absoluteHorizontalPosition?: number;\n relativeHorizontalPosition?: (typeof RelativeHorizontalPosition)[keyof typeof RelativeHorizontalPosition];\n verticalAnchor?: (typeof TableAnchorType)[keyof typeof TableAnchorType];\n absoluteVerticalPosition?: number;\n relativeVerticalPosition?: (typeof RelativeVerticalPosition)[keyof typeof RelativeVerticalPosition];\n bottomFromText?: number;\n topFromText?: number;\n leftFromText?: number;\n rightFromText?: number;\n overlap?: (typeof OverlapType)[keyof typeof OverlapType];\n /* CSpell:enable */\n}\n","/**\n * Table layout module for WordprocessingML documents.\n *\n * This module provides table layout algorithm settings.\n *\n * @module\n */\n\n/**\n * Table layout algorithm types.\n *\n * Specifies how the table width is calculated.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_TblLayoutType\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"fixed\"/>\n * <xsd:enumeration value=\"autofit\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const TableLayoutType = {\n /** Auto-fit layout - column widths are adjusted based on content */\n AUTOFIT: \"autofit\",\n /** Fixed layout - column widths are fixed as specified */\n FIXED: \"fixed\",\n} as const;\n","/**\n * Border module for WordprocessingML documents.\n *\n * Borders are used in multiple contexts (paragraphs, tables, table cells, sections)\n * and share the same CT_Border type definition. This module provides the BorderStyle\n * constants used throughout the document structure.\n *\n * Reference: http://officeopenxml.com/WPborders.php\n *\n * @see http://officeopenxml.com/WPtableBorders.php\n * @see http://officeopenxml.com/WPtableCellProperties-Borders.php\n * @see http://officeopenxml.com/WPsectionBorders.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Border\">\n * <xsd:attribute name=\"val\" type=\"ST_Border\" use=\"required\"/>\n * <xsd:attribute name=\"color\" type=\"ST_HexColor\" use=\"optional\" default=\"auto\"/>\n * <xsd:attribute name=\"themeColor\" type=\"ST_ThemeColor\" use=\"optional\"/>\n * <xsd:attribute name=\"themeTint\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"themeShade\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"sz\" type=\"ST_EighthPointMeasure\" use=\"optional\"/>\n * <xsd:attribute name=\"space\" type=\"ST_PointMeasure\" use=\"optional\" default=\"0\"/>\n * <xsd:attribute name=\"shadow\" type=\"s:ST_OnOff\" use=\"optional\"/>\n * <xsd:attribute name=\"frame\" type=\"s:ST_OnOff\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n *\n * @module\n */\nimport type { ThemeColor } from \"@office-open/core\";\n\n/**\n * Options for configuring a border element.\n *\n * @property style - The border style (single, dashed, dotted, etc.)\n * @property color - Border color in hex format (e.g., \"FF00AA\" for purple)\n * @property size - Border thickness in eighths of a point (1/8 pt)\n * @property space - Spacing offset from the content in points\n */\nexport interface BorderOptions {\n style: (typeof BorderStyle)[keyof typeof BorderStyle];\n /** Border color, in hex (eg 'FF00AA') */\n color?: string;\n /** Theme color reference */\n themeColor?: (typeof ThemeColor)[keyof typeof ThemeColor];\n /** Theme color tint (2-char hex) */\n themeTint?: string;\n /** Theme color shade (2-char hex) */\n themeShade?: string;\n /** Border shadow */\n shadow?: boolean;\n /** Border frame */\n frame?: boolean;\n /** Size of the border in 1/8 pt */\n size?: number;\n /** Spacing offset. Values are specified in pt */\n space?: number;\n}\n\n/**\n * Table borders are defined with the <w:tblBorders> element. Child elements of this element specify the kinds of `border`:\n *\n * `bottom`, `end` (`right` in the previous version of the standard), `insideH`, `insideV`, `start` (`left` in the previous version of the standard), and `top`.\n *\n * Reference: http://officeopenxml.com/WPtableBorders.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Border\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"single\"/>\n * <xsd:enumeration value=\"dashDotStroked\"/>\n * <xsd:enumeration value=\"dashed\"/>\n * <xsd:enumeration value=\"dashSmallGap\"/>\n * <xsd:enumeration value=\"dotDash\"/>\n * <xsd:enumeration value=\"dotDotDash\"/>\n * <xsd:enumeration value=\"dotted\"/>\n * <xsd:enumeration value=\"double\"/>\n * <xsd:enumeration value=\"doubleWave\"/>\n * <xsd:enumeration value=\"inset\"/>\n * <xsd:enumeration value=\"nil\"/>\n * <xsd:enumeration value=\"none\"/>\n * <xsd:enumeration value=\"outset\"/>\n * <xsd:enumeration value=\"thick\"/>\n * <xsd:enumeration value=\"thickThinLargeGap\"/>\n * <xsd:enumeration value=\"thickThinMediumGap\"/>\n * <xsd:enumeration value=\"thickThinSmallGap\"/>\n * <xsd:enumeration value=\"thinThickLargeGap\"/>\n * <xsd:enumeration value=\"thinThickMediumGap\"/>\n * <xsd:enumeration value=\"thinThickSmallGap\"/>\n * <xsd:enumeration value=\"thinThickThinLargeGap\"/>\n * <xsd:enumeration value=\"thinThickThinMediumGap\"/>\n * <xsd:enumeration value=\"thinThickThinSmallGap\"/>\n * <xsd:enumeration value=\"threeDEmboss\"/>\n * <xsd:enumeration value=\"threeDEngrave\"/>\n * <xsd:enumeration value=\"triple\"/>\n * <xsd:enumeration value=\"wave\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const BorderStyle = {\n /** A single line */\n SINGLE: \"single\",\n /** A line with a series of alternating thin and thick strokes */\n DASH_DOT_STROKED: \"dashDotStroked\",\n /** A dashed line */\n DASHED: \"dashed\",\n /** A dashed line with small gaps */\n DASH_SMALL_GAP: \"dashSmallGap\",\n /** A line with alternating dots and dashes */\n DOT_DASH: \"dotDash\",\n /** A line with a repeating dot - dot - dash sequence */\n DOT_DOT_DASH: \"dotDotDash\",\n /** A dotted line */\n DOTTED: \"dotted\",\n /** A double line */\n DOUBLE: \"double\",\n /** A double wavy line */\n DOUBLE_WAVE: \"doubleWave\",\n /** An inset set of lines */\n INSET: \"inset\",\n /** No border */\n NIL: \"nil\",\n /** No border */\n NONE: \"none\",\n /** An outset set of lines */\n OUTSET: \"outset\",\n /** A single line */\n THICK: \"thick\",\n /** A thick line contained within a thin line with a large-sized intermediate gap */\n THICK_THIN_LARGE_GAP: \"thickThinLargeGap\",\n /** A thick line contained within a thin line with a medium-sized intermediate gap */\n THICK_THIN_MEDIUM_GAP: \"thickThinMediumGap\",\n /** A thick line contained within a thin line with a small intermediate gap */\n THICK_THIN_SMALL_GAP: \"thickThinSmallGap\",\n /** A thin line contained within a thick line with a large-sized intermediate gap */\n THIN_THICK_LARGE_GAP: \"thinThickLargeGap\",\n /** A thick line contained within a thin line with a medium-sized intermediate gap */\n THIN_THICK_MEDIUM_GAP: \"thinThickMediumGap\",\n /** A thick line contained within a thin line with a small intermediate gap */\n THIN_THICK_SMALL_GAP: \"thinThickSmallGap\",\n /** A thin-thick-thin line with a large gap */\n THIN_THICK_THIN_LARGE_GAP: \"thinThickThinLargeGap\",\n /** A thin-thick-thin line with a medium gap */\n THIN_THICK_THIN_MEDIUM_GAP: \"thinThickThinMediumGap\",\n /** A thin-thick-thin line with a small gap */\n THIN_THICK_THIN_SMALL_GAP: \"thinThickThinSmallGap\",\n /** A three-staged gradient line, getting darker towards the paragraph */\n THREE_D_EMBOSS: \"threeDEmboss\",\n /** A three-staged gradient like, getting darker away from the paragraph */\n THREE_D_ENGRAVE: \"threeDEngrave\",\n /** A triple line */\n TRIPLE: \"triple\",\n /** A wavy line */\n WAVE: \"wave\",\n} as const;\n","/**\n * Table borders module for WordprocessingML documents.\n *\n * This module provides border options for tables.\n *\n * Reference: http://officeopenxml.com/WPtableBorders.php\n *\n * @module\n */\nimport { BorderStyle } from \"@shared/border\";\nimport type { BorderOptions } from \"@shared/border\";\n\n/**\n * Options for configuring table borders.\n *\n * Borders can be applied to the outside edges (top, bottom, left, right)\n * and inside lines (insideHorizontal, insideVertical) of the table.\n */\nexport interface TableBordersOptions {\n top?: BorderOptions;\n bottom?: BorderOptions;\n left?: BorderOptions;\n right?: BorderOptions;\n insideHorizontal?: BorderOptions;\n insideVertical?: BorderOptions;\n}\n\nconst NONE_BORDER: BorderOptions = {\n color: \"auto\",\n size: 0,\n style: BorderStyle.NONE,\n};\n\nexport const TABLE_BORDERS_NONE: TableBordersOptions = {\n bottom: NONE_BORDER,\n insideHorizontal: NONE_BORDER,\n insideVertical: NONE_BORDER,\n left: NONE_BORDER,\n right: NONE_BORDER,\n top: NONE_BORDER,\n};\n","/**\n * Table row height module for WordprocessingML documents.\n *\n * This module provides row height configuration including rules for how height should be applied.\n *\n * Reference: http://officeopenxml.com/WPtableRow.php\n *\n * @module\n */\n\n/**\n * Height rules for table rows.\n *\n * Specifies how the height value should be interpreted.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_HeightRule\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"auto\"/>\n * <xsd:enumeration value=\"exact\"/>\n * <xsd:enumeration value=\"atLeast\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const HeightRule = {\n /** Height is determined based on the content, so value is ignored. */\n AUTO: \"auto\",\n /** At least the value specified */\n ATLEAST: \"atLeast\",\n /** Exactly the value specified */\n EXACT: \"exact\",\n} as const;\n","/**\n * Table width module for WordprocessingML documents.\n *\n * This module provides width specifications for tables and cells.\n *\n * Reference: http://officeopenxml.com/WPtableWidth.php\n *\n * @module\n */\nimport type { Percentage, UniversalMeasure } from \"@office-open/core\";\n\n/**\n * Width type values for tables and cells.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_TblWidth\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"nil\"/>\n * <xsd:enumeration value=\"pct\"/>\n * <xsd:enumeration value=\"dxa\"/>\n * <xsd:enumeration value=\"auto\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const WidthType = {\n /** Auto. */\n AUTO: \"auto\",\n /** Value is in twentieths of a point */\n DXA: \"dxa\",\n /** No (empty) value. */\n NIL: \"nil\",\n /** Value is in percentage. */\n PERCENTAGE: \"pct\",\n} as const;\n\n/**\n * Properties for specifying table or cell width.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_TblWidth\">\n * <xsd:attribute name=\"w\" type=\"ST_MeasurementOrPercent\"/>\n * <xsd:attribute name=\"type\" type=\"ST_TblWidth\"/>\n * </xsd:complexType>\n * ```\n */\nexport interface TableWidthProperties {\n size: number | Percentage | UniversalMeasure;\n type?: (typeof WidthType)[keyof typeof WidthType];\n}\n\n/**\n * OOXML stores width percentages as fiftieths-of-a-percent integer\n * (`w:w=\"5000\"`, `w:type=\"pct\"` = 100%). The public API exposes them as plain\n * percentages (`size: 100` = 100%); these helpers convert at the stringify/parse\n * boundary so callers never handle the raw 5000 value. A bare number must never\n * be emitted with a \"%\" suffix — that is a different XSD branch (`s:ST_Percentage`)\n * meaning 5000%, which Word treats as `auto` on `tblW`.\n */\n\n/** Stringify: percentage (`100`, `\"50%\"`) → OOXML fiftieths integer (`5000`). */\nexport const widthPctToFiftieths = (\n size: number | Percentage | UniversalMeasure,\n): number | Percentage | UniversalMeasure => {\n if (typeof size === \"number\") return Math.round(size * 50);\n if (size.endsWith(\"%\")) return Math.round(Number(size.slice(0, -1)) * 50);\n return size;\n};\n\n/** Parse: OOXML fiftieths (`5000`) → percentage (`100`) when `type` is `\"pct\"`. */\nexport const widthFiftiethsToPct = (\n size: number | string | undefined,\n type: string | undefined,\n): number | string | undefined => (type === \"pct\" && typeof size === \"number\" ? size / 50 : size);\n","/**\n * Object element for WordprocessingML documents — w:object.\n *\n * Embeds an OLE object (e.g. an Excel sheet) in a run via a VML preview shape and\n * exactly one of OLEObject / control / movie. The OLE payload is emitted as\n * `<o:OLEObject>` (the vml-officeDrawing element Word actually writes via\n * CT_Object's lax any slot) — the XSD-declared `w:objectEmbed`/`w:objectLink`\n * spellings parse back but are rejected by Word's reader. The OLE binary is\n * registered as word/embeddings/oleObjectN.bin (EmbeddingCollection); the optional\n * preview icon as word/media/imageN.<type> (Media). Relationship ids are emitted\n * as `{fileName}` placeholders and rewritten by the compiler's media bridge.\n *\n * Reference: OOXML transitional, wml.xsd CT_Object; vml-officeDrawing.xsd CT_OLEObject\n *\n * @module\n */\nimport { toUint8Array, parseOnOff } from \"@office-open/core\";\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport { parseVmlStyle } from \"@office-open/core\";\nimport { stringifyVmlShape } from \"@office-open/core\";\nimport { parseVmlImageData, type VmlImageDataOptions } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrNum, escapeXml, findChild, textOf, type Element } from \"@office-open/xml\";\nimport type { EmbeddingData } from \"@shared/embeddings/embeddings\";\nimport type { MediaData } from \"@shared/media/data\";\n\nimport type { BodyContext } from \"../../context\";\nimport { createPictureData } from \"../paragraph/run/picture-run\";\n\n// ── Options ──\n\nexport interface ObjectEmbedOptions {\n /** OLE container binary — registered as word/embeddings/oleObjectN.bin. */\n data: Uint8Array | string;\n /** OLE program id (e.g. \"Excel.Sheet.12\"). */\n progId?: string;\n /** Draw aspect — how the object displays. */\n drawAspect?: \"content\" | \"icon\";\n /** Shape id (o:OLEObject/@ShapeID). Defaults to the preview shape's id. */\n shapeId?: string;\n /** OLE object id (o:OLEObject/@ObjectID). Defaults to a generated id. */\n objectId?: string;\n /** Field codes (o:OLEObject/o:FieldCodes child). */\n fieldCodes?: string;\n}\n\nexport interface ObjectLinkOptions extends ObjectEmbedOptions {\n /** Update mode (required for links). */\n updateMode: \"always\" | \"onCall\";\n /** Whether the field is locked. */\n lockedField?: boolean;\n}\n\nexport interface ObjectControlOptions {\n /** Control name (w:control/@name). */\n name?: string;\n /** Shape id (w:control/@shapeid). */\n shapeid?: string;\n /** Relationship id to the ActiveX part (external — not auto-registered). */\n rId: string;\n}\n\nexport interface ObjectIconImageOptions {\n /** Preview image bytes (binary or base64 data URL). */\n data: Uint8Array | string;\n /** Image type / extension (e.g. \"png\", \"emf\"). */\n type: string;\n /** Title for v:imagedata/@o:title. */\n title?: string;\n}\n\nexport interface ObjectElementOptions {\n /** Original width in twips (w:object/@w:dxaOrig). */\n dxaOrig?: number;\n /** Original height in twips (w:object/@w:dyaOrig). */\n dyaOrig?: number;\n /** VML shape id (v:shape/@id). Defaults to a generated id. */\n shapeId?: string;\n /** Display width (px or universal measure) for v:shape style + icon size. */\n width?: number | UniversalMeasure;\n /** Display height (px or universal measure). */\n height?: number | UniversalMeasure;\n /** Preview icon image (v:imagedata). */\n iconImage?: ObjectIconImageOptions;\n /** Embedded OLE object (o:OLEObject Type=\"Embed\"). */\n embed?: ObjectEmbedOptions;\n /** Linked OLE object (o:OLEObject Type=\"Link\"). */\n link?: ObjectLinkOptions;\n /** ActiveX control reference (w:control). */\n control?: ObjectControlOptions;\n /** Movie relationship id — CT_Rel (w:movie/@r:id). External. */\n movie?: string;\n}\n\n// ── Descriptor ──\n\nlet objectShapeCounter = 1025;\nlet objectOleCounter = 1;\n\nexport const objectDesc: CustomDescriptor<ObjectElementOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const inner: string[] = [];\n\n // VML preview shape (v:shape + optional v:imagedata)\n const shapeId = opts.shapeId ?? `_x0000_i${objectShapeCounter++}`;\n const widthVal = opts.width ?? 100;\n const heightVal = opts.height ?? 100;\n const styleWidth =\n typeof widthVal === \"number\" ? (`${widthVal}px` as UniversalMeasure) : widthVal;\n const styleHeight =\n typeof heightVal === \"number\" ? (`${heightVal}px` as UniversalMeasure) : heightVal;\n\n let imagedataOptions: VmlImageDataOptions | undefined;\n if (opts.iconImage) {\n const rawData = toUint8Array(opts.iconImage.data) as Uint8Array;\n const iconType = opts.iconImage.type;\n const { fileName: iconFileName } = ctx.file.media.addMedia(\n rawData,\n iconType,\n (fileName) =>\n ({\n type: iconType,\n ...createPictureData(rawData, { width: widthVal, height: heightVal }, fileName),\n }) as MediaData,\n );\n imagedataOptions = {\n relationshipId: `{${iconFileName}}`,\n officeTitle: opts.iconImage.title,\n };\n }\n inner.push(\n stringifyVmlShape({\n id: shapeId,\n type: \"#_x0000_t75\",\n // o:ole marks the shape as an OLE container (Word always writes it here).\n ole: \"\",\n style: { width: styleWidth, height: styleHeight },\n imagedata: imagedataOptions,\n }),\n );\n\n // Choice: o:OLEObject (embed/link) | w:control | w:movie\n if (opts.embed || opts.link) {\n const link = opts.link;\n const payload = opts.embed ?? link!;\n const fileName = registerEmbedding(payload, ctx);\n const attrs: string[] = [` Type=\"${link ? \"Link\" : \"Embed\"}\"`];\n if (payload.progId) attrs.push(` ProgID=\"${payload.progId}\"`);\n // Word ties the OLE object to its preview shape via ShapeID.\n attrs.push(` ShapeID=\"${payload.shapeId ?? shapeId}\"`);\n if (payload.drawAspect) {\n attrs.push(` DrawAspect=\"${payload.drawAspect === \"icon\" ? \"Icon\" : \"Content\"}\"`);\n }\n attrs.push(` ObjectID=\"${payload.objectId ?? `_${objectOleCounter++}`}\"`);\n attrs.push(` r:id=\"{${fileName}}\"`);\n let children = \"\";\n if (link) {\n attrs.push(` UpdateMode=\"${link.updateMode === \"onCall\" ? \"OnCall\" : \"Always\"}\"`);\n const innerEls: string[] = [];\n if (link.lockedField !== undefined) {\n innerEls.push(`<o:LockedField>${link.lockedField ? \"t\" : \"f\"}</o:LockedField>`);\n }\n if (link.fieldCodes)\n innerEls.push(`<o:FieldCodes>${escapeXml(link.fieldCodes)}</o:FieldCodes>`);\n children = innerEls.join(\"\");\n }\n const open = `<o:OLEObject${attrs.join(\"\")}`;\n inner.push(children ? `${open}>${children}</o:OLEObject>` : `${open}/>`);\n } else if (opts.control) {\n const c = opts.control;\n const cAttrs: string[] = [` r:id=\"${c.rId}\"`];\n if (c.name) cAttrs.push(` w:name=\"${c.name}\"`);\n if (c.shapeid) cAttrs.push(` w:shapeid=\"${c.shapeid}\"`);\n inner.push(`<w:control${cAttrs.join(\"\")}/>`);\n } else if (opts.movie) {\n inner.push(`<w:movie r:id=\"${opts.movie}\"/>`);\n }\n\n // w:object root attributes\n const objAttrs: string[] = [];\n if (opts.dxaOrig !== undefined) objAttrs.push(` w:dxaOrig=\"${opts.dxaOrig}\"`);\n if (opts.dyaOrig !== undefined) objAttrs.push(` w:dyaOrig=\"${opts.dyaOrig}\"`);\n\n return `<w:object${objAttrs.join(\"\")}>${inner.join(\"\")}</w:object>`;\n },\n\n parse(el, _ctx) {\n const result: Partial<ObjectElementOptions> = {};\n\n const dxaOrig = attrNum(el, \"w:dxaOrig\");\n if (dxaOrig !== undefined) result.dxaOrig = dxaOrig;\n const dyaOrig = attrNum(el, \"w:dyaOrig\");\n if (dyaOrig !== undefined) result.dyaOrig = dyaOrig;\n\n // VML shape — best-effort structural capture (binary media is not re-registered on parse)\n const shape = findChild(el, \"v:shape\");\n if (shape) {\n const id = attr(shape, \"id\");\n if (id) result.shapeId = id;\n const style = attr(shape, \"style\");\n if (style) {\n const parsed = parseVmlStyle(style);\n if (parsed[\"width\"]) result.width = parsed[\"width\"] as UniversalMeasure;\n if (parsed[\"height\"]) result.height = parsed[\"height\"] as UniversalMeasure;\n }\n const imagedataEl = findChild(shape, \"v:imagedata\");\n if (imagedataEl) {\n const imagedata = parseVmlImageData(imagedataEl);\n result.iconImage = {\n data: new Uint8Array(),\n type: extensionOf(imagedata.src ?? imagedata.relationshipId ?? \"\"),\n ...(imagedata.officeTitle !== undefined ? { title: imagedata.officeTitle } : {}),\n };\n }\n }\n\n // Choice elements — o:OLEObject is what Word writes; the w:objectEmbed/\n // w:objectLink spellings are accepted for XSD-conforming third-party files.\n const oleEl = findChild(el, \"o:OLEObject\");\n if (oleEl) {\n const common = parseOleObject(oleEl);\n if (attr(oleEl, \"Type\") === \"Link\") {\n const updateMode = attr(oleEl, \"UpdateMode\");\n const lockedFieldEl = findChild(oleEl, \"o:LockedField\");\n result.link = {\n ...common,\n updateMode: updateMode === \"OnCall\" ? \"onCall\" : \"always\",\n ...(lockedFieldEl ? { lockedField: parseOnOff(textOf(lockedFieldEl)) ?? false } : {}),\n };\n } else {\n result.embed = common;\n }\n }\n\n const embedEl = findChild(el, \"w:objectEmbed\");\n if (embedEl) result.embed = parseEmbed(embedEl);\n\n const linkEl = findChild(el, \"w:objectLink\");\n if (linkEl) {\n const base = parseEmbed(linkEl);\n const updateMode = attr(linkEl, \"w:updateMode\");\n const lockedField = attr(linkEl, \"w:lockedField\");\n result.link = {\n ...base,\n ...(updateMode ? { updateMode: updateMode as \"always\" | \"onCall\" } : {}),\n ...(lockedField !== undefined ? { lockedField: parseOnOff(lockedField) ?? false } : {}),\n } as ObjectLinkOptions;\n }\n\n const controlEl = findChild(el, \"w:control\");\n if (controlEl) {\n const rId = attr(controlEl, \"r:id\") ?? \"\";\n const name = attr(controlEl, \"w:name\");\n const shapeid = attr(controlEl, \"w:shapeid\");\n result.control = { rId, ...(name ? { name } : {}), ...(shapeid ? { shapeid } : {}) };\n }\n\n const movieEl = findChild(el, \"w:movie\");\n if (movieEl) {\n const rId = attr(movieEl, \"r:id\");\n if (rId) result.movie = rId;\n }\n\n return result as ObjectElementOptions;\n },\n};\n\n// ── Helpers ──\n\n/** Extract the file extension from an image reference (\"\" when absent). */\nfunction extensionOf(ref: string): string {\n const dot = ref.lastIndexOf(\".\");\n if (dot === -1) return \"\";\n return ref.slice(dot + 1);\n}\n\n/** Register an OLE embedding and return its allocated file name. */\nfunction registerEmbedding(opts: ObjectEmbedOptions, ctx: BodyContext): string {\n const fileName = ctx.file.embeddings.nextEmbeddingName();\n const data: EmbeddingData = {\n fileName,\n data: toUint8Array(opts.data) as Uint8Array,\n ...(opts.progId ? { progId: opts.progId } : {}),\n };\n ctx.file.embeddings.addEmbedding(fileName, data);\n return fileName;\n}\n\n/** Parse common o:OLEObject attributes (excludes r:id — external on parse). */\nfunction parseOleObject(el: Element): ObjectEmbedOptions {\n const opts: Partial<ObjectEmbedOptions> = {};\n const drawAspect = attr(el, \"DrawAspect\");\n if (drawAspect === \"Icon\") opts.drawAspect = \"icon\";\n else if (drawAspect === \"Content\") opts.drawAspect = \"content\";\n const progId = attr(el, \"ProgID\");\n if (progId) opts.progId = progId;\n const shapeId = attr(el, \"ShapeID\");\n if (shapeId) opts.shapeId = shapeId;\n const objectId = attr(el, \"ObjectID\");\n if (objectId) opts.objectId = objectId;\n const fieldCodesEl = findChild(el, \"o:FieldCodes\");\n if (fieldCodesEl) opts.fieldCodes = textOf(fieldCodesEl);\n // data is not recoverable from the relationship on parse; callers re-supply it.\n opts.data = new Uint8Array();\n return opts as ObjectEmbedOptions;\n}\n\n/** Parse common objectEmbed/objectLink attributes (excludes r:id — external on parse). */\nfunction parseEmbed(el: Element): ObjectEmbedOptions {\n const opts: Partial<ObjectEmbedOptions> = {};\n const drawAspect = attr(el, \"w:drawAspect\");\n if (drawAspect === \"content\" || drawAspect === \"icon\") opts.drawAspect = drawAspect;\n const progId = attr(el, \"w:progId\");\n if (progId) opts.progId = progId;\n const shapeId = attr(el, \"w:shapeId\");\n if (shapeId) opts.shapeId = shapeId;\n const fieldCodes = attr(el, \"w:fieldCodes\");\n if (fieldCodes) opts.fieldCodes = fieldCodes;\n // data is not recoverable from the relationship on parse; callers re-supply it.\n opts.data = new Uint8Array();\n return opts as ObjectEmbedOptions;\n}\n","/**\n * Shading module for WordprocessingML documents.\n *\n * Shading is used to apply background colors and patterns to paragraphs,\n * table cells, and text runs. The shading type is identical in all places.\n *\n * Reference: http://officeopenxml.com/WPshading.php\n *\n * @see http://officeopenxml.com/WPtableShading.php\n * @see http://officeopenxml.com/WPtableCellProperties-Shading.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Shd\">\n * <xsd:attribute name=\"val\" type=\"ST_Shd\" use=\"required\"/>\n * <xsd:attribute name=\"color\" type=\"ST_HexColor\" use=\"optional\"/>\n * <xsd:attribute name=\"themeColor\" type=\"ST_ThemeColor\" use=\"optional\"/>\n * <xsd:attribute name=\"themeTint\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"themeShade\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"fill\" type=\"ST_HexColor\" use=\"optional\"/>\n * <xsd:attribute name=\"themeFill\" type=\"ST_ThemeColor\" use=\"optional\"/>\n * <xsd:attribute name=\"themeFillTint\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"themeFillShade\" type=\"ST_UcharHexNumber\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n *\n * @module\n */\nimport { ThemeColor } from \"@office-open/core\";\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\n/**\n * Properties for configuring shading.\n *\n * @property fill - Background fill color in hex format (e.g., \"FF0000\" for red)\n * @property color - Pattern color in hex format\n * @property type - Shading pattern type\n */\nexport interface ShadingProperties {\n fill?: string;\n color?: string;\n type?: (typeof ShadingType)[keyof typeof ShadingType];\n /** Theme color reference */\n themeColor?: (typeof ThemeColor)[keyof typeof ThemeColor];\n /** Theme color tint (2-char hex) */\n themeTint?: string;\n /** Theme color shade (2-char hex) */\n themeShade?: string;\n /** Theme fill color reference */\n themeFill?: (typeof ThemeColor)[keyof typeof ThemeColor];\n /** Theme fill tint (2-char hex) */\n themeFillTint?: string;\n /** Theme fill shade (2-char hex) */\n themeFillShade?: string;\n}\n\n/**\n * Shading pattern types.\n *\n * Specifies the pattern used for shading. The pattern combines the fill\n * color and the pattern color.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_Shd\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"nil\"/>\n * <xsd:enumeration value=\"clear\"/>\n * <xsd:enumeration value=\"solid\"/>\n * <xsd:enumeration value=\"horzStripe\"/>\n * <xsd:enumeration value=\"vertStripe\"/>\n * <xsd:enumeration value=\"reverseDiagStripe\"/>\n * <xsd:enumeration value=\"diagStripe\"/>\n * <xsd:enumeration value=\"horzCross\"/>\n * <xsd:enumeration value=\"diagCross\"/>\n * <!-- ... percent values ... -->\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const ShadingType = {\n /** Clear shading - no pattern, fill color only */\n CLEAR: \"clear\",\n DIAGONAL_CROSS: \"diagCross\",\n DIAGONAL_STRIPE: \"diagStripe\",\n HORIZONTAL_CROSS: \"horzCross\",\n HORIZONTAL_STRIPE: \"horzStripe\",\n NIL: \"nil\",\n PERCENT_10: \"pct10\",\n PERCENT_12: \"pct12\",\n PERCENT_15: \"pct15\",\n PERCENT_20: \"pct20\",\n PERCENT_25: \"pct25\",\n PERCENT_30: \"pct30\",\n PERCENT_35: \"pct35\",\n PERCENT_37: \"pct37\",\n PERCENT_40: \"pct40\",\n PERCENT_45: \"pct45\",\n PERCENT_5: \"pct5\",\n PERCENT_50: \"pct50\",\n PERCENT_55: \"pct55\",\n PERCENT_60: \"pct60\",\n PERCENT_62: \"pct62\",\n PERCENT_65: \"pct65\",\n PERCENT_70: \"pct70\",\n PERCENT_75: \"pct75\",\n PERCENT_80: \"pct80\",\n PERCENT_85: \"pct85\",\n PERCENT_87: \"pct87\",\n PERCENT_90: \"pct90\",\n PERCENT_95: \"pct95\",\n REVERSE_DIAGONAL_STRIPE: \"reverseDiagStripe\",\n SOLID: \"solid\",\n THIN_DIAGONAL_CROSS: \"thinDiagCross\",\n THIN_DIAGONAL_STRIPE: \"thinDiagStripe\",\n THIN_HORIZONTAL_CROSS: \"thinHorzCross\",\n THIN_REVERSE_DIAGONAL_STRIPE: \"thinReverseDiagStripe\",\n THIN_VERTICAL_STRIPE: \"thinVertStripe\",\n VERTICAL_STRIPE: \"vertStripe\",\n} as const;\n\nconst THEME_COLORS = Object.values(ThemeColor) as readonly string[];\n\n/**\n * Parse a w:shd (CT_Shd) element into ShadingProperties.\n *\n * Reads every CT_Shd attribute (fill/color/val plus the theme* family), so the\n * result round-trips losslessly — paragraph, table-cell, and run shading all\n * share this single reader. Returns undefined when the element carries no data.\n */\nexport function parseShading(shd: Element): ShadingProperties | undefined {\n const shading: ShadingProperties = {};\n const fill = attr(shd, \"w:fill\");\n if (fill) shading.fill = fill;\n const color = attr(shd, \"w:color\");\n if (color) shading.color = color;\n const val = attr(shd, \"w:val\");\n if (val) shading.type = val as ShadingProperties[\"type\"];\n const themeColor = attr(shd, \"w:themeColor\");\n if (themeColor && THEME_COLORS.includes(themeColor)) {\n shading.themeColor = themeColor as ShadingProperties[\"themeColor\"];\n }\n const themeTint = attr(shd, \"w:themeTint\");\n if (themeTint) shading.themeTint = themeTint;\n const themeShade = attr(shd, \"w:themeShade\");\n if (themeShade) shading.themeShade = themeShade;\n const themeFill = attr(shd, \"w:themeFill\");\n if (themeFill && THEME_COLORS.includes(themeFill)) {\n shading.themeFill = themeFill as ShadingProperties[\"themeFill\"];\n }\n const themeFillTint = attr(shd, \"w:themeFillTint\");\n if (themeFillTint) shading.themeFillTint = themeFillTint;\n const themeFillShade = attr(shd, \"w:themeFillShade\");\n if (themeFillShade) shading.themeFillShade = themeFillShade;\n if (Object.keys(shading).length === 0) return undefined;\n return shading;\n}\n","/**\n * Run properties parser for DOCX documents.\n *\n * Parses w:rPr Element trees into RunPropertiesOptions objects.\n *\n * @module\n */\nimport {\n attr,\n attrBool,\n attrMeasure,\n attrNum,\n colorAttr,\n findChild,\n textOf,\n} from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { objectDesc } from \"@parts/object\";\nimport type { ObjectElementOptions } from \"@parts/object\";\nimport type { FootnoteEndnoteReferenceOptions } from \"@parts/paragraph/paragraph\";\nimport type {\n BreakClear,\n BreakOptions,\n RunPropertiesOptions,\n RunOptions,\n} from \"@parts/paragraph/run\";\nimport { parseShading } from \"@shared/shading\";\n\nimport type { DocxReadContext } from \"../../../context\";\nimport { stringifyElement } from \"../../../util/stringify-element\";\nimport type { LanguageOptions } from \"./language\";\n\n/**\n * Parse a w:rPr element into RunPropertiesOptions.\n */\nexport function parseRunProperties(el: Element): RunPropertiesOptions {\n const opts: Record<string, unknown> = {};\n\n const rStyle = findChild(el, \"w:rStyle\");\n if (rStyle) opts.style = attr(rStyle, \"w:val\");\n\n const font = findChild(el, \"w:rFonts\");\n if (font) {\n const ascii = attr(font, \"w:ascii\");\n const eastAsia = attr(font, \"w:eastAsia\");\n const hAnsi = attr(font, \"w:hAnsi\");\n const complexScript = attr(font, \"w:cs\");\n const asciiTheme = attr(font, \"w:asciiTheme\");\n const eastAsiaTheme = attr(font, \"w:eastAsiaTheme\");\n const hAnsiTheme = attr(font, \"w:hAnsiTheme\");\n const cstheme = attr(font, \"w:cstheme\");\n const hint = attr(font, \"w:hint\");\n\n if (\n ascii &&\n !eastAsia &&\n !hAnsi &&\n !complexScript &&\n !asciiTheme &&\n !eastAsiaTheme &&\n !hAnsiTheme &&\n !cstheme\n ) {\n opts.font = hint ? { name: ascii, hint } : ascii;\n } else {\n const fontObj: Record<string, string | undefined> = {};\n if (ascii) fontObj.ascii = ascii;\n if (eastAsia) fontObj.eastAsia = eastAsia;\n if (hAnsi) fontObj.hAnsi = hAnsi;\n if (complexScript) fontObj.complexScript = complexScript;\n if (asciiTheme) fontObj.asciiTheme = asciiTheme;\n if (eastAsiaTheme) fontObj.eastAsiaTheme = eastAsiaTheme;\n if (hAnsiTheme) fontObj.hAnsiTheme = hAnsiTheme;\n if (cstheme) fontObj.complexScriptTheme = cstheme;\n if (hint) fontObj.hint = hint;\n opts.font = fontObj;\n }\n }\n\n const bold = findChild(el, \"w:b\");\n if (bold) opts.bold = attrBool(bold, \"w:val\") ?? true;\n\n const boldCs = findChild(el, \"w:bCs\");\n if (boldCs) opts.boldComplexScript = attrBool(boldCs, \"w:val\") ?? true;\n\n const italic = findChild(el, \"w:i\");\n if (italic) opts.italic = attrBool(italic, \"w:val\") ?? true;\n\n const italicCs = findChild(el, \"w:iCs\");\n if (italicCs) opts.italicComplexScript = attrBool(italicCs, \"w:val\") ?? true;\n\n const underline = findChild(el, \"w:u\");\n if (underline) {\n const ul: Record<string, string | undefined> = {};\n const uType = attr(underline, \"w:val\");\n if (uType) ul.type = uType;\n const uColor = colorAttr(underline, \"w:color\");\n if (uColor) ul.color = uColor;\n opts.underline = ul;\n }\n\n // On/off properties\n for (const [name, optKey] of [\n [\"w:strike\", \"strike\"],\n [\"w:dstrike\", \"doubleStrike\"],\n [\"w:outline\", \"outline\"],\n [\"w:shadow\", \"shadow\"],\n [\"w:emboss\", \"emboss\"],\n [\"w:imprint\", \"imprint\"],\n [\"w:vanish\", \"vanish\"],\n [\"w:webHidden\", \"webHidden\"],\n [\"w:noProof\", \"noProof\"],\n [\"w:snapToGrid\", \"snapToGrid\"],\n [\"w:smallCaps\", \"smallCaps\"],\n [\"w:caps\", \"allCaps\"],\n [\"w:rtl\", \"rightToLeft\"],\n [\"w:cs\", \"complexScript\"],\n [\"w:specVanish\", \"specVanish\"],\n [\"w:oMath\", \"math\"],\n ] as const) {\n const child = findChild(el, name);\n if (child) opts[optKey] = attrBool(child, \"w:val\") ?? true;\n }\n\n const color = findChild(el, \"w:color\");\n if (color) {\n const c = colorAttr(color, \"w:val\");\n const themeColor = attr(color, \"w:themeColor\");\n const themeTint = attr(color, \"w:themeTint\");\n const themeShade = attr(color, \"w:themeShade\");\n if (themeColor || themeTint || themeShade) {\n const colorObj: Record<string, string | undefined> = {};\n if (c) colorObj.val = c;\n if (themeColor) colorObj.themeColor = themeColor;\n if (themeTint) colorObj.themeTint = themeTint;\n if (themeShade) colorObj.themeShade = themeShade;\n opts.color = colorObj;\n } else if (c) {\n opts.color = c;\n }\n }\n\n const sz = findChild(el, \"w:sz\");\n if (sz) {\n const halfPts = attrNum(sz, \"w:val\");\n if (halfPts !== undefined) opts.size = halfPts / 2;\n }\n\n const szCs = findChild(el, \"w:szCs\");\n if (szCs) {\n const halfPts = attrNum(szCs, \"w:val\");\n if (halfPts !== undefined) opts.sizeComplexScript = halfPts / 2;\n }\n\n const highlight = findChild(el, \"w:highlight\");\n if (highlight) {\n const val = attr(highlight, \"w:val\");\n if (val) opts.highlight = val;\n }\n\n const highlightCs = findChild(el, \"w:highlightCs\");\n if (highlightCs) {\n const val = attr(highlightCs, \"w:val\");\n if (val) opts.highlightComplexScript = val;\n }\n\n const vertAlign = findChild(el, \"w:vertAlign\");\n if (vertAlign) {\n const val = attr(vertAlign, \"w:val\");\n if (val === \"subscript\") opts.subScript = true;\n else if (val === \"superscript\") opts.superScript = true;\n }\n\n const effect = findChild(el, \"w:effect\");\n if (effect) {\n const val = attr(effect, \"w:val\");\n if (val) opts.effect = val;\n }\n\n const emphasisMark = findChild(el, \"w:em\");\n if (emphasisMark) {\n const val = attr(emphasisMark, \"w:val\");\n if (val) opts.emphasisMark = { type: val };\n }\n\n const spacing = findChild(el, \"w:spacing\");\n if (spacing) {\n const val = attrMeasure(spacing, \"w:val\");\n if (val !== undefined) opts.characterSpacing = val;\n }\n\n const scale = findChild(el, \"w:w\");\n if (scale) {\n const val = attrNum(scale, \"w:val\");\n if (val !== undefined) opts.scale = val;\n }\n\n const kern = findChild(el, \"w:kern\");\n if (kern) {\n // w:kern is ST_HpsMeasure in half-points; convert to points (÷2).\n const kernHalfPts = attrNum(kern, \"w:val\");\n if (kernHalfPts !== undefined) opts.kern = kernHalfPts / 2;\n }\n\n const position = findChild(el, \"w:position\");\n if (position) {\n const val = attr(position, \"w:val\");\n if (val !== undefined) opts.position = val;\n }\n\n const fitText = findChild(el, \"w:fitText\");\n if (fitText) {\n const val = attrNum(fitText, \"w:val\");\n if (val !== undefined) opts.fitText = val;\n }\n\n const lang = findChild(el, \"w:lang\");\n if (lang) {\n const langObj: LanguageOptions = {};\n const val = attr(lang, \"w:val\");\n if (val) langObj.value = val;\n const eastAsia = attr(lang, \"w:eastAsia\");\n if (eastAsia) langObj.eastAsia = eastAsia;\n const bidi = attr(lang, \"w:bidi\");\n if (bidi) langObj.bidirectional = bidi;\n if (Object.keys(langObj).length > 0) opts.language = langObj;\n }\n\n // Border (w:bdr)\n const bdr = findChild(el, \"w:bdr\");\n if (bdr) {\n opts.border = parseBorder(bdr);\n }\n\n // Shading (w:shd)\n const shd = findChild(el, \"w:shd\");\n if (shd) {\n opts.shading = parseShading(shd);\n }\n\n // East Asian layout (w:eastAsianLayout)\n const eastAsianLayout = findChild(el, \"w:eastAsianLayout\");\n if (eastAsianLayout) {\n opts.eastAsianLayout = parseEastAsianLayout(eastAsianLayout);\n }\n\n // Content part (w:contentPart)\n const contentPart = findChild(el, \"w:contentPart\");\n if (contentPart) {\n const rId = attr(contentPart, \"r:id\");\n if (rId) opts.contentPartRId = rId;\n }\n\n // Revision (w:rPrChange)\n const rPrChange = findChild(el, \"w:rPrChange\");\n if (rPrChange) {\n const rev: Record<string, unknown> = {};\n const author = attr(rPrChange, \"w:author\");\n if (author) rev.author = author;\n const date = attr(rPrChange, \"w:date\");\n if (date) rev.date = date;\n const id = attrNum(rPrChange, \"w:id\");\n if (id !== undefined) rev.id = id;\n const innerRPr = findChild(rPrChange, \"w:rPr\");\n if (innerRPr) {\n Object.assign(rev, parseRunProperties(innerRPr));\n }\n if (Object.keys(rev).length > 0) opts.revision = rev;\n }\n\n // w14:* text effects (glow/shadow/reflection/props3d) occupy the EG_RPrBase\n // extension slot at the end of rPr. Low-frequency complex subtrees — kept\n // verbatim as raw XML for fidelity while the rPr backbone stays editable.\n const w14Parts: string[] = [];\n for (const child of el.elements ?? []) {\n if (child.name?.startsWith(\"w14:\")) w14Parts.push(stringifyElement(child));\n }\n if (w14Parts.length > 0) opts.w14RawXml = w14Parts.join(\"\");\n\n return opts as RunPropertiesOptions;\n}\n\n/**\n * Parse a w:bdr element into BorderOptions.\n */\nexport function parseBorder(el: Element): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n const style = attr(el, \"w:val\");\n if (style) opts.style = style;\n const color = colorAttr(el, \"w:color\");\n if (color) opts.color = color;\n const size = attrNum(el, \"w:sz\");\n if (size !== undefined) opts.size = size;\n const space = attrNum(el, \"w:space\");\n if (space !== undefined) opts.space = space;\n const shadow = attrBool(el, \"w:shadow\");\n if (shadow !== undefined) opts.shadow = shadow;\n const frame = attrBool(el, \"w:frame\");\n if (frame !== undefined) opts.frame = frame;\n return opts;\n}\n\n/**\n * Parse a w:eastAsianLayout element into EastAsianLayoutOptions.\n */\nexport function parseEastAsianLayout(el: Element): Record<string, unknown> {\n const opts: Record<string, unknown> = {};\n const id = attrNum(el, \"w:id\");\n if (id !== undefined) opts.id = id;\n const combine = attrBool(el, \"w:combine\");\n if (combine !== undefined) opts.combine = combine;\n const combineBrackets = attr(el, \"w:combineBrackets\");\n if (combineBrackets) opts.combineBrackets = combineBrackets;\n const vert = attrBool(el, \"w:vert\");\n if (vert !== undefined) opts.vertical = vert;\n const vertCompress = attrBool(el, \"w:vertCompress\");\n if (vertCompress !== undefined) opts.verticalCompress = vertCompress;\n return opts;\n}\n\n// ── Special run child constants ──────────────────────────────────────────────\n\n/** Matches w:br[@w:type=\"page\"] → PageBreak */\nexport const PARSED_PAGE_BREAK = Symbol(\"PageBreak\");\n/** Matches w:br (line break) */\nexport const PARSED_LINE_BREAK = Symbol(\"LineBreak\");\n/** Matches w:tab */\nexport const PARSED_TAB = Symbol(\"Tab\");\n/** Matches w:cr */\nexport const PARSED_CARRIAGE_RETURN = Symbol(\"CarriageReturn\");\n/** Matches w:noBreakHyphen */\nexport const PARSED_NO_BREAK_HYPHEN = Symbol(\"NoBreakHyphen\");\n/** Matches w:softHyphen */\nexport const PARSED_SOFT_HYPHEN = Symbol(\"SoftHyphen\");\n/** Matches w:footnoteRef — auto-generated by Footnote class */\nexport const PARSED_FOOTNOTE_REF = Symbol(\"FootnoteRef\");\n/** Matches w:br[@w:type=\"column\"] */\nexport const PARSED_COLUMN_BREAK = Symbol(\"ColumnBreak\");\n/** Matches w:dayShort */\nexport const PARSED_DAY_SHORT = Symbol(\"DayShort\");\n/** Matches w:monthShort */\nexport const PARSED_MONTH_SHORT = Symbol(\"MonthShort\");\n/** Matches w:yearShort */\nexport const PARSED_YEAR_SHORT = Symbol(\"YearShort\");\n/** Matches w:dayLong */\nexport const PARSED_DAY_LONG = Symbol(\"DayLong\");\n/** Matches w:monthLong */\nexport const PARSED_MONTH_LONG = Symbol(\"MonthLong\");\n/** Matches w:yearLong */\nexport const PARSED_YEAR_LONG = Symbol(\"YearLong\");\n/** Matches w:annotationRef */\nexport const PARSED_ANNOTATION_REF = Symbol(\"AnnotationRef\");\n/** Matches w:separator */\nexport const PARSED_SEPARATOR = Symbol(\"Separator\");\n/** Matches w:continuationSeparator */\nexport const PARSED_CONTINUATION_SEPARATOR = Symbol(\"ContinuationSeparator\");\n/** Matches w:pgNum */\nexport const PARSED_PAGE_NUMBER = Symbol(\"PageNumber\");\n/** Matches w:lastRenderedPageBreak */\nexport const PARSED_LAST_RENDERED_PAGE_BREAK = Symbol(\"LastRenderedPageBreak\");\n\nexport type ParsedRunChild =\n | string\n | typeof PARSED_PAGE_BREAK\n | typeof PARSED_LINE_BREAK\n | typeof PARSED_TAB\n | typeof PARSED_CARRIAGE_RETURN\n | typeof PARSED_NO_BREAK_HYPHEN\n | typeof PARSED_SOFT_HYPHEN\n | typeof PARSED_FOOTNOTE_REF\n | typeof PARSED_COLUMN_BREAK\n | typeof PARSED_DAY_SHORT\n | typeof PARSED_MONTH_SHORT\n | typeof PARSED_YEAR_SHORT\n | typeof PARSED_DAY_LONG\n | typeof PARSED_MONTH_LONG\n | typeof PARSED_YEAR_LONG\n | typeof PARSED_ANNOTATION_REF\n | typeof PARSED_SEPARATOR\n | typeof PARSED_CONTINUATION_SEPARATOR\n | typeof PARSED_PAGE_NUMBER\n | typeof PARSED_LAST_RENDERED_PAGE_BREAK\n | { commentReference: number }\n | { object: ObjectElementOptions }\n | { break: number | BreakOptions }\n | { footnoteReference: number | FootnoteEndnoteReferenceOptions }\n | { endnoteReference: number | FootnoteEndnoteReferenceOptions };\n\n/**\n * Parse a w:r element into run data.\n * Returns { properties, children } where children are parsed run content items.\n */\nexport function parseRun(\n el: Element,\n _ctx: DocxReadContext,\n): {\n properties: RunPropertiesOptions | undefined;\n children: ParsedRunChild[];\n rsid?: string;\n runPropertiesRsid?: string;\n deletionRsid?: string;\n} {\n const rPr = findChild(el, \"w:rPr\");\n const properties = rPr ? parseRunProperties(rPr) : undefined;\n const children: ParsedRunChild[] = [];\n const rsid = attr(el, \"w:rsidR\");\n const runPropertiesRsid = attr(el, \"w:rsidRPr\");\n const deletionRsid = attr(el, \"w:rsidDel\");\n\n for (const child of el.elements ?? []) {\n switch (child.name) {\n case \"w:rPr\":\n // already handled above\n break;\n case \"w:t\": {\n const preserveSpace = attrBool(child, \"xml:space\");\n let text = textOf(child);\n if (preserveSpace && text) {\n // keep leading/trailing whitespace\n // textOf already returns the raw text\n }\n children.push(text);\n break;\n }\n case \"w:delText\": {\n // Deleted text in track changes (same format as w:t)\n const text = textOf(child);\n if (text) children.push(text);\n break;\n }\n case \"w:br\": {\n const brType = attr(child, \"w:type\");\n const brClear = attr(child, \"w:clear\");\n if (brType === \"page\") {\n children.push(PARSED_PAGE_BREAK);\n } else if (brType === \"column\") {\n children.push(PARSED_COLUMN_BREAK);\n } else if (brClear) {\n // Line break clearing floating content (w:br/@w:clear) — preserve clear\n children.push({\n break: { count: 1, clear: brClear as BreakClear },\n } as unknown as ParsedRunChild);\n } else {\n children.push(PARSED_LINE_BREAK);\n }\n break;\n }\n case \"w:tab\":\n children.push(PARSED_TAB);\n break;\n case \"w:cr\":\n children.push(PARSED_CARRIAGE_RETURN);\n break;\n case \"w:noBreakHyphen\":\n children.push(PARSED_NO_BREAK_HYPHEN);\n break;\n case \"w:softHyphen\":\n children.push(PARSED_SOFT_HYPHEN);\n break;\n case \"w:commentReference\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) children.push({ commentReference: id });\n break;\n }\n // Drawing/pict are handled at the paragraph level (parseSectionChild in body.ts)\n // where the drawing is extracted and replaced as a paragraph child.\n case \"w:drawing\":\n case \"w:pict\":\n break;\n case \"w:object\": {\n children.push({ object: objectDesc.parse(child, _ctx) } as unknown as ParsedRunChild);\n break;\n }\n // Symbol run — extract char and font attributes\n case \"w:sym\": {\n const charVal = attr(child, \"w:char\");\n const fontVal = attr(child, \"w:font\");\n if (charVal) {\n children.push({\n symbolRun: { char: charVal, symbolFont: fontVal ?? \"Wingdings\" },\n } as unknown as ParsedRunChild);\n }\n break;\n }\n // Footnote/endnote reference — preserve as { footnoteReference: id } / { endnoteReference: id }\n case \"w:footnoteReference\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) {\n const customMarkFollows = attrBool(child, \"w:customMarkFollows\") === true;\n children.push(\n customMarkFollows\n ? ({\n footnoteReference: { id, customMarkFollows: true },\n } as unknown as ParsedRunChild)\n : ({ footnoteReference: id } as unknown as ParsedRunChild),\n );\n }\n break;\n }\n case \"w:endnoteReference\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) {\n const customMarkFollows = attrBool(child, \"w:customMarkFollows\") === true;\n children.push(\n customMarkFollows\n ? ({ endnoteReference: { id, customMarkFollows: true } } as unknown as ParsedRunChild)\n : ({ endnoteReference: id } as unknown as ParsedRunChild),\n );\n }\n break;\n }\n // Footnote/endnote ref mark inside footnote/endnote content —\n // auto-generated by Footnote/Endnote class, skip to avoid duplication.\n case \"w:footnoteRef\":\n case \"w:endnoteRef\":\n children.push(PARSED_FOOTNOTE_REF);\n break;\n // Date/time field elements\n case \"w:dayShort\":\n children.push(PARSED_DAY_SHORT);\n break;\n case \"w:monthShort\":\n children.push(PARSED_MONTH_SHORT);\n break;\n case \"w:yearShort\":\n children.push(PARSED_YEAR_SHORT);\n break;\n case \"w:dayLong\":\n children.push(PARSED_DAY_LONG);\n break;\n case \"w:monthLong\":\n children.push(PARSED_MONTH_LONG);\n break;\n case \"w:yearLong\":\n children.push(PARSED_YEAR_LONG);\n break;\n // Other empty run elements\n case \"w:annotationRef\":\n children.push(PARSED_ANNOTATION_REF);\n break;\n case \"w:separator\":\n children.push(PARSED_SEPARATOR);\n break;\n case \"w:continuationSeparator\":\n children.push(PARSED_CONTINUATION_SEPARATOR);\n break;\n case \"w:pgNum\":\n children.push(PARSED_PAGE_NUMBER);\n break;\n case \"w:lastRenderedPageBreak\":\n children.push(PARSED_LAST_RENDERED_PAGE_BREAK);\n break;\n default:\n break;\n }\n }\n\n return { properties, children, rsid, runPropertiesRsid, deletionRsid };\n}\n\n/**\n * Convert parsed run data into an RunOptions suitable for the Document constructor.\n * Simplifies the parsed children into text + break format.\n * If the run contains only a commentReference, returns { commentReference: id } instead.\n * If the run only contains footnoteRef/endnoteRef (auto-generated), returns empty options.\n *\n * When empty run elements (tab, noBreakHyphen, date fields, etc.) are present,\n * uses children[] format to preserve them for round-trip fidelity.\n */\n\n/** Mapping from parse symbols to RunOptions child objects for empty elements. */\nconst SYMBOL_TO_CHILD = new Map<symbol, Record<string, true>>([\n [PARSED_TAB, { tab: true }],\n [PARSED_CARRIAGE_RETURN, { carriageReturn: true }],\n [PARSED_NO_BREAK_HYPHEN, { noBreakHyphen: true }],\n [PARSED_SOFT_HYPHEN, { softHyphen: true }],\n [PARSED_DAY_SHORT, { dayShort: true }],\n [PARSED_MONTH_SHORT, { monthShort: true }],\n [PARSED_YEAR_SHORT, { yearShort: true }],\n [PARSED_DAY_LONG, { dayLong: true }],\n [PARSED_MONTH_LONG, { monthLong: true }],\n [PARSED_YEAR_LONG, { yearLong: true }],\n [PARSED_ANNOTATION_REF, { annotationRef: true }],\n [PARSED_SEPARATOR, { separator: true }],\n [PARSED_CONTINUATION_SEPARATOR, { continuationSeparator: true }],\n [PARSED_PAGE_NUMBER, { pgNum: true }],\n [PARSED_LAST_RENDERED_PAGE_BREAK, { lastRenderedPageBreak: true }],\n]);\n\nexport function parsedRunToOptions(\n parsed: ReturnType<typeof parseRun>,\n): RunOptions | { commentReference: number } | null {\n // Filter out footnoteRef/endnoteRef symbols (auto-generated by Footnote/Endnote class)\n const contentChildren = parsed.children.filter((c) => c !== PARSED_FOOTNOTE_REF);\n const isOnlyFootnoteRef =\n contentChildren.length === 0 && parsed.children.some((c) => c === PARSED_FOOTNOTE_REF);\n\n // If the run only contained footnoteRef/endnoteRef (no text, no other content),\n // skip it entirely — the Footnote/Endnote class auto-adds FootnoteRefRun.\n if (isOnlyFootnoteRef) {\n return null;\n }\n\n const opts: Record<string, unknown> = { ...parsed.properties };\n if (parsed.rsid) opts.rsid = parsed.rsid;\n if (parsed.runPropertiesRsid) opts.runPropertiesRsid = parsed.runPropertiesRsid;\n if (parsed.deletionRsid) opts.deletionRsid = parsed.deletionRsid;\n\n // Check if this run is a pure reference run (commentReference, footnoteReference, endnoteReference)\n const isRefChild = (c: unknown): c is Record<string, number> =>\n typeof c === \"object\" &&\n c !== null &&\n (\"commentReference\" in c || \"footnoteReference\" in c || \"endnoteReference\" in c);\n\n const refChildren = contentChildren.filter(isRefChild);\n const nonRefChildren = contentChildren.filter((c) => !isRefChild(c));\n\n // If the run is a pure reference run (no text), return it directly.\n // Drop auto-generated rStyle (e.g., \"FootnoteReference\") since it's implicit.\n if (refChildren.length > 0 && nonRefChildren.length === 0) {\n return refChildren[0] as RunOptions | { commentReference: number };\n }\n\n // If the run only contains a symbolRun, return it directly\n const symbolIdx = nonRefChildren.findIndex(\n (c) => typeof c === \"object\" && c !== null && \"symbolRun\" in c,\n );\n if (symbolIdx >= 0 && nonRefChildren.length === 1 && !parsed.properties) {\n return nonRefChildren[symbolIdx] as unknown as RunOptions;\n }\n\n // If the run contains an OLE object (w:object), return it directly with any\n // run properties — an OLE object occupies its own run.\n const objectIdx = nonRefChildren.findIndex(\n (c) => typeof c === \"object\" && c !== null && \"object\" in c,\n );\n if (objectIdx >= 0) {\n const objectChild = nonRefChildren[objectIdx] as { object: ObjectElementOptions };\n return { ...parsed.properties, ...objectChild } as unknown as RunOptions;\n }\n\n // Collect text and breaks\n const textParts: string[] = [];\n let breakCount = 0;\n const structuredBreaks: BreakOptions[] = [];\n let hasPageBreak = false;\n let hasColumnBreak = false;\n const extraChildren: Record<string, true>[] = [];\n\n for (const child of nonRefChildren) {\n if (typeof child === \"string\") {\n textParts.push(child);\n } else if (child === PARSED_LINE_BREAK) {\n breakCount++;\n } else if (child === PARSED_PAGE_BREAK) {\n hasPageBreak = true;\n } else if (child === PARSED_COLUMN_BREAK) {\n hasColumnBreak = true;\n } else if (typeof child === \"object\" && child !== null && \"break\" in child) {\n // Line break carrying a clear attribute (w:br/@w:clear) — preserve structure\n structuredBreaks.push((child as { break: BreakOptions }).break);\n } else {\n // Empty run elements (tab, noBreakHyphen, date fields, etc.)\n const mapped = SYMBOL_TO_CHILD.get(child as symbol);\n if (mapped) extraChildren.push(mapped);\n }\n }\n\n // A single structured break (with clear) coexists cleanly with text/page/column\n // breaks via opts.break; mixed or multiple breaks fall back to children[] form.\n const hasStructuredBreaks = structuredBreaks.length > 0;\n const useChildrenForm =\n extraChildren.length > 0 ||\n (hasStructuredBreaks &&\n (breakCount > 0 || structuredBreaks.length > 1 || hasPageBreak || hasColumnBreak));\n\n if (useChildrenForm) {\n const children: (string | Record<string, unknown>)[] = [];\n for (const child of nonRefChildren) {\n if (typeof child === \"string\") {\n children.push(child);\n } else if (child === PARSED_LINE_BREAK) {\n children.push({ break: 1 });\n } else if (child === PARSED_PAGE_BREAK) {\n children.push({ pageBreak: true });\n } else if (child === PARSED_COLUMN_BREAK) {\n children.push({ columnBreak: true });\n } else if (typeof child === \"object\" && child !== null && \"break\" in child) {\n children.push({ break: (child as { break: BreakOptions }).break });\n } else {\n const mapped = SYMBOL_TO_CHILD.get(child as symbol);\n if (mapped) children.push(mapped);\n }\n }\n opts.children = children;\n } else {\n if (textParts.length > 0) {\n opts.text = textParts.join(\"\");\n }\n if (breakCount > 0) {\n opts.break = breakCount;\n } else if (hasStructuredBreaks) {\n opts.break = structuredBreaks[0];\n }\n if (hasPageBreak) {\n opts.pageBreak = true;\n }\n if (hasColumnBreak) {\n opts.columnBreak = true;\n }\n }\n\n // If the run has no content and no properties (e.g., a pure drawing run),\n // return null so it can be skipped by the caller.\n if (\n Object.keys(opts).length === 0 &&\n textParts.length === 0 &&\n breakCount === 0 &&\n !hasPageBreak &&\n !hasColumnBreak &&\n extraChildren.length === 0\n ) {\n return null;\n }\n\n return opts as RunOptions;\n}\n","/**\n * Direct XML string builders for paragraph and run properties.\n *\n * Replaces `buildParagraphProperties() + xml()` and `buildRunProperties() + xml()`\n * with direct string concatenation — no intermediate object-tree allocation,\n * no recursive xml() traversal. Follows PPTX/XLSX pattern.\n *\n * @module\n */\n\nimport {\n convertToTwip,\n decimalNumber,\n eighthPointMeasureValue,\n hexColorValue,\n hpsMeasureValue,\n pointMeasureValue,\n uCharHexNumber,\n} from \"@office-open/core\";\nimport { attrsRaw, escapeXml } from \"@office-open/xml\";\nimport type { CnfConditionalOptions } from \"@parts/paragraph/formatting/cnf-style\";\nimport type { IndentProperties } from \"@parts/paragraph/formatting/indent\";\nimport type { SpacingProperties } from \"@parts/paragraph/formatting/spacing\";\nimport type { TabStopDefinition } from \"@parts/paragraph/formatting/tab-stop\";\nimport type { FrameOptions } from \"@parts/paragraph/frame/frame-properties\";\nimport type { ParagraphPropertiesOptions } from \"@parts/paragraph/properties\";\nimport type { EastAsianLayoutOptions } from \"@parts/paragraph/run/east-asian-layout\";\nimport type { ColorOptions } from \"@parts/paragraph/run/formatting\";\nimport type { LanguageOptions } from \"@parts/paragraph/run/language\";\nimport type {\n ParagraphRunPropertiesOptions,\n RunPropertiesChangeOptions,\n RunPropertiesOptions,\n} from \"@parts/paragraph/run/properties\";\nimport type { FontProperties } from \"@parts/paragraph/run/run-fonts\";\nimport type { BorderOptions } from \"@shared/border\";\nimport { BorderStyle } from \"@shared/border\";\nimport type { ShadingProperties } from \"@shared/shading\";\n\n// ── Inline helpers ──\n\n/** On/off: `<w:name/>` for true, `<w:name w:val=\"0\"/>` for false */\nexport function onOff(name: string, val: boolean): string {\n return val ? `<${name}/>` : `<${name} w:val=\"0\"/>`;\n}\n\n// ── Border ──\n\nexport function borderStr(name: string, opts: BorderOptions): string {\n const a = attrsRaw({\n \"w:val\": opts.style,\n \"w:color\": opts.color !== undefined ? hexColorValue(opts.color) : undefined,\n \"w:sz\": opts.size !== undefined ? eighthPointMeasureValue(opts.size) : undefined,\n \"w:space\": opts.space !== undefined ? pointMeasureValue(opts.space) : undefined,\n \"w:themeColor\": opts.themeColor,\n \"w:themeTint\": opts.themeTint !== undefined ? uCharHexNumber(opts.themeTint) : undefined,\n \"w:themeShade\": opts.themeShade !== undefined ? uCharHexNumber(opts.themeShade) : undefined,\n \"w:shadow\": opts.shadow !== undefined ? (opts.shadow ? 1 : 0) : undefined,\n \"w:frame\": opts.frame !== undefined ? (opts.frame ? 1 : 0) : undefined,\n });\n return `<${name}${a}/>`;\n}\n\n// ── Shading ──\n\nexport function shadingStr(opts: ShadingProperties): string {\n const a = attrsRaw({\n \"w:val\": opts.type ?? \"clear\",\n \"w:color\": opts.color !== undefined ? hexColorValue(opts.color) : undefined,\n \"w:fill\": opts.fill !== undefined ? hexColorValue(opts.fill) : undefined,\n \"w:themeColor\": opts.themeColor,\n \"w:themeTint\": opts.themeTint !== undefined ? uCharHexNumber(opts.themeTint) : undefined,\n \"w:themeShade\": opts.themeShade !== undefined ? uCharHexNumber(opts.themeShade) : undefined,\n \"w:themeFill\": opts.themeFill,\n \"w:themeFillTint\":\n opts.themeFillTint !== undefined ? uCharHexNumber(opts.themeFillTint) : undefined,\n \"w:themeFillShade\":\n opts.themeFillShade !== undefined ? uCharHexNumber(opts.themeFillShade) : undefined,\n });\n return `<w:shd${a}/>`;\n}\n\n// ── Spacing ──\n\nfunction spacingStr(opts: SpacingProperties): string {\n const a = attrsRaw({\n \"w:after\": opts.after !== undefined ? convertToTwip(opts.after) : undefined,\n \"w:afterAutospacing\":\n opts.afterAutoSpacing !== undefined ? (opts.afterAutoSpacing ? 1 : 0) : undefined,\n \"w:afterLines\": opts.afterLines !== undefined ? decimalNumber(opts.afterLines) : undefined,\n \"w:before\": opts.before !== undefined ? convertToTwip(opts.before) : undefined,\n \"w:beforeAutospacing\":\n opts.beforeAutoSpacing !== undefined ? (opts.beforeAutoSpacing ? 1 : 0) : undefined,\n \"w:beforeLines\": opts.beforeLines !== undefined ? decimalNumber(opts.beforeLines) : undefined,\n \"w:line\": opts.line !== undefined ? convertToTwip(opts.line) : undefined,\n \"w:lineRule\": opts.lineRule,\n });\n return `<w:spacing${a}/>`;\n}\n\n// ── Indent ──\n\nfunction indentStr(opts: IndentProperties): string {\n const a = attrsRaw({\n \"w:start\": opts.start !== undefined ? convertToTwip(opts.start) : undefined,\n \"w:startChars\": opts.startChars !== undefined ? decimalNumber(opts.startChars) : undefined,\n \"w:end\": opts.end !== undefined ? convertToTwip(opts.end) : undefined,\n \"w:endChars\": opts.endChars !== undefined ? decimalNumber(opts.endChars) : undefined,\n \"w:left\": opts.left !== undefined ? convertToTwip(opts.left) : undefined,\n \"w:leftChars\": opts.leftChars !== undefined ? decimalNumber(opts.leftChars) : undefined,\n \"w:right\": opts.right !== undefined ? convertToTwip(opts.right) : undefined,\n \"w:rightChars\": opts.rightChars !== undefined ? decimalNumber(opts.rightChars) : undefined,\n \"w:hanging\": opts.hanging !== undefined ? convertToTwip(opts.hanging) : undefined,\n \"w:hangingChars\":\n opts.hangingChars !== undefined ? decimalNumber(opts.hangingChars) : undefined,\n \"w:firstLine\": opts.firstLine !== undefined ? convertToTwip(opts.firstLine) : undefined,\n \"w:firstLineChars\":\n opts.firstLineChars !== undefined ? decimalNumber(opts.firstLineChars) : undefined,\n });\n return `<w:ind${a}/>`;\n}\n\n// ── Tab stops ──\n\nfunction tabStopsStr(defs: TabStopDefinition[]): string {\n const items = defs.map(({ type, position, leader }) => {\n const a = attrsRaw({\n \"w:val\": type,\n \"w:pos\": convertToTwip(position),\n \"w:leader\": leader,\n });\n return `<w:tab${a}/>`;\n });\n return `<w:tabs>${items.join(\"\")}</w:tabs>`;\n}\n\n// ── CNF style ──\n\nfunction cnfStyleStr(opts: CnfConditionalOptions): string {\n const a = attrsRaw({\n \"w:firstRow\": opts.firstRow ? \"1\" : \"0\",\n \"w:lastRow\": opts.lastRow ? \"1\" : \"0\",\n \"w:firstColumn\": opts.firstColumn ? \"1\" : \"0\",\n \"w:lastColumn\": opts.lastColumn ? \"1\" : \"0\",\n \"w:oddVBand\": opts.oddVBand ? \"1\" : \"0\",\n \"w:evenVBand\": opts.evenVBand ? \"1\" : \"0\",\n \"w:oddHBand\": opts.oddHBand ? \"1\" : \"0\",\n \"w:evenHBand\": opts.evenHBand ? \"1\" : \"0\",\n \"w:firstRowFirstColumn\": opts.firstRowFirstColumn ? \"1\" : \"0\",\n \"w:firstRowLastColumn\": opts.firstRowLastColumn ? \"1\" : \"0\",\n \"w:lastRowFirstColumn\": opts.lastRowFirstColumn ? \"1\" : \"0\",\n \"w:lastRowLastColumn\": opts.lastRowLastColumn ? \"1\" : \"0\",\n });\n return `<w:cnfStyle${a}/>`;\n}\n\n// ── Frame properties ──\n\nfunction framePrStr(opts: FrameOptions): string {\n const alignment = (opts as { alignment?: { x?: string; y?: string } }).alignment;\n const position = (opts as { position?: { x?: number; y?: number } }).position;\n const a = attrsRaw({\n \"w:xAlign\": alignment?.x,\n \"w:yAlign\": alignment?.y,\n \"w:hAnchor\": opts.anchor?.horizontal,\n \"w:anchorLock\": opts.anchorLock,\n \"w:vAnchor\": opts.anchor?.vertical,\n \"w:dropCap\": opts.dropCap,\n \"w:h\": opts.height,\n \"w:lines\": opts.lines,\n \"w:hRule\": opts.rule,\n \"w:hSpace\": opts.space?.horizontal,\n \"w:vSpace\": opts.space?.vertical,\n \"w:w\": opts.width,\n \"w:wrap\": opts.wrap,\n \"w:x\": position?.x,\n \"w:y\": position?.y,\n });\n return `<w:framePr${a}/>`;\n}\n\n// ── Number properties ──\n\nfunction numPrStr(\n numberId: number | string,\n indentLevel: number,\n numberingChange?: { original: string; id: string; author: string; date?: string },\n): string {\n const idVal = typeof numberId === \"string\" ? `{${numberId}}` : numberId;\n const parts = [`<w:ilvl w:val=\"${Math.min(indentLevel, 9)}\"/>`, `<w:numId w:val=\"${idVal}\"/>`];\n if (numberingChange) {\n const a = attrsRaw({\n \"w:original\": numberingChange.original,\n \"w:id\": numberingChange.id,\n \"w:author\": numberingChange.author,\n \"w:date\": numberingChange.date,\n });\n parts.push(`<w:numberingChange${a}/>`);\n }\n return `<w:numPr>${parts.join(\"\")}</w:numPr>`;\n}\n\n// ── Run-level formatting helpers ──\n\nfunction colorStr(colorOrOptions: string | ColorOptions): string {\n if (typeof colorOrOptions === \"string\") {\n return `<w:color w:val=\"${hexColorValue(colorOrOptions)}\"/>`;\n }\n const opts = colorOrOptions;\n const a = attrsRaw({\n \"w:val\": opts.val !== undefined ? hexColorValue(opts.val) : undefined,\n \"w:themeColor\": opts.themeColor,\n \"w:themeTint\": opts.themeTint !== undefined ? uCharHexNumber(opts.themeTint) : undefined,\n \"w:themeShade\": opts.themeShade !== undefined ? uCharHexNumber(opts.themeShade) : undefined,\n });\n return `<w:color${a}/>`;\n}\n\nfunction runFontsStr(nameOrAttrs: string | FontProperties, hint?: string): string {\n if (typeof nameOrAttrs === \"string\") {\n const a = attrsRaw({\n \"w:ascii\": nameOrAttrs,\n \"w:cs\": nameOrAttrs,\n \"w:eastAsia\": nameOrAttrs,\n \"w:hAnsi\": nameOrAttrs,\n \"w:hint\": hint,\n });\n return `<w:rFonts${a}/>`;\n }\n const attrs = nameOrAttrs;\n const a = attrsRaw({\n \"w:ascii\": attrs.ascii,\n \"w:asciiTheme\": attrs.asciiTheme,\n \"w:cs\": attrs.complexScript,\n \"w:cstheme\": attrs.complexScriptTheme,\n \"w:eastAsia\": attrs.eastAsia,\n \"w:eastAsiaTheme\": attrs.eastAsiaTheme,\n \"w:hAnsi\": attrs.hAnsi,\n \"w:hAnsiTheme\": attrs.hAnsiTheme,\n \"w:hint\": attrs.hint,\n });\n return `<w:rFonts${a}/>`;\n}\n\nfunction underlineStr(type: string | undefined, color?: string): string {\n // Scalar build — this runs for every underlined run, and the Record +\n // Object.entries round-trip of attrParts showed up in compile profiles.\n if (color === undefined) return `<w:u w:val=\"${type ?? \"single\"}\"/>`;\n return `<w:u w:val=\"${type ?? \"single\"}\" w:color=\"${hexColorValue(color)}\"/>`;\n}\n\nfunction eastAsianLayoutStr(opts: EastAsianLayoutOptions): string {\n const a = attrsRaw({\n \"w:id\": opts.id !== undefined ? decimalNumber(opts.id) : undefined,\n \"w:combine\": opts.combine !== undefined ? (opts.combine ? 1 : 0) : undefined,\n \"w:combineBrackets\": opts.combineBrackets,\n \"w:vert\": opts.vertical !== undefined ? (opts.vertical ? 1 : 0) : undefined,\n \"w:vertCompress\":\n opts.verticalCompress !== undefined ? (opts.verticalCompress ? 1 : 0) : undefined,\n });\n return `<w:eastAsianLayout${a}/>`;\n}\n\nfunction languageStr(opts: LanguageOptions): string {\n const a = attrsRaw({\n \"w:val\": opts.value,\n \"w:eastAsia\": opts.eastAsia,\n \"w:bidi\": opts.bidirectional,\n });\n return `<w:lang${a}/>`;\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// Paragraph Properties\n// ════════════════════════════════════════════════════════════════════════════\n\nexport interface StringifyPPrResult {\n xml: string | undefined;\n numberingReferences: { reference: string; instance: number }[];\n}\n\n/** Shared empty result — plain-text paragraphs produce no pPr and no numbering. */\nexport const EMPTY_PPR_RESULT: StringifyPPrResult = { xml: undefined, numberingReferences: [] };\n\n/**\n * Build `<w:pPr>` XML string directly from options — no intermediate object tree.\n *\n * Replaces `buildParagraphProperties() + xml()` with a single-pass string builder.\n */\nexport function stringifyParagraphProperties(\n options?: ParagraphPropertiesOptions,\n): StringifyPPrResult {\n if (!options) return EMPTY_PPR_RESULT;\n\n let numberingReferences: { reference: string; instance: number }[] | undefined;\n\n let s = \"\";\n\n // Style / heading / bullet / numbering style references\n if (options.heading) {\n s += `<w:pStyle w:val=\"${escapeXml(options.heading)}\"/>`;\n }\n\n if (options.bullet) {\n s += '<w:pStyle w:val=\"ListParagraph\"/>';\n }\n\n if (options.numbering) {\n if (!options.style && !options.heading) {\n if (!options.numbering.custom) {\n s += '<w:pStyle w:val=\"ListParagraph\"/>';\n }\n }\n }\n\n if (options.style) {\n s += `<w:pStyle w:val=\"${escapeXml(options.style)}\"/>`;\n }\n\n // CT_PPrBase element order per XSD (wml.xsd) — strictly ordered sequence.\n // 1-4: keepNext, keepLines, pageBreakBefore\n if (options.keepNext !== undefined) s += onOff(\"w:keepNext\", options.keepNext);\n if (options.keepLines !== undefined) s += onOff(\"w:keepLines\", options.keepLines);\n if (options.pageBreakBefore !== undefined)\n s += onOff(\"w:pageBreakBefore\", options.pageBreakBefore);\n\n // 5: framePr\n if (options.frame) s += framePrStr(options.frame);\n\n // 6: widowControl\n if (options.widowControl !== undefined) s += onOff(\"w:widowControl\", options.widowControl);\n\n // 7: numPr\n if (options.bullet) {\n s += `<w:numPr><w:ilvl w:val=\"${Math.min(options.bullet.level, 9)}\"/><w:numId w:val=\"1\"/></w:numPr>`;\n }\n\n if (options.numbering) {\n (numberingReferences ??= []).push({\n instance: options.numbering.instance ?? 0,\n reference: options.numbering.reference,\n });\n\n const numId = `${options.numbering.reference}-${options.numbering.instance ?? 0}`;\n s += numPrStr(numId, options.numbering.level, options.numbering.numberingChange);\n } else if (options.numbering === false) {\n s += numPrStr(0, 0);\n }\n\n // 8: suppressLineNumbers\n if (options.suppressLineNumbers !== undefined)\n s += onOff(\"w:suppressLineNumbers\", options.suppressLineNumbers);\n\n // 9: pBdr\n if (options.border) {\n const bParts: string[] = [];\n if (options.border.top) bParts.push(borderStr(\"w:top\", options.border.top));\n if (options.border.left) bParts.push(borderStr(\"w:left\", options.border.left));\n if (options.border.bottom) bParts.push(borderStr(\"w:bottom\", options.border.bottom));\n if (options.border.right) bParts.push(borderStr(\"w:right\", options.border.right));\n if (options.border.between) bParts.push(borderStr(\"w:between\", options.border.between));\n if (options.border.bar) bParts.push(borderStr(\"w:bar\", options.border.bar));\n if (bParts.length) s += `<w:pBdr>${bParts.join(\"\")}</w:pBdr>`;\n }\n\n if (options.thematicBreak) {\n s += `<w:pBdr>${borderStr(\"w:bottom\", { color: \"auto\", size: 6, space: 1, style: BorderStyle.SINGLE })}</w:pBdr>`;\n }\n\n // 10: shd\n if (options.shading) s += shadingStr(options.shading);\n\n // 11: tabs\n const tabDefs: TabStopDefinition[] = [\n ...(options.rightTabStop !== undefined\n ? [{ position: options.rightTabStop, type: \"right\" as const }]\n : []),\n ...(options.tabStops ? options.tabStops : []),\n ...(options.leftTabStop !== undefined\n ? [{ position: options.leftTabStop, type: \"left\" as const }]\n : []),\n ];\n if (tabDefs.length > 0) s += tabStopsStr(tabDefs);\n\n // 12-18: suppressAutoHyphens, kinsoku, wordWrap, overflowPunct, topLinePunct, autoSpaceDE, autoSpaceDN\n if (options.suppressAutoHyphens !== undefined)\n s += onOff(\"w:suppressAutoHyphens\", options.suppressAutoHyphens);\n if (options.kinsoku !== undefined) s += onOff(\"w:kinsoku\", options.kinsoku);\n if (options.wordWrap !== undefined) s += onOff(\"w:wordWrap\", options.wordWrap);\n if (options.overflowPunctuation !== undefined)\n s += onOff(\"w:overflowPunct\", options.overflowPunctuation);\n if (options.topLinePunct !== undefined) s += onOff(\"w:topLinePunct\", options.topLinePunct);\n if (options.autoSpaceDE !== undefined) s += onOff(\"w:autoSpaceDE\", options.autoSpaceDE);\n if (options.autoSpaceEastAsianText !== undefined)\n s += onOff(\"w:autoSpaceDN\", options.autoSpaceEastAsianText);\n\n // 19: bidi\n if (options.bidirectional !== undefined) s += onOff(\"w:bidi\", options.bidirectional);\n\n // 20-21: adjustRightInd, snapToGrid\n if (options.adjustRightInd !== undefined) s += onOff(\"w:adjustRightInd\", options.adjustRightInd);\n if (options.snapToGrid !== undefined) s += onOff(\"w:snapToGrid\", options.snapToGrid);\n\n // 22-24: spacing, ind, contextualSpacing\n if (options.spacing) s += spacingStr(options.spacing);\n if (options.indent) s += indentStr(options.indent);\n if (options.contextualSpacing !== undefined)\n s += onOff(\"w:contextualSpacing\", options.contextualSpacing);\n\n // 25-26: mirrorIndents, suppressOverlap\n if (options.mirrorIndents !== undefined) s += onOff(\"w:mirrorIndents\", options.mirrorIndents);\n if (options.suppressOverlap !== undefined)\n s += onOff(\"w:suppressOverlap\", options.suppressOverlap);\n\n // 27: jc\n if (options.alignment) s += `<w:jc w:val=\"${options.alignment}\"/>`;\n\n // 28-30: textDirection, textAlignment, textboxTightWrap\n if (options.textDirection !== undefined)\n s += `<w:textDirection w:val=\"${options.textDirection}\"/>`;\n if (options.textAlignment !== undefined)\n s += `<w:textAlignment w:val=\"${options.textAlignment}\"/>`;\n if (options.textboxTightWrap !== undefined)\n s += `<w:textboxTightWrap w:val=\"${options.textboxTightWrap}\"/>`;\n\n // 31-33: outlineLvl, divId, cnfStyle\n if (options.outlineLevel !== undefined) s += `<w:outlineLvl w:val=\"${options.outlineLevel}\"/>`;\n if (options.divId !== undefined) s += `<w:divId w:val=\"${options.divId}\"/>`;\n if (options.cnfStyle) s += cnfStyleStr(options.cnfStyle);\n\n // Embedded run properties (w:rPr inside w:pPr)\n if (options.run) {\n const inner = stringifyRunPropertiesInner(options.run);\n if (inner !== undefined) {\n const extra: string[] = [];\n const runOpts = options.run as ParagraphRunPropertiesOptions;\n if (runOpts.insertion) {\n const { id, author, date } = runOpts.insertion;\n extra.push(`<w:ins w:id=\"${id}\" w:author=\"${escapeXml(author)}\" w:date=\"${date}\"/>`);\n }\n if (runOpts.deletion) {\n const { id, author, date } = runOpts.deletion;\n extra.push(`<w:del w:id=\"${id}\" w:author=\"${escapeXml(author)}\" w:date=\"${date}\"/>`);\n }\n const body = inner + extra.join(\"\");\n s += `<w:rPr>${body}</w:rPr>`;\n }\n }\n\n // Revision (pPrChange)\n if (options.revision) {\n const rev = options.revision;\n const { author: _a, date: _d, id: _i, ...originalProps } = rev;\n const inner = stringifyParagraphProperties({ ...originalProps, includeIfEmpty: true });\n s += `<w:pPrChange w:author=\"${escapeXml(rev.author)}\" w:date=\"${rev.date}\" w:id=\"${rev.id}\">${inner.xml ?? \"<w:pPr/>\"}</w:pPrChange>`;\n }\n\n const body = s;\n const xml = options.includeIfEmpty || body.length > 0 ? `<w:pPr>${body}</w:pPr>` : undefined;\n if (numberingReferences === undefined) {\n return xml === undefined\n ? EMPTY_PPR_RESULT\n : { xml, numberingReferences: EMPTY_PPR_RESULT.numberingReferences };\n }\n return { xml, numberingReferences };\n}\n\n// ════════════════════════════════════════════════════════════════════════════\n// Run Properties\n// ════════════════════════════════════════════════════════════════════════════\n\n/**\n * Build the inner content of `<w:rPr>` as a string.\n * Returns undefined if no properties are set.\n */\nexport function stringifyRunPropertiesInner(opts?: RunPropertiesOptions): string | undefined {\n if (!opts) return undefined;\n\n let s = \"\";\n\n // Style\n if (opts.style) s += `<w:rStyle w:val=\"${escapeXml(opts.style)}\"/>`;\n\n // Font\n if (opts.font) {\n if (typeof opts.font === \"string\") {\n s += runFontsStr(opts.font);\n } else if (\"name\" in opts.font) {\n s += runFontsStr(opts.font.name, opts.font.hint);\n } else {\n s += runFontsStr(opts.font);\n }\n }\n\n // Bold — w:b and w:bCs are independent toggle properties (Latin vs complex\n // script, per ISO/IEC 29500). Emit each only when explicitly set so round-trip\n // is field-faithful (source <w:b/> stays <w:b/>, not inflated to <w:b/><w:bCs/>).\n if (opts.bold !== undefined) s += onOff(\"w:b\", opts.bold);\n if (opts.boldComplexScript !== undefined) s += onOff(\"w:bCs\", opts.boldComplexScript);\n\n // Italic — w:i and w:iCs are independent (same rationale as bold).\n if (opts.italic !== undefined) s += onOff(\"w:i\", opts.italic);\n if (opts.italicComplexScript !== undefined) s += onOff(\"w:iCs\", opts.italicComplexScript);\n\n // Caps\n if (opts.smallCaps !== undefined) {\n s += onOff(\"w:smallCaps\", opts.smallCaps);\n } else if (opts.allCaps !== undefined) {\n s += onOff(\"w:caps\", opts.allCaps);\n }\n\n // Strike\n if (opts.strike !== undefined) s += onOff(\"w:strike\", opts.strike);\n if (opts.doubleStrike !== undefined) s += onOff(\"w:dstrike\", opts.doubleStrike);\n if (opts.emboss !== undefined) s += onOff(\"w:emboss\", opts.emboss);\n if (opts.imprint !== undefined) s += onOff(\"w:imprint\", opts.imprint);\n if (opts.outline !== undefined) s += onOff(\"w:outline\", opts.outline);\n if (opts.shadow !== undefined) s += onOff(\"w:shadow\", opts.shadow);\n if (opts.webHidden !== undefined) s += onOff(\"w:webHidden\", opts.webHidden);\n if (opts.noProof !== undefined) s += onOff(\"w:noProof\", opts.noProof);\n if (opts.snapToGrid !== undefined) s += onOff(\"w:snapToGrid\", opts.snapToGrid);\n if (opts.vanish) s += onOff(\"w:vanish\", opts.vanish);\n\n // Color\n if (opts.color) s += colorStr(opts.color);\n\n // Character spacing\n if (opts.characterSpacing) {\n s += `<w:spacing w:val=\"${convertToTwip(opts.characterSpacing)}\"/>`;\n }\n\n // Scale\n if (opts.scale !== undefined) s += `<w:w w:val=\"${opts.scale}\"/>`;\n\n // Kern — w:val=\"0\" is meaningful (explicitly disables kerning), so emit\n // whenever the field is set rather than truthy-checking it.\n if (opts.kern !== undefined) s += `<w:kern w:val=\"${hpsMeasureValue(opts.kern * 2)}\"/>`;\n\n // Position\n if (opts.position) s += `<w:position w:val=\"${opts.position}\"/>`;\n\n // Size (points → half-points). sz and szCs are independent (Latin vs complex\n // script); emit each only when set so round-trip is field-faithful.\n if (opts.size !== undefined) s += `<w:sz w:val=\"${hpsMeasureValue(opts.size * 2)}\"/>`;\n if (opts.sizeComplexScript !== undefined) {\n s += `<w:szCs w:val=\"${hpsMeasureValue(opts.sizeComplexScript * 2)}\"/>`;\n }\n\n // Highlight — independent Latin vs complex-script values.\n if (opts.highlight) s += `<w:highlight w:val=\"${opts.highlight}\"/>`;\n if (opts.highlightComplexScript !== undefined) {\n s += `<w:highlightCs w:val=\"${opts.highlightComplexScript}\"/>`;\n }\n\n // Underline\n if (opts.underline) s += underlineStr(opts.underline.type, opts.underline.color);\n\n // Effect\n if (opts.effect) s += `<w:effect w:val=\"${opts.effect}\"/>`;\n\n // Border\n if (opts.border) s += borderStr(\"w:bdr\", opts.border);\n\n // Shading\n if (opts.shading) s += shadingStr(opts.shading);\n\n // Vertical alignment\n if (opts.subScript) s += '<w:vertAlign w:val=\"subscript\"/>';\n if (opts.superScript) s += '<w:vertAlign w:val=\"superscript\"/>';\n\n // RTL\n if (opts.rightToLeft !== undefined) s += onOff(\"w:rtl\", opts.rightToLeft);\n\n // Emphasis mark\n if (opts.emphasisMark) s += `<w:em w:val=\"${opts.emphasisMark.type ?? \"dot\"}\"/>`;\n\n // Language\n if (opts.language) s += languageStr(opts.language);\n\n // Spec vanish\n if (opts.specVanish) s += \"<w:specVanish/>\";\n\n // Math\n if (opts.math) s += onOff(\"w:oMath\", opts.math);\n\n // Fit text\n if (opts.fitText !== undefined) s += `<w:fitText w:val=\"${opts.fitText}\"/>`;\n\n // Complex script\n if (opts.complexScript !== undefined) s += onOff(\"w:cs\", opts.complexScript);\n\n // East Asian layout\n if (opts.eastAsianLayout) s += eastAsianLayoutStr(opts.eastAsianLayout);\n\n // Content part\n if (opts.contentPartRId) s += `<w:contentPart r:id=\"${opts.contentPartRId}\"/>`;\n\n // Revision (rPrChange)\n if (opts.revision) {\n const rev = opts.revision as RunPropertiesChangeOptions;\n const { author: _a, date: _d, id: _i, ...originalProps } = rev;\n const inner = stringifyRunPropertiesInner(originalProps as RunPropertiesOptions);\n s += `<w:rPrChange w:author=\"${escapeXml(rev.author)}\" w:date=\"${rev.date}\" w:id=\"${rev.id}\"><w:rPr>${inner ?? \"\"}</w:rPr></w:rPrChange>`;\n }\n\n // w14:* text effects — raw passthrough, emitted last (EG_RPrBase extension slot)\n if (opts.w14RawXml) s += opts.w14RawXml;\n\n return s.length > 0 ? s : undefined;\n}\n\n/**\n * Build `<w:rPr>` XML string directly from options — no intermediate object tree.\n *\n * Replaces `buildRunProperties() + xml()` with a single-pass string builder.\n */\nexport function stringifyRunProperties(opts?: RunPropertiesOptions): string | undefined {\n const inner = stringifyRunPropertiesInner(opts);\n return inner ? `<w:rPr>${inner}</w:rPr>` : undefined;\n}\n","/**\n * Body-level child descriptors for DOCX.\n *\n * Provides descriptor-based stringification for section children.\n * All types use pure string builders — zero class instantiation, zero toXml().\n *\n * @module\n */\n\nimport { toUint8Array, uniqueId } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport {\n attr,\n attrBool,\n attrNum,\n children as xmlChildren,\n escapeXml,\n findChild,\n textOf,\n} from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { AltChunkOptions } from \"@parts/alt-chunk/alt-chunk\";\nimport type { CustomXmlPropertiesOptions } from \"@parts/custom-xml/custom-xml\";\nimport type { RunPropertiesOptions } from \"@parts/paragraph/run/properties\";\nimport { parseRunProperties } from \"@parts/paragraph/run/run-parse\";\nimport { onOff, stringifyRunPropertiesInner } from \"@parts/paragraph/stringify\";\nimport type { SubDocOptions } from \"@parts/sub-doc/sub-doc\";\nimport type {\n SdtCheckboxOptions,\n SdtDateOptions,\n SdtPropertiesOptions,\n} from \"@parts/table-of-contents\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { BodyContext, DocxReadContext } from \"../context\";\n\n// ── AltChunk (pure string — registers relationships + altChunks) ──\n\nconst ALTCHUNK_REL_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk\";\n\nfunction wrapHtmlDocument(fragment: string): string {\n if (/<(!DOCTYPE|html|HTML)/i.test(fragment)) {\n return fragment;\n }\n return `<!DOCTYPE html>\\n<html><head><meta charset=\"utf-8\"></head>\\n<body>${fragment}</body></html>`;\n}\n\nexport const altChunkDesc: CustomDescriptor<AltChunkOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const relId = uniqueId();\n const extension = opts.extension;\n const partPath = `afchunks/afchunk${relId}.${extension}`;\n const rawData = typeof opts.data === \"string\" ? toUint8Array(opts.data) : opts.data;\n const data =\n opts.contentType === \"text/html\" && typeof opts.data === \"string\"\n ? toUint8Array(wrapHtmlDocument(opts.data))\n : rawData;\n\n ctx.fileData.document.relationships.addRelationship(relId, ALTCHUNK_REL_TYPE, partPath);\n ctx.fileData.altChunks.addAltChunk(relId, {\n key: relId,\n data,\n path: partPath,\n extension,\n contentType: opts.contentType,\n });\n\n const rId = `rId${relId}`;\n if (opts.matchSource) {\n return `<w:altChunk r:id=\"${rId}\"><w:altChunkPr><w:matchSrc/></w:altChunkPr></w:altChunk>`;\n }\n return `<w:altChunk r:id=\"${rId}\"/>`;\n },\n\n parse(el, ctx) {\n const rId = attr(el, \"r:id\");\n const opts: Partial<AltChunkOptions> = {};\n\n // Check for matchSource\n const altChunkPr = findChild(el, \"w:altChunkPr\");\n if (altChunkPr && findChild(altChunkPr, \"w:matchSrc\")) {\n opts.matchSource = true;\n }\n\n // Resolve the altChunk data from relationships\n const dctx = ctx as DocxReadContext;\n if (rId) {\n const path = dctx.resolveRelationship(rId);\n if (path) {\n const data = dctx.getRaw(path);\n if (data) {\n opts.data = data;\n const ext = path.split(\".\").pop() ?? \"txt\";\n switch (ext) {\n case \"html\":\n opts.contentType = \"text/html\";\n opts.extension = \"html\";\n break;\n case \"rtf\":\n opts.contentType = \"application/rtf\";\n opts.extension = \"rtf\";\n break;\n default:\n opts.contentType = \"text/plain\";\n opts.extension = \"txt\";\n break;\n }\n }\n }\n }\n\n return opts as AltChunkOptions;\n },\n};\n\n// ── SubDoc (pure string — registers relationships + subDocs) ──\n\nconst SUBDOC_REL_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/subDocument\";\n\nexport const subDocDesc: CustomDescriptor<SubDocOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const relId = uniqueId();\n const partPath = `subdocs/subdoc${relId}.docx`;\n const data = toUint8Array(opts.data);\n\n ctx.fileData.document.relationships.addRelationship(relId, SUBDOC_REL_TYPE, partPath);\n ctx.fileData.subDocs.addSubDoc(relId, {\n data,\n path: partPath,\n });\n\n return `<w:subDoc r:id=\"rId${relId}\"/>`;\n },\n\n parse(el, ctx) {\n const rId = attr(el, \"r:id\");\n const dctx = ctx as DocxReadContext;\n if (rId) {\n const path = dctx.resolveRelationship(rId);\n if (path) {\n const data = dctx.getRaw(path);\n if (data) {\n return { data } as SubDocOptions;\n }\n }\n }\n return { data: new Uint8Array(0) } as SubDocOptions;\n },\n};\n\n// ── SDT (pure string — inline sdtPr + stringify children) ──\n\nexport interface SdtBlockOptions {\n properties: SdtPropertiesOptions;\n children?: SectionChild[];\n /** Run properties for the SDT end mark (w:sdtEndPr). */\n endProperties?: RunPropertiesOptions;\n}\n\nfunction sdtListItemXml(\n item: { displayText?: string; value?: string },\n forceValue?: boolean,\n): string {\n const attrs: string[] = [];\n if (item.displayText !== undefined) attrs.push(`w:displayText=\"${escapeXml(item.displayText)}\"`);\n const value = item.value ?? (forceValue ? item.displayText : undefined);\n if (value !== undefined) attrs.push(`w:value=\"${escapeXml(value)}\"`);\n return `<w:listItem ${attrs.join(\" \")}/>`;\n}\n\nfunction sdtListTypeXml(\n name: string,\n options: { items?: { displayText?: string; value?: string }[]; lastValue?: string },\n): string {\n const parts: string[] = [];\n if (options.items) {\n for (const item of options.items) {\n parts.push(sdtListItemXml(item, name === \"w:dropDownList\"));\n }\n }\n const attrs: string[] = [];\n if (options.lastValue !== undefined) attrs.push(`w:lastValue=\"${escapeXml(options.lastValue)}\"`);\n const attrStr = attrs.length ? \" \" + attrs.join(\" \") : \"\";\n return parts.length ? `<${name}${attrStr}>${parts.join(\"\")}</${name}>` : `<${name}${attrStr}/>`;\n}\n\nfunction sdtDateXml(options: {\n dateFormat?: string;\n languageId?: string;\n storeMappedDataAs?: string;\n calendar?: string;\n fullDate?: string;\n}): string {\n const parts: string[] = [];\n if (options.dateFormat !== undefined)\n parts.push(`<w:dateFormat w:val=\"${escapeXml(options.dateFormat)}\"/>`);\n if (options.languageId !== undefined)\n parts.push(`<w:lid w:val=\"${escapeXml(options.languageId)}\"/>`);\n if (options.storeMappedDataAs !== undefined)\n parts.push(`<w:storeMappedDataAs w:val=\"${options.storeMappedDataAs}\"/>`);\n if (options.calendar !== undefined) parts.push(`<w:calendar w:val=\"${options.calendar}\"/>`);\n const attrs: string[] = [];\n if (options.fullDate !== undefined) attrs.push(`w:fullDate=\"${options.fullDate}\"`);\n const attrStr = attrs.length ? \" \" + attrs.join(\" \") : \"\";\n return parts.length ? `<w:date${attrStr}>${parts.join(\"\")}</w:date>` : `<w:date${attrStr}/>`;\n}\n\nfunction sdtDataBindingXml(options: {\n prefixMappings?: string;\n xpath: string;\n storeItemID: string;\n}): string {\n const attrs: string[] = [\n `w:xpath=\"${escapeXml(options.xpath)}\"`,\n `w:storeItemID=\"${escapeXml(options.storeItemID)}\"`,\n ];\n if (options.prefixMappings !== undefined)\n attrs.push(`w:prefixMappings=\"${escapeXml(options.prefixMappings)}\"`);\n return `<w:dataBinding ${attrs.join(\" \")}/>`;\n}\n\nfunction sdtDocPartXml(\n name: string,\n options: { gallery?: string; category?: string; unique?: boolean },\n): string {\n const parts: string[] = [];\n if (options.gallery !== undefined)\n parts.push(`<w:docPartGallery w:val=\"${escapeXml(options.gallery)}\"/>`);\n if (options.category !== undefined)\n parts.push(`<w:docPartCategory w:val=\"${escapeXml(options.category)}\"/>`);\n if (options.unique !== undefined)\n parts.push(options.unique ? \"<w:docPartUnique/>\" : '<w:docPartUnique w:val=\"0\"/>');\n return parts.length ? `<${name}>${parts.join(\"\")}</${name}>` : `<${name}/>`;\n}\n\nconst W14_NS = 'xmlns:w14=\"http://schemas.microsoft.com/office/word/2010/wordml\"';\n\n/** Default symbol font for checkbox content controls (CT_SdtCheckboxSymbol). */\nconst CHECKBOX_FONT = \"MS Gothic\";\n\nconst DEFAULT_CHECKED: { val: string; font: string } = { val: \"2612\", font: CHECKBOX_FONT };\nconst DEFAULT_UNCHECKED: { val: string; font: string } = { val: \"2610\", font: CHECKBOX_FONT };\n\n/**\n * Build a w14:checkbox element (Word 2010+ content control checkbox).\n *\n * Lives in the w14 extension namespace; emitted with an inline xmlns:w14 so it\n * is valid wherever w:sdtPr appears. validate.ts tolerates the w14 namespace.\n */\nfunction sdtCheckboxXml(opts: SdtCheckboxOptions): string {\n const checked = opts.checkedState ?? DEFAULT_CHECKED;\n const unchecked = opts.uncheckedState ?? DEFAULT_UNCHECKED;\n const inner =\n (opts.checked ? \"<w14:checked/>\" : '<w14:checked w14:val=\"0\"/>') +\n `<w14:checkedState w14:val=\"${escapeXml(checked.val)}\" w14:font=\"${escapeXml(checked.font ?? CHECKBOX_FONT)}\"/>` +\n `<w14:uncheckedState w14:val=\"${escapeXml(unchecked.val)}\" w14:font=\"${escapeXml(unchecked.font ?? CHECKBOX_FONT)}\"/>`;\n return `<w14:checkbox ${W14_NS}>${inner}</w14:checkbox>`;\n}\n\n/** Build the run that renders a checkbox content control's current state symbol. */\nexport function checkboxSymbolRunInner(cb: SdtCheckboxOptions): string {\n const symbol =\n (cb.checked ?? false)\n ? (cb.checkedState ?? DEFAULT_CHECKED)\n : (cb.uncheckedState ?? DEFAULT_UNCHECKED);\n const font = escapeXml(symbol.font ?? CHECKBOX_FONT);\n const char = escapeXml(String.fromCodePoint(parseInt(symbol.val, 16)));\n return `<w:r><w:rPr><w:rFonts w:ascii=\"${font}\" w:hAnsi=\"${font}\"/></w:rPr><w:t>${char}</w:t></w:r>`;\n}\n\nexport function stringifySdtPr(opts: SdtPropertiesOptions): string {\n const parts: string[] = [];\n\n // rPr is not supported in pure JSON path — skip\n\n if (opts.alias !== undefined) parts.push(`<w:alias w:val=\"${escapeXml(opts.alias)}\"/>`);\n if (opts.tag !== undefined) parts.push(`<w:tag w:val=\"${escapeXml(opts.tag)}\"/>`);\n if (opts.id !== undefined) parts.push(`<w:id w:val=\"${opts.id}\"/>`);\n if (opts.lock !== undefined) parts.push(`<w:lock w:val=\"${opts.lock}\"/>`);\n\n // placeholder not supported in pure JSON path — skip\n\n if (opts.temporary !== undefined) parts.push(onOff(\"w:temporary\", opts.temporary));\n const effectiveShowingPlcHdr = opts.showingPlaceholder ?? false;\n if (opts.showingPlaceholder !== undefined || effectiveShowingPlcHdr) {\n parts.push(onOff(\"w:showingPlcHdr\", effectiveShowingPlcHdr));\n }\n if (opts.dataBinding) parts.push(sdtDataBindingXml(opts.dataBinding));\n if (opts.label !== undefined) parts.push(`<w:label w:val=\"${opts.label}\"/>`);\n if (opts.tabIndex !== undefined) parts.push(`<w:tabIndex w:val=\"${opts.tabIndex}\"/>`);\n\n // Type discriminator (xsd:choice)\n if (opts.equation) {\n parts.push(\"<w:equation/>\");\n } else if (opts.comboBox) {\n parts.push(sdtListTypeXml(\"w:comboBox\", opts.comboBox));\n } else if (opts.date) {\n parts.push(sdtDateXml(opts.date));\n } else if (opts.docPartObj) {\n parts.push(sdtDocPartXml(\"w:docPartObj\", opts.docPartObj));\n } else if (opts.docPartList) {\n parts.push(sdtDocPartXml(\"w:docPartList\", opts.docPartList));\n } else if (opts.dropDownList) {\n parts.push(sdtListTypeXml(\"w:dropDownList\", opts.dropDownList));\n } else if (opts.picture) {\n parts.push(\"<w:picture/>\");\n } else if (opts.richText) {\n parts.push(\"<w:richText/>\");\n } else if (opts.text !== undefined) {\n const multiLine = opts.text.multiLine ?? false;\n parts.push(`<w:text w:multiLine=\"${multiLine}\"/>`);\n } else if (opts.citation) {\n parts.push(\"<w:citation/>\");\n } else if (opts.group) {\n parts.push(\"<w:group/>\");\n } else if (opts.bibliography) {\n parts.push(\"<w:bibliography/>\");\n } else if (opts.checkbox) {\n parts.push(sdtCheckboxXml(opts.checkbox));\n }\n\n return parts.length ? `<w:sdtPr>${parts.join(\"\")}</w:sdtPr>` : \"<w:sdtPr/>\";\n}\n\n/**\n * Build the <w:sdt> shell shared by all four SDT levels (block/run/cell/row).\n * The caller supplies the sdtContent body; sdtPr/sdtEndPr are handled uniformly.\n */\nexport function stringifySdtShell(\n properties: SdtPropertiesOptions,\n endProperties: RunPropertiesOptions | undefined,\n contentXml: string,\n): string {\n const endPrInner = endProperties ? stringifyRunPropertiesInner(endProperties) : undefined;\n const endPr = endPrInner ? `<w:sdtEndPr>${endPrInner}</w:sdtEndPr>` : \"<w:sdtEndPr/>\";\n const content = contentXml ? `<w:sdtContent>${contentXml}</w:sdtContent>` : \"<w:sdtContent/>\";\n return `<w:sdt>${stringifySdtPr(properties)}${endPr}${content}</w:sdt>`;\n}\n\n// ── SDT parse helpers ──\n\n/** Parse w:sdtPr element into SdtPropertiesOptions. */\nfunction parseSdtPr(el: Element): SdtPropertiesOptions {\n const opts: SdtPropertiesOptions = {};\n\n const alias = findChild(el, \"w:alias\");\n if (alias) opts.alias = attr(alias, \"w:val\");\n\n const tag = findChild(el, \"w:tag\");\n if (tag) {\n const val = attr(tag, \"w:val\");\n if (val) opts.tag = val;\n }\n\n const id = findChild(el, \"w:id\");\n if (id) {\n const val = attrNum(id, \"w:val\");\n if (val !== undefined) opts.id = val;\n }\n\n const lock = findChild(el, \"w:lock\");\n if (lock) {\n const val = attr(lock, \"w:val\");\n if (val) opts.lock = val as SdtPropertiesOptions[\"lock\"];\n }\n\n const temporary = findChild(el, \"w:temporary\");\n if (temporary) opts.temporary = attrBool(temporary, \"w:val\") ?? true;\n\n const showingPlcHdr = findChild(el, \"w:showingPlcHdr\");\n if (showingPlcHdr) opts.showingPlaceholder = attrBool(showingPlcHdr, \"w:val\") ?? true;\n\n const label = findChild(el, \"w:label\");\n if (label) {\n const val = attrNum(label, \"w:val\");\n if (val !== undefined) opts.label = val;\n }\n\n const tabIndex = findChild(el, \"w:tabIndex\");\n if (tabIndex) {\n const val = attrNum(tabIndex, \"w:val\");\n if (val !== undefined) opts.tabIndex = val;\n }\n\n // Data binding\n const dataBinding = findChild(el, \"w:dataBinding\");\n if (dataBinding) {\n opts.dataBinding = {\n xpath: attr(dataBinding, \"w:xpath\") ?? \"\",\n storeItemID: attr(dataBinding, \"w:storeItemID\") ?? \"\",\n prefixMappings: attr(dataBinding, \"w:prefixMappings\"),\n };\n }\n\n // Type discriminators (xsd:choice)\n if (findChild(el, \"w:equation\")) {\n opts.equation = true;\n } else if (findChild(el, \"w:comboBox\")) {\n const comboBox = findChild(el, \"w:comboBox\")!;\n const items: { displayText?: string; value?: string }[] = [];\n for (const li of xmlChildren(comboBox, \"w:listItem\")) {\n items.push({ displayText: attr(li, \"w:displayText\"), value: attr(li, \"w:value\") });\n }\n opts.comboBox = {\n items: items.length > 0 ? items : undefined,\n lastValue: attr(comboBox, \"w:lastValue\"),\n };\n } else if (findChild(el, \"w:date\")) {\n const date = findChild(el, \"w:date\")!;\n const dateOpts: SdtDateOptions = {};\n const dateFormat = findChild(date, \"w:dateFormat\");\n if (dateFormat) dateOpts.dateFormat = textOf(dateFormat);\n const lid = findChild(date, \"w:lid\");\n if (lid) dateOpts.languageId = textOf(lid);\n const storeMapped = findChild(date, \"w:storeMappedDataAs\");\n if (storeMapped)\n dateOpts.storeMappedDataAs = attr(\n storeMapped,\n \"w:val\",\n ) as SdtDateOptions[\"storeMappedDataAs\"];\n const calendar = findChild(date, \"w:calendar\");\n if (calendar) dateOpts.calendar = attr(calendar, \"w:val\");\n const fullDate = attr(date, \"w:fullDate\");\n if (fullDate) dateOpts.fullDate = fullDate;\n opts.date = dateOpts;\n } else if (findChild(el, \"w:docPartObj\")) {\n const dp = findChild(el, \"w:docPartObj\")!;\n const dpObj: NonNullable<SdtPropertiesOptions[\"docPartObj\"]> = {};\n const gallery = findChild(dp, \"w:docPartGallery\");\n if (gallery) dpObj.gallery = attr(gallery, \"w:val\");\n const category = findChild(dp, \"w:docPartCategory\");\n if (category) dpObj.category = attr(category, \"w:val\");\n if (findChild(dp, \"w:docPartUnique\")) dpObj.unique = true;\n opts.docPartObj = dpObj;\n } else if (findChild(el, \"w:docPartList\")) {\n const dp = findChild(el, \"w:docPartList\")!;\n const dpObj: NonNullable<SdtPropertiesOptions[\"docPartList\"]> = {};\n const gallery = findChild(dp, \"w:docPartGallery\");\n if (gallery) dpObj.gallery = attr(gallery, \"w:val\");\n const category = findChild(dp, \"w:docPartCategory\");\n if (category) dpObj.category = attr(category, \"w:val\");\n if (findChild(dp, \"w:docPartUnique\")) dpObj.unique = true;\n opts.docPartList = dpObj;\n } else if (findChild(el, \"w:dropDownList\")) {\n const ddl = findChild(el, \"w:dropDownList\")!;\n const items: { displayText?: string; value?: string }[] = [];\n for (const li of xmlChildren(ddl, \"w:listItem\")) {\n items.push({ displayText: attr(li, \"w:displayText\"), value: attr(li, \"w:value\") });\n }\n opts.dropDownList = {\n items: items.length > 0 ? items : undefined,\n lastValue: attr(ddl, \"w:lastValue\"),\n };\n } else if (findChild(el, \"w:picture\")) {\n opts.picture = true;\n } else if (findChild(el, \"w:richText\")) {\n opts.richText = true;\n } else if (findChild(el, \"w:text\")) {\n const text = findChild(el, \"w:text\")!;\n opts.text = { multiLine: attrBool(text, \"w:multiLine\") };\n } else if (findChild(el, \"w:citation\")) {\n opts.citation = true;\n } else if (findChild(el, \"w:group\")) {\n opts.group = true;\n } else if (findChild(el, \"w:bibliography\")) {\n opts.bibliography = true;\n } else if (findChild(el, \"w14:checkbox\")) {\n const cb = findChild(el, \"w14:checkbox\")!;\n const cbObj: SdtCheckboxOptions = {};\n const checked = findChild(cb, \"w14:checked\");\n if (checked) cbObj.checked = attrBool(checked, \"w14:val\") ?? true;\n const checkedState = findChild(cb, \"w14:checkedState\");\n if (checkedState)\n cbObj.checkedState = {\n val: attr(checkedState, \"w14:val\") ?? \"\",\n font: attr(checkedState, \"w14:font\"),\n };\n const uncheckedState = findChild(cb, \"w14:uncheckedState\");\n if (uncheckedState)\n cbObj.uncheckedState = {\n val: attr(uncheckedState, \"w14:val\") ?? \"\",\n font: attr(uncheckedState, \"w14:font\"),\n };\n opts.checkbox = cbObj;\n }\n\n return opts;\n}\n\n/** Parse w:customXmlPr element into CustomXmlPropertiesOptions. */\nexport function parseCustomXmlProperties(el: Element): CustomXmlPropertiesOptions {\n const opts: CustomXmlPropertiesOptions = {};\n const placeholder = findChild(el, \"w:placeholder\");\n if (placeholder) {\n const val = attr(placeholder, \"w:val\");\n if (val) opts.placeholder = val;\n }\n const attributes: { name: string; val: string; uri?: string }[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:attr\") continue;\n const name = attr(child, \"w:name\");\n const val = attr(child, \"w:val\");\n if (name && val) {\n const attrOpts: { name: string; val: string; uri?: string } = { name, val };\n const uriVal = attr(child, \"w:uri\");\n if (uriVal) attrOpts.uri = uriVal;\n attributes.push(attrOpts);\n }\n }\n if (attributes.length > 0) opts.attributes = attributes;\n return opts;\n}\n\n/** Body child element parsing callback for SDT/customXml content. */\nlet _parseBodyChild: ((el: Element, ctx: DocxReadContext) => SectionChild) | undefined;\n\n/** Register the body child parser (called from parse/body.ts to break circular dependency). */\nexport function setBodyParseChild(\n parser: (el: Element, ctx: DocxReadContext) => SectionChild,\n): void {\n _parseBodyChild = parser;\n}\n\nfunction parseBodyChildren(elements: Element[], ctx: DocxReadContext): SectionChild[] {\n if (!_parseBodyChild) return [];\n const result: SectionChild[] = [];\n for (const el of elements) {\n result.push(_parseBodyChild(el, ctx));\n }\n return result;\n}\n\nexport const sdtBlockDesc: CustomDescriptor<SdtBlockOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const parts: string[] = [\"<w:sdt>\"];\n\n // sdtPr\n parts.push(stringifySdtPr(opts.properties));\n\n // sdtEndPr — typically empty, included for round-trip fidelity with Word\n const endPrInner = opts.endProperties\n ? stringifyRunPropertiesInner(opts.endProperties)\n : undefined;\n parts.push(endPrInner ? `<w:sdtEndPr>${endPrInner}</w:sdtEndPr>` : \"<w:sdtEndPr/>\");\n\n // sdtContent — checkbox renders its current state symbol; otherwise serialize children\n if (opts.properties.checkbox) {\n parts.push(\n `<w:sdtContent><w:p>${checkboxSymbolRunInner(opts.properties.checkbox)}</w:p></w:sdtContent>`,\n );\n } else if (opts.children && opts.children.length > 0) {\n const contentParts: string[] = [];\n for (const child of opts.children) {\n contentParts.push(ctx.stringifyChild(child));\n }\n const contentBody = contentParts.join(\"\");\n parts.push(contentBody ? `<w:sdtContent>${contentBody}</w:sdtContent>` : \"<w:sdtContent/>\");\n }\n\n parts.push(\"</w:sdt>\");\n return parts.join(\"\");\n },\n\n parse(el, ctx) {\n const dctx = ctx as DocxReadContext;\n\n // Parse sdtPr\n const sdtPr = findChild(el, \"w:sdtPr\");\n const properties = sdtPr ? parseSdtPr(sdtPr) : {};\n\n // Parse sdtEndPr (CT_RPr content at the end mark — run properties, no w:rPr wrapper)\n let endProperties: RunPropertiesOptions | undefined;\n const sdtEndPr = findChild(el, \"w:sdtEndPr\");\n if (sdtEndPr) {\n endProperties = parseRunProperties(sdtEndPr);\n }\n\n // Parse sdtContent children\n const sdtContent = findChild(el, \"w:sdtContent\");\n let childList: SectionChild[] | undefined;\n if (sdtContent && sdtContent.elements?.length) {\n childList = parseBodyChildren(sdtContent.elements, dctx);\n if (childList.length === 0) childList = undefined;\n }\n\n return { properties, children: childList, endProperties } as SdtBlockOptions;\n },\n};\n\n// ── Custom XML (pure string — no context side effects) ──\n\nexport interface CustomXmlBlockDescriptorOptions {\n element: string;\n uri?: string;\n customXmlPr?: CustomXmlPropertiesOptions;\n children?: SectionChild[];\n}\n\nfunction buildCustomXmlPropertiesXml(pr: CustomXmlPropertiesOptions): string {\n const parts: string[] = [\"<w:customXmlPr>\"];\n if (pr.placeholder !== undefined) {\n parts.push(`<w:placeholder w:val=\"${escapeXml(pr.placeholder)}\"/>`);\n }\n if (pr.attributes) {\n for (const attr of pr.attributes) {\n const attrParts: string[] = [\n `w:name=\"${escapeXml(attr.name)}\"`,\n `w:val=\"${escapeXml(attr.val)}\"`,\n ];\n if (attr.uri !== undefined) attrParts.push(`w:uri=\"${escapeXml(attr.uri)}\"`);\n parts.push(`<w:attr ${attrParts.join(\" \")}/>`);\n }\n }\n parts.push(\"</w:customXmlPr>\");\n return parts.join(\"\");\n}\n\n/**\n * Serialize the common customXml shell (element/uri/customXmlPr) wrapping\n * arbitrary content. Shared by all four customXml levels (block/run/row/cell).\n *\n * Microsoft Word removed support for `w:customXml` inline markup on 2010-01-10\n * (i4i Inc. v. Microsoft ruling) and deletes these elements on open; this\n * serializer exists for round-tripping documents that still carry them.\n * Prefer content controls (`w:sdt`) or a `customXml` part for new content.\n */\nexport function stringifyCustomXmlShell(\n opts: { element: string; uri?: string; customXmlPr?: CustomXmlPropertiesOptions },\n contentXml: string,\n): string {\n const attrs: string[] = [`w:element=\"${escapeXml(opts.element)}\"`];\n if (opts.uri !== undefined) attrs.push(`w:uri=\"${escapeXml(opts.uri)}\"`);\n const prXml = opts.customXmlPr ? buildCustomXmlPropertiesXml(opts.customXmlPr) : \"\";\n return `<w:customXml ${attrs.join(\" \")}>${prXml}${contentXml}</w:customXml>`;\n}\n\nexport const customXmlBlockDesc: CustomDescriptor<CustomXmlBlockDescriptorOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const contentParts: string[] = [];\n if (opts.children) {\n for (const child of opts.children) {\n contentParts.push(ctx.stringifyChild(child));\n }\n }\n return stringifyCustomXmlShell(opts, contentParts.join(\"\"));\n },\n\n parse(el, ctx) {\n const dctx = ctx as DocxReadContext;\n const opts: Partial<CustomXmlBlockDescriptorOptions> = {};\n\n const element = attr(el, \"w:element\");\n if (element) opts.element = element;\n\n const uri = attr(el, \"w:uri\");\n if (uri) opts.uri = uri;\n\n // Parse w:customXmlPr\n const xmlPr = findChild(el, \"w:customXmlPr\");\n if (xmlPr) {\n opts.customXmlPr = parseCustomXmlProperties(xmlPr);\n }\n\n // Parse block-level children\n const childList: SectionChild[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:customXmlPr\") continue;\n if (_parseBodyChild) {\n childList.push(_parseBodyChild(child, dctx));\n }\n }\n if (childList.length > 0) opts.children = childList;\n\n return opts as CustomXmlBlockDescriptorOptions;\n },\n};\n","/**\n * Text wrapping module for DrawingML elements.\n *\n * This module provides text wrapping options for floating/anchored drawings.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @module\n */\nimport type { Distance } from \"../drawing\";\n\n/**\n * Enumeration of text wrapping types for floating drawings.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @publicApi\n */\nexport const TextWrappingType = {\n NONE: 0,\n SQUARE: 1,\n TIGHT: 2,\n TOP_AND_BOTTOM: 3,\n THROUGH: 4,\n} as const;\n\n/**\n * Enumeration of text wrapping sides for floating drawings.\n *\n * Specifies on which side(s) text can wrap around the drawing.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @publicApi\n */\nexport const TextWrappingSide = {\n /** Text wraps on both sides of the drawing */\n BOTH_SIDES: \"bothSides\",\n /** Text wraps only on the left side */\n LEFT: \"left\",\n /** Text wraps only on the right side */\n RIGHT: \"right\",\n /** Text wraps on the side with more space */\n LARGEST: \"largest\",\n} as const;\n\n/**\n * A point in a wrap polygon (wrapTight/wrapThrough), in EMUs.\n */\nexport interface WrapPolygonPoint {\n x: number;\n y: number;\n}\n\n/**\n * Wrap polygon for wrapTight/wrapThrough — the contour text wraps around.\n * Round-tripped verbatim so Word's authored contour is preserved.\n */\nexport interface WrapPolygon {\n edited?: boolean;\n points: WrapPolygonPoint[];\n}\n\n/**\n * Options for configuring text wrapping around a drawing.\n */\nexport interface TextWrapping {\n type: (typeof TextWrappingType)[keyof typeof TextWrappingType];\n side?: (typeof TextWrappingSide)[keyof typeof TextWrappingSide];\n margins?: Distance;\n /** Wrap polygon for wrapTight/wrapThrough. Preserves the source contour on round-trip; defaults to the extent rectangle when unset. */\n polygon?: WrapPolygon;\n}\n","/**\n * Wrap Tight module for DrawingML text wrapping.\n *\n * This module provides tight text wrapping for floating drawings\n * where text wraps closely around the image shape.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nimport type { Margins } from \"../floating\";\nimport { TextWrappingSide } from \"./text-wrapping\";\nimport type { TextWrapping } from \"./text-wrapping\";\n\n/**\n * Creates a default rectangular wrap polygon matching the image extent.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapPath\">\n * <xsd:sequence>\n * <xsd:element name=\"start\" type=\"a:CT_Point2D\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * <xsd:element name=\"lineTo\" type=\"a:CT_Point2D\" minOccurs=\"2\" maxOccurs=\"unbounded\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"edited\" type=\"xsd:boolean\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n */\nconst createWrapPolygon = (cx: number, cy: number): string =>\n element(\"wp:wrapPolygon\", { edited: \"0\" }, [\n `<wp:start x=\"0\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"0\"/>`,\n ]);\n\n/**\n * Creates tight text wrapping for a floating drawing.\n *\n * WrapTight causes text to wrap closely around the contours\n * of the drawing rather than its rectangular bounding box.\n * A default rectangular wrap polygon matching the image extent is generated.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapTight\">\n * <xsd:sequence>\n * <xsd:element name=\"wrapPolygon\" type=\"CT_WrapPath\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"wrapText\" type=\"ST_WrapText\" use=\"required\"/>\n * <xsd:attribute name=\"distL\" type=\"ST_WrapDistance\"/>\n * <xsd:attribute name=\"distR\" type=\"ST_WrapDistance\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createWrapTight = (\n textWrapping: TextWrapping,\n margins: Margins = {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n extent: { x: number; y: number },\n): string =>\n element(\n \"wp:wrapTight\",\n {\n distL: margins.left,\n distR: margins.right,\n wrapText: textWrapping.side || TextWrappingSide.BOTH_SIDES,\n },\n [createWrapPolygon(extent.x, extent.y)],\n );\n","/**\n * Wrap Through module for DrawingML text wrapping.\n *\n * This module provides \"through\" text wrapping for floating drawings\n * where text wraps through the image contours, filling any concave areas.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nimport type { Margins } from \"../floating\";\nimport { TextWrappingSide } from \"./text-wrapping\";\nimport type { TextWrapping } from \"./text-wrapping\";\n\n/**\n * Creates a default rectangular wrap polygon matching the image extent.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapPath\">\n * <xsd:sequence>\n * <xsd:element name=\"start\" type=\"a:CT_Point2D\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * <xsd:element name=\"lineTo\" type=\"a:CT_Point2D\" minOccurs=\"2\" maxOccurs=\"unbounded\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"edited\" type=\"xsd:boolean\" use=\"optional\"/>\n * </xsd:complexType>\n * ```\n */\nconst createWrapPolygon = (cx: number, cy: number): string =>\n element(\"wp:wrapPolygon\", { edited: \"0\" }, [\n `<wp:start x=\"0\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"${-cy}\"/>`,\n `<wp:lineTo x=\"${cx}\" y=\"0\"/>`,\n `<wp:lineTo x=\"0\" y=\"0\"/>`,\n ]);\n\n/**\n * Creates \"through\" text wrapping for a floating drawing.\n *\n * WrapThrough is similar to WrapTight but allows text to wrap through\n * the concave portions of the drawing shape (e.g., the inside of the letter \"O\").\n * A default rectangular wrap polygon matching the image extent is generated.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-textWrap.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_WrapThrough\">\n * <xsd:sequence>\n * <xsd:element name=\"wrapPolygon\" type=\"CT_WrapPath\" minOccurs=\"1\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"wrapText\" type=\"ST_WrapText\" use=\"required\"/>\n * <xsd:attribute name=\"distL\" type=\"ST_WrapDistance\"/>\n * <xsd:attribute name=\"distR\" type=\"ST_WrapDistance\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createWrapThrough = (\n textWrapping: TextWrapping,\n margins: Margins = {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n extent: { x: number; y: number },\n): string =>\n element(\n \"wp:wrapThrough\",\n {\n distL: margins.left,\n distR: margins.right,\n wrapText: textWrapping.side || TextWrappingSide.BOTH_SIDES,\n },\n [createWrapPolygon(extent.x, extent.y)],\n );\n","/**\n * Shared constants for WordprocessingML documents.\n *\n * Provides alignment, number format, and space type constants\n * used across multiple document components.\n *\n * @module\n */\n\n// ── Alignment ──\n\n/**\n * Horizontal alignment options for floating drawings.\n *\n * Reference: https://www.datypic.com/sc/ooxml/t-wp_ST_AlignH.html\n *\n * @publicApi\n */\nexport const HorizontalPositionAlign = {\n CENTER: \"center\",\n INSIDE: \"inside\",\n LEFT: \"left\",\n OUTSIDE: \"outside\",\n RIGHT: \"right\",\n} as const;\n\n/**\n * Vertical alignment options for floating drawings.\n *\n * Reference: https://www.datypic.com/sc/ooxml/t-wp_ST_AlignV.html\n *\n * @publicApi\n */\nexport const VerticalPositionAlign = {\n BOTTOM: \"bottom\",\n CENTER: \"center\",\n INSIDE: \"inside\",\n OUTSIDE: \"outside\",\n TOP: \"top\",\n} as const;\n\n// ── Number format ──\n\n/**\n * Number format types for page numbers and list numbering.\n *\n * Reference: http://officeopenxml.com/WPnumbering-numFmt.php\n *\n * @publicApi\n */\nexport const NumberFormat = {\n AIUEO: \"aiueo\",\n AIUEO_FULL_WIDTH: \"aiueoFullWidth\",\n ARABIC_ABJAD: \"arabicAbjad\",\n ARABIC_ALPHA: \"arabicAlpha\",\n BAHT_TEXT: \"bahtText\",\n BULLET: \"bullet\",\n CARDINAL_TEXT: \"cardinalText\",\n CHICAGO: \"chicago\",\n CHINESE_COUNTING: \"chineseCounting\",\n CHINESE_COUNTING_TEN_THOUSAND: \"chineseCountingThousand\",\n CHINESE_LEGAL_SIMPLIFIED: \"chineseLegalSimplified\",\n CHOSUNG: \"chosung\",\n DECIMAL: \"decimal\",\n DECIMAL_ENCLOSED_CIRCLE: \"decimalEnclosedCircle\",\n DECIMAL_ENCLOSED_CIRCLE_CHINESE: \"decimalEnclosedCircleChinese\",\n DECIMAL_ENCLOSED_FULL_STOP: \"decimalEnclosedFullstop\",\n DECIMAL_ENCLOSED_PAREN: \"decimalEnclosedParen\",\n DECIMAL_FULL_WIDTH: \"decimalFullWidth\",\n DECIMAL_FULL_WIDTH_2: \"decimalFullWidth2\",\n DECIMAL_HALF_WIDTH: \"decimalHalfWidth\",\n DECIMAL_ZERO: \"decimalZero\",\n DOLLAR_TEXT: \"dollarText\",\n GANADA: \"ganada\",\n HEBREW_1: \"hebrew1\",\n HEBREW_2: \"hebrew2\",\n HEX: \"hex\",\n HINDI_CONSONANTS: \"hindiConsonants\",\n HINDI_COUNTING: \"hindiCounting\",\n HINDI_NUMBERS: \"hindiNumbers\",\n HINDI_VOWELS: \"hindiVowels\",\n IDEOGRAPH_DIGITAL: \"ideographDigital\",\n IDEOGRAPH_ENCLOSED_CIRCLE: \"ideographEnclosedCircle\",\n IDEOGRAPH_LEGAL_TRADITIONAL: \"ideographLegalTraditional\",\n IDEOGRAPH_TRADITIONAL: \"ideographTraditional\",\n IDEOGRAPH_ZODIAC: \"ideographZodiac\",\n IDEOGRAPH_ZODIAC_TRADITIONAL: \"ideographZodiacTraditional\",\n IROHA: \"iroha\",\n IROHA_FULL_WIDTH: \"irohaFullWidth\",\n JAPANESE_COUNTING: \"japaneseCounting\",\n JAPANESE_DIGITAL_TEN_THOUSAND: \"japaneseDigitalTenThousand\",\n JAPANESE_LEGAL: \"japaneseLegal\",\n KOREAN_COUNTING: \"koreanCounting\",\n KOREAN_DIGITAL: \"koreanDigital\",\n KOREAN_DIGITAL_2: \"koreanDigital2\",\n KOREAN_LEGAL: \"koreanLegal\",\n LOWER_LETTER: \"lowerLetter\",\n LOWER_ROMAN: \"lowerRoman\",\n NONE: \"none\",\n NUMBER_IN_DASH: \"numberInDash\",\n ORDINAL: \"ordinal\",\n ORDINAL_TEXT: \"ordinalText\",\n RUSSIAN_LOWER: \"russianLower\",\n RUSSIAN_UPPER: \"russianUpper\",\n TAIWANESE_COUNTING: \"taiwaneseCounting\",\n TAIWANESE_COUNTING_THOUSAND: \"taiwaneseCountingThousand\",\n TAIWANESE_DIGITAL: \"taiwaneseDigital\",\n THAI_COUNTING: \"thaiCounting\",\n THAI_LETTERS: \"thaiLetters\",\n THAI_NUMBERS: \"thaiNumbers\",\n UPPER_LETTER: \"upperLetter\",\n UPPER_ROMAN: \"upperRoman\",\n VIETNAMESE_COUNTING: \"vietnameseCounting\",\n} as const;\n\n// ── Space type ──\n\n/**\n * XML space handling modes.\n *\n * @publicApi\n */\nexport const SpaceType = {\n DEFAULT: \"default\",\n PRESERVE: \"preserve\",\n} as const;\n","/**\n * Floating position module for DrawingML elements.\n *\n * This module provides positioning options for floating/anchored drawings,\n * including horizontal and vertical relative positioning.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-position.php\n *\n * @module\n */\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { HorizontalPositionAlign, VerticalPositionAlign } from \"@shared/constants\";\nexport { HorizontalPositionAlign, VerticalPositionAlign } from \"@shared/constants\";\n\nimport type { TextWrapping } from \"../text-wrap\";\n\n/**\n * Horizontal Relative Positioning.\n *\n * Specifies the horizontal base from which the drawing position is calculated.\n *\n * Reference: https://www.datypic.com/sc/ooxml/t-wp_ST_RelFromH.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_RelFromH\">\n * <xsd:restriction base=\"xsd:token\">\n * <xsd:enumeration value=\"margin\"/>\n * <xsd:enumeration value=\"page\"/>\n * <xsd:enumeration value=\"column\"/>\n * <xsd:enumeration value=\"character\"/>\n * <xsd:enumeration value=\"leftMargin\"/>\n * <xsd:enumeration value=\"rightMargin\"/>\n * <xsd:enumeration value=\"insideMargin\"/>\n * <xsd:enumeration value=\"outsideMargin\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const HorizontalPositionRelativeFrom = {\n /**\n * ## Character\n *\n * Specifies that the horizontal positioning shall be relative to the position of the anchor within its run content.\n */\n CHARACTER: \"character\",\n /**\n * ## Column\n *\n * Specifies that the horizontal positioning shall be relative to the extents of the column which contains its anchor.\n */\n COLUMN: \"column\",\n /**\n * ## Inside Margin\n *\n * Specifies that the horizontal positioning shall be relative to the inside margin of the current page (the left margin on odd pages, right on even pages).\n */\n INSIDE_MARGIN: \"insideMargin\",\n /**\n * ## Left Margin\n *\n * Specifies that the horizontal positioning shall be relative to the left margin of the page.\n */\n LEFT_MARGIN: \"leftMargin\",\n /**\n * ## Page Margin\n *\n * Specifies that the horizontal positioning shall be relative to the page margins.\n */\n MARGIN: \"margin\",\n /**\n * ## Outside Margin\n *\n * Specifies that the horizontal positioning shall be relative to the outside margin of the current page (the right margin on odd pages, left on even pages).\n */\n OUTSIDE_MARGIN: \"outsideMargin\",\n /**\n * ## Page Edge\n *\n * Specifies that the horizontal positioning shall be relative to the edge of the page.\n */\n PAGE: \"page\",\n /**\n * ## Right Margin\n *\n * Specifies that the horizontal positioning shall be relative to the right margin of the page.\n */\n RIGHT_MARGIN: \"rightMargin\",\n} as const;\n\n/**\n * Vertical Relative Positioning.\n *\n * Specifies the vertical base from which the drawing position is calculated.\n *\n * Reference: https://www.datypic.com/sc/ooxml/t-wp_ST_RelFromV.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_RelFromV\">\n * <xsd:restriction base=\"xsd:token\">\n * <xsd:enumeration value=\"margin\"/>\n * <xsd:enumeration value=\"page\"/>\n * <xsd:enumeration value=\"paragraph\"/>\n * <xsd:enumeration value=\"line\"/>\n * <xsd:enumeration value=\"topMargin\"/>\n * <xsd:enumeration value=\"bottomMargin\"/>\n * <xsd:enumeration value=\"insideMargin\"/>\n * <xsd:enumeration value=\"outsideMargin\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const VerticalPositionRelativeFrom = {\n /**\n * ## Bottom Margin\n *\n * Specifies that the vertical positioning shall be relative to the bottom margin of the current page.\n */\n BOTTOM_MARGIN: \"bottomMargin\",\n /**\n * ## Inside Margin\n *\n * Specifies that the vertical positioning shall be relative to the inside margin of the current page.\n */\n INSIDE_MARGIN: \"insideMargin\",\n /**\n * ## Line\n *\n * Specifies that the vertical positioning shall be relative to the line containing the anchor character.\n */\n LINE: \"line\",\n /**\n * ## Page Margin\n *\n * Specifies that the vertical positioning shall be relative to the page margins.\n */\n MARGIN: \"margin\",\n /**\n * ## Outside Margin\n *\n * Specifies that the vertical positioning shall be relative to the outside margin of the current page.\n */\n OUTSIDE_MARGIN: \"outsideMargin\",\n /**\n * ## Page Edge\n *\n * Specifies that the vertical positioning shall be relative to the edge of the page.\n */\n PAGE: \"page\",\n /**\n * ## Paragraph\n *\n * Specifies that the vertical positioning shall be relative to the paragraph which contains the drawing anchor.\n */\n PARAGRAPH: \"paragraph\",\n /**\n * ## Top Margin\n *\n * Specifies that the vertical positioning shall be relative to the top margin of the current page.\n */\n TOP_MARGIN: \"topMargin\",\n} as const;\n\n/**\n * Options for horizontal positioning of a floating drawing.\n */\nexport interface HorizontalPositionOptions {\n /** The base from which horizontal position is calculated */\n relative?: (typeof HorizontalPositionRelativeFrom)[keyof typeof HorizontalPositionRelativeFrom];\n /** Alignment relative to the horizontal base */\n align?: (typeof HorizontalPositionAlign)[keyof typeof HorizontalPositionAlign];\n /** Offset in EMUs from the horizontal base, or universal measure (e.g., \"1in\", \"2cm\") */\n offset?: number | UniversalMeasure;\n}\n\n/**\n * Options for vertical positioning of a floating drawing.\n */\nexport interface VerticalPositionOptions {\n /** The base from which vertical position is calculated */\n relative?: (typeof VerticalPositionRelativeFrom)[keyof typeof VerticalPositionRelativeFrom];\n /** Alignment relative to the vertical base */\n align?: (typeof VerticalPositionAlign)[keyof typeof VerticalPositionAlign];\n /** Offset in EMUs from the vertical base, or universal measure (e.g., \"1in\", \"2cm\") */\n offset?: number | UniversalMeasure;\n}\n\n/**\n * Margin distances around a floating drawing in EMUs or universal measure.\n */\nexport interface Margins {\n left?: number | UniversalMeasure;\n bottom?: number | UniversalMeasure;\n top?: number | UniversalMeasure;\n right?: number | UniversalMeasure;\n}\n\n/**\n * Configuration options for a floating/anchored drawing.\n *\n * @see {@link Anchor}\n */\nexport interface Floating {\n horizontalPosition: HorizontalPositionOptions;\n verticalPosition: VerticalPositionOptions;\n allowOverlap?: boolean;\n lockAnchor?: boolean;\n behindDocument?: boolean;\n layoutInCell?: boolean;\n margins?: Margins;\n wrap?: TextWrapping;\n zIndex?: number;\n}\n","/**\n * Horizontal position module for floating drawings in WordprocessingML documents.\n *\n * This module provides horizontal positioning for floating drawing objects,\n * specifying the horizontal placement relative to a base element.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-position.php\n *\n * @module\n */\nimport { convertToEmu } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\nimport { HorizontalPositionAlign, HorizontalPositionRelativeFrom } from \"./floating-position\";\nimport type { HorizontalPositionOptions } from \"./floating-position\";\n\n/**\n * Creates a horizontal position element for floating drawings.\n *\n * The positionH element specifies the horizontal positioning of a floating\n * object relative to a base element (page, margin, column, etc.).\n *\n * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionH-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PosH\">\n * <xsd:choice>\n * <xsd:element name=\"align\" type=\"ST_AlignH\"/>\n * <xsd:element name=\"posOffset\" type=\"ST_PositionOffset\"/>\n * </xsd:choice>\n * <xsd:attribute name=\"relativeFrom\" type=\"ST_RelFromH\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @param options - Horizontal position configuration\n * @returns The positionH XML string\n *\n * @example\n * ```typescript\n * // Align to the left of the page\n * createHorizontalPosition({\n * relative: HorizontalPositionRelativeFrom.PAGE,\n * align: HorizontalPositionAlign.LEFT,\n * });\n *\n * // Offset from the margin\n * createHorizontalPosition({\n * relative: HorizontalPositionRelativeFrom.MARGIN,\n * offset: 914400, // 1 inch in EMUs\n * });\n * ```\n */\nexport const createHorizontalPosition = ({\n relative,\n align,\n offset,\n}: HorizontalPositionOptions): string => {\n const child = align\n ? `<wp:align>${align}</wp:align>`\n : offset !== undefined\n ? `<wp:posOffset>${convertToEmu(offset)}</wp:posOffset>`\n : `<wp:align>${HorizontalPositionAlign.LEFT}</wp:align>`;\n\n return element(\n \"wp:positionH\",\n {\n relativeFrom: relative ?? HorizontalPositionRelativeFrom.PAGE,\n },\n [child],\n );\n};\n","/**\n * Vertical position module for floating drawings in WordprocessingML documents.\n *\n * This module provides vertical positioning for floating drawing objects,\n * specifying the vertical placement relative to a base element.\n *\n * Reference: http://officeopenxml.com/drwPicFloating-position.php\n *\n * @module\n */\nimport { convertToEmu } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\nimport { VerticalPositionAlign, VerticalPositionRelativeFrom } from \"./floating-position\";\nimport type { VerticalPositionOptions } from \"./floating-position\";\n\n/**\n * Creates a vertical position element for floating drawings.\n *\n * The positionV element specifies the vertical positioning of a floating\n * object relative to a base element (page, margin, paragraph, line, etc.).\n *\n * Reference: https://www.datypic.com/sc/ooxml/e-wp_positionV-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PosV\">\n * <xsd:choice>\n * <xsd:element name=\"align\" type=\"ST_AlignV\"/>\n * <xsd:element name=\"posOffset\" type=\"ST_PositionOffset\"/>\n * </xsd:choice>\n * <xsd:attribute name=\"relativeFrom\" type=\"ST_RelFromV\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @param options - Vertical position configuration\n * @returns The positionV XML string\n *\n * @example\n * ```typescript\n * // Align to the top of the page\n * createVerticalPosition({\n * relative: VerticalPositionRelativeFrom.PAGE,\n * align: VerticalPositionAlign.TOP,\n * });\n *\n * // Offset from the paragraph\n * createVerticalPosition({\n * relative: VerticalPositionRelativeFrom.PARAGRAPH,\n * offset: 457200, // 0.5 inch in EMUs\n * });\n * ```\n */\nexport const createVerticalPosition = ({\n relative,\n align,\n offset,\n}: VerticalPositionOptions): string => {\n const child = align\n ? `<wp:align>${align}</wp:align>`\n : offset !== undefined\n ? `<wp:posOffset>${convertToEmu(offset)}</wp:posOffset>`\n : `<wp:align>${VerticalPositionAlign.TOP}</wp:align>`;\n\n return element(\n \"wp:positionV\",\n {\n relativeFrom: relative ?? VerticalPositionRelativeFrom.PAGE,\n },\n [child],\n );\n};\n","import { decimalNumber } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n/**\n * Page number module for WordprocessingML section properties.\n *\n * Defines page numbering format and starting value for document sections.\n *\n * Reference: http://officeopenxml.com/WPSectionPgNumType.php\n *\n * @module\n */\nimport type { NumberFormat } from \"@shared/constants\";\n\n/**\n * Specifies the separator character between chapter number and page number.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_ChapterSep\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"hyphen\"/>\n * <xsd:enumeration value=\"period\"/>\n * <xsd:enumeration value=\"colon\"/>\n * <xsd:enumeration value=\"emDash\"/>\n * <xsd:enumeration value=\"enDash\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageNumberSeparator = {\n /** Hyphen separator (-) */\n HYPHEN: \"hyphen\",\n /** Period separator (.) */\n PERIOD: \"period\",\n /** Colon separator (:) */\n COLON: \"colon\",\n /** Em dash separator (—) */\n EM_DASH: \"emDash\",\n /** En dash separator (–) */\n EN_DASH: \"enDash\",\n} as const;\n\n/**\n * Options for configuring page numbering.\n *\n * @property start - Starting page number for the section\n * @property formatType - Number format (decimal, roman, letter, etc.)\n * @property separator - Separator between chapter and page number\n */\nexport interface PageNumberTypeProperties {\n /** Starting page number for the section */\n start?: number;\n /** Number format (decimal, roman, letter, etc., default: decimal) */\n formatType?: (typeof NumberFormat)[keyof typeof NumberFormat];\n /** Separator between chapter and page number (default: hyphen) */\n separator?: (typeof PageNumberSeparator)[keyof typeof PageNumberSeparator];\n /** Heading style ID for chapter numbering */\n chapStyle?: number;\n}\n\n/**\n * Creates page numbering settings (pgNumType) for a document section.\n *\n * This element specifies the page numbering format and starting value\n * for all pages in a section.\n *\n * Reference: http://officeopenxml.com/WPSectionPgNumType.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PageNumber\">\n * <xsd:attribute name=\"fmt\" type=\"ST_NumberFormat\" use=\"optional\" default=\"decimal\"/>\n * <xsd:attribute name=\"start\" type=\"ST_DecimalNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"chapStyle\" type=\"ST_DecimalNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"chapSep\" type=\"ST_ChapterSep\" use=\"optional\" default=\"hyphen\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Start page numbering at 5 with lowercase roman numerals\n * createPageNumberType({\n * start: 5,\n * formatType: NumberFormat.LOWER_ROMAN\n * });\n * ```\n */\nexport const createPageNumberType = ({\n start,\n formatType,\n separator,\n chapStyle,\n}: PageNumberTypeProperties): string =>\n element(\"w:pgNumType\", {\n \"w:chapStyle\": chapStyle === undefined ? undefined : decimalNumber(chapStyle),\n \"w:fmt\": formatType,\n \"w:chapSep\": separator,\n \"w:start\": start === undefined ? undefined : decimalNumber(start),\n });\n","import type { PositiveUniversalMeasure } from \"@office-open/core\";\n\n/**\n * This simple type specifies the orientation of all pages in the parent section. This information is used to determine the actual paper size to use when printing the file.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_PageOrientation_topic_ID0EKBK3.html\n *\n * ## XSD Schema\n *\n * ```xml\n * <xsd:simpleType name=\"ST_PageOrientation\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"portrait\"/>\n * <xsd:enumeration value=\"landscape\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageOrientation = {\n /**\n * ## Portrait Mode\n *\n * Specifies that pages in this section shall be printed in portrait mode.\n */\n PORTRAIT: \"portrait\",\n /**\n * ## Landscape Mode\n *\n * Specifies that pages in this section shall be printed in landscape mode, which prints the page contents with a 90 degree rotation with respect to the normal page orientation.\n */\n LANDSCAPE: \"landscape\",\n} as const;\n\nexport interface PageSizeProperties {\n /**\n * ## Page Width\n *\n * This attribute indicates the width (in twentieths of a point) for all pages in the current section.\n *\n * ### Example\n *\n * ```xml\n * <w:pgSz w:w=\"15840\" w:h=\"12240\" />\n * ```\n *\n * All pages in this section are displayed on a page that is 15840 twentieths of a point (11\") wide.\n *\n * The possible values for this attribute are defined by the ST_TwipsMeasure simple type (§2.18.105).\n */\n width?: number | PositiveUniversalMeasure;\n /**\n * ## Page Height\n *\n * Specifies the height (in twentieths of a point) for all pages in the current section.\n *\n * ### Example\n *\n * ```xml\n * <w:pgSz w:w=\"15840\" w:h=\"12240\" />\n * ```\n *\n * All pages in this section are displayed on a page that is `12240` twentieths of a point (`8.5\"`) tall.\n *\n * The possible values for this attribute are defined by the `ST_TwipsMeasure` simple type (§2.18.105).\n */\n height?: number | PositiveUniversalMeasure;\n /**\n * ## Page Orientation\n *\n * Specifies the orientation of all pages in this section.\n *\n * This information is used to determine the actual paper size to use on the printer.\n *\n * This implies that the actual paper size width and height are reversed for pages in this section. If this attribute is omitted, then portrait shall be implied.\n *\n * ### Example\n *\n * ```xml\n * <w:pgSz w:w=\"15840\" w:h=\"12240\" w:orient=\"landscape\" />\n * ```\n *\n * Although the page width is 11\", and page height is 8.5\", according to the `w` and `h` attributes, because the `orient` attribute is set to landscape, pages in this section are printed on 8.5x11\" paper in landscape mode.\n *\n * The possible values for this attribute are defined by the `ST_PageOrientation` simple type (§2.18.71).\n */\n orientation?: (typeof PageOrientation)[keyof typeof PageOrientation];\n /**\n * ## Printer Paper Code\n *\n * Specifies a printer-specific paper code for the paper type, which shall be used by the printer for pages in this section.\n *\n * This code is stored to ensure the proper paper type is chosen if the specified paper size matches the sizes of multiple paper types supported by the current printer.\n *\n * It will be sent to the printer and used by the printer to determine the appropriate paper type to use when printing.\n *\n * This value is not interpreted or modified other than storing it as specified by the printer.\n *\n * The possible values for this attribute are defined by the `ST_DecimalNumber` simple type (§2.18.16).\n */\n code?: number;\n}\n","/**\n * Page text direction module for WordprocessingML section properties.\n *\n * Defines text flow direction for pages in a section.\n *\n * Reference: http://officeopenxml.com/WPsectionPr.php\n *\n * @module\n */\n\n/**\n * Specifies the text flow direction for pages in a section.\n *\n * This controls whether text flows horizontally (left-to-right) or\n * vertically (top-to-bottom), commonly used for East Asian languages.\n */\nexport const PageTextDirectionType = {\n /** Left-to-right, top-to-bottom (standard Western text flow) */\n LEFT_TO_RIGHT_TOP_TO_BOTTOM: \"lrTb\",\n /** Top-to-bottom, right-to-left (vertical East Asian text flow) */\n TOP_TO_BOTTOM_RIGHT_TO_LEFT: \"tbRl\",\n} as const;\n","/**\n * Section properties module for WordprocessingML documents.\n *\n * Section properties define page layout including page size, margins,\n * headers/footers, columns, and page numbering.\n *\n * Reference: http://officeopenxml.com/WPsection.php\n *\n * @module\n */\nimport type { HeaderFooterReference } from \"@parts/header-footer\";\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\nimport type { SectionVerticalAlign } from \"@shared/vertical-align\";\n\nimport type { ColumnsProperties } from \"./properties/columns\";\nimport type { DocGridProperties } from \"./properties/doc-grid\";\nimport type {\n EndnotePropertiesOptions,\n FootnotePropertiesOptions,\n} from \"./properties/footnote-endnote-properties\";\nimport type { LineNumberProperties } from \"./properties/line-number\";\nimport type { PageBordersOptions } from \"./properties/page-borders\";\nimport type { PageMarginProperties } from \"./properties/page-margin\";\nimport type { PageNumberTypeProperties } from \"./properties/page-number\";\nimport { PageOrientation } from \"./properties/page-size\";\nimport type { PageSizeProperties } from \"./properties/page-size\";\nimport { PageTextDirectionType } from \"./properties/page-text-direction\";\nimport type { SectionType } from \"./properties/section-type\";\n\n/**\n * Header/footer group for specifying different headers/footers\n * for default, first, and even pages.\n */\nexport interface HeaderFooterGroup<T> {\n default?: T;\n first?: T;\n even?: T;\n}\n\nexport interface SectionPropertiesOptionsBase {\n runPropertiesRsid?: string;\n deletionRsid?: string;\n rsid?: string;\n sectionRsid?: string;\n page?: {\n size?: PageSizeProperties;\n margin?: PageMarginProperties;\n pageNumbers?: PageNumberTypeProperties;\n borders?: PageBordersOptions;\n textDirection?: (typeof PageTextDirectionType)[keyof typeof PageTextDirectionType];\n };\n /**\n * Document grid. Three states: omitted (fresh generation emits Word's CJK\n * default line grid — linePitch 312, type \"lines\"); a DocGridProperties object\n * (emits provided values, e.g. from a parsed source); or false (explicit off —\n * a parsed source with no w:docGrid is preserved by emitting nothing).\n */\n grid?: DocGridProperties | false;\n headerWrapperGroup?: HeaderFooterGroup<HeaderFooterReference>;\n footerWrapperGroup?: HeaderFooterGroup<HeaderFooterReference>;\n lineNumbers?: LineNumberProperties;\n titlePage?: boolean;\n verticalAlign?: SectionVerticalAlign;\n column?: ColumnsProperties;\n type?: (typeof SectionType)[keyof typeof SectionType];\n noEndnote?: boolean;\n formProtection?: boolean;\n bidi?: boolean;\n rtlGutter?: boolean;\n paperSrc?: {\n first?: number;\n other?: number;\n };\n footnotePr?: FootnotePropertiesOptions;\n endnotePr?: EndnotePropertiesOptions;\n printerSettingsId?: string;\n}\n\nexport type SectionPropertiesChangeOptions = ChangedProperties & SectionPropertiesOptionsBase;\n\nexport type SectionPropertiesOptions = {\n revision?: SectionPropertiesChangeOptions;\n} & SectionPropertiesOptionsBase;\n\nexport const sectionMarginDefaults = {\n TOP: 1440,\n RIGHT: 1800,\n BOTTOM: 1440,\n LEFT: 1800,\n HEADER: 851,\n FOOTER: 992,\n GUTTER: 0,\n};\n\nexport const sectionPageSizeDefaults = {\n WIDTH: 11_906,\n HEIGHT: 16_838,\n ORIENTATION: PageOrientation.PORTRAIT,\n};\n","/**\n * Section properties descriptor for DOCX documents.\n *\n * Produces `<w:sectPr>` XML directly from options, eliminating all\n * intermediate XmlComponent instances (create* + toXml pattern).\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_SectPr\n *\n * @module\n */\n\nimport { convertToTwip } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrBool, attrMeasure, attrNum, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { ColumnProperties } from \"@parts/document/body/section-properties/properties/column\";\nimport type { ColumnsProperties } from \"@parts/document/body/section-properties/properties/columns\";\nimport type { DocGridProperties } from \"@parts/document/body/section-properties/properties/doc-grid\";\nimport type {\n EndnotePropertiesOptions,\n FootnotePropertiesOptions,\n} from \"@parts/document/body/section-properties/properties/footnote-endnote-properties\";\nimport type { LineNumberProperties } from \"@parts/document/body/section-properties/properties/line-number\";\nimport type { PageBordersOptions } from \"@parts/document/body/section-properties/properties/page-borders\";\nimport type { PageMarginProperties } from \"@parts/document/body/section-properties/properties/page-margin\";\nimport { PageNumberSeparator } from \"@parts/document/body/section-properties/properties/page-number\";\nimport type { PageNumberTypeProperties } from \"@parts/document/body/section-properties/properties/page-number\";\nimport type { PageSizeProperties } from \"@parts/document/body/section-properties/properties/page-size\";\nimport type {\n HeaderFooterGroup,\n SectionPropertiesChangeOptions,\n SectionPropertiesOptions,\n} from \"@parts/document/body/section-properties/section-properties\";\nimport {\n sectionMarginDefaults,\n sectionPageSizeDefaults,\n} from \"@parts/document/body/section-properties/section-properties\";\nimport type { HeaderFooterReference } from \"@parts/header-footer\";\nimport type { BorderOptions } from \"@shared/border\";\nimport { NumberFormat } from \"@shared/constants\";\nimport type { BodyContext } from \"@shared/index\";\n\n/** Valid page-number @w:fmt values (ST_NumberFormat). */\nconst PAGE_NUMBER_FORMATS = Object.values(NumberFormat) as readonly string[];\n/** Valid page-number @w:chapSep values (ST_ChapterSep). */\nconst PAGE_NUMBER_SEPARATORS = Object.values(PageNumberSeparator) as readonly string[];\n\n// ── Border XML helper ──\n\nfunction stringifyBorderXml(tag: string, opts: BorderOptions): string {\n const attrs: string[] = [];\n if (opts.style !== undefined) attrs.push(`w:val=\"${opts.style}\"`);\n if (opts.color !== undefined) attrs.push(`w:color=\"${opts.color}\"`);\n if (opts.size !== undefined) attrs.push(`w:sz=\"${opts.size}\"`);\n if (opts.space !== undefined) attrs.push(`w:space=\"${opts.space}\"`);\n if (opts.themeColor !== undefined) attrs.push(`w:themeColor=\"${opts.themeColor}\"`);\n if (opts.themeTint !== undefined) attrs.push(`w:themeTint=\"${opts.themeTint}\"`);\n if (opts.themeShade !== undefined) attrs.push(`w:themeShade=\"${opts.themeShade}\"`);\n if (opts.shadow !== undefined) attrs.push(`w:shadow=\"${opts.shadow ? 1 : 0}\"`);\n if (opts.frame !== undefined) attrs.push(`w:frame=\"${opts.frame ? 1 : 0}\"`);\n return `<${tag} ${attrs.join(\" \")}/>`;\n}\n\n// ── Inline XML builders (replacing create* + toXml) ──\n\nfunction pageSizeXml(\n w: number | string,\n h: number | string,\n orient?: string,\n code?: number,\n): string {\n const attrs: string[] = [`w:w=\"${w}\"`, `w:h=\"${h}\"`];\n if (orient) attrs.push(`w:orient=\"${orient}\"`);\n if (code !== undefined) attrs.push(`w:code=\"${code}\"`);\n return `<w:pgSz ${attrs.join(\" \")}/>`;\n}\n\nfunction pageMarginXml(\n top: number | string,\n right: number | string,\n bottom: number | string,\n left: number | string,\n header: number | string,\n footer: number | string,\n gutter: number | string,\n): string {\n return `<w:pgMar w:top=\"${top}\" w:right=\"${right}\" w:bottom=\"${bottom}\" w:left=\"${left}\" w:header=\"${header}\" w:footer=\"${footer}\" w:gutter=\"${gutter}\"/>`;\n}\n\nfunction headerFooterRefXml(tag: string, id: number, type: string): string {\n return `<${tag} r:id=\"rId${id}\" w:type=\"${type}\"/>`;\n}\n\nfunction sectionTypeXml(val: string): string {\n return `<w:type w:val=\"${val}\"/>`;\n}\n\nfunction verticalAlignXml(val: string): string {\n return `<w:vAlign w:val=\"${val}\"/>`;\n}\n\nfunction lineNumberXml(opts: NonNullable<SectionPropertiesOptions[\"lineNumbers\"]>): string {\n const attrs: string[] = [];\n if (opts.countBy !== undefined) attrs.push(`w:countBy=\"${opts.countBy}\"`);\n if (opts.start !== undefined) attrs.push(`w:start=\"${opts.start}\"`);\n if (opts.restart !== undefined) attrs.push(`w:restart=\"${opts.restart}\"`);\n if (opts.distance !== undefined) attrs.push(`w:distance=\"${opts.distance}\"`);\n return attrs.length ? `<w:lnNumType ${attrs.join(\" \")}/>` : \"<w:lnNumType/>\";\n}\n\nfunction pageNumberXml(opts: NonNullable<PageNumberTypeProperties>): string {\n const attrs: string[] = [];\n if (opts.start !== undefined) attrs.push(`w:start=\"${opts.start}\"`);\n if (opts.formatType !== undefined) attrs.push(`w:fmt=\"${opts.formatType}\"`);\n if (opts.separator !== undefined) attrs.push(`w:chapSep=\"${opts.separator}\"`);\n if (opts.chapStyle !== undefined) attrs.push(`w:chapStyle=\"${opts.chapStyle}\"`);\n // No attributes → omit pgNumType (never fabricate an empty element).\n return attrs.length ? `<w:pgNumType ${attrs.join(\" \")}/>` : \"\";\n}\n\nfunction docGridXml(linePitch: number, charSpace?: number, type?: string): string {\n const attrs: string[] = [`w:linePitch=\"${linePitch}\"`];\n if (charSpace !== undefined) attrs.push(`w:charSpace=\"${charSpace}\"`);\n if (type !== undefined) attrs.push(`w:type=\"${type}\"`);\n return `<w:docGrid ${attrs.join(\" \")}/>`;\n}\n\nfunction columnsXml(opts: NonNullable<SectionPropertiesOptions[\"column\"]>): string {\n const attrs: string[] = [];\n if (opts.space !== undefined) attrs.push(`w:space=\"${convertToTwip(opts.space)}\"`);\n if (opts.count !== undefined) attrs.push(`w:num=\"${opts.count}\"`);\n if (opts.separate !== undefined) attrs.push(`w:sep=\"${opts.separate ? 1 : 0}\"`);\n if (opts.equalWidth !== undefined) attrs.push(`w:equalWidth=\"${opts.equalWidth ? 1 : 0}\"`);\n\n const attrStr = attrs.join(\" \");\n\n // Custom width columns — children are ColumnProperties (Column class implements this interface)\n if (!opts.equalWidth && opts.children) {\n const colParts: string[] = [];\n for (const col of opts.children as readonly ColumnProperties[]) {\n const colAttrs: string[] = [`w:w=\"${convertToTwip(col.width)}\"`];\n if (col.space !== undefined) colAttrs.push(`w:space=\"${convertToTwip(col.space)}\"`);\n colParts.push(`<w:col ${colAttrs.join(\" \")}/>`);\n }\n return `<w:cols ${attrStr}>${colParts.join(\"\")}</w:cols>`;\n }\n return `<w:cols ${attrStr}/>`;\n}\n\nfunction footnotePrXml(\n tag: string,\n opts: FootnotePropertiesOptions | EndnotePropertiesOptions,\n): string {\n const parts: string[] = [];\n if (opts.pos !== undefined) parts.push(`<w:pos w:val=\"${opts.pos}\"/>`);\n if (opts.formatType !== undefined || opts.format !== undefined) {\n const fmtAttrs: string[] = [];\n // CT_NumFmt uses w:val (required) for the format type; w:fmt belongs to\n // CT_PageNumber (pgNumType). w:format is the optional free-form override.\n if (opts.formatType !== undefined) fmtAttrs.push(`w:val=\"${opts.formatType}\"`);\n if (opts.format !== undefined) fmtAttrs.push(`w:format=\"${opts.format}\"`);\n parts.push(`<w:numFmt ${fmtAttrs.join(\" \")}/>`);\n }\n if (opts.numStart !== undefined) parts.push(`<w:numStart w:val=\"${opts.numStart}\"/>`);\n if (opts.numRestart !== undefined) parts.push(`<w:numRestart w:val=\"${opts.numRestart}\"/>`);\n const body = parts.join(\"\");\n return body ? `<${tag}>${body}</${tag}>` : `<${tag}/>`;\n}\n\nfunction pageBordersXml(opts: NonNullable<PageBordersOptions>): string {\n const attrs: string[] = [];\n if (opts.display !== undefined) attrs.push(`w:display=\"${opts.display}\"`);\n if (opts.offsetFrom !== undefined) attrs.push(`w:offsetFrom=\"${opts.offsetFrom}\"`);\n if (opts.zOrder !== undefined) attrs.push(`w:zOrder=\"${opts.zOrder}\"`);\n\n const parts: string[] = [];\n if (opts.top) parts.push(stringifyBorderXml(\"w:top\", opts.top));\n if (opts.left) parts.push(stringifyBorderXml(\"w:left\", opts.left));\n if (opts.bottom) parts.push(stringifyBorderXml(\"w:bottom\", opts.bottom));\n if (opts.right) parts.push(stringifyBorderXml(\"w:right\", opts.right));\n\n const attrStr = attrs.join(\" \");\n const body = parts.join(\"\");\n if (!body && !attrStr) return \"<w:pgBorders/>\";\n return body ? `<w:pgBorders ${attrStr}>${body}</w:pgBorders>` : `<w:pgBorders ${attrStr}/>`;\n}\n\n// ── Header/footer references ──\n\nfunction appendHeaderFooterRefs(\n parts: string[],\n type: \"w:headerReference\" | \"w:footerReference\",\n group?: {\n default?: HeaderFooterReference;\n first?: HeaderFooterReference;\n even?: HeaderFooterReference;\n },\n): void {\n if (!group) return;\n if (group.default) parts.push(headerFooterRefXml(type, group.default.referenceId, \"default\"));\n if (group.first) parts.push(headerFooterRefXml(type, group.first.referenceId, \"first\"));\n if (group.even) parts.push(headerFooterRefXml(type, group.even.referenceId, \"even\"));\n}\n\n// ── sectPrChange (recursive) ──\n\nfunction stringifySectionPropertiesChange(opts: SectionPropertiesChangeOptions): string {\n const { author, date, id, ...inner } = opts;\n const innerXml = stringifySectionPropertiesInner(inner);\n return `<w:sectPrChange w:author=\"${author}\" w:date=\"${date}\" w:id=\"${id}\"><w:sectPr>${innerXml}</w:sectPr></w:sectPrChange>`;\n}\n\n// ── Core XML builder ──\n\nfunction stringifySectionPropertiesInner(opts: SectionPropertiesOptions): string {\n const parts: string[] = [];\n\n // Header/footer references\n appendHeaderFooterRefs(parts, \"w:headerReference\", opts.headerWrapperGroup);\n appendHeaderFooterRefs(parts, \"w:footerReference\", opts.footerWrapperGroup);\n\n // Destructure page options with defaults\n const {\n size: {\n width = sectionPageSizeDefaults.WIDTH,\n height = sectionPageSizeDefaults.HEIGHT,\n orientation = sectionPageSizeDefaults.ORIENTATION,\n code,\n } = {},\n margin: {\n top = sectionMarginDefaults.TOP,\n right = sectionMarginDefaults.RIGHT,\n bottom = sectionMarginDefaults.BOTTOM,\n left = sectionMarginDefaults.LEFT,\n header = sectionMarginDefaults.HEADER,\n footer = sectionMarginDefaults.FOOTER,\n gutter = sectionMarginDefaults.GUTTER,\n } = {},\n pageNumbers = {},\n borders,\n textDirection,\n } = opts.page ?? {};\n\n const {\n linePitch = 312,\n charSpace = 0,\n type: gridType = \"lines\",\n } = typeof opts.grid === \"object\" ? opts.grid : {};\n\n // Footnote/endnote properties\n if (opts.footnotePr) parts.push(footnotePrXml(\"w:footnotePr\", opts.footnotePr));\n if (opts.endnotePr) parts.push(footnotePrXml(\"w:endnotePr\", opts.endnotePr));\n\n // Section type\n if (opts.type) parts.push(sectionTypeXml(opts.type));\n\n // Page size — normalize both logical dimensions to twips, then swap w/h when\n // landscape. UniversalMeasure (\"210mm\") is converted so the emitted w:w/w:h is\n // always a plain twip number that the attrNum-based parse reads back exactly.\n const wTwips = convertToTwip(width);\n const hTwips = convertToTwip(height);\n const pgW = orientation === \"landscape\" ? hTwips : wTwips;\n const pgH = orientation === \"landscape\" ? wTwips : hTwips;\n parts.push(pageSizeXml(pgW, pgH, orientation, code));\n\n // Page margin (always present)\n parts.push(pageMarginXml(top, right, bottom, left, header, footer, gutter));\n\n // Page borders\n if (borders) parts.push(pageBordersXml(borders));\n\n // Line numbers\n if (opts.lineNumbers) parts.push(lineNumberXml(opts.lineNumbers));\n\n // Page numbers\n parts.push(pageNumberXml(pageNumbers));\n\n // Columns\n if (opts.column) parts.push(columnsXml(opts.column));\n\n // Vertical alignment\n if (opts.verticalAlign) parts.push(verticalAlignXml(opts.verticalAlign));\n\n // Boolean on/off elements — direct string output\n if (opts.titlePage !== undefined)\n parts.push(opts.titlePage ? \"<w:titlePg/>\" : '<w:titlePg w:val=\"0\"/>');\n if (textDirection) parts.push(`<w:textDirection w:val=\"${textDirection}\"/>`);\n if (opts.noEndnote !== undefined)\n parts.push(opts.noEndnote ? \"<w:noEndnote/>\" : '<w:noEndnote w:val=\"0\"/>');\n if (opts.formProtection !== undefined)\n parts.push(opts.formProtection ? \"<w:formProt/>\" : '<w:formProt w:val=\"0\"/>');\n if (opts.bidi !== undefined) parts.push(opts.bidi ? \"<w:bidi/>\" : '<w:bidi w:val=\"0\"/>');\n if (opts.rtlGutter !== undefined)\n parts.push(opts.rtlGutter ? \"<w:rtlGutter/>\" : '<w:rtlGutter w:val=\"0\"/>');\n\n // Paper source\n if (opts.paperSrc) {\n const psAttr: string[] = [];\n if (opts.paperSrc.first !== undefined) psAttr.push(`w:first=\"${opts.paperSrc.first}\"`);\n if (opts.paperSrc.other !== undefined) psAttr.push(`w:other=\"${opts.paperSrc.other}\"`);\n parts.push(`<w:paperSrc ${psAttr.join(\" \")}/>`);\n }\n\n // Printer settings\n if (opts.printerSettingsId !== undefined) {\n parts.push(`<w:printerSettings r:id=\"${opts.printerSettingsId}\"/>`);\n }\n\n // Document grid — three states:\n // - undefined (fresh, unset): emit Word's CJK default line grid (linePitch\n // 312, type \"lines\") so generated docs match East Asian line-snapping.\n // - object: emit provided values (round-trip fidelity).\n // - false (explicit off, e.g. parsed source had no w:docGrid): omit.\n if (opts.grid !== false) {\n parts.push(docGridXml(linePitch, charSpace, gridType));\n }\n\n // Revision (sectPrChange)\n if (opts.revision) {\n parts.push(stringifySectionPropertiesChange(opts.revision));\n }\n\n return parts.join(\"\");\n}\n\n// ── Descriptor ──\n\n/**\n * Section properties descriptor for DOCX `<w:sectPr>` elements.\n *\n * Produces complete XML directly from options — zero XmlComponent instances\n * in the hot path. All `create*()` + `.toXml()` calls eliminated in favor\n * of direct string concatenation.\n *\n * @example\n * ```typescript\n * const xml = sectionPropertiesDesc.stringify(sectPrOpts, ctx);\n * ```\n */\nexport const sectionPropertiesDesc: CustomDescriptor<SectionPropertiesOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n return stringifySectionPropertiesXml(opts);\n },\n\n parse(el, _ctx) {\n return parseSectionPropertiesEl(el);\n },\n};\n\n/** Standalone stringify — no context needed, pure options → XML. */\nexport function stringifySectionPropertiesXml(opts: SectionPropertiesOptions): string {\n const inner = stringifySectionPropertiesInner(opts);\n\n const attrs: string[] = [];\n if (opts.runPropertiesRsid !== undefined) attrs.push(`w:rsidRPr=\"${opts.runPropertiesRsid}\"`);\n if (opts.deletionRsid !== undefined) attrs.push(`w:rsidDel=\"${opts.deletionRsid}\"`);\n if (opts.rsid !== undefined) attrs.push(`w:rsidR=\"${opts.rsid}\"`);\n if (opts.sectionRsid !== undefined) attrs.push(`w:rsidSect=\"${opts.sectionRsid}\"`);\n\n const attrStr = attrs.length ? \" \" + attrs.join(\" \") : \"\";\n return `<w:sectPr${attrStr}>${inner}</w:sectPr>`;\n}\n\n// ── Parse (Element → SectionPropertiesOptions) ──\n\n/** Parse a w:sectPr element into SectionPropertiesOptions. */\nexport function parseSectionPropertiesEl(el: Element): SectionPropertiesOptions {\n const opts: Partial<SectionPropertiesOptions> = {};\n\n // rsid attributes on w:sectPr element\n for (const [attrName, optKey] of [\n [\"w:rsidR\", \"rsid\"],\n [\"w:rsidRPr\", \"runPropertiesRsid\"],\n [\"w:rsidDel\", \"deletionRsid\"],\n [\"w:rsidSect\", \"sectionRsid\"],\n ] as const) {\n const val = attr(el, attrName);\n if (val) opts[optKey] = val;\n }\n\n // Page properties — pgSz, pgMar, pgNumType are independent per CT_SectPr\n // (each minOccurs=0). Do not gate pgMar/pgNumType on pgSz: a sectPr that\n // omits <w:pgSz> must still round-trip its margins and page-number type.\n const page: NonNullable<SectionPropertiesOptions[\"page\"]> = {};\n\n // Page size\n const pgSz = findChild(el, \"w:pgSz\");\n if (pgSz) {\n const size: PageSizeProperties = {};\n const w = attrNum(pgSz, \"w:w\");\n const h = attrNum(pgSz, \"w:h\");\n const orient = attr(pgSz, \"w:orient\");\n if (orient === \"landscape\" && w !== undefined && h !== undefined) {\n size.width = h;\n size.height = w;\n } else {\n if (w !== undefined) size.width = w;\n if (h !== undefined) size.height = h;\n }\n if (orient) size.orientation = orient as PageSizeProperties[\"orientation\"];\n const code = attrNum(pgSz, \"w:code\");\n if (code !== undefined) size.code = code;\n if (Object.keys(size).length > 0) page.size = size;\n }\n\n // Page margins\n const pgMar = findChild(el, \"w:pgMar\");\n if (pgMar) {\n const margin: PageMarginProperties = {};\n for (const [a, o] of [\n [\"w:top\", \"top\"],\n [\"w:right\", \"right\"],\n [\"w:bottom\", \"bottom\"],\n [\"w:left\", \"left\"],\n [\"w:header\", \"header\"],\n [\"w:footer\", \"footer\"],\n [\"w:gutter\", \"gutter\"],\n ] as const) {\n const val = attrNum(pgMar, a);\n if (val !== undefined) margin[o] = val;\n }\n if (Object.keys(margin).length > 0) page.margin = margin;\n }\n\n // Page number type\n const pgNumType = findChild(el, \"w:pgNumType\");\n if (pgNumType) {\n const pageNumbers: PageNumberTypeProperties = {};\n const start = attrNum(pgNumType, \"w:start\");\n if (start !== undefined) pageNumbers.start = start;\n const fmt = attr(pgNumType, \"w:fmt\");\n if (fmt && PAGE_NUMBER_FORMATS.includes(fmt)) {\n pageNumbers.formatType = fmt as PageNumberTypeProperties[\"formatType\"];\n }\n const chapSep = attr(pgNumType, \"w:chapSep\");\n if (chapSep && PAGE_NUMBER_SEPARATORS.includes(chapSep)) {\n pageNumbers.separator = chapSep as PageNumberTypeProperties[\"separator\"];\n }\n const chapStyle = attrNum(pgNumType, \"w:chapStyle\");\n if (chapStyle !== undefined) pageNumbers.chapStyle = chapStyle;\n if (Object.keys(pageNumbers).length > 0) page.pageNumbers = pageNumbers;\n }\n\n if (Object.keys(page).length > 0) opts.page = page;\n\n // Columns\n const cols = findChild(el, \"w:cols\");\n if (cols) {\n const column: ColumnsProperties = {};\n const count = attrNum(cols, \"w:num\");\n if (count !== undefined) column.count = count;\n const space = attrMeasure(cols, \"w:space\");\n if (space !== undefined) column.space = space as ColumnsProperties[\"space\"];\n const separate = attrBool(cols, \"w:sep\");\n if (separate !== undefined) column.separate = separate;\n const equalWidth = attrBool(cols, \"w:equalWidth\");\n if (equalWidth !== undefined) column.equalWidth = equalWidth;\n const colChildren: ColumnProperties[] = [];\n for (const colEl of cols.elements ?? []) {\n if (colEl.name !== \"w:col\") continue;\n const width = attrMeasure(colEl, \"w:w\");\n if (width === undefined) continue;\n const colAttr: ColumnProperties = { width: width as ColumnProperties[\"width\"] };\n const colSpace = attrMeasure(colEl, \"w:space\");\n if (colSpace !== undefined) colAttr.space = colSpace as ColumnProperties[\"space\"];\n colChildren.push(colAttr);\n }\n if (colChildren.length > 0) column.children = colChildren;\n if (Object.keys(column).length > 0) opts.column = column;\n }\n\n // Section type\n const type = findChild(el, \"w:type\");\n if (type) {\n const val = attr(type, \"w:val\");\n if (val) opts.type = val as SectionPropertiesOptions[\"type\"];\n }\n\n // Title page\n const titlePg = findChild(el, \"w:titlePg\");\n if (titlePg) opts.titlePage = attrBool(titlePg, \"w:val\") ?? true;\n\n // On/off properties\n for (const [name, optKey] of [\n [\"w:noEndnote\", \"noEndnote\"],\n [\"w:formProt\", \"formProtection\"],\n [\"w:bidi\", \"bidi\"],\n [\"w:rtlGutter\", \"rtlGutter\"],\n ] as const) {\n const child = findChild(el, name);\n if (child) opts[optKey] = attrBool(child, \"w:val\") ?? true;\n }\n\n // Document grid — three-state: object (source had w:docGrid → preserve),\n // false (source had none → explicit off so stringify omits it), undefined\n // (fresh generation, stringify emits the CJK default line grid).\n const docGrid = findChild(el, \"w:docGrid\");\n if (docGrid) {\n const grid: Partial<DocGridProperties> = {};\n const type = attr(docGrid, \"w:type\");\n if (type) grid.type = type as DocGridProperties[\"type\"];\n const linePitch = attrNum(docGrid, \"w:linePitch\");\n if (linePitch !== undefined) grid.linePitch = linePitch;\n const charSpace = attrNum(docGrid, \"w:charSpace\");\n if (charSpace !== undefined) grid.charSpace = charSpace;\n opts.grid = grid as DocGridProperties;\n } else {\n opts.grid = false;\n }\n\n // Line numbers\n const lnNumType = findChild(el, \"w:lnNumType\");\n if (lnNumType) {\n const lineNumbers: LineNumberProperties = {};\n const countBy = attrNum(lnNumType, \"w:countBy\");\n if (countBy !== undefined) lineNumbers.countBy = countBy;\n const start = attrNum(lnNumType, \"w:start\");\n if (start !== undefined) lineNumbers.start = start;\n const restart = attr(lnNumType, \"w:restart\");\n if (restart) lineNumbers.restart = restart as LineNumberProperties[\"restart\"];\n const distance = attrNum(lnNumType, \"w:distance\");\n if (distance !== undefined) lineNumbers.distance = distance;\n if (Object.keys(lineNumbers).length > 0) opts.lineNumbers = lineNumbers;\n }\n\n // Page borders\n const pgBorders = findChild(el, \"w:pgBorders\");\n if (pgBorders) {\n const borders: Partial<PageBordersOptions> = {};\n for (const side of [\"top\", \"left\", \"bottom\", \"right\"] as const) {\n const sideEl = findChild(pgBorders, `w:${side}`);\n if (!sideEl) continue;\n const val = attr(sideEl, \"w:val\");\n if (!val) continue; // CT_Border/@val is XSD-required\n const b: BorderOptions = { style: val as BorderOptions[\"style\"] };\n const color = attr(sideEl, \"w:color\");\n if (color) b.color = color;\n const sz = attrNum(sideEl, \"w:sz\");\n if (sz !== undefined) b.size = sz;\n const space = attrNum(sideEl, \"w:space\");\n if (space !== undefined) b.space = space;\n borders[side] = b;\n }\n const display = attr(pgBorders, \"w:display\");\n if (display) borders.display = display as PageBordersOptions[\"display\"];\n const offsetFrom = attr(pgBorders, \"w:offsetFrom\");\n if (offsetFrom) borders.offsetFrom = offsetFrom as PageBordersOptions[\"offsetFrom\"];\n const zOrder = attr(pgBorders, \"w:zOrder\");\n if (zOrder) borders.zOrder = zOrder as PageBordersOptions[\"zOrder\"];\n if (Object.keys(borders).length > 0) {\n const page: NonNullable<SectionPropertiesOptions[\"page\"]> = opts.page ?? {};\n page.borders = borders;\n opts.page = page;\n }\n }\n\n // Vertical align\n const vAlign = findChild(el, \"w:vAlign\");\n if (vAlign) {\n const val = attr(vAlign, \"w:val\");\n if (val) opts.verticalAlign = val as SectionPropertiesOptions[\"verticalAlign\"];\n }\n\n // Text direction\n const textDirection = findChild(el, \"w:textDirection\");\n if (textDirection) {\n const val = attr(textDirection, \"w:val\");\n if (val) {\n const page: NonNullable<SectionPropertiesOptions[\"page\"]> = opts.page ?? {};\n page.textDirection = val as NonNullable<SectionPropertiesOptions[\"page\"]>[\"textDirection\"];\n opts.page = page;\n }\n }\n\n // Footnote properties\n const footnotePr = findChild(el, \"w:footnotePr\");\n if (footnotePr) {\n opts.footnotePr = parseNotePropertiesEl(footnotePr);\n }\n\n // Endnote properties\n const endnotePr = findChild(el, \"w:endnotePr\");\n if (endnotePr) {\n opts.endnotePr = parseNotePropertiesEl(endnotePr) as EndnotePropertiesOptions;\n }\n\n // Paper source\n const paperSrc = findChild(el, \"w:paperSrc\");\n if (paperSrc) {\n const ps: NonNullable<SectionPropertiesOptions[\"paperSrc\"]> = {};\n const first = attrNum(paperSrc, \"w:first\");\n if (first !== undefined) ps.first = first;\n const other = attrNum(paperSrc, \"w:other\");\n if (other !== undefined) ps.other = other;\n if (Object.keys(ps).length > 0) opts.paperSrc = ps;\n }\n\n // Printer settings\n const printerSettings = findChild(el, \"w:printerSettings\");\n if (printerSettings) {\n const rId = attr(printerSettings, \"r:id\");\n if (rId) opts.printerSettingsId = rId;\n }\n\n // Header/footer references\n const headerGroup: HeaderFooterGroup<HeaderFooterReference> = {};\n const footerGroup: HeaderFooterGroup<HeaderFooterReference> = {};\n for (const child of el.elements ?? []) {\n const type = attr(child, \"w:type\") as \"default\" | \"first\" | \"even\" | undefined;\n const rId = attr(child, \"r:id\");\n if (!type || !rId) continue;\n const referenceId = parseInt(rId.replace(\"rId\", \"\"), 10);\n if (child.name === \"w:headerReference\") {\n headerGroup[type] = { referenceId };\n } else if (child.name === \"w:footerReference\") {\n footerGroup[type] = { referenceId };\n }\n }\n if (Object.keys(headerGroup).length > 0) opts.headerWrapperGroup = headerGroup;\n if (Object.keys(footerGroup).length > 0) opts.footerWrapperGroup = footerGroup;\n\n // Revision (w:sectPrChange) — symmetric with stringifySectionPropertiesChange\n const sectPrChange = findChild(el, \"w:sectPrChange\");\n if (sectPrChange) {\n const rev: Partial<SectionPropertiesChangeOptions> = {};\n const author = attr(sectPrChange, \"w:author\");\n if (author) rev.author = author;\n const revDate = attr(sectPrChange, \"w:date\");\n if (revDate) rev.date = revDate;\n const revId = attrNum(sectPrChange, \"w:id\");\n if (revId !== undefined) rev.id = revId;\n const innerSectPr = findChild(sectPrChange, \"w:sectPr\");\n if (innerSectPr) Object.assign(rev, parseSectionPropertiesEl(innerSectPr));\n if (Object.keys(rev).length > 0) opts.revision = rev as SectionPropertiesChangeOptions;\n }\n\n return opts;\n}\n\nfunction parseNotePropertiesEl(el: Element): FootnotePropertiesOptions {\n const opts: FootnotePropertiesOptions = {};\n\n const posEl = findChild(el, \"w:pos\");\n if (posEl) {\n const val = attr(posEl, \"w:val\");\n if (val) opts.pos = val as FootnotePropertiesOptions[\"pos\"];\n }\n\n const numFmt = findChild(el, \"w:numFmt\");\n if (numFmt) {\n // CT_NumFmt: w:val (format type) + w:format (optional override).\n const fmt = attr(numFmt, \"w:val\");\n if (fmt) opts.formatType = fmt as FootnotePropertiesOptions[\"formatType\"];\n const format = attr(numFmt, \"w:format\");\n if (format) opts.format = format;\n }\n\n const numStart = findChild(el, \"w:numStart\");\n if (numStart) {\n const val = attrNum(numStart, \"w:val\");\n if (val !== undefined) opts.numStart = val;\n }\n\n const numRestart = findChild(el, \"w:numRestart\");\n if (numRestart) {\n const val = attr(numRestart, \"w:val\");\n if (val) opts.numRestart = val as FootnotePropertiesOptions[\"numRestart\"];\n }\n\n return opts;\n}\n","/**\n * Document attributes module for WordprocessingML documents.\n *\n * This module defines the XML namespace declarations used in OOXML documents.\n * These namespaces are required for proper document parsing and generation.\n *\n * Reference: http://officeopenxml.com/anatomyofOOXML.php\n *\n * @module\n */\n\n/**\n * XML namespace URIs used in WordprocessingML documents.\n *\n * These namespaces define the various XML schemas that can be referenced\n * in a document, including WordprocessingML, DrawingML, VML, and others.\n */\n/* CSpell:disable */\nexport const DocumentAttributeNamespaces = {\n aink: \"http://schemas.microsoft.com/office/drawing/2016/ink\",\n am3d: \"http://schemas.microsoft.com/office/drawing/2017/model3d\",\n cp: \"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\",\n cx: \"http://schemas.microsoft.com/office/drawing/2014/chartex\",\n cx1: \"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex\",\n cx2: \"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex\",\n cx3: \"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex\",\n cx4: \"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex\",\n cx5: \"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex\",\n cx6: \"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex\",\n cx7: \"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex\",\n cx8: \"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex\",\n dc: \"http://purl.org/dc/elements/1.1/\",\n dcmitype: \"http://purl.org/dc/dcmitype/\",\n dcterms: \"http://purl.org/dc/terms/\",\n m: \"http://schemas.openxmlformats.org/officeDocument/2006/math\",\n mc: \"http://schemas.openxmlformats.org/markup-compatibility/2006\",\n o: \"urn:schemas-microsoft-com:office:office\",\n r: \"http://schemas.openxmlformats.org/officeDocument/2006/relationships\",\n v: \"urn:schemas-microsoft-com:vml\",\n w: \"http://schemas.openxmlformats.org/wordprocessingml/2006/main\",\n w10: \"urn:schemas-microsoft-com:office:word\",\n w14: \"http://schemas.microsoft.com/office/word/2010/wordml\",\n w15: \"http://schemas.microsoft.com/office/word/2012/wordml\",\n w16: \"http://schemas.microsoft.com/office/word/2018/wordml\",\n w16cex: \"http://schemas.microsoft.com/office/word/2018/wordml/cex\",\n w16cid: \"http://schemas.microsoft.com/office/word/2016/wordml/cid\",\n w16sdtdh: \"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash\",\n w16se: \"http://schemas.microsoft.com/office/word/2015/wordml/symex\",\n wne: \"http://schemas.microsoft.com/office/word/2006/wordml\",\n wp: \"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\",\n wp14: \"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing\",\n wpc: \"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas\",\n wpg: \"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\",\n wpi: \"http://schemas.microsoft.com/office/word/2010/wordprocessingInk\",\n wps: \"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\",\n xsi: \"http://www.w3.org/2001/XMLSchema-instance\",\n};\n/* CSpell:enable */\n\n/**\n * Type representing valid namespace keys.\n */\nexport type DocumentAttributeNamespace = keyof typeof DocumentAttributeNamespaces;\n\n/**\n * Namespace-declaration attribute string for a WordprocessingML root element,\n * derived from the canonical {@link DocumentAttributeNamespaces} table. Key\n * order is preserved per call site so each part keeps its established byte\n * layout; the single table kills hand-copied URI drift between parts.\n */\nexport const documentNamespaceAttributes = (keys: readonly DocumentAttributeNamespace[]): string =>\n keys.map((key) => `xmlns:${key}=\"${DocumentAttributeNamespaces[key]}\"`).join(\" \");\n\n/**\n * Object form of {@link documentNamespaceAttributes} for element-builder\n * APIs that take an attributes record.\n */\nexport const documentNamespaceRecord = (\n keys: readonly DocumentAttributeNamespace[],\n): Record<string, string> =>\n Object.fromEntries(keys.map((key) => [`xmlns:${key}`, DocumentAttributeNamespaces[key]]));\n","import { Relationships, toUint8Array, uniqueUuid } from \"@office-open/core\";\n\n/**\n * Font Wrapper module for WordprocessingML documents.\n *\n * Manages font table relationships for embedded fonts.\n * Pure data container — no XmlComponent dependency.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_fonts.html\n *\n * @module\n */\nimport type { ViewWrapper } from \"../../context\";\nimport type { EmbeddedFontOptions } from \"./font-table\";\n\n/**\n * Font options extended with a unique font key.\n */\nexport type EmbeddedFontOptionsWithKey = EmbeddedFontOptions & {\n fontKey: string;\n /** Relationship id assigned to embedRegular (only fonts carrying data). */\n embedRid?: string;\n /** Normalized font bytes (Uint8Array regardless of the input form). */\n data?: Uint8Array;\n};\n\n/**\n * Wrapper class for managing embedded font relationships.\n *\n * Each embedded font is assigned a unique key for obfuscation.\n * The actual font table XML is generated by `fontTableDesc.stringify()`.\n *\n * @example\n * ```typescript\n * const fontWrapper = new FontWrapper([\n * { name: \"CustomFont\", data: fontBuffer }\n * ]);\n * ```\n */\nexport class FontWrapper implements ViewWrapper {\n public relationships: Relationships;\n public fontOptionsWithKey: EmbeddedFontOptionsWithKey[] = [];\n\n public constructor(public options: EmbeddedFontOptions[]) {\n // Keep every font declaration — metadata-only fonts (no `data`) carry no\n // bytes to embed but must still round-trip into fontTable.xml. Only fonts\n // with binary data receive a fontKey + relationship for the .odttf part.\n this.fontOptionsWithKey = options.map(\n (o): EmbeddedFontOptionsWithKey => ({\n ...o,\n data: o.data !== undefined ? toUint8Array(o.data) : undefined,\n fontKey: o.data !== undefined ? (o.fontKey ?? uniqueUuid()) : (o.fontKey ?? \"\"),\n }),\n );\n this.relationships = new Relationships();\n\n let relIdx = 0;\n for (const font of this.fontOptionsWithKey) {\n if (font.data === undefined) continue;\n relIdx++;\n font.embedRid = `rId${relIdx}`;\n const target = font.odttfPath\n ? font.odttfPath.startsWith(\"word/\")\n ? font.odttfPath.slice(5)\n : font.odttfPath\n : `fonts/${font.name}.odttf`;\n this.relationships.addRelationship(\n relIdx,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/font\",\n target,\n );\n }\n }\n}\n","/**\n * Structured Document Tag parser for DOCX documents.\n *\n * Parses w:sdt elements into SdtPropertiesOptions + children.\n *\n * @module\n */\nimport { attr, attrBool, attrNum, children, findChild, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type {\n SdtPropertiesOptions,\n SdtListItem,\n SdtDateOptions,\n SdtTextOptions,\n SdtComboBoxOptions,\n SdtDropDownListOptions,\n} from \"@parts/table-of-contents\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse w:sdtPr element into SdtPropertiesOptions.\n */\nexport function parseSdtProperties(el: Element): SdtPropertiesOptions {\n const opts: Record<string, unknown> = {};\n\n const alias = findChild(el, \"w:alias\");\n if (alias) opts.alias = attr(alias, \"w:val\");\n\n const tag = findChild(el, \"w:tag\");\n if (tag) {\n const val = attr(tag, \"w:val\");\n if (val) opts.tag = val;\n }\n\n const id = findChild(el, \"w:id\");\n if (id) {\n const val = attrNum(id, \"w:val\");\n if (val !== undefined) opts.id = val;\n }\n\n const lock = findChild(el, \"w:lock\");\n if (lock) {\n const val = attr(lock, \"w:val\");\n if (val) opts.lock = val as SdtPropertiesOptions[\"lock\"];\n }\n\n const temporary = findChild(el, \"w:temporary\");\n if (temporary) opts.temporary = attrBool(temporary, \"w:val\") ?? true;\n\n const showingPlcHdr = findChild(el, \"w:showingPlcHdr\");\n if (showingPlcHdr) opts.showingPlaceholder = attrBool(showingPlcHdr, \"w:val\") ?? true;\n\n const label = findChild(el, \"w:label\");\n if (label) {\n const val = attrNum(label, \"w:val\");\n if (val !== undefined) opts.label = val;\n }\n\n const tabIndex = findChild(el, \"w:tabIndex\");\n if (tabIndex) {\n const val = attrNum(tabIndex, \"w:val\");\n if (val !== undefined) opts.tabIndex = val;\n }\n\n // Data binding\n const dataBinding = findChild(el, \"w:dataBinding\");\n if (dataBinding) {\n opts.dataBinding = {\n xpath: attr(dataBinding, \"w:xpath\") ?? \"\",\n storeItemID: attr(dataBinding, \"w:storeItemID\") ?? \"\",\n prefixMappings: attr(dataBinding, \"w:prefixMappings\"),\n };\n }\n\n // Type discriminators (xsd:choice)\n if (findChild(el, \"w:equation\")) {\n opts.equation = true;\n } else if (findChild(el, \"w:comboBox\")) {\n const comboBox = findChild(el, \"w:comboBox\")!;\n const items: SdtListItem[] = [];\n for (const li of children(comboBox, \"w:listItem\")) {\n items.push({\n displayText: attr(li, \"w:displayText\"),\n value: attr(li, \"w:value\"),\n });\n }\n opts.comboBox = {\n items: items.length > 0 ? items : undefined,\n lastValue: attr(comboBox, \"w:lastValue\"),\n } as SdtComboBoxOptions;\n } else if (findChild(el, \"w:date\")) {\n const date = findChild(el, \"w:date\")!;\n const dateOpts: Record<string, unknown> = {};\n const dateFormat = findChild(date, \"w:dateFormat\");\n if (dateFormat) dateOpts.dateFormat = textOf(dateFormat);\n const lid = findChild(date, \"w:lid\");\n if (lid) dateOpts.languageId = textOf(lid);\n const storeMapped = findChild(date, \"w:storeMappedDataAs\");\n if (storeMapped) dateOpts.storeMappedDataAs = attr(storeMapped, \"w:val\");\n const calendar = findChild(date, \"w:calendar\");\n if (calendar) dateOpts.calendar = attr(calendar, \"w:val\");\n const fullDate = attr(date, \"w:fullDate\");\n if (fullDate) dateOpts.fullDate = fullDate;\n opts.date = dateOpts as SdtDateOptions;\n } else if (findChild(el, \"w:dropDownList\")) {\n const ddl = findChild(el, \"w:dropDownList\")!;\n const items: SdtListItem[] = [];\n for (const li of children(ddl, \"w:listItem\")) {\n items.push({\n displayText: attr(li, \"w:displayText\"),\n value: attr(li, \"w:value\"),\n });\n }\n opts.dropDownList = {\n items: items.length > 0 ? items : undefined,\n lastValue: attr(ddl, \"w:lastValue\"),\n } as SdtDropDownListOptions;\n } else if (findChild(el, \"w:picture\")) {\n opts.picture = true;\n } else if (findChild(el, \"w:richText\")) {\n opts.richText = true;\n } else if (findChild(el, \"w:text\")) {\n const text = findChild(el, \"w:text\")!;\n opts.text = {\n multiLine: attrBool(text, \"w:multiLine\"),\n } as SdtTextOptions;\n } else if (findChild(el, \"w:citation\")) {\n opts.citation = true;\n } else if (findChild(el, \"w:group\")) {\n opts.group = true;\n } else if (findChild(el, \"w:bibliography\")) {\n opts.bibliography = true;\n } else if (findChild(el, \"w:docPartObj\")) {\n const dp = findChild(el, \"w:docPartObj\")!;\n opts.docPartObj = {};\n const gallery = findChild(dp, \"w:docPartGallery\");\n if (gallery) (opts.docPartObj as Record<string, unknown>).gallery = attr(gallery, \"w:val\");\n const category = findChild(dp, \"w:docPartCategory\");\n if (category) (opts.docPartObj as Record<string, unknown>).category = attr(category, \"w:val\");\n } else if (findChild(el, \"w:docPartList\")) {\n const dp = findChild(el, \"w:docPartList\")!;\n opts.docPartList = {};\n const gallery = findChild(dp, \"w:docPartGallery\");\n if (gallery) (opts.docPartList as Record<string, unknown>).gallery = attr(gallery, \"w:val\");\n const category = findChild(dp, \"w:docPartCategory\");\n if (category) (opts.docPartList as Record<string, unknown>).category = attr(category, \"w:val\");\n } else if (findChild(el, \"w14:checkbox\")) {\n const cb = findChild(el, \"w14:checkbox\")!;\n const cbObj: Record<string, unknown> = {};\n const checked = findChild(cb, \"w14:checked\");\n if (checked) cbObj.checked = attrBool(checked, \"w14:val\") ?? true;\n const checkedState = findChild(cb, \"w14:checkedState\");\n if (checkedState)\n cbObj.checkedState = {\n val: attr(checkedState, \"w14:val\") ?? \"\",\n font: attr(checkedState, \"w14:font\"),\n };\n const uncheckedState = findChild(cb, \"w14:uncheckedState\");\n if (uncheckedState)\n cbObj.uncheckedState = {\n val: attr(uncheckedState, \"w14:val\") ?? \"\",\n font: attr(uncheckedState, \"w14:font\"),\n };\n opts.checkbox = cbObj;\n }\n\n return opts as SdtPropertiesOptions;\n}\n\n/**\n * Parse a block-level w:sdt element.\n * Returns an object suitable for the { sdt: ... } SectionChild variant.\n */\nexport function parseSdtBlock(\n el: Element,\n ctx: DocxReadContext,\n parseChildren: (elements: Element[], ctx: DocxReadContext) => unknown[],\n): {\n properties: SdtPropertiesOptions;\n children?: unknown[];\n} {\n const sdtPr = findChild(el, \"w:sdtPr\");\n const properties = sdtPr ? parseSdtProperties(sdtPr) : {};\n\n const sdtContent = findChild(el, \"w:sdtContent\");\n let childList: unknown[] | undefined;\n if (sdtContent) {\n childList = parseChildren(sdtContent.elements ?? [], ctx);\n if (childList.length === 0) childList = undefined;\n }\n\n return { properties, children: childList };\n}\n","/**\n * Table of Contents stringifier for DOCX.\n *\n * Produces `<w:sdt>` XML containing a TOC field code, replacing\n * `new TableOfContents(alias, options).toXml(ctx)` with direct\n * string concatenation — zero XmlComponent instances.\n *\n * @module\n */\n\nimport { escapeXml } from \"@office-open/xml\";\nimport type { TableOfContentsOptions } from \"@parts/table-of-contents/table-of-contents-properties\";\n\n// ── Field instruction string ──\n\nfunction tocInstructionStr(opts: TableOfContentsOptions): string {\n let instr = \"TOC\";\n\n if (opts.captionLabel) instr += ` \\\\a \"${opts.captionLabel}\"`;\n if (opts.entriesFromBookmark) instr += ` \\\\b \"${opts.entriesFromBookmark}\"`;\n if (opts.captionLabelIncludingNumbers) instr += ` \\\\c \"${opts.captionLabelIncludingNumbers}\"`;\n if (opts.sequenceAndPageNumbersSeparator)\n instr += ` \\\\d \"${opts.sequenceAndPageNumbersSeparator}\"`;\n if (opts.tcFieldIdentifier) instr += ` \\\\f \"${opts.tcFieldIdentifier}\"`;\n if (opts.hyperlink) instr += \" \\\\h\";\n if (opts.tcFieldLevelRange) instr += ` \\\\l \"${opts.tcFieldLevelRange}\"`;\n if (opts.pageNumbersEntryLevelsRange) instr += ` \\\\n \"${opts.pageNumbersEntryLevelsRange}\"`;\n if (opts.headingStyleRange) instr += ` \\\\o \"${opts.headingStyleRange}\"`;\n if (opts.entryAndPageNumberSeparator) instr += ` \\\\p \"${opts.entryAndPageNumberSeparator}\"`;\n if (opts.seqFieldIdentifierForPrefix) instr += ` \\\\s \"${opts.seqFieldIdentifierForPrefix}\"`;\n if (opts.stylesWithLevels?.length) {\n const styles = opts.stylesWithLevels.map((sl) => `${sl.styleName},${sl.level}`).join(\",\");\n instr += ` \\\\t \"${styles}\"`;\n }\n if (opts.useAppliedParagraphOutlineLevel) instr += \" \\\\u\";\n if (opts.preserveTabInEntries) instr += \" \\\\w\";\n if (opts.preserveNewLineInEntries) instr += \" \\\\x\";\n if (opts.hideTabAndPageNumbersInWebView) instr += \" \\\\z\";\n\n return instr;\n}\n\n// ── Main stringifier ──\n\nexport function stringifyTableOfContents(\n alias: string = \"Table of Contents\",\n options: TableOfContentsOptions = {},\n entriesXml: string = \"\",\n): string {\n const instr = tocInstructionStr(options);\n const aliasAttr = alias ? ` w:val=\"${escapeXml(alias)}\"` : \"\";\n\n // When the rendered entries are carried (round-trip), emit the field clean so\n // both MS Office and WPS display the existing TOC without an update prompt.\n // A freshly generated TOC carries no entries — mark it dirty so the consuming\n // application builds them from headings on open.\n const dirtyAttr = entriesXml.length > 0 ? \"\" : ' w:dirty=\"1\"';\n\n // Word shares the field-head control runs (begin/instr/separate) with the\n // first rendered entry's paragraph and the field-end run with the last,\n // rather than emitting standalone control-only paragraphs — those have no\n // w:t and render as blank lines above and below the TOC. So when entries are\n // carried we inject head into the first entry paragraph and end into the\n // last; a freshly generated TOC (no entries) keeps standalone head/end\n // paragraphs since it is dirty and rebuilt on open.\n const headRuns =\n `<w:r><w:rPr><w:rFonts w:asciiTheme=\"majorHAnsi\" w:cstheme=\"majorEastAsia\" w:hAnsiTheme=\"majorHAnsi\" w:cs=\"Times New Roman\"/></w:rPr><w:fldChar w:fldCharType=\"begin\"${dirtyAttr}/></w:r>` +\n `<w:r><w:instrText xml:space=\"preserve\"> ${instr} </w:instrText></w:r>` +\n `<w:r><w:fldChar w:fldCharType=\"separate\"/></w:r>`;\n const endRun = `<w:r><w:fldChar w:fldCharType=\"end\"/></w:r>`;\n const endParagraph = `<w:p>${endRun}</w:p>`;\n\n const body = entriesXml\n ? injectFieldEnd(injectFieldHead(entriesXml, headRuns), endRun)\n : `<w:p>${headRuns}</w:p>` + endParagraph;\n\n // SDT properties: alias + docPartObj\n const sdtPr =\n `<w:sdtPr>` +\n `<w:alias${aliasAttr}/>` +\n `<w:docPartObj><w:docPartGallery w:val=\"Table of Contents\"/></w:docPartObj>` +\n `</w:sdtPr>`;\n\n const content = `<w:sdtContent>${body}</w:sdtContent>`;\n\n return `<w:sdt>${sdtPr}${content}</w:sdt>`;\n}\n\n/**\n * Inject the field-head runs into the first `<w:p>` of `entriesXml`, placing\n * them after the opening tag (and after `<w:pPr>` when present) so the head\n * shares the first entry's paragraph. Returns `entriesXml` unchanged when no\n * `<w:p>` is found.\n */\nfunction injectFieldHead(entriesXml: string, headRuns: string): string {\n const pTagStart = entriesXml.search(/<w:p[ >]/);\n if (pTagStart < 0) return entriesXml;\n const pTagEnd = entriesXml.indexOf(\">\", pTagStart) + 1;\n let injectAt = pTagEnd;\n if (entriesXml.slice(pTagEnd, pTagEnd + 7) === \"<w:pPr>\") {\n const pPrEnd = entriesXml.indexOf(\"</w:pPr>\", pTagEnd);\n if (pPrEnd >= 0) injectAt = pPrEnd + \"</w:pPr>\".length;\n }\n return entriesXml.slice(0, injectAt) + headRuns + entriesXml.slice(injectAt);\n}\n\n/**\n * Inject the field-end run into the last `<w:p>` of `entriesXml` (before its\n * closing `</w:p>`) so the end shares the last entry's paragraph instead of\n * occupying a standalone control-only paragraph that renders as a blank line.\n * Returns `entriesXml` unchanged when no `</w:p>` is found.\n */\nfunction injectFieldEnd(entriesXml: string, endRun: string): string {\n const lastClose = entriesXml.lastIndexOf(\"</w:p>\");\n if (lastClose < 0) return entriesXml;\n return entriesXml.slice(0, lastClose) + endRun + entriesXml.slice(lastClose);\n}\n","/**\n * Direct XML string builders for Office MathML (OMML).\n *\n * Replaces `coerceMathInput()` + `new Math().toXml()` recursive class chain\n * with direct string concatenation — zero XmlComponent instances.\n *\n * Processes `MathInput` discriminated union directly to XML strings.\n *\n * @module\n */\n\nimport { parseOnOff } from \"@office-open/core\";\nimport { attr, children, escapeXml, findChild, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type {\n MathDelimiterProperties,\n MathInput,\n MathNaryProperties,\n MathRunPropertiesOptions,\n} from \"@parts/paragraph/math\";\n\n// ── MathRun properties ──\n\nfunction mathRunPropsStr(opts: MathRunPropertiesOptions): string {\n const parts: string[] = [];\n if (opts.lit) parts.push('<m:lit m:val=\"1\"/>');\n if (opts.normal) parts.push('<m:nor m:val=\"1\"/>');\n if (opts.script) parts.push(`<m:scr m:val=\"${opts.script}\"/>`);\n if (opts.style) parts.push(`<m:sty m:val=\"${opts.style}\"/>`);\n if (opts.breakAlignment) parts.push(`<m:brk m:alnAt=\"${opts.breakAlignment}\"/>`);\n if (opts.align) parts.push('<m:aln m:val=\"1\"/>');\n return parts.length ? `<m:rPr>${parts.join(\"\")}</m:rPr>` : \"\";\n}\n\n// ── Children array ──\n\nfunction stringifyChildren(items: MathInput[]): string {\n return items.map(stringifyMathInput).join(\"\");\n}\n\n// ── Main recursive stringifier ──\n\nexport function stringifyMathInput(value: MathInput): string {\n // String → MathRun shorthand\n if (typeof value === \"string\") {\n return `<m:r><m:t>${escapeXml(value)}</m:t></m:r>`;\n }\n\n // Class instances — still need toXml (shouldn't happen in compile/ JSON path)\n if (typeof value !== \"object\" || value === null) return \"\";\n\n // Discriminated union: check unique keys (order matters — subSuperScript first)\n if (\"subSuperScript\" in value) {\n const opts = value.subSuperScript;\n const pr = opts.alignScript\n ? '<m:sSubSupPr><m:alnScr m:val=\"1\"/></m:sSubSupPr>'\n : \"<m:sSubSupPr/>\";\n return `<m:sSubSup>${pr}<m:e>${stringifyChildren(opts.children)}</m:e><m:sub>${stringifyChildren(opts.subScript)}</m:sub><m:sup>${stringifyChildren(opts.superScript)}</m:sup></m:sSubSup>`;\n }\n\n if (\"preSubSuperScript\" in value) {\n const opts = value.preSubSuperScript;\n return `<m:sPre><m:sPrePr/><m:sub>${stringifyChildren(opts.subScript)}</m:sub><m:sup>${stringifyChildren(opts.superScript)}</m:sup><m:e>${stringifyChildren(opts.children)}</m:e></m:sPre>`;\n }\n\n if (\"superScript\" in value) {\n const opts = value.superScript;\n return `<m:sSup><m:sSupPr/><m:e>${stringifyChildren(opts.children)}</m:e><m:sup>${stringifyChildren(opts.superScript)}</m:sup></m:sSup>`;\n }\n\n if (\"subScript\" in value) {\n const opts = value.subScript;\n return `<m:sSub><m:sSubPr/><m:e>${stringifyChildren(opts.children)}</m:e><m:sub>${stringifyChildren(opts.subScript)}</m:sub></m:sSub>`;\n }\n\n if (\"fraction\" in value) {\n const opts = value.fraction;\n const pr = opts.fractionType ? `<m:fPr><m:type m:val=\"${opts.fractionType}\"/></m:fPr>` : \"\";\n const numArgPr = argPrXml(opts.numeratorArgumentSize);\n const denArgPr = argPrXml(opts.denominatorArgumentSize);\n return `<m:f>${pr}<m:num>${numArgPr}${stringifyChildren(opts.numerator)}</m:num><m:den>${denArgPr}${stringifyChildren(opts.denominator)}</m:den></m:f>`;\n }\n\n if (\"radical\" in value) {\n const opts = value.radical;\n const hasDegree = opts.degree && opts.degree.length > 0;\n const pr = !hasDegree ? '<m:radPr><m:degHide m:val=\"1\"/></m:radPr>' : \"<m:radPr/>\";\n const deg = hasDegree ? `<m:deg>${stringifyChildren(opts.degree!)}</m:deg>` : \"<m:deg/>\";\n return `<m:rad>${pr}${deg}<m:e>${stringifyChildren(opts.children)}</m:e></m:rad>`;\n }\n\n if (\"sum\" in value) {\n return stringifyNAry(value.sum, \"∑\");\n }\n\n if (\"integral\" in value) {\n return stringifyNAry(value.integral, \"∫\");\n }\n\n if (\"limitLower\" in value) {\n const opts = value.limitLower;\n return `<m:limLow><m:e>${stringifyChildren(opts.children)}</m:e><m:lim>${stringifyChildren(opts.limit)}</m:lim></m:limLow>`;\n }\n\n if (\"limitUpper\" in value) {\n const opts = value.limitUpper;\n return `<m:limUpp><m:e>${stringifyChildren(opts.children)}</m:e><m:lim>${stringifyChildren(opts.limit)}</m:lim></m:limUpp>`;\n }\n\n if (\"function\" in value) {\n const opts = value.function;\n return `<m:func><m:fName>${stringifyChildren(opts.name)}</m:fName><m:e>${stringifyChildren(opts.children)}</m:e></m:func>`;\n }\n\n if (\"matrix\" in value) {\n const opts = value.matrix;\n const rows = opts.rows\n .map(\n (row) =>\n `<m:mr>${row.map((cell) => `<m:e>${stringifyMathInput(cell)}</m:e>`).join(\"\")}</m:mr>`,\n )\n .join(\"\");\n // Matrix properties are complex — emit basic structure only when needed\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const prParts: string[] = [];\n if (p.baseJc) prParts.push(`<m:baseJc m:val=\"${p.baseJc as string}\"/>`);\n if (p.plcHide) prParts.push('<m:plcHide m:val=\"1\"/>');\n if (p.rSpRule) prParts.push(`<m:rSpRule m:val=\"${p.rSpRule as string}\"/>`);\n if (p.cGpRule) prParts.push(`<m:cGpRule m:val=\"${p.cGpRule as string}\"/>`);\n if (p.rSp) prParts.push(`<m:rSp m:val=\"${p.rSp as string}\"/>`);\n if (p.cSp) prParts.push(`<m:cSp m:val=\"${p.cSp as string}\"/>`);\n if (p.cGp) prParts.push(`<m:cGp m:val=\"${p.cGp as string}\"/>`);\n if (p.mcs) {\n const mcItems = (p.mcs as Array<{ count: number; mcJc: string }>)\n .map(\n (mc) =>\n `<m:mc><m:mcPr><m:count m:val=\"${mc.count}\"/><m:mcJc m:val=\"${mc.mcJc}\"/></m:mcPr></m:mc>`,\n )\n .join(\"\");\n prParts.push(`<m:mcs>${mcItems}</m:mcs>`);\n }\n if (prParts.length) pr = `<m:mPr>${prParts.join(\"\")}</m:mPr>`;\n }\n return `<m:m>${pr}${rows}</m:m>`;\n }\n\n // Bracket types\n if (\"roundBrackets\" in value) {\n const spec = bracketSpec(value.roundBrackets);\n return stringifyDelimiters(spec.children, \"(\", \")\", spec.properties);\n }\n if (\"curlyBrackets\" in value) {\n const spec = bracketSpec(value.curlyBrackets);\n return stringifyDelimiters(spec.children, \"{\", \"}\", spec.properties);\n }\n if (\"angledBrackets\" in value) {\n const spec = bracketSpec(value.angledBrackets);\n return stringifyDelimiters(spec.children, \"〈\", \"〉\", spec.properties);\n }\n if (\"squareBrackets\" in value) {\n const spec = bracketSpec(value.squareBrackets);\n return stringifyDelimiters(spec.children, \"[\", \"]\", spec.properties);\n }\n\n if (\"borderBox\" in value) {\n const opts = value.borderBox;\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const parts: string[] = [];\n if (p.hideTop) parts.push('<m:hideTop m:val=\"1\"/>');\n if (p.hideBottom) parts.push('<m:hideBot m:val=\"1\"/>');\n if (p.hideLeft) parts.push('<m:hideLeft m:val=\"1\"/>');\n if (p.hideRight) parts.push('<m:hideRight m:val=\"1\"/>');\n if (p.strikeHorizontal) parts.push('<m:strikeH m:val=\"1\"/>');\n if (p.strikeVertical) parts.push('<m:strikeV m:val=\"1\"/>');\n if (p.strikeDiagonalUp) parts.push('<m:strikeBLTR m:val=\"1\"/>');\n if (p.strikeDiagonalDown) parts.push('<m:strikeTLBR m:val=\"1\"/>');\n if (parts.length) pr = `<m:borderBoxPr>${parts.join(\"\")}</m:borderBoxPr>`;\n }\n return `<m:borderBox>${pr}<m:e>${stringifyChildren(opts.children)}</m:e></m:borderBox>`;\n }\n\n if (\"box\" in value) {\n const opts = value.box;\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const parts: string[] = [];\n if (p.opEmu) parts.push('<m:opEmu m:val=\"1\"/>');\n if (p.noBreak) parts.push('<m:noBreak m:val=\"1\"/>');\n if (p.diff) parts.push('<m:diff m:val=\"1\"/>');\n if (p.aln) parts.push('<m:aln m:val=\"1\"/>');\n if (parts.length) pr = `<m:boxPr>${parts.join(\"\")}</m:boxPr>`;\n }\n return `<m:box>${pr}<m:e>${stringifyChildren(opts.children)}</m:e></m:box>`;\n }\n\n if (\"groupChr\" in value) {\n const opts = value.groupChr;\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const parts: string[] = [];\n if (p.chr) parts.push(`<m:chr m:val=\"${p.chr as string}\"/>`);\n if (p.pos) parts.push(`<m:pos m:val=\"${p.pos as string}\"/>`);\n if (p.vertJc) parts.push(`<m:vertJc m:val=\"${p.vertJc as string}\"/>`);\n if (parts.length) pr = `<m:groupChrPr>${parts.join(\"\")}</m:groupChrPr>`;\n }\n return `<m:groupChr>${pr}<m:e>${stringifyChildren(opts.children)}</m:e></m:groupChr>`;\n }\n\n if (\"phant\" in value) {\n const opts = value.phant;\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const parts: string[] = [];\n if (p.show !== undefined) parts.push(`<m:show m:val=\"${p.show ? 1 : 0}\"/>`);\n if (p.zeroWid) parts.push('<m:zeroWid m:val=\"1\"/>');\n if (p.zeroAsc) parts.push('<m:zeroAsc m:val=\"1\"/>');\n if (p.zeroDesc) parts.push('<m:zeroDesc m:val=\"1\"/>');\n if (p.transp) parts.push('<m:transp m:val=\"1\"/>');\n if (parts.length) pr = `<m:phantPr>${parts.join(\"\")}</m:phantPr>`;\n }\n return `<m:phant>${pr}<m:e>${stringifyChildren(opts.children)}</m:e></m:phant>`;\n }\n\n if (\"eqArr\" in value) {\n const opts = value.eqArr;\n let pr = \"\";\n if (opts.properties) {\n const p = opts.properties;\n const parts: string[] = [];\n if (p.baseJc) parts.push(`<m:baseJc m:val=\"${p.baseJc as string}\"/>`);\n if (p.maxDist) parts.push('<m:maxDist m:val=\"1\"/>');\n if (p.objDist) parts.push('<m:objDist m:val=\"1\"/>');\n if (p.rSpRule) parts.push(`<m:rSpRule m:val=\"${p.rSpRule as string}\"/>`);\n if (p.rSp) parts.push(`<m:rSp m:val=\"${p.rSp as string}\"/>`);\n if (parts.length) pr = `<m:eqArrPr>${parts.join(\"\")}</m:eqArrPr>`;\n }\n const rows = opts.rows.map((row) => `<m:e>${stringifyChildren(row)}</m:e>`).join(\"\");\n return `<m:eqArr>${pr}${rows}</m:eqArr>`;\n }\n\n if (\"accent\" in value) {\n const opts = value.accent;\n const pr = opts.accentCharacter\n ? `<m:accPr><m:chr m:val=\"${opts.accentCharacter}\"/></m:accPr>`\n : \"\";\n return `<m:acc>${pr}<m:e>${stringifyChildren(opts.children)}</m:e></m:acc>`;\n }\n\n if (\"bar\" in value) {\n const opts = value.bar;\n return `<m:bar><m:barPr><m:pos m:val=\"${opts.type}\"/></m:barPr><m:e>${stringifyChildren(opts.children)}</m:e></m:bar>`;\n }\n\n // Fallback: { text: string; properties?: ... } → MathRun\n if (\"text\" in value) {\n const props = value.properties ? mathRunPropsStr(value.properties) : \"\";\n return `<m:r>${props}<m:t>${escapeXml(value.text)}</m:t></m:r>`;\n }\n\n return \"\";\n}\n\n// ── N-ary operator (sum/integral) ──\n\nfunction stringifyNAry(\n opts: {\n children: MathInput[];\n subScript?: MathInput[];\n superScript?: MathInput[];\n properties?: MathNaryProperties;\n },\n chr: string,\n): string {\n const hasSub = opts.subScript && opts.subScript.length > 0;\n const hasSup = opts.superScript && opts.superScript.length > 0;\n const prParts: string[] = [`<m:chr m:val=\"${chr}\"/>`];\n if (opts.properties?.limitLocation)\n prParts.push(`<m:limLoc m:val=\"${opts.properties.limitLocation}\"/>`);\n if (opts.properties?.grow !== undefined)\n prParts.push(`<m:grow m:val=\"${opts.properties.grow ? 1 : 0}\"/>`);\n if (!hasSub) prParts.push('<m:subHide m:val=\"1\"/>');\n if (!hasSup) prParts.push('<m:supHide m:val=\"1\"/>');\n const pr = `<m:naryPr>${prParts.join(\"\")}</m:naryPr>`;\n const sub = hasSub ? `<m:sub>${stringifyChildren(opts.subScript!)}</m:sub>` : \"<m:sub/>\";\n const sup = hasSup ? `<m:sup>${stringifyChildren(opts.superScript!)}</m:sup>` : \"<m:sup/>\";\n return `<m:nary>${pr}${sub}${sup}<m:e>${stringifyChildren(opts.children)}</m:e></m:nary>`;\n}\n\n// ── Delimiters (brackets) ──\n\nfunction stringifyDelimiters(\n children: MathInput[],\n begChr: string,\n endChr: string,\n properties?: MathDelimiterProperties,\n): string {\n const prParts: string[] = [`<m:begChr m:val=\"${properties?.beginCharacter ?? begChr}\"/>`];\n if (properties?.separatorCharacter)\n prParts.push(`<m:sepChr m:val=\"${properties.separatorCharacter}\"/>`);\n prParts.push(`<m:endChr m:val=\"${properties?.endCharacter ?? endChr}\"/>`);\n if (properties?.grow !== undefined) prParts.push(`<m:grow m:val=\"${properties.grow ? 1 : 0}\"/>`);\n if (properties?.shape) prParts.push(`<m:shp m:val=\"${properties.shape}\"/>`);\n return `<m:d><m:dPr>${prParts.join(\"\")}</m:dPr><m:e>${stringifyChildren(children)}</m:e></m:d>`;\n}\n\n/** Build an m:argPr/m:argSz block for an argument size scaling value. */\nfunction argPrXml(size: number | undefined): string {\n return size !== undefined ? `<m:argPr><m:argSz m:val=\"${size}\"/></m:argPr>` : \"\";\n}\n\n/** Split a bracket shorthand into children + optional delimiter properties. */\nfunction bracketSpec(\n v: MathInput[] | { children: MathInput[]; properties?: MathDelimiterProperties },\n): {\n children: MathInput[];\n properties?: MathDelimiterProperties;\n} {\n if (Array.isArray(v)) return { children: v };\n return { children: v.children, properties: v.properties };\n}\n\n// ── Top-level Math wrapper ──\n\nexport function stringifyMath(children: MathInput[]): string {\n const inner = children.map((c) => stringifyMathInput(c)).join(\"\");\n return `<m:oMath>${inner}</m:oMath>`;\n}\n\nexport function stringifyMathParagraph(\n children: MathInput[],\n justification?: \"left\" | \"right\" | \"center\" | \"centerGroup\",\n): string {\n const inner = children.map((c) => stringifyMathInput(c)).join(\"\");\n const pr = justification ? `<m:oMathParaPr><m:jc m:val=\"${justification}\"/></m:oMathParaPr>` : \"\";\n return `<m:oMathPara>${pr}<m:oMath>${inner}</m:oMath></m:oMathPara>`;\n}\n\n// ────────────────────────────────────────────────────────────────────────────────\n// Parse (OMML XML → MathInput)\n// ────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse all math children from an m:oMath (or similar container) element.\n */\nexport function parseMathChildren(el: Element): MathInput[] {\n const result: MathInput[] = [];\n for (const child of el.elements ?? []) {\n const parsed = parseMathElement(child);\n if (parsed !== undefined) result.push(parsed);\n }\n return result;\n}\n\nfunction parseMathElement(el: Element): MathInput | undefined {\n switch (el.name) {\n case \"m:r\":\n return parseMathRun(el);\n case \"m:f\":\n return parseMathFraction(el);\n case \"m:rad\":\n return parseMathRadical(el);\n case \"m:sSup\":\n return parseMathSuperScript(el);\n case \"m:sSub\":\n return parseMathSubScript(el);\n case \"m:sSubSup\":\n return parseMathSubSuperScript(el);\n case \"m:nary\":\n return parseMathNAry(el);\n case \"m:func\":\n return parseMathFunction(el);\n case \"m:d\":\n return parseMathDelimiter(el);\n case \"m:m\":\n return parseMathMatrix(el);\n case \"m:acc\":\n return parseMathAccent(el);\n case \"m:bar\":\n return parseMathBar(el);\n case \"m:borderBox\":\n return { borderBox: { children: parseMathArg(el, \"m:e\") } };\n case \"m:box\":\n return { box: { children: parseMathArg(el, \"m:e\") } };\n case \"m:groupChr\":\n return { groupChr: { children: parseMathArg(el, \"m:e\") } };\n case \"m:phant\":\n return { phant: { children: parseMathArg(el, \"m:e\") } };\n case \"m:eqArr\":\n return parseMathEqArr(el);\n case \"m:limLow\":\n return parseMathLimitLower(el);\n case \"m:limUpp\":\n return parseMathLimitUpper(el);\n // Property elements — not standalone content\n case \"m:rPr\":\n case \"m:fPr\":\n case \"m:radPr\":\n case \"m:sSupPr\":\n case \"m:sSubPr\":\n case \"m:sSubSupPr\":\n case \"m:naryPr\":\n case \"m:funcPr\":\n case \"m:dPr\":\n case \"m:mPr\":\n case \"m:accPr\":\n case \"m:barPr\":\n case \"m:borderBoxPr\":\n case \"m:boxPr\":\n case \"m:groupChrPr\":\n case \"m:phantPr\":\n case \"m:eqArrPr\":\n case \"m:limLowPr\":\n case \"m:limUppPr\":\n case \"m:ctrlPr\":\n return undefined;\n default:\n return undefined;\n }\n}\n\nfunction parseMathRun(el: Element): MathInput {\n const text = textOf(findChild(el, \"m:t\"));\n return text ?? \"\";\n}\n\n// ── Parse helpers ──\n\n/** Read an m:val on/off attribute (1/0/true/false; empty element = on). */\nfunction readOnOff(el: Element | undefined): boolean | undefined {\n if (!el) return undefined;\n const v = attr(el, \"m:val\");\n return parseOnOff(v) ?? true;\n}\n\n/** Read an m:val numeric attribute. */\nfunction readNum(el: Element | undefined): number | undefined {\n if (!el) return undefined;\n const v = attr(el, \"m:val\");\n if (v === undefined || v === \"\") return undefined;\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n}\n\n/** Read an m:argSz scaling value from an m:argPr-bearing argument element. */\nfunction readArgSize(argEl: Element | undefined): number | undefined {\n if (!argEl) return undefined;\n return readNum(findChild(argEl, \"m:argSz\"));\n}\n\nfunction parseMathFraction(el: Element): MathInput {\n const numeratorArgumentSize = readArgSize(findChild(el, \"m:num\"));\n const denominatorArgumentSize = readArgSize(findChild(el, \"m:den\"));\n return {\n fraction: {\n numerator: parseMathArg(el, \"m:num\"),\n denominator: parseMathArg(el, \"m:den\"),\n ...(numeratorArgumentSize !== undefined ? { numeratorArgumentSize } : {}),\n ...(denominatorArgumentSize !== undefined ? { denominatorArgumentSize } : {}),\n },\n };\n}\n\nfunction parseMathRadical(el: Element): MathInput {\n const degree = parseMathArg(el, \"m:deg\");\n const mathChildren = parseMathArg(el, \"m:e\");\n return {\n radical: {\n children: mathChildren,\n ...(degree.length > 0 ? { degree } : {}),\n },\n };\n}\n\nfunction parseMathSuperScript(el: Element): MathInput {\n return {\n superScript: {\n children: parseMathArg(el, \"m:e\"),\n superScript: parseMathArg(el, \"m:sup\"),\n },\n };\n}\n\nfunction parseMathSubScript(el: Element): MathInput {\n return {\n subScript: {\n children: parseMathArg(el, \"m:e\"),\n subScript: parseMathArg(el, \"m:sub\"),\n },\n };\n}\n\nfunction parseMathSubSuperScript(el: Element): MathInput {\n const pr = findChild(el, \"m:sSubSupPr\");\n const alignScript = pr ? readOnOff(findChild(pr, \"m:alnScr\")) : undefined;\n return {\n subSuperScript: {\n children: parseMathArg(el, \"m:e\"),\n subScript: parseMathArg(el, \"m:sub\"),\n superScript: parseMathArg(el, \"m:sup\"),\n ...(alignScript !== undefined ? { alignScript } : {}),\n },\n };\n}\n\nfunction parseMathNAry(el: Element): MathInput {\n const naryPr = findChild(el, \"m:naryPr\");\n const chrEl = naryPr ? findChild(naryPr, \"m:chr\") : undefined;\n const chrVal = chrEl ? attr(chrEl, \"m:val\") : undefined;\n\n const baseChildren = parseMathArg(el, \"m:e\");\n const sub = parseMathArg(el, \"m:sub\");\n const sup = parseMathArg(el, \"m:sup\");\n\n const properties: MathNaryProperties = {};\n if (naryPr) {\n const limLocEl = findChild(naryPr, \"m:limLoc\");\n if (limLocEl) {\n const limLoc = attr(limLocEl, \"m:val\");\n if (limLoc === \"subSup\" || limLoc === \"undOvr\") properties.limitLocation = limLoc;\n }\n const grow = readOnOff(findChild(naryPr, \"m:grow\"));\n if (grow !== undefined) properties.grow = grow;\n }\n\n const common = {\n children: baseChildren,\n ...(sub.length > 0 ? { subScript: sub } : {}),\n ...(sup.length > 0 ? { superScript: sup } : {}),\n ...(Object.keys(properties).length > 0 ? { properties } : {}),\n };\n\n if (chrVal === \"∑\") return { sum: common };\n return { integral: common };\n}\n\nfunction parseMathFunction(el: Element): MathInput {\n return {\n function: {\n name: parseMathArg(el, \"m:fName\"),\n children: parseMathArg(el, \"m:e\"),\n },\n };\n}\n\nfunction parseMathDelimiter(el: Element): MathInput {\n const dPr = findChild(el, \"m:dPr\");\n const begChrEl = dPr ? findChild(dPr, \"m:begChr\") : undefined;\n const begChr = begChrEl ? attr(begChrEl, \"m:val\") : \"(\";\n const mathChildren = parseMathArg(el, \"m:e\");\n\n // Collect delimiter properties when present (sepChr/grow/shp/non-default chars).\n const properties: MathDelimiterProperties = {};\n if (dPr) {\n if (begChrEl) properties.beginCharacter = begChr;\n const endChrEl = findChild(dPr, \"m:endChr\");\n if (endChrEl) properties.endCharacter = attr(endChrEl, \"m:val\");\n const sepChrEl = findChild(dPr, \"m:sepChr\");\n if (sepChrEl) properties.separatorCharacter = attr(sepChrEl, \"m:val\");\n const grow = readOnOff(findChild(dPr, \"m:grow\"));\n if (grow !== undefined) properties.grow = grow;\n const shpEl = findChild(dPr, \"m:shp\");\n if (shpEl) {\n const shp = attr(shpEl, \"m:val\");\n if (shp === \"centered\" || shp === \"match\") properties.shape = shp;\n }\n }\n const hasProperties = Object.keys(properties).length > 0;\n const value = hasProperties ? { children: mathChildren, properties } : mathChildren;\n\n switch (begChr) {\n case \"[\":\n return { squareBrackets: value };\n case \"{\":\n return { curlyBrackets: value };\n case \"<\":\n case \"⟨\":\n return { angledBrackets: value };\n default:\n return { roundBrackets: value };\n }\n}\n\nfunction parseMathMatrix(el: Element): MathInput {\n const rows: MathInput[][] = [];\n for (const mr of children(el, \"m:mr\")) {\n rows.push(parseMathArg(mr, \"m:e\"));\n }\n return { matrix: { rows } };\n}\n\nfunction parseMathAccent(el: Element): MathInput {\n const accPr = findChild(el, \"m:accPr\");\n const chrEl = accPr ? findChild(accPr, \"m:chr\") : undefined;\n const accentChar = chrEl ? attr(chrEl, \"m:val\") : undefined;\n\n return {\n accent: {\n children: parseMathArg(el, \"m:e\"),\n ...(accentChar ? { accentCharacter: accentChar } : {}),\n },\n };\n}\n\nfunction parseMathBar(el: Element): MathInput {\n const barPr = findChild(el, \"m:barPr\");\n const posEl = barPr ? findChild(barPr, \"m:pos\") : undefined;\n const pos = posEl ? attr(posEl, \"m:val\") : \"top\";\n\n return {\n bar: {\n children: parseMathArg(el, \"m:e\"),\n type: (pos as \"top\" | \"bot\") ?? \"top\",\n },\n };\n}\n\nfunction parseMathEqArr(el: Element): MathInput {\n const rows: MathInput[][] = [];\n for (const e of children(el, \"m:e\")) {\n rows.push(parseMathChildren(e));\n }\n return { eqArr: { rows } };\n}\n\nfunction parseMathLimitLower(el: Element): MathInput {\n return {\n limitLower: {\n children: parseMathArg(el, \"m:e\"),\n limit: parseMathArg(el, \"m:lim\"),\n },\n };\n}\n\nfunction parseMathLimitUpper(el: Element): MathInput {\n return {\n limitUpper: {\n children: parseMathArg(el, \"m:e\"),\n limit: parseMathArg(el, \"m:lim\"),\n },\n };\n}\n\nfunction parseMathArg(parent: Element, childName: string): MathInput[] {\n const container = findChild(parent, childName);\n if (!container) return [];\n return parseMathChildren(container);\n}\n","/**\n * Replace relationship references in raw XML with `{fileName}` placeholders.\n *\n * Raw-XML passthrough paths (document background, mc:AlternateContent VML\n * fallback) carry VML/structured content verbatim. Their r:id / r:embed /\n * r:link references must be replaced with `{fileName}` placeholders and the\n * referenced media collected, so the compiler's placeholder pass registers the\n * media and resolves the placeholders into relationship ids. Otherwise the\n * carried source rIds dangle — they are not defined in the generated rels and\n * Word rejects the package as unreadable.\n */\nimport type { DocxReadContext } from \"../context\";\nimport type { BackgroundRawMediaOptions } from \"../parts/document/document-background/document-background\";\nimport { imageTypeFromPath } from \"../parts/drawing/drawing-parse\";\n\nconst REL_ATTR_RE = /\\br:(id|embed|link)=\"([^\"]+)\"/g;\n\nexport function replaceRelsWithPlaceholders(\n xml: string,\n ctx: DocxReadContext,\n prefix: string,\n): { rawXml: string; rawMedia: BackgroundRawMediaOptions[] } {\n const rawMedia: BackgroundRawMediaOptions[] = [];\n const rawXml = xml.replace(REL_ATTR_RE, (match, attrName: string, rId: string) => {\n const mediaPath = ctx.resolveRelationship(rId);\n const data = mediaPath ? ctx.getRaw(mediaPath) : undefined;\n if (!mediaPath || !data) return match;\n const type = imageTypeFromPath(mediaPath);\n const fileName = `${prefix}-${rId}.${type}`;\n if (!rawMedia.some((m) => m.fileName === fileName)) {\n rawMedia.push({ fileName, data, type });\n }\n return `r:${attrName}=\"{${fileName}}\"`;\n });\n return { rawXml, rawMedia };\n}\n","/**\n * Body-level stringification for DOCX documents.\n *\n * Converts pure JSON options to XML strings for document body content.\n * Pure string concatenation — no intermediate object tree.\n *\n * @module\n */\n\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport { hexColorValue, uCharHexNumber } from \"@office-open/core\";\nimport { ThemeColor } from \"@office-open/core\";\nimport { stringifyVmlShape } from \"@office-open/core\";\nimport { stringifyVmlBackground } from \"@office-open/core\";\nimport { nextVmlShapeId } from \"@office-open/core\";\nimport type { VmlShapeStyle } from \"@office-open/core\";\nimport {\n attr,\n attrBool,\n attrMeasure,\n attrNum,\n escapeXml,\n findChild,\n textOf,\n} from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { sectionPropertiesDesc } from \"@parts/document/body/section-properties/descriptor\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport type {\n BackgroundRawMediaOptions,\n DocumentBackgroundOptions,\n} from \"@parts/document/document-background\";\nimport { parseDrawingRun } from \"@parts/drawing/drawing-parse\";\nimport { FontWrapper } from \"@parts/fonts/font-wrapper\";\nimport { objectDesc, type ObjectElementOptions } from \"@parts/object\";\nimport type { BordersOptions } from \"@parts/paragraph/formatting/border\";\nimport type { IndentProperties } from \"@parts/paragraph/formatting/indent\";\nimport { LineRuleType } from \"@parts/paragraph/formatting/spacing\";\nimport type { SpacingProperties } from \"@parts/paragraph/formatting/spacing\";\nimport { HeadingLevel } from \"@parts/paragraph/formatting/style\";\nimport type { TabStopDefinition } from \"@parts/paragraph/formatting/tab-stop\";\nimport type { FrameOptions } from \"@parts/paragraph/frame/frame-properties\";\nimport type {\n MarkupRangeOptions,\n BookmarkStartOptions,\n MoveRangeStartOptions,\n} from \"@parts/paragraph/links/bookmark\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type {\n ParagraphPropertiesOptions,\n ParagraphPropertiesChangeOptions,\n} from \"@parts/paragraph/properties\";\nimport { parseFormFieldData } from \"@parts/paragraph/run/form-field\";\nimport type { FormFieldOptions } from \"@parts/paragraph/run/form-field\";\nimport type { RubyOptions } from \"@parts/paragraph/run/ruby\";\nimport {\n breakXml,\n EMPTY_RUN_ELEMENTS,\n type BreakOptions,\n type RunOptions,\n} from \"@parts/paragraph/run/run\";\nimport { parseRun, parseRunProperties, parsedRunToOptions } from \"@parts/paragraph/run/run-parse\";\nimport { parseSdtProperties } from \"@parts/sdt/sdt-parse\";\nimport { stringifyTableOfContents } from \"@parts/table-of-contents/descriptor\";\nimport type { BorderOptions } from \"@shared/border\";\nimport { BorderStyle } from \"@shared/border\";\nimport type { MediaData } from \"@shared/media/data\";\nimport type { SectionChild } from \"@shared/section\";\nimport { parseShading } from \"@shared/shading\";\n\nimport type { DocxReadContext, DocxWriteContext, BodyContext } from \"./context\";\nimport { tableDesc, altChunkDesc, subDocDesc, sdtBlockDesc, customXmlBlockDesc } from \"./parts\";\nimport { parseCustomXmlProperties } from \"./parts/bodychildren\";\nimport { stringifyChildDispatch } from \"./parts/inline\";\nimport { parseMathChildren } from \"./parts/paragraph/math/stringify\";\nimport type { ParagraphChild, SdtRunOptions } from \"./parts/paragraph/paragraph\";\nimport {\n EMPTY_PPR_RESULT,\n stringifyParagraphProperties,\n stringifyRunProperties,\n} from \"./parts/paragraph/stringify\";\nimport { replaceRelsWithPlaceholders } from \"./util/replace-media-placeholders\";\nimport { stringifyElement } from \"./util/stringify-element\";\n\nexport type { BodyContext } from \"./context\";\n\n// ── Run ──\n\n/**\n * Stringify a run (w:r) from pure JSON options.\n *\n * Handles text, children, breaks, and run properties.\n */\nexport function stringifyRun(opts: RunOptions, ctx: BodyContext): string {\n let body = \"\";\n\n // Pre-scan children for commentReference — needs CommentReference style in rPr\n let commentRefStyle = false;\n if (opts.children) {\n for (const child of opts.children) {\n if (typeof child === \"object\" && child !== null && \"commentReference\" in child) {\n commentRefStyle = true;\n break;\n }\n }\n }\n\n // Run properties — inject CommentReference style if needed\n const runOpts = commentRefStyle ? { ...opts, style: \"CommentReference\" as const } : opts;\n const rPr = stringifyRunProperties(runOpts);\n if (rPr) body += rPr;\n\n // Breaks (w:br) — count shorthand or structured with clear (CT_Br)\n if (opts.break) {\n body += breakXml(opts.break);\n }\n\n // Children or text\n if (opts.children) {\n for (const child of opts.children) {\n if (typeof child === \"string\") {\n // Simple text string — direct output\n body += `<w:t xml:space=\"preserve\">${escapeXml(child)}</w:t>`;\n } else if (typeof child === \"object\" && child !== null) {\n // Simple run-level elements — bare content, no <w:r> wrapper\n if (\"tab\" in child) {\n body += \"<w:tab/>\";\n continue;\n }\n if (\"pageBreak\" in child) {\n body += '<w:br w:type=\"page\"/>';\n continue;\n }\n if (\"columnBreak\" in child) {\n body += '<w:br w:type=\"column\"/>';\n continue;\n }\n if (\"break\" in child) {\n body += breakXml((child as { break: number | BreakOptions }).break);\n continue;\n }\n if (\"commentReference\" in child) {\n body += `<w:commentReference w:id=\"${Number(child.commentReference)}\"/>`;\n continue;\n }\n\n // Empty run elements — self-closing XML with no attributes\n // { noBreakHyphen: true } → <w:noBreakHyphen/>, etc.\n const emptyXml = EMPTY_RUN_ELEMENTS[Object.keys(child)[0] ?? \"\"];\n if (emptyXml) {\n body += emptyXml;\n continue;\n }\n\n // OLE object — w:object (VML shape + objectEmbed/link/control/movie)\n if (\"object\" in child) {\n // RunOptions.children carries Record<string, unknown>, so `in`\n // narrows to unknown — cast back to the object variant payload.\n body +=\n objectDesc.stringify((child as { object: ObjectElementOptions }).object, ctx) ?? \"\";\n continue;\n }\n\n // JSON child dispatch (images, charts, etc.)\n const jsonResult = stringifyChildDispatch(child as ParagraphChild, ctx);\n if (jsonResult !== undefined) {\n body += Array.isArray(jsonResult) ? jsonResult.join(\"\") : jsonResult;\n } else {\n // Fallback: treat as an object-tree-like value — should not happen in JSON path\n throw new Error(`Unsupported run child type: ${Object.keys(child).join(\", \")}`);\n }\n }\n }\n } else if (opts.text !== undefined) {\n body += `<w:t xml:space=\"preserve\">${escapeXml(String(opts.text))}</w:t>`;\n }\n\n // rsid attributes on <w:r>\n let attr = \"\";\n if (opts.rsid) attr += ` w:rsidR=\"${opts.rsid}\"`;\n if (opts.runPropertiesRsid) attr += ` w:rsidRPr=\"${opts.runPropertiesRsid}\"`;\n if (opts.deletionRsid) attr += ` w:rsidDel=\"${opts.deletionRsid}\"`;\n\n return body.length === 0 ? (attr ? `<w:r${attr}/>` : \"<w:r/>\") : `<w:r${attr}>${body}</w:r>`;\n}\n\n// ── Paragraph ──\n\n/**\n * Stringify a paragraph (w:p) from pure JSON options or string.\n *\n * Handles paragraph properties, numbering registration, and run children.\n */\nexport function stringifyParagraph(\n opts: string | ParagraphOptions,\n ctx: BodyContext,\n sectionPropertiesXml?: string,\n): string {\n const isPlainText = typeof opts === \"string\";\n const resolved: ParagraphOptions = isPlainText ? { text: opts } : opts;\n let body = \"\";\n\n // Build paragraph properties — direct string output, no intermediate object tree.\n // A string paragraph is `{ text }` by construction: no pPr fields, no numbering.\n const props = isPlainText ? EMPTY_PPR_RESULT : stringifyParagraphProperties(resolved);\n\n // Register numbering references (length check skips the iterator allocation\n // on the common no-numbering path)\n const numberingRefs = props.numberingReferences;\n if (numberingRefs.length > 0 && !(ctx.viewWrapper instanceof FontWrapper)) {\n for (const ref of numberingRefs) {\n ctx.file.numbering.createConcreteNumberingInstance(ref.reference, ref.instance);\n }\n }\n\n // Paragraph properties XML\n if (props.xml) {\n if (sectionPropertiesXml) {\n // Insert sectPr before closing </w:pPr>\n body += props.xml.replace(\"</w:pPr>\", sectionPropertiesXml + \"</w:pPr>\");\n } else {\n body += props.xml;\n }\n } else if (sectionPropertiesXml) {\n // No pPr but we need sectPr — wrap in pPr\n body += `<w:pPr>${sectionPropertiesXml}</w:pPr>`;\n }\n\n // Text shorthand — the run is `{ text }` by construction (no rPr/break/children/rsid),\n // so build the bare <w:r> directly instead of walking stringifyRun's full dispatch.\n if (resolved.text !== undefined) {\n body += `<w:r><w:t xml:space=\"preserve\">${escapeXml(String(resolved.text))}</w:t></w:r>`;\n }\n\n // Children\n if (resolved.children) {\n for (const child of resolved.children) {\n if (typeof child === \"string\") {\n body += `<w:r><w:t xml:space=\"preserve\">${escapeXml(child)}</w:t></w:r>`;\n } else if (typeof child === \"object\" && child !== null) {\n // Try JSON child dispatch first (image, chart, pageBreak, etc.)\n const jsonResult = stringifyChildDispatch(child as ParagraphChild, ctx);\n if (jsonResult !== undefined) {\n body += Array.isArray(jsonResult) ? jsonResult.join(\"\") : jsonResult;\n } else {\n // RunOptions-like plain object — may be an empty run carrying only\n // run properties (round-tripped from <w:r><w:rPr>…</w:rPr></w:r>).\n body += stringifyRun(child as RunOptions, ctx);\n }\n }\n }\n }\n\n let attr = \"\";\n if (resolved.paraId) attr += ` w14:paraId=\"${resolved.paraId}\"`;\n if (resolved.textId) attr += ` w14:textId=\"${resolved.textId}\"`;\n if (resolved.rsid) attr += ` w:rsidR=\"${resolved.rsid}\"`;\n if (resolved.defaultRunRsid) attr += ` w:rsidRDefault=\"${resolved.defaultRunRsid}\"`;\n if (resolved.propertiesRsid) attr += ` w:rsidP=\"${resolved.propertiesRsid}\"`;\n if (resolved.runPropertiesRsid) attr += ` w:rsidRPr=\"${resolved.runPropertiesRsid}\"`;\n if (resolved.deletionRsid) attr += ` w:rsidDel=\"${resolved.deletionRsid}\"`;\n return body ? `<w:p${attr}>${body}</w:p>` : `<w:p${attr}/>`;\n}\n\n// ── Body child dispatch ──\n\n/**\n * Stringify a body-level child element.\n *\n * Dispatches to the appropriate stringifier based on the child type.\n * Pure JSON API — no class instance support.\n */\nexport function stringifyBodyChild(\n child: SectionChild,\n ctx: BodyContext,\n sectionPropertiesXml?: string,\n): string {\n // Plain object dispatch — all via descriptors\n if (\"paragraph\" in child) {\n return stringifyParagraph(child.paragraph, ctx, sectionPropertiesXml);\n }\n if (\"table\" in child) {\n return tableDesc.stringify(child.table, ctx) ?? \"\";\n }\n if (\"toc\" in child) {\n const { alias, ...options } = child.toc;\n const entriesXml = (options.entries ?? [])\n .map((entry) => stringifyBodyChild(entry, ctx))\n .join(\"\");\n return stringifyTableOfContents(alias, options, entriesXml);\n }\n if (\"textbox\" in child) {\n return stringifyTextbox(child.textbox, ctx);\n }\n if (\"sdt\" in child) {\n return sdtBlockDesc.stringify(child.sdt, ctx) ?? \"\";\n }\n if (\"altChunk\" in child) {\n return altChunkDesc.stringify(child.altChunk, ctx) ?? \"\";\n }\n if (\"subDoc\" in child) {\n return subDocDesc.stringify(child.subDoc, ctx) ?? \"\";\n }\n if (\"customXml\" in child) {\n return customXmlBlockDesc.stringify(child.customXml, ctx) ?? \"\";\n }\n if (\"bookmarkStart\" in child) {\n const bs = child.bookmarkStart;\n const a: string[] = [`w:id=\"${bs.id}\"`, `w:name=\"${escapeXml(bs.name)}\"`];\n if (bs.displacedByCustomXml) a.push(`w:displacedByCustomXml=\"${bs.displacedByCustomXml}\"`);\n if (bs.colFirst !== undefined) a.push(`w:colFirst=\"${bs.colFirst}\"`);\n if (bs.colLast !== undefined) a.push(`w:colLast=\"${bs.colLast}\"`);\n return `<w:bookmarkStart ${a.join(\" \")}/>`;\n }\n if (\"bookmarkEnd\" in child) {\n const be = child.bookmarkEnd;\n const a: string[] = [`w:id=\"${be.id}\"`];\n if (be.displacedByCustomXml) a.push(`w:displacedByCustomXml=\"${be.displacedByCustomXml}\"`);\n return `<w:bookmarkEnd ${a.join(\" \")}/>`;\n }\n if (\"rawXml\" in child) {\n return child.rawXml;\n }\n\n throw new Error(\"Unknown section child type\");\n}\n\n// ── Document background (pure function, no XmlComponent) ──\n\nfunction stringifyDocumentBackground(opts: DocumentBackgroundOptions, ctx: BodyContext): string {\n // Raw-XML passthrough for backgrounds that don't fit the structured model\n // (VML pattern fills, texture images). Register each referenced media item\n // so the compiler resolves the `{fileName}` placeholders into rIds.\n if (opts.rawXml) {\n if (opts.rawMedia) {\n for (const m of opts.rawMedia) {\n const data = toUint8Array(m.data);\n const entry = ctx.file.media.addMedia(\n data,\n m.type,\n (fileName) =>\n ({\n type: m.type,\n data,\n fileName,\n transformation: { emus: { x: 0, y: 0 }, pixels: { x: 0, y: 0 } },\n }) as MediaData,\n m.fileName,\n );\n // Dedup may reuse an earlier file name; remap the placeholder so the\n // compiler resolves it to the shared media relationship.\n if (entry.fileName !== m.fileName) {\n opts.rawXml = opts.rawXml.split(`{${m.fileName}}`).join(`{${entry.fileName}}`);\n }\n }\n }\n return opts.rawXml;\n }\n\n const attrs: string[] = [];\n if (opts.color !== undefined) attrs.push(`w:color=\"${hexColorValue(opts.color)}\"`);\n if (opts.themeColor !== undefined) attrs.push(`w:themeColor=\"${opts.themeColor}\"`);\n if (opts.themeShade !== undefined)\n attrs.push(`w:themeShade=\"${uCharHexNumber(opts.themeShade)}\"`);\n if (opts.themeTint !== undefined) attrs.push(`w:themeTint=\"${uCharHexNumber(opts.themeTint)}\"`);\n const attrStr = attrs.join(\" \");\n\n if (opts.image) {\n const image = opts.image;\n const rawData = toUint8Array(image.data) as Uint8Array;\n const { fileName } = ctx.file.media.addMedia(\n rawData,\n image.type,\n (name) =>\n ({\n type: image.type as \"jpg\" | \"png\" | \"gif\" | \"bmp\" | \"tif\" | \"ico\" | \"emf\" | \"wmf\",\n data: rawData,\n fileName: name,\n transformation: { emus: { x: 0, y: 0 }, pixels: { x: 0, y: 0 } },\n }) as MediaData,\n );\n\n const vmlBg = stringifyVmlBackground({\n // stringifyDocumentXml emits the background before body children, so the\n // allocator hands out 1025 here — matching Word's fixed v:background id.\n id: nextVmlShapeId(),\n fill: {\n type: \"frame\",\n recolor: true,\n relationshipId: `{${fileName}}`,\n officeTitle: fileName,\n },\n });\n return `<w:background ${attrStr}>${vmlBg}</w:background>`;\n }\n\n return `<w:background ${attrStr}/>`;\n}\n\n// ── Textbox (pure function, no XmlComponent) ──\n\nfunction stringifyTextbox(\n opts: Omit<ParagraphOptions, \"style\" | \"children\"> & {\n style?: VmlShapeStyle;\n children?: SectionChild[];\n },\n ctx: BodyContext,\n): string {\n // Destructure to separate VML style/children from paragraph properties\n const { style, children, ...paraOpts } = opts;\n const props = stringifyParagraphProperties(paraOpts);\n const pPrXml = props.xml ?? \"\";\n\n // Textbox content — serialize children via stringifyBodyChild\n const contentParts: string[] = [];\n if (children) {\n for (const c of children) {\n contentParts.push(stringifyBodyChild(c, ctx));\n }\n }\n const txbxContent = contentParts.join(\"\");\n\n const vshape = stringifyVmlShape({\n id: nextVmlShapeId(),\n type: \"#_x0000_t202\",\n style,\n textbox: {\n style: { fitShapeToText: true },\n insetmode: \"auto\",\n txbxContent,\n },\n });\n\n return `<w:p>${pPrXml}<w:pict>${vshape}</w:pict></w:p>`;\n}\n\n// ── Document body ──\n\n/** Document-level namespace string (cached, MS Word declaration order). */\nconst DOC_NS = documentNamespaceAttributes([\n \"wpc\",\n \"mc\",\n \"o\",\n \"r\",\n \"m\",\n \"v\",\n \"wp14\",\n \"wp\",\n \"w10\",\n \"w\",\n \"w14\",\n \"w15\",\n \"wpg\",\n \"wpi\",\n \"wne\",\n \"wps\",\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"aink\",\n \"am3d\",\n \"w16cex\",\n \"w16cid\",\n \"w16\",\n \"w16sdtdh\",\n \"w16se\",\n]);\n\n/**\n * Stringify the complete document.xml from context data.\n *\n * This is the pure JSON path — iterates raw section children via\n * `stringifyBodyChild()` while reusing existing SectionProperties\n * instances for sectPr XML (which are already created with correct\n * header/footer references).\n *\n * Produces the complete `<w:document>` element including namespaces,\n * background, body content with interleaved section properties.\n */\nexport function stringifyDocumentXml(ctx: DocxWriteContext, docCtx: BodyContext): string {\n const sections = ctx._options.sections;\n const bodySections = ctx.sectionProperties;\n const parts: string[] = [];\n\n // <w:document> open tag\n const conformanceAttr = ctx._options.conformance\n ? ` w:conformance=\"${ctx._options.conformance}\"`\n : \"\";\n parts.push(`<w:document ${DOC_NS} mc:Ignorable=\"w14 w15 wp14\"${conformanceAttr}>`);\n\n // Background (if any)\n if (ctx._options.background) {\n parts.push(stringifyDocumentBackground(ctx._options.background, docCtx));\n }\n\n // <w:body> — children go straight into `parts` (single join, no intermediate)\n parts.push(\"<w:body>\");\n\n for (const [si, section] of sections.entries()) {\n const children = section.children ?? [];\n const sectPrOpts = bodySections[si];\n const sectPrXml = sectPrOpts ? (sectionPropertiesDesc.stringify(sectPrOpts, docCtx) ?? \"\") : \"\";\n const isLast = si === sections.length - 1;\n\n // Per OOXML, a non-final section's sectPr lives in the pPr of its LAST\n // paragraph (the section-break paragraph carries both content and sectPr).\n // Host it there when possible; fall back to a dedicated break paragraph if\n // the section is empty or ends in a non-paragraph child. The last section\n // emits its sectPr at the body level.\n let sectPrHosted = isLast || !sectPrXml;\n for (const [ci, child] of children.entries()) {\n const inject = !isLast && sectPrXml && ci === children.length - 1 && \"paragraph\" in child;\n if (inject) sectPrHosted = true;\n parts.push(stringifyBodyChild(child, docCtx, inject ? sectPrXml : undefined));\n }\n if (!isLast && sectPrXml && !sectPrHosted) {\n parts.push(`<w:p><w:pPr>${sectPrXml}</w:pPr></w:p>`);\n }\n if (isLast && sectPrXml) {\n parts.push(sectPrXml);\n }\n }\n\n parts.push(\"</w:body></w:document>\");\n\n return parts.join(\"\");\n}\n\n// ────────────────────────────────────────────────────────────────────────────────\n// Parse (XML → JSON options)\n// ────────────────────────────────────────────────────────────────────────────────\n\nconst HEADING_MAP: Record<string, (typeof HeadingLevel)[keyof typeof HeadingLevel]> = {\n Heading1: HeadingLevel.HEADING_1,\n Heading2: HeadingLevel.HEADING_2,\n Heading3: HeadingLevel.HEADING_3,\n Heading4: HeadingLevel.HEADING_4,\n Heading5: HeadingLevel.HEADING_5,\n Heading6: HeadingLevel.HEADING_6,\n Title: HeadingLevel.TITLE,\n};\n\n/** Valid w:spacing/@w:lineRule values (ST_LineSpacingRule). */\nconst LINE_RULES = Object.values(LineRuleType) as readonly string[];\n/** Valid border @w:val values (ST_Border). */\nconst BORDER_STYLES = Object.values(BorderStyle) as readonly string[];\n/** Valid border @w:themeColor values (ST_ThemeColor). */\nconst THEME_COLORS = Object.values(ThemeColor) as readonly string[];\n\n/**\n * Reverse of inline.ts's deleted-page-number field map: maps a w:delInstrText\n * field code to the PageNumber placeholder a deletion run uses on the stringify\n * side, so deleted page-number fields round-trip instead of being dropped.\n */\nconst DELETED_PAGE_FIELD: Record<string, string> = {\n PAGE: \"CURRENT\",\n NUMPAGES: \"TOTAL_PAGES\",\n SECTIONPAGES: \"TOTAL_PAGES_IN_SECTION\",\n};\n\n// Inline element payloads extracted from the ParagraphChild union — used by\n// parse to build typed objects instead of Record<string, unknown>.\ntype SmartTagInlineOptions = Extract<ParagraphChild, { smartTag: unknown }>[\"smartTag\"];\ntype CustomXmlInlineOptions = Extract<ParagraphChild, { customXml: unknown }>[\"customXml\"];\ntype DirInlineOptions = Extract<ParagraphChild, { dir: unknown }>[\"dir\"];\ntype HyperlinkInlineOptions = Extract<ParagraphChild, { hyperlink: unknown }>[\"hyperlink\"];\ntype PermStartInlineOptions = Extract<ParagraphChild, { permStart: unknown }>[\"permStart\"];\n\n/**\n * Parse w:pPr element into paragraph properties (without children).\n */\nexport function parseParagraphProperties(\n el: Element,\n ctx: DocxReadContext,\n): Partial<ParagraphPropertiesOptions> {\n const opts: Partial<ParagraphPropertiesOptions> = {};\n\n // Style / heading\n const pStyle = findChild(el, \"w:pStyle\");\n if (pStyle) {\n const styleVal = attr(pStyle, \"w:val\");\n if (styleVal) {\n if (HEADING_MAP[styleVal]) {\n opts.heading = HEADING_MAP[styleVal];\n } else {\n opts.style = styleVal;\n }\n }\n }\n\n // Alignment\n const jc = findChild(el, \"w:jc\");\n if (jc) {\n const val = attr(jc, \"w:val\");\n if (val) opts.alignment = val as ParagraphPropertiesOptions[\"alignment\"];\n }\n\n // Spacing — before/after/line are ST_TwipsMeasure (number | UniversalMeasure);\n // use attrMeasure so UniversalMeasure round-trips with the stringify side.\n const spacing = findChild(el, \"w:spacing\");\n if (spacing) {\n const sp: SpacingProperties = {};\n const before = attrMeasure(spacing, \"w:before\");\n if (before !== undefined) sp.before = before as SpacingProperties[\"before\"];\n const after = attrMeasure(spacing, \"w:after\");\n if (after !== undefined) sp.after = after as SpacingProperties[\"after\"];\n const line = attrMeasure(spacing, \"w:line\");\n if (line !== undefined) sp.line = line as SpacingProperties[\"line\"];\n const lineRule = attr(spacing, \"w:lineRule\");\n if (lineRule && (LINE_RULES as readonly string[]).includes(lineRule)) {\n sp.lineRule = lineRule as SpacingProperties[\"lineRule\"];\n }\n const beforeAutoSpacing = attrBool(spacing, \"w:beforeAutospacing\");\n if (beforeAutoSpacing !== undefined) sp.beforeAutoSpacing = beforeAutoSpacing;\n const afterAutoSpacing = attrBool(spacing, \"w:afterAutospacing\");\n if (afterAutoSpacing !== undefined) sp.afterAutoSpacing = afterAutoSpacing;\n const beforeLines = attrNum(spacing, \"w:beforeLines\");\n if (beforeLines !== undefined) sp.beforeLines = beforeLines;\n const afterLines = attrNum(spacing, \"w:afterLines\");\n if (afterLines !== undefined) sp.afterLines = afterLines;\n if (Object.keys(sp).length > 0) opts.spacing = sp;\n }\n\n // Indent — left/right/start/end are ST_SignedTwipsMeasure, hanging/firstLine\n // are ST_TwipsMeasure (number | UniversalMeasure); use attrMeasure so\n // UniversalMeasure round-trips. *Chars are ST_DecimalNumber (pure number).\n const ind = findChild(el, \"w:ind\");\n if (ind) {\n const indentObj: IndentProperties = {};\n const left = attrMeasure(ind, \"w:left\");\n if (left !== undefined) indentObj.left = left as IndentProperties[\"left\"];\n const leftChars = attrNum(ind, \"w:leftChars\");\n if (leftChars !== undefined) indentObj.leftChars = leftChars;\n const right = attrMeasure(ind, \"w:right\");\n if (right !== undefined) indentObj.right = right as IndentProperties[\"right\"];\n const rightChars = attrNum(ind, \"w:rightChars\");\n if (rightChars !== undefined) indentObj.rightChars = rightChars;\n const start = attrMeasure(ind, \"w:start\");\n if (start !== undefined) indentObj.start = start as IndentProperties[\"start\"];\n const startChars = attrNum(ind, \"w:startChars\");\n if (startChars !== undefined) indentObj.startChars = startChars;\n const end = attrMeasure(ind, \"w:end\");\n if (end !== undefined) indentObj.end = end as IndentProperties[\"end\"];\n const endChars = attrNum(ind, \"w:endChars\");\n if (endChars !== undefined) indentObj.endChars = endChars;\n const hanging = attrMeasure(ind, \"w:hanging\");\n if (hanging !== undefined) indentObj.hanging = hanging as IndentProperties[\"hanging\"];\n const hangingChars = attrNum(ind, \"w:hangingChars\");\n if (hangingChars !== undefined) indentObj.hangingChars = hangingChars;\n const firstLine = attrMeasure(ind, \"w:firstLine\");\n if (firstLine !== undefined) indentObj.firstLine = firstLine as IndentProperties[\"firstLine\"];\n const firstLineChars = attrNum(ind, \"w:firstLineChars\");\n if (firstLineChars !== undefined) indentObj.firstLineChars = firstLineChars;\n if (Object.keys(indentObj).length > 0) opts.indent = indentObj;\n }\n\n // Numbering (w:numPr)\n const numPr = findChild(el, \"w:numPr\");\n if (numPr) {\n const ilvl = findChild(numPr, \"w:ilvl\");\n const level = ilvl ? (attrNum(ilvl, \"w:val\") ?? 0) : 0;\n const numIdEl = findChild(numPr, \"w:numId\");\n const numId = numIdEl ? attr(numIdEl, \"w:val\") : undefined;\n if (numId === \"0\") {\n // numId=0 is the OOXML reserved value that cancels numbering inherited\n // from the paragraph style — emit numId=0 verbatim instead of falling\n // back to a bullet (which would inject ListParagraph + numId=1).\n opts.numbering = false;\n } else if (numId !== undefined && ctx.numberingCache.size > 0) {\n const numEl = ctx.docx.numbering;\n if (numEl) {\n let abstractNumId: string | undefined;\n for (const child of numEl.elements ?? []) {\n if (child.name !== \"w:num\") continue;\n if (attr(child, \"w:numId\") === numId) {\n const absRef = findChild(child, \"w:abstractNumId\");\n abstractNumId = absRef ? attr(absRef, \"w:val\") : undefined;\n break;\n }\n }\n if (abstractNumId !== undefined) {\n // custom: true suppresses the ListParagraph pStyle auto-injection in\n // stringifyParagraphProperties. Round-tripped list paragraphs carry\n // no pStyle in the source (the list formatting lives in numbering);\n // injecting ListParagraph would reference a style that round-tripped\n // styles.xml may not define → dangling reference Word rejects.\n const numberingOpts: {\n reference: string;\n level: number;\n custom: boolean;\n numberingChange?: { original: string; id: string; author: string; date?: string };\n } = { reference: `list_${numId}`, level, custom: true };\n // w:numberingChange (CT_TrackChangeNumbering) — child of w:numPr\n const numberingChangeEl = findChild(numPr, \"w:numberingChange\");\n if (numberingChangeEl) {\n const nc: { original: string; id: string; author: string; date?: string } = {\n original: attr(numberingChangeEl, \"w:original\") ?? \"\",\n id: attr(numberingChangeEl, \"w:id\") ?? \"\",\n author: attr(numberingChangeEl, \"w:author\") ?? \"\",\n };\n const ncDate = attr(numberingChangeEl, \"w:date\");\n if (ncDate) nc.date = ncDate;\n numberingOpts.numberingChange = nc;\n }\n opts.numbering = numberingOpts;\n } else {\n opts.bullet = { level };\n }\n } else {\n opts.bullet = { level };\n }\n } else {\n opts.bullet = { level };\n }\n }\n\n // Tab stops\n const tabs = findChild(el, \"w:tabs\");\n if (tabs) {\n const tabStops: TabStopDefinition[] = [];\n for (const tab of tabs.elements ?? []) {\n if (tab.name !== \"w:tab\") continue;\n const tabObj: Partial<TabStopDefinition> = {};\n const pos = attrNum(tab, \"w:pos\");\n if (pos !== undefined) tabObj.position = pos;\n const val = attr(tab, \"w:val\");\n if (val) tabObj.type = val as TabStopDefinition[\"type\"];\n const leader = attr(tab, \"w:leader\");\n if (leader) tabObj.leader = leader as TabStopDefinition[\"leader\"];\n tabStops.push(tabObj as TabStopDefinition);\n }\n if (tabStops.length > 0) opts.tabStops = tabStops;\n }\n\n // On/off properties\n for (const [name, optKey] of [\n [\"w:keepNext\", \"keepNext\"],\n [\"w:keepLines\", \"keepLines\"],\n [\"w:pageBreakBefore\", \"pageBreakBefore\"],\n [\"w:widowControl\", \"widowControl\"],\n [\"w:suppressLineNumbers\", \"suppressLineNumbers\"],\n [\"w:contextualSpacing\", \"contextualSpacing\"],\n [\"w:bidi\", \"bidirectional\"],\n [\"w:wordWrap\", \"wordWrap\"],\n [\"w:suppressAutoHyphens\", \"suppressAutoHyphens\"],\n [\"w:adjustRightInd\", \"adjustRightInd\"],\n [\"w:snapToGrid\", \"snapToGrid\"],\n [\"w:mirrorIndents\", \"mirrorIndents\"],\n [\"w:kinsoku\", \"kinsoku\"],\n [\"w:topLinePunct\", \"topLinePunct\"],\n [\"w:autoSpaceDE\", \"autoSpaceDE\"],\n [\"w:autoSpaceDN\", \"autoSpaceEastAsianText\"],\n [\"w:overflowPunct\", \"overflowPunctuation\"],\n [\"w:suppressOverlap\", \"suppressOverlap\"],\n ] as const) {\n const child = findChild(el, name);\n if (child) opts[optKey] = attrBool(child, \"w:val\") ?? true;\n }\n\n // Thematic break\n const pBdr = findChild(el, \"w:pBdr\");\n if (pBdr) {\n const border: BordersOptions = {};\n for (const side of [\"top\", \"bottom\", \"left\", \"right\", \"between\", \"bar\"] as const) {\n const sideEl = findChild(pBdr, `w:${side}`);\n if (!sideEl) continue;\n // CT_Border requires w:val (style); skip malformed sides\n const style = attr(sideEl, \"w:val\");\n if (!style || !BORDER_STYLES.includes(style)) continue;\n const sideOpts: BorderOptions = { style: style as BorderOptions[\"style\"] };\n const color = attr(sideEl, \"w:color\");\n if (color) sideOpts.color = color;\n const size = attrNum(sideEl, \"w:sz\");\n if (size !== undefined) sideOpts.size = size;\n const space = attrNum(sideEl, \"w:space\");\n if (space !== undefined) sideOpts.space = space;\n const themeColor = attr(sideEl, \"w:themeColor\");\n if (themeColor && THEME_COLORS.includes(themeColor)) {\n sideOpts.themeColor = themeColor as BorderOptions[\"themeColor\"];\n }\n const themeTint = attr(sideEl, \"w:themeTint\");\n if (themeTint) sideOpts.themeTint = themeTint;\n const themeShade = attr(sideEl, \"w:themeShade\");\n if (themeShade) sideOpts.themeShade = themeShade;\n const shadow = attrBool(sideEl, \"w:shadow\");\n if (shadow !== undefined) sideOpts.shadow = shadow;\n const frame = attrBool(sideEl, \"w:frame\");\n if (frame !== undefined) sideOpts.frame = frame;\n border[side] = sideOpts;\n }\n if (Object.keys(border).length > 0) opts.border = border;\n }\n\n // Shading\n const shd = findChild(el, \"w:shd\");\n if (shd) {\n const shading = parseShading(shd);\n if (shading) opts.shading = shading;\n }\n\n // Text alignment\n const textAlignment = findChild(el, \"w:textAlignment\");\n if (textAlignment) {\n const val = attr(textAlignment, \"w:val\");\n if (val) opts.textAlignment = val as ParagraphPropertiesOptions[\"textAlignment\"];\n }\n\n // Outline level\n const outlineLvl = findChild(el, \"w:outlineLvl\");\n if (outlineLvl) {\n const val = attrNum(outlineLvl, \"w:val\");\n if (val !== undefined) opts.outlineLevel = val;\n }\n\n // Text direction (w:textDirection — ST_TextDirection).\n const textDirection = findChild(el, \"w:textDirection\");\n if (textDirection) {\n const val = attr(textDirection, \"w:val\");\n if (val) opts.textDirection = val as ParagraphPropertiesOptions[\"textDirection\"];\n }\n\n // Textbox tight wrap (w:textboxTightWrap).\n const textboxTightWrap = findChild(el, \"w:textboxTightWrap\");\n if (textboxTightWrap) {\n const val = attr(textboxTightWrap, \"w:val\");\n if (val) opts.textboxTightWrap = val as ParagraphPropertiesOptions[\"textboxTightWrap\"];\n }\n\n // HTML div id (w:divId).\n const divIdEl = findChild(el, \"w:divId\");\n if (divIdEl) {\n const val = attrNum(divIdEl, \"w:val\");\n if (val !== undefined) opts.divId = val;\n }\n\n // Conditional formatting style (w:cnfStyle — CT_Cnf w:val or 12 attrs).\n const cnfStyle = findChild(el, \"w:cnfStyle\");\n if (cnfStyle) {\n const cnf = parseCnfStyle(cnfStyle);\n if (cnf) opts.cnfStyle = cnf;\n }\n\n // Run properties (paragraph-level defaults)\n const rPr = findChild(el, \"w:rPr\");\n if (rPr) {\n opts.run = parseRunProperties(rPr);\n }\n\n // Frame properties — rebuilt into the public FrameOptions union so parse\n // output re-enters generate unchanged (CT_FramePr attributes are all\n // optional, hence the optional base fields).\n const framePr = findChild(el, \"w:framePr\");\n if (framePr) {\n // Mutable superset of the FrameOptions union members — cast once at the end.\n const frame: {\n type?: \"absolute\" | \"alignment\";\n position?: { x?: number | UniversalMeasure; y?: number | UniversalMeasure };\n alignment?: { x?: string; y?: string };\n anchor?: { horizontal?: string; vertical?: string };\n space?: { horizontal?: number | UniversalMeasure; vertical?: number | UniversalMeasure };\n dropCap?: string;\n lines?: string;\n wrap?: string;\n rule?: string;\n anchorLock?: boolean;\n width?: number | UniversalMeasure;\n height?: number | UniversalMeasure;\n } = {};\n for (const [attrName, optName] of [\n [\"w:dropCap\", \"dropCap\"],\n [\"w:lines\", \"lines\"],\n [\"w:wrap\", \"wrap\"],\n [\"w:hRule\", \"rule\"],\n ] as const) {\n const val = attr(framePr, attrName);\n if (val !== undefined) frame[optName] = val;\n }\n // Position: absolute coordinates (w:x/w:y) vs alignment (w:xAlign/w:yAlign)\n const x = attrMeasure(framePr, \"w:x\") as number | UniversalMeasure;\n const y = attrMeasure(framePr, \"w:y\") as number | UniversalMeasure;\n const xAlign = attr(framePr, \"w:xAlign\");\n const yAlign = attr(framePr, \"w:yAlign\");\n if (x !== undefined || y !== undefined) {\n frame.type = \"absolute\";\n frame.position = { ...(x !== undefined ? { x } : {}), ...(y !== undefined ? { y } : {}) };\n } else if (xAlign || yAlign) {\n frame.type = \"alignment\";\n frame.alignment = {\n ...(xAlign ? { x: xAlign } : {}),\n ...(yAlign ? { y: yAlign } : {}),\n };\n }\n // Anchor (hAnchor/vAnchor)\n const hAnchor = attr(framePr, \"w:hAnchor\");\n const vAnchor = attr(framePr, \"w:vAnchor\");\n if (hAnchor || vAnchor) {\n frame.anchor = {\n ...(hAnchor ? { horizontal: hAnchor } : {}),\n ...(vAnchor ? { vertical: vAnchor } : {}),\n };\n }\n // Spacing (hSpace/vSpace)\n const hSpace = attrMeasure(framePr, \"w:hSpace\") as number | UniversalMeasure;\n const vSpace = attrMeasure(framePr, \"w:vSpace\") as number | UniversalMeasure;\n if (hSpace !== undefined || vSpace !== undefined) {\n frame.space = {\n ...(hSpace !== undefined ? { horizontal: hSpace } : {}),\n ...(vSpace !== undefined ? { vertical: vSpace } : {}),\n };\n }\n const anchorLock = attrBool(framePr, \"w:anchorLock\");\n if (anchorLock !== undefined) frame.anchorLock = anchorLock;\n const w = attrMeasure(framePr, \"w:w\") as number | UniversalMeasure;\n if (w !== undefined) frame.width = w;\n const h = attrMeasure(framePr, \"w:h\") as number | UniversalMeasure;\n if (h !== undefined) frame.height = h;\n if (Object.keys(frame).length > 0) opts.frame = frame as FrameOptions;\n }\n\n // Revision (w:pPrChange) — symmetric with stringifyParagraphProperties\n const pPrChange = findChild(el, \"w:pPrChange\");\n if (pPrChange) {\n const rev: Partial<ParagraphPropertiesChangeOptions> = {};\n const author = attr(pPrChange, \"w:author\");\n if (author) rev.author = author;\n const revDate = attr(pPrChange, \"w:date\");\n if (revDate) rev.date = revDate;\n const revId = attrNum(pPrChange, \"w:id\");\n if (revId !== undefined) rev.id = revId;\n const innerPPr = findChild(pPrChange, \"w:pPr\");\n if (innerPPr) Object.assign(rev, parseParagraphProperties(innerPPr, ctx));\n if (Object.keys(rev).length > 0) opts.revision = rev as ParagraphPropertiesChangeOptions;\n }\n\n return opts;\n}\n\n// CT_Cnf attribute order — shared by parseCnfStyle (w:val digits + w: attrs).\nconst CNF_KEYS = [\n \"firstRow\",\n \"lastRow\",\n \"firstColumn\",\n \"lastColumn\",\n \"oddVBand\",\n \"evenVBand\",\n \"oddHBand\",\n \"evenHBand\",\n \"firstRowFirstColumn\",\n \"firstRowLastColumn\",\n \"lastRowFirstColumn\",\n \"lastRowLastColumn\",\n] as const;\n\n/** Read w:cnfStyle (CT_Cnf). Office's canonical w:val is a 12-char [01]*\n * string (ST_Cnf), one digit per flag in CNF_KEYS order; the XSD also\n * permits 12 individual w: attributes, parsed as a fallback. */\nfunction parseCnfStyle(\n el: Element,\n): NonNullable<ParagraphPropertiesOptions[\"cnfStyle\"]> | undefined {\n const val = attr(el, \"w:val\");\n const result: Record<string, boolean> = {};\n if (val && val.length === 12) {\n for (let i = 0; i < 12; i++) {\n if (val[i] === \"1\") result[CNF_KEYS[i]!] = true;\n }\n } else {\n for (const key of CNF_KEYS) {\n if (attrBool(el, `w:${key}`)) result[key] = true;\n }\n }\n return Object.keys(result).length\n ? (result as NonNullable<ParagraphPropertiesOptions[\"cnfStyle\"]>)\n : undefined;\n}\n\n/**\n * Concatenate `<w:t>` text in a run element.\n *\n * Used to capture a textInput form field's current value from the result run\n * (the runs between the `separate` and `end` fldChars). Only `<w:t>` is read —\n * `<w:tab>`/`<w:br>` in results are ignored as rare for user-entered text.\n */\n/** Parse the w:r children of a track-change wrapper (w:ins/w:moveFrom/w:moveTo). */\nfunction parseTrackChangeRuns(el: Element, ctx: DocxReadContext): RunOptions[] {\n const runs: RunOptions[] = [];\n for (const sub of el.elements ?? []) {\n if (sub.name !== \"w:r\") continue;\n const parsed = parseRun(sub, ctx);\n const runOpts = parsedRunToOptions(parsed);\n if (runOpts !== null && typeof runOpts === \"object\" && !(\"commentReference\" in runOpts)) {\n runs.push(runOpts as RunOptions);\n }\n }\n return runs;\n}\n\nfunction collectRunText(el: Element): string {\n let text = \"\";\n for (const c of el.elements ?? []) {\n if (c.name === \"w:t\") text += textOf(c);\n }\n return text;\n}\n\n/** Concatenate `<w:t>` text across all `<w:r>` children of a container (rt/rubyBase). */\nfunction collectRunsText(el: Element): string {\n let text = \"\";\n for (const r of el.elements ?? []) {\n if (r.name === \"w:r\") text += collectRunText(r);\n }\n return text;\n}\n\n/**\n * Parse the inline children of a smartTag/customXml container (recursive).\n *\n * Handles runs and nested smartTag/customXml. Form fields, hyperlinks and\n * other paragraph-level constructs are rare inside these containers and are\n * not handled here.\n */\nfunction parseContainerChildren(el: Element, ctx: DocxReadContext): ParagraphChild[] {\n const children: ParagraphChild[] = [];\n for (const sub of el.elements ?? []) {\n switch (sub.name) {\n case \"w:r\": {\n const parsed = parseRun(sub, ctx);\n const runOpts = parsedRunToOptions(parsed);\n if (runOpts !== null) children.push(runOpts);\n break;\n }\n case \"w:smartTag\": {\n const smartTag = parseSmartTagInline(sub, ctx);\n if (smartTag) children.push({ smartTag });\n break;\n }\n case \"w:customXml\": {\n const customXml = parseCustomXmlInline(sub, ctx);\n if (customXml) children.push({ customXml });\n break;\n }\n default:\n break;\n }\n }\n return children;\n}\n\n/** Parse a w:smartTag element into its ParagraphChild form. */\nfunction parseSmartTagInline(el: Element, ctx: DocxReadContext): SmartTagInlineOptions | undefined {\n const element = attr(el, \"w:element\");\n if (!element) return undefined;\n const st: SmartTagInlineOptions = { element };\n const uri = attr(el, \"w:uri\");\n if (uri) st.uri = uri;\n const pr = findChild(el, \"w:smartTagPr\");\n if (pr) {\n const props: Array<{ uri?: string; name: string; val: string }> = [];\n for (const a of pr.elements ?? []) {\n if (a.name !== \"w:attr\") continue;\n const prop: { uri?: string; name: string; val: string } = {\n name: attr(a, \"w:name\") ?? \"\",\n val: attr(a, \"w:val\") ?? \"\",\n };\n const auri = attr(a, \"w:uri\");\n if (auri) prop.uri = auri;\n props.push(prop);\n }\n if (props.length > 0) st.properties = props;\n }\n const content = parseContainerChildren(el, ctx);\n if (content.length > 0) st.children = content;\n return st;\n}\n\n/** Parse an inline w:customXml element into its ParagraphChild form. */\nfunction parseCustomXmlInline(\n el: Element,\n ctx: DocxReadContext,\n): CustomXmlInlineOptions | undefined {\n const element = attr(el, \"w:element\");\n if (!element) return undefined;\n const cx: CustomXmlInlineOptions = { element };\n const uri = attr(el, \"w:uri\");\n if (uri) cx.uri = uri;\n const pr = findChild(el, \"w:customXmlPr\");\n if (pr) {\n const parsed = parseCustomXmlProperties(pr);\n if (parsed.placeholder !== undefined || parsed.attributes !== undefined) {\n cx.customXmlPr = parsed;\n }\n }\n const content = parseContainerChildren(el, ctx);\n if (content.length > 0) cx.children = content;\n return cx;\n}\n\n/** Parse a move-revision range start (w:moveFromRangeStart / w:moveToRangeStart). */\nfunction parseMoveRangeStart(el: Element): MoveRangeStartOptions | null {\n const id = attrNum(el, \"w:id\");\n if (id === undefined) return null;\n const m: Partial<MoveRangeStartOptions> = { id };\n const name = attr(el, \"w:name\");\n if (name !== undefined) m.name = name;\n const author = attr(el, \"w:author\");\n if (author !== undefined) m.author = author;\n const date = attr(el, \"w:date\");\n if (date !== undefined) m.date = date;\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") m.displacedByCustomXml = disp;\n const colFirst = attrNum(el, \"w:colFirst\");\n if (colFirst !== undefined) m.colFirst = colFirst;\n const colLast = attrNum(el, \"w:colLast\");\n if (colLast !== undefined) m.colLast = colLast;\n return m as MoveRangeStartOptions;\n}\n\n/** Parse a customXml range start (Ins/Del/MoveFrom/MoveTo). */\nfunction parseCustomXmlRangeStart(\n el: Element,\n): { id: number; author?: string; date?: string } | null {\n const id = attrNum(el, \"w:id\");\n if (id === undefined) return null;\n const m: { id: number; author?: string; date?: string } = { id };\n const author = attr(el, \"w:author\");\n if (author !== undefined) m.author = author;\n const date = attr(el, \"w:date\");\n if (date !== undefined) m.date = date;\n return m;\n}\n\n/** Parse a CT_MarkupRange end marker (id + displacedByCustomXml). */\nfunction parseMarkupRangeOptions(el: Element): MarkupRangeOptions | undefined {\n const id = attrNum(el, \"w:id\");\n if (id === undefined) return undefined;\n const m: Partial<MarkupRangeOptions> = { id };\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") m.displacedByCustomXml = disp;\n return m as MarkupRangeOptions;\n}\n\n/**\n * Parse a w:p element into ParagraphOptions.\n */\n/**\n * Parse run-level children shared by paragraphs and inline-SDT content.\n * Includes the field accumulator that collapses form/complex fields spanning\n * multiple w:r runs into a single child.\n */\n/** Serialize a w:r's w:rPr child verbatim (or undefined when the run has none). */\nfunction runRPrXml(run: Element): string | undefined {\n const rPr = findChild(run, \"w:rPr\");\n return rPr ? stringifyElement(rPr) : undefined;\n}\n\nfunction parseRunLevelChildren(\n elements: Element[] | undefined,\n ctx: DocxReadContext,\n): ParagraphChild[] {\n const childList: ParagraphChild[] = [];\n\n // Field accumulator: a field (form field OR plain complex field) spans\n // several w:r elements (begin fldChar → instrText → separate → result → end).\n // - Form fields (checkBox/ddList/textInput) carry w:ffData on the begin\n // fldChar; their state lives there, and only a textInput's result is\n // captured (as `value`).\n // - Plain complex fields (PAGE/DATE/TOC/HYPERLINK...) have no ffData; their\n // instrText + result are captured as a complexField child for round-trip.\n // The whole field collapses to a single child.\n let fieldKind: \"form\" | \"complex\" | null = null;\n let pendingFormField: FormFieldOptions | null = null;\n let pendingInstruction = \"\";\n let pendingResult = \"\";\n // Verbatim rPr of the field's control runs (begin/instrText/separate/end)\n // and result run(s) — Word writes identical rPr across a field's runs, so\n // capturing it preserves field formatting (font/size) through round-trip.\n let pendingControlRPr: string | undefined;\n let pendingResultRPr: string | undefined;\n // True once the `separate` fldChar is seen: subsequent runs (up to `end`)\n // are the field's result.\n let collectingResult = false;\n\n for (const child of elements ?? []) {\n switch (child.name) {\n case \"w:pPr\":\n break;\n case \"w:r\": {\n // Field: fldChar markers + the instrText/result runs between them.\n const fldCharEl = findChild(child, \"w:fldChar\");\n if (fldCharEl) {\n const fctype = attr(fldCharEl, \"w:fldCharType\");\n if (fctype === \"begin\") {\n const ffDataEl = findChild(fldCharEl, \"w:ffData\");\n if (ffDataEl) {\n fieldKind = \"form\";\n pendingFormField = parseFormFieldData(ffDataEl);\n } else {\n fieldKind = \"complex\";\n pendingInstruction = \"\";\n pendingResult = \"\";\n }\n // Capture the begin run's rPr as the field's control-run rPr.\n pendingControlRPr = runRPrXml(child);\n pendingResultRPr = undefined;\n collectingResult = false;\n } else if (fctype === \"separate\") {\n collectingResult = true;\n } else if (fctype === \"end\" && fieldKind) {\n if (fieldKind === \"form\" && pendingFormField) {\n childList.push({ formField: pendingFormField });\n } else if (fieldKind === \"complex\") {\n const cf: {\n instruction: string;\n result?: string;\n rPrXml?: string;\n resultRPrXml?: string;\n } = { instruction: pendingInstruction };\n if (pendingResult) cf.result = pendingResult;\n if (pendingControlRPr) cf.rPrXml = pendingControlRPr;\n if (pendingResultRPr) cf.resultRPrXml = pendingResultRPr;\n childList.push({ complexField: cf });\n }\n fieldKind = null;\n pendingFormField = null;\n collectingResult = false;\n }\n break;\n }\n if (fieldKind) {\n if (fieldKind === \"complex\") {\n // Collect instrText (begin→separate) and result text (separate→end).\n if (collectingResult) {\n // Capture the first result run's rPr for round-trip.\n if (pendingResultRPr === undefined) pendingResultRPr = runRPrXml(child);\n pendingResult += collectRunText(child);\n } else {\n const instrEl = findChild(child, \"w:instrText\");\n if (instrEl) pendingInstruction += textOf(instrEl);\n }\n } else if (collectingResult && pendingFormField?.textInput) {\n // Capture a textInput's current value; checkbox/dropdown results\n // are discarded (their state is in w:ffData).\n const text = collectRunText(child);\n if (text) {\n const ti = pendingFormField.textInput;\n ti.value = (ti.value ?? \"\") + text;\n }\n }\n break; // instrText / result — handled by field state above\n }\n\n // Drawing may be a direct w:drawing child OR wrapped in\n // mc:AlternateContent > mc:Choice (DrawingML shapes wpg/wps use this\n // wrapper; the Fallback holds the VML equivalent). Resolve either and,\n // when an AlternateContent wrapper is present, carry the Fallback as\n // raw XML so the full mc:AlternateContent round-trips verbatim.\n let drawingEl = findChild(child, \"w:drawing\");\n let altFallback: string | undefined;\n let altFallbackMedia: BackgroundRawMediaOptions[] | undefined;\n let altRequires: string | undefined;\n if (!drawingEl) {\n const alt = findChild(child, \"mc:AlternateContent\");\n if (alt) {\n const choice = findChild(alt, \"mc:Choice\");\n if (choice) {\n drawingEl = findChild(choice, \"w:drawing\");\n altRequires = attr(choice, \"Requires\");\n }\n const fallback = findChild(alt, \"mc:Fallback\");\n if (fallback) {\n // Replace the VML fallback's r:id/r:embed/r:link refs with {fileName}\n // placeholders and collect the media; otherwise the carried source\n // rIds dangle (not defined in the generated rels).\n const replaced = replaceRelsWithPlaceholders(stringifyElement(fallback), ctx, \"vml\");\n altFallback = replaced.rawXml;\n altFallbackMedia = replaced.rawMedia.length > 0 ? replaced.rawMedia : undefined;\n }\n }\n }\n if (drawingEl) {\n const drawingChild = parseDrawingRun(drawingEl, ctx);\n if (drawingChild) {\n // Parse the wrapping run's rPr into structured fields so round-trip\n // stays editable (drawings/shapes can be wrapped in <w:r><w:rPr>…</w:rPr>…).\n const rPrEl = findChild(child, \"w:rPr\");\n const runProperties = rPrEl ? parseRunProperties(rPrEl) : undefined;\n // Attach the VML fallback + Choice Requires so stringify can rebuild\n // the mc:AlternateContent wrapper (Choice structured + Fallback raw).\n if (altFallback) {\n if (\"wpsShape\" in drawingChild) {\n drawingChild.wpsShape.vmlFallback = altFallback;\n drawingChild.wpsShape.vmlFallbackMedia = altFallbackMedia;\n if (altRequires) drawingChild.wpsShape.mcChoiceRequires = altRequires;\n } else if (\"wpgGroup\" in drawingChild) {\n drawingChild.wpgGroup.vmlFallback = altFallback;\n drawingChild.wpgGroup.vmlFallbackMedia = altFallbackMedia;\n if (altRequires) drawingChild.wpgGroup.mcChoiceRequires = altRequires;\n }\n }\n if (runProperties) {\n if (\"picture\" in drawingChild) {\n drawingChild.picture.runProperties = runProperties;\n } else if (\"wpsShape\" in drawingChild) {\n drawingChild.wpsShape.runProperties = runProperties;\n } else if (\"wpgGroup\" in drawingChild) {\n drawingChild.wpgGroup.runProperties = runProperties;\n }\n }\n childList.push(drawingChild);\n break;\n }\n }\n const parsed = parseRun(child, ctx);\n const runOpts = parsedRunToOptions(parsed);\n if (runOpts !== null) childList.push(runOpts);\n break;\n }\n case \"w:hyperlink\": {\n const hl: Partial<HyperlinkInlineOptions> = {};\n const rId = attr(child, \"r:id\");\n if (rId) {\n const target = ctx.docx.partRefs.hyperlinks.get(rId);\n if (target) hl.url = target;\n }\n const anchor = attr(child, \"w:anchor\");\n if (anchor) hl.anchor = anchor;\n const tooltip = attr(child, \"w:tooltip\");\n if (tooltip) hl.tooltip = tooltip;\n const tgtFrame = attr(child, \"w:tgtFrame\");\n if (tgtFrame) hl.targetFrame = tgtFrame;\n const docLocation = attr(child, \"w:docLocation\");\n if (docLocation) hl.docLocation = docLocation;\n const history = attrBool(child, \"w:history\");\n if (history !== undefined) hl.history = history;\n\n const linkRuns: (RunOptions | string)[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:r\") {\n const parsed = parseRun(sub, ctx);\n const runOpts = parsedRunToOptions(parsed);\n // parsedRunToOptions returns null for auto-generated/empty runs\n // (e.g. footnoteRef, pure drawing) and { commentReference } for\n // pure comment-reference runs; hyperlink children are\n // (RunOptions | string), so skip both.\n if (runOpts !== null && !(\"commentReference\" in runOpts)) {\n linkRuns.push(runOpts);\n }\n }\n }\n if (linkRuns.length > 0) {\n hl.children = linkRuns;\n childList.push({ hyperlink: hl });\n }\n break;\n }\n case \"w:bookmarkStart\": {\n const id = attrNum(child, \"w:id\");\n const name = attr(child, \"w:name\");\n if (id !== undefined && name) {\n const bookmarkStart: Partial<BookmarkStartOptions> = { id, name };\n const disp = attr(child, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkStart.displacedByCustomXml = disp;\n const colFirst = attrNum(child, \"w:colFirst\");\n if (colFirst !== undefined) bookmarkStart.colFirst = colFirst;\n const colLast = attrNum(child, \"w:colLast\");\n if (colLast !== undefined) bookmarkStart.colLast = colLast;\n childList.push({ bookmarkStart: bookmarkStart as BookmarkStartOptions });\n }\n break;\n }\n case \"w:bookmarkEnd\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) {\n const bookmarkEnd: Partial<MarkupRangeOptions> = { id };\n const disp = attr(child, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkEnd.displacedByCustomXml = disp;\n childList.push({ bookmarkEnd: bookmarkEnd as MarkupRangeOptions });\n }\n break;\n }\n case \"w:commentRangeStart\": {\n const m = parseMarkupRangeOptions(child);\n if (m) childList.push({ commentRangeStart: m });\n break;\n }\n case \"w:commentRangeEnd\": {\n const m = parseMarkupRangeOptions(child);\n if (m) childList.push({ commentRangeEnd: m });\n break;\n }\n case \"w:commentReference\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) childList.push({ commentReference: id });\n break;\n }\n case \"m:oMath\": {\n const mathChildren = parseMathChildren(child);\n childList.push({ math: { children: mathChildren } });\n break;\n }\n case \"w:ins\": {\n const children = parseTrackChangeRuns(child, ctx);\n if (children.length > 0) {\n childList.push({\n insertion: {\n id: attrNum(child, \"w:id\") ?? 0,\n author: attr(child, \"w:author\") ?? \"\",\n date: attr(child, \"w:date\") ?? \"\",\n children,\n },\n });\n }\n break;\n }\n case \"w:del\": {\n // Deleted page-number fields emit w:delInstrText (not w:instrText);\n // reverse inline.ts's field map so they round-trip as placeholder children.\n const children: (RunOptions | string)[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name !== \"w:r\") continue;\n const delInstrEl = findChild(sub, \"w:delInstrText\");\n if (delInstrEl) {\n const placeholder = DELETED_PAGE_FIELD[(textOf(delInstrEl) ?? \"\").trim()];\n if (placeholder) {\n children.push(placeholder);\n continue;\n }\n }\n const parsed = parseRun(sub, ctx);\n const runOpts = parsedRunToOptions(parsed);\n if (runOpts !== null && typeof runOpts === \"object\" && !(\"commentReference\" in runOpts)) {\n children.push(runOpts as RunOptions);\n }\n }\n if (children.length > 0) {\n childList.push({\n deletion: {\n id: attrNum(child, \"w:id\") ?? 0,\n author: attr(child, \"w:author\") ?? \"\",\n date: attr(child, \"w:date\") ?? \"\",\n children,\n },\n });\n }\n break;\n }\n case \"w:moveFrom\": {\n const children = parseTrackChangeRuns(child, ctx);\n if (children.length > 0) {\n childList.push({\n movedFrom: {\n id: attrNum(child, \"w:id\") ?? 0,\n author: attr(child, \"w:author\") ?? \"\",\n date: attr(child, \"w:date\") ?? \"\",\n children,\n },\n });\n }\n break;\n }\n case \"w:moveTo\": {\n const children = parseTrackChangeRuns(child, ctx);\n if (children.length > 0) {\n childList.push({\n movedTo: {\n id: attrNum(child, \"w:id\") ?? 0,\n author: attr(child, \"w:author\") ?? \"\",\n date: attr(child, \"w:date\") ?? \"\",\n children,\n },\n });\n }\n break;\n }\n case \"w:fldSimple\": {\n const instruction = attr(child, \"w:instr\");\n if (instruction) {\n const sf: {\n instruction: string;\n cachedValue?: string;\n fieldLock?: boolean;\n dirty?: boolean;\n } = { instruction };\n // cachedValue: concatenate the result-run <w:t> text (one or more\n // <w:r> children between the fldSimple tags).\n let cachedValue = \"\";\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:r\") cachedValue += collectRunText(sub);\n }\n if (cachedValue) sf.cachedValue = cachedValue;\n const sfLock = attrBool(child, \"w:fldLock\");\n if (sfLock !== undefined) sf.fieldLock = sfLock;\n const sfDirty = attrBool(child, \"w:dirty\");\n if (sfDirty !== undefined) sf.dirty = sfDirty;\n childList.push({ simpleField: sf });\n }\n break;\n }\n case \"w:smartTag\": {\n const st = parseSmartTagInline(child, ctx);\n if (st) childList.push({ smartTag: st });\n break;\n }\n case \"w:customXml\": {\n const cx = parseCustomXmlInline(child, ctx);\n if (cx) childList.push({ customXml: cx });\n break;\n }\n // ── Bidirectional containers (reuse the smartTag/customXml child parser) ──\n case \"w:dir\": {\n const val = attr(child, \"w:val\");\n if (val) {\n const dir: DirInlineOptions = { val: val as \"ltr\" | \"rtl\" };\n const content = parseContainerChildren(child, ctx);\n if (content.length > 0) dir.children = content;\n childList.push({ dir });\n }\n break;\n }\n case \"w:bdo\": {\n const val = attr(child, \"w:val\");\n if (val) {\n const bdo: DirInlineOptions = { val: val as \"ltr\" | \"rtl\" };\n const content = parseContainerChildren(child, ctx);\n if (content.length > 0) bdo.children = content;\n childList.push({ bdo });\n }\n break;\n }\n // ── Ruby annotation (East Asian pronunciation guides) ──\n case \"w:ruby\": {\n const rt = findChild(child, \"w:rt\");\n const rubyBase = findChild(child, \"w:rubyBase\");\n // text and base are required by CT_Ruby; skip the ruby if either is missing.\n if (!rt || !rubyBase) break;\n const ruby: RubyOptions = {\n text: collectRunsText(rt),\n base: collectRunsText(rubyBase),\n };\n const pr = findChild(child, \"w:rubyPr\");\n if (pr) {\n const alignEl = findChild(pr, \"w:rubyAlign\");\n if (alignEl) {\n const v = attr(alignEl, \"w:val\");\n if (v) ruby.alignment = v as RubyOptions[\"alignment\"];\n }\n // hps / hpsRaise / hpsBaseText are half-points; the API uses points.\n const hpsEl = findChild(pr, \"w:hps\");\n if (hpsEl) {\n const v = attrNum(hpsEl, \"w:val\");\n if (v !== undefined) ruby.fontSize = v / 2;\n }\n const hpsRaiseEl = findChild(pr, \"w:hpsRaise\");\n if (hpsRaiseEl) {\n const v = attrNum(hpsRaiseEl, \"w:val\");\n if (v !== undefined) ruby.raise = v / 2;\n }\n const hpsBaseEl = findChild(pr, \"w:hpsBaseText\");\n if (hpsBaseEl) {\n const v = attrNum(hpsBaseEl, \"w:val\");\n if (v !== undefined) ruby.baseFontSize = v / 2;\n }\n const lidEl = findChild(pr, \"w:lid\");\n if (lidEl) {\n const v = attr(lidEl, \"w:val\");\n if (v) ruby.languageId = v;\n }\n if (findChild(pr, \"w:dirty\")) ruby.dirty = true;\n }\n childList.push({ ruby });\n break;\n }\n // ── Range markers: proof errors, positional tabs, permissions, revisions ──\n case \"w:proofErr\": {\n const type = attr(child, \"w:type\");\n if (\n type === \"spellStart\" ||\n type === \"spellEnd\" ||\n type === \"gramStart\" ||\n type === \"gramEnd\"\n ) {\n childList.push({ proofErr: type });\n }\n break;\n }\n case \"w:ptab\": {\n const alignment = attr(child, \"w:alignment\");\n const leader = attr(child, \"w:leader\");\n const relativeTo = attr(child, \"w:relativeTo\");\n if (alignment !== undefined && leader !== undefined && relativeTo !== undefined) {\n childList.push({ positionalTab: { alignment, leader, relativeTo } });\n }\n break;\n }\n case \"w:permStart\": {\n const id = attr(child, \"w:id\");\n if (id !== undefined) {\n const ps: PermStartInlineOptions = { id };\n const ed = attr(child, \"w:ed\");\n if (ed !== undefined) ps.editor = ed;\n const editGroup = attr(child, \"w:edGrp\");\n if (editGroup !== undefined) ps.editGroup = editGroup;\n const colFirst = attrNum(child, \"w:colFirst\");\n if (colFirst !== undefined) ps.colFirst = colFirst;\n const colLast = attrNum(child, \"w:colLast\");\n if (colLast !== undefined) ps.colLast = colLast;\n childList.push({ permStart: ps });\n }\n break;\n }\n case \"w:permEnd\": {\n const id = attr(child, \"w:id\");\n if (id !== undefined) childList.push({ permEnd: id });\n break;\n }\n case \"w:moveFromRangeStart\": {\n const m = parseMoveRangeStart(child);\n if (m) childList.push({ moveFromRangeStart: m });\n break;\n }\n case \"w:moveFromRangeEnd\": {\n const m = parseMarkupRangeOptions(child);\n if (m) childList.push({ moveFromRangeEnd: m });\n break;\n }\n case \"w:moveToRangeStart\": {\n const m = parseMoveRangeStart(child);\n if (m) childList.push({ moveToRangeStart: m });\n break;\n }\n case \"w:moveToRangeEnd\": {\n const m = parseMarkupRangeOptions(child);\n if (m) childList.push({ moveToRangeEnd: m });\n break;\n }\n case \"w:customXmlInsRangeStart\": {\n const m = parseCustomXmlRangeStart(child);\n if (m) childList.push({ customXmlInsRangeStart: m });\n break;\n }\n case \"w:customXmlInsRangeEnd\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) childList.push({ customXmlInsRangeEnd: id });\n break;\n }\n case \"w:customXmlDelRangeStart\": {\n const m = parseCustomXmlRangeStart(child);\n if (m) childList.push({ customXmlDelRangeStart: m });\n break;\n }\n case \"w:customXmlDelRangeEnd\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) childList.push({ customXmlDelRangeEnd: id });\n break;\n }\n case \"w:customXmlMoveFromRangeStart\": {\n const m = parseCustomXmlRangeStart(child);\n if (m) childList.push({ customXmlMoveFromRangeStart: m });\n break;\n }\n case \"w:customXmlMoveFromRangeEnd\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) childList.push({ customXmlMoveFromRangeEnd: id });\n break;\n }\n case \"w:customXmlMoveToRangeStart\": {\n const m = parseCustomXmlRangeStart(child);\n if (m) childList.push({ customXmlMoveToRangeStart: m });\n break;\n }\n case \"w:customXmlMoveToRangeEnd\": {\n const id = attrNum(child, \"w:id\");\n if (id !== undefined) childList.push({ customXmlMoveToRangeEnd: id });\n break;\n }\n case \"w:sdt\": {\n const sdtPr = findChild(child, \"w:sdtPr\");\n const properties = sdtPr ? parseSdtProperties(sdtPr) : {};\n const sdtEndPr = findChild(child, \"w:sdtEndPr\");\n const endProperties = sdtEndPr ? parseRunProperties(sdtEndPr) : undefined;\n const sdtContent = findChild(child, \"w:sdtContent\");\n const sdtChildren = parseRunLevelChildren(sdtContent?.elements, ctx);\n const sdt: SdtRunOptions = { properties };\n if (sdtChildren.length > 0) sdt.children = sdtChildren;\n if (endProperties) sdt.endProperties = endProperties;\n childList.push({ sdt });\n break;\n }\n default:\n break;\n }\n }\n\n return childList;\n}\n\n/** True when a child is a single-field `{ text: string }` run (simple text). */\nfunction isTextOnlyRun(c: unknown): c is { text: string } {\n return typeof c === \"object\" && c !== null && \"text\" in c && Object.keys(c).length === 1;\n}\n\nexport function parseParagraph(el: Element, ctx: DocxReadContext): ParagraphOptions {\n const opts: Partial<ParagraphOptions> = {};\n\n // w:p element attributes: rsid family + w14:paraId/textId (hex string verbatim)\n const paraId = attr(el, \"w14:paraId\");\n if (paraId) opts.paraId = paraId;\n const textId = attr(el, \"w14:textId\");\n if (textId) opts.textId = textId;\n const rsid = attr(el, \"w:rsidR\");\n if (rsid) opts.rsid = rsid;\n const defaultRunRsid = attr(el, \"w:rsidRDefault\");\n if (defaultRunRsid) opts.defaultRunRsid = defaultRunRsid;\n const propertiesRsid = attr(el, \"w:rsidP\");\n if (propertiesRsid) opts.propertiesRsid = propertiesRsid;\n const runPropertiesRsid = attr(el, \"w:rsidRPr\");\n if (runPropertiesRsid) opts.runPropertiesRsid = runPropertiesRsid;\n const deletionRsid = attr(el, \"w:rsidDel\");\n if (deletionRsid) opts.deletionRsid = deletionRsid;\n\n const pPr = findChild(el, \"w:pPr\");\n if (pPr) {\n Object.assign(opts, parseParagraphProperties(pPr, ctx));\n }\n\n const childList = parseRunLevelChildren(el.elements, ctx);\n\n // Simple text optimization: a run of text-only children collapses into a\n // single opts.text (the canonical ParagraphOptions form) instead of a\n // children array.\n if (childList.length > 0) {\n if (childList.every(isTextOnlyRun)) {\n const combined = childList.map((c) => (isTextOnlyRun(c) ? c.text : \"\")).join(\"\");\n if (combined) {\n opts.text = combined;\n return opts as ParagraphOptions;\n }\n }\n opts.children = childList;\n }\n\n return opts as ParagraphOptions;\n}\n","/**\n * Drawing parser for DOCX documents.\n *\n * Parses w:drawing elements and extracts image, chart, or SmartArt data.\n *\n * @module\n */\nimport type { ChartSpaceOptions } from \"@office-open/core\";\nimport { parseOnOff } from \"@office-open/core\";\nimport {\n blipDesc,\n convertEmuToPixels,\n customGeometryDesc,\n effectListDesc,\n fillDesc,\n outlineDesc,\n parseAngle,\n parseColorChoice,\n parseNonVisualDrawingProperties,\n presetGeometryDesc,\n} from \"@office-open/core\";\nimport { scene3DDesc, shape3DDesc } from \"@office-open/core/drawing\";\nimport type {\n BlackWhiteMode,\n NonVisualContentPartPropertiesOptions,\n SourceRectangleOptions,\n} from \"@office-open/core/drawing\";\nimport { parseNonVisualContentPartProperties } from \"@office-open/core/drawing\";\nimport {\n COLOR_CATEGORIES,\n LAYOUT_CATEGORIES,\n STYLE_CATEGORIES,\n parseColorDefinition,\n parseLayoutDefinition,\n parseStyleDefinition,\n} from \"@office-open/core/smartart\";\nimport { attr, attrBool, attrNum, findChild, findFirst, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { ChartOptions } from \"@parts/paragraph/run/chart-run\";\nimport type { PictureOptions } from \"@parts/paragraph/run/picture-run\";\nimport type { SmartArtOptions } from \"@parts/paragraph/run/smartart-run\";\nimport type { GroupOptions } from \"@parts/paragraph/run/wpg-group-run\";\nimport type { ShapeOptions } from \"@parts/paragraph/run/wps-shape-run\";\nimport type {\n ChartMediaData,\n ContentPartMediaData,\n GroupChildMediaData,\n MediaData,\n MediaDataTransformation,\n GroupCommonMediaData,\n GroupMediaData,\n ShapeMediaData,\n} from \"@shared/media\";\nimport type { ContentPartOptions, NonVisualPropertiesOptions } from \"@shared/media/data\";\n\nimport { parseParagraph } from \"../../body\";\nimport type { DocxReadContext } from \"../../context\";\nimport type { GraphicFrameLocksOptions, GroupShapeLocksOptions } from \"./descriptor\";\nimport type { DocPropertiesOptions } from \"./doc-properties/doc-properties\";\nimport type {\n Floating,\n HorizontalPositionOptions,\n Margins,\n VerticalPositionOptions,\n} from \"./floating\";\nimport type { ChildOffset, ChildExtent } from \"./inline/graphic/graphic-data/wpg/wpg-group\";\nimport { parseBodyProperties } from \"./inline/graphic/graphic-data/wps/body-properties\";\nimport type { NonVisualShapePropertiesOptions } from \"./inline/graphic/graphic-data/wps/non-visual-shape-properties\";\nimport type {\n ShapeStyleOptions,\n ShapeStyleReferenceOptions,\n ShapeCoreOptions,\n} from \"./inline/graphic/graphic-data/wps/wps-shape\";\nimport { TextWrappingType } from \"./text-wrap\";\nimport type { TextWrapping, WrapPolygon } from \"./text-wrap\";\n\n/** Union type for parsed drawing child wrappers. */\nexport type DrawingChild =\n | { picture: PictureOptions }\n | { chart: ChartOptions }\n | { smartArt: SmartArtOptions }\n | { wpsShape: ShapeOptions }\n | { wpgGroup: GroupOptions }\n | { contentPart: ContentPartOptions };\n\n/**\n * Parse a w:drawing element and dispatch to the correct parser\n * based on the graphicData URI.\n */\nexport function parseDrawingRun(el: Element, ctx: DocxReadContext): DrawingChild | undefined {\n // A content part nests inside a wpg group (wpg:contentPart, no a:graphic\n // wrapper), so it must be checked before the graphicData dispatch; the\n // wp: spelling is accepted leniently for third-party files.\n const contentPartEl = findFirst(el, \"wpg:contentPart\") ?? findFirst(el, \"wp:contentPart\");\n if (contentPartEl) {\n // Group children keep the full ContentPartMediaData (type-discriminated);\n // the paragraph-level payload is the public ContentPartOptions.\n const { type: _type, ...contentPart } = parseContentPart(contentPartEl);\n return { contentPart };\n }\n\n const graphicData = findFirst(el, \"a:graphicData\");\n if (!graphicData) return undefined;\n\n const uri = attr(graphicData, \"uri\") ?? \"\";\n\n if (uri.includes(\"/chart\")) {\n return parseChartDrawing(el, ctx);\n }\n if (uri.includes(\"/diagram\")) {\n return parseSmartArtDrawing(el, ctx);\n }\n if (uri.includes(\"wordprocessingGroup\")) {\n return parseWpgGroupDrawing(el, ctx);\n }\n if (uri.includes(\"wordprocessingShape\")) {\n return parseWpsShapeDrawing(el, ctx);\n }\n return parsePictureRun(el, ctx);\n}\n\n/**\n * Determine image type from file extension or MIME type.\n */\nexport function imageTypeFromPath(\n path: string,\n): \"jpg\" | \"png\" | \"gif\" | \"bmp\" | \"tif\" | \"ico\" | \"emf\" | \"wmf\" {\n const ext = path.split(\".\").pop()?.toLowerCase() ?? \"\";\n switch (ext) {\n case \"jpg\":\n case \"jpeg\":\n return \"jpg\";\n case \"png\":\n return \"png\";\n case \"gif\":\n return \"gif\";\n case \"bmp\":\n return \"bmp\";\n case \"tif\":\n case \"tiff\":\n return \"tif\";\n case \"ico\":\n return \"ico\";\n case \"emf\":\n return \"emf\";\n case \"wmf\":\n return \"wmf\";\n default:\n return \"png\"; // fallback\n }\n}\n\n/**\n * Extent (EMU→pixels), alt text, and floating properties extracted from a\n * w:drawing's wp:inline or wp:anchor wrapper. Shared by image, wps shape,\n * and wpg group parsing.\n */\ninterface AnchorInfo {\n width?: number;\n height?: number;\n floating?: Floating;\n altText?: DocPropertiesOptions;\n graphicFrameLocks?: GraphicFrameLocksOptions | null;\n /** wp:effectExtent in raw EMUs — round-tripped verbatim. */\n effectExtent?: { l: number; t: number; r: number; b: number };\n}\n\n/** Read wp:cNvGraphicFramePr locking flags. An empty element (no graphicFrameLocks\n * child) returns `{}` so it round-trips as `<wp:cNvGraphicFramePr/>`. */\nfunction readGraphicFrameLocks(el: Element): GraphicFrameLocksOptions {\n const locks = findChild(el, \"a:graphicFrameLocks\");\n const result: GraphicFrameLocksOptions = {};\n if (!locks) return result;\n const a = locks.attributes ?? {};\n if (a[\"noGrp\"] !== undefined) result.noGrp = parseOnOff(a[\"noGrp\"]) ?? true;\n if (a[\"noDrilldown\"] !== undefined) result.noDrilldown = parseOnOff(a[\"noDrilldown\"]) ?? true;\n if (a[\"noSelect\"] !== undefined) result.noSelect = parseOnOff(a[\"noSelect\"]) ?? true;\n if (a[\"noChangeAspect\"] !== undefined)\n result.noChangeAspect = parseOnOff(a[\"noChangeAspect\"]) ?? true;\n if (a[\"noMove\"] !== undefined) result.noMove = parseOnOff(a[\"noMove\"]) ?? true;\n if (a[\"noResize\"] !== undefined) result.noResize = parseOnOff(a[\"noResize\"]) ?? true;\n return result as GraphicFrameLocksOptions;\n}\n\n/**\n * Read wpg:cNvGrpSpPr/a:grpSpLocks (CT_GroupLocking) into GroupShapeLocksOptions.\n * Returns `undefined` when the group has no locks (Word's default → empty cNvGrpSpPr).\n */\nfunction readGrpSpLocks(cNvGrpSpPr: Element | undefined): GroupShapeLocksOptions | undefined {\n if (!cNvGrpSpPr) return undefined;\n const locks = findChild(cNvGrpSpPr, \"a:grpSpLocks\");\n if (!locks) return undefined;\n const result: GroupShapeLocksOptions = {};\n const a = locks.attributes ?? {};\n if (a[\"noGrp\"] !== undefined) result.noGrp = parseOnOff(a[\"noGrp\"]) ?? true;\n if (a[\"noUngrp\"] !== undefined) result.noUngrp = parseOnOff(a[\"noUngrp\"]) ?? true;\n if (a[\"noSelect\"] !== undefined) result.noSelect = parseOnOff(a[\"noSelect\"]) ?? true;\n if (a[\"noRot\"] !== undefined) result.noRot = parseOnOff(a[\"noRot\"]) ?? true;\n if (a[\"noChangeAspect\"] !== undefined)\n result.noChangeAspect = parseOnOff(a[\"noChangeAspect\"]) ?? true;\n if (a[\"noMove\"] !== undefined) result.noMove = parseOnOff(a[\"noMove\"]) ?? true;\n if (a[\"noResize\"] !== undefined) result.noResize = parseOnOff(a[\"noResize\"]) ?? true;\n return Object.keys(result).length === 0 ? undefined : (result as GroupShapeLocksOptions);\n}\n\n/**\n * Extract {@link AnchorInfo} from the drawing's wp:inline or wp:anchor.\n * Returns `null` when the drawing has neither wrapper.\n */\nfunction parseAnchorOrInline(el: Element): AnchorInfo | null {\n const inline = findFirst(el, \"wp:inline\");\n const anchor = inline ? undefined : findFirst(el, \"wp:anchor\");\n const parent = inline ?? anchor;\n if (!parent) return null;\n\n const info: AnchorInfo = {};\n\n // Extent (EMU)\n const extent = findChild(parent, \"wp:extent\");\n if (extent) {\n const cxEmu = attrNum(extent, \"cx\");\n const cyEmu = attrNum(extent, \"cy\");\n if (cxEmu !== undefined) info.width = cxEmu;\n if (cyEmu !== undefined) info.height = cyEmu;\n }\n\n // Effect extent (raw EMUs — round-tripped verbatim, never converted to pixels)\n const ee = findChild(parent, \"wp:effectExtent\");\n if (ee) {\n info.effectExtent = {\n l: attrNum(ee, \"l\") ?? 0,\n t: attrNum(ee, \"t\") ?? 0,\n r: attrNum(ee, \"r\") ?? 0,\n b: attrNum(ee, \"b\") ?? 0,\n };\n }\n\n // Alt text (wp:docPr) — keep the id too so it round-trips verbatim\n const docPr = findChild(parent, \"wp:docPr\");\n if (docPr) {\n const cNvPrOpts = parseNonVisualDrawingProperties(docPr);\n const id = attr(docPr, \"id\");\n if (id !== undefined || Object.keys(cNvPrOpts).length > 0) {\n const alt: Partial<DocPropertiesOptions> = { ...cNvPrOpts };\n if (id !== undefined) alt.id = id;\n info.altText = alt as DocPropertiesOptions;\n }\n }\n\n // Graphic frame locks (wp:cNvGraphicFramePr) — preserved verbatim.\n const cNvGraphicFramePr = findChild(parent, \"wp:cNvGraphicFramePr\");\n if (cNvGraphicFramePr) info.graphicFrameLocks = readGraphicFrameLocks(cNvGraphicFramePr);\n\n // Floating (anchor only)\n if (anchor && !inline) {\n const floating: Partial<Floating> = {};\n\n // Margins (distT/distB/distL/distR on wp:anchor)\n const margins: Margins = {};\n const distT = attrNum(anchor, \"distT\");\n if (distT !== undefined) margins.top = distT;\n const distB = attrNum(anchor, \"distB\");\n if (distB !== undefined) margins.bottom = distB;\n const distL = attrNum(anchor, \"distL\");\n if (distL !== undefined) margins.left = distL;\n const distR = attrNum(anchor, \"distR\");\n if (distR !== undefined) margins.right = distR;\n if (Object.keys(margins).length > 0) floating.margins = margins;\n\n // Position H/V (relativeFrom + align/posOffset)\n const posH = findChild(anchor, \"wp:positionH\");\n if (posH) {\n const hp = readPosition(posH);\n if (hp) floating.horizontalPosition = hp as HorizontalPositionOptions;\n }\n const posV = findChild(anchor, \"wp:positionV\");\n if (posV) {\n const vp = readPosition(posV);\n if (vp) floating.verticalPosition = vp as VerticalPositionOptions;\n }\n\n // Wrap (element name → TextWrappingType number) + optional side\n const wrap = readWrap(anchor);\n if (wrap) floating.wrap = wrap;\n\n // Anchor-level flags (stringifyAnchor writes all of these)\n const allowOverlap = attrBool(anchor, \"allowOverlap\");\n if (allowOverlap !== undefined) floating.allowOverlap = allowOverlap;\n const behindDoc = attrBool(anchor, \"behindDoc\");\n if (behindDoc !== undefined) floating.behindDocument = behindDoc;\n const locked = attrBool(anchor, \"locked\");\n if (locked !== undefined) floating.lockAnchor = locked;\n const layoutInCell = attrBool(anchor, \"layoutInCell\");\n if (layoutInCell !== undefined) floating.layoutInCell = layoutInCell;\n const relativeHeight = attrNum(anchor, \"relativeHeight\");\n if (relativeHeight !== undefined) floating.zIndex = relativeHeight;\n\n if (Object.keys(floating).length > 0) info.floating = floating as Floating;\n }\n\n return info;\n}\n\n/**\n * Parse a w:drawing element and return picture data wrapped in { picture: ... }.\n */\nexport function parsePictureRun(\n el: Element,\n ctx: DocxReadContext,\n): { picture: PictureOptions } | undefined {\n const info = parseAnchorOrInline(el);\n if (!info) return undefined;\n\n // Get graphic → graphicData → blip\n const blip = findFirst(el, \"a:blip\");\n if (!blip) return undefined;\n\n const rEmbed = attr(blip, \"r:embed\");\n if (!rEmbed) return undefined;\n\n // Resolve the media path against the current part's relationships\n const mediaPath = ctx.resolveRelationship(rEmbed);\n if (!mediaPath) return undefined;\n\n // Read image data from ZIP\n const imageData = ctx.docx.doc.getRaw(mediaPath);\n if (!imageData) return undefined;\n\n const type = imageTypeFromPath(mediaPath);\n\n const imageOpts: Record<string, unknown> = {\n type,\n data: imageData,\n transformation: {\n ...(info.width !== undefined ? { width: info.width } : {}),\n ...(info.height !== undefined ? { height: info.height } : {}),\n ...(info.effectExtent ? { effectExtent: info.effectExtent } : {}),\n },\n };\n if (info.altText) imageOpts.altText = info.altText;\n if (info.floating) imageOpts.floating = info.floating;\n if (info.graphicFrameLocks !== undefined) imageOpts.graphicFrameLocks = info.graphicFrameLocks;\n\n // Blip-fill crop (pic:blipFill/a:srcRect)\n const blipFill = findFirst(el, \"pic:blipFill\");\n if (blipFill) {\n const srcRect = readSourceRectangle(blipFill);\n if (srcRect) imageOpts.sourceRectangle = srcRect;\n }\n\n // Picture non-visual properties (pic:nvPicPr/pic:cNvPr)\n const cNvPr = readPicCnvPr(el);\n if (cNvPr) imageOpts.nonVisualProperties = cNvPr;\n\n // Picture shape properties (pic:spPr): outline + fill + effects round-trip\n // via the shared core descriptors (bidirectional).\n const picSpPr = findFirst(el, \"pic:spPr\");\n if (picSpPr) {\n const fill = readShapeFill(picSpPr, ctx);\n if (fill) imageOpts.fill = fill;\n const ln = findChild(picSpPr, \"a:ln\");\n if (ln) imageOpts.outline = outlineDesc.parse(ln, ctx);\n const effectLst = findChild(picSpPr, \"a:effectLst\");\n if (effectLst) imageOpts.effects = effectListDesc.parse(effectLst, ctx);\n // Rotation/flip live on pic:spPr/a:xfrm (ST_Angle in 1/60000 deg). Convert\n // to degrees to match the MediaTransformation API — createTransformation\n // multiplies back by 60_000 on stringify, so integer-degree rotation stays\n // lossless across round-trip.\n const xfrm = findChild(picSpPr, \"a:xfrm\");\n if (xfrm) {\n const transform = imageOpts.transformation as {\n rotation?: number;\n flip?: { horizontal?: boolean; vertical?: boolean };\n };\n const rot = attrNum(xfrm, \"rot\");\n if (rot !== undefined) transform.rotation = parseAngle(rot);\n const flipH = attrBool(xfrm, \"flipH\");\n const flipV = attrBool(xfrm, \"flipV\");\n if (flipH !== undefined || flipV !== undefined) {\n transform.flip = {\n ...(flipH !== undefined ? { horizontal: flipH } : {}),\n ...(flipV !== undefined ? { vertical: flipV } : {}),\n };\n }\n }\n }\n\n // Blip recolor effects (a:lum/a:hsl/a:tint/...) under a:blip — image\n // brightness/contrast/tint adjustments applied directly to the image data.\n const blipResult = blipDesc.parse(blip, ctx);\n if (blipResult.blipEffects) imageOpts.blipEffects = blipResult.blipEffects;\n\n // Blip extension: a14:useLocalDpi (rendering hint, round-trip verbatim).\n const useLocalDpi = readBlipUseLocalDpi(blip);\n if (useLocalDpi !== undefined) imageOpts.useLocalDpi = useLocalDpi;\n\n // Blip extension: asvg:svgBlip — when present, the a:blip r:embed is the\n // raster fallback and the SVG part is referenced here. Restructure into an\n // SvgMediaOptions (vector primary + raster fallback) so stringify re-emits\n // both branches; otherwise the SVG is dropped on round-trip.\n const svg = readBlipSvg(blip, ctx);\n if (svg) {\n imageOpts.fallback = { type, data: imageData };\n imageOpts.type = \"svg\";\n imageOpts.data = svg.data;\n }\n\n return { picture: imageOpts as unknown as PictureOptions };\n}\n\n/**\n * Read the `a14:useLocalDpi` blip extension (val=\"0\" → false, \"1\" → true).\n * Returns undefined when the blip has no useLocalDpi extension.\n */\nfunction readBlipUseLocalDpi(blip: Element): boolean | undefined {\n const extLst = findChild(blip, \"a:extLst\");\n if (!extLst) return undefined;\n for (const ext of extLst.elements ?? []) {\n if (ext.type !== \"element\" || ext.name !== \"a:ext\") continue;\n const useLocalDpiEl = findChild(ext, \"a14:useLocalDpi\");\n if (useLocalDpiEl) {\n const val = useLocalDpiEl.attributes?.[\"val\"];\n return parseOnOff(val) ?? true;\n }\n }\n return undefined;\n}\n\n/**\n * Read the `asvg:svgBlip` blip extension. When present, the surrounding\n * `a:blip` r:embed carries the raster fallback and this extension targets the\n * vector SVG part. Returns the SVG bytes so the picture round-trips as an\n * SvgMediaOptions (vector primary + raster fallback); undefined when no SVG\n * extension exists.\n */\nfunction readBlipSvg(\n blip: Element,\n ctx: DocxReadContext,\n): { data: Uint8Array; fileName: string } | undefined {\n const extLst = findChild(blip, \"a:extLst\");\n if (!extLst) return undefined;\n for (const ext of extLst.elements ?? []) {\n if (ext.type !== \"element\" || ext.name !== \"a:ext\") continue;\n const svgBlip = findChild(ext, \"asvg:svgBlip\");\n if (svgBlip) {\n const rEmbed = attr(svgBlip, \"r:embed\");\n if (!rEmbed) return undefined;\n const svgPath = ctx.resolveRelationship(rEmbed);\n if (!svgPath) return undefined;\n const data = ctx.docx.doc.getRaw(svgPath);\n if (!data) return undefined;\n return { data, fileName: svgPath.split(\"/\").pop() ?? svgPath };\n }\n }\n return undefined;\n}\n\n// ── WPS shape / WPG group parsing ───────────────────────────────────────────\n\n/**\n * Read the blip-fill crop rectangle (`a:srcRect`, l/t/r/b percentage insets)\n * from a `pic:blipFill` parent. Returns undefined when there is no crop.\n */\nfunction readSourceRectangle(parent: Element): SourceRectangleOptions | undefined {\n const sr = findChild(parent, \"a:srcRect\");\n if (!sr) return undefined;\n const result: SourceRectangleOptions = {};\n const left = attrNum(sr, \"l\");\n const top = attrNum(sr, \"t\");\n const right = attrNum(sr, \"r\");\n const bottom = attrNum(sr, \"b\");\n if (left !== undefined) result.left = left;\n if (top !== undefined) result.top = top;\n if (right !== undefined) result.right = right;\n if (bottom !== undefined) result.bottom = bottom;\n // An empty <a:srcRect/> is meaningful (explicit no-crop reset), so return\n // the object even when no l/t/r/b attributes are present.\n return result as SourceRectangleOptions;\n}\n\n/**\n * Read pic:cNvPr (id/name/descr) from a drawing's pic:nvPicPr. Returns\n * undefined when there is no non-visual properties block.\n */\nfunction readPicCnvPr(el: Element): NonVisualPropertiesOptions | undefined {\n const nvPicPr = findFirst(el, \"pic:nvPicPr\");\n if (!nvPicPr) return undefined;\n const cNvPr = findChild(nvPicPr, \"pic:cNvPr\");\n const result: NonVisualPropertiesOptions = { ...parseNonVisualDrawingProperties(cNvPr) };\n if (cNvPr) {\n const id = attrNum(cNvPr, \"id\");\n if (id !== undefined) result.id = id;\n }\n // pic:cNvPicPr sibling — only preferRelativeResize is tracked (Word omits\n // the default true; an explicit false round-trips as \"0\").\n const cNvPicPr = findChild(nvPicPr, \"pic:cNvPicPr\");\n if (cNvPicPr) {\n const preferRelativeResize = attrBool(cNvPicPr, \"preferRelativeResize\");\n if (preferRelativeResize !== undefined) result.preferRelativeResize = preferRelativeResize;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\n/**\n * Read a fill element from a shape-properties parent, if present. Delegates to\n * core {@link fillDesc} so solid/gradient/pattern/group/no fills all round-trip\n * through the shared descriptor.\n */\nfunction readShapeFill(parent: Element, ctx: DocxReadContext) {\n const fillChild =\n findChild(parent, \"a:noFill\") ??\n findChild(parent, \"a:solidFill\") ??\n findChild(parent, \"a:gradFill\") ??\n findChild(parent, \"a:pattFill\") ??\n findChild(parent, \"a:grpFill\") ??\n findChild(parent, \"a:blipFill\");\n if (!fillChild) return undefined;\n return fillDesc.parse(parent, ctx);\n}\n\n/**\n * Read a single style-matrix reference (a:lnRef/a:fillRef/a:effectRef/a:fontRef):\n * the `idx` attribute plus an optional EG_ColorChoice color override.\n */\nfunction parseStyleRef(el: Element, ctx: DocxReadContext): ShapeStyleReferenceOptions | undefined {\n const idx = attr(el, \"idx\");\n if (idx === undefined) return undefined;\n const result: ShapeStyleReferenceOptions = { idx };\n const color = parseColorChoice(el, ctx);\n if (color && Object.keys(color).length > 0) result.color = color;\n return result as ShapeStyleReferenceOptions;\n}\n\n/**\n * Parse a wps:style (CT_ShapeStyle): line/fill/effect/font references into the\n * document theme. Delegates color to the shared core {@link parseColorChoice}.\n */\nfunction parseShapeStyle(styleEl: Element, ctx: DocxReadContext): ShapeStyleOptions {\n const result: ShapeStyleOptions = {};\n const lnRef = findChild(styleEl, \"a:lnRef\");\n if (lnRef) result.lineReference = parseStyleRef(lnRef, ctx);\n const fillRef = findChild(styleEl, \"a:fillRef\");\n if (fillRef) result.fillReference = parseStyleRef(fillRef, ctx);\n const effectRef = findChild(styleEl, \"a:effectRef\");\n if (effectRef) result.effectReference = parseStyleRef(effectRef, ctx);\n const fontRef = findChild(styleEl, \"a:fontRef\");\n if (fontRef) result.fontReference = parseStyleRef(fontRef, ctx);\n return result as ShapeStyleOptions;\n}\n\n/**\n * Parse the shared core of a `wps:wsp` element (everything except the outer\n * drawing transformation/floating): text content, body properties, fill, and\n * the txBox non-visual flag. Used both for standalone wps shapes and for wps\n * children nested inside a wpg group.\n */\nfunction parseWpsShapeCore(wspEl: Element, ctx: DocxReadContext): ShapeCoreOptions {\n const result: Partial<ShapeCoreOptions> = {};\n\n // Text content — w:txbxContent (w namespace, per CT_TxbxContent → w:EG_BlockLevelElts)\n // holds the shape's paragraphs, even when wrapped in wps:txbx.\n const txbxContent = findFirst(wspEl, \"w:txbxContent\");\n const children: ShapeCoreOptions[\"children\"] = [];\n if (txbxContent) {\n for (const child of txbxContent.elements ?? []) {\n if (child.name === \"w:p\") children.push(parseParagraph(child, ctx));\n }\n }\n result.children = children;\n\n // Linked text box chain (wps:linkedTxbx) — XSD choice partner of txbx.\n const linkedTxbx = findChild(wspEl, \"wps:linkedTxbx\");\n if (linkedTxbx) {\n result.linkedTextBox = {\n id: attrNum(linkedTxbx, \"id\") ?? 0,\n sequence: attrNum(linkedTxbx, \"seq\") ?? 1,\n };\n }\n // East-Asian vertical flow (wps:wsp @normalEastAsianFlow)\n const normalEastAsianFlow = attrBool(wspEl, \"normalEastAsianFlow\");\n if (normalEastAsianFlow !== undefined) result.normalEastAsianFlow = normalEastAsianFlow;\n\n // Non-visual shape properties: wps:cNvPr (id/name/descr) + a choice of\n // wps:cNvSpPr (txBox marker) or wps:cNvCnPr (connector) — mutually exclusive.\n const cNvPr = findChild(wspEl, \"wps:cNvPr\");\n const cNvSpPr = findChild(wspEl, \"wps:cNvSpPr\");\n const cNvCnPr = findChild(wspEl, \"wps:cNvCnPr\");\n const txBox = cNvSpPr ? attr(cNvSpPr, \"txBox\") : undefined;\n if (cNvPr || txBox !== undefined || cNvCnPr) {\n const nvp: NonVisualShapePropertiesOptions = {};\n if (cNvPr) {\n const id = attrNum(cNvPr, \"id\");\n const name = attr(cNvPr, \"name\");\n const descr = attr(cNvPr, \"descr\");\n const title = attr(cNvPr, \"title\");\n if (id !== undefined) nvp.id = id;\n if (name) nvp.name = name;\n if (descr) nvp.description = descr;\n if (title) nvp.title = title;\n }\n if (cNvCnPr) nvp.connector = true;\n else if (txBox !== undefined) nvp.textBox = txBox;\n result.nonVisualProperties = nvp as NonVisualShapePropertiesOptions;\n }\n\n // Shape properties (wps:spPr) — fill/outline/effects/geometry round-trip via\n // the shared core descriptors (bidirectional) so spPr stays structured.\n const spPr = findChild(wspEl, \"wps:spPr\");\n if (spPr) {\n const fill = readShapeFill(spPr, ctx);\n if (fill) result.fill = fill;\n const ln = findChild(spPr, \"a:ln\");\n if (ln) result.outline = outlineDesc.parse(ln, ctx);\n const effectLst = findChild(spPr, \"a:effectLst\");\n if (effectLst) result.effects = effectListDesc.parse(effectLst, ctx);\n const custGeom = findChild(spPr, \"a:custGeom\");\n if (custGeom) result.customGeometry = customGeometryDesc.parse(custGeom, ctx);\n const prstGeom = findChild(spPr, \"a:prstGeom\");\n if (prstGeom) result.presetGeometry = presetGeometryDesc.parse(prstGeom, ctx);\n const scene3d = findChild(spPr, \"a:scene3d\");\n if (scene3d) result.scene3d = scene3DDesc.parse(scene3d, ctx);\n const sp3d = findChild(spPr, \"a:sp3d\");\n if (sp3d) result.shape3d = shape3DDesc.parse(sp3d, ctx);\n }\n\n // Body properties (wps:bodyPr)\n const bodyPr = findChild(wspEl, \"wps:bodyPr\");\n if (bodyPr) result.bodyProperties = parseBodyProperties(bodyPr, ctx);\n\n // Shape style (wps:style) — theme references (lnRef/fillRef/effectRef/fontRef)\n const styleEl = findChild(wspEl, \"wps:style\");\n if (styleEl) result.style = parseShapeStyle(styleEl, ctx);\n\n return result as ShapeCoreOptions;\n}\n\n/**\n * Build a child's MediaDataTransformation directly from an `a:xfrm`, keeping\n * EMU values intact (no pixel rounding) so group child coordinates survive\n * round-trip without drift.\n */\nfunction readChildTransformation(spPr: Element | undefined): MediaDataTransformation {\n const result: MediaDataTransformation = {\n pixels: { x: 0, y: 0 },\n emus: { x: 0, y: 0 },\n };\n if (!spPr) return result;\n const xfrm = findChild(spPr, \"a:xfrm\");\n if (!xfrm) return result;\n\n const off = findChild(xfrm, \"a:off\");\n if (off?.attributes) {\n const x = Number(off.attributes[\"x\"] ?? 0);\n const y = Number(off.attributes[\"y\"] ?? 0);\n result.offset = {\n emus: { x, y },\n pixels: { x: convertEmuToPixels(x), y: convertEmuToPixels(y) },\n };\n }\n const ext = findChild(xfrm, \"a:ext\");\n if (ext?.attributes) {\n const cx = Number(ext.attributes[\"cx\"] ?? 0);\n const cy = Number(ext.attributes[\"cy\"] ?? 0);\n result.emus = { x: cx, y: cy };\n result.pixels = { x: convertEmuToPixels(cx), y: convertEmuToPixels(cy) };\n }\n\n const flipH = attrBool(xfrm, \"flipH\");\n const flipV = attrBool(xfrm, \"flipV\");\n if (flipH !== undefined || flipV !== undefined) {\n const flip: { horizontal?: boolean; vertical?: boolean } = {};\n if (flipH !== undefined) flip.horizontal = flipH;\n if (flipV !== undefined) flip.vertical = flipV;\n result.flip = flip;\n }\n const rot = attrNum(xfrm, \"rot\");\n if (rot !== undefined) result.rotation = rot;\n\n return result;\n}\n\n/**\n * Build a MediaDataTransformation from a directly nested xfrm (graphicFrame /\n * contentPart carry wp:/wpg:xfrm as a direct child instead of inside spPr).\n */\nfunction readDirectXfrmTransformation(el: Element): MediaDataTransformation {\n const xfrm = (el.elements ?? []).find(\n (c) => c.type === \"element\" && /^(wp|wpg|a):xfrm$/.test(c.name ?? \"\"),\n ) as Element | undefined;\n if (!xfrm) return { pixels: { x: 0, y: 0 }, emus: { x: 0, y: 0 } };\n\n const result: MediaDataTransformation = { pixels: { x: 0, y: 0 }, emus: { x: 0, y: 0 } };\n const off = findChild(xfrm, \"a:off\");\n if (off?.attributes) {\n result.offset = {\n emus: { x: Number(off.attributes[\"x\"] ?? 0), y: Number(off.attributes[\"y\"] ?? 0) },\n pixels: {\n x: convertEmuToPixels(Number(off.attributes[\"x\"] ?? 0)),\n y: convertEmuToPixels(Number(off.attributes[\"y\"] ?? 0)),\n },\n };\n }\n const ext = findChild(xfrm, \"a:ext\");\n if (ext?.attributes) {\n const cx = Number(ext.attributes[\"cx\"] ?? 0);\n const cy = Number(ext.attributes[\"cy\"] ?? 0);\n result.emus = { x: cx, y: cy };\n result.pixels = { x: convertEmuToPixels(cx), y: convertEmuToPixels(cy) };\n }\n return result;\n}\n\n/**\n * Parse a `wps:wsp` nested inside a wpg group into a {@link ShapeMediaData} child\n * (its transformation kept as EMU via {@link readChildTransformation}).\n */\nfunction parseWpsChildMediaData(wspEl: Element, ctx: DocxReadContext): ShapeMediaData | undefined {\n const data = parseWpsShapeCore(wspEl, ctx);\n const spPr = findChild(wspEl, \"wps:spPr\");\n return {\n type: \"wps\",\n transformation: readChildTransformation(spPr),\n data,\n };\n}\n\n/**\n * Parse a `pic:pic` nested inside a wpg group into a {@link MediaData} child.\n * Uses the original media path as the registration key so repeated references\n * to the same image collapse to one media entry.\n */\nfunction parsePicChildMediaData(picEl: Element, ctx: DocxReadContext): MediaData | undefined {\n const blip = findFirst(picEl, \"a:blip\");\n if (!blip) return undefined;\n const rEmbed = attr(blip, \"r:embed\");\n if (!rEmbed) return undefined;\n\n const mediaPath = ctx.resolveRelationship(rEmbed);\n if (!mediaPath) return undefined;\n const data = ctx.docx.doc.getRaw(mediaPath);\n if (!data) return undefined;\n\n const spPr = findChild(picEl, \"pic:spPr\");\n const result: MediaData = {\n type: imageTypeFromPath(mediaPath),\n // fileName is the bare basename; the compiler writes it under word/media/.\n fileName: mediaPath.split(\"/\").pop() ?? mediaPath,\n data,\n transformation: readChildTransformation(spPr),\n };\n const blipFill = findChild(picEl, \"pic:blipFill\");\n if (blipFill) {\n const srcRect = readSourceRectangle(blipFill);\n if (srcRect) result.sourceRectangle = srcRect;\n }\n const cNvPr = readPicCnvPr(picEl);\n if (cNvPr) result.nonVisualProperties = cNvPr;\n // Grouped picture spPr (fill/outline) rides on GroupCommonMediaData so it\n // round-trips through stringifyGroupChild → stringifyShapeProps.\n if (spPr) {\n const fill = readShapeFill(spPr, ctx);\n if (fill) (result as MediaData & GroupCommonMediaData).fill = fill;\n const ln = findChild(spPr, \"a:ln\");\n if (ln) (result as MediaData & GroupCommonMediaData).outline = outlineDesc.parse(ln, ctx);\n }\n // asvg:svgBlip extension — when present, the a:blip r:embed is the raster\n // fallback and the vector SVG lives in the extension. Reshape into an\n // SvgMediaData so stringify re-emits both (vector + fallback); otherwise the\n // SVG is dropped on round-trip.\n const svg = readBlipSvg(blip, ctx);\n if (svg) {\n return {\n ...result,\n type: \"svg\",\n data: svg.data,\n fileName: svg.fileName,\n fallback: {\n type: result.type,\n fileName: result.fileName,\n data,\n transformation: result.transformation,\n },\n } as MediaData;\n }\n return result;\n}\n\n/**\n * Parse a standalone wps shape drawing (graphicData URI wordprocessingShape).\n */\nfunction parseWpsShapeDrawing(\n el: Element,\n ctx: DocxReadContext,\n): { wpsShape: ShapeOptions } | undefined {\n const wsp = findFirst(el, \"wps:wsp\");\n if (!wsp) return undefined;\n\n const info = parseAnchorOrInline(el) ?? {};\n const data = parseWpsShapeCore(wsp, ctx);\n\n const shape: ShapeOptions = {\n ...data,\n transformation: {\n width: info.width ?? 0,\n height: info.height ?? 0,\n ...(info.effectExtent ? { effectExtent: info.effectExtent } : {}),\n },\n };\n if (info.floating) shape.floating = info.floating;\n if (info.altText) shape.altText = info.altText;\n if (info.graphicFrameLocks !== undefined) shape.graphicFrameLocks = info.graphicFrameLocks;\n\n return { wpsShape: shape as ShapeOptions };\n}\n\n/**\n * Parse a wpg group drawing (graphicData URI wordprocessingGroup).\n */\nfunction parseWpgGroupDrawing(\n el: Element,\n ctx: DocxReadContext,\n): { wpgGroup: GroupOptions } | undefined {\n const wgp = findFirst(el, \"wpg:wgp\");\n if (!wgp) return undefined;\n\n const info = parseAnchorOrInline(el) ?? {};\n const grpSpPr = findChild(wgp, \"wpg:grpSpPr\");\n const { childOffset, childExtent } = readGroupCoords(grpSpPr);\n\n const group: GroupOptions = {\n children: parseGroupChildren(wgp, ctx),\n transformation: {\n width: info.width ?? 0,\n height: info.height ?? 0,\n ...(info.effectExtent ? { effectExtent: info.effectExtent } : {}),\n },\n };\n if (childOffset) group.childOffset = childOffset;\n if (childExtent) group.childExtent = childExtent;\n if (info.floating) group.floating = info.floating;\n if (info.altText) group.altText = info.altText;\n if (info.graphicFrameLocks !== undefined) group.graphicFrameLocks = info.graphicFrameLocks;\n const grpSpLocks = readGrpSpLocks(findChild(wgp, \"wpg:cNvGrpSpPr\"));\n if (grpSpLocks) group.groupShapeLocks = grpSpLocks;\n // Group shape props (grpSpPr): fill + effects round-trip via shared descriptors.\n if (grpSpPr) {\n const fill = readShapeFill(grpSpPr, ctx);\n if (fill) group.fill = fill;\n const effectLst = findChild(grpSpPr, \"a:effectLst\");\n if (effectLst) group.effects = effectListDesc.parse(effectLst, ctx);\n }\n\n return { wpgGroup: group as GroupOptions };\n}\n\n/**\n * Read chOff/chExt child coordinate space from a group's grpSpPr/a:xfrm.\n * Shared by the top-level wpg:wgp and nested wpg:grpSp.\n */\nfunction readGroupCoords(grpSpPr: Element | undefined): {\n childOffset?: ChildOffset;\n childExtent?: ChildExtent;\n} {\n if (!grpSpPr) return {};\n const xfrm = findChild(grpSpPr, \"a:xfrm\");\n if (!xfrm) return {};\n let childOffset: ChildOffset | undefined;\n let childExtent: ChildExtent | undefined;\n const off = findChild(xfrm, \"a:chOff\");\n if (off?.attributes) {\n childOffset = { x: Number(off.attributes[\"x\"] ?? 0), y: Number(off.attributes[\"y\"] ?? 0) };\n }\n const ext = findChild(xfrm, \"a:chExt\");\n if (ext?.attributes) {\n childExtent = { cx: Number(ext.attributes[\"cx\"] ?? 0), cy: Number(ext.attributes[\"cy\"] ?? 0) };\n }\n return { childOffset, childExtent };\n}\n\n/**\n * Parse the children of a group element (CT_WordprocessingGroup choice):\n * wps:wsp shapes, pic:pic pictures, and nested wpg:grpSp groups (recursive).\n */\nfunction parseGroupChildren(groupEl: Element, ctx: DocxReadContext): GroupChildMediaData[] {\n const children: GroupChildMediaData[] = [];\n for (const child of groupEl.elements ?? []) {\n if (child.type !== \"element\") continue;\n const md = parseGroupChild(child, ctx);\n if (md) children.push(md);\n }\n return children;\n}\n\nfunction parseGroupChild(el: Element, ctx: DocxReadContext): GroupChildMediaData | undefined {\n if (el.name === \"wps:wsp\") return parseWpsChildMediaData(el, ctx);\n if (el.name === \"pic:pic\") {\n return parsePicChildMediaData(el, ctx) as GroupChildMediaData | undefined;\n }\n if (el.name === \"wpg:grpSp\") return parseNestedGroup(el, ctx);\n if (el.name === \"wpg:graphicFrame\") return parseGroupGraphicFrame(el, ctx);\n if (el.name === \"wpg:contentPart\" || el.name === \"wp:contentPart\") return parseContentPart(el);\n return undefined;\n}\n\n/**\n * Parse a wpg:graphicFrame group child (CT_GraphicFrame). Charts are the\n * payload Word produces in groups; the chart part is re-registered on\n * generate from the parsed chartOptions.\n */\nfunction parseGroupGraphicFrame(el: Element, ctx: DocxReadContext): ChartMediaData | undefined {\n const chartRef = findFirst(el, \"c:chart\");\n if (!chartRef) return undefined;\n const rId = attr(chartRef, \"r:id\");\n const chartPath = rId ? lookupRId(ctx.docx.partRefs.charts, rId) : undefined;\n if (!chartPath) return undefined;\n\n const chartXml = ctx.docx.doc.get(chartPath);\n if (!chartXml) return undefined;\n const chartOpts = parseChartXml(chartXml);\n if (!chartOpts) return undefined;\n\n const md: ChartMediaData = {\n type: \"chart\",\n transformation: readDirectXfrmTransformation(el),\n chartOptions: chartOpts as ChartSpaceOptions,\n };\n\n const cNvPr = findChild(el, \"wpg:cNvPr\") ?? findChild(el, \"wp:cNvPr\");\n if (cNvPr) {\n const nvp: NonVisualPropertiesOptions = {};\n const id = attrNum(cNvPr, \"id\");\n const name = attr(cNvPr, \"name\");\n const descr = attr(cNvPr, \"descr\");\n const title = attr(cNvPr, \"title\");\n if (id !== undefined) nvp.id = id;\n if (name) nvp.name = name;\n if (descr) nvp.description = descr;\n if (title) nvp.title = title;\n if (Object.keys(nvp).length > 0) md.nonVisualProperties = nvp;\n }\n const cNvFrPr = findChild(el, \"wpg:cNvFrPr\") ?? findChild(el, \"wp:cNvFrPr\");\n if (cNvFrPr) md.graphicFrameLocks = readGraphicFrameLocks(cNvFrPr);\n\n return md;\n}\n\n/**\n * Parse a wp:/wpg:contentPart element (CT_WordprocessingContentPart). The\n * r:id is captured verbatim — the relationship itself is not re-registered\n * on generate.\n */\nfunction parseContentPart(el: Element): ContentPartMediaData {\n const md: ContentPartMediaData = {\n type: \"contentPart\",\n referenceId: attr(el, \"r:id\") ?? \"\",\n transformation: readDirectXfrmTransformation(el),\n };\n const bwMode = attr(el, \"bwMode\");\n if (bwMode) md.blackWhiteMode = bwMode as BlackWhiteMode;\n\n const nv = findChild(el, \"wp:nvContentPartPr\") ?? findChild(el, \"wpg:nvContentPartPr\");\n if (nv) {\n const cNvPr = findChild(nv, \"wp:cNvPr\") ?? findChild(nv, \"wpg:cNvPr\");\n const cpPr = findChild(nv, \"wp:cNvContentPartPr\") ?? findChild(nv, \"wpg:cNvContentPartPr\");\n const nvp: NonVisualContentPartNv = {};\n if (cNvPr) {\n const id = attrNum(cNvPr, \"id\");\n const name = attr(cNvPr, \"name\");\n const descr = attr(cNvPr, \"descr\");\n const title = attr(cNvPr, \"title\");\n if (id !== undefined) nvp.id = id;\n if (name) nvp.name = name;\n if (descr) nvp.description = descr;\n if (title) nvp.title = title;\n }\n const contentPart = parseNonVisualContentPartProperties(cpPr);\n if (contentPart) nvp.contentPart = contentPart;\n if (Object.keys(nvp).length > 0) md.nonVisualProperties = nvp;\n }\n return md;\n}\n\n/** Non-visual properties of a content part (cNvPr + cNvContentPartPr). */\ninterface NonVisualContentPartNv extends NonVisualPropertiesOptions {\n contentPart?: NonVisualContentPartPropertiesOptions;\n}\n\n/**\n * Parse a nested wpg:grpSp (CT_WordprocessingGroup) into a GroupMediaData child.\n * Mirrors the top-level group: grpSpPr transform + chOff/chExt + fill, with its\n * own children (which may nest further groups).\n */\nfunction parseNestedGroup(grpSpEl: Element, ctx: DocxReadContext): GroupMediaData {\n const grpSpPr = findChild(grpSpEl, \"wpg:grpSpPr\");\n const { childOffset, childExtent } = readGroupCoords(grpSpPr);\n const result: GroupMediaData = {\n type: \"wpg\",\n transformation: readChildTransformation(grpSpPr),\n children: parseGroupChildren(grpSpEl, ctx),\n };\n if (childOffset) result.childOffset = childOffset;\n if (childExtent) result.childExtent = childExtent;\n const grpSpLocks = readGrpSpLocks(findChild(grpSpEl, \"wpg:cNvGrpSpPr\"));\n if (grpSpLocks) result.groupShapeLocks = grpSpLocks;\n if (grpSpPr) {\n const fill = readShapeFill(grpSpPr, ctx);\n if (fill) result.fill = fill;\n }\n return result;\n}\n\n// ── Floating (anchor) parse helpers ─────────────────────────────────────────\n\n/** Map wp:positionH/V children + relativeFrom into a position-options object. */\nfunction readPosition(\n posEl: Element,\n): HorizontalPositionOptions | VerticalPositionOptions | undefined {\n const relative = attr(posEl, \"relativeFrom\");\n const alignEl = findChild(posEl, \"wp:align\");\n const posOffset = findChild(posEl, \"wp:posOffset\");\n const result: { relative?: string; align?: string; offset?: number } = {};\n if (relative) result.relative = relative;\n if (alignEl) {\n const a = textOf(alignEl);\n if (a) result.align = a;\n } else if (posOffset) {\n const val = Number(textOf(posOffset));\n if (!isNaN(val)) result.offset = val;\n }\n return Object.keys(result).length > 0\n ? (result as HorizontalPositionOptions | VerticalPositionOptions)\n : undefined;\n}\n\n/** Read wp:wrapPolygon (start + lineTo points) into a WrapPolygon, if present. */\nfunction readWrapPolygon(el: Element): WrapPolygon | undefined {\n const poly = findChild(el, \"wp:wrapPolygon\");\n if (!poly) return undefined;\n const points: { x: number; y: number }[] = [];\n const start = findChild(poly, \"wp:start\");\n if (start) points.push({ x: attrNum(start, \"x\") ?? 0, y: attrNum(start, \"y\") ?? 0 });\n for (const child of poly.elements ?? []) {\n if (child.name === \"wp:lineTo\") {\n points.push({ x: attrNum(child, \"x\") ?? 0, y: attrNum(child, \"y\") ?? 0 });\n }\n }\n if (points.length === 0) return undefined;\n return { edited: attrBool(poly, \"edited\"), points };\n}\n\n/** Map the wp:anchor wrap child element into a TextWrapping ({ type, side? }). */\nfunction readWrap(anchor: Element): TextWrapping | undefined {\n const WRAP_TYPE: ReadonlyArray<[string, TextWrapping[\"type\"]]> = [\n [\"wrapNone\", TextWrappingType.NONE],\n [\"wrapSquare\", TextWrappingType.SQUARE],\n [\"wrapTight\", TextWrappingType.TIGHT],\n [\"wrapTopAndBottom\", TextWrappingType.TOP_AND_BOTTOM],\n [\"wrapThrough\", TextWrappingType.THROUGH],\n ];\n for (const [name, type] of WRAP_TYPE) {\n const el = findChild(anchor, `wp:${name}`);\n if (!el) continue;\n const wrap: TextWrapping = { type };\n const side = attr(el, \"wrapText\");\n if (side) wrap.side = side as TextWrapping[\"side\"];\n // wrapTight/wrapThrough carry a contour polygon; preserve it verbatim.\n if (name === \"wrapTight\" || name === \"wrapThrough\") {\n const polygon = readWrapPolygon(el);\n if (polygon) wrap.polygon = polygon;\n }\n return wrap;\n }\n return undefined;\n}\n\n// ── Common helpers ──────────────────────────────────────────────────────────\n\nfunction getDrawingExtent(el: Element): { width?: number; height?: number } {\n const inline = findFirst(el, \"wp:inline\");\n const anchor = inline ? undefined : findFirst(el, \"wp:anchor\");\n const parent = inline ?? anchor;\n if (!parent) return {};\n\n const extent = findChild(parent, \"wp:extent\");\n if (!extent) return {};\n\n const cxEmu = attrNum(extent, \"cx\");\n const cyEmu = attrNum(extent, \"cy\");\n return {\n ...(cxEmu !== undefined ? { width: cxEmu } : {}),\n ...(cyEmu !== undefined ? { height: cyEmu } : {}),\n };\n}\n\n// ── Chart parsing ───────────────────────────────────────────────────────────\n\n/**\n * Look up a relationship ID in a map, with fallback for double \"rId\" prefix\n * that the library's generation code produces (e.g. \"rIdrId7\" → \"rId7\").\n */\nfunction lookupRId(map: Map<string, string>, rId: string | undefined): string | undefined {\n if (!rId) return undefined;\n const direct = map.get(rId);\n if (direct) return direct;\n // Fallback: strip one \"rId\" prefix when the value starts with \"rIdrId\"\n if (rId.startsWith(\"rIdrId\")) return map.get(rId.slice(3));\n return undefined;\n}\n\nfunction parseChartDrawing(el: Element, ctx: DocxReadContext): { chart: ChartOptions } | undefined {\n const chartRef = findFirst(el, \"c:chart\");\n if (!chartRef) return undefined;\n\n const rId = attr(chartRef, \"r:id\");\n const chartPath = lookupRId(ctx.docx.partRefs.charts, rId);\n if (!chartPath) return undefined;\n\n const chartXml = ctx.docx.doc.get(chartPath);\n if (!chartXml) return undefined;\n\n const opts = parseChartXml(chartXml);\n if (!opts) return undefined;\n\n const ext = getDrawingExtent(el);\n if (ext.width !== undefined || ext.height !== undefined) {\n (opts as Record<string, unknown>).transformation = {\n ...ext,\n };\n }\n\n return { chart: opts as unknown as ChartOptions };\n}\n\n/**\n * Parse c:chartSpace element into ChartSpaceOptions.\n */\nfunction parseChartXml(el: Element): Partial<ChartSpaceOptions> | undefined {\n const chart = findChild(el, \"c:chart\");\n if (!chart) return undefined;\n\n const opts: Partial<ChartSpaceOptions> = {};\n\n // Title: c:chart → c:title → c:tx → c:rich → a:p → a:r → a:t\n const titleEl = findChild(chart, \"c:title\");\n if (titleEl) {\n const rich = findFirst(titleEl, \"c:rich\");\n if (rich) {\n const t = findFirst(rich, \"a:t\");\n if (t) {\n const title = textOf(t);\n if (title) opts.title = title;\n }\n }\n }\n\n // Plot area → chart type\n const plotArea = findChild(chart, \"c:plotArea\");\n if (!plotArea) return undefined;\n\n let chartType: ChartSpaceOptions[\"type\"] | undefined;\n let typeElement: Element | undefined;\n\n for (const child of plotArea.elements ?? []) {\n switch (child.name) {\n case \"c:barChart\": {\n const barDir = findChild(child, \"c:barDir\");\n chartType = barDir && attr(barDir, \"val\") === \"bar\" ? \"bar\" : \"column\";\n typeElement = child;\n break;\n }\n case \"c:lineChart\":\n chartType = \"line\";\n typeElement = child;\n break;\n case \"c:pieChart\":\n chartType = \"pie\";\n typeElement = child;\n break;\n case \"c:areaChart\":\n chartType = \"area\";\n typeElement = child;\n break;\n case \"c:scatterChart\":\n chartType = \"scatter\";\n typeElement = child;\n break;\n }\n if (chartType) break;\n }\n\n if (!chartType || !typeElement) return undefined;\n opts.type = chartType;\n\n // Parse series\n const series: { name: string; values: number[] }[] = [];\n let categories: string[] | undefined;\n\n for (const serEl of typeElement.elements ?? []) {\n if (serEl.name !== \"c:ser\") continue;\n\n // Series name: c:tx → c:strCache → c:pt → c:v\n const nameParts = extractStrCache(serEl, \"c:tx\");\n // Categories: c:cat → c:strCache → c:pt → c:v\n const cats = extractStrCache(serEl, \"c:cat\");\n if (cats.length > 0 && !categories) categories = cats;\n // Values: c:val → c:numCache → c:pt → c:v\n const vals = extractNumCache(serEl);\n\n series.push({ name: nameParts[0] ?? \"\", values: vals });\n }\n\n opts.categories = categories ?? [];\n opts.series = series;\n\n // Legend\n opts.showLegend = findChild(chart, \"c:legend\") !== undefined;\n\n // Style\n const styleEl = findChild(el, \"c:style\");\n if (styleEl) {\n const val = attrNum(styleEl, \"val\");\n if (val !== undefined) opts.style = val;\n }\n\n return opts;\n}\n\n/**\n * Extract string values from c:strCache within a container element.\n */\nfunction extractStrCache(parent: Element, containerName: string): string[] {\n const container = findChild(parent, containerName);\n if (!container) return [];\n const cache = findFirst(container, \"c:strCache\");\n if (!cache) return [];\n\n const values: string[] = [];\n for (const pt of cache.elements ?? []) {\n if (pt.name !== \"c:pt\") continue;\n const v = findChild(pt, \"c:v\");\n if (v) values.push(textOf(v) ?? \"\");\n }\n return values;\n}\n\n/**\n * Extract numeric values from c:numCache within a c:val container.\n */\nfunction extractNumCache(parent: Element): number[] {\n const valEl = findChild(parent, \"c:val\");\n if (!valEl) return [];\n const cache = findFirst(valEl, \"c:numCache\");\n if (!cache) return [];\n\n const values: number[] = [];\n for (const pt of cache.elements ?? []) {\n if (pt.name !== \"c:pt\") continue;\n const v = findChild(pt, \"c:v\");\n if (v) {\n const num = Number(textOf(v));\n if (!isNaN(num)) values.push(num);\n }\n }\n return values;\n}\n\n// ── SmartArt parsing ────────────────────────────────────────────────────────\n\nfunction parseSmartArtDrawing(\n el: Element,\n ctx: DocxReadContext,\n): { smartArt: SmartArtOptions } | undefined {\n const relIds = findFirst(el, \"dgm:relIds\");\n if (!relIds) return undefined;\n\n const rId = attr(relIds, \"r:dm\");\n const dataPath = lookupRId(ctx.docx.partRefs.diagramData, rId);\n if (!dataPath) return undefined;\n\n const dataEl = ctx.docx.doc.get(dataPath);\n if (!dataEl) return undefined;\n\n const opts = parseSmartArtDataXml(dataEl);\n if (!opts) return undefined;\n\n // Custom definitions come back structured; built-in stubs fold to their id\n // string so round-tripping a built-in diagram keeps the compact form.\n const layoutEl = readDiagramPart(ctx, relIds, \"r:lo\", ctx.docx.partRefs.diagramLayout);\n if (layoutEl) {\n const layout = parseLayoutDefinition(layoutEl);\n const id = layout.uniqueId?.split(\"/\").pop();\n opts.layout = id && id in LAYOUT_CATEGORIES ? id : layout;\n }\n const styleEl = readDiagramPart(ctx, relIds, \"r:qs\", ctx.docx.partRefs.diagramQuickStyle);\n if (styleEl) {\n const style = parseStyleDefinition(styleEl);\n const id = style.uniqueId?.split(\"/\").pop();\n opts.style = id && id in STYLE_CATEGORIES ? id : style;\n }\n const colorEl = readDiagramPart(ctx, relIds, \"r:cs\", ctx.docx.partRefs.diagramColors);\n if (colorEl) {\n const color = parseColorDefinition(colorEl);\n const id = color.uniqueId?.split(\"/\").pop();\n opts.color = id && id in COLOR_CATEGORIES ? id : color;\n }\n\n const ext = getDrawingExtent(el);\n if (ext.width !== undefined || ext.height !== undefined) {\n (opts as Record<string, unknown>).transformation = {\n ...ext,\n };\n }\n\n return { smartArt: opts as unknown as SmartArtOptions };\n}\n\n/** Resolve a dgm:relIds attribute through a part-kind map to its element. */\nfunction readDiagramPart(\n ctx: DocxReadContext,\n relIds: Element,\n attrName: \"r:lo\" | \"r:qs\" | \"r:cs\",\n refs: Map<string, string>,\n): Element | undefined {\n const rId = attr(relIds, attrName);\n if (!rId) return undefined;\n const path = lookupRId(refs, rId);\n return path ? ctx.docx.doc.get(path) : undefined;\n}\n\n/**\n * Parse dgm:dataModel element into SmartArtOptions.\n */\nfunction parseSmartArtDataXml(el: Element): Record<string, unknown> | undefined {\n const ptLst = findChild(el, \"dgm:ptLst\");\n if (!ptLst) return undefined;\n\n const opts: Record<string, unknown> = {};\n const nodeMap = new Map<string, string>(); // modelId → text\n\n for (const pt of ptLst.elements ?? []) {\n if (pt.name !== \"dgm:pt\") continue;\n const type = attr(pt, \"type\");\n const modelId = attr(pt, \"modelId\");\n\n if (type === \"doc\") {\n // Extract layout/style/color from prSet URIs\n const prSet = findChild(pt, \"dgm:prSet\");\n if (prSet) {\n const loTypeId = attr(prSet, \"loTypeId\") ?? \"\";\n const qsTypeId = attr(prSet, \"qsTypeId\") ?? \"\";\n const csTypeId = attr(prSet, \"csTypeId\") ?? \"\";\n\n const layout = loTypeId.split(\"/\").pop();\n if (layout) opts.layout = layout;\n const style = qsTypeId.split(\"/\").pop();\n if (style) opts.style = style;\n const color = csTypeId.split(\"/\").pop();\n if (color) opts.color = color;\n }\n } else if (type === \"node\" && modelId) {\n // Extract text: dgm:t → a:p → a:r → a:t\n const t = findFirst(pt, \"a:t\");\n nodeMap.set(modelId, t ? (textOf(t) ?? \"\") : \"\");\n }\n }\n\n // Build tree from connections\n const cxnLst = findChild(el, \"dgm:cxnLst\");\n if (!cxnLst) {\n opts.data = { nodes: [] };\n return opts;\n }\n\n // Map: parentId → childIds\n const childrenMap = new Map<string, string[]>();\n for (const cxn of cxnLst.elements ?? []) {\n if (cxn.name !== \"dgm:cxn\") continue;\n const srcId = attr(cxn, \"srcId\");\n const destId = attr(cxn, \"destId\");\n if (!srcId || !destId || !nodeMap.has(destId)) continue;\n\n let arr = childrenMap.get(srcId);\n if (!arr) {\n arr = [];\n childrenMap.set(srcId, arr);\n }\n arr.push(destId);\n }\n\n // Root children are connected from doc node (modelId=\"0\")\n const topIds = childrenMap.get(\"0\") ?? [];\n opts.data = { nodes: topIds.map((id) => buildSmartArtNode(id, nodeMap, childrenMap)) };\n\n return opts;\n}\n\nfunction buildSmartArtNode(\n id: string,\n nodeMap: Map<string, string>,\n childrenMap: Map<string, string[]>,\n): { text: string; children?: unknown[] } {\n const text = nodeMap.get(id) ?? \"\";\n const childIds = childrenMap.get(id) ?? [];\n\n if (childIds.length === 0) return { text };\n return { text, children: childIds.map((cid) => buildSmartArtNode(cid, nodeMap, childrenMap)) };\n}\n","/**\n * Drawing descriptor for DOCX documents.\n *\n * Produces `<w:drawing>` XML directly from media data and options,\n * eliminating the Drawing/Inline/Anchor/Graphic/GraphicData/Pic XmlComponent\n * class chain (~10 instances per drawing in the old path).\n *\n * Common path (inline image/chart/smartart without advanced properties):\n * zero XmlComponent instances — pure string concatenation.\n *\n * Advanced properties (outline, fill, effects on images) and floating\n * positioning use core `create*()` + `.toXml({stack:[]})` for sub-elements\n * (lightweight BuilderElement instances, not deep hierarchies).\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_Drawing\n *\n * @module\n */\n\nimport { TargetModeType } from \"@office-open/core\";\nimport { convertToEmu, uniqueNumericIdCreator, uniqueId } from \"@office-open/core\";\nimport type { CustomDescriptor, WriteContext } from \"@office-open/core/descriptor\";\nimport type {\n BlipEffectsOptions,\n EffectListOptions,\n FillOptions,\n OutlineOptions,\n SourceRectangleOptions,\n TileOptions,\n} from \"@office-open/core/drawing\";\nimport {\n calculateEffectExtent,\n createColorElement,\n groupShapePropertiesDesc,\n shapePropertiesDesc,\n stringifyNonVisualContentPartProperties,\n stringifyNonVisualDrawingProperties,\n} from \"@office-open/core/drawing\";\nimport { escapeXml } from \"@office-open/xml\";\nimport { stringifyParagraphInline } from \"@parts/inline\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type {\n ChartMediaData,\n ContentPartMediaData,\n ExtendedMediaData,\n GroupChildMediaData,\n MediaData,\n MediaDataTransformation,\n SmartArtMediaData,\n GroupMediaData,\n ShapeMediaData,\n} from \"@shared/media\";\nimport type { NonVisualPropertiesOptions } from \"@shared/media/data\";\n\nimport type { BodyContext, DocxReadContext } from \"../../context\";\nimport type { DocPropertiesOptions, HyperlinkOptions } from \"./doc-properties/doc-properties\";\n// Import parse function from drawing-parse.ts (parse path)\nimport { parseDrawingRun } from \"./drawing-parse\";\nimport type { Floating, HorizontalPositionOptions, VerticalPositionOptions } from \"./floating\";\nimport type { Margins } from \"./floating\";\nimport { HorizontalPositionRelativeFrom, VerticalPositionRelativeFrom } from \"./floating\";\nimport type { ChildOffset, ChildExtent } from \"./inline/graphic/graphic-data/wpg/wpg-group\";\n// wpg/wps types only\nimport {\n createBodyProperties,\n type BodyPropertiesOptions,\n} from \"./inline/graphic/graphic-data/wps/body-properties\";\nimport type { NonVisualShapePropertiesOptions } from \"./inline/graphic/graphic-data/wps/non-visual-shape-properties\";\nimport type {\n ShapeStyleOptions,\n ShapeStyleReferenceOptions,\n ShapeCoreOptions,\n} from \"./inline/graphic/graphic-data/wps/wps-shape\";\nimport { TextWrappingSide, TextWrappingType } from \"./text-wrap\";\nimport type { TextWrapping, WrapPolygon } from \"./text-wrap\";\n\n// Noop context for drawingml descriptors that don't use WriteContext\nconst NOOP_CTX: WriteContext = {\n addRelationship: () => \"\",\n addMedia: () => \"\",\n addHyperlink: () => {},\n};\n\n// ── Options ──\n\n/**\n * Options for the drawing descriptor.\n *\n * Combines media data with optional visual properties.\n */\n\n/** Locking flags for wp:cNvGraphicFramePr (CT_GraphicalObjectFrameLocking). */\nexport interface GraphicFrameLocksOptions {\n noGrp?: boolean;\n noDrilldown?: boolean;\n noSelect?: boolean;\n noChangeAspect?: boolean;\n noMove?: boolean;\n noResize?: boolean;\n}\n\n/**\n * Group shape locks (CT_GroupLocking) carried inside wpg:cNvGrpSpPr.\n * Distinct from GraphicFrameLocksOptions: groups use noUngrp/noRot instead of noDrilldown.\n */\nexport interface GroupShapeLocksOptions {\n noGrp?: boolean;\n noUngrp?: boolean;\n noSelect?: boolean;\n noRot?: boolean;\n noChangeAspect?: boolean;\n noMove?: boolean;\n noResize?: boolean;\n}\n\nexport interface DrawingDescriptorOptions {\n /** Media data (image, chart, smartart, wps, wpg) */\n mediaData: ExtendedMediaData;\n /** Non-visual document properties (name, description, hyperlinks) */\n docProperties?: DocPropertiesOptions;\n /** Floating/anchored positioning (omit for inline) */\n floating?: Floating;\n /** Shape outline */\n outline?: OutlineOptions;\n /** Shape fill */\n fill?: FillOptions;\n /** Shape effects (shadow, glow, etc.) */\n effects?: EffectListOptions;\n /** Image blip effects (brightness, contrast, etc.) */\n blipEffects?: BlipEffectsOptions;\n /** Image tile fill mode */\n tile?: TileOptions;\n /** Graphic frame locks (wp:cNvGraphicFramePr). `{}` → empty element; omit → authoring default. */\n graphicFrameLocks?: GraphicFrameLocksOptions | null;\n}\n\n// ── ID generation ──\n\nlet _docPropsIdGen = uniqueNumericIdCreator();\n\n/** Reset the doc properties ID generator (for testing). */\nexport const resetDrawingIdGen = (): void => {\n _docPropsIdGen = uniqueNumericIdCreator();\n};\n\n// ── Constants ──\n\nconst GRAPHIC_NS = 'xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"';\nconst PIC_URI = \"http://schemas.openxmlformats.org/drawingml/2006/picture\";\nconst CHART_URI = \"http://schemas.openxmlformats.org/drawingml/2006/chart\";\nconst DGM_URI = \"http://schemas.openxmlformats.org/drawingml/2006/diagram\";\nconst WPS_URI = \"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\";\nconst WPG_URI = \"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\";\nconst HYPERLINK_REL =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\";\n// Blip extension URIs (a:extLst under a:blip).\nconst SVG_BLIP_EXT_URI = \"{96DAC541-7B7A-43D3-8B79-37D633B846F1}\";\nconst USE_LOCAL_DPI_EXT_URI = \"{28A0092B-C50C-407E-A947-70E740481C1C}\";\nconst A14_NS = \"http://schemas.microsoft.com/office/drawing/2010/main\";\n\n/**\n * Build the `a14:useLocalDpi` blip extension. Returns \"\" when the hint is\n * absent (undefined) — Word's default. val=\"0\" (useLocalDpi=false) is the\n * common Word emission; val=\"1\" only when explicitly set.\n */\nfunction buildUseLocalDpiExt(useLocalDpi?: boolean): string {\n if (useLocalDpi === undefined) return \"\";\n return `<a:ext uri=\"${USE_LOCAL_DPI_EXT_URI}\"><a14:useLocalDpi xmlns:a14=\"${A14_NS}\" val=\"${\n useLocalDpi ? \"1\" : \"0\"\n }\"/></a:ext>`;\n}\n\n// ── Hyperlink handling ──\n\ninterface HyperlinkIds {\n clickId?: string;\n hoverId?: string;\n}\n\nfunction registerHyperlinks(\n hyperlink: HyperlinkOptions | undefined,\n ctx: BodyContext,\n): HyperlinkIds {\n if (!hyperlink) return {};\n const result: HyperlinkIds = {};\n if (hyperlink.click) {\n const linkId = uniqueId();\n ctx.viewWrapper.relationships.addRelationship(\n linkId,\n HYPERLINK_REL,\n hyperlink.click,\n TargetModeType.EXTERNAL,\n );\n result.clickId = `rId${linkId}`;\n }\n if (hyperlink.hover) {\n const linkId = uniqueId();\n ctx.viewWrapper.relationships.addRelationship(\n linkId,\n HYPERLINK_REL,\n hyperlink.hover,\n TargetModeType.EXTERNAL,\n );\n result.hoverId = `rId${linkId}`;\n }\n return result;\n}\n\nfunction buildHyperlinkChildren(ids: HyperlinkIds): string {\n const parts: string[] = [];\n const aNs = 'xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"';\n if (ids.clickId) parts.push(`<a:hlinkClick r:id=\"${ids.clickId}\" ${aNs}/>`);\n if (ids.hoverId) parts.push(`<a:hlinkHover r:id=\"${ids.hoverId}\" ${aNs}/>`);\n return parts.join(\"\");\n}\n\n// ── DocPr ──\n\nfunction stringifyDocPr(opts: DocPropertiesOptions | undefined, hlIds: HyperlinkIds): string {\n const id = opts?.id ?? _docPropsIdGen();\n return stringifyNonVisualDrawingProperties(\n \"wp:docPr\",\n id,\n opts,\n \"\",\n buildHyperlinkChildren(hlIds),\n );\n}\n\n// ── BlipFill (image data reference) ──\n\n/** Build `<a:srcRect .../>` from a crop spec, or \"\" when there is no crop. */\nfunction buildSrcRectXml(srcRect: SourceRectangleOptions | undefined): string {\n if (!srcRect) return \"\";\n const srAttrs: string[] = [];\n if (srcRect.left !== undefined) srAttrs.push(`l=\"${srcRect.left}\"`);\n if (srcRect.top !== undefined) srAttrs.push(`t=\"${srcRect.top}\"`);\n if (srcRect.right !== undefined) srAttrs.push(`r=\"${srcRect.right}\"`);\n if (srcRect.bottom !== undefined) srAttrs.push(`b=\"${srcRect.bottom}\"`);\n return srAttrs.length ? `<a:srcRect ${srAttrs.join(\" \")}/>` : \"<a:srcRect/>\";\n}\n\nfunction stringifyBlipFill(\n mediaData: MediaData,\n blipEffects?: BlipEffectsOptions,\n tile?: TileOptions,\n): string {\n const fileName =\n mediaData.type === \"svg\" && \"fallback\" in mediaData\n ? mediaData.fallback.fileName\n : mediaData.fileName;\n\n const parts: string[] = [];\n\n // a:blip — cstate omitted unless set; Word's default is \"none\", so emitting\n // it unconditionally inflates round-trip output that originally had none.\n const blipAttrs: string[] = [`r:embed=\"{${escapeXml(fileName)}}\"`];\n\n // Blip extension list: useLocalDpi (rendering hint) + SVG blip reference.\n // Both live in a single shared a:extLst; emitted only when at least one ext\n // is present so blips without extensions stay self-closing.\n const extParts: string[] = [];\n const useLocalDpiExt = buildUseLocalDpiExt(mediaData.useLocalDpi);\n if (useLocalDpiExt) extParts.push(useLocalDpiExt);\n if (mediaData.type === \"svg\") {\n extParts.push(\n `<a:ext uri=\"${SVG_BLIP_EXT_URI}\"><asvg:svgBlip xmlns:asvg=\"http://schemas.microsoft.com/office/drawing/2016/SVG/main\" r:embed=\"{${escapeXml(\n mediaData.fileName,\n )}}\"/></a:ext>`,\n );\n }\n const extLstXml = extParts.length > 0 ? `<a:extLst>${extParts.join(\"\")}</a:extLst>` : \"\";\n\n // Blip effects\n const blipEffectsXml = blipEffects ? buildBlipEffectsXml(blipEffects) : \"\";\n\n const blipContent = extLstXml + blipEffectsXml;\n if (blipContent) {\n parts.push(`<a:blip ${blipAttrs.join(\" \")}>${blipContent}</a:blip>`);\n } else {\n parts.push(`<a:blip ${blipAttrs.join(\" \")}/>`);\n }\n\n // Source rectangle (blip crop)\n const srcRectXml = buildSrcRectXml(mediaData.sourceRectangle);\n if (srcRectXml) parts.push(srcRectXml);\n\n // Tile or stretch\n if (tile) {\n const tileAttrs: string[] = [];\n if (tile.tx !== undefined) tileAttrs.push(`tx=\"${tile.tx}\"`);\n if (tile.ty !== undefined) tileAttrs.push(`ty=\"${tile.ty}\"`);\n if (tile.sx !== undefined) tileAttrs.push(`sx=\"${tile.sx}\"`);\n if (tile.sy !== undefined) tileAttrs.push(`sy=\"${tile.sy}\"`);\n const tileAttrStr = tileAttrs.length ? \" \" + tileAttrs.join(\" \") : \"\";\n parts.push(`<a:tile${tileAttrStr}/>`);\n } else {\n parts.push(\"<a:stretch><a:fillRect/></a:stretch>\");\n }\n\n return `<pic:blipFill>${parts.join(\"\")}</pic:blipFill>`;\n}\n\nfunction buildBlipEffectsXml(opts: BlipEffectsOptions): string {\n const parts: string[] = [];\n if (opts.grayscale) parts.push(\"<a:grayscl/>\");\n if (opts.luminance) {\n const a: string[] = [];\n if (opts.luminance.bright !== undefined) a.push(`bright=\"${opts.luminance.bright}\"`);\n if (opts.luminance.contrast !== undefined) a.push(`contrast=\"${opts.luminance.contrast}\"`);\n parts.push(`<a:lum${a.length ? \" \" + a.join(\" \") : \"\"}/>`);\n }\n if (opts.biLevel) parts.push(`<a:biLevel thresh=\"${opts.biLevel.threshold}\"/>`);\n if (opts.blur) {\n const a: string[] = [];\n if (opts.blur.radius !== undefined) a.push(`rad=\"${opts.blur.radius}\"`);\n if (opts.blur.grow === false) a.push('grow=\"0\"');\n parts.push(`<a:blur${a.length ? \" \" + a.join(\" \") : \"\"}/>`);\n }\n return parts.join(\"\");\n}\n\n// ── Shape Properties (pic:spPr) ──\n\nfunction stringifyShapeProps(\n transform: MediaDataTransformation,\n outline?: OutlineOptions,\n fill?: FillOptions,\n effects?: EffectListOptions,\n): string {\n const spPr = shapePropertiesDesc.stringify(\n {\n x: transform.offset?.emus?.x ?? 0,\n y: transform.offset?.emus?.y ?? 0,\n width: transform.emus.x,\n height: transform.emus.y,\n flipHorizontal: transform.flip?.horizontal,\n flipVertical: transform.flip?.vertical,\n rotation: transform.rotation,\n // Pictures always use a rect preset geometry.\n geometry: \"rect\",\n fill,\n outline,\n effects,\n },\n NOOP_CTX,\n );\n return `<pic:spPr bwMode=\"auto\">${spPr ?? \"\"}</pic:spPr>`;\n}\n\n// ── Non-visual picture properties (pic:nvPicPr) ──\n\nfunction stringifyNvPicPr(hlIds: HyperlinkIds, cNvPr?: NonVisualPropertiesOptions): string {\n const id = cNvPr?.id ?? 0;\n const cNvPrXml = stringifyNonVisualDrawingProperties(\n \"pic:cNvPr\",\n id,\n cNvPr,\n \"\",\n buildHyperlinkChildren(hlIds),\n );\n // preferRelativeResize defaults to true; only an explicit false is written.\n const cNvPicPrAttr = cNvPr?.preferRelativeResize === false ? ' preferRelativeResize=\"0\"' : \"\";\n return `<pic:nvPicPr>${cNvPrXml}<pic:cNvPicPr${cNvPicPrAttr}><a:picLocks noChangeAspect=\"1\"/></pic:cNvPicPr></pic:nvPicPr>`;\n}\n\n// ── WPS shape (pure string, no class instances) ──\n\n/** WpsShape options for stringification (extends ShapeCoreOptions with transformation). */\ninterface WpsStringifyOptions extends ShapeCoreOptions {\n transformation: MediaDataTransformation;\n}\n\nfunction stringifyWpsShape(opts: WpsStringifyOptions, ctx: BodyContext): string {\n const transform = opts.transformation;\n const spPrContent =\n shapePropertiesDesc.stringify(\n {\n x: transform.offset?.emus?.x ?? 0,\n y: transform.offset?.emus?.y ?? 0,\n width: transform.emus.x,\n height: transform.emus.y,\n flipHorizontal: transform.flip?.horizontal,\n flipVertical: transform.flip?.vertical,\n rotation: transform.rotation,\n customGeometry: opts.customGeometry,\n // WPS shapes always carry geometry — default to rect when none specified.\n geometry: opts.customGeometry ? undefined : (opts.presetGeometry ?? \"rect\"),\n fill: opts.fill,\n outline: opts.outline,\n effectDag: opts.effectDag,\n effects: opts.effects,\n scene3d: opts.scene3d,\n shape3d: opts.shape3d,\n },\n ctx,\n ) ?? \"\";\n\n // Non-visual shape properties — default txBox=\"1\"\n const cNvSpPr = opts.nonVisualProperties\n ? stringifyNonVisualShapeProperties(opts.nonVisualProperties)\n : '<wps:cNvSpPr txBox=\"1\"/>';\n\n // Paragraph children — pure JSON stringification\n const childXml =\n opts.children\n ?.map((c) => stringifyParagraphInline(c as ParagraphOptions | string, ctx))\n .join(\"\") ?? \"\";\n\n // Shape style (wps:style) — theme references, emitted after spPr (XSD order)\n const styleXml = opts.style ? stringifyShapeStyle(opts.style) : \"\";\n // wps:txbx — only emit when the shape carries text (text boxes). Pure\n // geometry shapes (no paragraphs) omit txbx in the source.\n const txbxXml = childXml ? `<wps:txbx><w:txbxContent>${childXml}</w:txbxContent></wps:txbx>` : \"\";\n // wps:linkedTxbx — XSD choice partner of txbx: the text lives in the linked\n // part, so the shape carries the chain reference instead of inline content.\n const linkedTxbxXml =\n !childXml && opts.linkedTextBox\n ? `<wps:linkedTxbx id=\"${opts.linkedTextBox.id}\" seq=\"${opts.linkedTextBox.sequence}\"/>`\n : \"\";\n // East-Asian vertical flow attribute (default false — emit only when set)\n const neafAttr = opts.normalEastAsianFlow ? ' normalEastAsianFlow=\"1\"' : \"\";\n\n return (\n `<wps:wsp${neafAttr}>` +\n cNvSpPr +\n `<wps:spPr bwMode=\"auto\">${spPrContent}</wps:spPr>` +\n styleXml +\n txbxXml +\n linkedTxbxXml +\n stringifyBodyPr(opts.bodyProperties) +\n \"</wps:wsp>\"\n );\n}\n\nfunction stringifyNonVisualShapeProperties(opts: NonVisualShapePropertiesOptions): string {\n let xml = \"\";\n // wps:cNvPr — id/name/descr/title (XSD CT_NonVisualDrawingProps)\n if (opts.id !== undefined || opts.name !== undefined) {\n const attrs: string[] = [];\n if (opts.id !== undefined) attrs.push(`id=\"${opts.id}\"`);\n if (opts.name !== undefined) attrs.push(`name=\"${escapeXml(opts.name)}\"`);\n if (opts.description !== undefined) attrs.push(`descr=\"${escapeXml(opts.description)}\"`);\n if (opts.title !== undefined) attrs.push(`title=\"${escapeXml(opts.title)}\"`);\n xml += `<wps:cNvPr ${attrs.join(\" \")}/>`;\n }\n // CT_WordprocessingShape choice: wps:cNvSpPr (text box/autoshape) or\n // wps:cNvCnPr (connector). Connectors carry empty cNvCnPr.\n if (opts.connector) {\n xml += \"<wps:cNvCnPr/>\";\n } else if (opts.textBox !== undefined) {\n xml += `<wps:cNvSpPr txBox=\"${opts.textBox}\"/>`;\n } else {\n xml += \"<wps:cNvSpPr/>\";\n }\n return xml;\n}\n\n/** Stringify a single style-matrix reference (a:lnRef/a:fillRef/...). */\nfunction stringifyStyleRef(name: string, ref: ShapeStyleReferenceOptions | undefined): string {\n if (!ref) return \"\";\n const idx = escapeXml(ref.idx);\n const colorXml = ref.color ? createColorElement(ref.color) : \"\";\n if (colorXml) return `<${name} idx=\"${idx}\">${colorXml}</${name}>`;\n return `<${name} idx=\"${idx}\"/>`;\n}\n\n/** Stringify a wps:style (CT_ShapeStyle): lnRef/fillRef/effectRef/fontRef. */\nfunction stringifyShapeStyle(opts: ShapeStyleOptions): string {\n const inner =\n stringifyStyleRef(\"a:lnRef\", opts.lineReference) +\n stringifyStyleRef(\"a:fillRef\", opts.fillReference) +\n stringifyStyleRef(\"a:effectRef\", opts.effectReference) +\n stringifyStyleRef(\"a:fontRef\", opts.fontReference);\n return inner ? `<wps:style>${inner}</wps:style>` : \"\";\n}\n\nfunction stringifyBodyPr(opts?: BodyPropertiesOptions): string {\n // Delegate to the shared createBodyProperties so attributes + EG_TextAutofit\n // (noAutofit/normAutofit/spAutoFit) + prstTxWarp/3D all round-trip. The old\n // inline copy dropped noAutoFit/spAutoFit and most CT_TextBodyProperties attrs.\n return createBodyProperties(opts ?? {});\n}\n\n// ── WPG group (pure string, no class instances) ──\n\nfunction stringifyWpgGroup(\n opts: {\n children: readonly GroupChildMediaData[];\n transformation: MediaDataTransformation;\n childOffset?: ChildOffset;\n childExtent?: ChildExtent;\n fill?: FillOptions;\n effects?: EffectListOptions;\n groupShapeLocks?: GroupShapeLocksOptions | null;\n },\n ctx: BodyContext,\n): string {\n const transform = opts.transformation;\n const grpSpPrContent =\n groupShapePropertiesDesc.stringify(\n {\n x: transform.offset?.emus?.x ?? 0,\n y: transform.offset?.emus?.y ?? 0,\n width: transform.emus.x,\n height: transform.emus.y,\n flipHorizontal: transform.flip?.horizontal,\n flipVertical: transform.flip?.vertical,\n rotation: transform.rotation,\n childOffsetX: opts.childOffset?.x,\n childOffsetY: opts.childOffset?.y,\n childExtentWidth: opts.childExtent?.cx,\n childExtentHeight: opts.childExtent?.cy,\n fill: opts.fill,\n effects: opts.effects,\n },\n ctx,\n ) ?? \"\";\n\n // Children — wps shapes, nested wpg groups, or pic elements\n const childXml = opts.children.map((child) => stringifyGroupChild(child, ctx)).join(\"\");\n\n return (\n \"<wpg:wgp>\" +\n stringifyCnvGrpSpPr(opts.groupShapeLocks) +\n `<wpg:grpSpPr>${grpSpPrContent}</wpg:grpSpPr>` +\n childXml +\n \"</wpg:wgp>\"\n );\n}\n\n/**\n * Stringify one group child: a wps shape, a nested wpg group, or a picture.\n * Shared by the top-level wpg:wgp and nested wpg:grpSp.\n */\nfunction stringifyGroupChild(child: GroupChildMediaData, ctx: BodyContext): string {\n if (child.type === \"wps\") {\n const wpsData = child as ShapeMediaData & { outline?: OutlineOptions; fill?: FillOptions };\n return stringifyWpsShape(\n {\n ...wpsData.data,\n outline: wpsData.outline ?? wpsData.data.outline,\n fill: wpsData.fill ?? wpsData.data.fill,\n transformation: wpsData.transformation,\n },\n ctx,\n );\n }\n if (child.type === \"wpg\") {\n return stringifyNestedGroup(child as GroupMediaData, ctx);\n }\n if (child.type === \"chart\") {\n return stringifyGroupGraphicFrame(child as ChartMediaData);\n }\n if (child.type === \"contentPart\") {\n return stringifyContentPart(\"wpg\", child as ContentPartMediaData);\n }\n // pic child (MediaData) — fill/outline ride on the group-child extension\n // (GroupCommonMediaData) so a grouped picture's spPr round-trips verbatim.\n const picData = child as MediaData & { outline?: OutlineOptions; fill?: FillOptions };\n const isSvg = picData.type === \"svg\";\n // a:blip r:embed targets the raster fallback for SVG pictures (what legacy\n // viewers render); the vector SVG lives in the svgBlip extension below.\n const blipTarget = isSvg && \"fallback\" in picData ? picData.fallback.fileName : picData.fileName;\n const picParts: string[] = [];\n picParts.push(stringifyNvPicPr({}, picData.nonVisualProperties));\n const groupBlipParts: string[] = [];\n const extParts: string[] = [];\n const useLocalDpiExt = buildUseLocalDpiExt(picData.useLocalDpi);\n if (useLocalDpiExt) extParts.push(useLocalDpiExt);\n if (isSvg) {\n extParts.push(\n `<a:ext uri=\"${SVG_BLIP_EXT_URI}\"><asvg:svgBlip xmlns:asvg=\"http://schemas.microsoft.com/office/drawing/2016/SVG/main\" r:embed=\"{${escapeXml(\n picData.fileName,\n )}}\"/></a:ext>`,\n );\n }\n const extLst = extParts.length > 0 ? `<a:extLst>${extParts.join(\"\")}</a:extLst>` : \"\";\n groupBlipParts.push(\n extLst\n ? `<a:blip r:embed=\"{${escapeXml(blipTarget)}}\">${extLst}</a:blip>`\n : `<a:blip r:embed=\"{${escapeXml(blipTarget)}}\"/>`,\n );\n const groupSrcRectXml = buildSrcRectXml(picData.sourceRectangle);\n if (groupSrcRectXml) groupBlipParts.push(groupSrcRectXml);\n groupBlipParts.push(\"<a:stretch><a:fillRect/></a:stretch>\");\n picParts.push(`<pic:blipFill>${groupBlipParts.join(\"\")}</pic:blipFill>`);\n picParts.push(stringifyShapeProps(picData.transformation, picData.outline, picData.fill));\n return `<pic:pic xmlns:pic=\"${PIC_URI}\">${picParts.join(\"\")}</pic:pic>`;\n}\n\n/**\n * Stringify a wpg:graphicFrame group child (CT_GraphicFrame): cNvPr +\n * cNvFrPr + a:xfrm + a:graphic. Charts are the graphic payload Word produces\n * inside groups; the chart part is registered by the group dispatch.\n */\nfunction stringifyGroupGraphicFrame(md: ChartMediaData): string {\n const nvp = md.nonVisualProperties;\n const cNvPrXml = stringifyNonVisualDrawingProperties(\"wpg:cNvPr\", nvp?.id ?? 0, nvp, \"Chart\");\n const cNvFrPrXml = stringifyCnvFrPr(md.graphicFrameLocks);\n const xfrmXml = stringifyChildXfrm(\"wpg\", md.transformation);\n return (\n \"<wpg:graphicFrame>\" +\n cNvPrXml +\n cNvFrPrXml +\n xfrmXml +\n `<a:graphic ${GRAPHIC_NS}>` +\n `<a:graphicData uri=\"${CHART_URI}\">` +\n `<c:chart xmlns:c=\"${CHART_URI}\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"{chart:${md.chartKey}}\"/>` +\n `</a:graphicData>` +\n `</a:graphic>` +\n \"</wpg:graphicFrame>\"\n );\n}\n\n/** Render wpg:cNvFrPr (CT_NonVisualGraphicFrameProperties — a:graphicFrameLocks). */\nfunction stringifyCnvFrPr(locks?: GraphicFrameLocksOptions | null): string {\n if (!locks) return \"<wpg:cNvFrPr/>\";\n const attrParts: string[] = [];\n if (locks.noGrp) attrParts.push('noGrp=\"1\"');\n if (locks.noDrilldown) attrParts.push('noDrilldown=\"1\"');\n if (locks.noSelect) attrParts.push('noSelect=\"1\"');\n if (locks.noChangeAspect) attrParts.push('noChangeAspect=\"1\"');\n if (locks.noMove) attrParts.push('noMove=\"1\"');\n if (locks.noResize) attrParts.push('noResize=\"1\"');\n if (attrParts.length === 0) return \"<wpg:cNvFrPr/>\";\n const attrStr = \" \" + attrParts.join(\" \");\n return `<wpg:cNvFrPr><a:graphicFrameLocks${attrStr} xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"/></wpg:cNvFrPr>`;\n}\n\n/**\n * Build the xfrm (off/ext) of a nested drawing from its transformation. The\n * root tag is host-namespaced (local element of CT_GraphicFrame /\n * CT_WordprocessingContentPart); the off/ext children belong to a:.\n */\nfunction stringifyChildXfrm(prefix: \"wp\" | \"wpg\", t: MediaDataTransformation): string {\n const x = t.offset?.emus?.x ?? 0;\n const y = t.offset?.emus?.y ?? 0;\n const flipAttrs =\n (t.flip?.horizontal ? ' flipH=\"1\"' : \"\") + (t.flip?.vertical ? ' flipV=\"1\"' : \"\");\n const rotAttr = t.rotation !== undefined ? ` rot=\"${t.rotation}\"` : \"\";\n return `<${prefix}:xfrm${flipAttrs}${rotAttr}><a:off x=\"${x}\" y=\"${y}\"/><a:ext cx=\"${t.emus.x}\" cy=\"${t.emus.y}\"/></${prefix}:xfrm>`;\n}\n\n/**\n * Stringify a wpg:contentPart child (CT_WordprocessingContentPart) inside a\n * group: nvContentPartPr (cNvPr + cNvContentPartPr) + a:xfrm + @bwMode/@r:id.\n * A content part never appears at the wp:inline/wp:anchor root (CT_Inline and\n * CT_Anchor take a:graphic only) — the run-level form is w:contentPart.\n */\nfunction stringifyContentPart(prefix: \"wpg\", md: ContentPartMediaData): string {\n const nvp = md.nonVisualProperties;\n const attrParts = [`r:id=\"${escapeXml(md.referenceId)}\"`];\n if (md.blackWhiteMode) attrParts.push(`bwMode=\"${escapeXml(md.blackWhiteMode)}\"`);\n const nvInner =\n stringifyNonVisualDrawingProperties(`${prefix}:cNvPr`, nvp?.id ?? 0, nvp, \"Content Part\") +\n stringifyNonVisualContentPartProperties(`${prefix}:cNvContentPartPr`, nvp?.contentPart);\n const nvXml = nvInner ? `<${prefix}:nvContentPartPr>${nvInner}</${prefix}:nvContentPartPr>` : \"\";\n return (\n `<${prefix}:contentPart ${attrParts.join(\" \")}>` +\n nvXml +\n stringifyChildXfrm(prefix, md.transformation) +\n `</${prefix}:contentPart>`\n );\n}\n\n/**\n * Stringify a nested wpg:grpSp (CT_WordprocessingGroup) group child. Same\n * structure as the top-level group, wrapped in wpg:grpSp with a cNvPr id/name.\n */\nfunction stringifyNestedGroup(grp: GroupMediaData, ctx: BodyContext): string {\n const grpSpPrContent =\n groupShapePropertiesDesc.stringify(\n {\n x: grp.transformation.offset?.emus?.x ?? 0,\n y: grp.transformation.offset?.emus?.y ?? 0,\n width: grp.transformation.emus.x,\n height: grp.transformation.emus.y,\n flipHorizontal: grp.transformation.flip?.horizontal,\n flipVertical: grp.transformation.flip?.vertical,\n rotation: grp.transformation.rotation,\n childOffsetX: grp.childOffset?.x,\n childOffsetY: grp.childOffset?.y,\n childExtentWidth: grp.childExtent?.cx,\n childExtentHeight: grp.childExtent?.cy,\n fill: grp.fill,\n effects: grp.effects,\n },\n ctx,\n ) ?? \"\";\n return (\n \"<wpg:grpSp>\" +\n '<wpg:cNvPr id=\"0\" name=\"\"/>' +\n stringifyCnvGrpSpPr(grp.groupShapeLocks) +\n `<wpg:grpSpPr>${grpSpPrContent}</wpg:grpSpPr>` +\n grp.children.map((c) => stringifyGroupChild(c, ctx)).join(\"\") +\n \"</wpg:grpSp>\"\n );\n}\n\n// ── Graphic data content ──\n\nfunction stringifyGraphicDataContent(\n mediaData: ExtendedMediaData,\n opts: DrawingDescriptorOptions,\n hlIds: HyperlinkIds,\n ctx: BodyContext,\n): string {\n const { outline, fill, effects, blipEffects, tile } = opts;\n const transform = mediaData.transformation;\n\n if (mediaData.type === \"chart\") {\n const md = mediaData as ChartMediaData;\n return (\n `<a:graphicData uri=\"${CHART_URI}\">` +\n `<c:chart xmlns:c=\"${CHART_URI}\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"{chart:${md.chartKey}}\"/>` +\n `</a:graphicData>`\n );\n }\n\n if (mediaData.type === \"smartart\") {\n const md = mediaData as SmartArtMediaData;\n return (\n `<a:graphicData uri=\"${DGM_URI}\">` +\n `<dgm:relIds xmlns:dgm=\"${DGM_URI}\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:dm=\"{smartart:${md.smartArtKey}}\" r:lo=\"{smartart-lo:${md.smartArtKey}}\" r:qs=\"{smartart-qs:${md.smartArtKey}}\" r:cs=\"{smartart-cs:${md.smartArtKey}}\"/>` +\n `</a:graphicData>`\n );\n }\n\n if (mediaData.type === \"wps\") {\n const md = mediaData as ShapeMediaData;\n const wpsXml = stringifyWpsShape(\n {\n ...md.data,\n outline,\n fill,\n transformation: transform,\n },\n ctx,\n );\n return `<a:graphicData uri=\"${WPS_URI}\">${wpsXml}</a:graphicData>`;\n }\n\n if (mediaData.type === \"wpg\") {\n const md = mediaData as GroupMediaData;\n const wpgXml = stringifyWpgGroup(\n {\n children: md.children,\n transformation: transform,\n childOffset: md.childOffset,\n childExtent: md.childExtent,\n fill: md.fill,\n effects: md.effects,\n groupShapeLocks: md.groupShapeLocks,\n },\n ctx,\n );\n return `<a:graphicData uri=\"${WPG_URI}\">${wpgXml}</a:graphicData>`;\n }\n\n // Default: image (pic:pic)\n const md = mediaData as MediaData;\n return (\n `<a:graphicData uri=\"${PIC_URI}\">` +\n `<pic:pic xmlns:pic=\"${PIC_URI}\">` +\n stringifyNvPicPr(hlIds, md.nonVisualProperties) +\n stringifyBlipFill(md, blipEffects, tile) +\n stringifyShapeProps(transform, outline, fill, effects) +\n `</pic:pic></a:graphicData>`\n );\n}\n\n// ── Position helpers (for anchor) ──\n\nfunction stringifyPositionH(opts: HorizontalPositionOptions): string {\n const rel = opts.relative ?? HorizontalPositionRelativeFrom.PAGE;\n const child = opts.align\n ? `<wp:align>${opts.align}</wp:align>`\n : opts.offset !== undefined\n ? `<wp:posOffset>${convertToEmu(opts.offset)}</wp:posOffset>`\n : \"<wp:align>left</wp:align>\";\n return `<wp:positionH relativeFrom=\"${rel}\">${child}</wp:positionH>`;\n}\n\nfunction stringifyPositionV(opts: VerticalPositionOptions): string {\n const rel = opts.relative ?? VerticalPositionRelativeFrom.PAGE;\n const child = opts.align\n ? `<wp:align>${opts.align}</wp:align>`\n : opts.offset !== undefined\n ? `<wp:posOffset>${convertToEmu(opts.offset)}</wp:posOffset>`\n : \"<wp:align>top</wp:align>\";\n return `<wp:positionV relativeFrom=\"${rel}\">${child}</wp:positionV>`;\n}\n\n// ── Text wrapping string builders ──\n\nfunction wrapPolygonStr(cx: number, cy: number, polygon?: WrapPolygon): string {\n // Preserve the source contour verbatim when round-tripped.\n if (polygon?.points.length) {\n // Emit `edited` only when the source had it — keeps the polygon byte-faithful on round-trip.\n const editedAttr = polygon.edited !== undefined ? ` edited=\"${polygon.edited ? 1 : 0}\"` : \"\";\n const [start, ...rest] = polygon.points;\n // length guard above guarantees `start` exists\n const startStr = `<wp:start x=\"${start!.x}\" y=\"${start!.y}\"/>`;\n const lineToStr = rest.map((p) => `<wp:lineTo x=\"${p.x}\" y=\"${p.y}\"/>`).join(\"\");\n return `<wp:wrapPolygon${editedAttr}>${startStr}${lineToStr}</wp:wrapPolygon>`;\n }\n // Default contour: extent rectangle (origin at top-left, y negated).\n return (\n `<wp:wrapPolygon edited=\"0\">` +\n `<wp:start x=\"0\" y=\"0\"/>` +\n `<wp:lineTo x=\"0\" y=\"${-cy}\"/>` +\n `<wp:lineTo x=\"${cx}\" y=\"${-cy}\"/>` +\n `<wp:lineTo x=\"${cx}\" y=\"0\"/>` +\n `<wp:lineTo x=\"0\" y=\"0\"/>` +\n `</wp:wrapPolygon>`\n );\n}\n\nfunction wrapSquareStr(textWrapping: TextWrapping, margins?: Margins): string {\n const side = textWrapping.side ?? TextWrappingSide.BOTH_SIDES;\n const m = margins ?? {};\n const a = [\n `wrapText=\"${side}\"`,\n ...(m.top != null ? [`distT=\"${convertToEmu(m.top)}\"`] : []),\n ...(m.bottom != null ? [`distB=\"${convertToEmu(m.bottom)}\"`] : []),\n ...(m.left != null ? [`distL=\"${convertToEmu(m.left)}\"`] : []),\n ...(m.right != null ? [`distR=\"${convertToEmu(m.right)}\"`] : []),\n ].join(\" \");\n return `<wp:wrapSquare ${a}/>`;\n}\n\nfunction wrapTightStr(\n textWrapping: TextWrapping,\n margins: Margins,\n cx: number,\n cy: number,\n): string {\n const side = textWrapping.side ?? TextWrappingSide.BOTH_SIDES;\n const a = [`wrapText=\"${side}\"`];\n if (margins.left != null) a.push(`distL=\"${convertToEmu(margins.left)}\"`);\n if (margins.right != null) a.push(`distR=\"${convertToEmu(margins.right)}\"`);\n return `<wp:wrapTight ${a.join(\" \")}>${wrapPolygonStr(cx, cy, textWrapping.polygon)}</wp:wrapTight>`;\n}\n\nfunction wrapThroughStr(\n textWrapping: TextWrapping,\n margins: Margins,\n cx: number,\n cy: number,\n): string {\n const side = textWrapping.side ?? TextWrappingSide.BOTH_SIDES;\n const a = [`wrapText=\"${side}\"`];\n if (margins.left != null) a.push(`distL=\"${convertToEmu(margins.left)}\"`);\n if (margins.right != null) a.push(`distR=\"${convertToEmu(margins.right)}\"`);\n return `<wp:wrapThrough ${a.join(\" \")}>${wrapPolygonStr(cx, cy, textWrapping.polygon)}</wp:wrapThrough>`;\n}\n\nfunction wrapTopAndBottomStr(margins?: Margins): string {\n const m = margins ?? {};\n const a = [\n ...(m.top != null ? [`distT=\"${convertToEmu(m.top)}\"`] : []),\n ...(m.bottom != null ? [`distB=\"${convertToEmu(m.bottom)}\"`] : []),\n ].join(\" \");\n return a ? `<wp:wrapTopAndBottom ${a}/>` : \"<wp:wrapTopAndBottom/>\";\n}\n\n// ── Inline wrapper ──\n\n/** Render wp:cNvGraphicFramePr. Undefined → authoring default (noChangeAspect=1);\n * `{}` → empty element; otherwise the given lock flags. */\nfunction stringifyCnvGraphicFramePr(locks?: GraphicFrameLocksOptions | null): string {\n const resolved = locks ?? { noChangeAspect: true };\n const attrParts: string[] = [];\n if (resolved.noGrp) attrParts.push('noGrp=\"1\"');\n if (resolved.noDrilldown) attrParts.push('noDrilldown=\"1\"');\n if (resolved.noSelect) attrParts.push('noSelect=\"1\"');\n if (resolved.noChangeAspect) attrParts.push('noChangeAspect=\"1\"');\n if (resolved.noMove) attrParts.push('noMove=\"1\"');\n if (resolved.noResize) attrParts.push('noResize=\"1\"');\n if (attrParts.length === 0) return \"<wp:cNvGraphicFramePr/>\";\n const attrStr = \" \" + attrParts.join(\" \");\n return `<wp:cNvGraphicFramePr><a:graphicFrameLocks${attrStr} xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"/></wp:cNvGraphicFramePr>`;\n}\n\n/**\n * Stringify wpg:cNvGrpSpPr (CT_NonVisualGroupShapeDrawingProperties): contains\n * an optional a:grpSpLocks (CT_GroupLocking). When no locks are present (the\n * Word default for groups) the element stays empty — groups do NOT inject a\n * default lock, unlike wp:cNvGraphicFramePr.\n */\nfunction stringifyCnvGrpSpPr(locks?: GroupShapeLocksOptions | null): string {\n if (!locks) return \"<wpg:cNvGrpSpPr/>\";\n const attrParts: string[] = [];\n if (locks.noGrp) attrParts.push('noGrp=\"1\"');\n if (locks.noUngrp) attrParts.push('noUngrp=\"1\"');\n if (locks.noSelect) attrParts.push('noSelect=\"1\"');\n if (locks.noRot) attrParts.push('noRot=\"1\"');\n if (locks.noChangeAspect) attrParts.push('noChangeAspect=\"1\"');\n if (locks.noMove) attrParts.push('noMove=\"1\"');\n if (locks.noResize) attrParts.push('noResize=\"1\"');\n if (attrParts.length === 0) return \"<wpg:cNvGrpSpPr/>\";\n const attrStr = \" \" + attrParts.join(\" \");\n return `<wpg:cNvGrpSpPr><a:grpSpLocks${attrStr} xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"/></wpg:cNvGrpSpPr>`;\n}\n\nfunction stringifyInline(\n opts: DrawingDescriptorOptions,\n hlIds: HyperlinkIds,\n ctx: BodyContext,\n): string {\n const { mediaData, effects, docProperties } = opts;\n const cx = mediaData.transformation.emus.x;\n const cy = mediaData.transformation.emus.y;\n\n // Prefer the verbatim source effectExtent (round-trip); fall back to\n // computing it from the shape's effects on the generation path.\n const effectExtent = mediaData.transformation.effectExtent ?? calculateEffectExtent(effects);\n // CT_Inline's choice is a:graphic — a content part only nests inside a wpg\n // group or canvas, never directly under wp:inline.\n const choiceXml = `<a:graphic ${GRAPHIC_NS}>${stringifyGraphicDataContent(mediaData, opts, hlIds, ctx)}</a:graphic>`;\n\n return (\n `<w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">` +\n `<wp:extent cx=\"${cx}\" cy=\"${cy}\"/>` +\n `<wp:effectExtent l=\"${effectExtent.l}\" t=\"${effectExtent.t}\" r=\"${effectExtent.r}\" b=\"${effectExtent.b}\"/>` +\n stringifyDocPr(docProperties, hlIds) +\n stringifyCnvGraphicFramePr(opts.graphicFrameLocks) +\n choiceXml +\n `</wp:inline></w:drawing>`\n );\n}\n\n// ── Anchor (floating) wrapper ──\n\nfunction stringifyAnchor(\n opts: DrawingDescriptorOptions,\n hlIds: HyperlinkIds,\n ctx: BodyContext,\n): string {\n const { mediaData, floating: rawFloating, docProperties } = opts;\n const cx = mediaData.transformation.emus.x;\n const cy = mediaData.transformation.emus.y;\n\n const floating: Required<Floating> = {\n allowOverlap: true,\n behindDocument: false,\n horizontalPosition: {},\n layoutInCell: true,\n lockAnchor: false,\n verticalPosition: {},\n zIndex: mediaData.transformation.emus.y,\n margins: {},\n wrap: { type: TextWrappingType.NONE },\n ...rawFloating,\n };\n\n const attrParts = [\n `distT=\"${convertToEmu(floating.margins?.top ?? 0)}\"`,\n `distB=\"${convertToEmu(floating.margins?.bottom ?? 0)}\"`,\n `distL=\"${convertToEmu(floating.margins?.left ?? 0)}\"`,\n `distR=\"${convertToEmu(floating.margins?.right ?? 0)}\"`,\n 'simplePos=\"0\"',\n `allowOverlap=\"${floating.allowOverlap ? 1 : 0}\"`,\n `behindDoc=\"${floating.behindDocument ? 1 : 0}\"`,\n `locked=\"${floating.lockAnchor ? 1 : 0}\"`,\n `layoutInCell=\"${floating.layoutInCell ? 1 : 0}\"`,\n `relativeHeight=\"${floating.zIndex}\"`,\n ];\n\n // Wrap\n let wrapXml: string;\n const rawWrap = rawFloating?.wrap;\n if (rawWrap?.type === TextWrappingType.SQUARE) {\n wrapXml = wrapSquareStr(rawWrap, floating.margins);\n } else if (rawWrap?.type === TextWrappingType.TIGHT) {\n wrapXml = wrapTightStr(rawWrap, floating.margins, cx, cy);\n } else if (rawWrap?.type === TextWrappingType.THROUGH) {\n wrapXml = wrapThroughStr(rawWrap, floating.margins, cx, cy);\n } else if (rawWrap?.type === TextWrappingType.TOP_AND_BOTTOM) {\n wrapXml = wrapTopAndBottomStr(floating.margins);\n } else {\n wrapXml = \"<wp:wrapNone/>\";\n }\n\n // CT_Anchor's choice is a:graphic — a content part only nests inside a wpg\n // group or canvas, never directly under wp:anchor.\n const choiceXml = `<a:graphic ${GRAPHIC_NS}>${stringifyGraphicDataContent(mediaData, opts, hlIds, ctx)}</a:graphic>`;\n\n // Prefer the verbatim source effectExtent (round-trip); default to zero.\n const ee = mediaData.transformation.effectExtent;\n const effectExtentXml = ee\n ? `<wp:effectExtent l=\"${ee.l}\" t=\"${ee.t}\" r=\"${ee.r}\" b=\"${ee.b}\"/>`\n : '<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>';\n\n return (\n `<w:drawing><wp:anchor ${attrParts.join(\" \")}>` +\n '<wp:simplePos x=\"0\" y=\"0\"/>' +\n stringifyPositionH(floating.horizontalPosition) +\n stringifyPositionV(floating.verticalPosition) +\n `<wp:extent cx=\"${cx}\" cy=\"${cy}\"/>` +\n effectExtentXml +\n wrapXml +\n stringifyDocPr(docProperties, hlIds) +\n stringifyCnvGraphicFramePr(opts.graphicFrameLocks) +\n choiceXml +\n `</wp:anchor></w:drawing>`\n );\n}\n\n// ── Descriptor ──\n\n/**\n * Drawing descriptor for DOCX `<w:drawing>` elements.\n *\n * Eliminates the Drawing/Inline/Anchor/Graphic/GraphicData/Pic XmlComponent\n * class chain. Inline images, charts, and smartarts produce XML via pure\n * string concatenation — zero XmlComponent instances.\n *\n * @example\n * ```typescript\n * const xml = drawingDesc.stringify({ mediaData, docProperties: opts.altText, floating: opts.floating }, ctx);\n * ```\n */\nexport const drawingDesc: CustomDescriptor<DrawingDescriptorOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n // Register hyperlink relationships\n const hlIds = registerHyperlinks(opts.docProperties?.hyperlink, ctx);\n\n if (opts.floating) {\n return stringifyAnchor(opts, hlIds, ctx);\n }\n return stringifyInline(opts, hlIds, ctx);\n },\n\n parse(el, ctx) {\n const result = parseDrawingRun(el, ctx as DocxReadContext);\n return (result ?? {}) as unknown as DrawingDescriptorOptions;\n },\n};\n","/**\n * Field module for WordprocessingML documents.\n *\n * This module provides support for complex fields, which are regions of text\n * that can contain dynamic content such as page numbers, dates, or mail merge fields.\n * Fields are delimited by field character elements (begin, separate, end).\n *\n * Reference: http://officeopenxml.com/WPrun.php\n *\n * @module\n */\n\nimport { element } from \"@office-open/xml\";\n\nimport type { FormFieldOptions } from \"./form-field\";\nimport { createFormFieldData } from \"./form-field\";\n\n/**\n * Field character types that delimit field regions.\n *\n * @internal\n */\nconst FieldCharacterType = {\n BEGIN: \"begin\",\n END: \"end\",\n SEPARATE: \"separate\",\n} as const;\n\n/**\n * Creates a field character element.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_FldChar\">\n * <xsd:sequence>\n * <xsd:element name=\"fldData\" type=\"CT_Text\" minOccurs=\"0\"/>\n * <xsd:element name=\"ffData\" type=\"CT_FFData\" minOccurs=\"0\"/>\n * <xsd:element name=\"numberingChange\" type=\"CT_TrackChangeNumbering\" minOccurs=\"0\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"fldCharType\" type=\"ST_FldCharType\" use=\"required\"/>\n * <xsd:attribute name=\"fldLock\" type=\"s:ST_OnOff\"/>\n * <xsd:attribute name=\"dirty\" type=\"s:ST_OnOff\"/>\n * </xsd:complexType>\n * ```\n * @internal\n */\nconst createFieldChar = (\n type: (typeof FieldCharacterType)[keyof typeof FieldCharacterType],\n dirty?: boolean,\n ffData?: string,\n fldData?: string,\n fieldLock?: boolean,\n): string => {\n const children: string[] = [];\n if (fldData !== undefined) {\n children.push(element(\"w:fldData\", { \"xml:space\": \"preserve\" }, [fldData]));\n }\n if (ffData) {\n children.push(ffData);\n }\n return element(\n \"w:fldChar\",\n {\n \"w:dirty\": dirty,\n \"w:fldLock\": fieldLock,\n \"w:fldCharType\": type,\n },\n children.length > 0 ? children : undefined,\n );\n};\n\n/**\n * Creates the beginning of a complex field.\n *\n * The Begin element marks the start of a field. A field consists of a begin character,\n * field instructions, an optional separate character, field result, and an end character.\n *\n * For form fields, pass `formField` to embed `w:ffData` within the begin `w:fldChar`.\n *\n * @param dirty - Whether the field should be recalculated\n * @param formField - Optional form field data to embed in the begin character\n *\n * @example\n * ```typescript\n * // Simple field begin\n * createBegin();\n *\n * // Form field (checkbox)\n * createBegin(false, {\n * name: \"Check1\",\n * checkBox: { checked: true, sizeAuto: true },\n * });\n * ```\n */\nexport const createBegin = (\n dirty?: boolean,\n formField?: FormFieldOptions,\n fieldLock?: boolean,\n): string =>\n createFieldChar(\n FieldCharacterType.BEGIN,\n dirty,\n formField ? createFormFieldData(formField) : undefined,\n undefined,\n fieldLock,\n );\n\n/**\n * Creates the separator between field code and field result in a complex field.\n *\n * The Separate element divides the field code (instructions) from the field result\n * (the computed value).\n */\nexport const createSeparate = (dirty?: boolean): string =>\n createFieldChar(FieldCharacterType.SEPARATE, dirty);\n\n/**\n * Creates the end of a complex field.\n *\n * The End element marks the end of a field. Every field that begins with a Begin\n * element must be terminated with an End element.\n */\nexport const createEnd = (dirty?: boolean): string =>\n createFieldChar(FieldCharacterType.END, dirty);\n","/**\n * Shared inline run/paragraph stringification for DOCX descriptors.\n *\n * Used by table.ts, comments.ts, body.ts, and other descriptors that need to\n * serialize paragraph/run content. Includes JSON child dispatch for all\n * ParagraphChild variants (picture, chart, hyperlink, etc.).\n *\n * Pure string concatenation — no intermediate object tree.\n *\n * @module\n */\n\nimport { toUint8Array } from \"@office-open/core\";\nimport { TargetModeType } from \"@office-open/core\";\nimport { uniqueId } from \"@office-open/core\";\nimport { chartSpaceDesc } from \"@office-open/core/chart\";\nimport { createDataModel, definitionId } from \"@office-open/core/smartart\";\nimport { escapeXml } from \"@office-open/xml\";\nimport type { BackgroundRawMediaOptions } from \"@parts/document/document-background/document-background\";\nimport type {\n BookmarkOptions,\n BookmarkStartOptions,\n MarkupRangeOptions,\n MoveRangeOptions,\n MoveRangeStartOptions,\n} from \"@parts/paragraph/links/bookmark\";\nimport type { ParagraphChild, ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type { CommentChildOptions } from \"@parts/paragraph/run/comment-run\";\nimport { createPictureData } from \"@parts/paragraph/run/picture-run\";\nimport type { RunPropertiesOptions } from \"@parts/paragraph/run/properties\";\nimport type { RubyOptions } from \"@parts/paragraph/run/ruby\";\nimport {\n breakXml,\n EMPTY_RUN_ELEMENTS,\n type BreakOptions,\n type RunOptions,\n} from \"@parts/paragraph/run/run\";\nimport type { SmartArtOptions } from \"@parts/paragraph/run/smartart-run\";\nimport type {\n ChartMediaData,\n GroupChildMediaData,\n MediaData,\n SmartArtMediaData,\n GroupMediaData,\n ShapeMediaData,\n} from \"@shared/media\";\nimport { createTransformation } from \"@shared/media\";\n\nimport type { BodyContext } from \"../context\";\nimport { checkboxSymbolRunInner, stringifyCustomXmlShell, stringifySdtShell } from \"./bodychildren\";\nimport { drawingDesc } from \"./drawing\";\nimport { stringifyMath } from \"./paragraph/math/stringify\";\nimport { createBegin, createSeparate, createEnd } from \"./paragraph/run/field\";\nimport { stringifyParagraphProperties, stringifyRunProperties } from \"./paragraph/stringify\";\n\n// ── Run ──\n\n/** Serialize a deleted run: rPr + delText (or field delInstrText). */\nfunction stringifyDeletedRun(c: RunOptions | string): string {\n const opts = typeof c === \"string\" ? { text: c } : c;\n const parts: string[] = [];\n const rPr = stringifyRunProperties(opts);\n if (rPr) parts.push(rPr);\n if (opts.break) parts.push(breakXml(opts.break));\n const fieldMap: Record<string, string> = {\n CURRENT: \"PAGE\",\n TOTAL_PAGES: \"NUMPAGES\",\n TOTAL_PAGES_IN_SECTION: \"SECTIONPAGES\",\n };\n if (opts.children) {\n for (const cc of opts.children) {\n if (typeof cc === \"string\") {\n // Page number fields use delInstrText instead of instrText\n const instrText = fieldMap[cc];\n if (instrText) {\n parts.push(\n '<w:fldChar w:fldCharType=\"begin\"/>' +\n `<w:delInstrText xml:space=\"preserve\">${instrText}</w:delInstrText>` +\n '<w:fldChar w:fldCharType=\"separate\"/>' +\n '<w:fldChar w:fldCharType=\"end\"/>',\n );\n } else {\n parts.push(`<w:delText xml:space=\"preserve\">${escapeXml(cc)}</w:delText>`);\n }\n }\n }\n } else if (opts.text) {\n parts.push(`<w:delText xml:space=\"preserve\">${escapeXml(String(opts.text))}</w:delText>`);\n }\n return `<w:r>${parts.join(\"\")}</w:r>`;\n}\n\nexport function stringifyRunInline(opts: RunOptions, ctx: BodyContext): string {\n const parts: string[] = [];\n\n const rPr = stringifyRunProperties(opts);\n if (rPr) parts.push(rPr);\n\n if (opts.break) parts.push(breakXml(opts.break));\n\n if (opts.children) {\n for (const child of opts.children) {\n if (typeof child === \"string\") {\n parts.push(`<w:t xml:space=\"preserve\">${escapeXml(child)}</w:t>`);\n } else if (typeof child === \"object\" && child !== null) {\n // Bare run-inner elements — emit directly inside this <w:r>. Must run\n // before stringifyChildDispatch, which wraps paragraph-level children\n // in their own <w:r> (correct for paragraphs, nested/invalid in a run).\n if (\"tab\" in child) {\n parts.push(\"<w:tab/>\");\n continue;\n }\n if (\"pageBreak\" in child) {\n parts.push('<w:br w:type=\"page\"/>');\n continue;\n }\n if (\"columnBreak\" in child) {\n parts.push('<w:br w:type=\"column\"/>');\n continue;\n }\n if (\"break\" in child) {\n parts.push(breakXml((child as { break: number | BreakOptions }).break));\n continue;\n }\n // Empty run elements — separator, noBreakHyphen, pgNum, etc.\n const emptyXml = EMPTY_RUN_ELEMENTS[Object.keys(child)[0] ?? \"\"];\n if (emptyXml) {\n parts.push(emptyXml);\n continue;\n }\n // JSON child dispatch (images, charts, hyperlinks, etc.)\n const jsonResult = stringifyChildDispatch(child as ParagraphChild, ctx);\n if (jsonResult !== undefined) {\n if (Array.isArray(jsonResult)) {\n parts.push(...jsonResult);\n } else {\n parts.push(jsonResult);\n }\n } else if (\"text\" in child || \"children\" in child || \"break\" in child) {\n parts.push(stringifyRunInline(child as RunOptions, ctx));\n }\n }\n }\n } else if (opts.text !== undefined) {\n parts.push(`<w:t xml:space=\"preserve\">${escapeXml(String(opts.text))}</w:t>`);\n }\n\n const rsidAttrs: string[] = [];\n if (opts.rsid) rsidAttrs.push(` w:rsidR=\"${opts.rsid}\"`);\n if (opts.runPropertiesRsid) rsidAttrs.push(` w:rsidRPr=\"${opts.runPropertiesRsid}\"`);\n if (opts.deletionRsid) rsidAttrs.push(` w:rsidDel=\"${opts.deletionRsid}\"`);\n const attr = rsidAttrs.join(\"\");\n\n const body = parts.join(\"\");\n return body.length === 0 ? (attr ? `<w:r${attr}/>` : \"<w:r/>\") : `<w:r${attr}>${body}</w:r>`;\n}\n\nlet nextChartId = 1;\n\n// ── JSON child dispatch ──\n\n/**\n * Stringify a ParagraphChild into one or more XML strings.\n *\n * Handles side effects (media, chart, smartArt, relationship registration)\n * directly without creating temporary class instances.\n *\n * Returns `undefined` if the child is not a recognized JSON wrapper.\n */\n/**\n * Wrap a `<w:drawing>` run, rebuilding an mc:AlternateContent wrapper when a\n * VML fallback was carried from parse (Choice stays structured/editable,\n * Fallback round-trips as raw XML for fidelity).\n */\nfunction wrapDrawingRun(\n drawingXml: string | undefined,\n opts: { vmlFallback?: string; mcChoiceRequires?: string; runProperties?: RunPropertiesOptions },\n): string {\n const xml = drawingXml ?? \"\";\n const rPr = stringifyRunProperties(opts.runProperties) ?? \"\";\n if (opts.vmlFallback) {\n const requires = opts.mcChoiceRequires ?? \"wps\";\n // opts.vmlFallback is the serialized <mc:Fallback>…</mc:Fallback> element,\n // so splice it in directly (no extra wrapper).\n return `<w:r>${rPr}<mc:AlternateContent><mc:Choice Requires=\"${requires}\">${xml}</mc:Choice>${opts.vmlFallback}</mc:AlternateContent></w:r>`;\n }\n return `<w:r>${rPr}${xml}</w:r>`;\n}\n\n/**\n * Register media carried by a VML fallback (mc:AlternateContent Fallback) so the\n * compiler resolves the fallback's `{fileName}` placeholders into rIds.\n *\n * A VML fallback image mirrors its Choice blip (same source bytes). When the\n * blip is already registered, reuse it and remap the fallback's `{fileName}`\n * placeholder to the shared media — matching Office, which emits one\n * relationship/file per image rather than a duplicate for the VML branch.\n */\nfunction registerVmlFallbackMedia(\n opts: { vmlFallback?: string; vmlFallbackMedia?: BackgroundRawMediaOptions[] },\n ctx: BodyContext,\n): void {\n if (!opts.vmlFallbackMedia) return;\n for (const m of opts.vmlFallbackMedia) {\n const data = toUint8Array(m.data);\n const entry = ctx.file.media.addMedia(\n data,\n m.type,\n (fileName) =>\n ({\n type: m.type,\n data,\n fileName,\n transformation: { emus: { x: 0, y: 0 }, pixels: { x: 0, y: 0 } },\n }) as MediaData,\n m.fileName,\n );\n // Dedup may reuse the Choice blip's file name; remap the VML fallback\n // placeholder so both branches share one relationship/file (matches Office).\n if (entry.fileName !== m.fileName && opts.vmlFallback) {\n opts.vmlFallback = opts.vmlFallback.split(`{${m.fileName}}`).join(`{${entry.fileName}}`);\n }\n }\n}\n\n/**\n * Build the rPr XML for a break/tab run from its structured run properties.\n */\n/** Shared attribute string for CT_MarkupRange end markers (commentRange, move range end). */\nfunction buildMarkupRangeAttrs(m: MarkupRangeOptions): string {\n const a: string[] = [`w:id=\"${m.id}\"`];\n if (m.displacedByCustomXml) a.push(`w:displacedByCustomXml=\"${m.displacedByCustomXml}\"`);\n return a.join(\" \");\n}\n\n/** Shared attribute string for w:bookmarkStart (CT_Bookmark). */\nfunction buildBookmarkStartAttrs(bs: BookmarkStartOptions): string {\n const a: string[] = [`w:id=\"${bs.id}\"`, `w:name=\"${escapeXml(bs.name)}\"`];\n if (bs.displacedByCustomXml) a.push(`w:displacedByCustomXml=\"${bs.displacedByCustomXml}\"`);\n if (bs.colFirst !== undefined) a.push(`w:colFirst=\"${bs.colFirst}\"`);\n if (bs.colLast !== undefined) a.push(`w:colLast=\"${bs.colLast}\"`);\n return a.join(\" \");\n}\n\n/** Shared attribute string for w:moveFromRangeStart / w:moveToRangeStart (CT_MoveBookmark). */\nfunction buildMoveRangeStartAttrs(m: MoveRangeStartOptions): string {\n const a: string[] = [`w:id=\"${m.id}\"`];\n if (m.name) a.push(`w:name=\"${escapeXml(m.name)}\"`);\n if (m.author) a.push(`w:author=\"${escapeXml(m.author)}\"`);\n if (m.date) a.push(`w:date=\"${m.date}\"`);\n if (m.displacedByCustomXml) a.push(`w:displacedByCustomXml=\"${m.displacedByCustomXml}\"`);\n if (m.colFirst !== undefined) a.push(`w:colFirst=\"${m.colFirst}\"`);\n if (m.colLast !== undefined) a.push(`w:colLast=\"${m.colLast}\"`);\n return a.join(\" \");\n}\n\n/** Stringify inline run/text content — the `wrap` shared by every sugar child. */\nfunction stringifyInlineWrap(wrap: (string | RunOptions)[] | undefined, ctx: BodyContext): string {\n const parts: string[] = [];\n for (const item of wrap ?? []) {\n parts.push(\n typeof item === \"string\"\n ? stringifyRunInline({ text: item }, ctx)\n : stringifyRunInline(item, ctx),\n );\n }\n return parts.join(\"\");\n}\n\n/**\n * Expand a `{ comment }` sugar child: allocate the comment id, register the\n * comment entry (side effect, consumed when word/comments.xml is stringified),\n * and emit the range markers + anchored content + reference with one shared id.\n *\n * The caller never supplies an id — the library owns id allocation and pairing.\n */\nfunction stringifyCommentChild(c: CommentChildOptions, ctx: BodyContext): string {\n const id = ctx.file.comments.nextId++;\n ctx.file.comments.entries.push({\n id,\n author: c.author,\n initials: c.initials,\n date: c.date,\n children: c.children,\n });\n\n return (\n `<w:commentRangeStart w:id=\"${id}\"/>` +\n stringifyInlineWrap(c.wrap, ctx) +\n `<w:commentRangeEnd w:id=\"${id}\"/>` +\n `<w:r><w:rPr><w:rStyle w:val=\"CommentReference\"/></w:rPr><w:commentReference w:id=\"${id}\"/></w:r>`\n );\n}\n\n/**\n * Expand a `{ bookmark }` sugar child: allocate the bookmark id and emit the\n * paired bookmarkStart/bookmarkEnd with the anchored content between them.\n * Bookmarks are pure markup — the only effect is the two markers.\n */\nfunction stringifyBookmarkChild(b: BookmarkOptions, ctx: BodyContext): string {\n const id = ctx.file.markupIds.rangeNext++;\n const startAttrs = buildBookmarkStartAttrs({\n id,\n name: b.name,\n displacedByCustomXml: b.displacedByCustomXml,\n colFirst: b.colFirst,\n colLast: b.colLast,\n });\n const endAttrs = buildMarkupRangeAttrs({ id, displacedByCustomXml: b.displacedByCustomXml });\n return `<w:bookmarkStart ${startAttrs}/>${stringifyInlineWrap(b.wrap, ctx)}<w:bookmarkEnd ${endAttrs}/>`;\n}\n\n/**\n * Expand a `{ moveFrom }` / `{ moveTo }` sugar child: allocate the range id and\n * the move-run id, then emit the paired range markers with the moved run between\n * them. The move run (CT_TrackChange) carries the moved content.\n */\nfunction stringifyMoveRangeChild(\n kind: \"moveFrom\" | \"moveTo\",\n opts: MoveRangeOptions,\n ctx: BodyContext,\n): string {\n const rangeId = ctx.file.markupIds.rangeNext++;\n const runId = ctx.file.markupIds.moveRunNext++;\n const isMoveFrom = kind === \"moveFrom\";\n const startTag = isMoveFrom ? \"w:moveFromRangeStart\" : \"w:moveToRangeStart\";\n const endTag = isMoveFrom ? \"w:moveFromRangeEnd\" : \"w:moveToRangeEnd\";\n const runTag = isMoveFrom ? \"w:moveFrom\" : \"w:moveTo\";\n const rangeStartAttrs = buildMoveRangeStartAttrs({\n id: rangeId,\n name: opts.name,\n author: opts.author,\n date: opts.date,\n displacedByCustomXml: opts.displacedByCustomXml,\n colFirst: opts.colFirst,\n colLast: opts.colLast,\n });\n const endAttrs = buildMarkupRangeAttrs({\n id: rangeId,\n displacedByCustomXml: opts.displacedByCustomXml,\n });\n return (\n `<${startTag} ${rangeStartAttrs}/>` +\n `<${runTag} w:id=\"${runId}\" w:author=\"${escapeXml(opts.author)}\" w:date=\"${opts.date}\">${stringifyInlineWrap(opts.wrap, ctx)}</${runTag}>` +\n `<${endTag} ${endAttrs}/>`\n );\n}\n\nfunction runPropertiesXml(child: ParagraphChild): string {\n return stringifyRunProperties(child as RunOptions) ?? \"\";\n}\n\nexport function stringifyChildDispatch(\n child: ParagraphChild,\n ctx: BodyContext,\n): string | string[] | undefined {\n // Simple break types — pure XML, no side effects. A break run may carry run\n // properties (round-tripped from <w:r><w:rPr>…</w:rPr><w:br…/></w:r>).\n if (\"pageBreak\" in child) {\n return `<w:r>${runPropertiesXml(child)}<w:br w:type=\"page\"/></w:r>`;\n }\n if (\"columnBreak\" in child) {\n return `<w:r>${runPropertiesXml(child)}<w:br w:type=\"column\"/></w:r>`;\n }\n if (\"tab\" in child) {\n return `<w:r>${runPropertiesXml(child)}<w:tab/></w:r>`;\n }\n\n // Reference types — pure XML, no side effects\n if (\"footnoteReference\" in child) {\n const ref = child.footnoteReference;\n const id = typeof ref === \"number\" ? ref : ref.id;\n const cmf =\n typeof ref === \"object\" && ref.customMarkFollows ? ' w:customMarkFollows=\"true\"' : \"\";\n return `<w:r><w:rPr><w:rStyle w:val=\"FootnoteReference\"/></w:rPr><w:footnoteReference w:id=\"${id}\"${cmf}/></w:r>`;\n }\n if (\"endnoteReference\" in child) {\n const ref = child.endnoteReference;\n const id = typeof ref === \"number\" ? ref : ref.id;\n const cmf =\n typeof ref === \"object\" && ref.customMarkFollows ? ' w:customMarkFollows=\"true\"' : \"\";\n return `<w:r><w:rPr><w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteReference w:id=\"${id}\"${cmf}/></w:r>`;\n }\n\n // Comment sugar — library allocates the id, emits the range markers +\n // reference, and registers the comment entry (see stringifyCommentChild).\n if (\"comment\" in child) return stringifyCommentChild(child.comment, ctx);\n\n // Comment markers — pure XML\n if (\"commentRangeStart\" in child)\n return `<w:commentRangeStart ${buildMarkupRangeAttrs(child.commentRangeStart)}/>`;\n if (\"commentRangeEnd\" in child)\n return `<w:commentRangeEnd ${buildMarkupRangeAttrs(child.commentRangeEnd)}/>`;\n if (\"commentReference\" in child)\n return `<w:r><w:rPr><w:rStyle w:val=\"CommentReference\"/></w:rPr><w:commentReference w:id=\"${child.commentReference}\"/></w:r>`;\n\n // Bookmark markers — pure XML\n if (\"bookmarkStart\" in child) {\n return `<w:bookmarkStart ${buildBookmarkStartAttrs(child.bookmarkStart)}/>`;\n }\n if (\"bookmarkEnd\" in child) {\n return `<w:bookmarkEnd ${buildMarkupRangeAttrs(child.bookmarkEnd)}/>`;\n }\n // Bookmark sugar — library allocates the id and pairs start/end.\n if (\"bookmark\" in child) return stringifyBookmarkChild(child.bookmark, ctx);\n\n // Symbol run — direct XML output.\n // <w:sym> is a self-closing element, not text: emit it directly so it is\n // not escaped into a <w:t> by the run children path.\n if (\"symbolRun\" in child) {\n const opts = child.symbolRun;\n const rPr = stringifyRunProperties(opts) ?? \"\";\n return `<w:r>${rPr}<w:sym w:char=\"${opts.char}\" w:font=\"${opts.symbolFont ?? \"Wingdings\"}\"/></w:r>`;\n }\n\n // Form field (checkbox / dropdown list / text input) — fldChar sequence.\n // Word needs the field code (instrText) between begin and separate to\n // recognize the field type and render its result.\n if (\"formField\" in child) {\n const ff = child.formField;\n let result = \"\";\n let instrCode = \"\";\n let symbolFont = false;\n if (ff.checkBox) {\n result = ff.checkBox.checked ? \"☒\" : \"☐\";\n instrCode = \"FORMCHECKBOX\";\n // U+2610/U+2612 are absent from common body fonts (Calibri/Times);\n // MS Gothic holds them and matches the SDT w14:checkbox default.\n symbolFont = true;\n } else if (ff.dropDownList) {\n const idx = ff.dropDownList.result ?? ff.dropDownList.default;\n result = idx !== undefined ? (ff.dropDownList.entries[idx] ?? \"\") : \"\";\n instrCode = \"FORMDROPDOWN\";\n } else if (ff.textInput) {\n // Prefer the user-entered value (result run) over the placeholder default.\n result = ff.textInput.value ?? ff.textInput.default ?? \"\";\n instrCode = \"FORMTEXT\";\n }\n const rPr = symbolFont\n ? '<w:rPr><w:rFonts w:ascii=\"MS Gothic\" w:hAnsi=\"MS Gothic\"/></w:rPr>'\n : \"\";\n return (\n `<w:r>${createBegin(false, ff)}</w:r>` +\n `<w:r><w:instrText xml:space=\"preserve\"> ${instrCode} </w:instrText></w:r>` +\n `<w:r>${createSeparate()}</w:r>` +\n `<w:r>${rPr}<w:t xml:space=\"preserve\">${escapeXml(result)}</w:t></w:r>` +\n `<w:r>${createEnd()}</w:r>`\n );\n }\n\n // Picture — side effect: media registration (content-deduplicated via core Media)\n if (\"picture\" in child) {\n const opts = child.picture;\n const rawData = toUint8Array(opts.data, { encoding: \"base64\" }) as Uint8Array;\n\n let mediaData: MediaData;\n if (opts.type === \"svg\") {\n const fallbackData = toUint8Array(opts.fallback.data, { encoding: \"base64\" }) as Uint8Array;\n const fallbackType = opts.fallback.type;\n // Register the raster fallback first so its file name is allocated, then\n // build the svg entry referencing it. Dedup applies to both independently.\n const fallback = ctx.file.media.addMedia(\n fallbackData,\n fallbackType,\n (fileName) =>\n ({\n type: fallbackType,\n ...createPictureData(fallbackData, opts.transformation, fileName),\n }) as MediaData,\n );\n mediaData = ctx.file.media.addMedia(\n rawData,\n \"svg\",\n (fileName) =>\n ({\n type: \"svg\" as const,\n ...createPictureData(\n rawData,\n opts.transformation,\n fileName,\n opts.sourceRectangle,\n opts.nonVisualProperties,\n ),\n useLocalDpi: opts.useLocalDpi,\n fallback,\n }) as MediaData,\n );\n } else {\n const type = opts.type;\n mediaData = ctx.file.media.addMedia(\n rawData,\n type,\n (fileName) =>\n ({\n type,\n ...createPictureData(\n rawData,\n opts.transformation,\n fileName,\n opts.sourceRectangle,\n opts.nonVisualProperties,\n ),\n useLocalDpi: opts.useLocalDpi,\n }) as MediaData,\n );\n }\n\n // Build drawing XML via descriptor (zero XmlComponent instances)\n const drawingXml = drawingDesc.stringify(\n {\n mediaData,\n docProperties: opts.altText,\n floating: opts.floating,\n outline: opts.outline,\n fill: opts.fill,\n effects: opts.effects,\n blipEffects: opts.blipEffects,\n tile: opts.tile,\n graphicFrameLocks: opts.graphicFrameLocks,\n },\n ctx,\n );\n return wrapDrawingRun(drawingXml, opts);\n }\n\n // Chart — side effect: chart registration\n if (\"chart\" in child) {\n const opts = child.chart;\n const chartKey = `chart_${nextChartId++}`;\n const mediaData: ChartMediaData = {\n chartKey,\n transformation: createTransformation(opts.transformation),\n type: \"chart\",\n };\n\n // Register chart — pass all ChartSpaceOptions fields through\n const chartXml = chartSpaceDesc.stringify(\n {\n categories: opts.categories,\n series: opts.series,\n showLegend: opts.showLegend,\n style: opts.style,\n title: opts.title,\n type: opts.type,\n threeD: opts.threeD,\n view3D: opts.view3D,\n },\n ctx.file,\n );\n ctx.file.charts.addChart(chartKey, {\n key: chartKey,\n chartSpaceXml: chartXml ?? \"\",\n });\n\n const drawingXml = drawingDesc.stringify(\n {\n mediaData,\n docProperties: opts.altText,\n floating: opts.floating,\n },\n ctx,\n );\n return `<w:r>${drawingXml}</w:r>`;\n }\n\n // SmartArt — side effect: smartArt registration\n if (\"smartArt\" in child) {\n const opts = child.smartArt;\n const hash = hashSmartArtData(opts);\n const smartArtKey = `smartart_${hash}`;\n const mediaData: SmartArtMediaData = {\n smartArtKey,\n transformation: createTransformation(opts.transformation),\n type: \"smartart\",\n };\n\n // Register SmartArt — custom definitions embed their own id in the doc\n // point's type ids.\n const layoutId =\n typeof opts.layout === \"object\" ? definitionId(opts.layout) : (opts.layout ?? \"default\");\n const styleId =\n typeof opts.style === \"object\" ? definitionId(opts.style) : (opts.style ?? \"simple1\");\n const colorId =\n typeof opts.color === \"object\" ? definitionId(opts.color) : (opts.color ?? \"accent1_2\");\n const dataModelXml = createDataModel(opts.data.nodes, layoutId, styleId, colorId);\n\n ctx.file.smartArts.addSmartArt(smartArtKey, {\n dataModelXml,\n key: smartArtKey,\n layout: opts.layout ?? \"default\",\n style: opts.style ?? \"simple1\",\n color: opts.color ?? \"accent1_2\",\n });\n\n const drawingXml = drawingDesc.stringify(\n {\n mediaData,\n docProperties: opts.altText,\n floating: opts.floating,\n },\n ctx,\n );\n return `<w:r>${drawingXml}</w:r>`;\n }\n\n // WPS Shape (WordProcessing Shape) — side effect: blip fill media registration\n if (\"wpsShape\" in child) {\n const opts = child.wpsShape;\n const mediaData: ShapeMediaData = {\n data: opts,\n transformation: createTransformation(opts.transformation),\n type: \"wps\",\n };\n\n const drawingXml = drawingDesc.stringify(\n {\n mediaData,\n docProperties: opts.altText,\n floating: opts.floating,\n outline: opts.outline,\n fill: opts.fill,\n graphicFrameLocks: opts.graphicFrameLocks,\n },\n ctx,\n );\n registerVmlFallbackMedia(opts, ctx);\n return wrapDrawingRun(drawingXml, opts);\n }\n\n // Content part (w:contentPart) — run-level EG_RunInnerContent element (CT_Rel).\n // Word references ink and other opaque parts this way; the richer placement\n // fields of ContentPartOptions only apply inside a wpg group child.\n if (\"contentPart\" in child) {\n return `<w:r><w:contentPart r:id=\"${child.contentPart.referenceId}\"/></w:r>`;\n }\n\n // WPG Group (WordProcessing Group) — group of shapes/pictures\n if (\"wpgGroup\" in child) {\n const opts = child.wpgGroup;\n const mediaData: GroupMediaData = {\n children: opts.children,\n transformation: createTransformation(opts.transformation),\n childOffset: opts.childOffset,\n childExtent: opts.childExtent,\n fill: opts.fill,\n effects: opts.effects,\n groupShapeLocks: opts.groupShapeLocks,\n type: \"wpg\",\n };\n\n // Register pic children media so {fileName} placeholders resolve, recursing\n // into nested wpg groups. wps children carry shape data, not media.\n const registerMedia = (children: readonly GroupChildMediaData[]): void => {\n for (const c of children) {\n if (c.type === \"wps\") continue;\n if (c.type === \"wpg\") {\n registerMedia(c.children);\n continue;\n }\n if (c.type === \"chart\") {\n // Group-nested charts register their chart part from the parsed or\n // fresh chartOptions; the {chart:key} placeholder resolves in the\n // compiler like a top-level chart run.\n if (c.chartOptions && !c.chartKey) {\n c.chartKey = `chart_${nextChartId++}`;\n ctx.file.charts.addChart(c.chartKey, {\n key: c.chartKey,\n chartSpaceXml: chartSpaceDesc.stringify(c.chartOptions, ctx.file) ?? \"\",\n });\n }\n continue;\n }\n if (c.type === \"contentPart\") continue;\n if (c.type === \"svg\") {\n // Register the raster fallback first so its file name is allocated,\n // then the SVG entry referencing it. Dedup applies to each independently.\n const fb = c.fallback;\n const fbEntry = ctx.file.media.addMedia(\n fb.data,\n fb.type,\n () => fb as MediaData,\n fb.fileName,\n );\n fb.fileName = fbEntry.fileName;\n const svgEntry = ctx.file.media.addMedia(c.data, \"svg\", () => c as MediaData, c.fileName);\n c.fileName = svgEntry.fileName;\n continue;\n }\n const entry = ctx.file.media.addMedia(c.data, c.type, () => c as MediaData, c.fileName);\n // Sync to the canonical entry: when these bytes dedupe against an earlier\n // image, addMedia returns that entry without invoking the build callback,\n // leaving c.fileName at the source basename — the {fileName} placeholder\n // then fails to resolve. entry.fileName is always the registered name.\n c.fileName = entry.fileName;\n }\n };\n registerMedia(opts.children);\n\n const drawingXml = drawingDesc.stringify(\n {\n mediaData,\n docProperties: opts.altText,\n floating: opts.floating,\n graphicFrameLocks: opts.graphicFrameLocks,\n },\n ctx,\n );\n registerVmlFallbackMedia(opts, ctx);\n return wrapDrawingRun(drawingXml, opts);\n }\n\n // Ruby annotation — pure string concatenation\n if (\"ruby\" in child && typeof child.ruby === \"object\" && child.ruby !== null) {\n const r = child.ruby as RubyOptions;\n const align = r.alignment ?? \"center\";\n const hps = (r.fontSize ?? 10) * 2;\n const hpsRaise = (r.raise ?? 10) * 2;\n const hpsBaseText = (r.baseFontSize ?? 20) * 2;\n const lid = r.languageId ?? \"ja-JP\";\n\n const prParts = [\n `<w:rubyAlign w:val=\"${align}\"/>`,\n `<w:hps w:val=\"${hps}\"/>`,\n `<w:hpsRaise w:val=\"${hpsRaise}\"/>`,\n `<w:hpsBaseText w:val=\"${hpsBaseText}\"/>`,\n `<w:lid w:val=\"${lid}\"/>`,\n ];\n if (r.dirty) prParts.push(\"<w:dirty/>\");\n\n const rt = `<w:rt><w:r><w:t xml:space=\"preserve\">${escapeXml(r.text)}</w:t></w:r></w:rt>`;\n const rubyBase = `<w:rubyBase><w:r><w:t xml:space=\"preserve\">${escapeXml(r.base)}</w:t></w:r></w:rubyBase>`;\n\n return `<w:ruby><w:rubyPr>${prParts.join(\"\")}</w:rubyPr>${rt}${rubyBase}</w:ruby>`;\n }\n\n // Math — pure string concatenation\n if (\"math\" in child && typeof child.math === \"object\" && child.math !== null) {\n const mathOpts = child.math;\n const children = mathOpts.children ?? [];\n return stringifyMath(children);\n }\n\n // Inserted text run(s) — w:ins wraps one or more runs (CT_RunTrackChange)\n if (\"insertion\" in child) {\n const { id, author, date, children } = child.insertion;\n const body = children\n .map((c) => stringifyRunInline(typeof c === \"string\" ? { text: c } : c, ctx))\n .join(\"\");\n return `<w:ins w:id=\"${id}\" w:author=\"${escapeXml(String(author))}\" w:date=\"${date}\">${body}</w:ins>`;\n }\n\n // Deleted text run(s) — w:del wraps one or more runs (delText content)\n if (\"deletion\" in child) {\n const { id, author, date, children } = child.deletion;\n const body = children.map((c) => stringifyDeletedRun(c)).join(\"\");\n return `<w:del w:id=\"${id}\" w:author=\"${escapeXml(String(author))}\" w:date=\"${date}\">${body}</w:del>`;\n }\n\n // Hyperlink — side effect: relationship registration\n if (\"hyperlink\" in child) {\n const hl = child.hyperlink;\n\n // Serialize children using stringifyRunInline. A top-level `text` is a\n // shorthand for a single text run; without it `{ text, hyperlink }` would\n // emit an empty <w:hyperlink>.\n const childParts: string[] = [];\n if (child.text !== undefined) {\n childParts.push(stringifyRunInline({ text: child.text }, ctx));\n }\n if (hl.children) {\n for (const rc of hl.children) {\n if (typeof rc === \"string\") {\n childParts.push(stringifyRunInline({ text: rc }, ctx));\n } else {\n childParts.push(stringifyRunInline(rc, ctx));\n }\n }\n }\n const body = childParts.join(\"\");\n\n const pushHlAttrs = (attrs: string[]): void => {\n if (hl.history !== false) attrs.push('w:history=\"1\"');\n if (hl.tooltip) attrs.push(`w:tooltip=\"${escapeXml(hl.tooltip)}\"`);\n if (hl.targetFrame) attrs.push(`w:tgtFrame=\"${escapeXml(hl.targetFrame)}\"`);\n if (hl.docLocation) attrs.push(`w:docLocation=\"${escapeXml(hl.docLocation)}\"`);\n };\n if (hl.url) {\n const linkId = uniqueId();\n ctx.viewWrapper.relationships.addRelationship(\n linkId,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n hl.url,\n TargetModeType.EXTERNAL,\n );\n const attrs = [`r:id=\"rId${linkId}\"`];\n pushHlAttrs(attrs);\n return `<w:hyperlink ${attrs.join(\" \")}>${body}</w:hyperlink>`;\n }\n if (hl.anchor) {\n const attrs = [`w:anchor=\"${escapeXml(hl.anchor)}\"`];\n pushHlAttrs(attrs);\n return `<w:hyperlink ${attrs.join(\" \")}>${body}</w:hyperlink>`;\n }\n return \"\";\n }\n\n // ── Proof error markers ──\n if (\"proofErr\" in child) return `<w:proofErr w:type=\"${child.proofErr}\"/>`;\n\n // ── Positional tab ──\n if (\"positionalTab\" in child) {\n const pt = child.positionalTab;\n return `<w:ptab w:alignment=\"${pt.alignment}\" w:leader=\"${pt.leader}\" w:relativeTo=\"${pt.relativeTo}\"/>`;\n }\n\n // ── Permission range markers ──\n if (\"permStart\" in child) {\n const ps = child.permStart;\n const a: string[] = [`w:id=\"${ps.id}\"`];\n if (ps.editor !== undefined) a.push(`w:ed=\"${escapeXml(String(ps.editor))}\"`);\n if (ps.editGroup !== undefined) a.push(`w:edGrp=\"${ps.editGroup}\"`);\n if (ps.colFirst !== undefined) a.push(`w:colFirst=\"${ps.colFirst}\"`);\n if (ps.colLast !== undefined) a.push(`w:colLast=\"${ps.colLast}\"`);\n return `<w:permStart ${a.join(\" \")}/>`;\n }\n if (\"permEnd\" in child) return `<w:permEnd w:id=\"${child.permEnd}\"/>`;\n\n // ── Move revision range markers ──\n if (\"moveFromRangeStart\" in child) {\n return `<w:moveFromRangeStart ${buildMoveRangeStartAttrs(child.moveFromRangeStart)}/>`;\n }\n if (\"moveFromRangeEnd\" in child)\n return `<w:moveFromRangeEnd ${buildMarkupRangeAttrs(child.moveFromRangeEnd)}/>`;\n if (\"moveToRangeStart\" in child) {\n return `<w:moveToRangeStart ${buildMoveRangeStartAttrs(child.moveToRangeStart)}/>`;\n }\n if (\"moveToRangeEnd\" in child)\n return `<w:moveToRangeEnd ${buildMarkupRangeAttrs(child.moveToRangeEnd)}/>`;\n // Move revision sugar — library allocates range + run ids and pairs markers.\n if (\"moveFrom\" in child) return stringifyMoveRangeChild(\"moveFrom\", child.moveFrom, ctx);\n if (\"moveTo\" in child) return stringifyMoveRangeChild(\"moveTo\", child.moveTo, ctx);\n\n // ── Move revision text runs ──\n if (\"movedFrom\" in child) {\n const { id, author, date, children } = child.movedFrom;\n const body = children\n .map((c) => stringifyRunInline(typeof c === \"string\" ? { text: c } : c, ctx))\n .join(\"\");\n return `<w:moveFrom w:id=\"${id}\" w:author=\"${escapeXml(String(author))}\" w:date=\"${date}\">${body}</w:moveFrom>`;\n }\n if (\"movedTo\" in child) {\n const { id, author, date, children } = child.movedTo;\n const body = children\n .map((c) => stringifyRunInline(typeof c === \"string\" ? { text: c } : c, ctx))\n .join(\"\");\n return `<w:moveTo w:id=\"${id}\" w:author=\"${escapeXml(String(author))}\" w:date=\"${date}\">${body}</w:moveTo>`;\n }\n\n // ── Custom XML range markers (track changes) ──\n if (\"customXmlInsRangeStart\" in child) {\n const o = child.customXmlInsRangeStart;\n return `<w:customXmlInsRangeStart w:id=\"${o.id}\"${o.author ? ` w:author=\"${escapeXml(o.author)}\"` : \"\"}${o.date ? ` w:date=\"${o.date}\"` : \"\"}/>`;\n }\n if (\"customXmlInsRangeEnd\" in child)\n return `<w:customXmlInsRangeEnd w:id=\"${child.customXmlInsRangeEnd}\"/>`;\n if (\"customXmlDelRangeStart\" in child) {\n const o = child.customXmlDelRangeStart;\n return `<w:customXmlDelRangeStart w:id=\"${o.id}\"${o.author ? ` w:author=\"${escapeXml(o.author)}\"` : \"\"}${o.date ? ` w:date=\"${o.date}\"` : \"\"}/>`;\n }\n if (\"customXmlDelRangeEnd\" in child)\n return `<w:customXmlDelRangeEnd w:id=\"${child.customXmlDelRangeEnd}\"/>`;\n if (\"customXmlMoveFromRangeStart\" in child) {\n const o = child.customXmlMoveFromRangeStart;\n return `<w:customXmlMoveFromRangeStart w:id=\"${o.id}\"${o.author ? ` w:author=\"${escapeXml(o.author)}\"` : \"\"}${o.date ? ` w:date=\"${o.date}\"` : \"\"}/>`;\n }\n if (\"customXmlMoveFromRangeEnd\" in child)\n return `<w:customXmlMoveFromRangeEnd w:id=\"${child.customXmlMoveFromRangeEnd}\"/>`;\n if (\"customXmlMoveToRangeStart\" in child) {\n const o = child.customXmlMoveToRangeStart;\n return `<w:customXmlMoveToRangeStart w:id=\"${o.id}\"${o.author ? ` w:author=\"${escapeXml(o.author)}\"` : \"\"}${o.date ? ` w:date=\"${o.date}\"` : \"\"}/>`;\n }\n if (\"customXmlMoveToRangeEnd\" in child)\n return `<w:customXmlMoveToRangeEnd w:id=\"${child.customXmlMoveToRangeEnd}\"/>`;\n\n // ── Simple field ──\n if (\"simpleField\" in child) {\n const sf = child.simpleField;\n const sfAttrs = [`w:instr=\"${escapeXml(sf.instruction)}\"`];\n if (sf.fieldLock !== undefined) sfAttrs.push(`w:fldLock=\"${sf.fieldLock ? 1 : 0}\"`);\n if (sf.dirty !== undefined) sfAttrs.push(`w:dirty=\"${sf.dirty ? 1 : 0}\"`);\n if (sf.cachedValue !== undefined) {\n return `<w:fldSimple ${sfAttrs.join(\" \")}><w:r><w:t>${escapeXml(sf.cachedValue)}</w:t></w:r></w:fldSimple>`;\n }\n return `<w:fldSimple ${sfAttrs.join(\" \")}/>`;\n }\n\n // ── Complex field (PAGE/DATE/TOC/... — fldChar field without w:ffData) ──\n if (\"complexField\" in child) {\n const cf = child.complexField;\n // Run-properties: Word writes identical rPr across a field's runs. Apply\n // the captured control-run rPr to begin/instrText/separate/end and the\n // result-run rPr to the result (defaults to the control rPr when the\n // result had none, matching Word's uniform behavior).\n const ctrl = cf.rPrXml ?? \"\";\n const res = cf.resultRPrXml ?? ctrl;\n // `separate` + the result run are emitted only when there is a cached\n // result; a result-less field round-trips as begin/instrText/end.\n const resultXml =\n cf.result !== undefined\n ? `<w:r>${ctrl}<w:fldChar w:fldCharType=\"separate\"/></w:r>` +\n `<w:r>${res}<w:t xml:space=\"preserve\">${escapeXml(cf.result)}</w:t></w:r>`\n : \"\";\n return (\n `<w:r>${ctrl}<w:fldChar w:fldCharType=\"begin\"/></w:r>` +\n `<w:r>${ctrl}<w:instrText xml:space=\"preserve\">${escapeXml(\n cf.instruction,\n )}</w:instrText></w:r>` +\n resultXml +\n `<w:r>${ctrl}<w:fldChar w:fldCharType=\"end\"/></w:r>`\n );\n }\n\n // ── Sequential identifier (SEQ field) ──\n if (\"seqIdentifier\" in child) {\n const id = child.seqIdentifier;\n return (\n \"<w:r>\" +\n '<w:fldChar w:fldCharType=\"begin\"/>' +\n `<w:instrText xml:space=\"preserve\"> SEQ ${escapeXml(id)} </w:instrText>` +\n '<w:fldChar w:fldCharType=\"separate\"/>' +\n '<w:fldChar w:fldCharType=\"end\"/>' +\n \"</w:r>\"\n );\n }\n\n // ── Page reference (PAGEREF field) ──\n if (\"pageReference\" in child) {\n const pr = child.pageReference;\n let instr = ` PAGEREF ${escapeXml(pr.bookmarkId)} `;\n if (pr.hyperlink) instr += \"\\\\h \";\n if (pr.useRelativePosition) instr += \"\\\\p \";\n return (\n \"<w:r>\" +\n '<w:fldChar w:fldCharType=\"begin\"/>' +\n `<w:instrText xml:space=\"preserve\">${instr}</w:instrText>` +\n '<w:fldChar w:fldCharType=\"end\"/>' +\n \"</w:r>\"\n );\n }\n\n // ── Bidirectional text containers ──\n if (\"dir\" in child) {\n const d = child.dir;\n const childXml = serializeDirChildren(d.children, ctx);\n return `<w:dir w:val=\"${d.val}\">${childXml}</w:dir>`;\n }\n if (\"bdo\" in child) {\n const b = child.bdo;\n const childXml = serializeDirChildren(b.children, ctx);\n return `<w:bdo w:val=\"${b.val}\">${childXml}</w:bdo>`;\n }\n\n // ── Smart tag ──\n if (\"smartTag\" in child) {\n const st = child.smartTag;\n const attrs: string[] = [];\n if (st.uri) attrs.push(`w:uri=\"${escapeXml(st.uri)}\"`);\n attrs.push(`w:element=\"${escapeXml(st.element)}\"`);\n\n const parts: string[] = [];\n if (st.properties?.length) {\n const propParts: string[] = [];\n for (const p of st.properties) {\n const pa: string[] = [];\n if (p.uri) pa.push(`w:uri=\"${escapeXml(p.uri)}\"`);\n pa.push(`w:name=\"${escapeXml(p.name)}\"`, `w:val=\"${escapeXml(p.val)}\"`);\n propParts.push(`<w:attr ${pa.join(\" \")}/>`);\n }\n parts.push(`<w:smartTagPr>${propParts.join(\"\")}</w:smartTagPr>`);\n }\n if (st.children) {\n for (const c of st.children) {\n if (typeof c === \"string\") {\n parts.push(stringifyRunInline({ text: c }, ctx));\n } else {\n const jr = stringifyChildDispatch(c, ctx);\n parts.push(\n jr !== undefined\n ? Array.isArray(jr)\n ? jr.join(\"\")\n : jr\n : stringifyRunInline(c as RunOptions, ctx),\n );\n }\n }\n }\n return `<w:smartTag ${attrs.join(\" \")}>${parts.join(\"\")}</w:smartTag>`;\n }\n\n // ── Custom XML run (CT_CustomXmlRun) ──\n if (\"customXml\" in child) {\n const cx = child.customXml;\n const contentParts: string[] = [];\n if (cx.children) {\n for (const c of cx.children) {\n if (typeof c === \"string\") {\n contentParts.push(stringifyRunInline({ text: c }, ctx));\n } else {\n const jr = stringifyChildDispatch(c as ParagraphChild, ctx);\n if (jr !== undefined) {\n contentParts.push(Array.isArray(jr) ? jr.join(\"\") : jr);\n } else {\n contentParts.push(stringifyRunInline(c as RunOptions, ctx));\n }\n }\n }\n }\n return stringifyCustomXmlShell(cx, contentParts.join(\"\"));\n }\n\n // ── Inline structured document tag (CT_SdtRun) ──\n if (\"sdt\" in child) {\n const s = child.sdt;\n let contentXml = \"\";\n if (s.properties.checkbox) {\n // Inline checkbox: render the state symbol as a run (no <w:p> wrapper).\n contentXml = checkboxSymbolRunInner(s.properties.checkbox);\n } else if (s.children && s.children.length > 0) {\n const cparts: string[] = [];\n for (const c of s.children) {\n if (typeof c === \"string\") {\n cparts.push(stringifyRunInline({ text: c }, ctx));\n } else {\n const jr = stringifyChildDispatch(c as ParagraphChild, ctx);\n if (jr !== undefined) {\n cparts.push(Array.isArray(jr) ? jr.join(\"\") : jr);\n } else if (\"text\" in c || \"children\" in c || \"break\" in c) {\n cparts.push(stringifyRunInline(c as RunOptions, ctx));\n }\n }\n }\n contentXml = cparts.join(\"\");\n }\n return stringifySdtShell(s.properties, s.endProperties, contentXml);\n }\n\n return undefined;\n}\n\n/** Serialize children of Dir/Bdo containers. */\nfunction serializeDirChildren(\n children: (ParagraphChild | string)[] | undefined,\n ctx: BodyContext,\n): string {\n if (!children) return \"\";\n const parts: string[] = [];\n for (const c of children) {\n if (typeof c === \"string\") {\n parts.push(stringifyRunInline({ text: c }, ctx));\n } else {\n const jr = stringifyChildDispatch(c, ctx);\n parts.push(\n jr !== undefined\n ? Array.isArray(jr)\n ? jr.join(\"\")\n : jr\n : stringifyRunInline(c as RunOptions, ctx),\n );\n }\n }\n return parts.join(\"\");\n}\n\n/** Hash SmartArt data for unique key generation (duplicated from SmartArtRun). */\nfunction hashSmartArtData(options: SmartArtOptions): number {\n // Layout/style/color participate: two diagrams with the same nodes but\n // different definitions are distinct parts.\n const data = JSON.stringify({\n data: options.data,\n layout: options.layout,\n style: options.style,\n color: options.color,\n });\n let hash = 0;\n for (let i = 0; i < data.length; i++) {\n const char = data.charCodeAt(i);\n hash = ((hash << 5) - hash + char) | 0;\n }\n return Math.abs(hash);\n}\n\n// ── Paragraph ──\n\nexport function stringifyParagraphInline(\n opts: string | ParagraphOptions,\n ctx: BodyContext,\n): string {\n const resolved: ParagraphOptions = typeof opts === \"string\" ? { text: opts } : opts;\n const parts: string[] = [];\n\n const props = stringifyParagraphProperties(resolved);\n if (props.xml) parts.push(props.xml);\n\n // Register numbering references from inline paragraphs (footnotes, endnotes, etc.)\n // so that concrete numbering instances are created and placeholders get resolved.\n if (props.numberingReferences.length > 0) {\n for (const ref of props.numberingReferences) {\n ctx.file.numbering.createConcreteNumberingInstance(ref.reference, ref.instance);\n }\n }\n\n if (resolved.text !== undefined) {\n parts.push(stringifyRunInline({ text: resolved.text }, ctx));\n }\n\n if (resolved.children) {\n for (const child of resolved.children) {\n if (typeof child === \"string\") {\n parts.push(stringifyRunInline({ text: child }, ctx));\n } else if (typeof child === \"object\" && child !== null) {\n // Try JSON child dispatch first (image, chart, hyperlink, etc.)\n const jsonResult = stringifyChildDispatch(child as ParagraphChild, ctx);\n if (jsonResult !== undefined) {\n if (Array.isArray(jsonResult)) {\n parts.push(...jsonResult);\n } else {\n parts.push(jsonResult);\n }\n } else if (\"text\" in child || \"children\" in child || \"break\" in child) {\n parts.push(stringifyRunInline(child as RunOptions, ctx));\n }\n }\n }\n }\n\n const body = parts.join(\"\");\n return body ? `<w:p>${body}</w:p>` : \"<w:p/>\";\n}\n","/**\n * Direct XML string builders for table properties.\n *\n * Replaces `buildTableProperties() + xml()`, `buildTableRowProperties() + xml()`,\n * `buildTableCellProperties() + xml()`, and `new TablePropertyExceptions().toXml()`\n * with direct string concatenation — no intermediate object tree.\n *\n * @module\n */\n\nimport { convertToTwip, xsdVerticalMergeRev } from \"@office-open/core\";\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport { attrsRaw } from \"@office-open/xml\";\nimport type { TableCellSpacingProperties } from \"@parts/table/table-cell-spacing\";\nimport type { TableCellBordersOptions } from \"@parts/table/table-cell/table-cell-components\";\nimport { VerticalMergeType } from \"@parts/table/table-cell/table-cell-components\";\nimport type {\n TableCellPropertiesChangeOptions,\n TableCellPropertiesOptions,\n} from \"@parts/table/table-cell/table-cell-properties\";\nimport type { TableBordersOptions } from \"@parts/table/table-properties/table-borders\";\nimport type { TableCellMarginOptions } from \"@parts/table/table-properties/table-cell-margin\";\nimport type { TableFloatOptions } from \"@parts/table/table-properties/table-float-properties\";\nimport type { TableLookOptions } from \"@parts/table/table-properties/table-look\";\nimport type {\n TablePropertiesChangeOptions,\n TablePropertiesOptions,\n} from \"@parts/table/table-properties/table-properties\";\nimport type { TablePropertyExOptions } from \"@parts/table/table-properties/table-property-exceptions\";\nimport type {\n CnfStyleOptions,\n TableRowPropertiesChangeOptions,\n TableRowPropertiesOptions,\n} from \"@parts/table/table-row/table-row-properties\";\nimport type { TableWidthProperties } from \"@parts/table/table-width\";\nimport { WidthType, widthPctToFiftieths } from \"@parts/table/table-width\";\nimport type { CellMergeAttributes } from \"@shared/track-revision\";\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport { borderStr, onOff, shadingStr } from \"../paragraph/stringify\";\n\n// ── Table width string ──\n\n// Normalize a CT_TblWidth @w value to a bare integer: pct percentage (50 / \"50%\") →\n// fiftieths, dxa length (twip number | UniversalMeasure) → twips. The emitted @w is\n// always an integer — never \"N%\" or a measure string, which are different XSD branches\n// (ST_Percentage / ST_UniversalMeasure) that Word treats as auto on tblW. A stray \"%\"\n// under dxa is a meaningless cross-branch value, passed through verbatim for parity.\nfunction tableWidthValue(\n size: TableWidthProperties[\"size\"],\n type: string | undefined,\n): number | string {\n if (type === WidthType.PERCENTAGE) return widthPctToFiftieths(size);\n if (typeof size === \"number\") return size;\n if (size.endsWith(\"%\")) return size;\n return convertToTwip(size as UniversalMeasure);\n}\n\nfunction tableWidthStr(name: string, opts: TableWidthProperties): string {\n const type = opts.type ?? WidthType.AUTO;\n const a = attrsRaw({\n \"w:w\": tableWidthValue(opts.size, type),\n \"w:type\": type,\n });\n return `<${name}${a}/>`;\n}\n\n// ── Cell margin string ──\n\nfunction cellMarginChildrenStr(opts: TableCellMarginOptions): string {\n // CT_TblCellMar sequence order: top, start, left, bottom, end, right.\n // Each side is an independent CT_TblWidth; margins default to DXA.\n const parts: string[] = [];\n const side = (name: string, w: TableWidthProperties | undefined): void => {\n if (w === undefined) return;\n parts.push(tableWidthStr(name, { size: w.size, type: w.type ?? WidthType.DXA }));\n };\n side(\"w:top\", opts.top);\n side(\"w:start\", opts.start);\n side(\"w:left\", opts.left);\n side(\"w:bottom\", opts.bottom);\n side(\"w:end\", opts.end);\n side(\"w:right\", opts.right);\n return parts.join(\"\");\n}\n\nfunction cellMarginStr(tag: string, opts: TableCellMarginOptions): string | undefined {\n const inner = cellMarginChildrenStr(opts);\n return inner ? `<${tag}>${inner}</${tag}>` : undefined;\n}\n\n// ── Table borders string ──\n\n// CT_TblBorders — all 6 sides are optional (minOccurs=0); emit only those set.\nfunction tableBordersStr(opts: TableBordersOptions): string | undefined {\n const parts: string[] = [];\n if (opts.top) parts.push(borderStr(\"w:top\", opts.top));\n if (opts.left) parts.push(borderStr(\"w:left\", opts.left));\n if (opts.bottom) parts.push(borderStr(\"w:bottom\", opts.bottom));\n if (opts.right) parts.push(borderStr(\"w:right\", opts.right));\n if (opts.insideHorizontal) parts.push(borderStr(\"w:insideH\", opts.insideHorizontal));\n if (opts.insideVertical) parts.push(borderStr(\"w:insideV\", opts.insideVertical));\n return parts.length > 0 ? `<w:tblBorders>${parts.join(\"\")}</w:tblBorders>` : undefined;\n}\n\n// ── Cell borders string ──\n\nfunction cellBordersStr(opts: TableCellBordersOptions): string | undefined {\n // CT_TcBorders sequence: top, start, left, bottom, end, right, insideH, insideV, tl2br, tr2bl.\n const parts: string[] = [];\n if (opts.top) parts.push(borderStr(\"w:top\", opts.top));\n if (opts.start) parts.push(borderStr(\"w:start\", opts.start));\n if (opts.left) parts.push(borderStr(\"w:left\", opts.left));\n if (opts.bottom) parts.push(borderStr(\"w:bottom\", opts.bottom));\n if (opts.end) parts.push(borderStr(\"w:end\", opts.end));\n if (opts.right) parts.push(borderStr(\"w:right\", opts.right));\n if (opts.insideHorizontal) parts.push(borderStr(\"w:insideH\", opts.insideHorizontal));\n if (opts.insideVertical) parts.push(borderStr(\"w:insideV\", opts.insideVertical));\n if (opts.topLeftToBottomRight) parts.push(borderStr(\"w:tl2br\", opts.topLeftToBottomRight));\n if (opts.topRightToBottomLeft) parts.push(borderStr(\"w:tr2bl\", opts.topRightToBottomLeft));\n return parts.length > 0 ? `<w:tcBorders>${parts.join(\"\")}</w:tcBorders>` : undefined;\n}\n\n// ── Float properties string ──\n\nfunction floatPropertiesStr(opts: TableFloatOptions): string {\n const a = attrsRaw({\n \"w:horzAnchor\": opts.horizontalAnchor,\n \"w:vertAnchor\": opts.verticalAnchor,\n \"w:tblpX\":\n opts.absoluteHorizontalPosition !== undefined\n ? convertToTwip(opts.absoluteHorizontalPosition)\n : undefined,\n \"w:tblpXSpec\": opts.relativeHorizontalPosition,\n \"w:tblpY\":\n opts.absoluteVerticalPosition !== undefined\n ? convertToTwip(opts.absoluteVerticalPosition)\n : undefined,\n \"w:tblpYSpec\": opts.relativeVerticalPosition,\n \"w:bottomFromText\":\n opts.bottomFromText !== undefined ? convertToTwip(opts.bottomFromText) : undefined,\n \"w:topFromText\": opts.topFromText !== undefined ? convertToTwip(opts.topFromText) : undefined,\n \"w:leftFromText\":\n opts.leftFromText !== undefined ? convertToTwip(opts.leftFromText) : undefined,\n \"w:rightFromText\":\n opts.rightFromText !== undefined ? convertToTwip(opts.rightFromText) : undefined,\n });\n return `<w:tblpPr${a}/>`;\n}\n\n// ── Table look string ──\n\nfunction tableLookStr(opts: TableLookOptions): string {\n const a = attrsRaw({\n \"w:firstRow\": opts.firstRow,\n \"w:lastRow\": opts.lastRow,\n \"w:firstColumn\": opts.firstColumn,\n \"w:lastColumn\": opts.lastColumn,\n \"w:noHBand\": opts.noHBand,\n \"w:noVBand\": opts.noVBand,\n });\n return `<w:tblLook${a}/>`;\n}\n\n// ── Conditional format style string (CT_Cnf) ──\n\nfunction cnfStyleStr(opts: CnfStyleOptions): string {\n const a = attrsRaw({\n \"w:val\": opts.val,\n \"w:firstRow\": opts.firstRow,\n \"w:lastRow\": opts.lastRow,\n \"w:firstColumn\": opts.firstColumn,\n \"w:lastColumn\": opts.lastColumn,\n \"w:oddVBand\": opts.oddVBand,\n \"w:evenVBand\": opts.evenVBand,\n \"w:oddHBand\": opts.oddHBand,\n \"w:evenHBand\": opts.evenHBand,\n \"w:firstRowFirstColumn\": opts.firstRowFirstColumn,\n \"w:firstRowLastColumn\": opts.firstRowLastColumn,\n \"w:lastRowFirstColumn\": opts.lastRowFirstColumn,\n \"w:lastRowLastColumn\": opts.lastRowLastColumn,\n });\n return `<w:cnfStyle${a}/>`;\n}\n\n// ── Change/revision attribute string ──\n\nfunction changeAttrStr(tag: string, opts: ChangedProperties): string {\n const a = attrsRaw({ \"w:author\": opts.author, \"w:date\": opts.date, \"w:id\": opts.id });\n return `<${tag}${a}/>`;\n}\n\n// ── Cell merge revision string ──\n\nfunction cellMergeStr(opts: CellMergeAttributes): string {\n const attrs: Record<string, string | number | boolean | undefined> = {\n \"w:author\": opts.author,\n \"w:date\": opts.date,\n \"w:id\": opts.id,\n };\n if (opts.verticalMerge !== undefined) {\n attrs[\"w:vMerge\"] = xsdVerticalMergeRev.to(opts.verticalMerge);\n }\n if (opts.verticalMergeOriginal !== undefined) {\n attrs[\"w:vMergeOrig\"] = xsdVerticalMergeRev.to(opts.verticalMergeOriginal);\n }\n const a = attrsRaw(attrs);\n return `<w:cellMerge${a}/>`;\n}\n\n// ── Cell spacing string ──\n\nfunction cellSpacingStr(opts: TableCellSpacingProperties): string {\n const a = attrsRaw({\n \"w:w\": tableWidthValue(opts.size, opts.type),\n \"w:type\": opts.type,\n });\n return `<w:tblCellSpacing${a}/>`;\n}\n\n// ── Table properties change (w:tblPrChange) ──\n\nfunction stringifyTablePropertiesChangeInner(options: TablePropertiesChangeOptions): string {\n const inner = stringifyTablePropertiesInner({ ...options, includeIfEmpty: true });\n const a = attrsRaw({ \"w:author\": options.author, \"w:date\": options.date, \"w:id\": options.id });\n return `<w:tblPrChange ${a}><w:tblPr>${inner}</w:tblPr></w:tblPrChange>`;\n}\n\n// ── Table properties (w:tblPr) ──\n\nfunction stringifyTablePropertiesInner(options: TablePropertiesOptions): string {\n const parts: string[] = [];\n\n if (options.style) {\n parts.push(`<w:tblStyle w:val=\"${options.style}\"/>`);\n }\n\n if (options.float) {\n parts.push(floatPropertiesStr(options.float));\n if (options.float.overlap) {\n parts.push(`<w:tblOverlap w:val=\"${options.float.overlap}\"/>`);\n }\n }\n\n if (options.visuallyRightToLeft !== undefined) {\n parts.push(onOff(\"w:bidiVisual\", options.visuallyRightToLeft));\n }\n\n if (options.styleRowBandSize !== undefined) {\n parts.push(`<w:tblStyleRowBandSize w:val=\"${options.styleRowBandSize}\"/>`);\n }\n\n if (options.styleColBandSize !== undefined) {\n parts.push(`<w:tblStyleColBandSize w:val=\"${options.styleColBandSize}\"/>`);\n }\n\n if (options.width) {\n parts.push(tableWidthStr(\"w:tblW\", options.width));\n }\n\n if (options.alignment) {\n parts.push(`<w:jc w:val=\"${options.alignment}\"/>`);\n }\n\n if (options.cellSpacing) {\n parts.push(cellSpacingStr(options.cellSpacing));\n }\n\n if (options.indent) {\n parts.push(tableWidthStr(\"w:tblInd\", options.indent));\n }\n\n if (options.borders) {\n const bs = tableBordersStr(options.borders);\n if (bs) parts.push(bs);\n }\n\n if (options.shading) {\n parts.push(shadingStr(options.shading));\n }\n\n if (options.layout) {\n parts.push(`<w:tblLayout w:type=\"${options.layout}\"/>`);\n }\n\n if (options.cellMargin) {\n const cm = cellMarginStr(\"w:tblCellMar\", options.cellMargin);\n if (cm) parts.push(cm);\n }\n\n if (options.tableLook) {\n parts.push(tableLookStr(options.tableLook));\n }\n\n if (options.caption !== undefined) {\n parts.push(`<w:tblCaption w:val=\"${options.caption}\"/>`);\n }\n\n if (options.description !== undefined) {\n parts.push(`<w:tblDescription w:val=\"${options.description}\"/>`);\n }\n\n if (options.revision) {\n parts.push(stringifyTablePropertiesChangeInner(options.revision));\n }\n\n return parts.join(\"\");\n}\n\nexport function stringifyTableProperties(options: TablePropertiesOptions): string | undefined {\n const inner = stringifyTablePropertiesInner(options);\n if (options.includeIfEmpty || inner) {\n return `<w:tblPr>${inner}</w:tblPr>`;\n }\n return undefined;\n}\n\n// ── Row properties change (w:trPrChange) ──\n\nfunction stringifyTableRowPropertiesChangeInner(options: TableRowPropertiesChangeOptions): string {\n const inner = stringifyTableRowPropertiesInner({ ...options, includeIfEmpty: true });\n const a = attrsRaw({ \"w:author\": options.author, \"w:date\": options.date, \"w:id\": options.id });\n return `<w:trPrChange ${a}><w:trPr>${inner}</w:trPr></w:trPrChange>`;\n}\n\n// ── Row properties (w:trPr) ──\n\nfunction stringifyTableRowPropertiesInner(options: TableRowPropertiesOptions): string {\n const parts: string[] = [];\n\n if (options.cnfStyle !== undefined) {\n parts.push(cnfStyleStr(options.cnfStyle));\n }\n\n if (options.divId !== undefined) {\n parts.push(`<w:divId w:val=\"${options.divId}\"/>`);\n }\n\n if (options.gridBefore !== undefined) {\n parts.push(`<w:gridBefore w:val=\"${options.gridBefore}\"/>`);\n }\n\n if (options.gridAfter !== undefined) {\n parts.push(`<w:gridAfter w:val=\"${options.gridAfter}\"/>`);\n }\n\n if (options.widthBefore) {\n parts.push(tableWidthStr(\"w:wBefore\", options.widthBefore));\n }\n\n if (options.widthAfter) {\n parts.push(tableWidthStr(\"w:wAfter\", options.widthAfter));\n }\n\n if (options.cantSplit !== undefined) {\n parts.push(onOff(\"w:cantSplit\", options.cantSplit));\n }\n\n if (options.tableHeader !== undefined) {\n parts.push(onOff(\"w:tblHeader\", options.tableHeader));\n }\n\n if (options.height) {\n const a = attrsRaw({\n \"w:val\": convertToTwip(options.height.value),\n \"w:hRule\": options.height.rule,\n });\n parts.push(`<w:trHeight${a}/>`);\n }\n\n if (options.cellSpacing) {\n parts.push(cellSpacingStr(options.cellSpacing));\n }\n\n if (options.rowAlignment) {\n parts.push(`<w:jc w:val=\"${options.rowAlignment}\"/>`);\n }\n\n if (options.hidden !== undefined) {\n parts.push(onOff(\"w:hidden\", options.hidden));\n }\n\n if (options.insertion) {\n parts.push(changeAttrStr(\"w:ins\", options.insertion));\n }\n\n if (options.deletion) {\n parts.push(changeAttrStr(\"w:del\", options.deletion));\n }\n\n if (options.revision) {\n parts.push(stringifyTableRowPropertiesChangeInner(options.revision));\n }\n\n return parts.join(\"\");\n}\n\nexport function stringifyTableRowProperties(\n options: TableRowPropertiesOptions,\n): string | undefined {\n const inner = stringifyTableRowPropertiesInner(options);\n if (options.includeIfEmpty || inner) {\n return `<w:trPr>${inner}</w:trPr>`;\n }\n return undefined;\n}\n\n// ── Cell properties change (w:tcPrChange) ──\n\nfunction stringifyTableCellPropertiesChangeInner(\n options: TableCellPropertiesChangeOptions,\n): string {\n const inner = stringifyTableCellPropertiesInner({ ...options, includeIfEmpty: true });\n const a = attrsRaw({ \"w:author\": options.author, \"w:date\": options.date, \"w:id\": options.id });\n return `<w:tcPrChange ${a}><w:tcPr>${inner}</w:tcPr></w:tcPrChange>`;\n}\n\n// ── Cell properties (w:tcPr) ──\n\nfunction stringifyTableCellPropertiesInner(options: TableCellPropertiesOptions): string {\n // CT_TcPrBase sequence: cnfStyle, tcW, gridSpan, hMerge, vMerge, tcBorders, shd,\n // noWrap, tcMar, textDirection, tcFitText, vAlign, hideMark, headers;\n // then EG_CellMarkupElements (cellIns/cellDel/cellMerge), then tcPrChange.\n const parts: string[] = [];\n\n if (options.cnfStyle !== undefined) {\n parts.push(cnfStyleStr(options.cnfStyle));\n }\n\n if (options.width) {\n parts.push(tableWidthStr(\"w:tcW\", options.width));\n }\n\n if (options.columnSpan) {\n parts.push(`<w:gridSpan w:val=\"${options.columnSpan}\"/>`);\n }\n\n if (options.horizontalMerge !== undefined) {\n if (options.horizontalMerge === \"restart\") {\n parts.push(`<w:hMerge w:val=\"restart\"/>`);\n } else {\n parts.push(`<w:hMerge/>`);\n }\n }\n\n if (options.verticalMerge) {\n parts.push(`<w:vMerge w:val=\"${options.verticalMerge}\"/>`);\n } else if (options.rowSpan && options.rowSpan > 1) {\n parts.push(`<w:vMerge w:val=\"${VerticalMergeType.RESTART}\"/>`);\n }\n\n if (options.borders) {\n const bs = cellBordersStr(options.borders);\n if (bs) parts.push(bs);\n }\n\n if (options.shading) {\n parts.push(shadingStr(options.shading));\n }\n\n if (options.noWrap !== undefined) {\n parts.push(onOff(\"w:noWrap\", options.noWrap));\n }\n\n if (options.margins) {\n const cm = cellMarginStr(\"w:tcMar\", options.margins);\n if (cm) parts.push(cm);\n }\n\n if (options.textDirection) {\n parts.push(`<w:textDirection w:val=\"${options.textDirection}\"/>`);\n }\n\n if (options.fitText !== undefined) {\n parts.push(onOff(\"w:tcFitText\", options.fitText));\n }\n\n if (options.verticalAlign) {\n parts.push(`<w:vAlign w:val=\"${options.verticalAlign}\"/>`);\n }\n\n if (options.hideMark !== undefined) {\n parts.push(onOff(\"w:hideMark\", options.hideMark));\n }\n\n if (options.headers !== undefined) {\n const headerParts = options.headers.map((h) => `<w:header w:val=\"${h}\"/>`).join(\"\");\n parts.push(`<w:headers>${headerParts}</w:headers>`);\n }\n\n if (options.insertion) {\n parts.push(changeAttrStr(\"w:cellIns\", options.insertion));\n }\n\n if (options.deletion) {\n parts.push(changeAttrStr(\"w:cellDel\", options.deletion));\n }\n\n if (options.cellMerge) {\n parts.push(cellMergeStr(options.cellMerge));\n }\n\n if (options.revision) {\n parts.push(stringifyTableCellPropertiesChangeInner(options.revision));\n }\n\n return parts.join(\"\");\n}\n\nexport function stringifyTableCellProperties(\n options: TableCellPropertiesOptions,\n): string | undefined {\n const inner = stringifyTableCellPropertiesInner(options);\n if (options.includeIfEmpty || inner) {\n return `<w:tcPr>${inner}</w:tcPr>`;\n }\n return undefined;\n}\n\n// ── Table property exceptions (w:tblPrEx) ──\n\nfunction stringifyTablePropertyExceptionsInner(options: TablePropertyExOptions): string {\n const parts: string[] = [];\n\n if (options.width) {\n parts.push(tableWidthStr(\"w:tblW\", options.width));\n }\n\n if (options.alignment) {\n parts.push(`<w:jc w:val=\"${options.alignment}\"/>`);\n }\n\n if (options.cellSpacing) {\n parts.push(cellSpacingStr(options.cellSpacing));\n }\n\n if (options.indent) {\n parts.push(tableWidthStr(\"w:tblInd\", options.indent));\n }\n\n if (options.borders) {\n const bs = tableBordersStr(options.borders);\n if (bs) parts.push(bs);\n }\n\n if (options.shading) {\n parts.push(shadingStr(options.shading));\n }\n\n if (options.layout) {\n parts.push(`<w:tblLayout w:type=\"${options.layout}\"/>`);\n }\n\n if (options.cellMargin) {\n const cm = cellMarginStr(\"w:tblCellMar\", options.cellMargin);\n if (cm) parts.push(cm);\n }\n\n if (options.tableLook) {\n parts.push(tableLookStr(options.tableLook));\n }\n\n if (options.tblPrExChange) {\n const change = options.tblPrExChange;\n const a = attrsRaw({ \"w:author\": change.author, \"w:date\": change.date, \"w:id\": change.id });\n // CT_TblPrExChange requires a tblPrEx child holding the previous (pre-change) values.\n const revInner = stringifyTablePropertyExceptionsInner(change);\n parts.push(`<w:tblPrExChange ${a}><w:tblPrEx>${revInner}</w:tblPrEx></w:tblPrExChange>`);\n }\n\n return parts.join(\"\");\n}\n\nexport function stringifyTablePropertyExceptions(options: TablePropertyExOptions): string {\n return `<w:tblPrEx>${stringifyTablePropertyExceptionsInner(options)}</w:tblPrEx>`;\n}\n","/**\n * Table (w:tbl) descriptor for DOCX.\n *\n * Stringifies pure JSON TableOptions into XML using direct string\n * concatenation — no intermediate object tree, no xml() pipeline.\n *\n * @module\n */\n\nimport { convertToTwip, ThemeColor } from \"@office-open/core\";\nimport { xsdVerticalMergeRev } from \"@office-open/core\";\nimport type { PositiveUniversalMeasure, UniversalMeasure } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrBool, attrMeasure, attrNum, children, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport {\n parseCustomXmlProperties,\n stringifyCustomXmlShell,\n stringifySdtShell,\n} from \"@parts/bodychildren\";\nimport type { CustomXmlCellOptions, CustomXmlRowOptions } from \"@parts/custom-xml\";\nimport { stringifyParagraphInline } from \"@parts/inline\";\nimport { parseRunProperties } from \"@parts/paragraph/run/run-parse\";\nimport { parseSdtProperties } from \"@parts/sdt/sdt-parse\";\nimport type { TableGridChangeOptions } from \"@parts/table/grid\";\nimport type { TableOptions } from \"@parts/table/table\";\nimport type { TableCellSpacingProperties } from \"@parts/table/table-cell-spacing\";\nimport type { SdtCellOptions, TableCellOptions } from \"@parts/table/table-cell/table-cell\";\nimport type { TableCellBordersOptions } from \"@parts/table/table-cell/table-cell-components\";\nimport { VerticalMergeType } from \"@parts/table/table-cell/table-cell-components\";\nimport type { TableBordersOptions } from \"@parts/table/table-properties/table-borders\";\nimport type { TableCellMarginOptions } from \"@parts/table/table-properties/table-cell-margin\";\nimport type { TableFloatOptions } from \"@parts/table/table-properties/table-float-properties\";\nimport type { TableLookOptions } from \"@parts/table/table-properties/table-look\";\nimport type {\n TablePropertyExChangeOptions,\n TablePropertyExOptions,\n} from \"@parts/table/table-properties/table-property-exceptions\";\nimport type { SdtRowOptions, TableRowOptions } from \"@parts/table/table-row/table-row\";\nimport type { CnfStyleOptions } from \"@parts/table/table-row/table-row-properties\";\nimport type { TableWidthProperties } from \"@parts/table/table-width\";\nimport { widthFiftiethsToPct } from \"@parts/table/table-width\";\nimport { BorderStyle } from \"@shared/border\";\nimport type { BorderOptions } from \"@shared/border\";\nimport type { SectionChild } from \"@shared/section\";\nimport { parseShading, type ShadingProperties } from \"@shared/shading\";\nimport type { CellMergeAttributes } from \"@shared/track-revision\";\nimport type { ChangedProperties } from \"@shared/track-revision/track-revision\";\n\nimport type { BodyContext, DocxReadContext } from \"../../context\";\nimport {\n stringifyTableCellProperties,\n stringifyTableProperties,\n stringifyTablePropertyExceptions,\n stringifyTableRowProperties,\n} from \"./stringify\";\nimport type {\n TableCellPropertiesChangeOptions,\n TableCellPropertiesOptions,\n} from \"./table-cell/table-cell-properties\";\nimport type {\n TablePropertiesChangeOptions,\n TablePropertiesOptions,\n} from \"./table-properties/table-properties\";\nimport type {\n TableRowPropertiesChangeOptions,\n TableRowPropertiesOptions,\n} from \"./table-row/table-row-properties\";\n\n// Valid border @w:val (ST_Border / BorderStyle) and @w:themeColor (ST_ThemeColor) values.\nconst BORDER_STYLES = Object.values(BorderStyle) as readonly string[];\nconst THEME_COLORS = Object.values(ThemeColor) as readonly string[];\n\n/** Parse track-change attributes (id/author/date) from w:ins/w:del/w:cellIns/w:cellDel. */\nfunction parseChangeAttrs(el: Element): Partial<ChangedProperties> {\n const change: Partial<ChangedProperties> = {};\n const id = attrNum(el, \"w:id\");\n if (id !== undefined) change.id = id;\n const author = attr(el, \"w:author\");\n if (author) change.author = author;\n const date = attr(el, \"w:date\");\n if (date) change.date = date;\n return change;\n}\n\n// ── Table grid ──\n\nfunction buildTableGridXml(\n widths: Array<number | string>,\n revision?: TableGridChangeOptions,\n): string {\n // w:gridCol @w is s:ST_TwipsMeasure — normalize UniversalMeasure to twip integers\n // so the emitted @w is always a bare integer (never \"25mm\").\n const gridCol = (w: number | string): string =>\n `<w:gridCol w:w=\"${convertToTwip(w as number | UniversalMeasure)}\"/>`;\n const cols = widths.map(gridCol).join(\"\");\n\n if (revision) {\n const revCols = revision.columnWidths.map(gridCol).join(\"\");\n return `<w:tblGrid>${cols}<w:tblGridChange w:id=\"${revision.id}\"><w:tblGrid>${revCols}</w:tblGrid></w:tblGridChange></w:tblGrid>`;\n }\n\n return `<w:tblGrid>${cols}</w:tblGrid>`;\n}\n\n// ── Cell span extraction ──\n\n/** Extract column/row span from a plain-object cell. */\nfunction getCellSpans(cell: TableCellOptions): {\n columnSpan: number;\n rowSpan: number;\n} {\n return { columnSpan: cell.columnSpan ?? 1, rowSpan: cell.rowSpan ?? 1 };\n}\n\n// ── Cell children stringification ──\n\n/**\n * Stringify a cell child (SectionChild) inline.\n * Handles strings and plain objects (paragraph/table).\n */\nfunction stringifyCellChild(child: SectionChild, ctx: BodyContext): string {\n if (typeof child === \"string\") {\n return stringifyParagraphInline(child, ctx);\n }\n\n // Plain object dispatch\n if (\"paragraph\" in child) {\n return stringifyParagraphInline(child.paragraph, ctx);\n }\n if (\"table\" in child) {\n // Recursive: nested table via descriptor\n return tableDesc.stringify(child.table, ctx) ?? \"\";\n }\n\n // Fallback for other types — should not happen inside table cells\n return \"\";\n}\n\n// ── Cell stringification ──\n\nfunction stringifyTableCell(cell: TableCellOptions, ctx: BodyContext): string {\n const parts: string[] = [];\n\n const tcPr = stringifyTableCellProperties(cell);\n if (tcPr) parts.push(tcPr);\n\n const children = cell.children as SectionChild[] | undefined;\n if (children) {\n for (const child of children) {\n parts.push(stringifyCellChild(child, ctx));\n }\n }\n\n // Cells must end with a paragraph unless the last child is already one\n const last = children?.[children.length - 1];\n const endsWithParagraph =\n last && typeof last !== \"string\" && (\"paragraph\" in last || \"table\" in last);\n if (!endsWithParagraph) {\n parts.push(\"<w:p/>\");\n }\n\n return `<w:tc>${parts.join(\"\")}</w:tc>`;\n}\n\n// ── Row stringification ──\n\nfunction stringifyTableRow(\n row: TableRowOptions,\n ctx: BodyContext,\n extraCells?: { cell: TableCellOptions; columnIndex: number }[],\n): string {\n const parts: string[] = [];\n\n // Property exceptions (tblPrEx)\n if (row.propertyExceptions) {\n parts.push(stringifyTablePropertyExceptions(row.propertyExceptions));\n }\n\n // Row properties\n const trPr = stringifyTableRowProperties(row);\n if (trPr) parts.push(trPr);\n\n const prefixCount = parts.length;\n\n // Cells (a cell may be wrapped by a cell-level SDT or customXml)\n for (const cell of row.cells) {\n if (\"sdt\" in cell) {\n const s = cell.sdt;\n const contentXml = (s.cells ?? []).map((c) => stringifyTableCell(c, ctx)).join(\"\");\n parts.push(stringifySdtShell(s.properties, s.endProperties, contentXml));\n } else if (\"customXml\" in cell) {\n const cx = cell.customXml;\n const contentXml = (cx.children ?? []).map((c) => stringifyTableCell(c, ctx)).join(\"\");\n parts.push(stringifyCustomXmlShell(cx, contentXml));\n } else {\n parts.push(stringifyTableCell(cell, ctx));\n }\n }\n\n // Insert extra CONTINUE cells at correct positions\n if (extraCells && extraCells.length > 0) {\n for (const { cell, columnIndex } of extraCells) {\n const insertIdx = findInsertIndex(row.cells, columnIndex, prefixCount);\n parts.splice(insertIdx, 0, stringifyTableCell(cell, ctx));\n }\n }\n\n // rsid attributes\n const rsidAttrs: string[] = [];\n if (row.runPropertiesRsid) rsidAttrs.push(` w:rsidRPr=\"${row.runPropertiesRsid}\"`);\n if (row.rsid) rsidAttrs.push(` w:rsidR=\"${row.rsid}\"`);\n if (row.deletionRsid) rsidAttrs.push(` w:rsidDel=\"${row.deletionRsid}\"`);\n if (row.tableRowRsid) rsidAttrs.push(` w:rsidTr=\"${row.tableRowRsid}\"`);\n const attr = rsidAttrs.join(\"\");\n\n const body = parts.join(\"\");\n return body ? `<w:tr${attr}>${body}</w:tr>` : attr ? `<w:tr${attr}/>` : \"<w:tr/>\";\n}\n\n// ── Row options type ──\n\n/** Type guard: a plain row (not SDT/customXml-wrapped). */\nfunction isPlainRow(\n r: TableRowOptions | { sdt: SdtRowOptions } | { customXml: CustomXmlRowOptions },\n): r is TableRowOptions {\n return !(\"sdt\" in r) && !(\"customXml\" in r);\n}\n\n/** Type guard: a plain cell (not SDT/customXml-wrapped). */\nfunction isPlainCell(\n c: TableCellOptions | { sdt: SdtCellOptions } | { customXml: CustomXmlCellOptions },\n): c is TableCellOptions {\n return !(\"sdt\" in c) && !(\"customXml\" in c);\n}\n\nfunction findInsertIndex(\n cells: TableRowOptions[\"cells\"],\n columnIndex: number,\n prefixCount: number,\n): number {\n let colIdx = 0;\n for (const [i, c] of cells.entries()) {\n if (!isPlainCell(c)) continue; // SDT/customXml-wrapped cells don't occupy grid columns\n const { columnSpan } = getCellSpans(c);\n colIdx += columnSpan;\n if (colIdx > columnIndex) {\n return i + prefixCount;\n }\n }\n return cells.length + prefixCount;\n}\n\n// ── Vertical merge ──\n\n/**\n * Pre-process rows to compute CONTINUE cells for vertical merge.\n */\nfunction computeVerticalMergeCells(\n rows: TableOptions[\"rows\"],\n): Map<number, { cell: TableCellOptions; columnIndex: number }[]> {\n const extraMap = new Map<number, { cell: TableCellOptions; columnIndex: number }[]>();\n for (let ri = 0; ri < rows.length - 1; ri++) {\n const row = rows[ri];\n if (!row || !isPlainRow(row)) continue; // SDT/customXml-wrapped rows don't participate in merge\n const cells = row.cells;\n let colIdx = 0;\n\n for (const cell of cells) {\n if (!isPlainCell(cell)) continue; // SDT/customXml-wrapped cells don't participate in merge\n const typedCell = cell;\n const { columnSpan, rowSpan } = getCellSpans(typedCell);\n\n if (rowSpan > 1) {\n const continueCell: TableCellOptions = {\n borders: typedCell.borders,\n children: [],\n columnSpan,\n rowSpan: rowSpan - 1,\n verticalMerge: VerticalMergeType.CONTINUE,\n };\n\n if (!extraMap.has(ri + 1)) {\n extraMap.set(ri + 1, []);\n }\n extraMap.get(ri + 1)!.push({ cell: continueCell, columnIndex: colIdx });\n }\n\n colIdx += columnSpan;\n }\n }\n\n return extraMap;\n}\n\n/** Parse a w:tblCellMar / w:tcMar container into TableCellMarginOptions. */\nfunction parseCellMargins(marginEl: Element): TableCellMarginOptions | undefined {\n const margins: TableCellMarginOptions = {};\n // CT_TblCellMar sides: top, start, left, bottom, end, right — each an\n // independent CT_TblWidth ({ size, type }). Parse faithfully: omit type\n // when the XML has none (stringify defaults it to DXA on the way back).\n for (const side of [\"top\", \"start\", \"left\", \"bottom\", \"end\", \"right\"] as const) {\n const sideEl = findChild(marginEl, `w:${side}`);\n if (sideEl) {\n const type = attr(sideEl, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(sideEl, \"w:w\"), type);\n if (size !== undefined) {\n margins[side] = (\n type ? { size, type: type as TableWidthProperties[\"type\"] } : { size }\n ) as TableWidthProperties;\n }\n }\n }\n if (Object.keys(margins).length === 0) return undefined;\n return margins as TableCellMarginOptions;\n}\n\n/** Parse a w:cnfStyle (CT_Cnf) element into CnfStyleOptions. */\nfunction parseCnfStyle(cnfEl: Element): CnfStyleOptions | undefined {\n const cnf: CnfStyleOptions = {};\n const val = attr(cnfEl, \"w:val\");\n if (val) cnf.val = val;\n const firstRow = attrBool(cnfEl, \"w:firstRow\");\n if (firstRow !== undefined) cnf.firstRow = firstRow;\n const lastRow = attrBool(cnfEl, \"w:lastRow\");\n if (lastRow !== undefined) cnf.lastRow = lastRow;\n const firstColumn = attrBool(cnfEl, \"w:firstColumn\");\n if (firstColumn !== undefined) cnf.firstColumn = firstColumn;\n const lastColumn = attrBool(cnfEl, \"w:lastColumn\");\n if (lastColumn !== undefined) cnf.lastColumn = lastColumn;\n const oddVBand = attrBool(cnfEl, \"w:oddVBand\");\n if (oddVBand !== undefined) cnf.oddVBand = oddVBand;\n const evenVBand = attrBool(cnfEl, \"w:evenVBand\");\n if (evenVBand !== undefined) cnf.evenVBand = evenVBand;\n const oddHBand = attrBool(cnfEl, \"w:oddHBand\");\n if (oddHBand !== undefined) cnf.oddHBand = oddHBand;\n const evenHBand = attrBool(cnfEl, \"w:evenHBand\");\n if (evenHBand !== undefined) cnf.evenHBand = evenHBand;\n const firstRowFirstColumn = attrBool(cnfEl, \"w:firstRowFirstColumn\");\n if (firstRowFirstColumn !== undefined) cnf.firstRowFirstColumn = firstRowFirstColumn;\n const firstRowLastColumn = attrBool(cnfEl, \"w:firstRowLastColumn\");\n if (firstRowLastColumn !== undefined) cnf.firstRowLastColumn = firstRowLastColumn;\n const lastRowFirstColumn = attrBool(cnfEl, \"w:lastRowFirstColumn\");\n if (lastRowFirstColumn !== undefined) cnf.lastRowFirstColumn = lastRowFirstColumn;\n const lastRowLastColumn = attrBool(cnfEl, \"w:lastRowLastColumn\");\n if (lastRowLastColumn !== undefined) cnf.lastRowLastColumn = lastRowLastColumn;\n if (Object.keys(cnf).length === 0) return undefined;\n return cnf as CnfStyleOptions;\n}\n\n/**\n * Parse a w:tblPrEx (CT_TblPrEx) element into TablePropertyExOptions.\n * CT_TblPrExBase shares its child elements with CT_TblPrBase, so this reuses\n * parseTablePropertiesEl and maps the table-level margins field to cellMargin.\n */\nfunction parseTablePropertyExceptions(el: Element): TablePropertyExOptions {\n const base = parseTablePropertiesEl(el);\n const opts: TablePropertyExOptions = {};\n if (base.width !== undefined) opts.width = base.width as TableWidthProperties;\n if (base.indent !== undefined) opts.indent = base.indent as TableWidthProperties;\n if (base.layout !== undefined) opts.layout = base.layout as TablePropertyExOptions[\"layout\"];\n if (base.borders !== undefined) opts.borders = base.borders as TableBordersOptions;\n if (base.shading !== undefined) opts.shading = base.shading as ShadingProperties;\n if (base.alignment !== undefined) {\n opts.alignment = base.alignment as TablePropertyExOptions[\"alignment\"];\n }\n if (base.cellMargin !== undefined) opts.cellMargin = base.cellMargin;\n if (base.tableLook !== undefined) opts.tableLook = base.tableLook as TableLookOptions;\n if (base.cellSpacing !== undefined) {\n opts.cellSpacing = base.cellSpacing as TableCellSpacingProperties;\n }\n const tblPrExChange = findChild(el, \"w:tblPrExChange\");\n if (tblPrExChange) {\n const change = parseTablePropertyExChange(tblPrExChange);\n if (change) opts.tblPrExChange = change;\n }\n return opts as TablePropertyExOptions;\n}\n\n/** Parse a w:tblPrExChange (CT_TblPrExChange) — track-change wrapper around the previous tblPrEx. */\nfunction parseTablePropertyExChange(el: Element): TablePropertyExChangeOptions | undefined {\n const change: Partial<TablePropertyExChangeOptions> = {};\n const id = attrNum(el, \"w:id\");\n if (id !== undefined) change.id = id;\n const author = attr(el, \"w:author\");\n if (author) change.author = author;\n const date = attr(el, \"w:date\");\n if (date) change.date = date;\n const innerTblPrEx = findChild(el, \"w:tblPrEx\");\n if (innerTblPrEx) {\n const inner = parseTablePropertyExceptions(innerTblPrEx);\n if (inner.width !== undefined) change.width = inner.width;\n if (inner.indent !== undefined) change.indent = inner.indent;\n if (inner.layout !== undefined) change.layout = inner.layout;\n if (inner.borders !== undefined) change.borders = inner.borders;\n if (inner.shading !== undefined) change.shading = inner.shading;\n if (inner.alignment !== undefined) change.alignment = inner.alignment;\n if (inner.cellMargin !== undefined) change.cellMargin = inner.cellMargin;\n if (inner.tableLook !== undefined) change.tableLook = inner.tableLook;\n if (inner.cellSpacing !== undefined) change.cellSpacing = inner.cellSpacing;\n }\n if (change.id === undefined || change.author === undefined) return undefined;\n return change as TablePropertyExChangeOptions;\n}\n\n/** Map base 6-flags to docx TableLookOptions for w:tblLook emit.\n * firstRow/lastRow pass through; firstCol→firstColumn, lastCol→lastColumn;\n * bandRow→!noHBand, bandCol→!noVBand (banding is inverted in w:tblLook). */\nfunction tableLookFromFlags(opts: TableOptions): TableLookOptions | undefined {\n const has =\n opts.firstRow !== undefined ||\n opts.lastRow !== undefined ||\n opts.firstCol !== undefined ||\n opts.lastCol !== undefined ||\n opts.bandRow !== undefined ||\n opts.bandCol !== undefined;\n if (!has) return undefined;\n const look: TableLookOptions = {};\n if (opts.firstRow !== undefined) look.firstRow = opts.firstRow;\n if (opts.lastRow !== undefined) look.lastRow = opts.lastRow;\n if (opts.firstCol !== undefined) look.firstColumn = opts.firstCol;\n if (opts.lastCol !== undefined) look.lastColumn = opts.lastCol;\n if (opts.bandRow !== undefined) look.noHBand = !opts.bandRow;\n if (opts.bandCol !== undefined) look.noVBand = !opts.bandCol;\n return look;\n}\n\n// ── Descriptor ──\n\nexport const tableDesc: CustomDescriptor<TableOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const parts: string[] = [];\n\n // Table properties\n // tblPr is required in CT_Tbl (minOccurs defaults to 1) — always emit it,\n // even when empty; do not inject optional defaults (width/borders are XSD-optional).\n const tblPrOpts: TablePropertiesOptions = {\n alignment: opts.alignment,\n borders: opts.borders,\n caption: opts.caption,\n cellMargin: opts.margins,\n cellSpacing: opts.cellSpacing,\n description: opts.description,\n float: opts.float,\n indent: opts.indent,\n layout: opts.layout,\n revision: opts.revision,\n shading: opts.shading,\n style: opts.style,\n styleColBandSize: opts.styleColBandSize,\n styleRowBandSize: opts.styleRowBandSize,\n tableLook: tableLookFromFlags(opts),\n visuallyRightToLeft: opts.visuallyRightToLeft,\n width: opts.width,\n includeIfEmpty: true,\n };\n parts.push(stringifyTableProperties(tblPrOpts)!);\n\n // Table grid\n const columnWidths =\n opts.columnWidths ??\n Array(Math.max(1, ...opts.rows.map((r) => (isPlainRow(r) ? r.cells.length : 0)))).fill(100);\n parts.push(buildTableGridXml(columnWidths, opts.columnWidthsRevision));\n\n // Compute vertical merge CONTINUE cells\n const extraCells = computeVerticalMergeCells(opts.rows);\n\n // Rows (a row may be wrapped by a row-level SDT)\n for (const [ri, r] of opts.rows.entries()) {\n if (\"sdt\" in r) {\n const sdt = r.sdt;\n const contentXml = (sdt.rows ?? []).map((rr) => stringifyTableRow(rr, ctx)).join(\"\");\n parts.push(stringifySdtShell(sdt.properties, sdt.endProperties, contentXml));\n } else if (\"customXml\" in r) {\n const cx = r.customXml;\n const contentXml = (cx.children ?? []).map((rr) => stringifyTableRow(rr, ctx)).join(\"\");\n parts.push(stringifyCustomXmlShell(cx, contentXml));\n } else {\n const extras = extraCells.get(ri);\n parts.push(stringifyTableRow(r, ctx, extras));\n }\n }\n\n return `<w:tbl>${parts.join(\"\")}</w:tbl>`;\n },\n\n parse(el, ctx) {\n return parseTableEl(el, ctx as DocxReadContext);\n },\n};\n\n// ── Parse (Element → TableOptions) ──\n\ntype ParseChildFn = (el: Element, ctx: DocxReadContext) => SectionChild;\n\n/** Callback used by table parser to parse body children. */\nlet _parseChild: ParseChildFn | undefined;\n\n/** Set the child parser callback (called from parseBody). */\nexport function setTableParseChild(fn: ParseChildFn): void {\n _parseChild = fn;\n}\n\nexport function parseTablePropertiesEl(el: Element): TablePropertiesOptions {\n const opts: TablePropertiesOptions = {};\n\n const style = findChild(el, \"w:tblStyle\");\n if (style) {\n const val = attr(style, \"w:val\");\n if (val) opts.style = val;\n }\n\n const tblW = findChild(el, \"w:tblW\");\n if (tblW) {\n const type = attr(tblW, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(tblW, \"w:w\"), type);\n if (size !== undefined || type) {\n opts.width = { size: size ?? 0, ...(type ? { type } : {}) } as TableWidthProperties;\n }\n }\n\n const jc = findChild(el, \"w:jc\");\n if (jc) {\n const val = attr(jc, \"w:val\");\n if (val) opts.alignment = val as TablePropertiesOptions[\"alignment\"];\n }\n\n const layout = findChild(el, \"w:tblLayout\");\n if (layout) {\n const val = attr(layout, \"w:type\");\n if (val === \"autofit\" || val === \"fixed\") opts.layout = val;\n }\n\n const tblBorders = findChild(el, \"w:tblBorders\");\n if (tblBorders) {\n // XML side names → TableBordersOptions keys (insideH/insideV map to\n // insideHorizontal/insideVertical); all 6 sides are CT_TblBorders-optional.\n const SIDE_KEYS: ReadonlyArray<[string, keyof TableBordersOptions]> = [\n [\"top\", \"top\"],\n [\"left\", \"left\"],\n [\"bottom\", \"bottom\"],\n [\"right\", \"right\"],\n [\"insideH\", \"insideHorizontal\"],\n [\"insideV\", \"insideVertical\"],\n ];\n const borders: TableBordersOptions = {};\n for (const [xmlSide, key] of SIDE_KEYS) {\n const sideEl = findChild(tblBorders, `w:${xmlSide}`);\n if (!sideEl) continue;\n // CT_Border requires w:val (style); skip malformed sides\n const style = attr(sideEl, \"w:val\");\n if (!style || !BORDER_STYLES.includes(style)) continue;\n const sideOpts: BorderOptions = { style: style as BorderOptions[\"style\"] };\n const color = attr(sideEl, \"w:color\");\n if (color) sideOpts.color = color;\n const size = attrNum(sideEl, \"w:sz\");\n if (size !== undefined) sideOpts.size = size;\n const space = attrNum(sideEl, \"w:space\");\n if (space !== undefined) sideOpts.space = space;\n const themeColor = attr(sideEl, \"w:themeColor\");\n if (themeColor && THEME_COLORS.includes(themeColor)) {\n sideOpts.themeColor = themeColor as BorderOptions[\"themeColor\"];\n }\n const themeTint = attr(sideEl, \"w:themeTint\");\n if (themeTint) sideOpts.themeTint = themeTint;\n const themeShade = attr(sideEl, \"w:themeShade\");\n if (themeShade) sideOpts.themeShade = themeShade;\n const shadow = attrBool(sideEl, \"w:shadow\");\n if (shadow !== undefined) sideOpts.shadow = shadow;\n const frame = attrBool(sideEl, \"w:frame\");\n if (frame !== undefined) sideOpts.frame = frame;\n borders[key] = sideOpts;\n }\n if (Object.keys(borders).length > 0) opts.borders = borders;\n }\n\n const tblCellMar = findChild(el, \"w:tblCellMar\");\n if (tblCellMar) {\n const margins = parseCellMargins(tblCellMar);\n if (margins) opts.cellMargin = margins;\n }\n\n const shd = findChild(el, \"w:shd\");\n if (shd) {\n const shading = parseShading(shd);\n if (shading) opts.shading = shading;\n }\n\n // description → w:tblDescription/@w:val\n const tblDesc = findChild(el, \"w:tblDescription\");\n if (tblDesc) {\n const val = attr(tblDesc, \"w:val\");\n if (val) opts.description = val;\n }\n\n // float → w:tblpPr attributes + w:tblOverlap (sibling element in CT_TblPrBase)\n const tblpPr = findChild(el, \"w:tblpPr\");\n const tblOverlap = findChild(el, \"w:tblOverlap\");\n if (tblpPr || tblOverlap) {\n const floatOpts: Partial<TableFloatOptions> = {};\n if (tblpPr) {\n const horzAnchor = attr(tblpPr, \"w:horzAnchor\");\n if (horzAnchor)\n floatOpts.horizontalAnchor = horzAnchor as TableFloatOptions[\"horizontalAnchor\"];\n const vertAnchor = attr(tblpPr, \"w:vertAnchor\");\n if (vertAnchor) floatOpts.verticalAnchor = vertAnchor as TableFloatOptions[\"verticalAnchor\"];\n const tblpX = attrNum(tblpPr, \"w:tblpX\");\n if (tblpX !== undefined) floatOpts.absoluteHorizontalPosition = tblpX;\n const tblpXSpec = attr(tblpPr, \"w:tblpXSpec\");\n if (tblpXSpec)\n floatOpts.relativeHorizontalPosition =\n tblpXSpec as TableFloatOptions[\"relativeHorizontalPosition\"];\n const tblpY = attrNum(tblpPr, \"w:tblpY\");\n if (tblpY !== undefined) floatOpts.absoluteVerticalPosition = tblpY;\n const tblpYSpec = attr(tblpPr, \"w:tblpYSpec\");\n if (tblpYSpec)\n floatOpts.relativeVerticalPosition =\n tblpYSpec as TableFloatOptions[\"relativeVerticalPosition\"];\n const bottomFromText = attrNum(tblpPr, \"w:bottomFromText\");\n if (bottomFromText !== undefined) floatOpts.bottomFromText = bottomFromText;\n const topFromText = attrNum(tblpPr, \"w:topFromText\");\n if (topFromText !== undefined) floatOpts.topFromText = topFromText;\n const leftFromText = attrNum(tblpPr, \"w:leftFromText\");\n if (leftFromText !== undefined) floatOpts.leftFromText = leftFromText;\n const rightFromText = attrNum(tblpPr, \"w:rightFromText\");\n if (rightFromText !== undefined) floatOpts.rightFromText = rightFromText;\n }\n if (tblOverlap) {\n const overlap = attr(tblOverlap, \"w:val\");\n if (overlap) floatOpts.overlap = overlap as TableFloatOptions[\"overlap\"];\n }\n if (Object.keys(floatOpts).length > 0) opts.float = floatOpts as TableFloatOptions;\n }\n\n // indent → w:tblInd/@w:w and @w:type\n const tblInd = findChild(el, \"w:tblInd\");\n if (tblInd) {\n const type = attr(tblInd, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(tblInd, \"w:w\"), type);\n if (size !== undefined) {\n opts.indent = { size, ...(type ? { type } : {}) } as TableWidthProperties;\n }\n }\n\n // visuallyRightToLeft → w:bidiVisual\n const bidiVisual = findChild(el, \"w:bidiVisual\");\n if (bidiVisual) opts.visuallyRightToLeft = attrBool(bidiVisual, \"w:val\") ?? true;\n\n // styleRowBandSize / styleColBandSize\n const tblStyleRowBandSize = findChild(el, \"w:tblStyleRowBandSize\");\n if (tblStyleRowBandSize) {\n const val = attrNum(tblStyleRowBandSize, \"w:val\");\n if (val !== undefined) opts.styleRowBandSize = val;\n }\n const tblStyleColBandSize = findChild(el, \"w:tblStyleColBandSize\");\n if (tblStyleColBandSize) {\n const val = attrNum(tblStyleColBandSize, \"w:val\");\n if (val !== undefined) opts.styleColBandSize = val;\n }\n\n // caption → w:tblCaption/@w:val\n const tblCaption = findChild(el, \"w:tblCaption\");\n if (tblCaption) {\n const val = attr(tblCaption, \"w:val\");\n if (val) opts.caption = val;\n }\n\n // cellSpacing → w:tblCellSpacing\n const tblCellSpacing = findChild(el, \"w:tblCellSpacing\");\n if (tblCellSpacing) {\n const type = attr(tblCellSpacing, \"w:type\");\n const w = widthFiftiethsToPct(attrMeasure(tblCellSpacing, \"w:w\"), type);\n if (w !== undefined)\n opts.cellSpacing = { size: w, ...(type ? { type } : {}) } as TableCellSpacingProperties;\n }\n\n // Revision (w:tblPrChange)\n const tblPrChange = findChild(el, \"w:tblPrChange\");\n if (tblPrChange) {\n const rev: Partial<TablePropertiesChangeOptions> = {};\n const author = attr(tblPrChange, \"w:author\");\n if (author) rev.author = author;\n const date = attr(tblPrChange, \"w:date\");\n if (date) rev.date = date;\n const id = attrNum(tblPrChange, \"w:id\");\n if (id !== undefined) rev.id = id;\n const innerTblPr = findChild(tblPrChange, \"w:tblPr\");\n if (innerTblPr) {\n Object.assign(rev, parseTablePropertiesEl(innerTblPr));\n }\n if (Object.keys(rev).length > 0) opts.revision = rev as TablePropertiesChangeOptions;\n }\n\n // tblLook — conditional formatting flags (CT_TblLook)\n const tblLook = findChild(el, \"w:tblLook\");\n if (tblLook) {\n const look: TableLookOptions = {};\n const firstRow = attrBool(tblLook, \"w:firstRow\");\n if (firstRow !== undefined) look.firstRow = firstRow;\n const lastRow = attrBool(tblLook, \"w:lastRow\");\n if (lastRow !== undefined) look.lastRow = lastRow;\n const firstColumn = attrBool(tblLook, \"w:firstColumn\");\n if (firstColumn !== undefined) look.firstColumn = firstColumn;\n const lastColumn = attrBool(tblLook, \"w:lastColumn\");\n if (lastColumn !== undefined) look.lastColumn = lastColumn;\n const noHBand = attrBool(tblLook, \"w:noHBand\");\n if (noHBand !== undefined) look.noHBand = noHBand;\n const noVBand = attrBool(tblLook, \"w:noVBand\");\n if (noVBand !== undefined) look.noVBand = noVBand;\n if (Object.keys(look).length > 0) opts.tableLook = look;\n }\n\n return opts;\n}\n\nfunction parseColumnWidthsEl(el: Element): {\n widths: Array<number | string>;\n revision?: TableGridChangeOptions;\n} {\n const widths: Array<number | string> = [];\n const tblGrid = findChild(el, \"w:tblGrid\");\n if (!tblGrid) return { widths };\n\n for (const col of children(tblGrid, \"w:gridCol\")) {\n const w = attrMeasure(col, \"w:w\");\n widths.push(w ?? 100);\n }\n\n // CT_TblGrid may carry a tblGridChange (CT_TblGridChange = CT_Markup + tblGrid).\n const tblGridChange = findChild(tblGrid, \"w:tblGridChange\");\n if (tblGridChange) {\n const id = attrNum(tblGridChange, \"w:id\");\n const innerGrid = findChild(tblGridChange, \"w:tblGrid\");\n const revWidths: Array<number | string> = [];\n if (innerGrid) {\n for (const col of children(innerGrid, \"w:gridCol\")) {\n const w = attrMeasure(col, \"w:w\");\n revWidths.push(w ?? 100);\n }\n }\n if (id !== undefined) {\n return {\n widths,\n revision: { id, columnWidths: revWidths as number[] | PositiveUniversalMeasure[] },\n };\n }\n }\n\n return { widths };\n}\n\nexport function parseTableRowPropertiesEl(el: Element): TableRowPropertiesOptions {\n const opts: TableRowPropertiesOptions = {};\n\n const trHeight = findChild(el, \"w:trHeight\");\n if (trHeight) {\n const val = attrMeasure(trHeight, \"w:val\");\n const rule = attr(trHeight, \"w:hRule\");\n if (val !== undefined) {\n opts.height = { value: val, ...(rule ? { rule } : {}) } as NonNullable<\n TableRowPropertiesOptions[\"height\"]\n >;\n }\n }\n\n // cnfStyle → w:cnfStyle (CT_Cnf)\n const cnfStyle = findChild(el, \"w:cnfStyle\");\n if (cnfStyle) {\n const cnf = parseCnfStyle(cnfStyle);\n if (cnf) opts.cnfStyle = cnf;\n }\n\n // divId → w:divId/@w:val\n const divId = findChild(el, \"w:divId\");\n if (divId) {\n const val = attrNum(divId, \"w:val\");\n if (val !== undefined) opts.divId = val;\n }\n\n // gridBefore / gridAfter\n const gridBefore = findChild(el, \"w:gridBefore\");\n if (gridBefore) {\n const val = attrNum(gridBefore, \"w:val\");\n if (val !== undefined) opts.gridBefore = val;\n }\n const gridAfter = findChild(el, \"w:gridAfter\");\n if (gridAfter) {\n const val = attrNum(gridAfter, \"w:val\");\n if (val !== undefined) opts.gridAfter = val;\n }\n\n // wBefore / wAfter → widthBefore / widthAfter\n const wBefore = findChild(el, \"w:wBefore\");\n if (wBefore) {\n const type = attr(wBefore, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(wBefore, \"w:w\"), type);\n if (size !== undefined)\n opts.widthBefore = { size, ...(type ? { type } : {}) } as TableWidthProperties;\n }\n const wAfter = findChild(el, \"w:wAfter\");\n if (wAfter) {\n const type = attr(wAfter, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(wAfter, \"w:w\"), type);\n if (size !== undefined)\n opts.widthAfter = { size, ...(type ? { type } : {}) } as TableWidthProperties;\n }\n\n // rowAlignment → w:jc/@w:val\n const jc = findChild(el, \"w:jc\");\n if (jc) {\n const val = attr(jc, \"w:val\");\n if (val) opts.rowAlignment = val as TableRowPropertiesOptions[\"rowAlignment\"];\n }\n\n // hidden → w:hidden\n const hidden = findChild(el, \"w:hidden\");\n if (hidden) opts.hidden = attrBool(hidden, \"w:val\") ?? true;\n\n // cellSpacing → w:tblCellSpacing\n const tblCellSpacing = findChild(el, \"w:tblCellSpacing\");\n if (tblCellSpacing) {\n const type = attr(tblCellSpacing, \"w:type\");\n const w = widthFiftiethsToPct(attrMeasure(tblCellSpacing, \"w:w\"), type);\n if (w !== undefined)\n opts.cellSpacing = { size: w, ...(type ? { type } : {}) } as TableCellSpacingProperties;\n }\n\n // insertion / deletion (track changes)\n const ins = findChild(el, \"w:ins\");\n if (ins) opts.insertion = parseChangeAttrs(ins) as ChangedProperties;\n const del = findChild(el, \"w:del\");\n if (del) opts.deletion = parseChangeAttrs(del) as ChangedProperties;\n\n // Revision (w:trPrChange)\n const trPrChange = findChild(el, \"w:trPrChange\");\n if (trPrChange) {\n const rev: Partial<TableRowPropertiesChangeOptions> = {};\n const author = attr(trPrChange, \"w:author\");\n if (author) rev.author = author;\n const date = attr(trPrChange, \"w:date\");\n if (date) rev.date = date;\n const id = attrNum(trPrChange, \"w:id\");\n if (id !== undefined) rev.id = id;\n const innerTrPr = findChild(trPrChange, \"w:trPr\");\n if (innerTrPr) {\n Object.assign(rev, parseTableRowPropertiesEl(innerTrPr));\n }\n if (Object.keys(rev).length > 0) opts.revision = rev as TableRowPropertiesChangeOptions;\n }\n\n const tblHeader = findChild(el, \"w:tblHeader\");\n if (tblHeader) {\n opts.tableHeader = attrBool(tblHeader, \"w:val\") ?? true;\n }\n\n const cantSplit = findChild(el, \"w:cantSplit\");\n if (cantSplit) {\n opts.cantSplit = attrBool(cantSplit, \"w:val\") ?? true;\n }\n\n return opts;\n}\n\nexport function parseTableCellPropertiesEl(el: Element): TableCellPropertiesOptions {\n const opts: TableCellPropertiesOptions = {};\n\n const cnfStyle = findChild(el, \"w:cnfStyle\");\n if (cnfStyle) {\n const cnf = parseCnfStyle(cnfStyle);\n if (cnf) opts.cnfStyle = cnf;\n }\n\n const tcW = findChild(el, \"w:tcW\");\n if (tcW) {\n const type = attr(tcW, \"w:type\");\n const size = widthFiftiethsToPct(attrMeasure(tcW, \"w:w\"), type);\n if (size !== undefined) {\n opts.width = { size, ...(type ? { type } : {}) } as TableWidthProperties;\n }\n }\n\n const gridSpan = findChild(el, \"w:gridSpan\");\n if (gridSpan) {\n const val = attrNum(gridSpan, \"w:val\");\n if (val !== undefined) opts.columnSpan = val;\n }\n\n const vMerge = findChild(el, \"w:vMerge\");\n if (vMerge) {\n const val = attr(vMerge, \"w:val\");\n opts.verticalMerge = val === \"restart\" ? \"restart\" : \"continue\";\n }\n\n const vAlign = findChild(el, \"w:vAlign\");\n if (vAlign) {\n const val = attr(vAlign, \"w:val\");\n if (val) opts.verticalAlign = val as TableCellPropertiesOptions[\"verticalAlign\"];\n }\n\n const shd = findChild(el, \"w:shd\");\n if (shd) {\n const shading = parseShading(shd);\n if (shading) opts.shading = shading;\n }\n\n const tcBorders = findChild(el, \"w:tcBorders\");\n if (tcBorders) {\n // XML side name → TableCellBordersOptions key (incl. start/end + diagonals);\n // all sides are CT_TcBorders-optional. Mirrors table-level borders parse.\n const SIDE_KEYS: ReadonlyArray<[string, keyof TableCellBordersOptions]> = [\n [\"top\", \"top\"],\n [\"start\", \"start\"],\n [\"left\", \"left\"],\n [\"bottom\", \"bottom\"],\n [\"end\", \"end\"],\n [\"right\", \"right\"],\n [\"insideH\", \"insideHorizontal\"],\n [\"insideV\", \"insideVertical\"],\n [\"tl2br\", \"topLeftToBottomRight\"],\n [\"tr2bl\", \"topRightToBottomLeft\"],\n ];\n const borders: TableCellBordersOptions = {};\n for (const [xmlSide, key] of SIDE_KEYS) {\n const sideEl = findChild(tcBorders, `w:${xmlSide}`);\n if (!sideEl) continue;\n // CT_Border requires w:val (style); skip malformed sides\n const style = attr(sideEl, \"w:val\");\n if (!style || !BORDER_STYLES.includes(style)) continue;\n const sideOpts: BorderOptions = { style: style as BorderOptions[\"style\"] };\n const color = attr(sideEl, \"w:color\");\n if (color) sideOpts.color = color;\n const size = attrNum(sideEl, \"w:sz\");\n if (size !== undefined) sideOpts.size = size;\n const space = attrNum(sideEl, \"w:space\");\n if (space !== undefined) sideOpts.space = space;\n const themeColor = attr(sideEl, \"w:themeColor\");\n if (themeColor && THEME_COLORS.includes(themeColor)) {\n sideOpts.themeColor = themeColor as BorderOptions[\"themeColor\"];\n }\n const themeTint = attr(sideEl, \"w:themeTint\");\n if (themeTint) sideOpts.themeTint = themeTint;\n const themeShade = attr(sideEl, \"w:themeShade\");\n if (themeShade) sideOpts.themeShade = themeShade;\n const shadow = attrBool(sideEl, \"w:shadow\");\n if (shadow !== undefined) sideOpts.shadow = shadow;\n const frame = attrBool(sideEl, \"w:frame\");\n if (frame !== undefined) sideOpts.frame = frame;\n borders[key] = sideOpts;\n }\n if (Object.keys(borders).length > 0) opts.borders = borders;\n }\n\n const noWrap = findChild(el, \"w:noWrap\");\n if (noWrap) opts.noWrap = attrBool(noWrap, \"w:val\") ?? true;\n\n const tcMar = findChild(el, \"w:tcMar\");\n if (tcMar) {\n const margins = parseCellMargins(tcMar);\n if (margins) opts.margins = margins;\n }\n\n const textDirection = findChild(el, \"w:textDirection\");\n if (textDirection) {\n const val = attr(textDirection, \"w:val\");\n if (val) opts.textDirection = val as TableCellPropertiesOptions[\"textDirection\"];\n }\n\n // horizontalMerge → w:hMerge\n const hMerge = findChild(el, \"w:hMerge\");\n if (hMerge) {\n const val = attr(hMerge, \"w:val\");\n opts.horizontalMerge = val === \"restart\" ? \"restart\" : \"continue\";\n }\n\n // fitText → w:tcFitText\n const tcFitText = findChild(el, \"w:tcFitText\");\n if (tcFitText) opts.fitText = attrBool(tcFitText, \"w:val\") ?? true;\n\n // hideMark → w:hideMark\n const hideMark = findChild(el, \"w:hideMark\");\n if (hideMark) opts.hideMark = attrBool(hideMark, \"w:val\") ?? true;\n\n // headers → w:headers/w:header\n const headersEl = findChild(el, \"w:headers\");\n if (headersEl) {\n const headerVals: string[] = [];\n for (const h of headersEl.elements ?? []) {\n if (h.name !== \"w:header\") continue;\n const val = attr(h, \"w:val\");\n if (val) headerVals.push(val);\n }\n if (headerVals.length > 0) opts.headers = headerVals;\n }\n\n // insertion / deletion (track changes)\n const cellIns = findChild(el, \"w:cellIns\");\n if (cellIns) opts.insertion = parseChangeAttrs(cellIns) as ChangedProperties;\n const cellDel = findChild(el, \"w:cellDel\");\n if (cellDel) opts.deletion = parseChangeAttrs(cellDel) as ChangedProperties;\n\n // Revision (w:tcPrChange)\n const tcPrChange = findChild(el, \"w:tcPrChange\");\n if (tcPrChange) {\n const rev: Partial<TableCellPropertiesChangeOptions> = {};\n const author = attr(tcPrChange, \"w:author\");\n if (author) rev.author = author;\n const date = attr(tcPrChange, \"w:date\");\n if (date) rev.date = date;\n const id = attrNum(tcPrChange, \"w:id\");\n if (id !== undefined) rev.id = id;\n const innerTcPr = findChild(tcPrChange, \"w:tcPr\");\n if (innerTcPr) {\n Object.assign(rev, parseTableCellPropertiesEl(innerTcPr));\n }\n if (Object.keys(rev).length > 0) opts.revision = rev as TableCellPropertiesChangeOptions;\n }\n\n // cellMerge → w:cellMerge\n const cellMerge = findChild(el, \"w:cellMerge\");\n if (cellMerge) {\n const cm = parseChangeAttrs(cellMerge) as Partial<CellMergeAttributes>;\n const vMerge = attr(cellMerge, \"w:vMerge\");\n if (vMerge) cm.verticalMerge = xsdVerticalMergeRev.from(vMerge) as \"continue\" | \"restart\";\n const vMergeOrig = attr(cellMerge, \"w:vMergeOrig\");\n if (vMergeOrig) {\n cm.verticalMergeOriginal = xsdVerticalMergeRev.from(vMergeOrig) as \"continue\" | \"restart\";\n }\n if (Object.keys(cm).length > 0) opts.cellMerge = cm as CellMergeAttributes;\n }\n\n return opts;\n}\n\nfunction parseTableCellEl(el: Element, ctx: DocxReadContext): TableCellOptions {\n const opts: Partial<TableCellOptions> = {};\n\n const tcPr = findChild(el, \"w:tcPr\");\n if (tcPr) {\n Object.assign(opts, parseTableCellPropertiesEl(tcPr));\n }\n\n const childElements: SectionChild[] = [];\n for (const child of el.elements ?? []) {\n switch (child.name) {\n case \"w:tcPr\":\n break;\n case \"w:p\":\n case \"w:tbl\":\n if (_parseChild) childElements.push(_parseChild(child, ctx));\n break;\n default:\n break;\n }\n }\n\n opts.children = childElements;\n return opts as TableCellOptions;\n}\n\nfunction parseTableRowEl(el: Element, ctx: DocxReadContext): TableRowOptions {\n const opts: Partial<TableRowOptions> = {};\n\n const trPr = findChild(el, \"w:trPr\");\n if (trPr) {\n Object.assign(opts, parseTableRowPropertiesEl(trPr));\n }\n\n // w:tblPrEx (CT_TblPrEx) — per-row table-property exceptions\n const tblPrEx = findChild(el, \"w:tblPrEx\");\n if (tblPrEx) {\n const exceptions = parseTablePropertyExceptions(tblPrEx);\n if (Object.keys(exceptions).length > 0) opts.propertyExceptions = exceptions;\n }\n\n // rsid attributes on w:tr element\n for (const [attrName, optKey] of [\n [\"w:rsidRPr\", \"runPropertiesRsid\"],\n [\"w:rsidR\", \"rsid\"],\n [\"w:rsidDel\", \"deletionRsid\"],\n [\"w:rsidTr\", \"tableRowRsid\"],\n ] as const) {\n const val = attr(el, attrName);\n if (val) opts[optKey] = val;\n }\n\n const childCells: (\n | TableCellOptions\n | { sdt: SdtCellOptions }\n | { customXml: CustomXmlCellOptions }\n )[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:tc\") {\n childCells.push(parseTableCellEl(child, ctx));\n } else if (child.name === \"w:sdt\") {\n const sdtPr = findChild(child, \"w:sdtPr\");\n const properties = sdtPr ? parseSdtProperties(sdtPr) : {};\n const sdtEndPr = findChild(child, \"w:sdtEndPr\");\n const endProperties = sdtEndPr ? parseRunProperties(sdtEndPr) : undefined;\n const sdtContent = findChild(child, \"w:sdtContent\");\n const sdtCells: TableCellOptions[] = [];\n if (sdtContent) {\n for (const sub of sdtContent.elements ?? []) {\n if (sub.name === \"w:tc\") sdtCells.push(parseTableCellEl(sub, ctx));\n }\n }\n const sdt: SdtCellOptions = {\n properties,\n };\n if (sdtCells.length > 0) sdt.cells = sdtCells;\n if (endProperties) sdt.endProperties = endProperties;\n childCells.push({ sdt });\n } else if (child.name === \"w:customXml\") {\n const element = attr(child, \"w:element\") ?? \"\";\n const cx: CustomXmlCellOptions = { element };\n const cxUri = attr(child, \"w:uri\");\n if (cxUri) cx.uri = cxUri;\n const xmlPr = findChild(child, \"w:customXmlPr\");\n if (xmlPr) {\n const parsed = parseCustomXmlProperties(xmlPr);\n if (parsed.placeholder !== undefined || parsed.attributes !== undefined)\n cx.customXmlPr = parsed;\n }\n const cxCells: TableCellOptions[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:tc\") cxCells.push(parseTableCellEl(sub, ctx));\n }\n if (cxCells.length > 0) cx.children = cxCells;\n childCells.push({ customXml: cx });\n }\n }\n\n opts.cells = childCells;\n return opts as TableRowOptions;\n}\n\nfunction parseTableEl(el: Element, ctx: DocxReadContext): TableOptions {\n const opts: Partial<TableOptions> = {};\n\n const tblPr = findChild(el, \"w:tblPr\");\n if (tblPr) {\n const tblPrParsed = parseTablePropertiesEl(tblPr);\n // tableLook maps to base 6-flags and cellMargin to `margins`; pull both\n // aside so the flat assign only carries TableOptions field names.\n const { tableLook, cellMargin, ...rest } = tblPrParsed;\n Object.assign(opts, rest);\n if (cellMargin !== undefined) opts.margins = cellMargin;\n if (tableLook) {\n if (tableLook.firstRow !== undefined) opts.firstRow = tableLook.firstRow;\n if (tableLook.lastRow !== undefined) opts.lastRow = tableLook.lastRow;\n if (tableLook.firstColumn !== undefined) opts.firstCol = tableLook.firstColumn;\n if (tableLook.lastColumn !== undefined) opts.lastCol = tableLook.lastColumn;\n if (tableLook.noHBand !== undefined) opts.bandRow = !tableLook.noHBand;\n if (tableLook.noVBand !== undefined) opts.bandCol = !tableLook.noVBand;\n }\n }\n\n const grid = parseColumnWidthsEl(el);\n if (grid.widths.length > 0) {\n opts.columnWidths = grid.widths as NonNullable<TableOptions[\"columnWidths\"]>;\n }\n if (grid.revision) {\n opts.columnWidthsRevision = grid.revision;\n }\n\n const rows: (TableRowOptions | { sdt: SdtRowOptions } | { customXml: CustomXmlRowOptions })[] =\n [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:tr\") {\n rows.push(parseTableRowEl(child, ctx));\n } else if (child.name === \"w:sdt\") {\n const sdtPr = findChild(child, \"w:sdtPr\");\n const properties = sdtPr ? parseSdtProperties(sdtPr) : {};\n const sdtEndPr = findChild(child, \"w:sdtEndPr\");\n const endProperties = sdtEndPr ? parseRunProperties(sdtEndPr) : undefined;\n const sdtContent = findChild(child, \"w:sdtContent\");\n const sdtRows: TableRowOptions[] = [];\n if (sdtContent) {\n for (const sub of sdtContent.elements ?? []) {\n if (sub.name === \"w:tr\") sdtRows.push(parseTableRowEl(sub, ctx));\n }\n }\n const sdt: SdtRowOptions = {\n properties,\n };\n if (sdtRows.length > 0) sdt.rows = sdtRows;\n if (endProperties) sdt.endProperties = endProperties;\n rows.push({ sdt });\n } else if (child.name === \"w:customXml\") {\n const element = attr(child, \"w:element\") ?? \"\";\n const cx: CustomXmlRowOptions = { element };\n const cxUri = attr(child, \"w:uri\");\n if (cxUri) cx.uri = cxUri;\n const xmlPr = findChild(child, \"w:customXmlPr\");\n if (xmlPr) {\n const parsed = parseCustomXmlProperties(xmlPr);\n if (parsed.placeholder !== undefined || parsed.attributes !== undefined)\n cx.customXmlPr = parsed;\n }\n const cxRows: TableRowOptions[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:tr\") cxRows.push(parseTableRowEl(sub, ctx));\n }\n if (cxRows.length > 0) cx.children = cxRows;\n rows.push({ customXml: cx });\n }\n }\n\n opts.rows = rows;\n return opts as TableOptions;\n}\n","/**\n * Numbering level definitions module for WordprocessingML documents.\n *\n * This module defines the formatting and behavior of individual levels within\n * a numbered or bulleted list hierarchy.\n *\n * Reference: http://officeopenxml.com/WPnumbering-numFmt.php\n *\n * @module\n */\nimport type { AlignmentType } from \"../paragraph/formatting\";\nimport type { LevelParagraphStylePropertiesOptions } from \"../paragraph/properties\";\nimport type { RunStylePropertiesOptions } from \"../paragraph/run/properties\";\n\n/**\n * Number format types for list levels.\n *\n * Defines the various numbering formats available for list levels, including\n * decimal, roman numerals, letters, and various international formats.\n *\n * Reference: http://officeopenxml.com/WPnumbering-numFmt.php\n *\n * @publicApi\n */\nexport const LevelFormat = {\n /** Decimal numbering (1, 2, 3...). */\n DECIMAL: \"decimal\",\n /** Uppercase roman numerals (I, II, III...). */\n UPPER_ROMAN: \"upperRoman\",\n /** Lowercase roman numerals (i, ii, iii...). */\n LOWER_ROMAN: \"lowerRoman\",\n /** Uppercase letters (A, B, C...). */\n UPPER_LETTER: \"upperLetter\",\n /** Lowercase letters (a, b, c...). */\n LOWER_LETTER: \"lowerLetter\",\n /** Ordinal numbers (1st, 2nd, 3rd...). */\n ORDINAL: \"ordinal\",\n /** Cardinal text (one, two, three...). */\n CARDINAL_TEXT: \"cardinalText\",\n /** Ordinal text (first, second, third...). */\n ORDINAL_TEXT: \"ordinalText\",\n /** Hexadecimal numbering. */\n HEX: \"hex\",\n /** Chicago Manual of Style numbering. */\n CHICAGO: \"chicago\",\n /** Ideograph digital numbering. */\n IDEOGRAPH__DIGITAL: \"ideographDigital\",\n /** Japanese counting system. */\n JAPANESE_COUNTING: \"japaneseCounting\",\n /** Japanese aiueo ordering. */\n AIUEO: \"aiueo\",\n /** Japanese iroha ordering. */\n IROHA: \"iroha\",\n /** Full-width decimal numbering. */\n DECIMAL_FULL_WIDTH: \"decimalFullWidth\",\n /** Half-width decimal numbering. */\n DECIMAL_HALF_WIDTH: \"decimalHalfWidth\",\n /** Japanese legal numbering. */\n JAPANESE_LEGAL: \"japaneseLegal\",\n /** Japanese digital ten thousand numbering. */\n JAPANESE_DIGITAL_TEN_THOUSAND: \"japaneseDigitalTenThousand\",\n /** Decimal numbers enclosed in circles. */\n DECIMAL_ENCLOSED_CIRCLE: \"decimalEnclosedCircle\",\n /** Full-width decimal numbering variant 2. */\n DECIMAL_FULL_WIDTH2: \"decimalFullWidth2\",\n /** Full-width aiueo ordering. */\n AIUEO_FULL_WIDTH: \"aiueoFullWidth\",\n /** Full-width iroha ordering. */\n IROHA_FULL_WIDTH: \"irohaFullWidth\",\n /** Decimal with leading zeros. */\n DECIMAL_ZERO: \"decimalZero\",\n /** Bullet points. */\n BULLET: \"bullet\",\n /** Korean ganada ordering. */\n GANADA: \"ganada\",\n /** Korean chosung ordering. */\n CHOSUNG: \"chosung\",\n /** Decimal enclosed with fullstop. */\n DECIMAL_ENCLOSED_FULLSTOP: \"decimalEnclosedFullstop\",\n /** Decimal enclosed in parentheses. */\n DECIMAL_ENCLOSED_PARENTHESES: \"decimalEnclosedParen\",\n /** Decimal enclosed in circles (Chinese). */\n DECIMAL_ENCLOSED_CIRCLE_CHINESE: \"decimalEnclosedCircleChinese\",\n /** Ideograph enclosed in circles. */\n IDEOGRAPH_ENCLOSED_CIRCLE: \"ideographEnclosedCircle\",\n /** Traditional ideograph numbering. */\n IDEOGRAPH_TRADITIONAL: \"ideographTraditional\",\n /** Ideograph zodiac numbering. */\n IDEOGRAPH_ZODIAC: \"ideographZodiac\",\n /** Traditional ideograph zodiac numbering. */\n IDEOGRAPH_ZODIAC_TRADITIONAL: \"ideographZodiacTraditional\",\n /** Taiwanese counting system. */\n TAIWANESE_COUNTING: \"taiwaneseCounting\",\n /** Traditional ideograph legal numbering. */\n IDEOGRAPH_LEGAL_TRADITIONAL: \"ideographLegalTraditional\",\n /** Taiwanese counting thousand system. */\n TAIWANESE_COUNTING_THOUSAND: \"taiwaneseCountingThousand\",\n /** Taiwanese digital numbering. */\n TAIWANESE_DIGITAL: \"taiwaneseDigital\",\n /** Chinese counting system. */\n CHINESE_COUNTING: \"chineseCounting\",\n /** Simplified Chinese legal numbering. */\n CHINESE_LEGAL_SIMPLIFIED: \"chineseLegalSimplified\",\n /** Chinese counting thousand system. */\n CHINESE_COUNTING_THOUSAND: \"chineseCountingThousand\",\n /** Korean digital numbering. */\n KOREAN_DIGITAL: \"koreanDigital\",\n /** Korean counting system. */\n KOREAN_COUNTING: \"koreanCounting\",\n /** Korean legal numbering. */\n KOREAN_LEGAL: \"koreanLegal\",\n /** Korean digital numbering variant 2. */\n KOREAN_DIGITAL2: \"koreanDigital2\",\n /** Vietnamese counting system. */\n VIETNAMESE_COUNTING: \"vietnameseCounting\",\n /** Russian lowercase numbering. */\n RUSSIAN_LOWER: \"russianLower\",\n /** Russian uppercase numbering. */\n RUSSIAN_UPPER: \"russianUpper\",\n /** No numbering. */\n NONE: \"none\",\n /** Number enclosed in dashes. */\n NUMBER_IN_DASH: \"numberInDash\",\n /** Hebrew numbering variant 1. */\n HEBREW1: \"hebrew1\",\n /** Hebrew numbering variant 2. */\n HEBREW2: \"hebrew2\",\n /** Arabic alpha numbering. */\n ARABIC_ALPHA: \"arabicAlpha\",\n /** Arabic abjad numbering. */\n ARABIC_ABJAD: \"arabicAbjad\",\n /** Hindi vowels. */\n HINDI_VOWELS: \"hindiVowels\",\n /** Hindi consonants. */\n HINDI_CONSONANTS: \"hindiConsonants\",\n /** Hindi numbers. */\n HINDI_NUMBERS: \"hindiNumbers\",\n /** Hindi counting system. */\n HINDI_COUNTING: \"hindiCounting\",\n /** Thai letters. */\n THAI_LETTERS: \"thaiLetters\",\n /** Thai numbers. */\n THAI_NUMBERS: \"thaiNumbers\",\n /** Thai counting system. */\n THAI_COUNTING: \"thaiCounting\",\n /** Thai Baht text. */\n BAHT_TEXT: \"bahtText\",\n /** Dollar text. */\n DOLLAR_TEXT: \"dollarText\",\n /** Custom numbering format. */\n CUSTOM: \"custom\",\n} as const;\n\n/**\n * Suffix types for list levels.\n *\n * Defines what follows the numbering text (tab, space, or nothing).\n *\n * @publicApi\n */\nexport const LevelSuffix = {\n /** No separator after the numbering. */\n NOTHING: \"nothing\",\n /** Space character after the numbering. */\n SPACE: \"space\",\n /** Tab character after the numbering. */\n TAB: \"tab\",\n} as const;\n\n/**\n * Options for configuring a numbering level.\n *\n * @property level - Level index (0-8)\n * @property format - Number format type (decimal, roman, letter, etc.)\n * @property text - Level text template with placeholders like %1, %2\n * @property alignment - Text alignment for the numbering\n * @property start - Starting number for this level\n * @property suffix - Character(s) following the numbering (tab, space, nothing)\n * @property isLegalNumberingStyle - Use legal numbering style\n * @property style - Run and paragraph style properties\n */\nexport interface LevelsOptions {\n /** Level index (0-8). */\n level: number;\n /** Number format type (decimal, roman, letter, bullet, etc.). */\n format?: (typeof LevelFormat)[keyof typeof LevelFormat];\n /** Level text template with placeholders like %1, %2. */\n text?: string;\n /** Whether this level emits no text (CT_LevelText @w:null). */\n textNull?: boolean;\n /** Text alignment for the numbering. */\n alignment?: (typeof AlignmentType)[keyof typeof AlignmentType];\n /** Starting number for this level. */\n start?: number;\n /** Character(s) following the numbering. */\n suffix?: (typeof LevelSuffix)[keyof typeof LevelSuffix];\n /** Use legal numbering style (e.g., 1.1.1). */\n isLegalNumberingStyle?: boolean;\n /** Restart numbering after this level (0-based level index). */\n levelRestart?: number;\n /** Paragraph style ID this level is linked to (CT_Lvl pStyle). */\n paragraphStyle?: string;\n /** Picture bullet ID reference. */\n levelPictureBulletId?: number;\n /** Template code for the level. */\n templateCode?: string;\n /** Whether this level is tentative (w:tentative attribute). */\n tentative?: boolean;\n /** Whether this level is tentative (w15:tentative attribute). */\n w15Tentative?: boolean;\n /** Legacy spacing/indent settings. `enabled` maps to the required CT_LvlLegacy @w:legacy flag. */\n legacy?: { enabled?: boolean; space?: number; indent?: number };\n /** Run and paragraph style properties. */\n style?: {\n /** Run style properties for the numbering text. */\n run?: RunStylePropertiesOptions;\n /** Paragraph style properties for the level. */\n paragraph?: LevelParagraphStylePropertiesOptions;\n };\n}\n","import { uniqueNumericIdCreator, convertInchesToTwip } from \"@office-open/core\";\nimport { decimalNumber } from \"@office-open/core\";\n/**\n * Numbering module for WordprocessingML documents.\n *\n * Numbering provides support for numbered and bulleted lists.\n * Pure string serialization — no XmlComponent inheritance.\n *\n * Reference: http://officeopenxml.com/WPnumbering.php\n *\n * @module\n */\nimport { attr, attrBool, attrNum, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport { AlignmentType } from \"@parts/paragraph\";\nimport type { ParagraphPropertiesOptions } from \"@parts/paragraph/properties\";\nimport { parseRunProperties } from \"@parts/paragraph/run/run-parse\";\n\nimport type { DocxReadContext } from \"../../context\";\nimport { stringifyElement } from \"../../util/stringify-element\";\nimport { stringifyParagraphProperties, stringifyRunProperties } from \"../paragraph/stringify\";\nimport { LevelFormat } from \"./level\";\nimport type { LevelsOptions } from \"./level\";\n\n/**\n * Options for configuring numbering definitions.\n */\nexport interface NumberingOptions {\n /** Array of numbering configurations, each with levels and a reference name. */\n config: {\n levels: LevelsOptions[];\n reference: string;\n extraOptions?: AbstractNumberingExtraOptions;\n }[];\n /** Numbering cleanup ID (w:numIdMacAtCleanup) */\n numIdMacAtCleanup?: number;\n /** Picture bullet definitions for numbering (w:numPicBullet) */\n numPicBullets?: {\n numPicBulletId: number;\n /** Verbatim w:pict element XML (CT_Picture) */\n pict?: string;\n /** Verbatim w:drawing element XML (CT_Drawing) — alternative to pict */\n drawing?: string;\n }[];\n}\n\n/** Namespace attributes for w:numbering (pre-computed constant). */\nconst NUMBERING_ATTRS =\n documentNamespaceAttributes([\n \"wpc\",\n \"mc\",\n \"o\",\n \"r\",\n \"m\",\n \"v\",\n \"wp14\",\n \"wp\",\n \"w10\",\n \"w\",\n \"w14\",\n \"w15\",\n \"wpg\",\n \"wpi\",\n \"wne\",\n \"wps\",\n ]) + ' mc:Ignorable=\"w14 w15 wp14\"';\n\n/** Default bullet levels (9 levels: 0-8). */\nconst DEFAULT_BULLET_LEVELS: LevelsOptions[] = [\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 0,\n style: {\n paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: convertInchesToTwip(0.5) } },\n },\n text: \"●\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 1,\n style: {\n paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: convertInchesToTwip(1) } },\n },\n text: \"○\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 2,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 2160 } } },\n text: \"■\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 3,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 2880 } } },\n text: \"●\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 4,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 3600 } } },\n text: \"○\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 5,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 4320 } } },\n text: \"■\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 6,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 5040 } } },\n text: \"●\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 7,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 5760 } } },\n text: \"●\",\n },\n {\n alignment: AlignmentType.LEFT,\n format: LevelFormat.BULLET,\n level: 8,\n style: { paragraph: { indent: { hanging: convertInchesToTwip(0.25), left: 6480 } } },\n text: \"●\",\n },\n];\n\n/**\n * Numbering definitions for a WordprocessingML document.\n *\n * Pure data accumulator — no XmlComponent inheritance.\n * Serializes via `serialize()` producing a complete XML part.\n */\nexport class Numbering {\n private abstractNumberingData = new Map<\n string,\n { id: number; levels: LevelsOptions[]; extraOptions?: AbstractNumberingExtraOptions }\n >();\n private concreteNumberingData = new Map<\n string,\n {\n numId: number;\n abstractNumId: number;\n reference: string;\n instance: number;\n overrideLevels?: { num: number; start?: number }[];\n }\n >();\n private referenceConfigMap = new Map<string, LevelsOptions[]>();\n private abstractNumUniqueNumericId = uniqueNumericIdCreator();\n private concreteNumUniqueNumericId = uniqueNumericIdCreator(1);\n private _numIdMacAtCleanup?: number;\n private _numPicBullets?: { numPicBulletId: number; pict?: string; drawing?: string }[];\n\n public constructor(options: NumberingOptions) {\n this._numIdMacAtCleanup = options.numIdMacAtCleanup;\n this._numPicBullets = options.numPicBullets;\n\n // Only inject the default bullet numbering when the caller supplied no\n // numbering definitions. Round-tripped documents carry their own, so\n // injecting a default would inflate the part (extra abstractNum + 9 levels).\n if (options.config.length === 0) {\n const defaultAbstractId = this.abstractNumUniqueNumericId();\n this.abstractNumberingData.set(\"default-bullet-numbering\", {\n id: defaultAbstractId,\n levels: DEFAULT_BULLET_LEVELS,\n });\n this.concreteNumberingData.set(\"default-bullet-numbering\", {\n abstractNumId: defaultAbstractId,\n instance: 0,\n numId: 1,\n overrideLevels: [{ num: 0, start: 1 }],\n reference: \"default-bullet-numbering\",\n });\n }\n\n for (const con of options.config) {\n this.abstractNumberingData.set(con.reference, {\n id: this.abstractNumUniqueNumericId(),\n levels: con.levels,\n extraOptions: con.extraOptions,\n });\n this.referenceConfigMap.set(con.reference, con.levels);\n }\n }\n\n /** Serialize to word/numbering.xml content (with XML declaration). */\n public serialize(): string {\n const parts: string[] = [];\n parts.push(`<w:numbering ${NUMBERING_ATTRS}>`);\n\n // numPicBullet elements come first (XSD order)\n if (this._numPicBullets) {\n for (const bullet of this._numPicBullets) {\n const inner = bullet.pict ?? bullet.drawing;\n if (inner) {\n parts.push(\n `<w:numPicBullet w:numPicBulletId=\"${bullet.numPicBulletId}\">${inner}</w:numPicBullet>`,\n );\n } else {\n parts.push(`<w:numPicBullet w:numPicBulletId=\"${bullet.numPicBulletId}\"/>`);\n }\n }\n }\n\n for (const an of this.abstractNumberingData.values()) {\n parts.push(stringifyAbstractNumbering(an.id, an.levels, an.extraOptions));\n }\n for (const cn of this.concreteNumberingData.values()) {\n parts.push(stringifyConcreteNumbering(cn));\n }\n if (this._numIdMacAtCleanup !== undefined) {\n parts.push(`<w:numIdMacAtCleanup w:val=\"${decimalNumber(this._numIdMacAtCleanup)}\"/>`);\n }\n\n parts.push(\"</w:numbering>\");\n return '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>' + parts.join(\"\");\n }\n\n /**\n * Creates a concrete numbering instance from an abstract numbering definition.\n */\n public createConcreteNumberingInstance(reference: string, instance: number): void {\n const abstractNumbering = this.abstractNumberingData.get(reference);\n if (!abstractNumbering) return;\n\n const fullReference = `${reference}-${instance}`;\n if (this.concreteNumberingData.has(fullReference)) return;\n\n const referenceConfigLevels = this.referenceConfigMap.get(reference);\n const firstLevelStartNumber = referenceConfigLevels?.[0]?.start;\n\n // Only emit a lvlOverride when the instance's start differs from the\n // abstract default (1) — otherwise it is redundant and inflates the part.\n const overrideLevels =\n typeof firstLevelStartNumber === \"number\" &&\n Number.isInteger(firstLevelStartNumber) &&\n firstLevelStartNumber !== 1\n ? [{ num: 0, start: firstLevelStartNumber }]\n : undefined;\n\n this.concreteNumberingData.set(fullReference, {\n abstractNumId: abstractNumbering.id,\n instance,\n numId: this.concreteNumUniqueNumericId(),\n overrideLevels,\n reference,\n });\n }\n\n /** Gets all concrete numbering instances. */\n public get concreteNumbering(): { numId: number; reference: string; instance: number }[] {\n return [...this.concreteNumberingData.values()];\n }\n\n /** Gets all reference configurations. */\n public get referenceConfig(): LevelsOptions[][] {\n return [...this.referenceConfigMap.values()];\n }\n}\n\n// ── Types ──\n\n/** Extra options for abstract numbering (w:abstractNum attributes + w15 restart). */\ninterface AbstractNumberingExtraOptions {\n nsid?: string;\n /** w:multiLevelType value (singleLevel/multilevel/hybridMultilevel). */\n multiLevelType?: string;\n /** w15:restartNumberingAfterBreak attribute on w:abstractNum. Omitted when undefined. */\n restartNumberingAfterBreak?: boolean;\n tmpl?: string;\n name?: string;\n styleLink?: string;\n numStyleLink?: string;\n}\n\n// ── Pure function serializers ──\n\nfunction stringifyAbstractNumbering(\n id: number,\n levels: LevelsOptions[],\n extraOptions?: AbstractNumberingExtraOptions,\n): string {\n const parts: string[] = [];\n // w15:restartNumberingAfterBreak is optional (w15 extension); only emit when\n // explicitly carried so round-trip matches sources that omit it.\n const restartAttr =\n extraOptions?.restartNumberingAfterBreak !== undefined\n ? ` w15:restartNumberingAfterBreak=\"${extraOptions.restartNumberingAfterBreak ? 1 : 0}\"`\n : \"\";\n parts.push(`<w:abstractNum w:abstractNumId=\"${decimalNumber(id)}\"${restartAttr}>`);\n\n if (extraOptions?.nsid !== undefined) {\n parts.push(`<w:nsid w:val=\"${extraOptions.nsid}\"/>`);\n }\n parts.push(`<w:multiLevelType w:val=\"${extraOptions?.multiLevelType ?? \"hybridMultilevel\"}\"/>`);\n if (extraOptions?.tmpl !== undefined) {\n parts.push(`<w:tmpl w:val=\"${extraOptions.tmpl}\"/>`);\n }\n if (extraOptions?.name !== undefined) {\n parts.push(`<w:name w:val=\"${extraOptions.name}\"/>`);\n }\n if (extraOptions?.styleLink !== undefined) {\n parts.push(`<w:styleLink w:val=\"${extraOptions.styleLink}\"/>`);\n }\n if (extraOptions?.numStyleLink !== undefined) {\n parts.push(`<w:numStyleLink w:val=\"${extraOptions.numStyleLink}\"/>`);\n }\n\n for (const level of levels) {\n parts.push(stringifyLevel(level));\n }\n\n parts.push(\"</w:abstractNum>\");\n return parts.join(\"\");\n}\n\nfunction stringifyConcreteNumbering(cn: {\n numId: number;\n abstractNumId: number;\n overrideLevels?: { num: number; start?: number }[];\n}): string {\n const parts: string[] = [];\n parts.push(`<w:num w:numId=\"${decimalNumber(cn.numId)}\">`);\n parts.push(`<w:abstractNumId w:val=\"${decimalNumber(cn.abstractNumId)}\"/>`);\n\n if (cn.overrideLevels) {\n for (const level of cn.overrideLevels) {\n if (level.start !== undefined) {\n parts.push(\n `<w:lvlOverride w:ilvl=\"${level.num}\"><w:startOverride w:val=\"${level.start}\"/></w:lvlOverride>`,\n );\n } else {\n parts.push(`<w:lvlOverride w:ilvl=\"${level.num}\"/>`);\n }\n }\n }\n\n parts.push(\"</w:num>\");\n return parts.join(\"\");\n}\n\nfunction stringifyLevel(opts: LevelsOptions): string {\n const children: string[] = [];\n\n children.push(`<w:start w:val=\"${decimalNumber(opts.start ?? 1)}\"/>`);\n if (opts.format) children.push(`<w:numFmt w:val=\"${opts.format}\"/>`);\n if (opts.levelRestart !== undefined)\n children.push(`<w:lvlRestart w:val=\"${decimalNumber(opts.levelRestart)}\"/>`);\n if (opts.paragraphStyle !== undefined)\n children.push(`<w:pStyle w:val=\"${opts.paragraphStyle}\"/>`);\n // CT_Lvl sequence: pStyle → isLgl → suff (XSD). isLgl must precede suff.\n if (opts.isLegalNumberingStyle) children.push(\"<w:isLgl/>\");\n if (opts.suffix) children.push(`<w:suff w:val=\"${opts.suffix}\"/>`);\n if (opts.text !== undefined || opts.textNull) {\n const lvlTextAttrs: string[] = [];\n if (opts.text !== undefined) lvlTextAttrs.push(`w:val=\"${opts.text}\"`);\n if (opts.textNull) lvlTextAttrs.push('w:null=\"1\"');\n children.push(`<w:lvlText ${lvlTextAttrs.join(\" \")}/>`);\n }\n if (opts.levelPictureBulletId !== undefined)\n children.push(`<w:lvlPicBulletId w:val=\"${decimalNumber(opts.levelPictureBulletId)}\"/>`);\n if (opts.legacy !== undefined) {\n const legacyAttrs: string[] = [`w:legacy=\"${(opts.legacy.enabled ?? true) ? 1 : 0}\"`];\n if (opts.legacy.space !== undefined) legacyAttrs.push(`w:legacySpace=\"${opts.legacy.space}\"`);\n if (opts.legacy.indent !== undefined)\n legacyAttrs.push(`w:legacyIndent=\"${opts.legacy.indent}\"`);\n children.push(`<w:legacy ${legacyAttrs.join(\" \")}/>`);\n }\n children.push(`<w:lvlJc w:val=\"${opts.alignment ?? AlignmentType.START}\"/>`);\n\n // Paragraph/run properties — use compile-path pure string builders\n const pPrXml = stringifyParagraphProperties(opts.style && opts.style.paragraph).xml;\n const rPrXml = stringifyRunProperties(opts.style && opts.style.run);\n if (pPrXml) children.push(pPrXml);\n if (rPrXml) children.push(rPrXml);\n\n const lvlAttrs: string[] = [`w:ilvl=\"${decimalNumber(Math.min(opts.level, 9))}\"`];\n // w15:tentative is optional; only emit when carried (matches sources that omit it).\n if (opts.w15Tentative !== undefined)\n lvlAttrs.push(`w15:tentative=\"${opts.w15Tentative ? 1 : 0}\"`);\n if (opts.templateCode !== undefined) lvlAttrs.push(`w:tplc=\"${opts.templateCode}\"`);\n if (opts.tentative !== undefined) lvlAttrs.push(`w:tentative=\"${opts.tentative ? 1 : 0}\"`);\n\n return `<w:lvl ${lvlAttrs.join(\" \")}>${children.join(\"\")}</w:lvl>`;\n}\n\n// ── Parse (Element → NumberingOptions) ──\n\n/**\n * Parse w:numbering element into NumberingOptions.\n */\nexport function parseNumberingDefinitions(\n el: Element,\n parseParagraphProperties: (\n el: Element,\n ctx: DocxReadContext,\n ) => Partial<ParagraphPropertiesOptions>,\n ctx: DocxReadContext,\n): NumberingOptions | undefined {\n // Picture bullets (w:numPicBullet — choice of w:pict | w:drawing)\n const numPicBullets: NonNullable<NumberingOptions[\"numPicBullets\"]> = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:numPicBullet\") continue;\n const id = attrNum(child, \"w:numPicBulletId\");\n const bullet: { numPicBulletId: number; pict?: string; drawing?: string } = {\n numPicBulletId: id ?? 0,\n };\n const pictEl = findChild(child, \"w:pict\");\n if (pictEl) bullet.pict = stringifyElement(pictEl);\n const drawingEl = findChild(child, \"w:drawing\");\n if (drawingEl) bullet.drawing = stringifyElement(drawingEl);\n numPicBullets.push(bullet);\n }\n\n // numIdMacAtCleanup (w:numIdMacAtCleanup)\n const cleanupEl = findChild(el, \"w:numIdMacAtCleanup\");\n const numIdMacAtCleanup = cleanupEl ? attrNum(cleanupEl, \"w:val\") : undefined;\n\n const abstractNums = new Map<string, Element>();\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:abstractNum\") continue;\n const id = attr(child, \"w:abstractNumId\");\n if (id !== undefined) abstractNums.set(id, child);\n }\n\n // Concrete num instances: numId → abstractId + the num element. The element\n // is kept so its lvlOverride/startOverride can be read — a concrete num may\n // re-pin a level's start, and dropping the override silently reverts the\n // list's restart numbering on round-trip.\n const numEntries: { numId: string; abstractId: string; numEl: Element }[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:num\") continue;\n const numId = attr(child, \"w:numId\");\n const abstractRef = findChild(child, \"w:abstractNumId\");\n const abstractId = abstractRef ? attr(abstractRef, \"w:val\") : undefined;\n if (numId !== undefined && abstractId !== undefined) {\n numEntries.push({ numId, abstractId, numEl: child });\n }\n }\n\n const configs: NumberingOptions[\"config\"] = [];\n\n for (const { numId, abstractId, numEl } of numEntries) {\n const abstractEl = abstractNums.get(abstractId);\n if (!abstractEl) continue;\n\n const levels: LevelsOptions[] = [];\n for (const child of abstractEl.elements ?? []) {\n if (child.name !== \"w:lvl\") continue;\n const levelOpts = parseLevelEl(child, parseParagraphProperties, ctx);\n if (levelOpts) levels.push(levelOpts);\n }\n\n if (levels.length > 0) {\n const extraOptions: AbstractNumberingExtraOptions = {};\n const nsidEl = findChild(abstractEl, \"w:nsid\");\n if (nsidEl) {\n const v = attr(nsidEl, \"w:val\");\n if (v) extraOptions.nsid = v;\n }\n const multiLevelTypeEl = findChild(abstractEl, \"w:multiLevelType\");\n if (multiLevelTypeEl) {\n const v = attr(multiLevelTypeEl, \"w:val\");\n if (v) extraOptions.multiLevelType = v;\n }\n const restartVal = attrBool(abstractEl, \"w15:restartNumberingAfterBreak\");\n if (restartVal !== undefined) extraOptions.restartNumberingAfterBreak = restartVal;\n const tmplEl = findChild(abstractEl, \"w:tmpl\");\n if (tmplEl) {\n const v = attr(tmplEl, \"w:val\");\n if (v) extraOptions.tmpl = v;\n }\n const nameEl = findChild(abstractEl, \"w:name\");\n if (nameEl) {\n const v = attr(nameEl, \"w:val\");\n if (v) extraOptions.name = v;\n }\n const styleLinkEl = findChild(abstractEl, \"w:styleLink\");\n if (styleLinkEl) {\n const v = attr(styleLinkEl, \"w:val\");\n if (v) extraOptions.styleLink = v;\n }\n const numStyleLinkEl = findChild(abstractEl, \"w:numStyleLink\");\n if (numStyleLinkEl) {\n const v = attr(numStyleLinkEl, \"w:val\");\n if (v) extraOptions.numStyleLink = v;\n }\n // Apply per-instance level start overrides. The abstract level defines\n // the default start; a concrete num may re-pin it via lvlOverride, and\n // dropping it silently reverts the list's restart numbering.\n for (const overrideEl of numEl.elements ?? []) {\n if (overrideEl.name !== \"w:lvlOverride\") continue;\n const ilvl = attrNum(overrideEl, \"w:ilvl\");\n if (ilvl === undefined) continue;\n const startOverrideEl = findChild(overrideEl, \"w:startOverride\");\n if (!startOverrideEl) continue;\n const val = attrNum(startOverrideEl, \"w:val\");\n if (val === undefined) continue;\n const level = levels.find((l) => l.level === ilvl);\n if (level) level.start = val;\n }\n configs.push({ reference: `list_${numId}`, levels, extraOptions });\n }\n }\n\n if (configs.length === 0 && numPicBullets.length === 0 && numIdMacAtCleanup === undefined) {\n return undefined;\n }\n const result: NumberingOptions = { config: configs };\n if (numPicBullets.length > 0) result.numPicBullets = numPicBullets;\n if (numIdMacAtCleanup !== undefined) result.numIdMacAtCleanup = numIdMacAtCleanup;\n return result;\n}\n\nfunction parseLevelEl(\n el: Element,\n parseParagraphProperties: (\n el: Element,\n ctx: DocxReadContext,\n ) => Partial<ParagraphPropertiesOptions>,\n ctx: DocxReadContext,\n): LevelsOptions | undefined {\n const opts: Partial<LevelsOptions> = {};\n\n const level = attrNum(el, \"w:ilvl\");\n if (level !== undefined) opts.level = level;\n\n const start = findChild(el, \"w:start\");\n if (start) {\n const val = attrNum(start, \"w:val\");\n if (val !== undefined) opts.start = val;\n }\n\n const lvlRestart = findChild(el, \"w:lvlRestart\");\n if (lvlRestart) {\n const val = attrNum(lvlRestart, \"w:val\");\n if (val !== undefined) opts.levelRestart = val;\n }\n\n const numFmt = findChild(el, \"w:numFmt\");\n if (numFmt) {\n const val = attr(numFmt, \"w:val\");\n if (val) opts.format = val as LevelsOptions[\"format\"];\n }\n\n const suff = findChild(el, \"w:suff\");\n if (suff) {\n const val = attr(suff, \"w:val\");\n if (val) opts.suffix = val as LevelsOptions[\"suffix\"];\n }\n\n const pStyle = findChild(el, \"w:pStyle\");\n if (pStyle) {\n const val = attr(pStyle, \"w:val\");\n if (val) opts.paragraphStyle = val;\n }\n\n if (findChild(el, \"w:isLgl\")) opts.isLegalNumberingStyle = true;\n\n const lvlText = findChild(el, \"w:lvlText\");\n if (lvlText) {\n const val = attr(lvlText, \"w:val\");\n if (val) opts.text = val;\n const isNull = attrBool(lvlText, \"w:null\");\n if (isNull) opts.textNull = isNull;\n }\n\n const lvlPicBulletId = findChild(el, \"w:lvlPicBulletId\");\n if (lvlPicBulletId) {\n const val = attrNum(lvlPicBulletId, \"w:val\");\n if (val !== undefined) opts.levelPictureBulletId = val;\n }\n\n // Legacy spacing (w:legacy/@w:legacy [required], @w:legacySpace, @w:legacyIndent)\n const legacyEl = findChild(el, \"w:legacy\");\n if (legacyEl) {\n const legacy: NonNullable<LevelsOptions[\"legacy\"]> = {};\n const enabled = attrBool(legacyEl, \"w:legacy\");\n if (enabled !== undefined) legacy.enabled = enabled;\n const space = attrNum(legacyEl, \"w:legacySpace\");\n if (space !== undefined) legacy.space = space;\n const indent = attrNum(legacyEl, \"w:legacyIndent\");\n if (indent !== undefined) legacy.indent = indent;\n opts.legacy = legacy;\n }\n\n const lvlJc = findChild(el, \"w:lvlJc\");\n if (lvlJc) {\n const val = attr(lvlJc, \"w:val\");\n if (val) opts.alignment = val as LevelsOptions[\"alignment\"];\n }\n\n // Level attributes (w:tplc templateCode; w:tentative; w15:tentative)\n const tplc = attr(el, \"w:tplc\");\n if (tplc) opts.templateCode = tplc;\n const tentative = attrBool(el, \"w:tentative\");\n if (tentative !== undefined) opts.tentative = tentative;\n const w15Tentative = attrBool(el, \"w15:tentative\");\n if (w15Tentative !== undefined) opts.w15Tentative = w15Tentative;\n\n // Run + paragraph properties — reuse the complete parse helpers for full\n // fidelity (stringifyLevel delegates to stringifyRunProperties /\n // stringifyParagraphProperties, so parse must use the matching readers).\n const style: NonNullable<LevelsOptions[\"style\"]> = {};\n const rPr = findChild(el, \"w:rPr\");\n if (rPr) {\n const runOpts = parseRunProperties(rPr);\n if (Object.keys(runOpts).length > 0) style.run = runOpts;\n }\n const pPr = findChild(el, \"w:pPr\");\n if (pPr) {\n const paraOpts = parseParagraphProperties(pPr, ctx);\n if (Object.keys(paraOpts).length > 0) {\n style.paragraph = paraOpts;\n }\n }\n if (Object.keys(style).length > 0) opts.style = style;\n\n return Object.keys(opts).length > 0 ? (opts as LevelsOptions) : undefined;\n}\n","import { decimalNumber } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\n/**\n * Specifies the type of the current document grid, which defines the grid behavior.\n *\n * The grid can define a grid which snaps all East Asian characters to grid positions, but leaves Latin text with its default spacing; a grid which adds the specified character pitch to all characters on each row; or a grid which affects only the line pitch for the current section.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_DocGrid_topic_ID0ELYP2.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_DocGrid\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"default\"/>\n * <xsd:enumeration value=\"lines\"/>\n * <xsd:enumeration value=\"linesAndChars\"/>\n * <xsd:enumeration value=\"snapToChars\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n */\nexport const DocumentGridType = {\n /**\n * Specifies that no document grid shall be applied to the contents of the current section in the document.\n */\n DEFAULT: \"default\",\n /**\n * Specifies that the parent section shall have additional line pitch added to each line within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain the specified number of lines per page.\n */\n LINES: \"lines\",\n /**\n * Specifies that the parent section shall have both the additional line pitch and character pitch added to each line and character within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain a specific number of lines per page and characters per line.\n *\n * When this value is set, the input specified via the user interface may be allowed in exact number of line/character pitch units. */\n LINES_AND_CHARS: \"linesAndChars\",\n /**\n * Specifies that the parent section shall have both the additional line pitch and character pitch added to each line and character within it (as specified on the <docGrid> element (§2.6.5)) in order to maintain a specific number of lines per page and characters per line.\n *\n * When this value is set, the input specified via the user interface may be restricted to the number of lines per page and characters per line, with the consumer or producer translating this information based on the current font data to get the resulting line and character pitch values\n */\n SNAP_TO_CHARS: \"snapToChars\",\n} as const;\n\nexport interface DocGridProperties {\n /**\n * Specifies the type of the current document grid, which defines the grid behavior.\n *\n * The grid can define a grid which snaps all East Asian characters to grid positions, but leaves Latin text with its default spacing; a grid which adds the specified character pitch to each character on each row; or a grid which affects only the line pitch for the current section.\n */\n type?: (typeof DocumentGridType)[keyof typeof DocumentGridType];\n /**\n * Specifies the number of lines to be allowed on the document grid for the current page assuming all lines have equal line pitch applied to them. This line pitch shall not be added to any line which appears within a table cell unless the <adjustLineHeightInTable> element (§2.15.3.1) is present in the document's compatibility settings.\n *\n * This attribute is specified in twentieths of a point, and defines the pitch for each line of text on this page such that the desired number of single spaced lines of text fits on the current page.\n *\n * ```xml\n * <w:docGrid w:linePitch=\"684\" …/>\n * ```\n *\n * The `linePitch` attribute specifies that 34.2 points is to the amount of pitch allowed for each line on this page in order to maintain the specific document grid. ]\n *\n * Individual paragraphs can override the line pitch information specified for the document grid by either:\n *\n * Specifying an exact line spacing value using the `lineRule` attribute of value exact on the <spacing> element (§2.3.1.33).\n *\n * Specifying that the paragraph text shall not snap to the document grid via the <snapToGrid> element (§2.3.1.32).\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n linePitch: number;\n /**\n * Specifies the number of characters to be allowed on the document grid for each line in this section.\n *\n * This attribute's value shall be specified by multiplying the difference between the desired character pitch and the character pitch for that character in the font size of the Normal font by 4096.\n *\n * This value shall then be used to add the character pitch for the specified point size to each character in the section [: This results in text in the Normal style having a specific number of characters per line. ]\n *\n * ```xml\n * <w:docGrid w:charSize=\"40960\" …/>\n * ```\n * The `charSpace` attribute specifies a value of 40960, which means that the delta between the character pitch of each character in the grid and the Normal font is 10 points, resulting in a character pitch of 11+10 = 21 points for all characters in this section. ]\n *\n * Individual runs of text can override the line pitch information specified for the document grid by specifying that the run text shall not snap to the document grid via the <snapToGrid> element (§2.3.2.32).\n *\n * The possible values for this attribute are defined by the `ST_DecimalNumber` simple type (§2.18.16).\n */\n charSpace?: number;\n}\n\n/**\n * This element specifies the settings for the document grid, which enables precise layout of full-width East Asian language characters within a document by specifying the desired number of characters per line and lines per page for all East Asian text content in this section.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_docGrid_topic_ID0EHU5S.html\n *\n * ```xml\n * <xsd:complexType name=\"CT_DocGrid\">\n * <xsd:attribute name=\"type\" type=\"ST_DocGrid\"/>\n * <xsd:attribute name=\"linePitch\" type=\"ST_DecimalNumber\"/>\n * <xsd:attribute name=\"charSpace\" type=\"ST_DecimalNumber\"/>\n * </xsd:complexType>\n * ```\n * @returns\n */\nexport const createDocumentGrid = ({ type, linePitch, charSpace }: DocGridProperties): string =>\n element(\"w:docGrid\", {\n \"w:charSpace\": charSpace ? decimalNumber(charSpace) : undefined,\n \"w:linePitch\": decimalNumber(linePitch),\n \"w:type\": type,\n });\n","/**\n * Page borders module for WordprocessingML section properties.\n *\n * Defines borders around pages in a document section.\n *\n * Reference: http://officeopenxml.com/WPsectionBorders.php\n *\n * @module\n */\nimport type { BorderOptions } from \"@shared/border\";\n\n/**\n * Specifies which pages display the page border.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderDisplay\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"allPages\"/>\n * <xsd:enumeration value=\"firstPage\"/>\n * <xsd:enumeration value=\"notFirstPage\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderDisplay = {\n /** Display border on all pages */\n ALL_PAGES: \"allPages\",\n /** Display border only on first page */\n FIRST_PAGE: \"firstPage\",\n /** Display border on all pages except first page */\n NOT_FIRST_PAGE: \"notFirstPage\",\n} as const;\n\n/**\n * Specifies whether page border is positioned relative to page edge or text.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderOffset\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"page\"/>\n * <xsd:enumeration value=\"text\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderOffsetFrom = {\n /** Position border relative to page edge */\n PAGE: \"page\",\n /** Position border relative to text (default) */\n TEXT: \"text\",\n} as const;\n\n/**\n * Specifies z-order of page border relative to intersecting objects.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_PageBorderZOrder\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"front\"/>\n * <xsd:enumeration value=\"back\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const PageBorderZOrder = {\n /** Display border behind page contents */\n BACK: \"back\",\n /** Display border in front of page contents (default) */\n FRONT: \"front\",\n} as const;\n\n/**\n * Options for configuring page borders.\n *\n * @property display - Which pages display the border\n * @property offsetFrom - Whether border is positioned relative to page or text\n * @property zOrder - Whether border appears in front or behind page contents\n * @property top - Top border styling\n * @property right - Right border styling\n * @property bottom - Bottom border styling\n * @property left - Left border styling\n */\nexport interface PageBordersOptions {\n /** Which pages display the border */\n display?: (typeof PageBorderDisplay)[keyof typeof PageBorderDisplay];\n /** Whether border is positioned relative to page or text (default: text) */\n offsetFrom?: (typeof PageBorderOffsetFrom)[keyof typeof PageBorderOffsetFrom];\n /** Whether border appears in front or behind page contents (default: front) */\n zOrder?: (typeof PageBorderZOrder)[keyof typeof PageBorderZOrder];\n /** Top border styling */\n top?: BorderOptions;\n /** Right border styling */\n right?: BorderOptions;\n /** Bottom border styling */\n bottom?: BorderOptions;\n /** Left border styling */\n left?: BorderOptions;\n}\n","/**\n * Page margin module for WordprocessingML section properties.\n *\n * Defines page margins for document sections.\n *\n * Reference: http://officeopenxml.com/WPsectionPr.php\n *\n * @module\n */\nimport { convertToTwip } from \"@office-open/core\";\nimport type { PositiveUniversalMeasure, UniversalMeasure } from \"@office-open/core\";\n\n/**\n * Options for configuring page margins.\n *\n * All measurements are in twips (1/20th of a point) or universal measure.\n *\n * @property top - Top margin\n * @property right - Right margin\n * @property bottom - Bottom margin\n * @property left - Left margin\n * @property header - Header margin (distance from top of page to header)\n * @property footer - Footer margin (distance from bottom of page to footer)\n * @property gutter - Gutter margin for binding\n */\nexport interface PageMarginProperties {\n /** Top margin in twips or universal measure */\n top?: number | UniversalMeasure;\n /** Right margin in twips or universal measure */\n right?: number | PositiveUniversalMeasure;\n /** Bottom margin in twips or universal measure */\n bottom?: number | UniversalMeasure;\n /** Left margin in twips or universal measure */\n left?: number | PositiveUniversalMeasure;\n /** Header margin (distance from top of page to header) in twips or universal measure */\n header?: number | PositiveUniversalMeasure;\n /** Footer margin (distance from bottom of page to footer) in twips or universal measure */\n footer?: number | PositiveUniversalMeasure;\n /** Gutter margin for binding in twips or universal measure */\n gutter?: number | PositiveUniversalMeasure;\n}\n\n/**\n * Creates page margins (pgMar) for a document section.\n *\n * This element specifies the page margins for all pages in a section,\n * including top, bottom, left, right, header, footer, and gutter margins.\n *\n * Reference: http://officeopenxml.com/WPsectionPr.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_PageMar\">\n * <xsd:attribute name=\"top\" type=\"ST_SignedTwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"right\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"bottom\" type=\"ST_SignedTwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"left\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"header\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"footer\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * <xsd:attribute name=\"gutter\" type=\"s:ST_TwipsMeasure\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Create page margins with 1 inch margins (1440 twips = 1 inch)\n * createPageMargin(1440, 1440, 1440, 1440, 720, 720, 0);\n * ```\n */\nexport const createPageMargin = (\n top: number | UniversalMeasure,\n right: number | PositiveUniversalMeasure,\n bottom: number | UniversalMeasure,\n left: number | PositiveUniversalMeasure,\n header: number | PositiveUniversalMeasure,\n footer: number | PositiveUniversalMeasure,\n gutter: number | PositiveUniversalMeasure,\n): string =>\n `<w:pgMar w:bottom=\"${convertToTwip(bottom)}\" w:footer=\"${convertToTwip(footer)}\" w:gutter=\"${convertToTwip(gutter)}\" w:header=\"${convertToTwip(header)}\" w:left=\"${convertToTwip(left)}\" w:right=\"${convertToTwip(right)}\" w:top=\"${convertToTwip(top)}\"/>`;\n","import { convertToTwip, decimalNumber } from \"@office-open/core\";\nimport type { PositiveUniversalMeasure } from \"@office-open/core\";\nimport { element } from \"@office-open/xml\";\n\n/**\n * This simple type specifies when the line numbering in the parent section shall be reset to its restart value. The line numbering increments for each line (even if the line number itself is not displayed) until it reaches the restart point specified by this element.\n *\n * Reference: https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_ST_LineNumberRestart_topic_ID0EUS42.html\n *\n * ## XSD Schema\n *\n * ```xml\n * <xsd:simpleType name=\"ST_LineNumberRestart\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"newPage\"/>\n * <xsd:enumeration value=\"newSection\"/>\n * <xsd:enumeration value=\"continuous\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const LineNumberRestartFormat = {\n /**\n * ## Restart Line Numbering on Each Page\n *\n * Specifies that line numbering for the parent section shall restart to the starting value whenever a new page is displayed.\n */\n NEW_PAGE: \"newPage\",\n /**\n * ## Restart Line Numbering for Each Section\n *\n * Specifies that line numbering for the parent section shall restart to the starting value whenever the parent begins.\n */\n NEW_SECTION: \"newSection\",\n /**\n * ## Continue Line Numbering From Previous Section\n *\n * Specifies that line numbering for the parent section shall continue from the line numbering from the end of the previous section, if any.\n */\n CONTINUOUS: \"continuous\",\n} as const;\n\nexport interface LineNumberProperties {\n /**\n * Specifies the line number increments to be displayed in the current document.\n *\n * Although each line has an associated line number, only lines which are an even multiple of this value shall be displayed.\n *\n * ### Example\n *\n * ```xml\n * <w:lnNumType … w:countBy=\"5\"/>\n * ```\n *\n * This setting ensures that only lines whose number is a multiple of (e.g. 5, 10, and 15) will have a line number displayed. ]\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n countBy?: number;\n /**\n * ## Line Numbering Starting Value\n *\n * Specifies the starting value used for the first line whenever the line numbering is restarted by use of the `restart` attribute.\n *\n * ### Example\n *\n * ```xml\n * <w:lnNumType w:start=\"3\" w:countBy=\"5\"/>\n * ```\n *\n * The `start` attribute specifies that line numbers shall be counted starting from the number 3.\n *\n * The possible values for this attribute are defined by the ST_DecimalNumber simple type (§2.18.16).\n */\n start?: number;\n /**\n * ## Line Numbering Restart Setting\n *\n * Specifies when the line numbering in this section shall be reset to the line number specified by the `start` attribute's value.\n *\n * The line numbering increments for each line (even if it is not displayed) until it reaches the restart point specified by this element.\n *\n * ### Example\n *\n * ```xml\n * <w:sectPr>\n * ...\n * <w:lnNumType w:restart=\"newPage\" ... />\n * </w:sectPr>\n * ```\n *\n * The value of `newPage` specifies that the line numbers shall restart at the top of each page to the value specified by the `start` attribute. In this case, `newPage` is the default, so this value could have been omitted entirely.\n *\n * The possible values for this attribute are defined by the ST_LineNumberRestart simple type (§2.18.54).\n */\n restart?: (typeof LineNumberRestartFormat)[keyof typeof LineNumberRestartFormat];\n /**\n * Specifies the distance between the text margin and the edge of any line numbers appearing in that section.\n *\n * ```xml\n * <w:lnNumType ... w:distance=\"720\"/>\n * ```\n *\n * The possible values for this attribute are defined by the ST_TwipsMeasure simple type (§2.18.105).\n */\n distance?: number | PositiveUniversalMeasure;\n}\n\n/**\n * This element specifies the settings for line numbering to be displayed before each column of text in this section in the document.\n *\n * References:\n * - https://c-rex.net/samples/ooxml/e1/Part4/OOXML_P4_DOCX_lnNumType_topic_ID0EVRAT.html\n * - http://officeopenxml.com/WPsectionLineNumbering.php\n *\n * ## XSD Schema\n *\n * ```xml\n * <xsd:complexType name=\"CT_LineNumber\">\n * <xsd:attribute name=\"countBy\" type=\"ST_DecimalNumber\" use=\"optional\"/>\n * <xsd:attribute name=\"start\" type=\"ST_DecimalNumber\" use=\"optional\" default=\"1\"/>\n * <xsd:attribute name=\"distance\" type=\"s:ST_TwipsMeasure\" use=\"optional\"/>\n * <xsd:attribute name=\"restart\" type=\"ST_LineNumberRestart\" use=\"optional\" default=\"newPage\"/>\n * </xsd:complexType>\n * ```\n */\nexport const createLineNumberType = ({\n countBy,\n start,\n restart,\n distance,\n}: LineNumberProperties): string =>\n element(\"w:lnNumType\", {\n \"w:countBy\": countBy === undefined ? undefined : decimalNumber(countBy),\n \"w:distance\": distance === undefined ? undefined : convertToTwip(distance),\n \"w:restart\": restart,\n \"w:start\": start === undefined ? undefined : decimalNumber(start),\n });\n","/**\n * Section type module for WordprocessingML section properties.\n *\n * Defines how a section begins relative to the previous section.\n *\n * Reference: http://officeopenxml.com/WPsection.php\n *\n * @module\n */\n/**\n * Specifies the type of section break.\n *\n * This determines where the section begins relative to the previous section.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:simpleType name=\"ST_SectionMark\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"nextPage\"/>\n * <xsd:enumeration value=\"nextColumn\"/>\n * <xsd:enumeration value=\"continuous\"/>\n * <xsd:enumeration value=\"evenPage\"/>\n * <xsd:enumeration value=\"oddPage\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @publicApi\n */\nexport const SectionType = {\n /** Section begins on the next page */\n NEXT_PAGE: \"nextPage\",\n /** Section begins on the next column */\n NEXT_COLUMN: \"nextColumn\",\n /** Section begins immediately following the previous section */\n CONTINUOUS: \"continuous\",\n /** Section begins on the next even-numbered page */\n EVEN_PAGE: \"evenPage\",\n /** Section begins on the next odd-numbered page */\n ODD_PAGE: \"oddPage\",\n} as const;\n\n/**\n * Creates section type (type) for a document section.\n *\n * This element specifies the type of section break, which determines\n * where the new section begins relative to the previous section.\n *\n * Reference: http://officeopenxml.com/WPsection.php\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_SectType\">\n * <xsd:attribute name=\"val\" type=\"ST_SectionMark\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * // Create a continuous section (no page break)\n * createSectionType(SectionType.CONTINUOUS);\n *\n * // Create a section that starts on next odd page\n * createSectionType(SectionType.ODD_PAGE);\n * ```\n */\nexport const createSectionType = (value: (typeof SectionType)[keyof typeof SectionType]): string =>\n `<w:type w:val=\"${value}\"/>`;\n","import { escapeXml } from \"@office-open/xml\";\nimport { documentNamespaceRecord } from \"@parts/document/document-attributes\";\nimport { AlignmentType } from \"@parts/paragraph\";\n/**\n * Factory module for creating default document styles.\n *\n * Creates styles matching Microsoft Word's default document template.\n * Pure string generation — no XmlComponent inheritance.\n *\n * Reference: http://officeopenxml.com/WPstyles.php\n *\n * @module\n */\nimport type { ParagraphStylePropertiesOptions } from \"@parts/paragraph/properties\";\nimport type { RunStylePropertiesOptions } from \"@parts/paragraph/run/properties\";\nimport {\n stringifyTableCellProperties,\n stringifyTableProperties,\n stringifyTableRowProperties,\n} from \"@parts/table/stringify\";\nimport type { TableCellPropertiesOptions } from \"@parts/table/table-cell/table-cell-properties\";\nimport type { TablePropertiesOptions } from \"@parts/table/table-properties/table-properties\";\nimport type { TableRowPropertiesOptions } from \"@parts/table/table-row/table-row-properties\";\nimport { WidthType } from \"@parts/table/table-width\";\nimport { BorderStyle, type BorderOptions } from \"@shared/border\";\n\nimport { stringifyParagraphProperties, stringifyRunProperties } from \"../paragraph/stringify\";\nimport type { StylesOptions } from \"./styles\";\n\n// ── Style options interfaces ──\n\nexport interface DefaultStylesOptions {\n document?: DocumentDefaultsOptions;\n title?: ParagraphStyleOptions;\n subtitle?: ParagraphStyleOptions;\n heading1?: ParagraphStyleOptions;\n heading2?: ParagraphStyleOptions;\n heading3?: ParagraphStyleOptions;\n heading4?: ParagraphStyleOptions;\n heading5?: ParagraphStyleOptions;\n heading6?: ParagraphStyleOptions;\n heading7?: ParagraphStyleOptions;\n heading8?: ParagraphStyleOptions;\n heading9?: ParagraphStyleOptions;\n strong?: ParagraphStyleOptions;\n emphasis?: ParagraphStyleOptions;\n listParagraph?: ParagraphStyleOptions;\n quote?: ParagraphStyleOptions;\n intenseQuote?: ParagraphStyleOptions;\n hyperlink?: CharacterStyleOptions;\n footnoteReference?: CharacterStyleOptions;\n footnoteText?: ParagraphStyleOptions;\n footnoteTextChar?: CharacterStyleOptions;\n endnoteReference?: CharacterStyleOptions;\n endnoteText?: ParagraphStyleOptions;\n endnoteTextChar?: CharacterStyleOptions;\n}\n\nexport interface DocumentDefaultsOptions {\n paragraph?: ParagraphStylePropertiesOptions | null;\n run?: RunStylePropertiesOptions | null;\n}\n\nexport interface StyleOptions {\n name?: string;\n aliases?: string;\n basedOn?: string;\n next?: string;\n link?: string;\n autoRedefine?: boolean;\n uiPriority?: number;\n semiHidden?: boolean;\n unhideWhenUsed?: boolean;\n quickFormat?: boolean;\n locked?: boolean;\n personal?: boolean;\n personalCompose?: boolean;\n personalReply?: boolean;\n /** CT_Style w:hidden — style hidden from the UI (CT_OnOff). */\n hidden?: boolean;\n /** CT_Style w:rsid — revision save id (CT_LongHexNumber, hex string verbatim). */\n rsid?: string;\n /** CT_Style @w:default — the default style for its type (CT_OnOff). */\n default?: boolean;\n /** CT_Style @w:customStyle — a user-defined custom style (CT_OnOff). */\n customStyle?: boolean;\n}\n\nexport type ParagraphStyleOptions = {\n paragraph?: ParagraphStylePropertiesOptions;\n run?: RunStylePropertiesOptions;\n} & StyleOptions & { id?: string };\n\nexport type CharacterStyleOptions = {\n run?: RunStylePropertiesOptions;\n} & StyleOptions & { id?: string };\n\n// ── String builders ──\n\n/**\n * Build CT_Style style-level children (name…rsid), shared by paragraph/character/table styles.\n * Order follows CT_Style sequence: name, aliases, basedOn, next, link, autoRedefine, hidden,\n * uiPriority, semiHidden, unhideWhenUsed, qFormat, locked, personal, personalCompose,\n * personalReply, rsid.\n */\nfunction stringifyStyleLevelChildren(opts: StyleOptions & { id?: string }): string {\n const parts: string[] = [`<w:name w:val=\"${escapeXml(opts.name ?? opts.id ?? \"\")}\"/>`];\n if (opts.aliases) parts.push(`<w:aliases w:val=\"${escapeXml(opts.aliases)}\"/>`);\n if (opts.basedOn) parts.push(`<w:basedOn w:val=\"${escapeXml(opts.basedOn)}\"/>`);\n if (opts.next) parts.push(`<w:next w:val=\"${escapeXml(opts.next)}\"/>`);\n if (opts.link) parts.push(`<w:link w:val=\"${escapeXml(opts.link)}\"/>`);\n if (opts.autoRedefine) parts.push(\"<w:autoRedefine/>\");\n if (opts.hidden) parts.push(\"<w:hidden/>\");\n if (opts.uiPriority !== undefined) parts.push(`<w:uiPriority w:val=\"${opts.uiPriority}\"/>`);\n if (opts.semiHidden) parts.push(\"<w:semiHidden/>\");\n if (opts.unhideWhenUsed) parts.push(\"<w:unhideWhenUsed/>\");\n if (opts.quickFormat) parts.push(\"<w:qFormat/>\");\n if (opts.locked) parts.push(\"<w:locked/>\");\n if (opts.personal) parts.push(\"<w:personal/>\");\n if (opts.personalCompose) parts.push(\"<w:personalCompose/>\");\n if (opts.personalReply) parts.push(\"<w:personalReply/>\");\n if (opts.rsid) parts.push(`<w:rsid w:val=\"${opts.rsid}\"/>`);\n return parts.join(\"\");\n}\n\n/**\n * Build the `<w:style>` opening tag: type/styleId plus the optional w:default\n * and w:customStyle element attributes (CT_Style). Shared by paragraph/\n * character/table styles.\n */\nfunction styleOpenTag(\n type: string,\n opts: { id?: string; default?: boolean; customStyle?: boolean },\n): string {\n let attrs = ` w:type=\"${type}\" w:styleId=\"${escapeXml(opts.id ?? \"\")}\"`;\n if (opts.default) attrs += ' w:default=\"1\"';\n if (opts.customStyle) attrs += ' w:customStyle=\"1\"';\n return `<w:style${attrs}>`;\n}\n\n/** Build `<w:style>` XML for a paragraph style. */\nexport function stringifyParagraphStyle(\n opts: StyleOptions & {\n id: string;\n paragraph?: ParagraphStylePropertiesOptions;\n run?: RunStylePropertiesOptions;\n },\n): string {\n const children: string[] = [stringifyStyleLevelChildren(opts)];\n\n const pPr = stringifyParagraphProperties(opts.paragraph).xml;\n if (pPr) children.push(pPr);\n const rPr = stringifyRunProperties(opts.run);\n if (rPr) children.push(rPr);\n\n return `${styleOpenTag(\"paragraph\", opts)}${children.join(\"\")}</w:style>`;\n}\n\n/** Build `<w:style>` XML for a character style. */\nexport function stringifyCharacterStyle(\n opts: StyleOptions & {\n id: string;\n run?: RunStylePropertiesOptions;\n },\n): string {\n const children: string[] = [stringifyStyleLevelChildren(opts)];\n\n const rPr = stringifyRunProperties(opts.run);\n if (rPr) children.push(rPr);\n\n return `${styleOpenTag(\"character\", opts)}${children.join(\"\")}</w:style>`;\n}\n\n// ── Table style (CT_Style type=\"table\") ──\n\n/** ST_TblStyleOverrideType — OOXML tokens verbatim (CT_TblStylePr @w:type). */\nexport type TableStyleOverrideType =\n | \"wholeTable\"\n | \"firstRow\"\n | \"lastRow\"\n | \"firstCol\"\n | \"lastCol\"\n | \"band1Vert\"\n | \"band2Vert\"\n | \"band1Horz\"\n | \"band2Horz\"\n | \"neCell\"\n | \"nwCell\"\n | \"seCell\"\n | \"swCell\";\n\n/** Conditional table style format (CT_TblStylePr). */\nexport interface ConditionalTableStyleOptions {\n /** Which region this format applies to (CT_TblStylePr @w:type, required). */\n type: TableStyleOverrideType;\n /** Paragraph properties (CT_PPrGeneral). */\n paragraph?: ParagraphStylePropertiesOptions;\n /** Run properties (CT_RPr). */\n run?: RunStylePropertiesOptions;\n /** Table properties (CT_TblPrBase). */\n table?: TablePropertiesOptions;\n /** Table row properties (CT_TrPr). */\n row?: TableRowPropertiesOptions;\n /** Table cell properties (CT_TcPr). */\n cell?: TableCellPropertiesOptions;\n}\n\n/** Table style (CT_Style type=\"table\"). */\nexport type TableStyleOptions = {\n /** Paragraph properties (CT_PPrGeneral). */\n paragraph?: ParagraphStylePropertiesOptions;\n /** Run properties (CT_RPr). */\n run?: RunStylePropertiesOptions;\n /** Table properties (CT_TblPrBase). */\n table?: TablePropertiesOptions;\n /** Table row properties (CT_TrPr). */\n row?: TableRowPropertiesOptions;\n /** Table cell properties (CT_TcPr). */\n cell?: TableCellPropertiesOptions;\n /** Conditional formats per region (CT_TblStylePr, unbounded). */\n conditionalFormats?: ConditionalTableStyleOptions[];\n} & StyleOptions & { id: string };\n\n/** Numbering style (CT_Style type=\"numbering\"). */\nexport type NumberingStyleOptions = {\n /** Paragraph properties (CT_PPrGeneral — usually carries numPr). */\n paragraph?: ParagraphStylePropertiesOptions;\n /** Run properties (CT_RPr). */\n run?: RunStylePropertiesOptions;\n} & StyleOptions & { id: string };\n\n/** Build `<w:tblStylePr>` XML for a conditional table style format. */\nexport function stringifyConditionalTableStyle(opts: ConditionalTableStyleOptions): string {\n const children: string[] = [];\n // CT_TblStylePr child order: pPr, rPr, tblPr, trPr, tcPr\n const pPr = stringifyParagraphProperties(opts.paragraph).xml;\n if (pPr) children.push(pPr);\n const rPr = stringifyRunProperties(opts.run);\n if (rPr) children.push(rPr);\n if (opts.table) {\n const tblPr = stringifyTableProperties(opts.table);\n if (tblPr) children.push(tblPr);\n }\n if (opts.row) {\n const trPr = stringifyTableRowProperties(opts.row);\n if (trPr) children.push(trPr);\n }\n if (opts.cell) {\n const tcPr = stringifyTableCellProperties(opts.cell);\n if (tcPr) children.push(tcPr);\n }\n return `<w:tblStylePr w:type=\"${opts.type}\">${children.join(\"\")}</w:tblStylePr>`;\n}\n\n/** Build `<w:style type=\"table\">` XML for a table style. */\nexport function stringifyTableStyle(opts: TableStyleOptions): string {\n const children: string[] = [stringifyStyleLevelChildren(opts)];\n // CT_Style child order: style-level, pPr, rPr, tblPr, trPr, tcPr, tblStylePr[]\n const pPr = stringifyParagraphProperties(opts.paragraph).xml;\n if (pPr) children.push(pPr);\n const rPr = stringifyRunProperties(opts.run);\n if (rPr) children.push(rPr);\n if (opts.table) {\n const tblPr = stringifyTableProperties(opts.table);\n if (tblPr) children.push(tblPr);\n }\n if (opts.row) {\n const trPr = stringifyTableRowProperties(opts.row);\n if (trPr) children.push(trPr);\n }\n if (opts.cell) {\n const tcPr = stringifyTableCellProperties(opts.cell);\n if (tcPr) children.push(tcPr);\n }\n for (const cf of opts.conditionalFormats ?? []) {\n children.push(stringifyConditionalTableStyle(cf));\n }\n return `${styleOpenTag(\"table\", opts)}${children.join(\"\")}</w:style>`;\n}\n\n/** Build `<w:style type=\"numbering\">` XML for a numbering style. */\nexport function stringifyNumberingStyle(opts: NumberingStyleOptions): string {\n const children: string[] = [stringifyStyleLevelChildren(opts)];\n // CT_Style child order: style-level, pPr, rPr\n const pPr = stringifyParagraphProperties(opts.paragraph).xml;\n if (pPr) children.push(pPr);\n const rPr = stringifyRunProperties(opts.run);\n if (rPr) children.push(rPr);\n return `${styleOpenTag(\"numbering\", opts)}${children.join(\"\")}</w:style>`;\n}\n\n/** Resolve a user override for heading level N (1-9) from default styles options. */\nfunction headingOverride(\n options: DefaultStylesOptions,\n level: number,\n): ParagraphStyleOptions | undefined {\n switch (level) {\n case 1:\n return options.heading1;\n case 2:\n return options.heading2;\n case 3:\n return options.heading3;\n case 4:\n return options.heading4;\n case 5:\n return options.heading5;\n case 6:\n return options.heading6;\n case 7:\n return options.heading7;\n case 8:\n return options.heading8;\n case 9:\n return options.heading9;\n default:\n return undefined;\n }\n}\n\n/** Word's default `<w:rPrDefault>` — theme fonts, kern, 11pt, ligatures. Injected\n * for fresh documents (no structured docDefaults provided) to mirror Word's\n * Normal.dotx. On round-trip the structured form is used instead. */\nconst WORD_DEFAULT_RPR_DEFAULT =\n `<w:rPrDefault><w:rPr>` +\n `<w:rFonts w:asciiTheme=\"minorHAnsi\" w:eastAsiaTheme=\"minorEastAsia\" w:hAnsiTheme=\"minorHAnsi\" w:cstheme=\"minorBidi\"/>` +\n `<w:kern w:val=\"2\"/>` +\n `<w:sz w:val=\"22\"/><w:szCs w:val=\"24\"/>` +\n `<w:lang w:val=\"en-US\" w:eastAsia=\"zh-CN\" w:bidi=\"ar-SA\"/>` +\n `<w14:ligatures w14:val=\"standardContextual\"/>` +\n `</w:rPr></w:rPrDefault>`;\n\n/** Word's default `<w:pPrDefault>` — widow/orphan control + 8pt after / 1.16 line.\n * Injected for fresh documents only. */\nconst WORD_DEFAULT_PPR_DEFAULT =\n `<w:pPrDefault><w:pPr>` +\n `<w:widowControl/>` +\n `<w:spacing w:after=\"160\" w:line=\"278\" w:lineRule=\"auto\"/>` +\n `</w:pPr></w:pPrDefault>`;\n\n/**\n * Build `<w:docDefaults>` XML from a structured {@link DocumentDefaultsOptions}.\n *\n * Three states per run/paragraph:\n * - object → structured child element\n * - null → explicit empty tag (`<w:pPrDefault/>`) — the source declared \"no\n * defaults here\", so Word does NOT inject its own spacing. Distinct\n * from absence (ECMA-376: empty pPrDefault suppresses default\n * spacing; a missing pPrDefault is application-defined).\n * - undefined → field is missing. On fresh generation (`injectDefaults`) we\n * mirror Word's Normal.dotx; on round-trip we omit the element\n * to preserve the source's \"this default category is absent\".\n */\nexport function stringifyDocDefaults(opts: DocumentDefaultsOptions, injectDefaults = true): string {\n const children: string[] = [];\n\n // rPrDefault\n if (opts.run) {\n const rPr = stringifyRunProperties(opts.run);\n children.push(rPr ? `<w:rPrDefault>${rPr}</w:rPrDefault>` : `<w:rPrDefault/>`);\n } else if (opts.run === null) {\n children.push(`<w:rPrDefault/>`);\n } else if (injectDefaults) {\n children.push(WORD_DEFAULT_RPR_DEFAULT);\n }\n\n // pPrDefault\n if (opts.paragraph) {\n const pPr = stringifyParagraphProperties(opts.paragraph).xml;\n children.push(pPr ? `<w:pPrDefault>${pPr}</w:pPrDefault>` : `<w:pPrDefault/>`);\n } else if (opts.paragraph === null) {\n children.push(`<w:pPrDefault/>`);\n } else if (injectDefaults) {\n children.push(WORD_DEFAULT_PPR_DEFAULT);\n }\n\n return `<w:docDefaults>${children.join(\"\")}</w:docDefaults>`;\n}\n\n// ── Factory ──\n\nlet cachedDefaultStyles: StylesOptions | null = null;\n\n/**\n * Factory for creating default document styles.\n *\n * Creates styles matching Microsoft Word's default document template.\n * Pure string generation — no XmlComponent inheritance.\n */\nexport class DefaultStylesFactory {\n public newInstance(options: DefaultStylesOptions = {}): StylesOptions {\n if (Object.keys(options).length === 0) {\n if (!cachedDefaultStyles) {\n cachedDefaultStyles = this.build({});\n }\n return cachedDefaultStyles;\n }\n return this.build(options);\n }\n\n private build(options: DefaultStylesOptions): StylesOptions {\n // importedStyles carries only docDefaults + latentStyles verbatim. Every\n // builtin w:style is emitted as a structured Options object so HTML renderers\n // can consume style attributes directly.\n const importedStyles: { _raw: string }[] = [];\n const paragraphStyles: (ParagraphStyleOptions & { id: string })[] = [];\n const characterStyles: (CharacterStyleOptions & { id: string })[] = [];\n const tableStyles: TableStyleOptions[] = [];\n const numberingStyles: NumberingStyleOptions[] = [];\n\n // XML namespace attributes for styles root element (matching Word exactly)\n const initialAttributes: Record<string, string> = {\n ...documentNamespaceRecord([\"mc\", \"r\", \"w\", \"w14\", \"w15\"]),\n \"mc:Ignorable\": \"w14 w15\",\n };\n\n importedStyles.push({ _raw: stringifyDocDefaults(options.document ?? {}) });\n\n // Latent styles - complete list from Word's default template\n // Only include styles that are NOT explicitly defined below\n importedStyles.push({\n _raw:\n `<w:latentStyles w:defLockedState=\"0\" w:defUIPriority=\"99\" w:defSemiHidden=\"0\" w:defUnhideWhenUsed=\"0\" w:defQFormat=\"0\" w:count=\"376\">` +\n `<w:lsdException w:name=\"Normal\" w:uiPriority=\"0\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 1\" w:uiPriority=\"9\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 2\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 3\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 4\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 5\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 6\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 7\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 8\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"heading 9\" w:semiHidden=\"1\" w:uiPriority=\"9\" w:unhideWhenUsed=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"Default Paragraph Font\" w:semiHidden=\"1\" w:uiPriority=\"1\" w:unhideWhenUsed=\"1\"/>` +\n `<w:lsdException w:name=\"Normal Table\" w:semiHidden=\"1\" w:uiPriority=\"99\" w:unhideWhenUsed=\"1\"/>` +\n `<w:lsdException w:name=\"No List\" w:semiHidden=\"1\" w:uiPriority=\"99\" w:unhideWhenUsed=\"1\"/>` +\n `<w:lsdException w:name=\"Subtitle\" w:uiPriority=\"11\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"Strong\" w:uiPriority=\"22\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"Emphasis\" w:uiPriority=\"20\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"Hyperlink\" w:semiHidden=\"1\" w:unhideWhenUsed=\"1\"/>` +\n `<w:lsdException w:name=\"FollowedHyperlink\" w:semiHidden=\"1\" w:unhideWhenUsed=\"1\"/>` +\n `<w:lsdException w:name=\"No Spacing\" w:uiPriority=\"1\" w:qFormat=\"1\"/>` +\n `<w:lsdException w:name=\"Revision\" w:semiHidden=\"1\"/>` +\n `</w:latentStyles>`,\n });\n\n // Built-in styles required by Word\n // Normal paragraph style (default for paragraphs)\n paragraphStyles.push({\n id: \"Normal\",\n name: \"Normal\",\n default: true,\n quickFormat: true,\n });\n\n // heading 1-9 styles with proper formatting\n const headings = [\n {\n id: \"Heading1\",\n name: \"heading 1\",\n link: \"Heading1Char\",\n sz: 48,\n before: 480,\n after: 80,\n outlineLvl: 0,\n },\n {\n id: \"Heading2\",\n name: \"heading 2\",\n link: \"Heading2Char\",\n sz: 40,\n before: 160,\n after: 80,\n outlineLvl: 1,\n },\n {\n id: \"Heading3\",\n name: \"heading 3\",\n link: \"Heading3Char\",\n sz: 32,\n before: 160,\n after: 80,\n outlineLvl: 2,\n },\n {\n id: \"Heading4\",\n name: \"heading 4\",\n link: \"Heading4Char\",\n sz: 28,\n before: 80,\n after: 40,\n outlineLvl: 3,\n },\n {\n id: \"Heading5\",\n name: \"heading 5\",\n link: \"Heading5Char\",\n sz: 24,\n before: 80,\n after: 40,\n outlineLvl: 4,\n },\n {\n id: \"Heading6\",\n name: \"heading 6\",\n link: \"Heading6Char\",\n sz: undefined,\n before: 40,\n after: 0,\n outlineLvl: 5,\n },\n {\n id: \"Heading7\",\n name: \"heading 7\",\n link: \"Heading7Char\",\n sz: undefined,\n before: 40,\n after: 0,\n outlineLvl: 6,\n },\n {\n id: \"Heading8\",\n name: \"heading 8\",\n link: \"Heading8Char\",\n sz: undefined,\n before: undefined,\n after: 0,\n outlineLvl: 7,\n },\n {\n id: \"Heading9\",\n name: \"heading 9\",\n link: \"Heading9Char\",\n sz: undefined,\n before: undefined,\n after: 0,\n outlineLvl: 8,\n },\n ];\n\n for (const [headingIdx, h] of headings.entries()) {\n const outlineLvl = h.outlineLvl;\n const headingOverrideOpts = headingOverride(options, headingIdx + 1);\n if (headingOverrideOpts) {\n // User-defined heading overrides the built-in entirely.\n paragraphStyles.push({\n id: h.id,\n name: headingOverrideOpts.name ?? h.name,\n basedOn: headingOverrideOpts.basedOn ?? \"Normal\",\n next: headingOverrideOpts.next ?? \"Normal\",\n link: headingOverrideOpts.link ?? h.link,\n uiPriority: headingOverrideOpts.uiPriority ?? 9,\n quickFormat: headingOverrideOpts.quickFormat ?? true,\n semiHidden: headingOverrideOpts.semiHidden,\n unhideWhenUsed: headingOverrideOpts.unhideWhenUsed,\n paragraph: { outlineLevel: headingIdx, ...headingOverrideOpts.paragraph },\n run: headingOverrideOpts.run,\n });\n characterStyles.push({\n id: h.link,\n name: `${h.name} Char`,\n basedOn: \"DefaultParagraphFont\",\n link: h.id,\n run: headingOverrideOpts.run,\n });\n continue;\n }\n\n // heading 1-6 use accent1 color + major theme fonts; 7-9 use text1 color.\n const accentRange = outlineLvl < 6;\n const runProps: RunStylePropertiesOptions = {\n font: accentRange\n ? {\n asciiTheme: \"majorHAnsi\",\n eastAsiaTheme: \"majorEastAsia\",\n hAnsiTheme: \"majorHAnsi\",\n complexScriptTheme: \"majorBidi\",\n }\n : { complexScriptTheme: \"majorBidi\" },\n color: accentRange\n ? { val: \"0F4761\", themeColor: \"accent1\", themeShade: \"BF\" }\n : { val: \"595959\", themeColor: \"text1\", themeTint: \"A6\" },\n };\n if (h.sz) {\n const sizePt = h.sz / 2; // half-points → points\n runProps.size = sizePt;\n runProps.sizeComplexScript = sizePt;\n }\n // heading 6-9 have bold\n if (outlineLvl >= 5) {\n runProps.bold = true;\n runProps.boldComplexScript = true;\n }\n\n paragraphStyles.push({\n id: h.id,\n name: h.name,\n basedOn: \"Normal\",\n next: \"Normal\",\n link: h.link,\n uiPriority: 9,\n semiHidden: outlineLvl > 0,\n unhideWhenUsed: outlineLvl > 0,\n quickFormat: true,\n paragraph: {\n keepNext: true,\n keepLines: true,\n spacing: {\n before: h.before,\n after: h.after,\n },\n outlineLevel: outlineLvl,\n },\n run: runProps,\n });\n\n // Linked character styles for headings\n characterStyles.push({\n id: h.link,\n name: `${h.name} Char`,\n basedOn: \"DefaultParagraphFont\",\n link: h.id,\n uiPriority: 9,\n semiHidden: outlineLvl > 0,\n run: runProps,\n });\n }\n\n // DefaultParagraphFont character style (default for runs)\n characterStyles.push({\n id: \"DefaultParagraphFont\",\n name: \"Default Paragraph Font\",\n default: true,\n uiPriority: 1,\n semiHidden: true,\n unhideWhenUsed: true,\n });\n\n // Normal Table style (default for tables)\n tableStyles.push({\n id: \"NormalTable\",\n name: \"Normal Table\",\n default: true,\n uiPriority: 99,\n semiHidden: true,\n unhideWhenUsed: true,\n table: {\n indent: { size: 0, type: WidthType.DXA },\n cellMargin: {\n top: { size: 0, type: WidthType.DXA },\n left: { size: 108, type: WidthType.DXA },\n bottom: { size: 0, type: WidthType.DXA },\n right: { size: 108, type: WidthType.DXA },\n },\n },\n });\n\n // No List numbering style (default for numbering)\n numberingStyles.push({\n id: \"NoList\",\n name: \"No List\",\n default: true,\n uiPriority: 99,\n semiHidden: true,\n unhideWhenUsed: true,\n });\n\n // Title style (user override via options.title, else built-in default)\n if (options.title) {\n paragraphStyles.push({\n id: \"Title\",\n name: options.title.name ?? \"Title\",\n basedOn: options.title.basedOn ?? \"Normal\",\n next: options.title.next ?? \"Normal\",\n link: options.title.link ?? \"TitleChar\",\n uiPriority: options.title.uiPriority ?? 10,\n quickFormat: options.title.quickFormat ?? true,\n paragraph: options.title.paragraph,\n run: options.title.run,\n });\n characterStyles.push({\n id: \"TitleChar\",\n name: \"Title Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Title\",\n run: options.title.run,\n });\n } else {\n const titleRun: RunStylePropertiesOptions = {\n font: {\n asciiTheme: \"majorHAnsi\",\n eastAsiaTheme: \"majorEastAsia\",\n hAnsiTheme: \"majorHAnsi\",\n complexScriptTheme: \"majorBidi\",\n },\n characterSpacing: -10,\n kern: 14,\n size: 28,\n sizeComplexScript: 28,\n };\n paragraphStyles.push({\n id: \"Title\",\n name: \"Title\",\n basedOn: \"Normal\",\n next: \"Normal\",\n link: \"TitleChar\",\n uiPriority: 10,\n quickFormat: true,\n paragraph: {\n spacing: { after: 80, line: 240, lineRule: \"auto\" },\n contextualSpacing: true,\n alignment: AlignmentType.CENTER,\n },\n run: titleRun,\n });\n characterStyles.push({\n id: \"TitleChar\",\n name: \"Title Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Title\",\n uiPriority: 10,\n run: titleRun,\n });\n }\n\n // Subtitle style (user override via options.subtitle, else built-in default)\n if (options.subtitle) {\n paragraphStyles.push({\n id: \"Subtitle\",\n name: options.subtitle.name ?? \"Subtitle\",\n basedOn: options.subtitle.basedOn ?? \"Normal\",\n next: options.subtitle.next ?? \"Normal\",\n link: options.subtitle.link ?? \"SubtitleChar\",\n uiPriority: options.subtitle.uiPriority ?? 11,\n quickFormat: options.subtitle.quickFormat ?? true,\n paragraph: options.subtitle.paragraph,\n run: options.subtitle.run,\n });\n characterStyles.push({\n id: \"SubtitleChar\",\n name: \"Subtitle Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Subtitle\",\n run: options.subtitle.run,\n });\n } else {\n const subtitleRun: RunStylePropertiesOptions = {\n font: {\n asciiTheme: \"majorHAnsi\",\n eastAsiaTheme: \"majorEastAsia\",\n hAnsiTheme: \"majorHAnsi\",\n complexScriptTheme: \"majorBidi\",\n },\n color: { val: \"595959\", themeColor: \"text1\", themeTint: \"A6\" },\n characterSpacing: 15,\n size: 14,\n sizeComplexScript: 14,\n };\n paragraphStyles.push({\n id: \"Subtitle\",\n name: \"Subtitle\",\n basedOn: \"Normal\",\n next: \"Normal\",\n link: \"SubtitleChar\",\n uiPriority: 11,\n quickFormat: true,\n paragraph: { alignment: AlignmentType.CENTER },\n run: subtitleRun,\n });\n characterStyles.push({\n id: \"SubtitleChar\",\n name: \"Subtitle Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Subtitle\",\n uiPriority: 11,\n run: subtitleRun,\n });\n }\n\n // List Paragraph style (user override via options.listParagraph, else built-in default)\n if (options.listParagraph) {\n paragraphStyles.push({\n id: \"ListParagraph\",\n name: options.listParagraph.name ?? \"List Paragraph\",\n basedOn: options.listParagraph.basedOn ?? \"Normal\",\n uiPriority: options.listParagraph.uiPriority ?? 34,\n quickFormat: options.listParagraph.quickFormat ?? true,\n paragraph: options.listParagraph.paragraph,\n run: options.listParagraph.run,\n });\n } else {\n paragraphStyles.push({\n id: \"ListParagraph\",\n name: \"List Paragraph\",\n basedOn: \"Normal\",\n uiPriority: 34,\n quickFormat: true,\n paragraph: { indent: { left: 720 }, contextualSpacing: true },\n });\n }\n\n // Strong style — only emitted when the user provides a definition\n if (options.strong) {\n paragraphStyles.push({\n id: \"Strong\",\n name: options.strong.name ?? \"Strong\",\n basedOn: options.strong.basedOn ?? \"Normal\",\n next: options.strong.next ?? \"Normal\",\n quickFormat: options.strong.quickFormat ?? true,\n paragraph: options.strong.paragraph,\n run: options.strong.run,\n });\n }\n\n // Emphasis style — only emitted when the user provides a definition\n if (options.emphasis) {\n paragraphStyles.push({\n id: \"Emphasis\",\n name: options.emphasis.name ?? \"Emphasis\",\n basedOn: options.emphasis.basedOn ?? \"Normal\",\n next: options.emphasis.next ?? \"Normal\",\n quickFormat: options.emphasis.quickFormat ?? true,\n paragraph: options.emphasis.paragraph,\n run: options.emphasis.run,\n });\n }\n\n // Quote style (user override via options.quote, else built-in default)\n const quoteRun: RunStylePropertiesOptions = {\n italic: true,\n italicComplexScript: true,\n color: { val: \"404040\", themeColor: \"text1\", themeTint: \"BF\" },\n };\n if (options.quote) {\n paragraphStyles.push({\n id: \"Quote\",\n name: options.quote.name ?? \"Quote\",\n basedOn: options.quote.basedOn ?? \"Normal\",\n next: options.quote.next ?? \"Normal\",\n link: options.quote.link ?? \"QuoteChar\",\n uiPriority: options.quote.uiPriority ?? 29,\n quickFormat: options.quote.quickFormat ?? true,\n paragraph: options.quote.paragraph,\n run: options.quote.run,\n });\n characterStyles.push({\n id: \"QuoteChar\",\n name: \"Quote Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Quote\",\n run: options.quote.run,\n });\n } else {\n paragraphStyles.push({\n id: \"Quote\",\n name: \"Quote\",\n basedOn: \"Normal\",\n next: \"Normal\",\n link: \"QuoteChar\",\n uiPriority: 29,\n quickFormat: true,\n paragraph: { spacing: { before: 160 }, alignment: AlignmentType.CENTER },\n run: quoteRun,\n });\n characterStyles.push({\n id: \"QuoteChar\",\n name: \"Quote Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"Quote\",\n uiPriority: 29,\n run: quoteRun,\n });\n }\n\n // Intense Quote style + linked character style (built-in defaults)\n const intenseQuoteRun: RunStylePropertiesOptions = {\n italic: true,\n italicComplexScript: true,\n color: { val: \"0F4761\", themeColor: \"accent1\", themeShade: \"BF\" },\n };\n const intenseQuoteBorder: BorderOptions = {\n style: BorderStyle.SINGLE,\n size: 4,\n space: 10,\n color: \"0F4761\",\n themeColor: \"accent1\",\n themeShade: \"BF\",\n };\n paragraphStyles.push({\n id: \"IntenseQuote\",\n name: \"Intense Quote\",\n basedOn: \"Normal\",\n next: \"Normal\",\n link: \"IntenseQuoteChar\",\n uiPriority: 30,\n quickFormat: true,\n paragraph: {\n border: { top: intenseQuoteBorder, bottom: intenseQuoteBorder },\n spacing: { before: 360, after: 360 },\n indent: { left: 864, right: 864 },\n alignment: AlignmentType.CENTER,\n },\n run: intenseQuoteRun,\n });\n characterStyles.push({\n id: \"IntenseQuoteChar\",\n name: \"Intense Quote Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"IntenseQuote\",\n uiPriority: 30,\n run: intenseQuoteRun,\n });\n\n // Hyperlink character style\n characterStyles.push({\n id: \"Hyperlink\",\n name: \"Hyperlink\",\n basedOn: \"DefaultParagraphFont\",\n semiHidden: true,\n unhideWhenUsed: true,\n run: { color: \"0563C1\", underline: { type: \"single\" } },\n ...options.hyperlink,\n });\n\n // Footnote Reference character style\n characterStyles.push({\n id: \"FootnoteReference\",\n name: \"footnote reference\",\n basedOn: \"DefaultParagraphFont\",\n semiHidden: true,\n unhideWhenUsed: true,\n run: { superScript: true },\n ...options.footnoteReference,\n });\n\n // Footnote Text paragraph style\n paragraphStyles.push({\n id: \"FootnoteText\",\n name: \"footnote text\",\n basedOn: \"Normal\",\n link: \"FootnoteTextChar\",\n semiHidden: true,\n uiPriority: 99,\n unhideWhenUsed: true,\n paragraph: { spacing: { after: 0, line: 240, lineRule: \"auto\" } },\n run: { size: 20 },\n ...options.footnoteText,\n });\n\n // Footnote Text Char character style\n characterStyles.push({\n id: \"FootnoteTextChar\",\n name: \"Footnote Text Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"FootnoteText\",\n semiHidden: true,\n run: { size: 20 },\n ...options.footnoteTextChar,\n });\n\n // Endnote Reference character style\n characterStyles.push({\n id: \"EndnoteReference\",\n name: \"endnote reference\",\n basedOn: \"DefaultParagraphFont\",\n semiHidden: true,\n unhideWhenUsed: true,\n run: { superScript: true },\n ...options.endnoteReference,\n });\n\n // Endnote Text paragraph style\n paragraphStyles.push({\n id: \"EndnoteText\",\n name: \"endnote text\",\n basedOn: \"Normal\",\n link: \"EndnoteTextChar\",\n semiHidden: true,\n uiPriority: 99,\n unhideWhenUsed: true,\n paragraph: { spacing: { after: 0, line: 240, lineRule: \"auto\" } },\n run: { size: 20 },\n ...options.endnoteText,\n });\n\n // Endnote Text Char character style\n characterStyles.push({\n id: \"EndnoteTextChar\",\n name: \"Endnote Text Char\",\n basedOn: \"DefaultParagraphFont\",\n link: \"EndnoteText\",\n semiHidden: true,\n run: { size: 20 },\n ...options.endnoteTextChar,\n });\n\n // Intense Reference character style\n characterStyles.push({\n id: \"IntenseReference\",\n name: \"Intense Reference\",\n basedOn: \"DefaultParagraphFont\",\n uiPriority: 32,\n quickFormat: true,\n run: {\n bold: true,\n boldComplexScript: true,\n smallCaps: true,\n color: { val: \"0F4761\", themeColor: \"accent1\", themeShade: \"BF\" },\n characterSpacing: 5,\n },\n });\n\n return {\n importedStyles,\n paragraphStyles,\n characterStyles,\n tableStyles,\n numberingStyles,\n initialAttributes,\n };\n }\n}\n","/**\n * Styles module for WordprocessingML documents.\n *\n * Pure collector — no XmlComponent inheritance.\n * Collects child elements as raw XML strings and serializes.\n *\n * Reference: http://officeopenxml.com/WPstyles.php\n *\n * @module\n */\nimport { attr, attrBool, attrNum, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type {\n ParagraphPropertiesOptions,\n ParagraphStylePropertiesOptions,\n} from \"@parts/paragraph/properties\";\nimport type { RunStylePropertiesOptions } from \"@parts/paragraph/run/properties\";\nimport { parseRunProperties } from \"@parts/paragraph/run/run-parse\";\nimport type {\n CharacterStyleOptions,\n ConditionalTableStyleOptions,\n DefaultStylesOptions,\n DocumentDefaultsOptions,\n NumberingStyleOptions,\n ParagraphStyleOptions,\n TableStyleOptions,\n} from \"@parts/styles/factory\";\nimport {\n stringifyCharacterStyle,\n stringifyNumberingStyle,\n stringifyParagraphStyle,\n stringifyTableStyle,\n} from \"@parts/styles/factory\";\nimport {\n parseTableCellPropertiesEl,\n parseTablePropertiesEl,\n parseTableRowPropertiesEl,\n} from \"@parts/table/descriptor\";\nimport type { TableCellPropertiesOptions } from \"@parts/table/table-cell/table-cell-properties\";\nimport type { TablePropertiesOptions } from \"@parts/table/table-properties/table-properties\";\nimport type { TableRowPropertiesOptions } from \"@parts/table/table-row/table-row-properties\";\n\nimport type { DocxReadContext } from \"../../context\";\nimport { stringifyElement } from \"../../util/stringify-element\";\n\n/**\n * Options for configuring document styles.\n */\nexport interface StylesOptions {\n /** Default styles for document, headings, and common elements */\n default?: DefaultStylesOptions;\n /** Initial namespace attributes for the styles root element */\n initialAttributes?: Record<string, string>;\n /** Array of raw XML style elements */\n importedStyles?: { _raw: string }[];\n /** Array of custom paragraph style definitions */\n paragraphStyles?: (ParagraphStyleOptions & { id: string })[];\n /** Array of custom character style definitions */\n characterStyles?: (CharacterStyleOptions & { id: string })[];\n /** Array of custom table style definitions (CT_Style type=\"table\"). */\n tableStyles?: TableStyleOptions[];\n /** Array of numbering style definitions (CT_Style type=\"numbering\"). */\n numberingStyles?: NumberingStyleOptions[];\n /**\n * Verbatim `<w:latentStyles>` XML (CT_LatentStyles + lsdException list).\n * When set (from parse), generate uses it in place of the default factory's\n * latent styles so the full latent-style table round-trips.\n */\n latentStylesXml?: string;\n /**\n * Verbatim `<w:docDefaults>` XML. When set (from parse), generate uses it in\n * place of the default factory's document defaults so rPrDefault/pPrDefault\n * round-trip byte-for-byte.\n */\n docDefaultsXml?: string;\n /**\n * @internal — set by parseStyleDefinitions to mark a round-trip origin so\n * context.ts consumes the parsed structured styles directly (no factory\n * builtin rebuild). Fresh generation never sets this.\n */\n roundTripped?: boolean;\n}\n\n/**\n * Extract the `w:styleId` from a raw `<w:style>` XML string, if present.\n *\n * Returns `undefined` for non-style elements (docDefaults / latentStyles),\n * whose raw XML carries no `w:styleId` attribute.\n */\nexport function extractStyleId(raw: string): string | undefined {\n const m = raw.match(/w:styleId=\"([^\"]+)\"/);\n return m ? m[1] : undefined;\n}\n\n/**\n * Represents the styles definitions in a WordprocessingML document.\n *\n * Pure collector — no XmlComponent inheritance.\n * Collects child elements as raw XML strings and serializes.\n */\nexport class Styles {\n private attributes: Record<string, string> = {};\n private parts: string[] = [];\n\n public constructor(options: StylesOptions) {\n if (options.initialAttributes) {\n this.attributes = options.initialAttributes;\n }\n\n // styleIds explicitly redefined via paragraphStyles/characterStyles take\n // precedence over importedStyles (user definitions override builtins) —\n // skip those imported entries to avoid duplicate styleId in the output.\n const customStyleIds = new Set<string>();\n for (const s of options.paragraphStyles ?? []) customStyleIds.add(s.id);\n for (const s of options.characterStyles ?? []) customStyleIds.add(s.id);\n for (const s of options.tableStyles ?? []) customStyleIds.add(s.id);\n\n if (options.importedStyles) {\n for (const style of options.importedStyles) {\n if (!style._raw) continue;\n if (customStyleIds.size > 0) {\n const id = extractStyleId(style._raw);\n if (id && customStyleIds.has(id)) continue;\n }\n this.parts.push(style._raw);\n }\n }\n\n if (options.paragraphStyles) {\n for (const style of options.paragraphStyles) {\n this.parts.push(stringifyParagraphStyle(style));\n }\n }\n\n if (options.characterStyles) {\n for (const style of options.characterStyles) {\n this.parts.push(stringifyCharacterStyle(style));\n }\n }\n\n if (options.tableStyles) {\n for (const style of options.tableStyles) {\n this.parts.push(stringifyTableStyle(style));\n }\n }\n\n if (options.numberingStyles) {\n for (const style of options.numberingStyles) {\n this.parts.push(stringifyNumberingStyle(style));\n }\n }\n }\n\n /**\n * Serialize to word/styles.xml content (with XML declaration).\n */\n public serialize(): string {\n const attrParts: string[] = [];\n for (const [k, v] of Object.entries(this.attributes)) {\n if (v !== undefined && v !== null) attrParts.push(` ${k}=\"${v}\"`);\n }\n\n const attrs = attrParts.join(\"\");\n const body = this.parts.join(\"\");\n return `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><w:styles${attrs}>${body}</w:styles>`;\n }\n}\n\n// ── Parse helpers (for descriptor pipeline) ──\n\n/**\n * Build a cache of style elements keyed by styleId.\n */\nexport function buildStyleCache(stylesEl: Element | undefined): Map<string, Element> {\n const cache = new Map<string, Element>();\n if (!stylesEl) return cache;\n\n for (const child of stylesEl.elements ?? []) {\n if (child.name !== \"w:style\") continue;\n const styleId = attr(child, \"w:styleId\");\n if (styleId) {\n cache.set(styleId, child);\n }\n }\n\n return cache;\n}\n\n/**\n * Build a cache of abstract numbering elements keyed by abstractNumId.\n */\nexport function buildNumberingCache(numberingEl: Element | undefined): Map<string, Element> {\n const cache = new Map<string, Element>();\n if (!numberingEl) return cache;\n\n for (const child of numberingEl.elements ?? []) {\n if (child.name !== \"w:abstractNum\") continue;\n const abstractNumId = attr(child, \"w:abstractNumId\");\n if (abstractNumId !== undefined) {\n cache.set(abstractNumId, child);\n }\n }\n\n return cache;\n}\n\n/** Parsed style — concrete shape (not Record) with a transient _type marker. */\ninterface ParsedStyle {\n _type?: string;\n id?: string;\n default?: boolean;\n customStyle?: boolean;\n name?: string;\n aliases?: string;\n basedOn?: string;\n next?: string;\n link?: string;\n uiPriority?: number;\n quickFormat?: boolean;\n semiHidden?: boolean;\n unhideWhenUsed?: boolean;\n autoRedefine?: boolean;\n locked?: boolean;\n personal?: boolean;\n personalCompose?: boolean;\n personalReply?: boolean;\n hidden?: boolean;\n rsid?: string;\n paragraph?: ParagraphStylePropertiesOptions;\n run?: RunStylePropertiesOptions;\n table?: Partial<TablePropertiesOptions>;\n row?: Partial<TableRowPropertiesOptions>;\n cell?: Partial<TableCellPropertiesOptions>;\n conditionalFormats?: ConditionalTableStyleOptions[];\n}\n\n/**\n * Parse w:styles element into StylesOptions.\n *\n * Skips built-in styles that DefaultStylesFactory already generates,\n * keeping only user-defined custom styles for round-trip fidelity.\n */\nexport function parseStyleDefinitions(\n el: Element,\n parseParagraphProperties: (\n el: Element,\n ctx: DocxReadContext,\n ) => Partial<ParagraphPropertiesOptions>,\n ctx: DocxReadContext,\n): StylesOptions | undefined {\n const opts: StylesOptions = {};\n const paragraphStyles: (ParagraphStyleOptions & { id: string })[] = [];\n const characterStyles: (CharacterStyleOptions & { id: string })[] = [];\n const tableStyles: TableStyleOptions[] = [];\n const numberingStyles: NumberingStyleOptions[] = [];\n\n for (const child of el.elements ?? []) {\n if (child.name === \"w:docDefaults\") {\n const defOpts = parseDocDefaults(child, parseParagraphProperties, ctx);\n if (defOpts) opts.default = defOpts;\n // Also capture verbatim for byte-exact round-trip (the structured path\n // may re-order or default-fill rPrDefault/pPrDefault children).\n opts.docDefaultsXml = stringifyElement(child);\n } else if (child.name === \"w:latentStyles\") {\n // Preserve the latent-style table verbatim so the full lsdException list\n // round-trips (the default factory only emits ~20 entries).\n opts.latentStylesXml = stringifyElement(child);\n } else if (child.name === \"w:style\") {\n const styleOpts = parseStyleElement(child, parseParagraphProperties, ctx);\n // Skip styles without a type or styleId — both are required to be useful.\n if (!styleOpts?._type || !styleOpts.id) continue;\n // All styles (builtin + custom) round-trip structured so HTML renderers\n // can consume style attributes directly. Builtin verbatim _raw is gone —\n // a customized builtin (e.g. recolored Heading1) round-trips losslessly\n // via parseStyleElement ↔ stringify*Style field symmetry.\n const type = styleOpts._type;\n delete styleOpts._type;\n\n if (type === \"table\") {\n tableStyles.push(styleOpts as TableStyleOptions);\n } else if (type === \"numbering\") {\n numberingStyles.push(styleOpts as NumberingStyleOptions);\n } else if (type === \"paragraph\") {\n paragraphStyles.push(styleOpts as ParagraphStyleOptions & { id: string });\n } else if (type === \"character\") {\n characterStyles.push(styleOpts as CharacterStyleOptions & { id: string });\n }\n }\n }\n\n if (paragraphStyles.length > 0) opts.paragraphStyles = paragraphStyles;\n if (characterStyles.length > 0) opts.characterStyles = characterStyles;\n if (tableStyles.length > 0) opts.tableStyles = tableStyles;\n if (numberingStyles.length > 0) opts.numberingStyles = numberingStyles;\n // Mark round-trip origin so context.ts consumes parsed structured styles\n // directly instead of rebuilding builtins via the factory.\n opts.roundTripped = true;\n\n return Object.keys(opts).length > 0 ? opts : undefined;\n}\n\nfunction parseDocDefaults(\n el: Element,\n parseParagraphProperties: (\n el: Element,\n ctx: DocxReadContext,\n ) => Partial<ParagraphPropertiesOptions>,\n ctx: DocxReadContext,\n): DefaultStylesOptions | undefined {\n const document: DocumentDefaultsOptions = {};\n\n // null = explicit empty default element (`<w:rPrDefault/>` or\n // `<w:rPrDefault><w:rPr/></w:rPrDefault>`); distinguishes \"no defaults declared\"\n // (Word suppresses its own) from a missing element (Word injects application\n // defaults). See ECMA-376 CT_DocDefaults.\n const rPrDefault = findChild(el, \"w:rPrDefault\");\n if (rPrDefault) {\n const rPr = findChild(rPrDefault, \"w:rPr\");\n if (rPr) {\n const runDefaults = parseRunProperties(rPr);\n document.run = Object.keys(runDefaults).length > 0 ? runDefaults : null;\n } else {\n document.run = null;\n }\n }\n\n const pPrDefault = findChild(el, \"w:pPrDefault\");\n if (pPrDefault) {\n const pPr = findChild(pPrDefault, \"w:pPr\");\n if (pPr) {\n // Reuse the full paragraph-properties reader (stringifyDocDefaults uses\n // stringifyParagraphProperties) instead of only reading spacing, so jc/\n // ind/etc. round-trip too.\n const paraDefaults = parseParagraphProperties(pPr, ctx);\n document.paragraph = Object.keys(paraDefaults).length > 0 ? paraDefaults : null;\n } else {\n document.paragraph = null;\n }\n }\n\n return Object.keys(document).length > 0 ? { document } : undefined;\n}\n\nfunction parseStyleElement(\n el: Element,\n parseParagraphProperties: (\n el: Element,\n ctx: DocxReadContext,\n ) => Partial<ParagraphPropertiesOptions>,\n ctx: DocxReadContext,\n): ParsedStyle | undefined {\n const opts: ParsedStyle = {};\n\n const type = attr(el, \"w:type\");\n if (type) opts._type = type;\n\n const id = attr(el, \"w:styleId\");\n if (id) opts.id = id;\n\n if (attrBool(el, \"w:default\")) opts.default = true;\n if (attrBool(el, \"w:customStyle\")) opts.customStyle = true;\n\n const nameEl = findChild(el, \"w:name\");\n if (nameEl) {\n const name = attr(nameEl, \"w:val\");\n if (name) opts.name = name;\n }\n\n const basedOn = findChild(el, \"w:basedOn\");\n if (basedOn) {\n const val = attr(basedOn, \"w:val\");\n if (val) opts.basedOn = val;\n }\n\n const next = findChild(el, \"w:next\");\n if (next) {\n const val = attr(next, \"w:val\");\n if (val) opts.next = val;\n }\n\n const link = findChild(el, \"w:link\");\n if (link) {\n const val = attr(link, \"w:val\");\n if (val) opts.link = val;\n }\n\n const uiPriority = findChild(el, \"w:uiPriority\");\n if (uiPriority) {\n const val = attrNum(uiPriority, \"w:val\");\n if (val !== undefined) opts.uiPriority = val;\n }\n\n if (findChild(el, \"w:qFormat\")) opts.quickFormat = true;\n if (findChild(el, \"w:semiHidden\")) opts.semiHidden = true;\n if (findChild(el, \"w:unhideWhenUsed\")) opts.unhideWhenUsed = true;\n if (findChild(el, \"w:autoRedefine\")) opts.autoRedefine = true;\n if (findChild(el, \"w:locked\")) opts.locked = true;\n if (findChild(el, \"w:personal\")) opts.personal = true;\n if (findChild(el, \"w:personalCompose\")) opts.personalCompose = true;\n if (findChild(el, \"w:personalReply\")) opts.personalReply = true;\n if (findChild(el, \"w:hidden\")) opts.hidden = true;\n\n const rsidEl = findChild(el, \"w:rsid\");\n if (rsidEl) {\n const val = attr(rsidEl, \"w:val\");\n if (val) opts.rsid = val;\n }\n\n const aliases = findChild(el, \"w:aliases\");\n if (aliases) {\n const val = attr(aliases, \"w:val\");\n if (val) opts.aliases = val;\n }\n\n const pPr = findChild(el, \"w:pPr\");\n if (pPr) {\n const paraOpts = parseParagraphProperties(pPr, ctx);\n if (Object.keys(paraOpts).length > 0) {\n opts.paragraph = paraOpts;\n }\n }\n\n const rPr = findChild(el, \"w:rPr\");\n if (rPr) {\n const runOpts = parseRunProperties(rPr);\n if (Object.keys(runOpts).length > 0) opts.run = runOpts;\n }\n\n // Table-style-only properties (CT_Style type=\"table\").\n const tblPr = findChild(el, \"w:tblPr\");\n if (tblPr) {\n const tableOpts = parseTablePropertiesEl(tblPr);\n if (Object.keys(tableOpts).length > 0) opts.table = tableOpts;\n }\n const trPr = findChild(el, \"w:trPr\");\n if (trPr) {\n const rowOpts = parseTableRowPropertiesEl(trPr);\n if (Object.keys(rowOpts).length > 0) opts.row = rowOpts;\n }\n const tcPr = findChild(el, \"w:tcPr\");\n if (tcPr) {\n const cellOpts = parseTableCellPropertiesEl(tcPr);\n if (Object.keys(cellOpts).length > 0) opts.cell = cellOpts;\n }\n // Conditional table style formats (CT_TblStylePr, unbounded).\n const conditionalFormats: ConditionalTableStyleOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:tblStylePr\") continue;\n const type = attr(child, \"w:type\") as ConditionalTableStyleOptions[\"type\"] | undefined;\n if (!type) continue;\n const cf: ConditionalTableStyleOptions = { type };\n const cfPPr = findChild(child, \"w:pPr\");\n if (cfPPr) {\n const paraOpts = parseParagraphProperties(cfPPr, ctx);\n if (Object.keys(paraOpts).length > 0) {\n cf.paragraph = paraOpts;\n }\n }\n const cfRPr = findChild(child, \"w:rPr\");\n if (cfRPr) {\n const runOpts = parseRunProperties(cfRPr);\n if (Object.keys(runOpts).length > 0) cf.run = runOpts;\n }\n const cfTblPr = findChild(child, \"w:tblPr\");\n if (cfTblPr) {\n const tableOpts = parseTablePropertiesEl(cfTblPr);\n if (Object.keys(tableOpts).length > 0) cf.table = tableOpts;\n }\n const cfTrPr = findChild(child, \"w:trPr\");\n if (cfTrPr) {\n const rowOpts = parseTableRowPropertiesEl(cfTrPr);\n if (Object.keys(rowOpts).length > 0) cf.row = rowOpts;\n }\n const cfTcPr = findChild(child, \"w:tcPr\");\n if (cfTcPr) {\n const cellOpts = parseTableCellPropertiesEl(cfTcPr);\n if (Object.keys(cellOpts).length > 0) cf.cell = cellOpts;\n }\n conditionalFormats.push(cf);\n }\n if (conditionalFormats.length > 0) opts.conditionalFormats = conditionalFormats;\n\n return opts;\n}\n","/**\n * Settings descriptor — produces word/settings.xml.\n *\n * Stringifies pure JSON SettingsOptions into XML without creating\n * Settings/Compatibility/DocumentProtection/etc. class instances.\n * Zero XmlComponent allocation — pure string concatenation.\n *\n * @module\n */\n\nimport { derivePasswordHash, parseOnOff } from \"@office-open/core\";\nimport {\n parseVmlShapeDefaults,\n parseVmlShapeLayout,\n stringifyVmlShapeDefaults,\n stringifyVmlShapeLayout,\n} from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, escapeXml, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\nimport { documentNamespaceAttributes } from \"../document/document-attributes\";\nimport type {\n SettingsOptions,\n DocumentProtectionOptions,\n WriteProtectionOptions,\n MailMergeOptions,\n OdsoOptions,\n OdsoFieldMapDataOptions,\n CompatibilityOptions,\n CompatSettingOptions,\n CaptionsOptions,\n CaptionOptions,\n AutoCaptionOptions,\n MathPropertiesOptions,\n RsidsOptions,\n ReadModeInkLockDownOptions,\n RevisionViewOptions,\n DocumentFootnotePropertiesOptions,\n DocumentEndnotePropertiesOptions,\n ShapeDefaultsOptions,\n} from \"./settings\";\n\n/** Derive the namespace-prefixed val attribute from the element tag. */\nfunction valAttr(tag: string): string {\n const ns = tag.split(\":\")[0];\n return `${ns}:val`;\n}\n\nfunction onOff(tag: string, val: boolean | undefined): string {\n return val !== undefined ? `<${tag} ${valAttr(tag)}=\"${val ? 1 : 0}\"/>` : \"\";\n}\n\nfunction numVal(tag: string, val: number | undefined): string {\n return val !== undefined ? `<${tag} ${valAttr(tag)}=\"${val}\"/>` : \"\";\n}\n\nfunction strVal(tag: string, val: string | undefined): string {\n return val !== undefined ? `<${tag} ${valAttr(tag)}=\"${escapeXml(val)}\"/>` : \"\";\n}\n\n/** Build attribute string from key-value pairs, skipping undefined. */\nfunction attrStr(attrs: Record<string, string | number | boolean | undefined>): string {\n const parts: string[] = [];\n for (const [k, v] of Object.entries(attrs)) {\n if (v !== undefined) parts.push(`${k}=\"${escapeXml(String(v))}\"`);\n }\n return parts.join(\" \");\n}\n\n/** Self-closing element with attributes only. */\nfunction attrEl(tag: string, attrs: Record<string, string | number | boolean | undefined>): string {\n const a = attrStr(attrs);\n return a ? `<${tag} ${a}/>` : `<${tag}/>`;\n}\n\nfunction compatSetting(name: string, val: string | number, uri?: string): string {\n const u = uri ?? \"http://schemas.microsoft.com/office/word\";\n return `<w:compatSetting w:name=\"${escapeXml(name)}\" w:uri=\"${u}\" w:val=\"${val}\"/>`;\n}\n\n// ── Parse helpers ──\n\n/** Read a CT_OnOff child as boolean (presence true unless val is explicitly false). */\nfunction readOnOff(el: Element | undefined): boolean | undefined {\n if (!el || !el.name) return undefined;\n const v = attr(el, valAttr(el.name));\n return parseOnOff(v) ?? true;\n}\n\n/** Read an attribute as a number, or undefined if absent/unparseable. */\nfunction readNum(el: Element | undefined, name: string): number | undefined {\n if (!el) return undefined;\n const v = attr(el, name);\n if (v === undefined || v === \"\") return undefined;\n const n = parseInt(v, 10);\n return Number.isNaN(n) ? undefined : n;\n}\n\n/** Read an attribute as a string, or undefined if absent. */\nfunction readStr(el: Element | undefined, name: string): string | undefined {\n if (!el) return undefined;\n const v = attr(el, name);\n return v === undefined || v === \"\" ? undefined : v;\n}\n\n/** Read an attribute constrained to an enum; undefined if absent or not allowed. */\nfunction readEnum<T extends string>(\n el: Element | undefined,\n name: string,\n allowed: readonly T[],\n): T | undefined {\n const v = readStr(el, name);\n return v !== undefined && (allowed as readonly string[]).includes(v) ? (v as T) : undefined;\n}\n\n/** Shared password/crypto attributes (AG_TransitionalPassword) → options keys. */\nconst PASSWORD_ATTR_MAP: [string, string, boolean][] = [\n [\"hashValue\", \"w:hashValue\", false],\n [\"saltValue\", \"w:saltValue\", false],\n [\"hash\", \"w:hash\", false],\n [\"salt\", \"w:salt\", false],\n [\"spinCount\", \"w:spinCount\", true],\n [\"algorithmName\", \"w:algorithmName\", false],\n [\"cryptoAlgorithmClass\", \"w:cryptAlgorithmClass\", false],\n [\"cryptoAlgorithmSid\", \"w:cryptAlgorithmSid\", true],\n [\"cryptoAlgorithmType\", \"w:cryptAlgorithmType\", false],\n [\"cryptoProvider\", \"w:cryptProvider\", false],\n [\"cryptoProviderType\", \"w:cryptProviderType\", false],\n [\"cryptoProviderTypeExtension\", \"w:cryptProviderTypeExt\", true],\n [\"cryptoProviderTypeExtensionSource\", \"w:cryptProviderTypeExtSource\", false],\n [\"algorithmExtensionId\", \"w:algIdExt\", true],\n [\"algorithmExtensionSource\", \"w:algIdExtSource\", false],\n [\"cryptoSpinCount\", \"w:cryptSpinCount\", true],\n];\n\n/** Read shared password/crypto attributes into an options object. */\nfunction readPasswordAttrs(el: Element): Record<string, string | number> {\n const out: Record<string, string | number> = {};\n for (const [key, xmlAttr, isNum] of PASSWORD_ATTR_MAP) {\n const v = attr(el, xmlAttr);\n if (v === undefined || v === \"\") continue;\n out[key] = isNum ? parseInt(v, 10) : v;\n }\n return out;\n}\n\n/**\n * CT_OnOff compat flag elements → CompatibilityOptions keys. The XML tag often\n * differs from the option key (e.g. wordPerfectJustification → w:wpJustification).\n * Order mirrors stringifyCompatibility so round-trip preserves element order.\n */\nconst COMPAT_FLAG_MAP: [string, string][] = [\n [\"useSingleBorderforContiguousCells\", \"w:useSingleBorderforContiguousCells\"],\n [\"wordPerfectJustification\", \"w:wpJustification\"],\n [\"noTabStopForHangingIndent\", \"w:noTabHangInd\"],\n [\"noLeading\", \"w:noLeading\"],\n [\"spaceForUnderline\", \"w:spaceForUL\"],\n [\"noColumnBalance\", \"w:noColumnBalance\"],\n [\"balanceSingleByteDoubleByteWidth\", \"w:balanceSingleByteDoubleByteWidth\"],\n [\"noExtraLineSpacing\", \"w:noExtraLineSpacing\"],\n [\"doNotLeaveBackslashAlone\", \"w:doNotLeaveBackslashAlone\"],\n [\"underlineTrailingSpaces\", \"w:ulTrailSpace\"],\n [\"doNotExpandShiftReturn\", \"w:doNotExpandShiftReturn\"],\n [\"spacingInWholePoints\", \"w:spacingInWholePoints\"],\n [\"lineWrapLikeWord6\", \"w:lineWrapLikeWord6\"],\n [\"printBodyTextBeforeHeader\", \"w:printBodyTextBeforeHeader\"],\n [\"printColorsBlack\", \"w:printColBlack\"],\n [\"spaceWidth\", \"w:wpSpaceWidth\"],\n [\"showBreaksInFrames\", \"w:showBreaksInFrames\"],\n [\"subFontBySize\", \"w:subFontBySize\"],\n [\"suppressBottomSpacing\", \"w:suppressBottomSpacing\"],\n [\"suppressTopSpacing\", \"w:suppressTopSpacing\"],\n [\"suppressSpacingAtTopOfPage\", \"w:suppressSpacingAtTopOfPage\"],\n [\"suppressTopSpacingWP\", \"w:suppressTopSpacingWP\"],\n [\"suppressSpBfAfterPgBrk\", \"w:suppressSpBfAfterPgBrk\"],\n [\"swapBordersFacingPages\", \"w:swapBordersFacingPages\"],\n [\"convertMailMergeEsc\", \"w:convMailMergeEsc\"],\n [\"truncateFontHeightsLikeWP6\", \"w:truncateFontHeightsLikeWP6\"],\n [\"macWordSmallCaps\", \"w:mwSmallCaps\"],\n [\"usePrinterMetrics\", \"w:usePrinterMetrics\"],\n [\"doNotSuppressParagraphBorders\", \"w:doNotSuppressParagraphBorders\"],\n [\"wrapTrailSpaces\", \"w:wrapTrailSpaces\"],\n [\"footnoteLayoutLikeWW8\", \"w:footnoteLayoutLikeWW8\"],\n [\"shapeLayoutLikeWW8\", \"w:shapeLayoutLikeWW8\"],\n [\"alignTablesRowByRow\", \"w:alignTablesRowByRow\"],\n [\"forgetLastTabAlignment\", \"w:forgetLastTabAlignment\"],\n [\"adjustLineHeightInTable\", \"w:adjustLineHeightInTable\"],\n [\"autoSpaceLikeWord95\", \"w:autoSpaceLikeWord95\"],\n [\"noSpaceRaiseLower\", \"w:noSpaceRaiseLower\"],\n [\"doNotUseHTMLParagraphAutoSpacing\", \"w:doNotUseHTMLParagraphAutoSpacing\"],\n [\"layoutRawTableWidth\", \"w:layoutRawTableWidth\"],\n [\"layoutTableRowsApart\", \"w:layoutTableRowsApart\"],\n [\"useWord97LineBreakRules\", \"w:useWord97LineBreakRules\"],\n [\"doNotBreakWrappedTables\", \"w:doNotBreakWrappedTables\"],\n [\"doNotSnapToGridInCell\", \"w:doNotSnapToGridInCell\"],\n [\"selectFieldWithFirstOrLastCharacter\", \"w:selectFldWithFirstOrLastChar\"],\n [\"applyBreakingRules\", \"w:applyBreakingRules\"],\n [\"doNotWrapTextWithPunctuation\", \"w:doNotWrapTextWithPunct\"],\n [\"doNotUseEastAsianBreakRules\", \"w:doNotUseEastAsianBreakRules\"],\n [\"useWord2002TableStyleRules\", \"w:useWord2002TableStyleRules\"],\n [\"growAutofit\", \"w:growAutofit\"],\n [\"useFELayout\", \"w:useFELayout\"],\n [\"useNormalStyleForList\", \"w:useNormalStyleForList\"],\n [\"doNotUseIndentAsNumberingTabStop\", \"w:doNotUseIndentAsNumberingTabStop\"],\n [\"useAlternateEastAsianLineBreakRules\", \"w:useAltKinsokuLineBreakRules\"],\n [\"allowSpaceOfSameStyleInTable\", \"w:allowSpaceOfSameStyleInTable\"],\n [\"doNotSuppressIndentation\", \"w:doNotSuppressIndentation\"],\n [\"doNotAutofitConstrainedTables\", \"w:doNotAutofitConstrainedTables\"],\n [\"autofitToFirstFixedWidthCell\", \"w:autofitToFirstFixedWidthCell\"],\n [\"underlineTabInNumberingList\", \"w:underlineTabInNumList\"],\n [\"displayHangulFixedWidth\", \"w:displayHangulFixedWidth\"],\n [\"splitPgBreakAndParaMark\", \"w:splitPgBreakAndParaMark\"],\n [\"doNotVerticallyAlignCellWithSp\", \"w:doNotVertAlignCellWithSp\"],\n [\"doNotBreakConstrainedForcedTable\", \"w:doNotBreakConstrainedForcedTable\"],\n [\"ignoreVerticalAlignmentInTextboxes\", \"w:doNotVertAlignInTxbx\"],\n [\"useAnsiKerningPairs\", \"w:useAnsiKerningPairs\"],\n [\"cachedColumnBalance\", \"w:cachedColBalance\"],\n];\n\n/** compatSetting names that map to dedicated sugar fields (not into compatSettings[]). */\nconst COMPAT_SETTING_SUGAR: Record<\n string,\n | \"version\"\n | \"overrideTableStyleFontSizeAndJustification\"\n | \"enableOpenTypeFeatures\"\n | \"doNotFlipMirrorIndents\"\n> = {\n compatibilityMode: \"version\",\n overrideTableStyleFontSizeAndJustification: \"overrideTableStyleFontSizeAndJustification\",\n enableOpenTypeFeatures: \"enableOpenTypeFeatures\",\n doNotFlipMirrorIndents: \"doNotFlipMirrorIndents\",\n};\n\n/** Parse w:footnotePr / w:endnotePr (CT_FtnDocProps / CT_EdnDocProps). */\nfunction parseFtnEdnPr(el: Element): Record<string, unknown> | undefined {\n const o: Record<string, unknown> = {};\n const pos = readStr(findChild(el, \"w:pos\"), \"w:val\");\n if (pos) o.pos = pos;\n const numFmtEl = findChild(el, \"w:numFmt\");\n if (numFmtEl) {\n const v = readStr(numFmtEl, \"w:val\");\n if (v) o.numFmt = v;\n const format = readStr(numFmtEl, \"w:format\");\n if (format) o.format = format;\n }\n const numStart = readNum(findChild(el, \"w:numStart\"), \"w:val\");\n if (numStart !== undefined) o.numStart = numStart;\n const numRestart = readStr(findChild(el, \"w:numRestart\"), \"w:val\");\n if (numRestart) o.numRestart = numRestart;\n return Object.keys(o).length > 0 ? o : undefined;\n}\n\n/** Parse w:compat (CT_Compat): on/off flag elements + w:compatSetting entries. */\nfunction parseCompatibility(el: Element): CompatibilityOptions | undefined {\n const o: Record<string, unknown> = {};\n const flagMap: Record<string, string> = Object.fromEntries(\n COMPAT_FLAG_MAP.map(([key, tag]) => [tag, key]),\n );\n const extras: CompatSettingOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.type !== \"element\" || !child.name) continue;\n const key = flagMap[child.name];\n if (key !== undefined) {\n o[key] = true;\n continue;\n }\n if (child.name === \"w:compatSetting\") {\n const name = attr(child, \"w:name\");\n const val = attr(child, \"w:val\");\n if (name === undefined || val === undefined) continue;\n const sugar = COMPAT_SETTING_SUGAR[name];\n if (sugar === \"version\") {\n const n = parseInt(val, 10);\n if (!Number.isNaN(n)) o.version = n;\n } else if (sugar !== undefined) {\n o[sugar] = parseOnOff(val) ?? true;\n } else {\n extras.push({ name, val, uri: attr(child, \"w:uri\") });\n }\n }\n }\n if (extras.length > 0) o.compatSettings = extras;\n return Object.keys(o).length > 0 ? (o as CompatibilityOptions) : undefined;\n}\n\n/** Parse m:mathPr (CT_MathPr). */\nfunction parseMathPr(el: Element): MathPropertiesOptions | undefined {\n const o: Partial<MathPropertiesOptions> = {};\n const mathFont = readStr(findChild(el, \"m:mathFont\"), \"m:val\");\n if (mathFont) o.mathFont = mathFont;\n const binaryOperatorBreak = readEnum(findChild(el, \"m:brkBin\"), \"m:val\", [\n \"before\",\n \"after\",\n \"repeat\",\n ] as const);\n if (binaryOperatorBreak) o.binaryOperatorBreak = binaryOperatorBreak;\n const binaryOperatorBreakSubtraction = readEnum(findChild(el, \"m:brkBinSub\"), \"m:val\", [\n \"--\",\n \"-+\",\n \"+-\",\n ] as const);\n if (binaryOperatorBreakSubtraction)\n o.binaryOperatorBreakSubtraction = binaryOperatorBreakSubtraction;\n const smallFractions = readOnOff(findChild(el, \"m:smallFrac\"));\n if (smallFractions !== undefined) o.smallFractions = smallFractions;\n const displayDefaults = readOnOff(findChild(el, \"m:dispDef\"));\n if (displayDefaults !== undefined) o.displayDefaults = displayDefaults;\n const leftMargin = readNum(findChild(el, \"m:lMargin\"), \"m:val\");\n if (leftMargin !== undefined) o.leftMargin = leftMargin;\n const rightMargin = readNum(findChild(el, \"m:rMargin\"), \"m:val\");\n if (rightMargin !== undefined) o.rightMargin = rightMargin;\n const defaultJustification = readEnum(findChild(el, \"m:defJc\"), \"m:val\", [\n \"left\",\n \"right\",\n \"center\",\n \"centerGroup\",\n ] as const);\n if (defaultJustification) o.defaultJustification = defaultJustification;\n const preSpacing = readNum(findChild(el, \"m:preSp\"), \"m:val\");\n if (preSpacing !== undefined) o.preSpacing = preSpacing;\n const postSpacing = readNum(findChild(el, \"m:postSp\"), \"m:val\");\n if (postSpacing !== undefined) o.postSpacing = postSpacing;\n const interSpacing = readNum(findChild(el, \"m:interSp\"), \"m:val\");\n if (interSpacing !== undefined) o.interSpacing = interSpacing;\n const intraSpacing = readNum(findChild(el, \"m:intraSp\"), \"m:val\");\n if (intraSpacing !== undefined) o.intraSpacing = intraSpacing;\n const wrapIndent = readNum(findChild(el, \"m:wrapIndent\"), \"m:val\");\n if (wrapIndent !== undefined) o.wrapIndent = wrapIndent;\n const wrapRight = readOnOff(findChild(el, \"m:wrapRight\"));\n if (wrapRight !== undefined) o.wrapRight = wrapRight;\n const integralLimitLocation = readEnum(findChild(el, \"m:intLim\"), \"m:val\", [\n \"subSup\",\n \"undOvr\",\n ] as const);\n if (integralLimitLocation) o.integralLimitLocation = integralLimitLocation;\n const naryLimitLocation = readEnum(findChild(el, \"m:naryLim\"), \"m:val\", [\n \"subSup\",\n \"undOvr\",\n ] as const);\n if (naryLimitLocation) o.naryLimitLocation = naryLimitLocation;\n return Object.keys(o).length > 0 ? (o as MathPropertiesOptions) : undefined;\n}\n\n/** Parse w:captions (CT_Captions). */\nfunction parseCaptions(el: Element): CaptionsOptions | undefined {\n const captions: CaptionOptions[] = [];\n const autoCaptions: AutoCaptionOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.type !== \"element\") continue;\n if (child.name === \"w:caption\") {\n const c: CaptionOptions = { name: attr(child, \"w:name\") ?? \"\" };\n const pos = attr(child, \"w:pos\");\n if (pos) c.pos = pos as CaptionOptions[\"pos\"];\n const chapNum = attr(child, \"w:chapNum\");\n if (chapNum !== undefined) c.chapNum = parseOnOff(chapNum) ?? false;\n const heading = attr(child, \"w:heading\");\n if (heading !== undefined) c.heading = parseInt(heading, 10);\n const noLabel = attr(child, \"w:noLabel\");\n if (noLabel !== undefined) c.noLabel = parseOnOff(noLabel) ?? false;\n const numFmt = attr(child, \"w:numFmt\");\n if (numFmt) c.numFmt = numFmt;\n const sep = attr(child, \"w:sep\");\n if (sep) c.sep = sep as CaptionOptions[\"sep\"];\n captions.push(c);\n } else if (child.name === \"w:autoCaptions\") {\n for (const ac of child.elements ?? []) {\n if (ac.name !== \"w:autoCaption\") continue;\n const name = attr(ac, \"w:name\");\n const caption = attr(ac, \"w:caption\");\n if (name && caption) autoCaptions.push({ name, caption });\n }\n }\n }\n if (captions.length === 0) return undefined;\n const o: CaptionsOptions = { captions };\n if (autoCaptions.length > 0) o.autoCaptions = autoCaptions;\n return o;\n}\n\n/** Parse w:odso (CT_Odso). */\nfunction parseOdso(el: Element): OdsoOptions | undefined {\n const o: OdsoOptions = {};\n const udl = readStr(findChild(el, \"w:udl\"), \"w:val\");\n if (udl) o.udl = udl;\n const table = readStr(findChild(el, \"w:table\"), \"w:val\");\n if (table) o.table = table;\n const srcEl = findChild(el, \"w:src\");\n if (srcEl) {\n const rid = attr(srcEl, \"r:id\");\n if (rid) o.src = rid;\n }\n const colDelim = readNum(findChild(el, \"w:colDelim\"), \"w:val\");\n if (colDelim !== undefined) o.colDelim = colDelim;\n const type = readStr(findChild(el, \"w:type\"), \"w:val\");\n if (type) o.type = type as OdsoOptions[\"type\"];\n const fHdr = readOnOff(findChild(el, \"w:fHdr\"));\n if (fHdr !== undefined) o.fHdr = fHdr;\n const fieldMapData: OdsoFieldMapDataOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:fieldMapData\") continue;\n const fm: OdsoFieldMapDataOptions = {};\n const t = readStr(findChild(child, \"w:type\"), \"w:val\");\n if (t) fm.type = t as OdsoFieldMapDataOptions[\"type\"];\n const n = readStr(findChild(child, \"w:name\"), \"w:val\");\n if (n) fm.name = n;\n const mn = readStr(findChild(child, \"w:mappedName\"), \"w:val\");\n if (mn) fm.mappedName = mn;\n const col = readNum(findChild(child, \"w:column\"), \"w:val\");\n if (col !== undefined) fm.column = col;\n const lid = readStr(findChild(child, \"w:lid\"), \"w:val\");\n if (lid) fm.lid = lid;\n const dyn = readOnOff(findChild(child, \"w:dynamicAddress\"));\n if (dyn !== undefined) fm.dynamicAddress = dyn;\n if (Object.keys(fm).length > 0) fieldMapData.push(fm);\n }\n if (fieldMapData.length > 0) o.fieldMapData = fieldMapData;\n const recipientData: string[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:recipientData\") continue;\n const rid = attr(child, \"r:id\");\n if (rid) recipientData.push(rid);\n }\n if (recipientData.length > 0) o.recipientData = recipientData;\n const uniqueTag = readStr(findChild(el, \"w:uniqueTag\"), \"w:val\");\n if (uniqueTag) o.uniqueTag = uniqueTag;\n return Object.keys(o).length > 0 ? o : undefined;\n}\n\n/** Parse w:mailMerge (CT_MailMerge). */\nfunction parseMailMerge(el: Element): MailMergeOptions | undefined {\n const o: Partial<MailMergeOptions> = {};\n const mdt = readStr(findChild(el, \"w:mainDocumentType\"), \"w:val\");\n if (mdt) o.mainDocumentType = mdt as MailMergeOptions[\"mainDocumentType\"];\n const dataType = readStr(findChild(el, \"w:dataType\"), \"w:val\");\n if (dataType) o.dataType = dataType as MailMergeOptions[\"dataType\"];\n const dest = readStr(findChild(el, \"w:destination\"), \"w:val\");\n if (dest) o.destination = dest as MailMergeOptions[\"destination\"];\n const connectString = readStr(findChild(el, \"w:connectString\"), \"w:val\");\n if (connectString) o.connectString = connectString;\n const query = readStr(findChild(el, \"w:query\"), \"w:val\");\n if (query) o.query = query;\n const dsEl = findChild(el, \"w:dataSource\");\n if (dsEl) {\n const rid = attr(dsEl, \"r:id\");\n if (rid) o.dataSource = rid;\n }\n const hsEl = findChild(el, \"w:headerSource\");\n if (hsEl) {\n const rid = attr(hsEl, \"r:id\");\n if (rid) o.headerSource = rid;\n }\n const linkToQuery = readOnOff(findChild(el, \"w:linkToQuery\"));\n if (linkToQuery !== undefined) o.linkToQuery = linkToQuery;\n const doNotSuppress = readOnOff(findChild(el, \"w:doNotSuppressBlankLines\"));\n if (doNotSuppress !== undefined) o.doNotSuppressBlankLines = doNotSuppress;\n const addressFieldName = readStr(findChild(el, \"w:addressFieldName\"), \"w:val\");\n if (addressFieldName) o.addressFieldName = addressFieldName;\n const mailSubject = readStr(findChild(el, \"w:mailSubject\"), \"w:val\");\n if (mailSubject) o.mailSubject = mailSubject;\n const mailAsAttachment = readOnOff(findChild(el, \"w:mailAsAttachment\"));\n if (mailAsAttachment !== undefined) o.mailAsAttachment = mailAsAttachment;\n const viewMergedData = readOnOff(findChild(el, \"w:viewMergedData\"));\n if (viewMergedData !== undefined) o.viewMergedData = viewMergedData;\n const activeRecord = readNum(findChild(el, \"w:activeRecord\"), \"w:val\");\n if (activeRecord !== undefined) o.activeRecord = activeRecord;\n const checkErrors = readNum(findChild(el, \"w:checkErrors\"), \"w:val\");\n if (checkErrors !== undefined) o.checkErrors = checkErrors;\n const active = readOnOff(findChild(el, \"w:active\"));\n if (active !== undefined) o.active = active;\n const recipientsEl = findChild(el, \"w:recipients\");\n if (recipientsEl) {\n const rid = attr(recipientsEl, \"r:id\");\n if (rid) o.recipients = rid;\n }\n const odsoEl = findChild(el, \"w:odso\");\n if (odsoEl) {\n const odso = parseOdso(odsoEl);\n if (odso) o.odso = odso;\n }\n if (Object.keys(o).length === 0) return undefined;\n return o as MailMergeOptions;\n}\n\n// ── Password derivation ──\n\ninterface DerivedPassword {\n hashValue: string;\n saltValue: string;\n spinCount: number;\n algorithmName: string;\n}\n\nfunction maybeDerive(\n password: string | undefined,\n hashValue: string | undefined,\n): DerivedPassword | undefined {\n return password !== undefined && hashValue === undefined\n ? derivePasswordHash(password)\n : undefined;\n}\n\n// ── Complex sub-elements ──\n\n/** Valid w:documentProtection/@w:edit values (ST_DocProtect). */\nconst DOC_PROTECT_EDITS = [\"none\", \"readOnly\", \"comments\", \"trackedChanges\", \"forms\"] as const;\n\nfunction stringifyDocProtect(opts: DocumentProtectionOptions): string {\n const derived = maybeDerive(opts.password, opts.hashValue);\n const attrs: Record<string, string | number> = { \"w:enforcement\": \"1\" };\n if (opts.edit !== undefined) attrs[\"w:edit\"] = opts.edit;\n if (opts.formatting !== undefined) attrs[\"w:formatting\"] = opts.formatting ? \"1\" : \"0\";\n if (opts.algorithmName ?? derived?.algorithmName)\n attrs[\"w:algorithmName\"] = opts.algorithmName ?? derived!.algorithmName;\n if (opts.hashValue ?? derived?.hashValue)\n attrs[\"w:hashValue\"] = opts.hashValue ?? derived!.hashValue;\n if (opts.saltValue ?? derived?.saltValue)\n attrs[\"w:saltValue\"] = opts.saltValue ?? derived!.saltValue;\n if (opts.hash !== undefined) attrs[\"w:hash\"] = opts.hash;\n if (opts.salt !== undefined) attrs[\"w:salt\"] = opts.salt;\n if (opts.spinCount ?? derived?.spinCount)\n attrs[\"w:spinCount\"] = opts.spinCount ?? derived!.spinCount;\n if (opts.cryptoAlgorithmClass !== undefined)\n attrs[\"w:cryptAlgorithmClass\"] = opts.cryptoAlgorithmClass;\n if (opts.cryptoAlgorithmSid !== undefined) attrs[\"w:cryptAlgorithmSid\"] = opts.cryptoAlgorithmSid;\n if (opts.cryptoAlgorithmType !== undefined)\n attrs[\"w:cryptAlgorithmType\"] = opts.cryptoAlgorithmType;\n if (opts.cryptoProvider !== undefined) attrs[\"w:cryptProvider\"] = opts.cryptoProvider;\n if (opts.cryptoProviderType !== undefined) attrs[\"w:cryptProviderType\"] = opts.cryptoProviderType;\n if (opts.cryptoProviderTypeExtension !== undefined)\n attrs[\"w:cryptProviderTypeExt\"] = opts.cryptoProviderTypeExtension;\n if (opts.cryptoProviderTypeExtensionSource !== undefined)\n attrs[\"w:cryptProviderTypeExtSource\"] = opts.cryptoProviderTypeExtensionSource;\n if (opts.algorithmExtensionId !== undefined) attrs[\"w:algIdExt\"] = opts.algorithmExtensionId;\n if (opts.algorithmExtensionSource !== undefined)\n attrs[\"w:algIdExtSource\"] = opts.algorithmExtensionSource;\n if (opts.cryptoSpinCount !== undefined) attrs[\"w:cryptSpinCount\"] = opts.cryptoSpinCount;\n return attrEl(\"w:documentProtection\", attrs);\n}\n\nfunction stringifyWriteProtect(opts: WriteProtectionOptions): string {\n const derived = maybeDerive(opts.password, opts.hashValue);\n const attrs: Record<string, string | number> = {};\n if (opts.recommended !== undefined) attrs[\"w:recommended\"] = opts.recommended ? \"1\" : \"0\";\n if (opts.hashValue ?? derived?.hashValue)\n attrs[\"w:hashValue\"] = opts.hashValue ?? derived!.hashValue;\n if (opts.saltValue ?? derived?.saltValue)\n attrs[\"w:saltValue\"] = opts.saltValue ?? derived!.saltValue;\n if (opts.hash !== undefined) attrs[\"w:hash\"] = opts.hash;\n if (opts.salt !== undefined) attrs[\"w:salt\"] = opts.salt;\n if (opts.spinCount ?? derived?.spinCount)\n attrs[\"w:spinCount\"] = opts.spinCount ?? derived!.spinCount;\n if (opts.algorithmName ?? derived?.algorithmName)\n attrs[\"w:algorithmName\"] = opts.algorithmName ?? derived!.algorithmName;\n if (opts.cryptoAlgorithmClass !== undefined)\n attrs[\"w:cryptAlgorithmClass\"] = opts.cryptoAlgorithmClass;\n if (opts.cryptoAlgorithmSid !== undefined) attrs[\"w:cryptAlgorithmSid\"] = opts.cryptoAlgorithmSid;\n if (opts.cryptoAlgorithmType !== undefined)\n attrs[\"w:cryptAlgorithmType\"] = opts.cryptoAlgorithmType;\n if (opts.cryptoProvider !== undefined) attrs[\"w:cryptProvider\"] = opts.cryptoProvider;\n if (opts.cryptoProviderType !== undefined) attrs[\"w:cryptProviderType\"] = opts.cryptoProviderType;\n if (opts.algorithmExtensionId !== undefined) attrs[\"w:algIdExt\"] = opts.algorithmExtensionId;\n if (opts.algorithmExtensionSource !== undefined)\n attrs[\"w:algIdExtSource\"] = opts.algorithmExtensionSource;\n if (opts.cryptoProviderTypeExtension !== undefined)\n attrs[\"w:cryptProviderTypeExt\"] = opts.cryptoProviderTypeExtension;\n if (opts.cryptoProviderTypeExtensionSource !== undefined)\n attrs[\"w:cryptProviderTypeExtSource\"] = opts.cryptoProviderTypeExtensionSource;\n if (opts.cryptoSpinCount !== undefined) attrs[\"w:cryptSpinCount\"] = opts.cryptoSpinCount;\n return attrEl(\"w:writeProtection\", attrs);\n}\n\nfunction stringifyRevisionView(opts: RevisionViewOptions): string {\n const attrs: Record<string, string> = {};\n if (opts.markup !== undefined) attrs[\"w:markup\"] = opts.markup ? \"true\" : \"false\";\n if (opts.comments !== undefined) attrs[\"w:comments\"] = opts.comments ? \"true\" : \"false\";\n if (opts.insDel !== undefined) attrs[\"w:insDel\"] = opts.insDel ? \"true\" : \"false\";\n if (opts.formatting !== undefined) attrs[\"w:formatting\"] = opts.formatting ? \"true\" : \"false\";\n if (opts.inkAnnotations !== undefined)\n attrs[\"w:inkAnnotations\"] = opts.inkAnnotations ? \"true\" : \"false\";\n return attrEl(\"w:revisionView\", attrs);\n}\n\nfunction stringifyMailMerge(opts: MailMergeOptions): string {\n const p: string[] = [];\n p.push(strVal(\"w:mainDocumentType\", opts.mainDocumentType));\n p.push(onOff(\"w:linkToQuery\", opts.linkToQuery));\n p.push(strVal(\"w:dataType\", opts.dataType));\n p.push(strVal(\"w:connectString\", opts.connectString));\n p.push(strVal(\"w:query\", opts.query));\n if (opts.dataSource !== undefined) p.push(attrEl(\"w:dataSource\", { \"r:id\": opts.dataSource }));\n if (opts.headerSource !== undefined)\n p.push(attrEl(\"w:headerSource\", { \"r:id\": opts.headerSource }));\n p.push(onOff(\"w:doNotSuppressBlankLines\", opts.doNotSuppressBlankLines));\n p.push(strVal(\"w:destination\", opts.destination));\n p.push(strVal(\"w:addressFieldName\", opts.addressFieldName));\n p.push(strVal(\"w:mailSubject\", opts.mailSubject));\n p.push(onOff(\"w:mailAsAttachment\", opts.mailAsAttachment));\n p.push(onOff(\"w:viewMergedData\", opts.viewMergedData));\n p.push(numVal(\"w:activeRecord\", opts.activeRecord));\n p.push(numVal(\"w:checkErrors\", opts.checkErrors));\n if (opts.odso !== undefined) p.push(stringifyOdso(opts.odso));\n p.push(onOff(\"w:active\", opts.active));\n if (opts.recipients !== undefined) p.push(attrEl(\"w:recipients\", { \"r:id\": opts.recipients }));\n return `<w:mailMerge>${p.join(\"\")}</w:mailMerge>`;\n}\n\nfunction stringifyOdso(opts: OdsoOptions): string {\n const p: string[] = [];\n p.push(strVal(\"w:udl\", opts.udl));\n p.push(strVal(\"w:table\", opts.table));\n if (opts.src !== undefined) p.push(attrEl(\"w:src\", { \"r:id\": opts.src }));\n p.push(numVal(\"w:colDelim\", opts.colDelim));\n p.push(strVal(\"w:type\", opts.type));\n p.push(onOff(\"w:fHdr\", opts.fHdr));\n if (opts.fieldMapData !== undefined) {\n for (const fm of opts.fieldMapData) p.push(stringifyOdsoFieldMap(fm));\n }\n if (opts.recipientData !== undefined) {\n for (const rd of opts.recipientData) p.push(attrEl(\"w:recipientData\", { \"r:id\": rd }));\n }\n p.push(strVal(\"w:uniqueTag\", opts.uniqueTag));\n return `<w:odso>${p.join(\"\")}</w:odso>`;\n}\n\nfunction stringifyOdsoFieldMap(opts: OdsoFieldMapDataOptions): string {\n const p: string[] = [];\n p.push(strVal(\"w:type\", opts.type));\n p.push(strVal(\"w:name\", opts.name));\n p.push(strVal(\"w:mappedName\", opts.mappedName));\n p.push(numVal(\"w:column\", opts.column));\n p.push(strVal(\"w:lid\", opts.lid));\n p.push(onOff(\"w:dynamicAddress\", opts.dynamicAddress));\n return `<w:fieldMapData>${p.join(\"\")}</w:fieldMapData>`;\n}\n\nfunction stringifyFootnotePr(opts: DocumentFootnotePropertiesOptions): string {\n const p: string[] = [];\n if (opts.pos !== undefined) p.push(attrEl(\"w:pos\", { \"w:val\": opts.pos }));\n if (opts.numFmt !== undefined || opts.format !== undefined) {\n const a: Record<string, string> = {};\n if (opts.numFmt !== undefined) a[\"w:val\"] = opts.numFmt;\n if (opts.format !== undefined) a[\"w:format\"] = opts.format;\n p.push(attrEl(\"w:numFmt\", a));\n }\n p.push(numVal(\"w:numStart\", opts.numStart));\n p.push(strVal(\"w:numRestart\", opts.numRestart));\n return `<w:footnotePr>${p.join(\"\")}</w:footnotePr>`;\n}\n\nfunction stringifyEndnotePr(opts: DocumentEndnotePropertiesOptions): string {\n const p: string[] = [];\n if (opts.pos !== undefined) p.push(attrEl(\"w:pos\", { \"w:val\": opts.pos }));\n if (opts.numFmt !== undefined || opts.format !== undefined) {\n const a: Record<string, string> = {};\n if (opts.numFmt !== undefined) a[\"w:val\"] = opts.numFmt;\n if (opts.format !== undefined) a[\"w:format\"] = opts.format;\n p.push(attrEl(\"w:numFmt\", a));\n }\n p.push(numVal(\"w:numStart\", opts.numStart));\n p.push(strVal(\"w:numRestart\", opts.numRestart));\n return `<w:endnotePr>${p.join(\"\")}</w:endnotePr>`;\n}\n\nfunction stringifyRsids(opts: RsidsOptions): string {\n const p: string[] = [];\n if (opts.rsidRoot !== undefined) p.push(attrEl(\"w:rsidRoot\", { \"w:val\": opts.rsidRoot }));\n if (opts.rsids !== undefined) {\n for (const rsid of opts.rsids) p.push(attrEl(\"w:rsid\", { \"w:val\": rsid }));\n }\n return `<w:rsids>${p.join(\"\")}</w:rsids>`;\n}\n\nfunction stringifyReadModeInkLockDown(opts: ReadModeInkLockDownOptions): string {\n return attrEl(\"w:readModeInkLockDown\", {\n \"w:actualPg\": opts.actualPg === false ? \"0\" : \"1\",\n \"w:w\": opts.w,\n \"w:h\": opts.h,\n \"w:fontSz\": opts.fontSz,\n });\n}\n\nfunction stringifyCaptions(opts: CaptionsOptions): string {\n const p: string[] = [];\n for (const cap of opts.captions) {\n const attrs: Record<string, string | number> = { \"w:name\": cap.name };\n if (cap.pos !== undefined) attrs[\"w:pos\"] = cap.pos;\n if (cap.chapNum !== undefined) attrs[\"w:chapNum\"] = cap.chapNum ? \"1\" : \"0\";\n if (cap.heading !== undefined) attrs[\"w:heading\"] = cap.heading;\n if (cap.noLabel !== undefined) attrs[\"w:noLabel\"] = cap.noLabel ? \"1\" : \"0\";\n if (cap.numFmt !== undefined) attrs[\"w:numFmt\"] = cap.numFmt;\n if (cap.sep !== undefined) attrs[\"w:sep\"] = cap.sep;\n p.push(attrEl(\"w:caption\", attrs));\n }\n if (opts.autoCaptions?.length) {\n const acXml = opts.autoCaptions\n .map((ac) => attrEl(\"w:autoCaption\", { \"w:name\": ac.name, \"w:caption\": ac.caption }))\n .join(\"\");\n p.push(`<w:autoCaptions>${acXml}</w:autoCaptions>`);\n }\n return `<w:captions>${p.join(\"\")}</w:captions>`;\n}\n\nfunction stringifyMathPr(opts: MathPropertiesOptions): string {\n const p: string[] = [];\n if (opts.mathFont !== undefined) p.push(attrEl(\"m:mathFont\", { \"m:val\": opts.mathFont }));\n if (opts.binaryOperatorBreak !== undefined)\n p.push(attrEl(\"m:brkBin\", { \"m:val\": opts.binaryOperatorBreak }));\n if (opts.binaryOperatorBreakSubtraction !== undefined)\n p.push(attrEl(\"m:brkBinSub\", { \"m:val\": opts.binaryOperatorBreakSubtraction }));\n p.push(onOff(\"m:smallFrac\", opts.smallFractions));\n p.push(onOff(\"m:dispDef\", opts.displayDefaults));\n p.push(numVal(\"m:lMargin\", opts.leftMargin));\n p.push(numVal(\"m:rMargin\", opts.rightMargin));\n if (opts.defaultJustification !== undefined)\n p.push(attrEl(\"m:defJc\", { \"m:val\": opts.defaultJustification }));\n p.push(numVal(\"m:preSp\", opts.preSpacing));\n p.push(numVal(\"m:postSp\", opts.postSpacing));\n p.push(numVal(\"m:interSp\", opts.interSpacing));\n p.push(numVal(\"m:intraSp\", opts.intraSpacing));\n p.push(numVal(\"m:wrapIndent\", opts.wrapIndent));\n p.push(onOff(\"m:wrapRight\", opts.wrapRight));\n if (opts.integralLimitLocation !== undefined)\n p.push(attrEl(\"m:intLim\", { \"m:val\": opts.integralLimitLocation }));\n if (opts.naryLimitLocation !== undefined)\n p.push(attrEl(\"m:naryLim\", { \"m:val\": opts.naryLimitLocation }));\n return `<m:mathPr>${p.join(\"\")}</m:mathPr>`;\n}\n\nfunction stringifyColorSchemeMapping(\n opts: NonNullable<SettingsOptions[\"colorSchemeMapping\"]>,\n): string {\n const attrs: Record<string, string> = {};\n if (opts.bg1 !== undefined) attrs[\"w:bg1\"] = opts.bg1;\n if (opts.t1 !== undefined) attrs[\"w:t1\"] = opts.t1;\n if (opts.bg2 !== undefined) attrs[\"w:bg2\"] = opts.bg2;\n if (opts.t2 !== undefined) attrs[\"w:t2\"] = opts.t2;\n if (opts.accent1 !== undefined) attrs[\"w:accent1\"] = opts.accent1;\n if (opts.accent2 !== undefined) attrs[\"w:accent2\"] = opts.accent2;\n if (opts.accent3 !== undefined) attrs[\"w:accent3\"] = opts.accent3;\n if (opts.accent4 !== undefined) attrs[\"w:accent4\"] = opts.accent4;\n if (opts.accent5 !== undefined) attrs[\"w:accent5\"] = opts.accent5;\n if (opts.accent6 !== undefined) attrs[\"w:accent6\"] = opts.accent6;\n if (opts.hyperlink !== undefined) attrs[\"w:hyperlink\"] = opts.hyperlink;\n if (opts.followedHyperlink !== undefined) attrs[\"w:followedHyperlink\"] = opts.followedHyperlink;\n return attrEl(\"w:clrSchemeMapping\", attrs);\n}\n\n// ── Compatibility ──\n\n/** MS Office default compatSettings for a fresh Word 2013+ document. */\nconst FRESH_COMPATIBILITY: CompatibilityOptions = {\n version: 15,\n overrideTableStyleFontSizeAndJustification: true,\n enableOpenTypeFeatures: true,\n doNotFlipMirrorIndents: true,\n};\n\nfunction stringifyCompatibility(opts: CompatibilityOptions): string {\n const p: string[] = [];\n // Individual compat on/off elements (XSD order)\n if (opts.useSingleBorderforContiguousCells)\n p.push(onOff(\"w:useSingleBorderforContiguousCells\", true));\n if (opts.wordPerfectJustification) p.push(onOff(\"w:wpJustification\", true));\n if (opts.noTabStopForHangingIndent) p.push(onOff(\"w:noTabHangInd\", true));\n if (opts.noLeading) p.push(onOff(\"w:noLeading\", true));\n if (opts.spaceForUnderline) p.push(onOff(\"w:spaceForUL\", true));\n if (opts.noColumnBalance) p.push(onOff(\"w:noColumnBalance\", true));\n if (opts.balanceSingleByteDoubleByteWidth)\n p.push(onOff(\"w:balanceSingleByteDoubleByteWidth\", true));\n if (opts.noExtraLineSpacing) p.push(onOff(\"w:noExtraLineSpacing\", true));\n if (opts.doNotLeaveBackslashAlone) p.push(onOff(\"w:doNotLeaveBackslashAlone\", true));\n if (opts.underlineTrailingSpaces) p.push(onOff(\"w:ulTrailSpace\", true));\n if (opts.doNotExpandShiftReturn) p.push(onOff(\"w:doNotExpandShiftReturn\", true));\n if (opts.spacingInWholePoints) p.push(onOff(\"w:spacingInWholePoints\", true));\n if (opts.lineWrapLikeWord6) p.push(onOff(\"w:lineWrapLikeWord6\", true));\n if (opts.printBodyTextBeforeHeader) p.push(onOff(\"w:printBodyTextBeforeHeader\", true));\n if (opts.printColorsBlack) p.push(onOff(\"w:printColBlack\", true));\n if (opts.spaceWidth) p.push(onOff(\"w:wpSpaceWidth\", true));\n if (opts.showBreaksInFrames) p.push(onOff(\"w:showBreaksInFrames\", true));\n if (opts.subFontBySize) p.push(onOff(\"w:subFontBySize\", true));\n if (opts.suppressBottomSpacing) p.push(onOff(\"w:suppressBottomSpacing\", true));\n if (opts.suppressTopSpacing) p.push(onOff(\"w:suppressTopSpacing\", true));\n if (opts.suppressSpacingAtTopOfPage) p.push(onOff(\"w:suppressSpacingAtTopOfPage\", true));\n if (opts.suppressTopSpacingWP) p.push(onOff(\"w:suppressTopSpacingWP\", true));\n if (opts.suppressSpBfAfterPgBrk) p.push(onOff(\"w:suppressSpBfAfterPgBrk\", true));\n if (opts.swapBordersFacingPages) p.push(onOff(\"w:swapBordersFacingPages\", true));\n if (opts.convertMailMergeEsc) p.push(onOff(\"w:convMailMergeEsc\", true));\n if (opts.truncateFontHeightsLikeWP6) p.push(onOff(\"w:truncateFontHeightsLikeWP6\", true));\n if (opts.macWordSmallCaps) p.push(onOff(\"w:mwSmallCaps\", true));\n if (opts.usePrinterMetrics) p.push(onOff(\"w:usePrinterMetrics\", true));\n if (opts.doNotSuppressParagraphBorders) p.push(onOff(\"w:doNotSuppressParagraphBorders\", true));\n if (opts.wrapTrailSpaces) p.push(onOff(\"w:wrapTrailSpaces\", true));\n if (opts.footnoteLayoutLikeWW8) p.push(onOff(\"w:footnoteLayoutLikeWW8\", true));\n if (opts.shapeLayoutLikeWW8) p.push(onOff(\"w:shapeLayoutLikeWW8\", true));\n if (opts.alignTablesRowByRow) p.push(onOff(\"w:alignTablesRowByRow\", true));\n if (opts.forgetLastTabAlignment) p.push(onOff(\"w:forgetLastTabAlignment\", true));\n if (opts.adjustLineHeightInTable) p.push(onOff(\"w:adjustLineHeightInTable\", true));\n if (opts.autoSpaceLikeWord95) p.push(onOff(\"w:autoSpaceLikeWord95\", true));\n if (opts.noSpaceRaiseLower) p.push(onOff(\"w:noSpaceRaiseLower\", true));\n if (opts.doNotUseHTMLParagraphAutoSpacing)\n p.push(onOff(\"w:doNotUseHTMLParagraphAutoSpacing\", true));\n if (opts.layoutRawTableWidth) p.push(onOff(\"w:layoutRawTableWidth\", true));\n if (opts.layoutTableRowsApart) p.push(onOff(\"w:layoutTableRowsApart\", true));\n if (opts.useWord97LineBreakRules) p.push(onOff(\"w:useWord97LineBreakRules\", true));\n if (opts.doNotBreakWrappedTables) p.push(onOff(\"w:doNotBreakWrappedTables\", true));\n if (opts.doNotSnapToGridInCell) p.push(onOff(\"w:doNotSnapToGridInCell\", true));\n if (opts.selectFieldWithFirstOrLastCharacter)\n p.push(onOff(\"w:selectFldWithFirstOrLastChar\", true));\n if (opts.applyBreakingRules) p.push(onOff(\"w:applyBreakingRules\", true));\n if (opts.doNotWrapTextWithPunctuation) p.push(onOff(\"w:doNotWrapTextWithPunct\", true));\n if (opts.doNotUseEastAsianBreakRules) p.push(onOff(\"w:doNotUseEastAsianBreakRules\", true));\n if (opts.useWord2002TableStyleRules) p.push(onOff(\"w:useWord2002TableStyleRules\", true));\n if (opts.growAutofit) p.push(onOff(\"w:growAutofit\", true));\n if (opts.useFELayout) p.push(onOff(\"w:useFELayout\", true));\n if (opts.useNormalStyleForList) p.push(onOff(\"w:useNormalStyleForList\", true));\n if (opts.doNotUseIndentAsNumberingTabStop)\n p.push(onOff(\"w:doNotUseIndentAsNumberingTabStop\", true));\n if (opts.useAlternateEastAsianLineBreakRules)\n p.push(onOff(\"w:useAltKinsokuLineBreakRules\", true));\n if (opts.allowSpaceOfSameStyleInTable) p.push(onOff(\"w:allowSpaceOfSameStyleInTable\", true));\n if (opts.doNotSuppressIndentation) p.push(onOff(\"w:doNotSuppressIndentation\", true));\n if (opts.doNotAutofitConstrainedTables) p.push(onOff(\"w:doNotAutofitConstrainedTables\", true));\n if (opts.autofitToFirstFixedWidthCell) p.push(onOff(\"w:autofitToFirstFixedWidthCell\", true));\n if (opts.underlineTabInNumberingList) p.push(onOff(\"w:underlineTabInNumList\", true));\n if (opts.displayHangulFixedWidth) p.push(onOff(\"w:displayHangulFixedWidth\", true));\n if (opts.splitPgBreakAndParaMark) p.push(onOff(\"w:splitPgBreakAndParaMark\", true));\n if (opts.doNotVerticallyAlignCellWithSp) p.push(onOff(\"w:doNotVertAlignCellWithSp\", true));\n if (opts.doNotBreakConstrainedForcedTable)\n p.push(onOff(\"w:doNotBreakConstrainedForcedTable\", true));\n if (opts.ignoreVerticalAlignmentInTextboxes) p.push(onOff(\"w:doNotVertAlignInTxbx\", true));\n if (opts.useAnsiKerningPairs) p.push(onOff(\"w:useAnsiKerningPairs\", true));\n if (opts.cachedColumnBalance) p.push(onOff(\"w:cachedColBalance\", true));\n // compatSetting elements last (XSD order)\n if (opts.version) p.push(compatSetting(\"compatibilityMode\", opts.version));\n if (opts.overrideTableStyleFontSizeAndJustification)\n p.push(compatSetting(\"overrideTableStyleFontSizeAndJustification\", 1));\n if (opts.enableOpenTypeFeatures) p.push(compatSetting(\"enableOpenTypeFeatures\", 1));\n if (opts.doNotFlipMirrorIndents) p.push(compatSetting(\"doNotFlipMirrorIndents\", 1));\n\n // Additional compatSetting entries (sugar fields above take precedence on name clash)\n if (opts.compatSettings) {\n const emitted = new Set<string>();\n if (opts.version) emitted.add(\"compatibilityMode\");\n if (opts.overrideTableStyleFontSizeAndJustification)\n emitted.add(\"overrideTableStyleFontSizeAndJustification\");\n if (opts.enableOpenTypeFeatures) emitted.add(\"enableOpenTypeFeatures\");\n if (opts.doNotFlipMirrorIndents) emitted.add(\"doNotFlipMirrorIndents\");\n for (const cs of opts.compatSettings) {\n if (emitted.has(cs.name)) continue;\n p.push(compatSetting(cs.name, cs.val, cs.uri));\n emitted.add(cs.name);\n }\n }\n return p.length ? `<w:compat>${p.join(\"\")}</w:compat>` : \"\";\n}\n\n// ── Namespace attributes ──\n\nconst SETTINGS_NS =\n documentNamespaceAttributes([\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n ]) + ' mc:Ignorable=\"w14 w15 wp14\"';\n\n// ── Descriptor ──\n\nexport const settingsDesc: CustomDescriptor<SettingsOptions> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n // Round-trip: when parse captured the settings part verbatim, re-emit it\n // as-is (the structured path below only covers a subset of CT_Settings).\n // Use captured root attributes (xmlns:* + mc:Ignorable) so source-specific\n // namespaces (xmlns:sl, xmlns:wpsCustomData, …) are preserved.\n if (opts.rawXml !== undefined) {\n const ns = opts.rootAttributes ? attrStr(opts.rootAttributes) : SETTINGS_NS;\n return `<w:settings ${ns}>${opts.rawXml}</w:settings>`;\n }\n\n const p: string[] = [];\n\n // XSD CT_Settings sequence order\n if (opts.writeProtection !== undefined) p.push(stringifyWriteProtect(opts.writeProtection));\n if (opts.view !== undefined) p.push(attrEl(\"w:view\", { \"w:val\": opts.view }));\n if (opts.zoom !== undefined)\n p.push(attrEl(\"w:zoom\", { \"w:percent\": opts.zoom.percent ?? 100, \"w:val\": opts.zoom.val }));\n p.push(onOff(\"w:removePersonalInformation\", opts.removePersonalInformation));\n p.push(onOff(\"w:removeDateAndTime\", opts.removeDateAndTime));\n // XSD order: doNotDisplayPageBoundaries (5) → displayBackgroundShape (6)\n p.push(onOff(\"w:doNotDisplayPageBoundaries\", opts.doNotDisplayPageBoundaries));\n p.push(onOff(\"w:displayBackgroundShape\", opts.displayBackgroundShape));\n p.push(onOff(\"w:printPostScriptOverText\", opts.printPostScriptOverText));\n p.push(onOff(\"w:printFractionalCharacterWidth\", opts.printFractionalCharacterWidth));\n p.push(onOff(\"w:printFormsData\", opts.printFormsData));\n p.push(onOff(\"w:embedTrueTypeFonts\", opts.embedTrueTypeFonts));\n p.push(onOff(\"w:embedSystemFonts\", opts.embedSystemFonts));\n p.push(onOff(\"w:saveSubsetFonts\", opts.saveSubsetFonts));\n p.push(onOff(\"w:saveFormsData\", opts.saveFormsData));\n p.push(onOff(\"w:mirrorMargins\", opts.mirrorMargins));\n p.push(onOff(\"w:alignBordersAndEdges\", opts.alignBordersAndEdges));\n p.push(onOff(\"w:bordersDoNotSurroundHeader\", opts.bordersDoNotSurroundHeader));\n p.push(onOff(\"w:bordersDoNotSurroundFooter\", opts.bordersDoNotSurroundFooter));\n p.push(onOff(\"w:gutterAtTop\", opts.gutterAtTop));\n p.push(onOff(\"w:hideSpellingErrors\", opts.hideSpellingErrors));\n p.push(onOff(\"w:hideGrammaticalErrors\", opts.hideGrammaticalErrors));\n\n // activeWritingStyle\n if (opts.activeWritingStyle !== undefined) {\n for (const ws of opts.activeWritingStyle) {\n const attrs: Record<string, string | number | boolean> = {};\n if (ws.lang !== undefined) attrs[\"w:lang\"] = ws.lang;\n if (ws.vendorID !== undefined) attrs[\"w:vendorID\"] = ws.vendorID;\n if (ws.dllVersion !== undefined) attrs[\"w:dllVersion\"] = ws.dllVersion;\n if (ws.nlCheck !== undefined) attrs[\"w:nlCheck\"] = ws.nlCheck;\n if (ws.checkStyle !== undefined) attrs[\"w:checkStyle\"] = ws.checkStyle;\n if (ws.appCheck !== undefined) attrs[\"w:appCheck\"] = ws.appCheck;\n if (ws.appName !== undefined) attrs[\"w:appName\"] = ws.appName;\n p.push(attrEl(\"w:activeWritingStyle\", attrs));\n }\n }\n\n // proofState\n if (opts.proofState !== undefined) {\n const attrs: Record<string, string> = {};\n if (opts.proofState.spelling !== undefined) attrs[\"w:spelling\"] = opts.proofState.spelling;\n if (opts.proofState.grammar !== undefined) attrs[\"w:grammar\"] = opts.proofState.grammar;\n p.push(attrEl(\"w:proofState\", attrs));\n }\n\n p.push(onOff(\"w:formsDesign\", opts.formsDesign));\n\n if (opts.attachedTemplate !== undefined)\n p.push(attrEl(\"w:attachedTemplate\", { \"r:id\": opts.attachedTemplate }));\n p.push(onOff(\"w:linkStyles\", opts.linkStyles));\n\n // stylePaneFormatFilter\n if (opts.stylePaneFormatFilter !== undefined) {\n const f = opts.stylePaneFormatFilter;\n const attrs: Record<string, string> = {};\n const flags: [keyof typeof f, string][] = [\n [\"allStyles\", \"w:allStyles\"],\n [\"customStyles\", \"w:customStyles\"],\n [\"stylesInUse\", \"w:stylesInUse\"],\n [\"headingStyles\", \"w:headingStyles\"],\n [\"numberingStyles\", \"w:numberingStyles\"],\n [\"tableStyles\", \"w:tableStyles\"],\n [\"directFormattingOnRuns\", \"w:directFormattingOnRuns\"],\n [\"directFormattingOnParagraphs\", \"w:directFormattingOnParagraphs\"],\n [\"directFormattingOnNumbering\", \"w:directFormattingOnNumbering\"],\n [\"directFormattingOnTables\", \"w:directFormattingOnTables\"],\n [\"clearFormatting\", \"w:clearFormatting\"],\n [\"top3HeadingStyles\", \"w:top3HeadingStyles\"],\n [\"visibleStyles\", \"w:visibleStyles\"],\n [\"alternateStyleNames\", \"w:alternateStyleNames\"],\n [\"latentStyles\", \"w:latentStyles\"],\n ];\n for (const [prop, xmlKey] of flags) {\n if (f[prop] !== undefined) attrs[xmlKey] = f[prop] ? \"1\" : \"0\";\n }\n p.push(attrEl(\"w:stylePaneFormatFilter\", attrs));\n }\n\n p.push(strVal(\"w:stylePaneSortMethod\", opts.stylePaneSortMethod));\n p.push(strVal(\"w:documentType\", opts.documentType));\n\n if (opts.revisionView !== undefined) p.push(stringifyRevisionView(opts.revisionView));\n p.push(onOff(\"w:trackRevisions\", opts.trackRevisions));\n p.push(onOff(\"w:doNotTrackMoves\", opts.doNotTrackMoves));\n p.push(onOff(\"w:doNotTrackFormatting\", opts.doNotTrackFormatting));\n\n if (opts.mailMerge !== undefined) p.push(stringifyMailMerge(opts.mailMerge));\n if (opts.documentProtection !== undefined) p.push(stringifyDocProtect(opts.documentProtection));\n\n p.push(onOff(\"w:autoFormatOverride\", opts.autoFormatOverride));\n p.push(onOff(\"w:styleLockTheme\", opts.styleLockTheme));\n p.push(onOff(\"w:styleLockQFSet\", opts.styleLockQFSet));\n\n // defaultTabStop — optional (CT_Settings minOccurs=0); emit only when set\n if (opts.defaultTabStop !== undefined) p.push(numVal(\"w:defaultTabStop\", opts.defaultTabStop)!);\n\n // hyphenation\n p.push(onOff(\"w:autoHyphenation\", opts.hyphenation?.autoHyphenation));\n p.push(numVal(\"w:consecutiveHyphenLimit\", opts.hyphenation?.consecutiveHyphenLimit));\n p.push(numVal(\"w:hyphenationZone\", opts.hyphenation?.hyphenationZone));\n p.push(onOff(\"w:doNotHyphenateCaps\", opts.hyphenation?.doNotHyphenateCaps));\n\n p.push(onOff(\"w:showEnvelope\", opts.showEnvelope));\n p.push(numVal(\"w:summaryLength\", opts.summaryLength));\n p.push(strVal(\"w:clickAndTypeStyle\", opts.clickAndTypeStyle));\n p.push(strVal(\"w:defaultTableStyle\", opts.defaultTableStyle));\n p.push(onOff(\"w:evenAndOddHeaders\", opts.evenAndOddHeaders));\n p.push(onOff(\"w:bookFoldRevPrinting\", opts.bookFoldRevPrinting));\n p.push(onOff(\"w:bookFoldPrinting\", opts.bookFoldPrinting));\n p.push(numVal(\"w:bookFoldPrintingSheets\", opts.bookFoldPrintingSheets));\n p.push(numVal(\"w:drawingGridHorizontalSpacing\", opts.drawingGridHorizontalSpacing));\n p.push(numVal(\"w:drawingGridVerticalSpacing\", opts.drawingGridVerticalSpacing));\n p.push(numVal(\"w:displayHorizontalDrawingGridEvery\", opts.displayHorizontalDrawingGridEvery));\n p.push(numVal(\"w:displayVerticalDrawingGridEvery\", opts.displayVerticalDrawingGridEvery));\n // XSD order: doNotUseMarginsForDrawingGridOrigin (55) → origins (56,57)\n p.push(\n onOff(\"w:doNotUseMarginsForDrawingGridOrigin\", opts.doNotUseMarginsForDrawingGridOrigin),\n );\n p.push(numVal(\"w:drawingGridHorizontalOrigin\", opts.drawingGridHorizontalOrigin));\n p.push(numVal(\"w:drawingGridVerticalOrigin\", opts.drawingGridVerticalOrigin));\n p.push(onOff(\"w:doNotShadeFormData\", opts.doNotShadeFormData));\n p.push(onOff(\"w:noPunctuationKerning\", opts.noPunctuationKerning));\n\n // characterSpacingControl — optional (CT_Settings minOccurs=0); emit only when set\n if (opts.characterSpacingControl !== undefined) {\n p.push(strVal(\"w:characterSpacingControl\", opts.characterSpacingControl)!);\n }\n\n p.push(onOff(\"w:printTwoOnOne\", opts.printTwoOnOne));\n p.push(onOff(\"w:strictFirstAndLastChars\", opts.strictFirstAndLastChars));\n\n if (opts.noLineBreaksAfter !== undefined) {\n const attrs: Record<string, string> = {};\n if (opts.noLineBreaksAfter.lang !== undefined) attrs[\"w:lang\"] = opts.noLineBreaksAfter.lang;\n if (opts.noLineBreaksAfter.val !== undefined) attrs[\"w:val\"] = opts.noLineBreaksAfter.val;\n p.push(attrEl(\"w:noLineBreaksAfter\", attrs));\n }\n if (opts.noLineBreaksBefore !== undefined) {\n const attrs: Record<string, string> = {};\n if (opts.noLineBreaksBefore.lang !== undefined)\n attrs[\"w:lang\"] = opts.noLineBreaksBefore.lang;\n if (opts.noLineBreaksBefore.val !== undefined) attrs[\"w:val\"] = opts.noLineBreaksBefore.val;\n p.push(attrEl(\"w:noLineBreaksBefore\", attrs));\n }\n\n p.push(onOff(\"w:savePreviewPicture\", opts.savePreviewPicture));\n p.push(onOff(\"w:doNotValidateAgainstSchema\", opts.doNotValidateAgainstSchema));\n p.push(onOff(\"w:saveInvalidXml\", opts.saveInvalidXml));\n p.push(onOff(\"w:ignoreMixedContent\", opts.ignoreMixedContent));\n p.push(onOff(\"w:alwaysShowPlaceholderText\", opts.alwaysShowPlaceholderText));\n p.push(onOff(\"w:doNotDemarcateInvalidXml\", opts.doNotDemarcateInvalidXml));\n p.push(onOff(\"w:saveXmlDataOnly\", opts.saveXmlDataOnly));\n p.push(onOff(\"w:useXSLTWhenSaving\", opts.useXSLTWhenSaving));\n\n if (opts.saveThroughXslt !== undefined) {\n const attrs: Record<string, string> = {};\n if (opts.saveThroughXslt.id !== undefined) attrs[\"r:id\"] = opts.saveThroughXslt.id;\n if (opts.saveThroughXslt.val !== undefined) attrs[\"w:val\"] = opts.saveThroughXslt.val;\n if (opts.saveThroughXslt.solutionID !== undefined)\n attrs[\"w:solutionID\"] = opts.saveThroughXslt.solutionID;\n p.push(attrEl(\"w:saveThroughXslt\", attrs));\n }\n\n p.push(onOff(\"w:showXMLTags\", opts.showXMLTags));\n p.push(onOff(\"w:alwaysMergeEmptyNamespace\", opts.alwaysMergeEmptyNamespace));\n p.push(onOff(\"w:updateFields\", opts.updateFields));\n\n if (opts.hdrShapeDefaults !== undefined)\n p.push(\n `<w:hdrShapeDefaults>${stringifyShapeDefaultsInner(opts.hdrShapeDefaults)}</w:hdrShapeDefaults>`,\n );\n if (opts.footnotePr !== undefined) p.push(stringifyFootnotePr(opts.footnotePr));\n if (opts.endnotePr !== undefined) p.push(stringifyEndnotePr(opts.endnotePr));\n\n // Compatibility — tri-state:\n // undefined → fresh MS Office defaults (4 compatSettings)\n // object → user-specified fields (version defaults to 15)\n // false → omit <w:compat> entirely\n if (opts.compatibility !== false) {\n const compatOpts =\n opts.compatibility === undefined\n ? FRESH_COMPATIBILITY\n : {\n ...opts.compatibility,\n version: opts.compatibility.version ?? 15,\n };\n const compatXml = stringifyCompatibility(compatOpts);\n if (compatXml) p.push(compatXml);\n }\n\n // docVars\n if (opts.docVars?.length) {\n const vars = opts.docVars\n .map((v) => attrEl(\"w:docVar\", { \"w:name\": v.name, \"w:val\": v.val }))\n .join(\"\");\n p.push(`<w:docVars>${vars}</w:docVars>`);\n }\n\n if (opts.rsids !== undefined) p.push(stringifyRsids(opts.rsids));\n if (opts.mathPr !== undefined) p.push(stringifyMathPr(opts.mathPr));\n\n if (opts.attachedSchema !== undefined) {\n for (const schema of opts.attachedSchema) p.push(strVal(\"w:attachedSchema\", schema)!);\n }\n\n // XSD order: attachedSchema → themeFontLang → clrSchemeMapping → doNotIncludeSubdocsInStats\n if (opts.themeFontLang !== undefined) {\n const a: Record<string, string> = {};\n if (opts.themeFontLang.val !== undefined) a[\"w:val\"] = opts.themeFontLang.val;\n if (opts.themeFontLang.eastAsia !== undefined) a[\"w:eastAsia\"] = opts.themeFontLang.eastAsia;\n if (opts.themeFontLang.bidi !== undefined) a[\"w:bidi\"] = opts.themeFontLang.bidi;\n p.push(attrEl(\"w:themeFontLang\", a));\n }\n if (opts.colorSchemeMapping !== undefined)\n p.push(stringifyColorSchemeMapping(opts.colorSchemeMapping));\n p.push(onOff(\"w:doNotIncludeSubdocsInStats\", opts.doNotIncludeSubdocsInStats));\n p.push(onOff(\"w:doNotAutoCompressPictures\", opts.doNotAutoCompressPictures));\n if (opts.forceUpgrade !== undefined) p.push(\"<w:forceUpgrade/>\");\n if (opts.captions !== undefined) p.push(stringifyCaptions(opts.captions));\n if (opts.readModeInkLockDown !== undefined)\n p.push(stringifyReadModeInkLockDown(opts.readModeInkLockDown));\n\n if (opts.smartTagType !== undefined) {\n for (const st of opts.smartTagType) {\n const attrs: Record<string, string> = {};\n if (st.namespace !== undefined) attrs[\"w:namespace\"] = st.namespace;\n if (st.namespaceuri !== undefined) attrs[\"w:namespaceuri\"] = st.namespaceuri;\n if (st.name !== undefined) attrs[\"w:name\"] = st.name;\n if (st.url !== undefined) attrs[\"w:url\"] = st.url;\n p.push(attrEl(\"w:smartTagType\", attrs));\n }\n }\n\n // XSD order: smartTagType → shapeDefaults → doNotEmbedSmartTags → decimalSymbol\n if (opts.shapeDefaults !== undefined)\n p.push(\n `<w:shapeDefaults>${stringifyShapeDefaultsInner(opts.shapeDefaults)}</w:shapeDefaults>`,\n );\n p.push(onOff(\"w:doNotEmbedSmartTags\", opts.doNotEmbedSmartTags));\n p.push(strVal(\"w:decimalSymbol\", opts.decimalSymbol));\n p.push(strVal(\"w:listSeparator\", opts.listSeparator));\n\n // Word 2010/2013 document identifiers — CT_Settings trailing sequence\n // (decimalSymbol → listSeparator → w14:docId → w15:chartTrackingRefBased → w15:docId).\n // Preserved verbatim for round-trip fidelity; val attribute is namespace-scoped.\n if (opts.w14DocId !== undefined) p.push(strVal(\"w14:docId\", opts.w14DocId));\n if (opts.w15ChartTrackingRefBased) p.push(`<w15:chartTrackingRefBased/>`);\n if (opts.w15DocId !== undefined) p.push(strVal(\"w15:docId\", opts.w15DocId));\n\n const body = p.join(\"\");\n return `<w:settings ${SETTINGS_NS}>${body}</w:settings>`;\n },\n\n parse(el, _ctx) {\n const opts: Record<string, unknown> = {};\n\n // writeProtection (CT_WriteProtection)\n const wpEl = findChild(el, \"w:writeProtection\");\n if (wpEl) {\n const wp = readPasswordAttrs(wpEl) as WriteProtectionOptions;\n const recommended = attr(wpEl, \"w:recommended\");\n if (recommended !== undefined) wp.recommended = parseOnOff(recommended) ?? false;\n if (Object.keys(wp).length > 0) opts.writeProtection = wp;\n }\n\n // view → w:view/@w:val\n const viewVal = readStr(findChild(el, \"w:view\"), \"w:val\");\n if (viewVal) opts.view = viewVal;\n\n // zoom → w:zoom/@w:percent, @w:val\n const zoomEl = findChild(el, \"w:zoom\");\n if (zoomEl) {\n const zoom: Record<string, unknown> = {};\n const percent = attr(zoomEl, \"w:percent\");\n if (percent) zoom.percent = parseInt(percent, 10);\n const zval = attr(zoomEl, \"w:val\");\n if (zval) zoom.val = zval;\n if (Object.keys(zoom).length > 0) opts.zoom = zoom;\n }\n\n // CT_OnOff scalar settings (presence = true unless w:val is explicitly false)\n const onOffScalar: [string, string][] = [\n [\"removePersonalInformation\", \"w:removePersonalInformation\"],\n [\"removeDateAndTime\", \"w:removeDateAndTime\"],\n [\"doNotDisplayPageBoundaries\", \"w:doNotDisplayPageBoundaries\"],\n [\"displayBackgroundShape\", \"w:displayBackgroundShape\"],\n [\"printPostScriptOverText\", \"w:printPostScriptOverText\"],\n [\"printFractionalCharacterWidth\", \"w:printFractionalCharacterWidth\"],\n [\"printFormsData\", \"w:printFormsData\"],\n [\"embedTrueTypeFonts\", \"w:embedTrueTypeFonts\"],\n [\"embedSystemFonts\", \"w:embedSystemFonts\"],\n [\"saveSubsetFonts\", \"w:saveSubsetFonts\"],\n [\"saveFormsData\", \"w:saveFormsData\"],\n [\"mirrorMargins\", \"w:mirrorMargins\"],\n [\"alignBordersAndEdges\", \"w:alignBordersAndEdges\"],\n [\"bordersDoNotSurroundHeader\", \"w:bordersDoNotSurroundHeader\"],\n [\"bordersDoNotSurroundFooter\", \"w:bordersDoNotSurroundFooter\"],\n [\"gutterAtTop\", \"w:gutterAtTop\"],\n [\"hideSpellingErrors\", \"w:hideSpellingErrors\"],\n [\"hideGrammaticalErrors\", \"w:hideGrammaticalErrors\"],\n [\"formsDesign\", \"w:formsDesign\"],\n [\"linkStyles\", \"w:linkStyles\"],\n [\"trackRevisions\", \"w:trackRevisions\"],\n [\"doNotTrackMoves\", \"w:doNotTrackMoves\"],\n [\"doNotTrackFormatting\", \"w:doNotTrackFormatting\"],\n [\"autoFormatOverride\", \"w:autoFormatOverride\"],\n [\"styleLockTheme\", \"w:styleLockTheme\"],\n [\"styleLockQFSet\", \"w:styleLockQFSet\"],\n [\"showEnvelope\", \"w:showEnvelope\"],\n [\"evenAndOddHeaders\", \"w:evenAndOddHeaders\"],\n [\"bookFoldRevPrinting\", \"w:bookFoldRevPrinting\"],\n [\"bookFoldPrinting\", \"w:bookFoldPrinting\"],\n [\"doNotUseMarginsForDrawingGridOrigin\", \"w:doNotUseMarginsForDrawingGridOrigin\"],\n [\"doNotShadeFormData\", \"w:doNotShadeFormData\"],\n [\"noPunctuationKerning\", \"w:noPunctuationKerning\"],\n [\"printTwoOnOne\", \"w:printTwoOnOne\"],\n [\"strictFirstAndLastChars\", \"w:strictFirstAndLastChars\"],\n [\"savePreviewPicture\", \"w:savePreviewPicture\"],\n [\"doNotValidateAgainstSchema\", \"w:doNotValidateAgainstSchema\"],\n [\"saveInvalidXml\", \"w:saveInvalidXml\"],\n [\"ignoreMixedContent\", \"w:ignoreMixedContent\"],\n [\"alwaysShowPlaceholderText\", \"w:alwaysShowPlaceholderText\"],\n [\"doNotDemarcateInvalidXml\", \"w:doNotDemarcateInvalidXml\"],\n [\"saveXmlDataOnly\", \"w:saveXmlDataOnly\"],\n [\"useXSLTWhenSaving\", \"w:useXSLTWhenSaving\"],\n [\"showXMLTags\", \"w:showXMLTags\"],\n [\"alwaysMergeEmptyNamespace\", \"w:alwaysMergeEmptyNamespace\"],\n [\"updateFields\", \"w:updateFields\"],\n [\"doNotIncludeSubdocsInStats\", \"w:doNotIncludeSubdocsInStats\"],\n [\"doNotAutoCompressPictures\", \"w:doNotAutoCompressPictures\"],\n [\"doNotEmbedSmartTags\", \"w:doNotEmbedSmartTags\"],\n ];\n for (const [key, tag] of onOffScalar) {\n const v = readOnOff(findChild(el, tag));\n if (v !== undefined) opts[key] = v;\n }\n\n // activeWritingStyle → w:activeWritingStyle[] (multiple)\n const awsList: Array<Record<string, unknown>> = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:activeWritingStyle\") continue;\n const entry: Record<string, unknown> = {};\n const lang = attr(child, \"w:lang\");\n if (lang) entry.lang = lang;\n const vendorID = attr(child, \"w:vendorID\");\n if (vendorID) entry.vendorID = vendorID;\n const dllVersion = attr(child, \"w:dllVersion\");\n if (dllVersion) entry.dllVersion = dllVersion;\n const nlCheck = attr(child, \"w:nlCheck\");\n if (nlCheck !== undefined) entry.nlCheck = parseOnOff(nlCheck) ?? true;\n const checkStyle = attr(child, \"w:checkStyle\");\n if (checkStyle !== undefined) entry.checkStyle = parseOnOff(checkStyle) ?? true;\n const appCheck = attr(child, \"w:appCheck\");\n if (appCheck) entry.appCheck = appCheck;\n const appName = attr(child, \"w:appName\");\n if (appName) entry.appName = appName;\n if (Object.keys(entry).length > 0) awsList.push(entry);\n }\n if (awsList.length > 0) opts.activeWritingStyle = awsList;\n\n // proofState → w:proofState/@w:spelling, @w:grammar\n const proofEl = findChild(el, \"w:proofState\");\n if (proofEl) {\n const proof: Record<string, unknown> = {};\n const spelling = attr(proofEl, \"w:spelling\");\n if (spelling) proof.spelling = spelling;\n const grammar = attr(proofEl, \"w:grammar\");\n if (grammar) proof.grammar = grammar;\n if (Object.keys(proof).length > 0) opts.proofState = proof;\n }\n\n // attachedTemplate → w:attachedTemplate/@r:id\n const attachedTplEl = findChild(el, \"w:attachedTemplate\");\n if (attachedTplEl) {\n const rid = attr(attachedTplEl, \"r:id\");\n if (rid) opts.attachedTemplate = rid;\n }\n\n // stylePaneFormatFilter → w:stylePaneFormatFilter (complex attributes)\n const spffEl = findChild(el, \"w:stylePaneFormatFilter\");\n if (spffEl) {\n const filter: Record<string, boolean> = {};\n const spffFlags: [string, string][] = [\n [\"allStyles\", \"w:allStyles\"],\n [\"customStyles\", \"w:customStyles\"],\n [\"stylesInUse\", \"w:stylesInUse\"],\n [\"headingStyles\", \"w:headingStyles\"],\n [\"numberingStyles\", \"w:numberingStyles\"],\n [\"tableStyles\", \"w:tableStyles\"],\n [\"directFormattingOnRuns\", \"w:directFormattingOnRuns\"],\n [\"directFormattingOnParagraphs\", \"w:directFormattingOnParagraphs\"],\n [\"directFormattingOnNumbering\", \"w:directFormattingOnNumbering\"],\n [\"directFormattingOnTables\", \"w:directFormattingOnTables\"],\n [\"clearFormatting\", \"w:clearFormatting\"],\n [\"top3HeadingStyles\", \"w:top3HeadingStyles\"],\n [\"visibleStyles\", \"w:visibleStyles\"],\n [\"alternateStyleNames\", \"w:alternateStyleNames\"],\n [\"latentStyles\", \"w:latentStyles\"],\n ];\n for (const [prop, xmlKey] of spffFlags) {\n const v = attr(spffEl, xmlKey);\n if (v !== undefined) filter[prop] = parseOnOff(v) ?? true;\n }\n if (Object.keys(filter).length > 0) opts.stylePaneFormatFilter = filter;\n }\n\n // stylePaneSortMethod / documentType / clickAndTypeStyle / defaultTableStyle\n const stylePaneSortMethod = readStr(findChild(el, \"w:stylePaneSortMethod\"), \"w:val\");\n if (stylePaneSortMethod)\n opts.stylePaneSortMethod = stylePaneSortMethod as SettingsOptions[\"stylePaneSortMethod\"];\n const documentType = readStr(findChild(el, \"w:documentType\"), \"w:val\");\n if (documentType) opts.documentType = documentType as SettingsOptions[\"documentType\"];\n const clickAndTypeStyle = readStr(findChild(el, \"w:clickAndTypeStyle\"), \"w:val\");\n if (clickAndTypeStyle) opts.clickAndTypeStyle = clickAndTypeStyle;\n const defaultTableStyle = readStr(findChild(el, \"w:defaultTableStyle\"), \"w:val\");\n if (defaultTableStyle) opts.defaultTableStyle = defaultTableStyle;\n\n // mailMerge → w:mailMerge (CT_MailMerge)\n const mailMergeEl = findChild(el, \"w:mailMerge\");\n if (mailMergeEl) {\n const mm = parseMailMerge(mailMergeEl);\n if (mm) opts.mailMerge = mm;\n }\n\n // revisionView → w:revisionView (CT_TrackChangesView)\n const revViewEl = findChild(el, \"w:revisionView\");\n if (revViewEl) {\n const rv: Record<string, boolean> = {};\n const rvFlags: [string, string][] = [\n [\"markup\", \"w:markup\"],\n [\"comments\", \"w:comments\"],\n [\"insDel\", \"w:insDel\"],\n [\"formatting\", \"w:formatting\"],\n [\"inkAnnotations\", \"w:inkAnnotations\"],\n ];\n for (const [k, a] of rvFlags) {\n const v = attr(revViewEl, a);\n if (v !== undefined) rv[k] = parseOnOff(v) ?? true;\n }\n if (Object.keys(rv).length > 0) opts.revisionView = rv as RevisionViewOptions;\n }\n\n // documentProtection → w:documentProtection (CT_DocProtect)\n const docProtEl = findChild(el, \"w:documentProtection\");\n if (docProtEl) {\n const prot: DocumentProtectionOptions = {};\n const edit = attr(docProtEl, \"w:edit\");\n if (edit && (DOC_PROTECT_EDITS as readonly string[]).includes(edit)) {\n prot.edit = edit as DocumentProtectionOptions[\"edit\"];\n }\n const enforcement = attr(docProtEl, \"w:enforcement\");\n if (enforcement !== undefined) {\n Object.assign(prot, readPasswordAttrs(docProtEl));\n const formatting = attr(docProtEl, \"w:formatting\");\n if (formatting !== undefined) prot.formatting = parseOnOff(formatting) ?? false;\n }\n if (Object.keys(prot).length > 0) opts.documentProtection = prot;\n }\n\n // defaultTabStop → w:defaultTabStop/@w:val\n const defaultTabStop = readNum(findChild(el, \"w:defaultTabStop\"), \"w:val\");\n if (defaultTabStop !== undefined) opts.defaultTabStop = defaultTabStop;\n\n // hyphenation (autoHyphenation/consecutiveHyphenLimit/hyphenationZone/doNotHyphenateCaps)\n if (\n findChild(el, \"w:autoHyphenation\") ||\n findChild(el, \"w:doNotHyphenateCaps\") ||\n findChild(el, \"w:consecutiveHyphenLimit\") ||\n findChild(el, \"w:hyphenationZone\")\n ) {\n const hyphenation: Record<string, unknown> = {};\n const autoHyph = readOnOff(findChild(el, \"w:autoHyphenation\"));\n if (autoHyph !== undefined) hyphenation.autoHyphenation = autoHyph;\n const noHyphCaps = readOnOff(findChild(el, \"w:doNotHyphenateCaps\"));\n if (noHyphCaps !== undefined) hyphenation.doNotHyphenateCaps = noHyphCaps;\n const consLimit = readNum(findChild(el, \"w:consecutiveHyphenLimit\"), \"w:val\");\n if (consLimit !== undefined) hyphenation.consecutiveHyphenLimit = consLimit;\n const zone = readNum(findChild(el, \"w:hyphenationZone\"), \"w:val\");\n if (zone !== undefined) hyphenation.hyphenationZone = zone;\n if (Object.keys(hyphenation).length > 0) opts.hyphenation = hyphenation;\n }\n\n // summaryLength → w:summaryLength/@w:val\n const summaryLength = readNum(findChild(el, \"w:summaryLength\"), \"w:val\");\n if (summaryLength !== undefined) opts.summaryLength = summaryLength;\n\n // bookFoldPrintingSheets → w:bookFoldPrintingSheets/@w:val\n const bookFoldSheets = readNum(findChild(el, \"w:bookFoldPrintingSheets\"), \"w:val\");\n if (bookFoldSheets !== undefined) opts.bookFoldPrintingSheets = bookFoldSheets;\n\n // drawing grid numerics\n const drawNum: [string, string][] = [\n [\"drawingGridHorizontalSpacing\", \"w:drawingGridHorizontalSpacing\"],\n [\"drawingGridVerticalSpacing\", \"w:drawingGridVerticalSpacing\"],\n [\"displayHorizontalDrawingGridEvery\", \"w:displayHorizontalDrawingGridEvery\"],\n [\"displayVerticalDrawingGridEvery\", \"w:displayVerticalDrawingGridEvery\"],\n [\"drawingGridHorizontalOrigin\", \"w:drawingGridHorizontalOrigin\"],\n [\"drawingGridVerticalOrigin\", \"w:drawingGridVerticalOrigin\"],\n ];\n for (const [key, tag] of drawNum) {\n const v = readNum(findChild(el, tag), \"w:val\");\n if (v !== undefined) opts[key] = v;\n }\n\n // characterSpacingControl → w:characterSpacingControl/@w:val\n const characterSpacingControl = readStr(findChild(el, \"w:characterSpacingControl\"), \"w:val\");\n if (characterSpacingControl) {\n opts.characterSpacingControl =\n characterSpacingControl as SettingsOptions[\"characterSpacingControl\"];\n }\n\n // noLineBreaksAfter/Before → w:noLineBreaksAfter/Before (w:lang, w:val)\n const lineBreakPairs: [string, string][] = [\n [\"noLineBreaksAfter\", \"w:noLineBreaksAfter\"],\n [\"noLineBreaksBefore\", \"w:noLineBreaksBefore\"],\n ];\n for (const [key, tag] of lineBreakPairs) {\n const lbEl = findChild(el, tag);\n if (!lbEl) continue;\n const entry: Record<string, string> = {};\n const lang = attr(lbEl, \"w:lang\");\n if (lang) entry.lang = lang;\n const val = attr(lbEl, \"w:val\");\n if (val) entry.val = val;\n if (Object.keys(entry).length > 0) opts[key] = entry;\n }\n\n // saveThroughXslt → w:saveThroughXslt (r:id, w:val, w:solutionID)\n const stxEl = findChild(el, \"w:saveThroughXslt\");\n if (stxEl) {\n const stx: Record<string, string> = {};\n const id = attr(stxEl, \"r:id\");\n if (id) stx.id = id;\n const val = attr(stxEl, \"w:val\");\n if (val) stx.val = val;\n const solutionID = attr(stxEl, \"w:solutionID\");\n if (solutionID) stx.solutionID = solutionID;\n if (Object.keys(stx).length > 0) opts.saveThroughXslt = stx;\n }\n\n // hdrShapeDefaults / shapeDefaults → structured CT_ShapeDefaults content\n const hdrSdEl = findChild(el, \"w:hdrShapeDefaults\");\n if (hdrSdEl) opts.hdrShapeDefaults = parseShapeDefaultsInner(hdrSdEl);\n const sdEl = findChild(el, \"w:shapeDefaults\");\n if (sdEl) opts.shapeDefaults = parseShapeDefaultsInner(sdEl);\n\n // footnotePr / endnotePr (CT_FtnDocProps / CT_EdnDocProps)\n const fnPrEl = findChild(el, \"w:footnotePr\");\n if (fnPrEl) {\n const fn = parseFtnEdnPr(fnPrEl);\n if (fn) opts.footnotePr = fn;\n }\n const enPrEl = findChild(el, \"w:endnotePr\");\n if (enPrEl) {\n const en = parseFtnEdnPr(enPrEl);\n if (en) opts.endnotePr = en;\n }\n\n // compatibility — tri-state: object when <w:compat> holds content, false\n // when absent (prevents fresh defaults from being injected on round-trip).\n const compatEl = findChild(el, \"w:compat\");\n const compat = compatEl ? parseCompatibility(compatEl) : undefined;\n opts.compatibility = compat ?? false;\n\n // docVars → w:docVars/w:docVar\n const docVarsEl = findChild(el, \"w:docVars\");\n if (docVarsEl) {\n const vars: Array<{ name: string; val: string }> = [];\n for (const child of docVarsEl.elements ?? []) {\n if (child.name !== \"w:docVar\") continue;\n const name = attr(child, \"w:name\");\n const val = attr(child, \"w:val\");\n if (name !== undefined && val !== undefined) vars.push({ name, val });\n }\n if (vars.length > 0) opts.docVars = vars;\n }\n\n // rsids → w:rsids (CT_DocRsids)\n const rsidsEl = findChild(el, \"w:rsids\");\n if (rsidsEl) {\n const rsids: Record<string, unknown> = {};\n const root = readStr(findChild(rsidsEl, \"w:rsidRoot\"), \"w:val\");\n if (root) rsids.rsidRoot = root;\n const list: string[] = [];\n for (const child of rsidsEl.elements ?? []) {\n if (child.name !== \"w:rsid\") continue;\n const val = attr(child, \"w:val\");\n if (val) list.push(val);\n }\n if (list.length > 0) rsids.rsids = list;\n if (Object.keys(rsids).length > 0) opts.rsids = rsids as RsidsOptions;\n }\n\n // mathPr → m:mathPr (CT_MathPr)\n const mathPrEl = findChild(el, \"m:mathPr\");\n if (mathPrEl) {\n const mp = parseMathPr(mathPrEl);\n if (mp) opts.mathPr = mp;\n }\n\n // attachedSchema → w:attachedSchema/@w:val (multiple)\n const attachedSchemas: string[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:attachedSchema\") continue;\n const val = attr(child, \"w:val\");\n if (val) attachedSchemas.push(val);\n }\n if (attachedSchemas.length > 0) opts.attachedSchema = attachedSchemas;\n\n // themeFontLang → w:themeFontLang (CT_Language: val/eastAsia/bidi)\n const tflEl = findChild(el, \"w:themeFontLang\");\n if (tflEl) {\n const tfl: Record<string, string> = {};\n const val = attr(tflEl, \"w:val\");\n if (val) tfl.val = val;\n const eastAsia = attr(tflEl, \"w:eastAsia\");\n if (eastAsia) tfl.eastAsia = eastAsia;\n const bidi = attr(tflEl, \"w:bidi\");\n if (bidi) tfl.bidi = bidi;\n if (Object.keys(tfl).length > 0) opts.themeFontLang = tfl;\n }\n\n // clrSchemeMapping → w:clrSchemeMapping\n const csmEl = findChild(el, \"w:clrSchemeMapping\");\n if (csmEl) {\n const csm: Record<string, string> = {};\n const csmMap: [string, string][] = [\n [\"bg1\", \"w:bg1\"],\n [\"t1\", \"w:t1\"],\n [\"bg2\", \"w:bg2\"],\n [\"t2\", \"w:t2\"],\n [\"accent1\", \"w:accent1\"],\n [\"accent2\", \"w:accent2\"],\n [\"accent3\", \"w:accent3\"],\n [\"accent4\", \"w:accent4\"],\n [\"accent5\", \"w:accent5\"],\n [\"accent6\", \"w:accent6\"],\n [\"hyperlink\", \"w:hyperlink\"],\n [\"followedHyperlink\", \"w:followedHyperlink\"],\n ];\n for (const [key, xmlAttr] of csmMap) {\n const v = attr(csmEl, xmlAttr);\n if (v) csm[key] = v;\n }\n if (Object.keys(csm).length > 0) opts.colorSchemeMapping = csm;\n }\n\n // forceUpgrade → w:forceUpgrade (CT_Empty, presence)\n if (findChild(el, \"w:forceUpgrade\")) opts.forceUpgrade = true;\n\n // captions → w:captions (CT_Captions)\n const captionsEl = findChild(el, \"w:captions\");\n if (captionsEl) {\n const captions = parseCaptions(captionsEl);\n if (captions) opts.captions = captions;\n }\n\n // readModeInkLockDown → w:readModeInkLockDown\n const rmilEl = findChild(el, \"w:readModeInkLockDown\");\n if (rmilEl) {\n opts.readModeInkLockDown = {\n actualPg: parseOnOff(attr(rmilEl, \"w:actualPg\")) ?? true,\n w: parseInt(attr(rmilEl, \"w:w\") ?? \"0\", 10),\n h: parseInt(attr(rmilEl, \"w:h\") ?? \"0\", 10),\n fontSz: parseInt(attr(rmilEl, \"w:fontSz\") ?? \"0\", 10),\n } as ReadModeInkLockDownOptions;\n }\n\n // smartTagType → w:smartTagType[] (multiple)\n const smartTags: Array<Record<string, string>> = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:smartTagType\") continue;\n const entry: Record<string, string> = {};\n const ns = attr(child, \"w:namespace\");\n if (ns) entry.namespace = ns;\n const nsuri = attr(child, \"w:namespaceuri\");\n if (nsuri) entry.namespaceuri = nsuri;\n const name = attr(child, \"w:name\");\n if (name) entry.name = name;\n const url = attr(child, \"w:url\");\n if (url) entry.url = url;\n if (Object.keys(entry).length > 0) smartTags.push(entry);\n }\n if (smartTags.length > 0) opts.smartTagType = smartTags;\n\n // decimalSymbol / listSeparator → w:decimalSymbol|w:listSeparator/@w:val\n const decimalSymbol = readStr(findChild(el, \"w:decimalSymbol\"), \"w:val\");\n if (decimalSymbol) opts.decimalSymbol = decimalSymbol;\n const listSeparator = readStr(findChild(el, \"w:listSeparator\"), \"w:val\");\n if (listSeparator) opts.listSeparator = listSeparator;\n\n // Word 2010/2013 document identifiers — preserve for round-trip fidelity\n const w14DocId = readStr(findChild(el, \"w14:docId\"), \"w14:val\");\n if (w14DocId) opts.w14DocId = w14DocId;\n if (findChild(el, \"w15:chartTrackingRefBased\")) opts.w15ChartTrackingRefBased = true;\n const w15DocId = readStr(findChild(el, \"w15:docId\"), \"w15:val\");\n if (w15DocId) opts.w15DocId = w15DocId;\n\n return opts as unknown as SettingsOptions;\n },\n};\n\n/** Serialize the o: element sequence hosted by w:hdrShapeDefaults/w:shapeDefaults. */\nfunction stringifyShapeDefaultsInner(opts: ShapeDefaultsOptions): string {\n let s = \"\";\n if (opts.shapedefaults !== undefined) s += stringifyVmlShapeDefaults(opts.shapedefaults);\n if (opts.shapelayout !== undefined) s += stringifyVmlShapeLayout(opts.shapelayout);\n return s;\n}\n\n/** Parse the o: element sequence hosted by w:hdrShapeDefaults/w:shapeDefaults. */\nfunction parseShapeDefaultsInner(el: Element): ShapeDefaultsOptions {\n const out: Partial<ShapeDefaultsOptions> = {};\n const sd = findChild(el, \"o:shapedefaults\");\n if (sd) out.shapedefaults = parseVmlShapeDefaults(sd);\n const sl = findChild(el, \"o:shapelayout\");\n if (sl) out.shapelayout = parseVmlShapeLayout(sl);\n return out as ShapeDefaultsOptions;\n}\n","/**\n * Table of Contents Properties module.\n *\n * This module defines configuration options for table of contents generation,\n * including field switches and style mappings.\n *\n * Reference: http://officeopenxml.com/WPtableOfContents.php\n *\n * @module\n */\n\nimport type { SectionChild } from \"@shared/section\";\n\n/**\n * Represents a style-to-level mapping for table of contents entries.\n *\n * StyleLevel associates a paragraph style name with a TOC level, allowing\n * custom styles to be included in the table of contents at specific levels.\n *\n * @publicApi\n */\nexport class StyleLevel {\n /** The name of the paragraph style. */\n public styleName: string;\n /** The TOC level (1-9) to assign to this style. */\n public level: number;\n\n public constructor(styleName: string, level: number) {\n this.styleName = styleName;\n this.level = level;\n }\n}\n\n/**\n * Options for configuring a Table of Contents.\n *\n * These options control which content is included in the TOC and how it is formatted.\n * Options correspond to field switches in the TOC field code.\n *\n * Reference:\n * - https://www.ecma-international.org/publications/standards/Ecma-376.htm (Part 1, Page 1251)\n * - http://officeopenxml.com/WPtableOfContents.php\n */\nexport interface TableOfContentsOptions {\n /**\n * \\a option - Includes captioned items, but omits caption labels and numbers.\n * The identifier designated by text in this switch's field-argument corresponds to the caption label.\n * Use captionLabelIncludingNumbers (\\c) to build a table of captions with labels and numbers.\n */\n captionLabel?: string;\n\n /**\n * \\b option - Includes entries only from the portion of the document marked by\n * the bookmark named by text in this switch's field-argument.\n */\n entriesFromBookmark?: string;\n\n /**\n * \\c option - Includes figures, tables, charts, and other items that are numbered\n * by a SEQ field (§17.16.5.56). The sequence identifier designated by text in this switch's\n * field-argument, which corresponds to the caption label, shall match the identifier in the\n * corresponding SEQ field.\n */\n captionLabelIncludingNumbers?: string;\n\n /**\n * \\d option - When used with \\s, the text in this switch's field-argument defines\n * the separator between sequence and page numbers. The default separator is a hyphen (-).\n */\n sequenceAndPageNumbersSeparator?: string;\n\n /**\n * \\f option - Includes only those TC fields whose identifier exactly matches the\n * text in this switch's field-argument (which is typically a letter).\n */\n tcFieldIdentifier?: string;\n\n /**\n * \\h option - Makes the table of contents entries hyperlinks.\n */\n hyperlink?: boolean;\n\n /**\n * \\l option - Includes TC fields that assign entries to one of the levels specified\n * by text in this switch's field-argument as a range having the form startLevel-endLevel,\n * where startLevel and endLevel are integers, and startLevel has a value equal-to or less-than endLevel.\n * TC fields that assign entries to lower levels are skipped.\n */\n tcFieldLevelRange?: string;\n\n /**\n * \\n option - Without field-argument, omits page numbers from the table of contents.\n * Page numbers are omitted from all levels unless a range of entry levels is specified by\n * text in this switch's field-argument. A range is specified as for \\l.\n */\n pageNumbersEntryLevelsRange?: string;\n\n /**\n * \\o option - Uses paragraphs formatted with all or the specified range of builtin\n * heading styles. Headings in a style range are specified by text in this switch's\n * field-argument using the notation specified as for \\l, where each integer corresponds\n * to the style with a style ID of HeadingX (e.g. 1 corresponds to Heading1).\n * If no heading range is specified, all heading levels used in the document are listed.\n */\n headingStyleRange?: string;\n\n /**\n * \\p option - Text in this switch's field-argument specifies a sequence of characters\n * that separate an entry and its page number. The default is a tab with leader dots.\n */\n entryAndPageNumberSeparator?: string;\n\n /**\n * \\s option - For entries numbered with a SEQ field (§17.16.5.56), adds a prefix to the page number.\n * The prefix depends on the type of entry. text in this switch's field-argument shall match the\n * identifier in the SEQ field.\n */\n seqFieldIdentifierForPrefix?: string;\n\n /**\n * \\t field-argument Uses paragraphs formatted with styles other than the built-in heading styles.\n * Text in this switch's field-argument specifies those styles as a set of comma-separated doublets,\n * with each doublet being a comma-separated set of style name and table of content level.\n * \\t can be combined with \\o.\n */\n stylesWithLevels?: StyleLevel[];\n\n /**\n * \\u Uses the applied paragraph outline level.\n */\n useAppliedParagraphOutlineLevel?: boolean;\n\n /**\n * \\w Preserves tab entries within table entries.\n */\n preserveTabInEntries?: boolean;\n\n /**\n * \\x Preserves newline characters within table entries.\n */\n preserveNewLineInEntries?: boolean;\n\n /**\n * \\z Hides tab leader and page numbers in web page view (§17.18.102).\n */\n hideTabAndPageNumbersInWebView?: boolean;\n\n /**\n * Rendered TOC entries — the paragraph content between the field's `separate`\n * and `end` markers. Round-tripped structurally (each entry is a TOC-style\n * paragraph carrying a HYPERLINK field, tab leader, and PAGEREF page number)\n * so both MS Office and WPS display the existing TOC without regenerating.\n *\n * Omit on fresh generation — the field is then emitted `dirty` so the\n * consuming application builds the entries from headings on open.\n */\n entries?: SectionChild[];\n}\n","/**\n * Structured Document Tag Properties module.\n *\n * Represents CT_SdtPr — the properties of a structured document tag (content control).\n * Supports all SDT types defined in the OOXML specification: comboBox, dropDownList,\n * date, text, equation,richText, picture, citation, group, bibliography, docPartObj,\n * docPartList.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_SdtPr\n *\n * @module\n */\n\n// ─── Lock ───────────────────────────────────────────────────────────────────\n\n/**\n * SDT lock type (ST_Lock).\n */\nexport const SdtLock = {\n /** Lock the SDT itself (cannot delete the control) */\n SDT_LOCKED: \"sdtLocked\",\n /** Lock the content (cannot edit content within the control) */\n CONTENT_LOCKED: \"contentLocked\",\n /** No locking */\n UNLOCKED: \"unlocked\",\n /** Lock both SDT and content */\n SDT_CONTENT_LOCKED: \"sdtContentLocked\",\n} as const;\n\n// ─── Supporting Types ───────────────────────────────────────────────────────\n\n/**\n * A list item for comboBox or dropDownList SDTs (CT_SdtListItem).\n */\nexport interface SdtListItem {\n /** Display text shown in the UI */\n displayText?: string;\n /** Underlying value */\n value?: string;\n}\n\n/**\n * Options for comboBox SDT type (CT_SdtComboBox).\n */\nexport interface SdtComboBoxOptions {\n /** List items */\n items?: SdtListItem[];\n /** Last selected value */\n lastValue?: string;\n}\n\n/**\n * Options for dropDownList SDT type (CT_SdtDropDownList).\n */\nexport interface SdtDropDownListOptions {\n /** List items */\n items?: SdtListItem[];\n /** Last selected value */\n lastValue?: string;\n}\n\n/**\n * Date mapping type (ST_SdtDateMappingType).\n */\nexport const SdtDateMappingType = {\n TEXT: \"text\",\n DATE: \"date\",\n DATE_TIME: \"dateTime\",\n} as const;\n\n/**\n * Options for date SDT type (CT_SdtDate).\n */\nexport interface SdtDateOptions {\n /** Date format string (e.g., \"yyyy-MM-dd\") */\n dateFormat?: string;\n /** Language ID (e.g., \"en-US\") */\n languageId?: string;\n /** How the date value is stored */\n storeMappedDataAs?: (typeof SdtDateMappingType)[keyof typeof SdtDateMappingType];\n /** Calendar type */\n calendar?: string;\n /** Full date value (ISO 8601) */\n fullDate?: string;\n}\n\n/**\n * Options for plain text SDT type (CT_SdtText).\n */\nexport interface SdtTextOptions {\n /** Whether the text control supports multiple lines */\n multiLine?: boolean;\n}\n\n/**\n * Symbol for a checkbox content control state (CT_SdtCheckboxSymbol).\n *\n * `val` is a hex Unicode code point (e.g., \"2612\" for ☒); `font` defaults to\n * \"MS Gothic\" per the OOXML specification.\n */\nexport interface SdtCheckboxSymbol {\n /** Hex Unicode code point of the symbol (e.g., \"2612\") */\n val: string;\n /** Font face; defaults to \"MS Gothic\" */\n font?: string;\n}\n\n/**\n * Options for a checkbox content control (CT_SdtCheckbox, w14:checkbox).\n *\n * Word 2010+ content control checkbox. When present, the SDT renders the\n * current state symbol instead of its declared children.\n */\nexport interface SdtCheckboxOptions {\n /** Whether the checkbox is checked (default: false) */\n checked?: boolean;\n /** Symbol for the checked state (default: ☒ 0x2612, MS Gothic) */\n checkedState?: SdtCheckboxSymbol;\n /** Symbol for the unchecked state (default: ☐ 0x2610, MS Gothic) */\n uncheckedState?: SdtCheckboxSymbol;\n}\n\n/**\n * Data binding options (CT_DataBinding).\n */\nexport interface SdtDataBindingOptions {\n /** XML namespace prefix mappings */\n prefixMappings?: string;\n /** XPath expression (required) */\n xpath: string;\n /** Custom XML store item ID (required) */\n storeItemID: string;\n}\n\n/**\n * Options for CT_SdtPr — structured document tag properties.\n */\nexport interface SdtPropertiesOptions {\n /** Display name */\n alias?: string;\n /** Application-specific tag */\n tag?: string;\n /** Unique ID */\n id?: number;\n /** Lock behavior */\n lock?: (typeof SdtLock)[keyof typeof SdtLock];\n /** Whether the control is temporary */\n temporary?: boolean;\n /** Whether the placeholder text is currently shown */\n showingPlaceholder?: boolean;\n /** Data binding to custom XML */\n dataBinding?: SdtDataBindingOptions;\n /** Numeric label */\n label?: number;\n /** Tab order index */\n tabIndex?: number;\n\n // ─── Type discriminators (xsd:choice, at most one) ───\n\n /** Equation SDT */\n equation?: boolean;\n /** ComboBox SDT (allows free-text entry) */\n comboBox?: SdtComboBoxOptions;\n /** Date SDT */\n date?: SdtDateOptions;\n /** Document part object SDT */\n docPartObj?: {\n gallery?: string;\n category?: string;\n unique?: boolean;\n };\n /** Document part list SDT */\n docPartList?: {\n gallery?: string;\n category?: string;\n unique?: boolean;\n };\n /** DropDownList SDT (selection only) */\n dropDownList?: SdtDropDownListOptions;\n /** Picture SDT */\n picture?: boolean;\n /** Rich text SDT */\n richText?: boolean;\n /** Plain text SDT */\n text?: SdtTextOptions;\n /** Citation SDT */\n citation?: boolean;\n /** Group SDT */\n group?: boolean;\n /** Bibliography SDT */\n bibliography?: boolean;\n /** Checkbox content control SDT (Word 2010+, w14:checkbox) */\n checkbox?: SdtCheckboxOptions;\n}\n","/**\n * Table of Contents parser for DOCX documents.\n *\n * Parses TOC-type SDT elements into TOC options.\n *\n * @module\n */\nimport { attr, children, findChild, findFirst, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type {\n StyleLevel,\n TableOfContentsOptions,\n} from \"@parts/table-of-contents/table-of-contents-properties\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Try to parse a w:sdt element as a TOC.\n * Returns { alias, ...tocOptions } if it's a TOC, or undefined otherwise.\n *\n * Detects TOC in two ways:\n * 1. SDT with w:docPartObj > w:docPartGallery = \"Table of Contents\" (Word-generated)\n * 2. SDT whose content contains a TOC field instruction (library-generated)\n */\nexport function parseToc(\n el: Element,\n ctx: DocxReadContext,\n parseChildren?: (elements: Element[], ctx: DocxReadContext) => SectionChild[],\n):\n | ({\n alias?: string;\n } & TableOfContentsOptions)\n | undefined {\n const sdtPr = findChild(el, \"w:sdtPr\");\n if (!sdtPr) return undefined;\n\n // Detection method 1: docPartObj with gallery \"Table of Contents\"\n const docPartObj = findChild(sdtPr, \"w:docPartObj\");\n let isToc = false;\n\n if (docPartObj) {\n const gallery = findChild(docPartObj, \"w:docPartGallery\");\n if (gallery && textOf(gallery) === \"Table of Contents\") {\n isToc = true;\n }\n }\n\n // Detection method 2: scan content for TOC field instruction\n if (!isToc) {\n const sdtContent = findChild(el, \"w:sdtContent\");\n if (sdtContent) {\n isToc = hasTocFieldInstruction(sdtContent);\n }\n }\n\n if (!isToc) return undefined;\n\n // It's a TOC SDT\n const alias = (() => {\n const aliasEl = findChild(sdtPr, \"w:alias\");\n return aliasEl ? attr(aliasEl, \"w:val\") : undefined;\n })();\n\n // Parse field instruction from content to extract TOC options\n const tocOpts: Record<string, unknown> = {};\n const sdtContent = findChild(el, \"w:sdtContent\");\n\n if (sdtContent) {\n // Look for field instructions\n for (const p of children(sdtContent, \"w:p\")) {\n for (const r of children(p, \"w:r\")) {\n for (const instrText of children(r, \"w:instrText\")) {\n const instruction = textOf(instrText).trim();\n parseTocFieldInstruction(instruction, tocOpts);\n }\n }\n }\n // Rendered entries — the paragraphs between the field's separate and end\n // markers. Captured structurally so MS Office and WPS both display the\n // existing TOC instead of regenerating it from headings.\n if (parseChildren) {\n const entryEls = selectTocEntryElements(sdtContent.elements ?? []);\n if (entryEls.length > 0) {\n tocOpts.entries = parseChildren(entryEls, ctx);\n }\n }\n }\n\n return { alias, ...tocOpts } as { alias?: string } & TableOfContentsOptions;\n}\n\n/**\n * Check whether an element tree contains a TOC field instruction\n * (w:instrText with text starting with \"TOC\").\n */\nfunction hasTocFieldInstruction(el: Element): boolean {\n for (const p of children(el, \"w:p\")) {\n for (const r of children(p, \"w:r\")) {\n for (const instrText of children(r, \"w:instrText\")) {\n const instruction = textOf(instrText)?.trim();\n if (instruction?.startsWith(\"TOC\")) return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Parse a TOC field instruction string (e.g., ' TOC \\o \"1-3\" \\h \\z ')\n * into TableOfContentsOptions properties.\n */\nexport function parseTocFieldInstruction(instruction: string, opts: Record<string, unknown>): void {\n if (!instruction.startsWith(\"TOC\")) return;\n\n const rest = instruction.slice(3).trim();\n const switches = parseFieldSwitches(rest);\n\n if (switches[\"a\"]) opts.captionLabel = switches[\"a\"];\n if (switches[\"b\"]) opts.entriesFromBookmark = switches[\"b\"];\n if (switches[\"c\"]) opts.captionLabelIncludingNumbers = switches[\"c\"];\n if (switches[\"d\"]) opts.sequenceAndPageNumbersSeparator = switches[\"d\"];\n if (switches[\"f\"]) opts.tcFieldIdentifier = switches[\"f\"];\n if (\"h\" in switches) opts.hyperlink = true;\n if (switches[\"l\"]) opts.tcFieldLevelRange = switches[\"l\"];\n if (switches[\"n\"]) opts.pageNumbersEntryLevelsRange = switches[\"n\"];\n if (switches[\"o\"]) opts.headingStyleRange = switches[\"o\"];\n if (switches[\"p\"]) opts.entryAndPageNumberSeparator = switches[\"p\"];\n if (switches[\"s\"]) opts.seqFieldIdentifierForPrefix = switches[\"s\"];\n if (switches[\"t\"]) {\n // \\t \"Style1,1,Style2,2\" -> stylesWithLevels pairs\n const parts = switches[\"t\"]!.split(\",\");\n const stylesWithLevels: StyleLevel[] = [];\n for (let i = 0; i + 1 < parts.length; i += 2) {\n const styleName = parts[i];\n const level = parseInt(parts[i + 1] ?? \"\", 10);\n if (styleName && !Number.isNaN(level)) stylesWithLevels.push({ styleName, level });\n }\n if (stylesWithLevels.length > 0) opts.stylesWithLevels = stylesWithLevels;\n }\n if (\"u\" in switches) opts.useAppliedParagraphOutlineLevel = true;\n if (\"w\" in switches) opts.preserveTabInEntries = true;\n if (\"x\" in switches) opts.preserveNewLineInEntries = true;\n if (\"z\" in switches) opts.hideTabAndPageNumbersInWebView = true;\n}\n\n/**\n * Extract TOC options from the elements of a captured TOC field (SDT content or\n * a bare cross-paragraph field). Feeds every w:instrText to the instruction\n * parser; non-TOC fields (HYPERLINK/PAGEREF inside the rendered entries) are\n * ignored — parseTocFieldInstruction only acts on instructions starting \"TOC\".\n */\nexport function parseTocFieldFromElements(els: Element[]): TableOfContentsOptions {\n const opts: Record<string, unknown> = {};\n for (const el of els) collectTocInstructions(el, opts);\n return opts as TableOfContentsOptions;\n}\n\n/**\n * Select the rendered-entry paragraphs of a captured TOC field. Tracks field\n * depth so a nested HYPERLINK/PAGEREF field inside an entry doesn't fool the\n * boundary detection.\n *\n * A paragraph is an entry when, after walking it, the field is past `separate`\n * and not past `end` (depth ≥ 1) and the paragraph carries rendered text (`w:t`).\n * This captures an entry whose paragraph also opens the field (`begin`) or holds\n * the `separate` marker — common when Word emits begin + separate + first entry\n * in one paragraph — while the `w:t` requirement excludes a pure control\n * paragraph (field head / separate-only / end).\n */\nexport function selectTocEntryElements(els: Element[]): Element[] {\n const entries: Element[] = [];\n let depth = 0;\n let afterSeparate = false;\n for (const el of els) {\n const walk = (node: Element): void => {\n if (node.name === \"w:fldChar\") {\n const type = attr(node, \"w:fldCharType\");\n if (type === \"begin\") depth++;\n else if (type === \"separate\" && depth === 1) afterSeparate = true;\n else if (type === \"end\") depth--;\n }\n for (const c of node.elements ?? []) {\n if (c.type === \"element\") walk(c);\n }\n };\n walk(el);\n if (afterSeparate && depth >= 1 && findFirst(el, \"w:t\") !== undefined) {\n entries.push(el);\n }\n }\n return entries;\n}\n\n/** Recursively feed every w:instrText to the TOC instruction parser. */\nfunction collectTocInstructions(el: Element, opts: Record<string, unknown>): void {\n if (el.name === \"w:instrText\") {\n const instruction = textOf(el)?.trim();\n if (instruction) parseTocFieldInstruction(instruction, opts);\n }\n for (const c of el.elements ?? []) {\n if (c.type === \"element\") collectTocInstructions(c, opts);\n }\n}\n\n/**\n * Parse field switches like \\o \"1-3\" \\h \\z into a map.\n */\nfunction parseFieldSwitches(text: string): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = {};\n let i = 0;\n\n while (i < text.length) {\n // Skip whitespace\n while (i < text.length && text[i] === \" \") i++;\n if (i >= text.length) break;\n\n // Expect backslash\n if (text[i] !== \"\\\\\") {\n i++;\n continue;\n }\n i++;\n\n // Read switch name\n const nameStart = i;\n while (i < text.length && /[a-zA-Z]/.test(text[i] ?? \"\")) i++;\n const name = text.slice(nameStart, i);\n if (!name) continue;\n\n // Skip whitespace\n while (i < text.length && text[i] === \" \") i++;\n\n // Read argument (quoted or unquoted)\n if (i < text.length && text[i] === '\"') {\n i++;\n const argStart = i;\n while (i < text.length && text[i] !== '\"') i++;\n result[name] = text.slice(argStart, i);\n if (i < text.length) i++; // skip closing quote\n } else if (i < text.length && text[i] !== \"\\\\\") {\n const argStart = i;\n while (i < text.length && text[i] !== \" \" && text[i] !== \"\\\\\") i++;\n const arg = text.slice(argStart, i).trim();\n if (arg) result[name] = arg;\n else result[name] = undefined;\n } else {\n result[name] = undefined;\n }\n }\n\n return result;\n}\n","/**\n * Footnotes descriptor — produces word/footnotes.xml.\n *\n * Generates the complete `<w:footnotes>` element including:\n * - Separator footnote (id round-tripped from source; default -1)\n * - Continuation separator footnote (id round-tripped from source; default 0)\n * - User footnotes with auto-injected footnoteRef in first paragraph\n *\n * Reference: http://officeopenxml.com/WPfootnotes.php, CT_Footnotes / CT_FtnEdn\n *\n * @module\n */\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrNum } from \"@office-open/xml\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport { stringifyParagraphInline } from \"@parts/inline\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\n\nimport { parseParagraph } from \"../../body\";\nimport type { BodyContext, DocxReadContext } from \"../../context\";\n\n// ── Input ──\n\n/** System footnote (separator / continuationSeparator). Round-tripped verbatim. */\nexport interface FootnoteSeparator {\n id: number;\n paragraphs: (ParagraphOptions | string)[];\n}\n\nexport interface FootnotesData {\n notes: Map<number, (ParagraphOptions | string)[]>;\n /**\n * Separator footnote — id + content round-tripped from the source so it stays\n * consistent with settings.footnotePr, which references this id.\n */\n separator?: FootnoteSeparator;\n /** Continuation separator footnote — id + content round-tripped from the source. */\n continuationSeparator?: FootnoteSeparator;\n}\n\n// ── Constants ──\n\nconst NS = documentNamespaceAttributes([\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n]);\n\n/** XML for the footnoteRef run — auto-injected at start of first paragraph. */\nconst FOOTNOTE_REF_RUN =\n '<w:r><w:rPr><w:rStyle w:val=\"FootnoteReference\"/></w:rPr><w:footnoteRef/></w:r>';\n\n/** Default separator footnote (id=-1) for freshly generated documents. */\nconst SEPARATOR_FOOTNOTE =\n '<w:footnote w:type=\"separator\" w:id=\"-1\">' +\n '<w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>' +\n \"<w:r><w:separator/></w:r>\" +\n \"</w:p>\" +\n \"</w:footnote>\";\n\n/** Default continuation separator footnote (id=0) for freshly generated documents. */\nconst CONTINUATION_SEPARATOR_FOOTNOTE =\n '<w:footnote w:type=\"continuationSeparator\" w:id=\"0\">' +\n '<w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>' +\n \"<w:r><w:continuationSeparator/></w:r>\" +\n \"</w:p>\" +\n \"</w:footnote>\";\n\n// ── Descriptor ──\n\n/** Render a system footnote from round-tripped id + content, or the spec default. */\nfunction footnoteSystemNote(\n type: \"separator\" | \"continuationSeparator\",\n sep: FootnoteSeparator | undefined,\n fallback: string,\n ctx: BodyContext,\n): string {\n if (!sep) return fallback;\n const inner = sep.paragraphs.map((p) => stringifyParagraphInline(p, ctx)).join(\"\");\n return `<w:footnote w:type=\"${type}\" w:id=\"${sep.id}\">${inner}</w:footnote>`;\n}\n\nexport const footnotesDesc: CustomDescriptor<FootnotesData, BodyContext> = {\n kind: \"custom\",\n\n stringify(data, ctx) {\n const parts: string[] = [`<w:footnotes ${NS} mc:Ignorable=\"w14 w15 wp14\">`];\n\n // Separator / continuation separator: round-trip id + content verbatim so they\n // stay consistent with settings.footnotePr (which references these ids). Fall\n // back to spec defaults only for freshly generated documents.\n parts.push(footnoteSystemNote(\"separator\", data.separator, SEPARATOR_FOOTNOTE, ctx));\n parts.push(\n footnoteSystemNote(\n \"continuationSeparator\",\n data.continuationSeparator,\n CONTINUATION_SEPARATOR_FOOTNOTE,\n ctx,\n ),\n );\n\n for (const [id, paragraphs] of data.notes) {\n parts.push(`<w:footnote w:id=\"${id}\">`);\n for (const [i, para] of paragraphs.entries()) {\n const pXml = stringifyParagraphInline(para, ctx);\n if (i === 0) {\n // footnoteRef goes after the paragraph open tag, but after <w:pPr>\n // when present — CT_P requires pPr to be the first child.\n const pPrEnd = pXml.indexOf(\"</w:pPr>\");\n if (pPrEnd !== -1) {\n const at = pPrEnd + \"</w:pPr>\".length;\n parts.push(pXml.slice(0, at) + FOOTNOTE_REF_RUN + pXml.slice(at));\n } else {\n const openIdx = pXml.indexOf(\">\");\n if (openIdx !== -1) {\n parts.push(pXml.slice(0, openIdx + 1) + FOOTNOTE_REF_RUN + pXml.slice(openIdx + 1));\n } else {\n parts.push(pXml);\n }\n }\n } else {\n parts.push(pXml);\n }\n }\n parts.push(\"</w:footnote>\");\n }\n\n parts.push(\"</w:footnotes>\");\n return parts.join(\"\");\n },\n\n parse(el, ctx) {\n const notes = new Map<number, (ParagraphOptions | string)[]>();\n let separator: FootnoteSeparator | undefined;\n let continuationSeparator: FootnoteSeparator | undefined;\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:footnote\") continue;\n const id = attrNum(child, \"w:id\");\n if (id === undefined) continue;\n const type = attr(child, \"w:type\");\n\n const paragraphs: (ParagraphOptions | string)[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:p\") {\n paragraphs.push(parseParagraph(sub, ctx as DocxReadContext));\n }\n }\n\n // System footnotes carry type=\"separator\"/\"continuationSeparator\" — capture\n // their id + content so stringify round-trips them verbatim (settings\n // references these ids). Normal footnotes (type absent/\"normal\") go to notes.\n if (type === \"separator\") {\n separator = { id, paragraphs };\n } else if (type === \"continuationSeparator\") {\n continuationSeparator = { id, paragraphs };\n } else {\n notes.set(id, paragraphs);\n }\n }\n return { notes, separator, continuationSeparator } as FootnotesData;\n },\n};\n","/**\n * Endnotes descriptor — produces word/endnotes.xml.\n *\n * Generates the complete `<w:endnotes>` element including:\n * - Separator endnote (id round-tripped from source; default -1)\n * - Continuation separator endnote (id round-tripped from source; default 0)\n * - User endnotes with auto-injected endnoteRef in first paragraph\n *\n * Reference: http://officeopenxml.com/WPfootnotes.php, CT_Endnotes / CT_FtnEdn\n *\n * @module\n */\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrNum } from \"@office-open/xml\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport { stringifyParagraphInline } from \"@parts/inline\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\n\nimport { parseParagraph } from \"../../body\";\nimport type { BodyContext, DocxReadContext } from \"../../context\";\n\n// ── Input ──\n\n/** System endnote (separator / continuationSeparator). Round-tripped verbatim. */\nexport interface EndnoteSeparator {\n id: number;\n paragraphs: (ParagraphOptions | string)[];\n}\n\nexport interface EndnotesData {\n notes: Map<number, (ParagraphOptions | string)[]>;\n /**\n * Separator endnote — id + content round-tripped from the source so it stays\n * consistent with settings.endnotePr, which references this id.\n */\n separator?: EndnoteSeparator;\n /** Continuation separator endnote — id + content round-tripped from the source. */\n continuationSeparator?: EndnoteSeparator;\n}\n\n// ── Constants ──\n\nconst NS = documentNamespaceAttributes([\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n]);\n\n/** XML for the endnoteRef run — auto-injected at start of first paragraph. */\nconst ENDNOTE_REF_RUN =\n '<w:r><w:rPr><w:rStyle w:val=\"EndnoteReference\"/></w:rPr><w:endnoteRef/></w:r>';\n\n/** Default separator endnote (id=-1) for freshly generated documents. */\nconst SEPARATOR_ENDNOTE =\n '<w:endnote w:type=\"separator\" w:id=\"-1\">' +\n '<w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>' +\n \"<w:r><w:separator/></w:r>\" +\n \"</w:p>\" +\n \"</w:endnote>\";\n\n/** Default continuation separator endnote (id=0) for freshly generated documents. */\nconst CONTINUATION_SEPARATOR_ENDNOTE =\n '<w:endnote w:type=\"continuationSeparator\" w:id=\"0\">' +\n '<w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr>' +\n \"<w:r><w:continuationSeparator/></w:r>\" +\n \"</w:p>\" +\n \"</w:endnote>\";\n\n// ── Descriptor ──\n\n/** Render a system endnote from round-tripped id + content, or the spec default. */\nfunction endnoteSystemNote(\n type: \"separator\" | \"continuationSeparator\",\n sep: EndnoteSeparator | undefined,\n fallback: string,\n ctx: BodyContext,\n): string {\n if (!sep) return fallback;\n const inner = sep.paragraphs.map((p) => stringifyParagraphInline(p, ctx)).join(\"\");\n return `<w:endnote w:type=\"${type}\" w:id=\"${sep.id}\">${inner}</w:endnote>`;\n}\n\nexport const endnotesDesc: CustomDescriptor<EndnotesData, BodyContext> = {\n kind: \"custom\",\n\n stringify(data, ctx) {\n const parts: string[] = [`<w:endnotes ${NS} mc:Ignorable=\"w14 w15 wp14\">`];\n\n // Separator / continuation separator: round-trip id + content verbatim so they\n // stay consistent with settings.endnotePr (which references these ids). Fall\n // back to spec defaults only for freshly generated documents.\n parts.push(endnoteSystemNote(\"separator\", data.separator, SEPARATOR_ENDNOTE, ctx));\n parts.push(\n endnoteSystemNote(\n \"continuationSeparator\",\n data.continuationSeparator,\n CONTINUATION_SEPARATOR_ENDNOTE,\n ctx,\n ),\n );\n\n for (const [id, paragraphs] of data.notes) {\n parts.push(`<w:endnote w:id=\"${id}\">`);\n for (const [i, para] of paragraphs.entries()) {\n const pXml = stringifyParagraphInline(para, ctx);\n if (i === 0) {\n // Insert endnoteRef after <w:p> or <w:p ...>\n const openIdx = pXml.indexOf(\">\");\n if (openIdx !== -1) {\n parts.push(pXml.slice(0, openIdx + 1) + ENDNOTE_REF_RUN + pXml.slice(openIdx + 1));\n } else {\n parts.push(pXml);\n }\n } else {\n parts.push(pXml);\n }\n }\n parts.push(\"</w:endnote>\");\n }\n\n parts.push(\"</w:endnotes>\");\n return parts.join(\"\");\n },\n\n parse(el, ctx) {\n const notes = new Map<number, (ParagraphOptions | string)[]>();\n let separator: EndnoteSeparator | undefined;\n let continuationSeparator: EndnoteSeparator | undefined;\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:endnote\") continue;\n const id = attrNum(child, \"w:id\");\n if (id === undefined) continue;\n const type = attr(child, \"w:type\");\n\n const paragraphs: (ParagraphOptions | string)[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:p\") {\n paragraphs.push(parseParagraph(sub, ctx as DocxReadContext));\n }\n }\n\n // System endnotes carry type=\"separator\"/\"continuationSeparator\" — capture\n // their id + content so stringify round-trips them verbatim (settings\n // references these ids). Normal endnotes (type absent/\"normal\") go to notes.\n if (type === \"separator\") {\n separator = { id, paragraphs };\n } else if (type === \"continuationSeparator\") {\n continuationSeparator = { id, paragraphs };\n } else {\n notes.set(id, paragraphs);\n }\n }\n return { notes, separator, continuationSeparator } as EndnotesData;\n },\n};\n","/**\n * Permission range markers for WordprocessingML document protection.\n *\n * These elements mark editable ranges within a protected document.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_PermStart, CT_PermEnd\n *\n * @module\n */\n\n/**\n * Editing group values for permission ranges.\n *\n * Defines who can edit within a permission range.\n *\n * Reference: ISO/IEC 29500-4, ST_EdGrp\n */\nexport const EditGroupType = {\n NONE: \"none\",\n EVERYONE: \"everyone\",\n ADMINISTRATORS: \"administrators\",\n CONTRIBUTORS: \"contributors\",\n EDITORS: \"editors\",\n OWNERS: \"owners\",\n CURRENT: \"current\",\n} as const;\n\nexport type EditGroup = (typeof EditGroupType)[keyof typeof EditGroupType];\n\n/**\n * Options for creating a permission start marker.\n */\nexport interface PermStartOptions {\n /** Unique identifier for this permission range (typically a number) */\n id: string | number;\n /** Editing group that can edit this range */\n editGroup?: EditGroup;\n /** Individual user who can edit this range (CT_PermStart @ed) */\n editor?: string;\n /** First column this range covers (for table cells) */\n colFirst?: number;\n /** Last column this range covers (for table cells) */\n colLast?: number;\n}\n","/**\n * AltChunk collection module for managing alternative format content parts.\n *\n * @module\n */\n\n/**\n * Stores alternative format chunk data for later serialization by the compiler.\n */\nexport interface AltChunkData {\n /** Unique key for this alt chunk (e.g., relId) */\n key: string;\n /** Raw content data */\n data: Uint8Array;\n /** Part sub-path within word/ (e.g., \"afchunks/afchunk1.html\") */\n path: string;\n /** File extension (e.g., \"html\", \"rtf\", \"txt\") */\n extension: string;\n /** MIME content type (e.g., \"text/html\", \"application/rtf\") */\n contentType: string;\n}\n\n/**\n * Manages alternative format chunk parts in a document.\n *\n * Stores external content (HTML, RTF, plain text) that will be\n * serialized into separate parts in the DOCX package.\n */\nexport class AltChunkCollection {\n private map: Map<string, AltChunkData>;\n\n public constructor() {\n this.map = new Map<string, AltChunkData>();\n }\n\n public addAltChunk(key: string, data: AltChunkData): void {\n this.map.set(key, data);\n }\n\n public get array(): AltChunkData[] {\n return [...this.map.values()];\n }\n}\n","/**\n * Sub-document collection module for managing sub-document parts.\n *\n * @module\n */\n\n/**\n * Stores sub-document data for later serialization by the compiler.\n */\nexport interface SubDocData {\n /** Raw document data (.docx bytes) */\n data: Uint8Array;\n /** Part sub-path within word/ (e.g., \"subdocs/subdoc1.docx\") */\n path: string;\n}\n\n/**\n * Manages sub-document parts in a document.\n */\nexport class SubDocCollection {\n private map: Map<string, SubDocData>;\n\n public constructor() {\n this.map = new Map<string, SubDocData>();\n }\n\n public addSubDoc(key: string, data: SubDocData): void {\n this.map.set(key, data);\n }\n\n public get array(): SubDocData[] {\n return [...this.map.values()];\n }\n}\n","/**\n * Font module for WordprocessingML documents.\n *\n * Provides support for font definitions and embedded fonts.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * @module\n */\nimport { element } from \"@office-open/xml\";\n\nconst createStringElement = (name: string, value: string): string =>\n element(name, { \"w:val\": value });\n\n/**\n * Options for a font relationship (embedded font).\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html\n *\n * @property id - Relationship to Part\n * @property fontKey - Embedded Font Obfuscation Key (GUID)\n * @property subsetted - Whether the embedded font is subsetted\n */\nexport interface FontRelationshipOptions {\n /** Relationship to Part */\n id: string;\n /** Embedded Font Obfuscation Key (GUID) */\n fontKey?: string;\n /** Whether the embedded font is subsetted */\n subsetted?: boolean;\n}\n\n/**\n * Character set constants for font definitions.\n * Maps character set names to their hexadecimal identifiers.\n *\n * @publicApi\n */\nexport const CharacterSet = {\n ANSI: \"00\",\n ARABIC: \"B2\",\n BALTIC: \"BA\",\n CHINESEBIG5: \"88\",\n DEFAULT: \"01\",\n EASTEUROPE: \"EE\",\n GB_2312: \"86\",\n GREEK: \"A1\",\n HANGUL: \"81\",\n HEBREW: \"B1\",\n JIS: \"80\",\n JOHAB: \"82\",\n MAC: \"4D\",\n OEM: \"FF\",\n RUSSIAN: \"CC\",\n SYMBOL: \"02\",\n THAI: \"DE\",\n TURKISH: \"A2\",\n VIETNAMESE: \"A3\",\n} as const;\n\n/**\n * Options for defining a font in the document.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * @property name - Font name (required)\n * @property altName - Alternative font name\n * @property panose1 - PANOSE-1 classification\n * @property charset - Character set identifier\n * @property family - Font family\n * @property notTrueType - Whether this is not a TrueType font\n * @property pitch - Font pitch\n * @property sig - Font signature (Unicode and code page ranges)\n * @property embedRegular - Embedded regular font relationship\n * @property embedBold - Embedded bold font relationship\n * @property embedItalic - Embedded italic font relationship\n * @property embedBoldItalic - Embedded bold-italic font relationship\n */\nexport interface FontEntry {\n /** Font name (required) */\n name: string;\n /** Alternative font name */\n altName?: string;\n /** PANOSE-1 classification */\n panose1?: string;\n /** Character set identifier */\n charset?: (typeof CharacterSet)[keyof typeof CharacterSet];\n /** Font family */\n family?: string;\n /** Whether this is not a TrueType font */\n notTrueType?: boolean;\n /** Font pitch */\n pitch?: string;\n /** Font signature (Unicode and code page ranges) */\n sig?: {\n /** Unicode Subset Bitfield 0 */\n usb0: string;\n /** Unicode Subset Bitfield 1 */\n usb1: string;\n /** Unicode Subset Bitfield 2 */\n usb2: string;\n /** Unicode Subset Bitfield 3 */\n usb3: string;\n /** Code Page Bitfield 0 */\n csb0: string;\n /** Code Page Bitfield 1 */\n csb1: string;\n };\n /** Embedded regular font relationship */\n embedRegular?: FontRelationshipOptions;\n /** Embedded bold font relationship */\n embedBold?: FontRelationshipOptions;\n /** Embedded italic font relationship */\n embedItalic?: FontRelationshipOptions;\n /** Embedded bold-italic font relationship */\n embedBoldItalic?: FontRelationshipOptions;\n}\n\n/**\n * Creates a font relationship element for embedding fonts.\n */\nconst createFontRelationship = (\n { id, fontKey, subsetted }: FontRelationshipOptions,\n name: string,\n): string => {\n const attrs: Record<string, string | undefined> = { \"r:id\": id };\n if (fontKey) {\n attrs[\"w:fontKey\"] = `{${fontKey}}`;\n }\n const children = subsetted ? [`<w:subsetted/>`] : undefined;\n return element(name, attrs, children);\n};\n\n/**\n * Creates a font element with the specified options.\n *\n * This function builds a complete font definition including optional embedded font files,\n * font signature, character set, and other font properties.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_font-1.html\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_Font\">\n * <xsd:sequence>\n * <xsd:element name=\"altName\" type=\"CT_String\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"panose1\" type=\"CT_Panose\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"charset\" type=\"CT_Charset\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"family\" type=\"CT_FontFamily\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"notTrueType\" type=\"CT_OnOff\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"pitch\" type=\"CT_Pitch\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"sig\" type=\"CT_FontSig\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedRegular\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedBold\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedItalic\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * <xsd:element name=\"embedBoldItalic\" type=\"CT_FontRel\" minOccurs=\"0\" maxOccurs=\"1\"/>\n * </xsd:sequence>\n * <xsd:attribute name=\"name\" type=\"s:ST_String\" use=\"required\"/>\n * </xsd:complexType>\n * ```\n *\n * @example\n * ```typescript\n * const font = createFont({\n * name: \"Arial\",\n * family: \"swiss\",\n * pitch: \"variable\",\n * charset: CharacterSet.ANSI\n * });\n * ```\n */\nexport const createFont = ({\n name,\n altName,\n panose1,\n charset,\n family,\n notTrueType,\n pitch,\n sig,\n embedRegular,\n embedBold,\n embedItalic,\n embedBoldItalic,\n}: FontEntry): string => {\n const children: string[] = [];\n\n // http://www.datypic.com/sc/ooxml/e-w_altName-1.html\n if (altName) children.push(createStringElement(\"w:altName\", altName));\n // http://www.datypic.com/sc/ooxml/e-w_panose1-1.html\n if (panose1) children.push(createStringElement(\"w:panose1\", panose1));\n // http://www.datypic.com/sc/ooxml/e-w_charset-1.html\n if (charset) children.push(createStringElement(\"w:charset\", charset));\n // http://www.datypic.com/sc/ooxml/e-w_family-1.html\n if (family) children.push(createStringElement(\"w:family\", family));\n // http://www.datypic.com/sc/ooxml/e-w_notTrueType-1.html\n if (notTrueType) children.push(`<w:notTrueType/>`);\n if (pitch) children.push(createStringElement(\"w:pitch\", pitch));\n // http://www.datypic.com/sc/ooxml/e-w_sig-1.html\n if (sig) {\n children.push(\n `<w:sig w:csb0=\"${sig.csb0}\" w:csb1=\"${sig.csb1}\" w:usb0=\"${sig.usb0}\" w:usb1=\"${sig.usb1}\" w:usb2=\"${sig.usb2}\" w:usb3=\"${sig.usb3}\"/>`,\n );\n }\n // http://www.datypic.com/sc/ooxml/e-w_embedRegular-1.html\n if (embedRegular) children.push(createFontRelationship(embedRegular, \"w:embedRegular\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedBold-1.html\n if (embedBold) children.push(createFontRelationship(embedBold, \"w:embedBold\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedItalic-1.html\n if (embedItalic) children.push(createFontRelationship(embedItalic, \"w:embedItalic\"));\n // http://www.datypic.com/sc/ooxml/e-w_embedBoldItalic-1.html\n if (embedBoldItalic) children.push(createFontRelationship(embedBoldItalic, \"w:embedBoldItalic\"));\n\n return element(\"w:font\", { \"w:name\": name }, children);\n};\n","/**\n * Font table descriptor — produces word/fontTable.xml.\n *\n * Reference: http://www.datypic.com/sc/ooxml/e-w_fonts.html, CT_FontsList\n *\n * @module\n */\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrBool, escapeXml, findChild } from \"@office-open/xml\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport type { FontSignature } from \"@parts/fonts/font-table\";\nimport type { EmbeddedFontOptionsWithKey } from \"@parts/fonts/font-wrapper\";\n\n// ── Input ──\n\nexport interface FontTableInput {\n fonts: EmbeddedFontOptionsWithKey[];\n}\n\n// ── XML helpers ──\n\nconst NS = documentNamespaceAttributes([\n \"mc\",\n \"r\",\n \"w\",\n \"w14\",\n \"w15\",\n \"w16\",\n \"w16cex\",\n \"w16cid\",\n \"w16sdtdh\",\n \"w16se\",\n]);\n\n/** Default font signature for regular embedded fonts. */\nconst DEFAULT_SIG: FontSignature = {\n usb0: \"E0002AFF\",\n usb1: \"C000247B\",\n usb2: \"00000009\",\n usb3: \"00000000\",\n csb0: \"000001FF\",\n csb1: \"00000000\",\n};\n\nfunction fontXml(font: EmbeddedFontOptionsWithKey): string {\n const parts: string[] = [`<w:font w:name=\"${escapeXml(font.name)}\">`];\n\n // CT_Font child order (wml.xsd): altName, panose1, charset, family,\n // notTrueType, pitch, sig, embed*. Embedded fonts (carrying data) fall back\n // to defaults when the parsed value is absent; metadata-only fonts emit only\n // what was parsed.\n if (font.altName) parts.push(`<w:altName w:val=\"${escapeXml(font.altName)}\"/>`);\n if (font.panose1) parts.push(`<w:panose1 w:val=\"${escapeXml(font.panose1)}\"/>`);\n if (font.characterSet || font.characterSetName) {\n const valAttr = font.characterSet ? ` w:val=\"${escapeXml(font.characterSet)}\"` : \"\";\n const csAttr = font.characterSetName\n ? ` w:characterSet=\"${escapeXml(font.characterSetName)}\"`\n : \"\";\n parts.push(`<w:charset${valAttr}${csAttr}/>`);\n }\n const family = font.family ?? (font.embedRid ? \"auto\" : undefined);\n if (family) parts.push(`<w:family w:val=\"${escapeXml(family)}\"/>`);\n const pitch = font.pitch ?? (font.embedRid ? \"variable\" : undefined);\n if (pitch) parts.push(`<w:pitch w:val=\"${escapeXml(pitch)}\"/>`);\n const sig = font.sig ?? (font.embedRid ? DEFAULT_SIG : undefined);\n if (sig) {\n parts.push(\n `<w:sig w:usb0=\"${sig.usb0}\" w:usb1=\"${sig.usb1}\" w:usb2=\"${sig.usb2}\" ` +\n `w:usb3=\"${sig.usb3}\" w:csb0=\"${sig.csb0}\" w:csb1=\"${sig.csb1}\"/>`,\n );\n }\n if (font.embedRid) {\n const embedAttrs = [`r:id=\"${font.embedRid}\"`, `w:fontKey=\"{${font.fontKey}}\"`];\n if (font.subsetted !== undefined) embedAttrs.push(`w:subsetted=\"${font.subsetted ? 1 : 0}\"`);\n parts.push(`<w:embedRegular ${embedAttrs.join(\" \")}/>`);\n }\n\n parts.push(\"</w:font>\");\n return parts.join(\"\");\n}\n\n// ── Descriptor ──\n\nexport const fontTableDesc: CustomDescriptor<FontTableInput> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n const parts: string[] = [\n `<w:fonts ${NS} mc:Ignorable=\"w14 w15 w16se w16cid w16 w16cex w16sdtdh\">`,\n ];\n for (const font of opts.fonts) {\n parts.push(fontXml(font));\n }\n parts.push(\"</w:fonts>\");\n return parts.join(\"\");\n },\n\n parse(el, _ctx) {\n const fonts: EmbeddedFontOptionsWithKey[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:font\") continue;\n const font: Partial<EmbeddedFontOptionsWithKey> = { fontKey: \"\" };\n const name = child.attributes?.[\"w:name\"];\n if (name) font.name = String(name);\n\n const altNameEl = findChild(child, \"w:altName\");\n if (altNameEl) {\n const val = attr(altNameEl, \"w:val\");\n if (val) font.altName = val;\n }\n\n const panose1El = findChild(child, \"w:panose1\");\n if (panose1El) {\n const val = attr(panose1El, \"w:val\");\n if (val) font.panose1 = val;\n }\n\n const charsetEl = findChild(child, \"w:charset\");\n if (charsetEl) {\n const val = attr(charsetEl, \"w:val\");\n if (val) font.characterSet = val as EmbeddedFontOptionsWithKey[\"characterSet\"];\n const csName = attr(charsetEl, \"w:characterSet\");\n if (csName) font.characterSetName = csName;\n }\n\n const familyEl = findChild(child, \"w:family\");\n if (familyEl) {\n const val = attr(familyEl, \"w:val\");\n if (val) font.family = val;\n }\n\n const pitchEl = findChild(child, \"w:pitch\");\n if (pitchEl) {\n const val = attr(pitchEl, \"w:val\");\n if (val) font.pitch = val;\n }\n\n const sigEl = findChild(child, \"w:sig\");\n if (sigEl) {\n const sig: FontSignature = {\n usb0: \"\",\n usb1: \"\",\n usb2: \"\",\n usb3: \"\",\n csb0: \"\",\n csb1: \"\",\n };\n for (const key of [\"usb0\", \"usb1\", \"usb2\", \"usb3\", \"csb0\", \"csb1\"] as const) {\n const val = attr(sigEl, `w:${key}`);\n if (val) sig[key] = val;\n }\n if (Object.values(sig).some(Boolean)) font.sig = sig;\n }\n\n // Obfuscation key + relationship id from embedRegular (the .odttf bytes\n // are resolved separately by parse.ts via fontTable.xml.rels).\n const embedEl = findChild(child, \"w:embedRegular\");\n if (embedEl) {\n const rawKey = attr(embedEl, \"w:fontKey\");\n if (rawKey) {\n font.fontKey = rawKey.replace(/^\\{\\{|\\}\\}$/g, \"\").replace(/^\\{|\\}$/g, \"\");\n }\n const rid = attr(embedEl, \"r:id\");\n if (rid) font.embedRid = rid;\n const subsetted = attrBool(embedEl, \"w:subsetted\");\n if (subsetted !== undefined) font.subsetted = subsetted;\n }\n\n fonts.push(font as EmbeddedFontOptionsWithKey);\n }\n return { fonts };\n },\n};\n","/**\n * Bibliography module for WordprocessingML documents.\n *\n * Provides types for bibliography sources.\n * XML generation is handled by the descriptor pipeline (bibliographyDesc).\n *\n * Reference: ISO/IEC 29500-4, shared-bibliography.xsd, CT_Sources, CT_SourceType\n *\n * @module\n */\n\n/**\n * Options for a single bibliography source entry.\n *\n * Maps to CT_SourceType in the bibliography XSD schema.\n * All fields are optional — include only the relevant ones for each source type.\n *\n * @property type - Source type (Book, JournalArticle, ConferenceProceedings, etc.)\n * @property title - Title of the work\n * @property author - Author names (plain text, semicolon-separated)\n * @property year - Publication year\n * @property month - Publication month\n * @property day - Publication day\n * @property bookTitle - Title of the book (for book sections, articles in collections)\n * @property journal - Journal name (JournalName in XSD)\n * @property volume - Volume number\n * @property issue - Issue number\n * @property pages - Page range\n * @property publisher - Publisher name\n * @property city - City of publication\n * @property url - URL for internet sources\n * @property edition - Edition number or description\n * @property institution - Institution (for theses, reports)\n */\nexport interface SourceTypeOptions {\n type?: string;\n title?: string;\n author?: string;\n year?: string;\n month?: string;\n day?: string;\n bookTitle?: string;\n journal?: string;\n volume?: string;\n issue?: string;\n pages?: string;\n publisher?: string;\n city?: string;\n url?: string;\n edition?: string;\n institution?: string;\n}\n\n/**\n * Options for creating a bibliography container.\n *\n * @property sources - Array of bibliography source entries\n * @property styleName - Bibliography style name (e.g., \"APA\", \"Chicago\", \"IEEE\")\n */\nexport interface BibliographyOptions {\n sources: SourceTypeOptions[];\n styleName?: string;\n}\n\n// ── Descriptor ──\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { escapeXml, findChild, textOf } from \"@office-open/xml\";\n\nconst SOURCE_FIELDS: readonly (readonly [string, keyof SourceTypeOptions])[] = [\n [\"SourceType\", \"type\"],\n [\"Title\", \"title\"],\n [\"Author\", \"author\"],\n [\"Year\", \"year\"],\n [\"Month\", \"month\"],\n [\"Day\", \"day\"],\n [\"BookTitle\", \"bookTitle\"],\n [\"JournalName\", \"journal\"],\n [\"Volume\", \"volume\"],\n [\"Issue\", \"issue\"],\n [\"Pages\", \"pages\"],\n [\"Publisher\", \"publisher\"],\n [\"City\", \"city\"],\n [\"URL\", \"url\"],\n [\"Edition\", \"edition\"],\n [\"Institution\", \"institution\"],\n] as const;\n\nexport const bibliographyDesc: CustomDescriptor<BibliographyOptions> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n const attrParts: string[] = [\n 'xmlns:b=\"http://schemas.openxmlformats.org/officeDocument/2006/bibliography\"',\n ];\n if (opts.styleName !== undefined) {\n attrParts.push(`StyleName=\"${escapeXml(opts.styleName)}\"`);\n }\n\n const parts: string[] = [`<b:Sources ${attrParts.join(\" \")}>`];\n\n for (const source of opts.sources) {\n const sourceParts: string[] = [];\n for (const [tagName, key] of SOURCE_FIELDS) {\n const value = source[key];\n if (value !== undefined) {\n sourceParts.push(`<b:${tagName}>${escapeXml(value)}</b:${tagName}>`);\n }\n }\n parts.push(`<b:Source>${sourceParts.join(\"\")}</b:Source>`);\n }\n\n parts.push(\"</b:Sources>\");\n return parts.join(\"\");\n },\n\n parse(el, _ctx) {\n const opts: Partial<BibliographyOptions> = {};\n\n // StyleName attribute\n const styleName = el.attributes?.[\"StyleName\"];\n if (styleName) opts.styleName = styleName as string;\n\n // Parse b:Source children\n const sources: SourceTypeOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"b:Source\") continue;\n const source: SourceTypeOptions = {};\n for (const [, key] of SOURCE_FIELDS) {\n const xmlChild = findChild(child, `b:${SOURCE_FIELDS.find((f) => f[1] === key)![0]}`);\n if (xmlChild) {\n const val = textOf(xmlChild);\n if (val) source[key] = val;\n }\n }\n sources.push(source);\n }\n opts.sources = sources;\n\n return opts as BibliographyOptions;\n },\n};\n","/**\n * Glossary document component — stores building block definitions.\n *\n * Generates word/glossary/document.xml containing Quick Parts entries\n * that appear in Word's Insert > Quick Parts gallery.\n *\n * @module\n */\n\nimport { parseOnOff } from \"@office-open/core\";\nimport { documentNamespaceAttributes } from \"@parts/document/document-attributes\";\nimport type { SectionChild } from \"@shared/section\";\n\n/** Gallery type for building blocks (ST_DocPartGallery) */\nexport const DocPartGallery = {\n PLACEHOLDER: \"placeholder\",\n DEFAULT: \"default\",\n DOC_PARTS: \"docParts\",\n COVER_PAGE: \"coverPg\",\n EQUATIONS: \"eq\",\n FOOTERS: \"ftrs\",\n HEADERS: \"hdrs\",\n PAGE_NUMBERS: \"pgNum\",\n TABLES: \"tbls\",\n WATERMARKS: \"watermarks\",\n AUTO_TEXT: \"autoTxt\",\n TEXT_BOX: \"txtBox\",\n PAGE_NUMBERS_TOP: \"pgNumT\",\n PAGE_NUMBERS_BOTTOM: \"pgNumB\",\n PAGE_NUMBERS_MARGIN: \"pgNumMargins\",\n TABLE_OF_CONTENTS: \"tblOfContents\",\n BIBLIOGRAPHY: \"bib\",\n CUSTOM_QUICK_PARTS: \"custQuickParts\",\n CUSTOM_COVER_PAGE: \"custCoverPg\",\n CUSTOM_EQUATIONS: \"custEq\",\n CUSTOM_FOOTERS: \"custFtrs\",\n CUSTOM_HEADERS: \"custHdrs\",\n CUSTOM_PAGE_NUMBERS: \"custPgNum\",\n CUSTOM_TABLES: \"custTbls\",\n CUSTOM_WATERMARKS: \"custWatermarks\",\n CUSTOM_AUTO_TEXT: \"custAutoTxt\",\n CUSTOM_TEXT_BOX: \"custTxtBox\",\n CUSTOM_PAGE_NUMBERS_TOP: \"custPgNumT\",\n CUSTOM_PAGE_NUMBERS_BOTTOM: \"custPgNumB\",\n CUSTOM_PAGE_NUMBERS_MARGIN: \"custPgNumMargins\",\n CUSTOM_TABLE_OF_CONTENTS: \"custTblOfContents\",\n CUSTOM_BIBLIOGRAPHY: \"custBib\",\n CUSTOM1: \"custom1\",\n CUSTOM2: \"custom2\",\n CUSTOM3: \"custom3\",\n CUSTOM4: \"custom4\",\n CUSTOM5: \"custom5\",\n} as const;\n\nexport type DocPartGallery = (typeof DocPartGallery)[keyof typeof DocPartGallery];\n\n/** Building block type (ST_DocPartType) */\nexport const DocPartType = {\n NONE: \"none\",\n NORMAL: \"normal\",\n AUTO_EXPAND: \"autoExp\",\n TOOLBAR: \"toolbar\",\n SPELLER: \"speller\",\n FORM_FIELD: \"formFld\",\n BUILDING_BLOCK_PLACEHOLDER: \"bbPlcHdr\",\n} as const;\n\nexport type DocPartType = (typeof DocPartType)[keyof typeof DocPartType];\n\n/** Building block behavior (ST_DocPartBehavior) */\nexport const DocPartBehavior = {\n CONTENT: \"content\",\n PARAGRAPH: \"p\",\n PAGE: \"pg\",\n} as const;\n\nexport type DocPartBehavior = (typeof DocPartBehavior)[keyof typeof DocPartBehavior];\n\n/** A single building block (CT_DocPart) */\nexport interface DocPartOptions {\n /** Building block name (required) */\n name: string;\n /** Gallery category (required) */\n gallery: DocPartGallery;\n /** Category name within the gallery */\n category?: string;\n /** Building block types */\n types?: DocPartType[];\n /** Whether all building block types are included (w:all attribute) */\n allTypes?: boolean;\n /** Insertion behaviors */\n behaviors?: DocPartBehavior[];\n /** Description */\n description?: string;\n /** GUID for this building block */\n guid?: string;\n /** Whether the name is decorated (built-in) */\n decorated?: boolean;\n /** Body content — paragraphs, tables, etc. */\n children: SectionChild[];\n}\n\n/** Glossary document options */\nexport interface GlossaryDocumentOptions {\n /** Building blocks */\n parts: DocPartOptions[];\n}\n\n// ── Descriptor ──\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, escapeXml, findChild } from \"@office-open/xml\";\n\nimport { parseParagraph } from \"../body\";\nimport type { BodyContext, DocxReadContext } from \"../context\";\n\nconst GLOSSARY_NS = documentNamespaceAttributes([\n \"wpc\",\n \"mc\",\n \"o\",\n \"r\",\n \"m\",\n \"v\",\n \"wp\",\n \"w10\",\n \"w\",\n \"w14\",\n \"wpg\",\n \"wpi\",\n \"wne\",\n \"wps\",\n]);\n\nfunction docPartPrXml(part: GlossaryDocumentOptions[\"parts\"][number]): string {\n const prParts: string[] = [];\n prParts.push(\n `<w:name w:val=\"${escapeXml(part.name)}\"${part.decorated ? ' w:decorated=\"1\"' : \"\"}/>`,\n );\n if (part.category || part.gallery) {\n const catParts: string[] = [];\n if (part.category) {\n catParts.push(`<w:name w:val=\"${escapeXml(part.category)}\"/>`);\n }\n catParts.push(`<w:gallery w:val=\"${part.gallery}\"/>`);\n prParts.push(`<w:category>${catParts.join(\"\")}</w:category>`);\n }\n if (part.types && part.types.length > 0) {\n const typeXml = part.types.map((t) => `<w:type w:val=\"${t}\"/>`).join(\"\");\n const allAttr = part.allTypes ? ' w:all=\"1\"' : \"\";\n prParts.push(`<w:types${allAttr}>${typeXml}</w:types>`);\n }\n if (part.behaviors && part.behaviors.length > 0) {\n const behaviorXml = part.behaviors.map((b) => `<w:behavior w:val=\"${b}\"/>`).join(\"\");\n prParts.push(`<w:behaviors>${behaviorXml}</w:behaviors>`);\n }\n if (part.description) {\n prParts.push(`<w:description w:val=\"${escapeXml(part.description)}\"/>`);\n }\n if (part.guid) {\n prParts.push(`<w:guid w:val=\"${escapeXml(part.guid)}\"/>`);\n }\n return `<w:docPartPr>${prParts.join(\"\")}</w:docPartPr>`;\n}\n\nexport const glossaryDesc: CustomDescriptor<GlossaryDocumentOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const partsXml = opts.parts\n .map((part) => {\n const bodyContent = ((part.children ?? []) as SectionChild[])\n .map((child) => ctx.stringifyChild(child))\n .join(\"\");\n\n return `<w:docPart>${docPartPrXml(part)}<w:docPartBody>${bodyContent}</w:docPartBody></w:docPart>`;\n })\n .join(\"\");\n\n return `<w:glossaryDocument ${GLOSSARY_NS}><w:docParts>${partsXml}</w:docParts></w:glossaryDocument>`;\n },\n\n parse(el, ctx) {\n const dctx = ctx as DocxReadContext;\n const parts: DocPartOptions[] = [];\n\n const docPartsEl = findChild(el, \"w:docParts\");\n if (!docPartsEl) return { parts };\n\n for (const docPart of docPartsEl.elements ?? []) {\n if (docPart.name !== \"w:docPart\") continue;\n const part: Partial<DocPartOptions> = {};\n\n // Parse w:docPartPr\n const pr = findChild(docPart, \"w:docPartPr\");\n if (pr) {\n // name\n const name = findChild(pr, \"w:name\");\n if (name) {\n part.name = attr(name, \"w:val\") ?? \"\";\n const decorated = attr(name, \"w:decorated\");\n if (parseOnOff(decorated)) part.decorated = true;\n }\n\n // category\n const category = findChild(pr, \"w:category\");\n if (category) {\n const catName = findChild(category, \"w:name\");\n if (catName) part.category = attr(catName, \"w:val\");\n const gallery = findChild(category, \"w:gallery\");\n if (gallery) part.gallery = attr(gallery, \"w:val\") as DocPartOptions[\"gallery\"];\n }\n\n // types\n const types = findChild(pr, \"w:types\");\n if (types) {\n const typeList: string[] = [];\n for (const t of types.elements ?? []) {\n if (t.name === \"w:type\") {\n const val = attr(t, \"w:val\");\n if (val) typeList.push(val);\n }\n }\n if (typeList.length > 0) part.types = typeList as DocPartOptions[\"types\"];\n const allAttr = attr(types, \"w:all\");\n if (parseOnOff(allAttr)) part.allTypes = true;\n }\n\n // behaviors\n const behaviors = findChild(pr, \"w:behaviors\");\n if (behaviors) {\n const behaviorList: string[] = [];\n for (const b of behaviors.elements ?? []) {\n if (b.name === \"w:behavior\") {\n const val = attr(b, \"w:val\");\n if (val) behaviorList.push(val);\n }\n }\n if (behaviorList.length > 0) part.behaviors = behaviorList as DocPartOptions[\"behaviors\"];\n }\n\n // description\n const desc = findChild(pr, \"w:description\");\n if (desc) {\n const val = attr(desc, \"w:val\");\n if (val) part.description = val;\n }\n\n // guid\n const guid = findChild(pr, \"w:guid\");\n if (guid) {\n const val = attr(guid, \"w:val\");\n if (val) part.guid = val;\n }\n }\n\n // Parse w:docPartBody children\n const body = findChild(docPart, \"w:docPartBody\");\n if (body) {\n const childList: unknown[] = [];\n for (const sub of body.elements ?? []) {\n if (sub.name === \"w:p\") {\n childList.push({ paragraph: parseParagraph(sub, dctx) });\n }\n }\n if (childList.length > 0) part.children = childList as DocPartOptions[\"children\"];\n }\n\n parts.push(part as DocPartOptions);\n }\n\n return { parts };\n },\n};\n","/**\n * Comments descriptor — produces word/comments.xml.\n *\n * Stringifies pure JSON CommentsOptions into XML without creating\n * Comment/Comments class instances.\n *\n * @module\n */\n\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrNum, escapeXml } from \"@office-open/xml\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type { CommentsOptions, CommentOptions } from \"@parts/paragraph/run/comment-run\";\n\nimport { parseParagraph } from \"../body\";\nimport type { BodyContext } from \"../context\";\nimport type { DocxReadContext } from \"../context\";\nimport { documentNamespaceAttributes } from \"./document/document-attributes\";\nimport { stringifyParagraphInline } from \"./inline\";\n\nconst COMMENTS_NS = documentNamespaceAttributes([\n \"aink\",\n \"am3d\",\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"w16\",\n \"w16cex\",\n \"w16cid\",\n \"w16sdtdh\",\n \"w16se\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n]);\n\n// ── Comment stringification ──\n\nfunction stringifyComment(opts: CommentOptions, ctx: BodyContext): string {\n const dateStr =\n typeof opts.date === \"string\" ? opts.date : (opts.date ?? new Date()).toISOString();\n // w:author is XSD-required (CT_TrackChange); default to empty string when absent.\n const attrs: string[] = [\n `w:id=\"${opts.id}\"`,\n `w:author=\"${escapeXml(opts.author ?? \"\")}\"`,\n `w:date=\"${escapeXml(dateStr)}\"`,\n ];\n if (opts.initials !== undefined) attrs.push(`w:initials=\"${escapeXml(opts.initials)}\"`);\n\n const parts: string[] = [];\n for (const child of opts.children) {\n parts.push(stringifyParagraphInline(child, ctx));\n }\n\n return `<w:comment ${attrs.join(\" \")}>${parts.join(\"\")}</w:comment>`;\n}\n\n// ── Descriptor ──\n\nexport const commentsDesc: CustomDescriptor<CommentsOptions, BodyContext> = {\n kind: \"custom\",\n\n stringify(opts, ctx) {\n const parts: string[] = [`<w:comments ${COMMENTS_NS}>`];\n\n for (const child of opts.children) {\n parts.push(stringifyComment(child, ctx));\n }\n\n parts.push(\"</w:comments>\");\n return parts.join(\"\");\n },\n\n parse(el, ctx) {\n const comments: CommentOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.name !== \"w:comment\") continue;\n const id = attrNum(child, \"w:id\");\n if (id === undefined) continue;\n const comment: Partial<CommentOptions> = { id };\n const date = attr(child, \"w:date\");\n if (date) comment.date = date;\n const author = attr(child, \"w:author\");\n if (author !== undefined) comment.author = author;\n const initials = attr(child, \"w:initials\");\n if (initials !== undefined) comment.initials = initials;\n\n const children: (string | ParagraphOptions)[] = [];\n for (const sub of child.elements ?? []) {\n if (sub.name === \"w:p\") {\n children.push(parseParagraph(sub, ctx as DocxReadContext));\n }\n }\n comment.children = children;\n comments.push(comment as CommentOptions);\n }\n return { children: comments };\n },\n};\n","/**\n * Core Properties module for WordprocessingML documents.\n *\n * Provides the DocumentOptions interface for document metadata.\n * XML generation is handled by the descriptor pipeline (corePropertiesDesc).\n *\n * Reference: ISO-IEC29500-4_2016 shared-documentPropertiesCore.xsd\n *\n * @module\n */\nimport type { ContentTypesInput, DataType } from \"@office-open/core\";\nimport type { BibliographyOptions } from \"@parts/bibliography\";\nimport type { EmbeddedFontOptions } from \"@parts/fonts/font-table\";\nimport type { GlossaryDocumentOptions } from \"@parts/glossary-document\";\nimport type { CommentsOptions } from \"@parts/paragraph/run/comment-run\";\nimport type { HyphenationOptions } from \"@parts/settings\";\nimport type { CompatibilityOptions } from \"@parts/settings/compatibility\";\nimport type {\n DocumentProtectionOptions,\n SettingsOptions,\n WriteProtectionOptions,\n} from \"@parts/settings/settings\";\nimport type { SectionOptions } from \"@shared/section\";\n\nimport type { AppPropertiesOptions } from \"./app-properties\";\nimport type { CustomPropertyOptions } from \"./custom-properties\";\nimport type { DocumentBackgroundOptions } from \"./document\";\nimport type { EndnoteSeparator } from \"./endnotes/descriptor\";\nimport type { FootnoteSeparator } from \"./footnotes/descriptor\";\nimport type { NumberingOptions } from \"./numbering\";\nimport type { ParagraphOptions } from \"./paragraph\";\nimport type { StylesOptions } from \"./styles\";\nimport type { WebSettingsOptions } from \"./web-settings\";\n\n/**\n * Document-level feature toggles parsed from settings.xml.\n *\n * @property trackRevisions - Track changes\n * @property updateFields - Update fields on open\n * @property documentProtection - Document write protection\n */\nexport interface FeaturesOptions {\n trackRevisions?: boolean;\n updateFields?: boolean;\n documentProtection?: DocumentProtectionOptions;\n}\n\n/**\n * Options for configuring document properties.\n *\n * @property sections - Document section configurations\n * @property title - Document title\n * @property subject - Document subject\n * @property creator - Document creator/author\n * @property keywords - Document keywords for searchability\n * @property description - Document description\n * @property lastModifiedBy - User who last modified the document\n * @property revision - Revision number\n * @property lastPrinted - Last printed timestamp (W3CDTF), round-tripped from cp:lastPrinted\n * @property externalStyles - External stylesheet reference\n * @property styles - Document styles configuration\n * @property numbering - Numbering configuration\n * @property comments - Document comments configuration\n * @property bibliography - Document bibliography sources\n * @property footnotes - Document footnotes\n * @property background - Document background settings\n * @property features - Document features like track changes\n * @property compatibility - Compatibility settings\n * @property customProperties - Custom document properties\n * @property evenAndOddHeaderAndFooters - Enable different headers/footers for even/odd pages\n * @property defaultTabStop - Default tab stop width\n * @property fonts - Font configurations\n * @property hyphenation - Hyphenation settings\n */\nexport interface DocumentOptions extends CorePropertiesOptions {\n sections: SectionOptions[];\n externalStyles?: string;\n styles?: StylesOptions;\n numbering?: NumberingOptions;\n comments?: CommentsOptions;\n bibliography?: BibliographyOptions;\n footnotes?: Record<string, { children: (ParagraphOptions | string)[] }> & {\n /**\n * Separator footnote — id + content round-tripped verbatim from the source\n * so the generated id stays consistent with settings.footnotePr, which\n * references it. Omit for freshly generated documents (defaults apply).\n */\n separator?: FootnoteSeparator;\n /** Continuation separator footnote — round-tripped verbatim from the source. */\n continuationSeparator?: FootnoteSeparator;\n };\n endnotes?: Record<string, { children: (ParagraphOptions | string)[] }> & {\n /** Separator endnote — id + content round-tripped verbatim from the source. */\n separator?: EndnoteSeparator;\n /** Continuation separator endnote — round-tripped verbatim from the source. */\n continuationSeparator?: EndnoteSeparator;\n };\n background?: DocumentBackgroundOptions;\n features?: FeaturesOptions;\n compatibility?: CompatibilityOptions;\n customProperties?: CustomPropertyOptions[];\n evenAndOddHeaderAndFooters?: boolean;\n defaultTabStop?: number;\n fonts?: EmbeddedFontOptions[];\n hyphenation?: HyphenationOptions;\n /** Document conformance class (w:document/@w:conformance). */\n conformance?: \"strict\" | \"transitional\";\n /** Controls whether punctuation is compressed at line ends */\n characterSpacingControl?: \"compressPunctuation\" | \"doNotCompress\";\n /** Default document view mode */\n view?: \"none\" | \"print\" | \"outline\" | \"masterPages\" | \"normal\" | \"web\";\n /** Default zoom level (percentage) and type */\n zoom?: {\n percent?: number;\n val?: \"none\" | \"fullPage\" | \"bestFit\" | \"textFit\";\n };\n /** Write protection recommendation (not enforcement) */\n writeProtection?: WriteProtectionOptions;\n /** Whether to display the background shape in print layout */\n displayBackgroundShape?: boolean;\n /** Whether to embed TrueType fonts in the document */\n embedTrueTypeFonts?: boolean;\n /** Whether to embed system fonts in the document */\n embedSystemFonts?: boolean;\n /** Whether to save only a subset of the embedded fonts */\n saveSubsetFonts?: boolean;\n /** Document variables (key-value pairs stored in the document) */\n docVars?: { name: string; val: string }[];\n /** Theme color scheme remapping */\n colorSchemeMapping?: SettingsOptions[\"colorSchemeMapping\"];\n /** Mail merge configuration */\n mailMerge?: SettingsOptions[\"mailMerge\"];\n /** Glossary document — building blocks (Quick Parts) */\n glossary?: GlossaryDocumentOptions;\n /** Additional document settings passed through to the settings.xml part */\n settings?: SettingsOptions;\n /** Web settings for browser rendering (word/webSettings.xml) */\n webSettings?: WebSettingsOptions;\n /** Content types from [Content_Types].xml (parse path only) */\n contentTypes?: ContentTypesInput;\n /**\n * Parts carried verbatim from the source that generate() does not rebuild\n * (e.g. word/theme/*, customXml/*). Kept as raw bytes so their [Content_Types]\n * declarations stay valid and the package opens in Word. Media/fonts/headers\n * are rebuilt by the compiler and must NOT be listed here.\n */\n rawParts?: { path: string; data: DataType }[];\n /** Extended properties (docProps/app.xml) */\n appProperties?: AppPropertiesOptions;\n}\n\n// ── Descriptor ──\n\nimport type { CorePropertiesOptions } from \"@office-open/core\";\nimport { buildCorePropertiesXmlString, parseCorePropsElement } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\n\nexport const corePropertiesDesc: CustomDescriptor<CorePropertiesOptions> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n return buildCorePropertiesXmlString(opts);\n },\n\n parse(el, _ctx) {\n return parseCorePropsElement(el);\n },\n};\n","/**\n * Web Settings module for WordprocessingML documents.\n *\n * Provides types for web settings configuration.\n * XML generation is handled by the descriptor pipeline (webSettingsDesc).\n *\n * Reference: http://officeopenxml.com/WPwebSettings.php\n *\n * @module\n */\n\nimport type { FramesetOptions } from \"@parts/frameset\";\n\n/**\n * Border options for div elements.\n */\nexport interface DivBorderOptions {\n top?: { style: string; color?: string; size?: number };\n left?: { style: string; color?: string; size?: number };\n bottom?: { style: string; color?: string; size?: number };\n right?: { style: string; color?: string; size?: number };\n}\n\n/**\n * Options for a div element (CT_Div).\n */\nexport interface DivOptions {\n /** Unique div identifier (required by CT_Div/@id) */\n id: number;\n marginLeft: number | UniversalMeasure;\n marginRight: number | UniversalMeasure;\n marginTop: number | UniversalMeasure;\n marginBottom: number | UniversalMeasure;\n /** Mark as HTML blockquote element */\n blockQuote?: boolean;\n /** Mark as HTML body element */\n bodyDiv?: boolean;\n border?: DivBorderOptions;\n children?: DivOptions[];\n}\n\n/**\n * Screen size types for web settings target.\n */\nexport const TargetScreenSize = {\n SIZE_544X376: \"544x376\",\n SIZE_640X480: \"640x480\",\n SIZE_720X512: \"720x512\",\n SIZE_800X600: \"800x600\",\n SIZE_1024X768: \"1024x768\",\n SIZE_1152X882: \"1152x882\",\n SIZE_1152X900: \"1152x900\",\n SIZE_1280X1024: \"1280x1024\",\n SIZE_1600X1200: \"1600x1200\",\n SIZE_1800X1440: \"1800x1440\",\n SIZE_1920X1200: \"1920x1200\",\n} as const;\n\n/**\n * Options for the w:optimizeForBrowser element.\n *\n * CT_OptimizeForBrowser extends CT_OnOff with an optional @w:target attribute.\n */\nexport interface OptimizeForBrowserOptions {\n /** On/off value — defaults to true when omitted (CT_OnOff). */\n value?: boolean;\n /** Target screen resolution name (w:optimizeForBrowser/@w:target). */\n target?: string;\n}\n\n/**\n * Options for web settings (CT_WebSettings).\n */\nexport interface WebSettingsOptions {\n /** Frameset definition for web layout */\n frameset?: FramesetOptions;\n /** Div elements for HTML div formatting */\n divs?: DivOptions[];\n /** Character encoding for web output */\n encoding?: string;\n /** Optimize document rendering for web browser (w:optimizeForBrowser). */\n optimizeForBrowser?: boolean | OptimizeForBrowserOptions;\n /** Rely on VML for graphics display */\n relyOnVML?: boolean;\n /** Allow PNG image format in web output */\n allowPNG?: boolean;\n /** Do not rely on CSS for formatting */\n doNotRelyOnCSS?: boolean;\n /** Do not save as single web file */\n doNotSaveAsSingleFile?: boolean;\n /** Do not organize supporting files in folders */\n doNotOrganizeInFolder?: boolean;\n /** Do not use long file names for supporting files */\n doNotUseLongFileNames?: boolean;\n /** Pixels per inch for web output */\n pixelsPerInch?: number;\n /** Target screen size */\n targetScreenSize?: (typeof TargetScreenSize)[keyof typeof TargetScreenSize] | string;\n /** Save smart tags as XML */\n saveSmartTagsAsXml?: boolean;\n}\n\n// ── Descriptor ──\n\nimport type { UniversalMeasure } from \"@office-open/core\";\nimport type { CustomDescriptor } from \"@office-open/core/descriptor\";\nimport { attr, attrBool, attrMeasure, attrNum, escapeXml, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { WebFrameOptions, FramesetSplitbarOptions } from \"@parts/frameset\";\n\nimport { documentNamespaceAttributes } from \"./document/document-attributes\";\n\n/** Subset of WebSettingsOptions for descriptor stringify. */\nexport interface WebSettingsInput {\n frameset?: FramesetOptions;\n divs?: DivOptions[];\n encoding?: string;\n optimizeForBrowser?: boolean | OptimizeForBrowserOptions;\n relyOnVML?: boolean;\n allowPNG?: boolean;\n doNotRelyOnCSS?: boolean;\n doNotSaveAsSingleFile?: boolean;\n doNotOrganizeInFolder?: boolean;\n doNotUseLongFileNames?: boolean;\n pixelsPerInch?: number;\n targetScreenSize?: string;\n saveSmartTagsAsXml?: boolean;\n}\n\nconst WS_NS = documentNamespaceAttributes([\"mc\", \"r\", \"w\", \"w15\"]);\n\nfunction wsOnOff(tag: string, val: boolean): string {\n return `<${tag} w:val=\"${val ? \"true\" : \"false\"}\"/>`;\n}\n\nfunction wsStringVal(tag: string, val: string): string {\n return `<${tag} w:val=\"${escapeXml(val)}\"/>`;\n}\n\nfunction wsNumVal(tag: string, val: number | UniversalMeasure): string {\n return `<${tag} w:val=\"${val}\"/>`;\n}\n\n// ── Parse helpers (for descriptor parse path) ──\n\nfunction parseFramesetEl(el: Element): FramesetOptions {\n const opts: Partial<FramesetOptions> = {};\n\n const sz = findChild(el, \"w:sz\");\n if (sz) {\n const val = attr(sz, \"w:val\");\n if (val) opts.size = val;\n }\n\n const splitbar = findChild(el, \"w:framesetSplitbar\");\n if (splitbar) opts.splitbar = parseSplitbarEl(splitbar);\n\n const layout = findChild(el, \"w:frameLayout\");\n if (layout) {\n const val = attr(layout, \"w:val\");\n if (val === \"rows\" || val === \"cols\") opts.layout = val;\n }\n\n const title = findChild(el, \"w:title\");\n if (title) {\n const val = attr(title, \"w:val\");\n if (val) opts.title = val;\n }\n\n const children: (FramesetOptions | WebFrameOptions)[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:frameset\") {\n children.push(parseFramesetEl(child));\n } else if (child.name === \"w:frame\") {\n children.push(parseFrameEl(child));\n }\n }\n if (children.length > 0) opts.children = children;\n\n return opts as FramesetOptions;\n}\n\nfunction parseSplitbarEl(el: Element): FramesetSplitbarOptions {\n const opts: Partial<FramesetSplitbarOptions> = {};\n\n const w = findChild(el, \"w:w\");\n if (w) {\n const val = attrNum(w, \"w:w\");\n if (val !== undefined) opts.width = val;\n }\n\n const color = findChild(el, \"w:color\");\n if (color) {\n const val = attr(color, \"w:val\");\n if (val) opts.color = val;\n }\n\n if (findChild(el, \"w:noBorder\")) opts.noBorder = true;\n if (findChild(el, \"w:flatBorders\")) opts.flatBorders = true;\n\n return opts as FramesetSplitbarOptions;\n}\n\nfunction parseFrameEl(el: Element): WebFrameOptions {\n const opts: Partial<WebFrameOptions> = {};\n\n const sz = findChild(el, \"w:sz\");\n if (sz) {\n const val = attr(sz, \"w:val\");\n if (val) opts.size = val;\n }\n\n const name = findChild(el, \"w:name\");\n if (name) {\n const val = attr(name, \"w:val\");\n if (val) opts.name = val;\n }\n\n const title = findChild(el, \"w:title\");\n if (title) {\n const val = attr(title, \"w:val\");\n if (val) opts.title = val;\n }\n\n const source = findChild(el, \"w:sourceFileName\");\n if (source) {\n const val = attr(source, \"r:id\");\n if (val) opts.sourceRId = val;\n }\n\n const marW = findChild(el, \"w:marW\");\n if (marW) {\n const val = attrNum(marW, \"w:val\");\n if (val !== undefined) opts.marginWidth = val;\n }\n\n const marH = findChild(el, \"w:marH\");\n if (marH) {\n const val = attrNum(marH, \"w:val\");\n if (val !== undefined) opts.marginHeight = val;\n }\n\n const scrollbar = findChild(el, \"w:scrollbar\");\n if (scrollbar) {\n const val = attr(scrollbar, \"w:val\");\n if (val === \"on\" || val === \"off\" || val === \"auto\") opts.scrollbar = val;\n }\n\n if (findChild(el, \"w:noResizeAllowed\")) opts.noResizeAllowed = true;\n if (findChild(el, \"w:linkedToFile\")) opts.linkedToFile = true;\n\n const longDesc = findChild(el, \"w:longDesc\");\n if (longDesc) {\n const val = attr(longDesc, \"r:id\");\n if (val) opts.longDescRId = val;\n }\n\n return opts as WebFrameOptions;\n}\n\nfunction parseDivsEl(el: Element): DivOptions[] {\n const result: DivOptions[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:div\") {\n result.push(parseDivEl(child));\n }\n }\n return result;\n}\n\nfunction parseDivEl(el: Element): DivOptions {\n const id = attrNum(el, \"w:id\") ?? 0;\n const opts: Partial<DivOptions> = { id };\n\n const marLeft = findChild(el, \"w:marLeft\");\n if (marLeft) {\n const val = attrMeasure(marLeft, \"w:val\");\n if (val !== undefined) opts.marginLeft = val as number | UniversalMeasure;\n }\n\n const marRight = findChild(el, \"w:marRight\");\n if (marRight) {\n const val = attrMeasure(marRight, \"w:val\");\n if (val !== undefined) opts.marginRight = val as number | UniversalMeasure;\n }\n\n const marTop = findChild(el, \"w:marTop\");\n if (marTop) {\n const val = attrMeasure(marTop, \"w:val\");\n if (val !== undefined) opts.marginTop = val as number | UniversalMeasure;\n }\n\n const marBottom = findChild(el, \"w:marBottom\");\n if (marBottom) {\n const val = attrMeasure(marBottom, \"w:val\");\n if (val !== undefined) opts.marginBottom = val as number | UniversalMeasure;\n }\n\n const blockQuote = findChild(el, \"w:blockQuote\");\n if (blockQuote) {\n const val = attr(blockQuote, \"w:val\");\n opts.blockQuote = val !== \"off\";\n }\n\n const bodyDiv = findChild(el, \"w:bodyDiv\");\n if (bodyDiv) {\n const val = attr(bodyDiv, \"w:val\");\n opts.bodyDiv = val !== \"off\";\n }\n\n const divBdr = findChild(el, \"w:divBdr\");\n if (divBdr) {\n opts.border = parseDivBorderEl(divBdr);\n }\n\n const divsChild = findChild(el, \"w:divsChild\");\n if (divsChild) {\n const children = parseDivsEl(divsChild);\n if (children.length > 0) opts.children = children;\n }\n\n return opts as DivOptions;\n}\n\nfunction parseDivBorderEl(el: Element): DivBorderOptions {\n const opts: Partial<DivBorderOptions> = {};\n\n for (const side of [\"top\", \"left\", \"bottom\", \"right\"] as const) {\n const sideEl = findChild(el, `w:${side}`);\n if (sideEl) {\n const b: Partial<NonNullable<DivBorderOptions[\"top\"]>> = {};\n const val = attr(sideEl, \"w:val\");\n if (val) b.style = val;\n const color = attr(sideEl, \"w:color\");\n if (color) b.color = color;\n const sz = attrNum(sideEl, \"w:sz\");\n if (sz !== undefined) b.size = sz;\n opts[side] = b as NonNullable<DivBorderOptions[\"top\"]>;\n }\n }\n\n return opts as DivBorderOptions;\n}\n\nfunction wsDivBorderXml(b: NonNullable<DivOptions[\"border\"]>): string {\n const parts: string[] = [\"<w:divBdr>\"];\n const sides: [string, NonNullable<DivOptions[\"border\"]>[\"top\"]][] = [\n [\"w:top\", b.top],\n [\"w:left\", b.left],\n [\"w:bottom\", b.bottom],\n [\"w:right\", b.right],\n ];\n for (const [tag, side] of sides) {\n if (!side) continue;\n const attrParts: string[] = [`w:val=\"${escapeXml(side.style)}\"`];\n if (side.color) attrParts.push(`w:color=\"${escapeXml(side.color)}\"`);\n if (side.size !== undefined) attrParts.push(`w:sz=\"${side.size}\"`);\n parts.push(`<${tag} ${attrParts.join(\" \")}/>`);\n }\n parts.push(\"</w:divBdr>\");\n return parts.join(\"\");\n}\n\nfunction wsDivXml(d: DivOptions): string {\n const parts: string[] = [`<w:div w:id=\"${d.id}\">`];\n if (d.blockQuote !== undefined)\n parts.push(wsStringVal(\"w:blockQuote\", d.blockQuote ? \"on\" : \"off\"));\n if (d.bodyDiv !== undefined) parts.push(wsStringVal(\"w:bodyDiv\", d.bodyDiv ? \"on\" : \"off\"));\n parts.push(wsNumVal(\"w:marLeft\", d.marginLeft));\n parts.push(wsNumVal(\"w:marRight\", d.marginRight));\n parts.push(wsNumVal(\"w:marTop\", d.marginTop));\n parts.push(wsNumVal(\"w:marBottom\", d.marginBottom));\n if (d.border) parts.push(wsDivBorderXml(d.border));\n if (d.children?.length) {\n parts.push(\"<w:divsChild>\");\n for (const child of d.children) parts.push(wsDivXml(child));\n parts.push(\"</w:divsChild>\");\n }\n parts.push(\"</w:div>\");\n return parts.join(\"\");\n}\n\nexport function framesetXml(fs: FramesetOptions): string {\n const parts: string[] = [\"<w:frameset>\"];\n if (fs.size !== undefined) parts.push(wsStringVal(\"w:sz\", fs.size));\n if (fs.splitbar) {\n parts.push(\"<w:framesetSplitbar>\");\n if (fs.splitbar.width !== undefined)\n parts.push(`<w:w w:w=\"${fs.splitbar.width}\" w:type=\"dxa\"/>`);\n if (fs.splitbar.color !== undefined) parts.push(wsStringVal(\"w:color\", fs.splitbar.color));\n if (fs.splitbar.noBorder) parts.push(\"<w:noBorder/>\");\n if (fs.splitbar.flatBorders) parts.push(\"<w:flatBorders/>\");\n parts.push(\"</w:framesetSplitbar>\");\n }\n if (fs.layout !== undefined) parts.push(`<w:frameLayout w:val=\"${fs.layout}\"/>`);\n if (fs.title !== undefined) parts.push(wsStringVal(\"w:title\", fs.title));\n if (fs.children) {\n for (const child of fs.children) {\n if (\"children\" in child || \"layout\" in child || \"splitbar\" in child) {\n parts.push(framesetXml(child as FramesetOptions));\n } else {\n parts.push(frameXml(child as WebFrameOptions));\n }\n }\n }\n parts.push(\"</w:frameset>\");\n return parts.join(\"\");\n}\n\nexport function frameXml(f: WebFrameOptions): string {\n const parts: string[] = [\"<w:frame>\"];\n if (f.size !== undefined) parts.push(wsStringVal(\"w:sz\", f.size));\n if (f.name !== undefined) parts.push(wsStringVal(\"w:name\", f.name));\n if (f.title !== undefined) parts.push(wsStringVal(\"w:title\", f.title));\n if (f.sourceRId !== undefined) parts.push(`<w:sourceFileName r:id=\"${escapeXml(f.sourceRId)}\"/>`);\n if (f.marginWidth !== undefined) parts.push(wsNumVal(\"w:marW\", f.marginWidth));\n if (f.marginHeight !== undefined) parts.push(wsNumVal(\"w:marH\", f.marginHeight));\n if (f.scrollbar !== undefined) parts.push(`<w:scrollbar w:val=\"${f.scrollbar}\"/>`);\n if (f.noResizeAllowed) parts.push(\"<w:noResizeAllowed/>\");\n if (f.linkedToFile) parts.push(\"<w:linkedToFile/>\");\n if (f.longDescRId !== undefined) parts.push(`<w:longDesc r:id=\"${escapeXml(f.longDescRId)}\"/>`);\n parts.push(\"</w:frame>\");\n return parts.join(\"\");\n}\n\nexport const webSettingsDesc: CustomDescriptor<WebSettingsInput> = {\n kind: \"custom\",\n\n stringify(opts, _ctx) {\n const p: string[] = [`<w:webSettings ${WS_NS}>`];\n\n if (opts.frameset !== undefined) p.push(framesetXml(opts.frameset));\n if (opts.divs?.length) {\n p.push(\"<w:divs>\");\n for (const d of opts.divs) p.push(wsDivXml(d));\n p.push(\"</w:divs>\");\n }\n if (opts.encoding !== undefined) p.push(wsStringVal(\"w:encoding\", opts.encoding));\n if (opts.optimizeForBrowser !== undefined) {\n const ob = opts.optimizeForBrowser;\n if (typeof ob === \"boolean\") {\n p.push(wsOnOff(\"w:optimizeForBrowser\", ob));\n } else {\n // CT_OptimizeForBrowser: CT_OnOff + optional @w:target. Omit w:val when\n // true to match typical Word output; emit w:val=\"false\" only when disabled.\n const valAttr = ob.value === false ? ' w:val=\"false\"' : \"\";\n const targetAttr = ob.target ? ` w:target=\"${escapeXml(ob.target)}\"` : \"\";\n p.push(`<w:optimizeForBrowser${valAttr}${targetAttr}/>`);\n }\n }\n if (opts.relyOnVML !== undefined) p.push(wsOnOff(\"w:relyOnVML\", opts.relyOnVML));\n if (opts.allowPNG !== undefined) p.push(wsOnOff(\"w:allowPNG\", opts.allowPNG));\n if (opts.doNotRelyOnCSS !== undefined) p.push(wsOnOff(\"w:doNotRelyOnCSS\", opts.doNotRelyOnCSS));\n if (opts.doNotSaveAsSingleFile !== undefined)\n p.push(wsOnOff(\"w:doNotSaveAsSingleFile\", opts.doNotSaveAsSingleFile));\n if (opts.doNotOrganizeInFolder !== undefined)\n p.push(wsOnOff(\"w:doNotOrganizeInFolder\", opts.doNotOrganizeInFolder));\n if (opts.doNotUseLongFileNames !== undefined)\n p.push(wsOnOff(\"w:doNotUseLongFileNames\", opts.doNotUseLongFileNames));\n if (opts.pixelsPerInch !== undefined) p.push(wsNumVal(\"w:pixelsPerInch\", opts.pixelsPerInch));\n if (opts.targetScreenSize !== undefined)\n p.push(wsStringVal(\"w:targetScreenSz\", opts.targetScreenSize));\n if (opts.saveSmartTagsAsXml !== undefined)\n p.push(wsOnOff(\"w:saveSmartTagsAsXml\", opts.saveSmartTagsAsXml));\n\n p.push(\"</w:webSettings>\");\n return p.join(\"\");\n },\n\n parse(el, _ctx) {\n const opts: Partial<WebSettingsInput> = {};\n\n // Frameset\n const frameset = findChild(el, \"w:frameset\");\n if (frameset) {\n opts.frameset = parseFramesetEl(frameset);\n }\n\n // Divs\n const divs = findChild(el, \"w:divs\");\n if (divs) {\n const parsed = parseDivsEl(divs);\n if (parsed.length > 0) opts.divs = parsed;\n }\n\n // Encoding\n const encoding = findChild(el, \"w:encoding\");\n if (encoding) {\n const val = attr(encoding, \"w:val\");\n if (val) opts.encoding = val;\n }\n\n // Boolean fields\n for (const [name, optKey] of [\n [\"w:relyOnVML\", \"relyOnVML\"],\n [\"w:allowPNG\", \"allowPNG\"],\n [\"w:doNotRelyOnCSS\", \"doNotRelyOnCSS\"],\n [\"w:doNotSaveAsSingleFile\", \"doNotSaveAsSingleFile\"],\n [\"w:doNotOrganizeInFolder\", \"doNotOrganizeInFolder\"],\n [\"w:doNotUseLongFileNames\", \"doNotUseLongFileNames\"],\n [\"w:saveSmartTagsAsXml\", \"saveSmartTagsAsXml\"],\n ] as const) {\n const child = findChild(el, name);\n if (child) opts[optKey] = attrBool(child, \"w:val\") ?? true;\n }\n\n // optimizeForBrowser — CT_OptimizeForBrowser (CT_OnOff + optional @w:target)\n const obEl = findChild(el, \"w:optimizeForBrowser\");\n if (obEl) {\n const target = attr(obEl, \"w:target\");\n if (target) {\n opts.optimizeForBrowser = { value: attrBool(obEl, \"w:val\") ?? true, target };\n } else {\n opts.optimizeForBrowser = attrBool(obEl, \"w:val\") ?? true;\n }\n }\n\n // Pixels per inch\n const ppi = findChild(el, \"w:pixelsPerInch\");\n if (ppi) {\n const val = attrNum(ppi, \"w:val\");\n if (val !== undefined) opts.pixelsPerInch = val;\n }\n\n // Target screen size\n const targetScreenSize = findChild(el, \"w:targetScreenSz\");\n if (targetScreenSize) {\n const val = attr(targetScreenSize, \"w:val\");\n if (val) opts.targetScreenSize = val;\n }\n\n return opts as WebSettingsInput;\n },\n};\n","/**\n * Cell merge track revision component.\n *\n * @module\n */\n\nimport type { ChangedProperties } from \"../track-revision\";\n\n/**\n * Vertical merge revision types.\n */\nexport const VerticalMergeRevisionType = {\n /**\n * Cell that is merged with upper one.\n */\n CONTINUE: \"continue\",\n /**\n * Cell that is starting the vertical merge.\n */\n RESTART: \"restart\",\n} as const;\n\nexport type CellMergeAttributes = ChangedProperties & {\n verticalMerge?: (typeof VerticalMergeRevisionType)[keyof typeof VerticalMergeRevisionType];\n verticalMergeOriginal?: (typeof VerticalMergeRevisionType)[keyof typeof VerticalMergeRevisionType];\n};\n","/**\n * Vertical alignment module for WordprocessingML documents.\n *\n * This module provides vertical alignment options for table cells and sections.\n *\n * ## XSD Schema\n * ```xml\n * <xsd:complexType name=\"CT_VerticalJc\">\n * <xsd:attribute name=\"val\" type=\"ST_VerticalJc\" use=\"required\"/>\n * </xsd:complexType>\n *\n * <xsd:simpleType name=\"ST_VerticalJc\">\n * <xsd:restriction base=\"xsd:string\">\n * <xsd:enumeration value=\"both\"/>\n * <xsd:enumeration value=\"top\"/>\n * <xsd:enumeration value=\"center\"/>\n * <xsd:enumeration value=\"bottom\"/>\n * </xsd:restriction>\n * </xsd:simpleType>\n * ```\n *\n * @module\n */\n/**\n * Enumeration for table-cell vertical alignment. Only `top`, `center`, `bottom`\n * are valid according to ECMA-376 (§17.18.87 ST_VerticalJc within `<w:tcPr>`).\n *\n * @publicApi\n */\nexport const VerticalAlignTable = {\n BOTTOM: \"bottom\",\n CENTER: \"center\",\n TOP: \"top\",\n} as const;\n\n/**\n * Enumeration for section (<w:sectPr>) vertical alignment. Adds `both` on top of\n * the table-cell set (§17.18.87 ST_VerticalJc within <w:sectPr>).\n *\n * @publicApi\n */\nexport const VerticalAlignSection = {\n ...VerticalAlignTable,\n BOTH: \"both\",\n} as const;\n\nexport type TableVerticalAlign = (typeof VerticalAlignTable)[keyof typeof VerticalAlignTable];\n\nexport type SectionVerticalAlign = (typeof VerticalAlignSection)[keyof typeof VerticalAlignSection];\n\n/**\n * Creates a vertical alignment element in a WordprocessingML document.\n *\n * Used in table cells and sections to control vertical text positioning.\n *\n * @example\n * ```typescript\n * createVerticalAlign(VerticalAlignTable.CENTER);\n * ```\n */\nexport const createVerticalAlign = (value: TableVerticalAlign | SectionVerticalAlign): string =>\n `<w:vAlign w:val=\"${value}\"/>`;\n","import { IMAGE_MEDIA_CONTENT_TYPES, TargetModeType } from \"@office-open/core\";\nimport {\n DOCX_NS,\n OoxmlMimeType,\n appendContentType,\n appendOverride,\n appendRelationship,\n applyCorePropertiesOverride,\n createReplacer,\n getNextRelationshipIndex,\n getReferencedMedia,\n nextNumericId,\n replaceImagePlaceholders,\n strFromU8,\n toJson,\n unzipSync,\n zipAndConvert,\n} from \"@office-open/core\";\nimport type {\n BasePatchOptions,\n CorePropertiesOptions,\n OutputByType,\n OutputType,\n} from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport { OOXML_XML_DECLARATION } from \"@office-open/xml\";\nimport { escapeXml, stringify, parse } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { commentsDesc } from \"@parts/comments\";\nimport { DocumentAttributeNamespaces } from \"@parts/document\";\nimport {\n stringifyChildDispatch,\n stringifyParagraphInline,\n stringifyRunInline,\n} from \"@parts/inline\";\nimport type { ParagraphChild } from \"@parts/paragraph/paragraph\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\nimport type { RunOptions } from \"@parts/paragraph/run/run\";\nimport { tableDesc } from \"@parts/table/descriptor\";\nimport type { TableOptions } from \"@parts/table/table\";\nimport { Media } from \"@shared/media\";\nimport type { MediaData } from \"@shared/media/data\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { BodyContext } from \"../context\";\nimport type { ViewWrapper } from \"../context\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\nconst COMMENTS_REL_TYPE =\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments\";\nconst COMMENTS_CONTENT_TYPE =\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml\";\n\n/** A comment injected by patch — same as CommentOptions but without an id\n * (the patch assigns continuation ids). */\nexport type PatchComment = Omit<CommentOptions, \"id\">;\n\n/** A comment request resolved to an id and an anchor (paragraph index or placeholder). */\ninterface AssignedComment {\n id: number;\n anchor: { kind: \"paragraph\"; index: number } | { kind: \"placeholder\"; key: string };\n options: PatchComment;\n}\n\n/**\n * Document patching module for modifying existing .docx files.\n *\n * Uses compile-path stringifiers (zero class instantiation) to serialize\n * patch content — no Formatter, no XmlComponent instances.\n *\n * @module\n */\n\n// ── Patch content stringification ──\n\n/**\n * Lightweight BodyContext adapter for patch serialization.\n * Captures hyperlink and image relationships for post-processing.\n */\nfunction createPatchContext(\n file: { media: Media<MediaData> },\n hyperlinkSink: Array<{ id: string; link: string }>,\n): BodyContext {\n return {\n fileData: file as unknown as BodyContext[\"fileData\"],\n file: file as unknown as BodyContext[\"file\"],\n viewWrapper: {\n relationships: {\n addRelationship: (linkId: string, _type: string, target: string, _mode?: string) => {\n hyperlinkSink.push({ id: linkId, link: target });\n },\n relationshipCount: 0,\n },\n } as unknown as BodyContext[\"viewWrapper\"],\n stringifyChild: () => \"\",\n addRelationship: () => \"\",\n addMedia: () => \"\",\n addHyperlink: () => {},\n };\n}\n\n/**\n * Serialize a patch child (SectionChild / ParagraphChild / string) into XML\n * elements via the compile-path stringifiers. Shared by the placeholder\n * replacer and body-level `append`. Relies on the module-level\n * {@link currentPatchCtx} for relationship/media sinks.\n */\nconst formatChildElement = (child: unknown): Element[] => {\n let xmlStr: string;\n\n if (typeof child === \"string\") {\n // Plain string → simple run\n xmlStr = `<w:r><w:t xml:space=\"preserve\">${escapeXml(child)}</w:t></w:r>`;\n } else if (typeof child === \"object\" && child !== null) {\n const obj = child as Record<string, unknown>;\n // SectionChild level (paragraph / table) — for DOCUMENT patches and append\n if (\"paragraph\" in obj) {\n xmlStr = stringifyParagraphInline(obj.paragraph as ParagraphOptions, currentPatchCtx);\n } else if (\"table\" in obj) {\n xmlStr = tableDesc.stringify(obj.table as TableOptions, currentPatchCtx) ?? \"\";\n } else {\n // ParagraphChild level — for PARAGRAPH patches\n // Try compile-path JSON child dispatch first\n const jr = stringifyChildDispatch(child as ParagraphChild, currentPatchCtx);\n if (jr !== undefined) {\n xmlStr = Array.isArray(jr) ? jr.join(\"\") : jr;\n } else {\n // RunOptions (plain objects with text/children/bold/etc.)\n xmlStr = stringifyRunInline(child as RunOptions, currentPatchCtx);\n }\n }\n } else {\n xmlStr = \"<w:r/>\";\n }\n\n const jsonObj = parse(xmlStr, { captureSpacesBetweenElements: true });\n const rootEl = jsonObj.elements?.[0];\n // parse yields a single root element for a well-formed fragment\n return rootEl ? [rootEl] : [];\n};\n\nconst docxReplacer = createReplacer({\n ns: DOCX_NS,\n formatChild: formatChildElement,\n});\n\n/**\n * Splice block-level children into `<w:body>` before the trailing `<w:sectPr>`\n * (the final section properties). If the body has no trailing sectPr, append at\n * the end. Reuses {@link formatChildElement} so the same serialization and\n * relationship/media sinks apply as placeholder patches.\n */\nconst appendToBody = (root: Element, children: SectionChild[]): void => {\n const docEl = root.elements?.find((e) => e.name === \"w:document\");\n const body = docEl?.elements?.find((e) => e.name === \"w:body\");\n if (!body) return;\n const els = body.elements ?? (body.elements = []);\n const newEls: Element[] = [];\n for (const child of children) {\n newEls.push(...formatChildElement(child));\n }\n // Insert before the trailing <w:sectPr>; otherwise at the end.\n let insertAt = els.length;\n for (let i = els.length - 1; i >= 0; i--) {\n const el = els[i];\n if (el && el.name === \"w:sectPr\") {\n insertAt = i;\n break;\n }\n }\n els.splice(insertAt, 0, ...newEls);\n};\n\n/** Current patch context — set per file in the main loop. */\nlet currentPatchCtx: BodyContext;\n\n/**\n * A patch operation: replace a placeholder with either inline run-level\n * content (`type: \"paragraph\"`) or block-level content (`type: \"document\"`).\n *\n * The `type` is a bare string literal (no PatchType enum) — the core\n * replacer already discriminates on `patch.type`.\n */\nexport type Patch =\n | { type: \"paragraph\"; children: (string | RunOptions | ParagraphChild)[] }\n | { type: \"document\"; children: SectionChild[] };\n\ninterface ImageRelationshipAddition {\n key: string;\n mediaDatas: { fileName: string }[];\n}\n\ninterface HyperlinkRelationshipAddition {\n key: string;\n hyperlink: { id: string; link: string };\n}\n\nexport interface PatchDocumentOptions<\n T extends OutputType = OutputType,\n> extends BasePatchOptions<T> {\n /** Placeholder substitutions: `{{key}}` (per delimiters) → patch content. */\n placeholders?: Readonly<Record<string, Patch>>;\n /** Literal find/replace: the find string → patch content (no delimiters added). */\n findReplace?: Readonly<Record<string, Patch>>;\n /** Core-properties metadata override (merged over the existing docProps/core.xml). */\n coreProperties?: Partial<CorePropertiesOptions>;\n keepOriginalStyles?: boolean;\n recursive?: boolean;\n /** Block-level content appended to the document body, before the final section break. */\n append?: SectionChild[];\n /**\n * Comments to inject. `paragraphs` anchors a comment to the Nth body paragraph\n * (0-based, wraps the whole paragraph); `placeholders` anchors to the run\n * containing a {{key}} (wrapped before placeholder substitution). Ids are\n * continued from any existing word/comments.xml; entries are merged in.\n */\n comments?: {\n paragraphs?: Readonly<Record<number, PatchComment[]>>;\n placeholders?: Readonly<Record<string, PatchComment[]>>;\n };\n}\n\nconst UTF16LE = new Uint8Array([0xff, 0xfe]);\nconst UTF16BE = new Uint8Array([0xfe, 0xff]);\n\nconst compareByteArrays = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Patches an existing .docx document by replacing placeholders with new content.\n *\n * @publicApi\n */\nexport const patchDocument = async <T extends OutputType = OutputType>({\n outputType,\n data,\n placeholders,\n findReplace,\n coreProperties,\n append,\n comments,\n keepOriginalStyles = true,\n placeholderDelimiters = { end: \"}}\", start: \"{{\" } as const,\n recursive = true,\n}: PatchDocumentOptions<T>): Promise<OutputByType[T]> => {\n const zipContent = unzipSync(toUint8Array(data));\n const contexts = new Map<string, BodyContext>();\n const media = new Media<MediaData>();\n const file = { media } as BodyContext[\"file\"];\n\n // Resolve comment ids by continuation from any existing word/comments.xml.\n const assignedComments = buildAssignedComments(zipContent, comments);\n\n const map = new Map<string, Element>();\n\n const imageRelationshipAdditions: ImageRelationshipAddition[] = [];\n const hyperlinkRelationshipAdditions: HyperlinkRelationshipAddition[] = [];\n let hasMedia = false;\n\n const binaryContentMap = new Map<string, Uint8Array>();\n\n for (const [key, value] of Object.entries(zipContent)) {\n const startBytes = value.slice(0, 2);\n if (compareByteArrays(startBytes, UTF16LE) || compareByteArrays(startBytes, UTF16BE)) {\n binaryContentMap.set(key, value);\n continue;\n }\n\n if (!key.endsWith(\".xml\") && !key.endsWith(\".rels\")) {\n binaryContentMap.set(key, value);\n continue;\n }\n\n const json = toJson(strFromU8(value));\n\n if (key === \"word/document.xml\") {\n const document = json.elements?.find((i) => i.name === \"w:document\");\n if (document && document.attributes) {\n for (const ns of [\"mc\", \"wp\", \"r\", \"w15\", \"m\"] as const) {\n document.attributes[`xmlns:${ns}`] = DocumentAttributeNamespaces[ns];\n }\n document.attributes[\"mc:Ignorable\"] =\n `${document.attributes[\"mc:Ignorable\"] || \"\"} w15`.trim();\n }\n }\n\n if (key.startsWith(\"word/\") && !key.endsWith(\".xml.rels\")) {\n const hyperlinkSink: Array<{ id: string; link: string }> = [];\n\n const context: BodyContext = {\n fileData: file,\n file,\n viewWrapper: {\n relationships: {\n addRelationship: (\n linkId: string,\n _: string,\n target: string,\n __: (typeof TargetModeType)[keyof typeof TargetModeType],\n ) => {\n hyperlinkRelationshipAdditions.push({\n hyperlink: {\n id: linkId,\n link: target,\n },\n key,\n });\n },\n },\n } as unknown as ViewWrapper,\n stringifyChild: () => \"\",\n addRelationship: () => \"\",\n addMedia: () => \"\",\n addHyperlink: () => {},\n };\n contexts.set(key, context);\n\n if (!placeholderDelimiters?.start.trim() || !placeholderDelimiters?.end.trim()) {\n throw new Error(\"Both start and end delimiters must be non-empty strings.\");\n }\n\n const { start, end } = placeholderDelimiters;\n\n // Create compile-path context for stringifying patch children\n const patchCtx = createPatchContext(file, hyperlinkSink);\n currentPatchCtx = patchCtx;\n\n // Anchor placeholder comments BEFORE substitution, wrapping the {{key}} run.\n if (key === \"word/document.xml\") {\n for (const ac of assignedComments) {\n if (ac.anchor.kind === \"placeholder\") {\n wrapPlaceholderComment(json, `${start}${ac.anchor.key}${end}`, ac.id);\n }\n }\n }\n\n // Build (find-text → patch) entries. Placeholders wrap the key in\n // delimiters; findReplace uses the literal key. Both share one engine.\n const entries: Array<{ find: string; patch: Patch }> = [];\n if (placeholders) {\n for (const [key, value] of Object.entries(placeholders)) {\n entries.push({ find: `${start}${key}${end}`, patch: value });\n }\n }\n if (findReplace) {\n for (const [key, value] of Object.entries(findReplace)) {\n entries.push({ find: key, patch: value });\n }\n }\n\n for (const { find: patchText, patch: patchValue } of entries) {\n while (true) {\n const { didFindOccurrence } = docxReplacer({\n context,\n json,\n keepOriginalStyles,\n patch: patchValue,\n patchText,\n });\n if (!recursive || !didFindOccurrence) {\n break;\n }\n }\n }\n\n // Append block-level children to the document body before the final sectPr.\n if (append && append.length > 0 && key === \"word/document.xml\") {\n appendToBody(json, append);\n }\n\n // Anchor paragraph comments AFTER body edits, wrapping the Nth paragraph.\n if (key === \"word/document.xml\") {\n for (const ac of assignedComments) {\n if (ac.anchor.kind === \"paragraph\") {\n wrapParagraphComment(json, ac.anchor.index, ac.id);\n }\n }\n }\n\n // Flush hyperlink relationships captured by the compile-path context\n for (const hl of hyperlinkSink) {\n hyperlinkRelationshipAdditions.push({\n hyperlink: { id: hl.id, link: hl.link },\n key,\n });\n }\n\n const mediaDatas = getReferencedMedia(JSON.stringify(json), media.array);\n if (mediaDatas.length > 0) {\n hasMedia = true;\n imageRelationshipAdditions.push({\n key,\n mediaDatas,\n });\n }\n }\n\n map.set(key, json);\n }\n\n // Merge injected comments into word/comments.xml + wire rels + content types.\n if (assignedComments.length > 0) {\n mergeCommentsPart(map, assignedComments, file);\n }\n\n for (const { key, mediaDatas } of imageRelationshipAdditions) {\n const relationshipKey = `word/_rels/${key.split(\"/\").pop()}.rels`;\n const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();\n map.set(relationshipKey, relationshipsJson);\n\n const index = getNextRelationshipIndex(relationshipsJson);\n const newJson = replaceImagePlaceholders(\n JSON.stringify(map.get(key)),\n mediaDatas,\n index,\n \"plain\",\n );\n map.set(key, JSON.parse(newJson) as Element);\n\n for (const [i, media] of mediaDatas.entries()) {\n const { fileName } = media;\n appendRelationship(\n relationshipsJson,\n index + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${fileName}`,\n );\n }\n }\n\n for (const { key, hyperlink } of hyperlinkRelationshipAdditions) {\n const relationshipKey = `word/_rels/${key.split(\"/\").pop()}.rels`;\n\n const relationshipsJson = map.get(relationshipKey) ?? createRelationshipFile();\n map.set(relationshipKey, relationshipsJson);\n\n appendRelationship(\n relationshipsJson,\n hyperlink.id,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\",\n hyperlink.link,\n TargetModeType.EXTERNAL,\n );\n }\n\n if (hasMedia) {\n const contentTypesJson = map.get(\"[Content_Types].xml\");\n\n if (!contentTypesJson) {\n throw new Error(\"Could not find content types file\");\n }\n\n // Cover every media extension the patch path can register (RegularMediaData\n // includes emf/wmf/tif/ico), not just a hand-picked subset — a patched-in\n // image needs its <Default> even when the source package lacks one.\n for (const [ext, mime] of Object.entries(IMAGE_MEDIA_CONTENT_TYPES)) {\n appendContentType(contentTypesJson, mime, ext);\n }\n }\n\n const files: Record<string, Uint8Array> = {};\n\n for (const [key, value] of map) {\n files[key] =\n key === \"docProps/core.xml\" && coreProperties\n ? encoder.encode(OOXML_XML_DECLARATION + applyCorePropertiesOverride(value, coreProperties))\n : encoder.encode(stringify(value));\n }\n\n for (const [key, value] of binaryContentMap) {\n files[key] = value;\n }\n\n for (const { data: mediaData, fileName } of media.array) {\n files[`word/media/${fileName}`] =\n mediaData instanceof Uint8Array ? mediaData : new Uint8Array(mediaData);\n }\n\n return await zipAndConvert(files, outputType, OoxmlMimeType.DOCX);\n};\n\nconst createRelationshipFile = (): Element => ({\n declaration: {\n attributes: {\n encoding: \"UTF-8\",\n standalone: \"yes\",\n version: \"1.0\",\n },\n },\n elements: [\n {\n attributes: {\n xmlns: \"http://schemas.openxmlformats.org/package/2006/relationships\",\n },\n elements: [],\n name: \"Relationships\",\n type: \"element\",\n },\n ],\n});\n\n/** Build a bare OOXML element node with attributes and no children. */\nfunction makeElement(name: string, attributes: Record<string, string> = {}): Element {\n return { type: \"element\", name, attributes, elements: [] };\n}\n\n/** A `<w:r>` carrying a `<w:commentReference>` (CommentReference run style). */\nfunction commentReferenceRun(id: number): Element {\n // parse yields a single root <w:r> for this well-formed fragment\n return parse(\n `<w:r><w:rPr><w:rStyle w:val=\"CommentReference\"/></w:rPr><w:commentReference w:id=\"${id}\"/></w:r>`,\n ).elements![0]!;\n}\n\n/** Next continuation id for an appended `<w:comment>` (-1 seed → 0 when none). */\nfunction nextCommentId(commentsPart: Element | undefined): number {\n const root = commentsPart?.elements?.find((e) => e.name === \"w:comments\");\n return nextNumericId(root, \"w:comment\", \"w:id\", -1);\n}\n\n/** Assign continuation ids to every requested comment anchor. */\nfunction buildAssignedComments(\n zipContent: Record<string, Uint8Array>,\n comments: PatchDocumentOptions[\"comments\"],\n): AssignedComment[] {\n if (!comments) return [];\n const raw = zipContent[\"word/comments.xml\"];\n let nextId = raw ? nextCommentId(toJson(strFromU8(raw))) : 0;\n const assigned: AssignedComment[] = [];\n if (comments.placeholders) {\n for (const [key, list] of Object.entries(comments.placeholders)) {\n for (const options of list) {\n assigned.push({ id: nextId++, anchor: { kind: \"placeholder\", key }, options });\n }\n }\n }\n if (comments.paragraphs) {\n for (const [indexStr, list] of Object.entries(comments.paragraphs)) {\n const index = Number(indexStr);\n for (const options of list) {\n assigned.push({ id: nextId++, anchor: { kind: \"paragraph\", index }, options });\n }\n }\n }\n return assigned;\n}\n\n/** Wrap the Nth body paragraph with comment range markers + a reference run. */\nfunction wrapParagraphComment(json: Element, index: number, commentId: number): void {\n const body = json.elements\n ?.find((e) => e.name === \"w:document\")\n ?.elements?.find((e) => e.name === \"w:body\");\n if (!body) return;\n const paragraphs = (body.elements ?? []).filter((e) => e.name === \"w:p\");\n const target = paragraphs[index];\n if (!target) {\n throw new Error(`patchDocument: no paragraph at index ${index} to comment`);\n }\n const els = target.elements ?? (target.elements = []);\n const start = makeElement(\"w:commentRangeStart\", { \"w:id\": String(commentId) });\n const end = makeElement(\"w:commentRangeEnd\", { \"w:id\": String(commentId) });\n // Insert start after a leading <w:pPr> (or at the head); end + ref at the tail.\n const first = els[0];\n const insertAt = first && first.name === \"w:pPr\" ? 1 : 0;\n els.splice(insertAt, 0, start);\n els.push(end, commentReferenceRun(commentId));\n}\n\n/** Wrap the first run whose `<w:t>` contains the placeholder with comment markers. */\nfunction wrapPlaceholderComment(json: Element, placeholder: string, commentId: number): void {\n const body = json.elements\n ?.find((e) => e.name === \"w:document\")\n ?.elements?.find((e) => e.name === \"w:body\");\n if (!body) return;\n for (const p of body.elements ?? []) {\n if (p.name !== \"w:p\") continue;\n const els = p.elements ?? [];\n for (const [i, el] of els.entries()) {\n if (el.name !== \"w:r\") continue;\n const t = (el.elements ?? []).find((e) => e.name === \"w:t\");\n const text = t?.elements?.[0]?.text;\n if (typeof text === \"string\" && text.includes(placeholder)) {\n els.splice(i, 0, makeElement(\"w:commentRangeStart\", { \"w:id\": String(commentId) }));\n els.splice(\n i + 2,\n 0,\n makeElement(\"w:commentRangeEnd\", { \"w:id\": String(commentId) }),\n commentReferenceRun(commentId),\n );\n return; // only the first occurrence\n }\n }\n }\n}\n\n/**\n * Merge assigned comments into word/comments.xml (appending to an existing part\n * or creating one) and wire document.xml.rels + content types when newly added.\n */\nfunction mergeCommentsPart(\n map: Map<string, Element>,\n assigned: AssignedComment[],\n file: { media: Media<MediaData> },\n): void {\n const newOpts: CommentOptions[] = assigned.map((ac) => ({ id: ac.id, ...ac.options }));\n const ctx = createPatchContext(file, []);\n const newXml = commentsDesc.stringify({ children: newOpts }, ctx) ?? \"\";\n const existingEl = map.get(\"word/comments.xml\");\n const wasNew = !existingEl;\n\n if (existingEl) {\n // Append new <w:comment> elements to the existing <w:comments> root.\n const existingRoot = existingEl.elements?.find((e) => e.name === \"w:comments\");\n const newRoot = parse(newXml).elements?.find((e) => e.name === \"w:comments\");\n existingRoot?.elements?.push(...(newRoot?.elements ?? []));\n } else {\n map.set(\n \"word/comments.xml\",\n toJson(`<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>${newXml}`),\n );\n }\n\n if (wasNew) {\n const relsKey = \"word/_rels/document.xml.rels\";\n const relsJson = map.get(relsKey) ?? createRelationshipFile();\n map.set(relsKey, relsJson);\n appendRelationship(\n relsJson,\n getNextRelationshipIndex(relsJson),\n COMMENTS_REL_TYPE,\n \"comments.xml\",\n );\n }\n\n // Content types — ensure the comments Override exists (deduped). An existing\n // comments part normally already declares it, but defend against incomplete templates.\n const contentTypes = map.get(\"[Content_Types].xml\");\n if (contentTypes) {\n appendOverride(contentTypes, \"/word/comments.xml\", COMMENTS_CONTENT_TYPE);\n }\n}\n","/**\n * Patch detector for discovering placeholders in document templates.\n *\n * @module\n */\nimport { DOCX_NS, createTraverser, strFromU8, toJson, unzipSync } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport type { DataType } from \"@office-open/core\";\n\n/**\n * Options for patch detection.\n *\n * @property data - The document template to scan for placeholders\n */\ninterface PatchDetectorOptions {\n data: DataType;\n}\n\n/**\n * Detects all placeholders present in a document template.\n *\n * Scans through all XML content in a .docx file to find placeholder text\n * enclosed in delimiters (default: {{placeholder}}). This is useful for\n * discovering what patches a template expects before performing replacement.\n *\n * @param options - Patch detector configuration\n * @returns Array of placeholder keys found in the document\n *\n * @example\n * ```typescript\n * const placeholders = await patchDetector({ data: templateBuffer });\n * // Returns: [\"name\", \"date\", \"address\"] if template contains {{name}}, {{date}}, {{address}}\n *\n * // Use detected placeholders to create patches\n * const patches = {};\n * for (const key of placeholders) {\n * patches[key] = {\n * type: \"paragraph\",\n * children: [new TextRun(getUserData(key))],\n * };\n * });\n * ```\n */\nexport const patchDetector = async ({ data }: PatchDetectorOptions): Promise<string[]> => {\n const zipContent = unzipSync(toUint8Array(data));\n const patches = new Set<string>();\n\n for (const [key, value] of Object.entries(zipContent)) {\n if (!key.endsWith(\".xml\") && !key.endsWith(\".rels\")) {\n continue;\n }\n if (key.startsWith(\"word/\") && !key.endsWith(\".xml.rels\")) {\n const json = toJson(strFromU8(value));\n const { traverse } = createTraverser(DOCX_NS);\n for (const p of traverse(json)) {\n for (const patch of findPatchKeys(p.text)) {\n patches.add(patch);\n }\n }\n }\n }\n return [...patches];\n};\n\n/**\n * Extracts placeholder keys from text using regex pattern.\n *\n * @param text - Text to search for placeholders\n * @returns Array of placeholder keys (without delimiters)\n */\nconst findPatchKeys = (text: string): string[] => {\n const pattern = /(?<=\\{\\{).+?(?=\\}\\})/gs;\n return text.match(pattern) ?? [];\n};\n","/**\n * External styles factory module for WordprocessingML documents.\n *\n * Parses styles from external XML and returns raw XML strings.\n * No XmlComponent dependency.\n *\n * Reference: http://officeopenxml.com/WPstyles.php\n *\n * @module\n */\nimport { stringify, parse } from \"@office-open/xml\";\nimport type { Element as XMLElement } from \"@office-open/xml\";\n\nimport type { StylesOptions } from \"./styles\";\n\n/**\n * Factory for creating styles from external XML sources.\n *\n * Parses styles from XML (typically from a styles.xml file)\n * and returns raw XML strings for each style element.\n */\nexport class ExternalStylesFactory {\n /**\n * Creates new Styles based on the given XML data.\n *\n * Parses the styles XML and converts each child to a raw XML string.\n */\n public newInstance(xmlData: string): StylesOptions {\n const xmlObj = parse(xmlData, { compact: false }) as XMLElement;\n\n let stylesXmlElement: XMLElement | undefined;\n for (const xmlElm of xmlObj.elements || []) {\n if (xmlElm.name === \"w:styles\") {\n stylesXmlElement = xmlElm;\n }\n }\n\n if (stylesXmlElement === undefined) {\n return { importedStyles: [], initialAttributes: {} };\n }\n\n const stylesElements = stylesXmlElement.elements || [];\n\n return {\n importedStyles: stylesElements.map((childElm) => ({\n _raw: stringify({ elements: [childElm] }),\n })),\n initialAttributes: (stylesXmlElement.attributes as Record<string, string>) ?? {},\n };\n }\n}\n","/**\n * DOCX compilation context.\n *\n * DocxWriteContext holds all mutable state needed during document compilation.\n * generateDocument() creates a DocxWriteContext internally.\n *\n * @module\n */\n\nimport { Relationships, buildRootRelationships } from \"@office-open/core\";\nimport { ChartCollection } from \"@office-open/core/chart\";\nimport type { HyperlinkTarget, ReadContext, WriteContext } from \"@office-open/core/descriptor\";\nimport { SmartArtCollection } from \"@office-open/core/smartart\";\nimport type { Element } from \"@office-open/xml\";\nimport { AltChunkCollection } from \"@parts/alt-chunk/alt-chunk-collection\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport type { SectionPropertiesOptions } from \"@parts/document/body/section-properties/section-properties\";\nimport type { EndnoteSeparator } from \"@parts/endnotes/descriptor\";\nimport { FontWrapper } from \"@parts/fonts/font-wrapper\";\nimport type { FootnoteSeparator } from \"@parts/footnotes/descriptor\";\nimport type { GlossaryDocumentOptions } from \"@parts/glossary-document\";\nimport type { HeaderFooterEntry } from \"@parts/header-footer\";\nimport { Numbering } from \"@parts/numbering\";\nimport type { ParagraphOptions } from \"@parts/paragraph/paragraph\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\nimport type { SettingsOptions } from \"@parts/settings/settings\";\nimport { Styles, extractStyleId } from \"@parts/styles\";\nimport { ExternalStylesFactory } from \"@parts/styles/external-styles-factory\";\nimport { DefaultStylesFactory, stringifyDocDefaults } from \"@parts/styles/factory\";\nimport { SubDocCollection } from \"@parts/sub-doc/sub-doc-collection\";\nimport type { WebSettingsOptions } from \"@parts/web-settings\";\nimport { EmbeddingCollection } from \"@shared/embeddings/embeddings\";\nimport { Media } from \"@shared/media\";\nimport type { MediaData } from \"@shared/media/data\";\nimport type { SectionOptions } from \"@shared/section\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { DocxDocument } from \"./parse\";\n\n/** User styles override factory defaults with the same styleId; keep the rest. */\nfunction mergeById<T extends { id: string }>(\n factoryStyles: T[] | undefined,\n userStyles: T[] | undefined,\n): T[] {\n const factory = factoryStyles ?? [];\n if (!userStyles || userStyles.length === 0) return factory;\n const userIds = new Set(userStyles.map((s) => s.id));\n return [...factory.filter((s) => !userIds.has(s.id)), ...userStyles];\n}\n\n/**\n * Highest comment id in an explicit comments list, or -1 when there are none.\n * Seeds the comment id allocator so auto-allocated ids never collide with ids\n * the caller already assigned (e.g. round-tripped from an existing document).\n */\nfunction maxCommentId(comments: readonly CommentOptions[] | undefined): number {\n let max = -1;\n if (comments) {\n for (const c of comments) {\n if (c.id > max) max = c.id;\n }\n }\n return max;\n}\n\n/** Narrows an object to a `{ id: number }` marker without an `as` cast. */\nfunction isNumericIdMarker(value: unknown): value is { id: number } {\n return (\n typeof value === \"object\" && value !== null && \"id\" in value && typeof value.id === \"number\"\n );\n}\n\n/**\n * Single preflight scan of the full Options tree. Collects everything that\n * must be known before stringify starts: the max explicit markup ids (seeding\n * the `{ bookmark }` / `{ moveFrom }` / `{ moveTo }` sugar allocators so they\n * never collide with caller-assigned ids) and whether any `{ comment }` sugar\n * appears — the document→comments relationship must exist whenever\n * comments.xml will be generated, and sugar entries are only registered\n * during stringify, after the constructor wires relationships. Every\n * `{ comment }` always stringifies, so the prediction matches the entries\n * actually registered.\n */\ninterface DocumentTreeScan {\n maxRangeId: number;\n maxMoveRunId: number;\n hasCommentSugar: boolean;\n}\n\nfunction scanDocumentTree(value: unknown, acc: DocumentTreeScan): void {\n if (value === null || value === undefined || typeof value !== \"object\") return;\n if (value instanceof Uint8Array || value instanceof Date) return;\n if (Array.isArray(value)) {\n for (const item of value) scanDocumentTree(item, acc);\n return;\n }\n const obj = value as Record<string, unknown>;\n const rangeMarker = obj.bookmarkStart ?? obj.moveFromRangeStart ?? obj.moveToRangeStart;\n if (isNumericIdMarker(rangeMarker) && rangeMarker.id > acc.maxRangeId)\n acc.maxRangeId = rangeMarker.id;\n const moveRun = obj.movedFrom ?? obj.movedTo;\n if (isNumericIdMarker(moveRun) && moveRun.id > acc.maxMoveRunId) acc.maxMoveRunId = moveRun.id;\n if (typeof obj.comment === \"object\" && obj.comment !== null) acc.hasCommentSugar = true;\n // for...in walks own enumerable keys without allocating a keys array (options\n // trees are JSON literals / class instances whose methods are non-enumerable).\n for (const key in obj) scanDocumentTree(obj[key], acc);\n}\n\n/** Interface for document view wrappers — provides relationships access. */\nexport interface ViewWrapper {\n relationships: Relationships;\n}\n\n// ── BodyContext ──\n\n/**\n * Context for body-level stringification.\n *\n * Pure JSON pipeline context — extends WriteContext for descriptor compatibility.\n * No dependency on XmlComponent Context (compile/ uses zero toXml calls).\n */\nexport interface BodyContext extends WriteContext {\n /** The root write context with all mutable document state. */\n fileData: DocxWriteContext;\n /** Alias for fileData — some descriptor internals access context.file. */\n file: DocxWriteContext;\n /** Current view wrapper for relationship access. */\n viewWrapper: { relationships: Relationships };\n /**\n * Stringify a body-level child element — injected to break circular imports.\n * Bound to its owning context via closure at injection time, so callers pass\n * only the child.\n */\n stringifyChild: (child: SectionChild) => string;\n}\n\n// ── DocxWriteContext ──\n\nexport class DocxWriteContext implements WriteContext {\n private _currentRelationshipId = 1;\n\n // --- Accessed by XmlComponent via context.file.* during toXml() ---\n declare public document: { relationships: Relationships };\n declare public numbering: Numbering;\n declare public media: Media<MediaData>;\n declare public charts: ChartCollection;\n declare public smartArts: SmartArtCollection;\n declare public embeddings: EmbeddingCollection;\n declare public altChunks: AltChunkCollection;\n declare public subDocs: SubDocCollection;\n declare public comments: {\n relationships: Relationships;\n /** Comment entries registered by `{ comment }` sugar children during stringify. */\n entries: CommentOptions[];\n /** Next auto-allocated comment id (seeded above any explicit comment id). */\n nextId: number;\n };\n declare public markupIds: {\n /** Next id for bookmark + move-range markers (CT_MarkupRange) — shared, like Word. */\n rangeNext: number;\n /** Next id for movedFrom/movedTo runs (CT_TrackChange). */\n moveRunNext: number;\n };\n declare public footNotes: {\n relationships: Relationships;\n notes: Map<number, (ParagraphOptions | string)[]>;\n separator?: FootnoteSeparator;\n continuationSeparator?: FootnoteSeparator;\n };\n declare public endnotes: {\n relationships: Relationships;\n notes: Map<number, (ParagraphOptions | string)[]>;\n separator?: EndnoteSeparator;\n continuationSeparator?: EndnoteSeparator;\n };\n\n // --- Additional state used by the compiler ---\n declare public fileRelationships: Relationships;\n declare public _settingsOptions: SettingsOptions;\n declare public styles: Styles;\n declare public fontTable: FontWrapper;\n declare public glossaryOptions: GlossaryDocumentOptions | undefined;\n declare public webSettings: WebSettingsOptions | undefined;\n\n // --- Section properties (one per section, raw options for descriptor pipeline) ---\n private _sectionProperties: SectionPropertiesOptions[] = [];\n public get sectionProperties(): readonly SectionPropertiesOptions[] {\n return this._sectionProperties;\n }\n\n // Footnotes/endnotes are optional parts. Fresh compile always emits them\n // (Word ships a separators-only file); round-trip emits them only when the\n // source package declared the part — otherwise emitting the part + document\n // relationship without a [Content_Types] Override is an OPC violation that\n // makes Word reject the package as unreadable content.\n private readonly _hasFootnotes: boolean;\n private readonly _hasEndnotes: boolean;\n private readonly _hasNumbering: boolean;\n public get hasFootnotes(): boolean {\n return this._hasFootnotes;\n }\n public get hasEndnotes(): boolean {\n return this._hasEndnotes;\n }\n public get hasNumbering(): boolean {\n return this._hasNumbering;\n }\n\n // --- WriteContext interface (core descriptor pipeline) ---\n\n public addRelationship(_type: string, _target: string, _mode?: string): string {\n const id = this._currentRelationshipId++;\n return `rId${id}`;\n }\n\n public addMedia(data: Uint8Array, type: string): string {\n const entry = this.media.addMedia(\n data,\n type,\n (fileName) =>\n ({\n data,\n fileName,\n type,\n transformation: { pixels: { x: 0, y: 0 }, emus: { x: 0, y: 0 } },\n }) as MediaData,\n );\n return `{${entry.fileName}}`;\n }\n\n public addHyperlink(_key: string, _target: HyperlinkTarget): void {\n // DrawingML text hyperlinks are not emitted by DOCX; text boxes use w:hyperlink.\n }\n\n // --- Internal tracking ---\n private _headers: HeaderFooterEntry[] = [];\n private _footers: HeaderFooterEntry[] = [];\n\n // --- Original input preserved for descriptor usage ---\n declare public _options: DocumentOptions;\n\n /** Preflight result: does the body tree carry any `{ comment }` sugar? */\n declare private _hasCommentSugar: boolean;\n\n constructor(options: DocumentOptions) {\n this._options = options;\n\n this.numbering = new Numbering(options.numbering ? options.numbering : { config: [] });\n\n this.comments = {\n relationships: new Relationships(),\n entries: [],\n nextId: maxCommentId(options.comments?.children) + 1,\n };\n const scan: DocumentTreeScan = { maxRangeId: -1, maxMoveRunId: -1, hasCommentSugar: false };\n scanDocumentTree(options.sections, scan);\n this._hasCommentSugar = scan.hasCommentSugar;\n this.markupIds = {\n rangeNext: scan.maxRangeId + 1,\n moveRunNext: scan.maxMoveRunId + 1,\n };\n this.fileRelationships = buildRootRelationships(\"word/document.xml\", true);\n this.footNotes = { relationships: new Relationships(), notes: new Map() };\n this.endnotes = { relationships: new Relationships(), notes: new Map() };\n this.document = { relationships: new Relationships() };\n this._settingsOptions = {\n compatibility: options.compatibility,\n defaultTabStop: options.defaultTabStop,\n evenAndOddHeaders: options.evenAndOddHeaderAndFooters || undefined,\n characterSpacingControl: options.characterSpacingControl,\n hyphenation: {\n autoHyphenation: options.hyphenation?.autoHyphenation,\n consecutiveHyphenLimit: options.hyphenation?.consecutiveHyphenLimit,\n doNotHyphenateCaps: options.hyphenation?.doNotHyphenateCaps,\n hyphenationZone: options.hyphenation?.hyphenationZone,\n },\n trackRevisions: options.features?.trackRevisions,\n updateFields: options.features?.updateFields,\n documentProtection: options.features?.documentProtection,\n view: options.view,\n zoom: options.zoom,\n writeProtection: options.writeProtection,\n displayBackgroundShape:\n options.displayBackgroundShape ?? (options.background?.image ? true : undefined),\n embedTrueTypeFonts: options.embedTrueTypeFonts,\n embedSystemFonts: options.embedSystemFonts,\n saveSubsetFonts: options.saveSubsetFonts,\n docVars: options.docVars,\n colorSchemeMapping: options.colorSchemeMapping,\n mailMerge: options.mailMerge,\n ...options.settings,\n };\n\n this.media = new Media<MediaData>();\n this.charts = new ChartCollection();\n this.smartArts = new SmartArtCollection();\n this.embeddings = new EmbeddingCollection();\n this.altChunks = new AltChunkCollection();\n this.subDocs = new SubDocCollection();\n\n if (options.externalStyles !== undefined) {\n const externalStyles = new ExternalStylesFactory().newInstance(options.externalStyles);\n const defaultStyles = new DefaultStylesFactory().newInstance(options.styles?.default ?? {});\n // External (user-provided full styles.xml) wins; factory builtins fill\n // any gaps. Drop factory builtins whose styleId the external XML already\n // defines (no duplicate styleId). docDefaults/latentStyles come from the\n // external XML — the factory's are not mixed in.\n const externalIds = new Set<string>();\n for (const s of externalStyles.importedStyles ?? []) {\n const id = extractStyleId(s._raw);\n if (id) externalIds.add(id);\n }\n const notInExternal = <T extends { id: string }>(arr: T[] | undefined) =>\n (arr ?? []).filter((s) => !externalIds.has(s.id));\n this.styles = new Styles({\n importedStyles: externalStyles.importedStyles,\n initialAttributes: externalStyles.initialAttributes ?? defaultStyles.initialAttributes,\n paragraphStyles: notInExternal(defaultStyles.paragraphStyles),\n characterStyles: notInExternal(defaultStyles.characterStyles),\n tableStyles: notInExternal(defaultStyles.tableStyles),\n numberingStyles: notInExternal(defaultStyles.numberingStyles),\n });\n } else if (options.styles) {\n const s = options.styles;\n if (s.roundTripped) {\n // Round-trip origin (parseStyleDefinitions): structured default.document\n // wins so the visual editor can edit default run/paragraph properties\n // and have them take effect on generate. docDefaultsXml verbatim is only\n // a fallback for older parses without default.document or a completely\n // empty <w:docDefaults/>. No factory builtin rebuild — parsed builtins\n // already carry the source document's customizations.\n const f = new DefaultStylesFactory().newInstance({});\n const docDefaults =\n s.default?.document !== undefined\n ? stringifyDocDefaults(s.default.document, false)\n : (s.docDefaultsXml ?? f.importedStyles?.[0]?._raw ?? \"\");\n const latentStyles = s.latentStylesXml ?? f.importedStyles?.[1]?._raw ?? \"\";\n this.styles = new Styles({\n importedStyles: [{ _raw: docDefaults }, { _raw: latentStyles }],\n initialAttributes: s.initialAttributes ?? f.initialAttributes,\n paragraphStyles: s.paragraphStyles,\n characterStyles: s.characterStyles,\n tableStyles: s.tableStyles,\n numberingStyles: s.numberingStyles,\n });\n } else {\n // Fresh generation: factory default builtins (structured) + user\n // overrides. User paragraphStyles/characterStyles/tableStyles/\n // numberingStyles override factory builtins with the same styleId.\n const f = new DefaultStylesFactory().newInstance(s.default);\n this.styles = new Styles({\n importedStyles: f.importedStyles,\n initialAttributes: s.initialAttributes ?? f.initialAttributes,\n paragraphStyles: mergeById(f.paragraphStyles, s.paragraphStyles),\n characterStyles: mergeById(f.characterStyles, s.characterStyles),\n tableStyles: mergeById(f.tableStyles, s.tableStyles),\n numberingStyles: mergeById(f.numberingStyles, s.numberingStyles),\n });\n }\n } else {\n const stylesFactory = new DefaultStylesFactory();\n this.styles = new Styles(stylesFactory.newInstance());\n }\n\n // Register numbering references from custom paragraph/character styles.\n // Style definitions may contain numbering properties whose concrete instances\n // are never created through the body paragraph processing path.\n if (options.styles?.paragraphStyles) {\n for (const style of options.styles.paragraphStyles) {\n const num = style.paragraph?.numbering;\n if (num) {\n this.numbering.createConcreteNumberingInstance(num.reference, num.instance ?? 0);\n }\n }\n }\n\n // Resolve footnote/endnote presence from the source [Content_Types]: a\n // round-tripped package only carries these parts when the source declared\n // them. Fresh compile (no contentTypes) always emits both.\n const sourceOverrides = options.contentTypes?.overrides ?? [];\n this._hasFootnotes =\n !options.contentTypes || sourceOverrides.some((o) => o.partName === \"/word/footnotes.xml\");\n this._hasEndnotes =\n !options.contentTypes || sourceOverrides.some((o) => o.partName === \"/word/endnotes.xml\");\n // Numbering follows the source [Content_Types] on round-trip — the part is\n // optional, and emitting it without a matching Override is an OPC violation.\n // Fresh compile always emits it (Word ships a default bullet list).\n this._hasNumbering =\n !options.contentTypes || sourceOverrides.some((o) => o.partName === \"/word/numbering.xml\");\n\n this.addDefaultRelationships();\n\n for (const section of options.sections) {\n this.addSection(section);\n }\n\n if (options.footnotes) {\n for (const key in options.footnotes) {\n // Skip the round-tripped separator markers (they carry no .children).\n if (key === \"separator\" || key === \"continuationSeparator\") continue;\n const note = options.footnotes[key];\n if (!note) continue;\n this.footNotes.notes.set(parseFloat(key), note.children);\n }\n this.footNotes.separator = options.footnotes.separator;\n this.footNotes.continuationSeparator = options.footnotes.continuationSeparator;\n }\n\n if (options.endnotes) {\n for (const key in options.endnotes) {\n if (key === \"separator\" || key === \"continuationSeparator\") continue;\n const note = options.endnotes[key];\n if (!note) continue;\n this.endnotes.notes.set(parseFloat(key), note.children);\n }\n this.endnotes.separator = options.endnotes.separator;\n this.endnotes.continuationSeparator = options.endnotes.continuationSeparator;\n }\n\n this.fontTable = new FontWrapper(options.fonts ?? []);\n this.glossaryOptions = options.glossary;\n this.webSettings = options.webSettings ?? undefined;\n\n if (options.glossary) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument\",\n \"glossary/document.xml\",\n );\n }\n\n if (this.webSettings) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings\",\n \"webSettings.xml\",\n );\n }\n }\n\n get headers(): HeaderFooterEntry[] {\n return this._headers;\n }\n\n get footers(): HeaderFooterEntry[] {\n return this._footers;\n }\n\n // --- Private helpers ---\n\n private addSection({ headers = {}, footers = {}, properties }: SectionOptions): void {\n const sectPrOptions: SectionPropertiesOptions = {\n ...properties,\n footerWrapperGroup: {\n default: footers.default ? this.createFooter(footers.default) : undefined,\n even: footers.even ? this.createFooter(footers.even) : undefined,\n first: footers.first ? this.createFooter(footers.first) : undefined,\n },\n headerWrapperGroup: {\n default: headers.default ? this.createHeader(headers.default) : undefined,\n even: headers.even ? this.createHeader(headers.even) : undefined,\n first: headers.first ? this.createHeader(headers.first) : undefined,\n },\n };\n this._sectionProperties.push(sectPrOptions);\n }\n\n private createHeader(header: SectionChild[]): HeaderFooterEntry {\n const referenceId = this._currentRelationshipId++;\n const entry: HeaderFooterEntry = {\n children: header,\n relationships: new Relationships(),\n referenceId,\n };\n this.addHeaderToDocument(entry);\n return entry;\n }\n\n private createFooter(footer: SectionChild[]): HeaderFooterEntry {\n const referenceId = this._currentRelationshipId++;\n const entry: HeaderFooterEntry = {\n children: footer,\n relationships: new Relationships(),\n referenceId,\n };\n this.addFooterToDocument(entry);\n return entry;\n }\n\n private addHeaderToDocument(header: HeaderFooterEntry): void {\n this._headers.push(header);\n this.document.relationships.addRelationship(\n header.referenceId,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header\",\n `header${this._headers.length}.xml`,\n );\n }\n\n private addFooterToDocument(footer: HeaderFooterEntry): void {\n this._footers.push(footer);\n this.document.relationships.addRelationship(\n footer.referenceId,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer\",\n `footer${this._footers.length}.xml`,\n );\n }\n\n private addDefaultRelationships(): void {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\",\n \"styles.xml\",\n );\n if (this._hasNumbering) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering\",\n \"numbering.xml\",\n );\n }\n if (this._hasFootnotes) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes\",\n \"footnotes.xml\",\n );\n }\n if (this._hasEndnotes) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes\",\n \"endnotes.xml\",\n );\n }\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings\",\n \"settings.xml\",\n );\n // Comments is an optional part — only wire the document→comments relationship\n // when the document actually carries comments. Emitting it unconditionally\n // produces an orphan comments.xml that Word rejects as an OPC violation\n // (empty part with no [Content_Types] Override when content types are\n // passed through from the source on round-trip).\n if (this._options.comments?.children?.length || this._hasCommentSugar) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments\",\n \"comments.xml\",\n );\n }\n if (this._options.bibliography) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/bibliography\",\n \"bibliography.xml\",\n );\n }\n\n // Theme — always present: fresh-compile generates a default theme, round-trip\n // passes the source theme through rawParts. Word needs the document→theme\n // relationship to resolve theme colors/fonts.\n const themePart = this._options.rawParts?.find((p) => p.path.startsWith(\"word/theme/\"));\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme\",\n themePart ? themePart.path.replace(/^word\\//, \"\") : \"theme/theme1.xml\",\n );\n\n // customXml storage — raw-passthrough parts. Declare the document→customXml\n // relationship for each item (itemProps are linked via the item's own .rels,\n // not directly by the document) so Word can bind cover-page metadata, etc.\n for (const part of this._options.rawParts ?? []) {\n if (\n part.path.startsWith(\"customXml/\") &&\n part.path.endsWith(\".xml\") &&\n !part.path.includes(\"/_rels/\") &&\n !part.path.includes(\"itemProps\")\n ) {\n this.document.relationships.addRelationship(\n this._currentRelationshipId++,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml\",\n `../${part.path}`,\n );\n }\n }\n }\n}\n\n// ── DocxReadContext ──\n\n/**\n * DOCX-specific read context.\n *\n * Holds references to the parsed DocxDocument and cached style/numbering data\n * used throughout the DOCX parsing pipeline. Implements ReadContext for\n * descriptor pipeline compatibility.\n */\nexport class DocxReadContext implements ReadContext {\n /**\n * Path of the part currently being parsed. Each part carries its own .rels\n * with independent rId numbering, so drawings inside a part must resolve\n * image relationships against that part's rels. Defaults to the document body.\n */\n public currentPart = \"word/document.xml\";\n\n constructor(\n public docx: DocxDocument,\n public styleCache: Map<string, Element>,\n public numberingCache: Map<string, Element>,\n ) {}\n\n resolveRelationship(rId: string): string | undefined {\n const partMedia = this.docx.partRefs.partMedia.get(this.currentPart);\n if (partMedia) {\n const media = partMedia.get(rId);\n if (media) return media;\n }\n return (\n this.docx.partRefs.headers.get(rId) ??\n this.docx.partRefs.footers.get(rId) ??\n this.docx.partRefs.media.get(rId) ??\n this.docx.partRefs.charts.get(rId) ??\n this.docx.partRefs.diagramData.get(rId) ??\n this.docx.partRefs.afChunks.get(rId) ??\n this.docx.partRefs.subDocs.get(rId) ??\n this.docx.partRefs.hyperlinks.get(rId)\n );\n }\n\n /**\n * Run `fn` with `currentPart` temporarily set to `partPath`, restoring the\n * previous value afterwards. Use when parsing a sub-document part (header,\n * footer, footnotes, …) so its drawings resolve images from its own rels.\n */\n withPart<T>(partPath: string, fn: () => T): T {\n const prev = this.currentPart;\n this.currentPart = partPath;\n try {\n return fn();\n } finally {\n this.currentPart = prev;\n }\n }\n\n getPart(path: string): Element | undefined {\n return this.docx.doc.get(path);\n }\n\n getRaw(path: string): Uint8Array | undefined {\n return this.docx.doc.getRaw(path);\n }\n}\n","/**\n * AltChunk parser for DOCX documents.\n *\n * Parses w:altChunk elements and extracts embedded content from the ZIP.\n *\n * @module\n */\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { AltChunkOptions } from \"@parts/alt-chunk/alt-chunk\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse a w:altChunk element into AltChunkOptions.\n * Reads the referenced data from the ZIP package.\n */\nexport function parseAltChunk(el: Element, ctx: DocxReadContext): AltChunkOptions {\n const rId = attr(el, \"r:id\");\n if (!rId) {\n throw new Error(\"w:altChunk missing r:id attribute\");\n }\n\n // Look up the path from relationships\n const path = ctx.docx.partRefs.afChunks.get(rId);\n if (!path) {\n throw new Error(`AltChunk relationship ${rId} not found`);\n }\n\n // Read raw data from ZIP\n const data = ctx.docx.doc.getRaw(path);\n if (!data) {\n throw new Error(`AltChunk data not found at ${path}`);\n }\n\n // Determine content type from extension\n const ext = path.split(\".\").pop() ?? \"txt\";\n let contentType: \"text/html\" | \"application/rtf\" | \"text/plain\";\n let extension: \"html\" | \"rtf\" | \"txt\";\n\n switch (ext) {\n case \"html\":\n contentType = \"text/html\";\n extension = \"html\";\n break;\n case \"rtf\":\n contentType = \"application/rtf\";\n extension = \"rtf\";\n break;\n default:\n contentType = \"text/plain\";\n extension = \"txt\";\n break;\n }\n\n return {\n data,\n contentType,\n extension,\n };\n}\n","/**\n * Parser for custom XML block elements (w:customXml).\n *\n * @module\n */\nimport { attr, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { DocxReadContext } from \"../../context\";\nimport { parseCustomXmlProperties } from \"../bodychildren\";\nimport type { CustomXmlBlockOptions } from \"./custom-xml\";\n\n/**\n * Parse w:customXml element into CustomXmlBlockOptions.\n *\n * Uses a callback for child parsing to avoid circular dependencies\n * (same pattern as parseTable).\n */\nexport function parseCustomXmlBlock(\n el: Element,\n ctx: DocxReadContext,\n parseChild: (el: Element, ctx: DocxReadContext) => SectionChild,\n): CustomXmlBlockOptions {\n const opts: Partial<CustomXmlBlockOptions> = {};\n\n // Required attribute\n const element = attr(el, \"w:element\");\n if (element) opts.element = element;\n\n // Optional URI\n const uri = attr(el, \"w:uri\");\n if (uri) opts.uri = uri;\n\n // Parse w:customXmlPr\n const xmlPr = findChild(el, \"w:customXmlPr\");\n if (xmlPr) {\n opts.customXmlPr = parseCustomXmlProperties(xmlPr);\n }\n\n // Parse block-level children\n const children: SectionChild[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:customXmlPr\") continue;\n const parsed = parseChild(child, ctx);\n children.push(parsed);\n }\n if (children.length > 0) opts.children = children;\n\n return opts as CustomXmlBlockOptions;\n}\n","/**\n * SubDoc parser for DOCX documents.\n *\n * Parses w:subDoc elements and extracts embedded document data.\n *\n * @module\n */\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { SubDocOptions } from \"@parts/sub-doc/sub-doc\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse a w:subDoc element into SubDocOptions.\n * Reads the referenced document data from the ZIP package.\n */\nexport function parseSubDoc(el: Element, ctx: DocxReadContext): SubDocOptions {\n const rId = attr(el, \"r:id\");\n if (!rId) {\n throw new Error(\"w:subDoc missing r:id attribute\");\n }\n\n const path = ctx.docx.partRefs.subDocs.get(rId);\n if (!path) {\n throw new Error(`SubDoc relationship ${rId} not found`);\n }\n\n const data = ctx.docx.doc.getRaw(path);\n if (!data) {\n throw new Error(`SubDoc data not found at ${path}`);\n }\n\n return { data };\n}\n","import { parseVmlShapeStyle, parseVmlStyle } from \"@office-open/core\";\n/**\n * Textbox parser for DOCX documents.\n *\n * Parses w:pict → v:shape → v:textbox → w:txbxContent elements.\n *\n * @module\n */\nimport { attr, findChild, findFirst } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse a w:pict element that contains a textbox.\n * Returns an object suitable for the { textbox: ... } SectionChild variant.\n */\nexport function parseTextbox(\n el: Element,\n ctx: DocxReadContext,\n parseChildren: (elements: Element[], ctx: DocxReadContext) => unknown[],\n): {\n style?: Record<string, string>;\n children?: unknown[];\n} {\n const shape = findFirst(el, \"v:shape\");\n if (!shape) return {};\n\n const opts: Record<string, unknown> = {};\n\n // Parse VML style\n const styleAttr = attr(shape, \"style\");\n if (styleAttr) {\n opts.style = parseVmlShapeStyle(parseVmlStyle(styleAttr));\n }\n\n // Parse textbox content\n const textbox = findFirst(shape, \"v:textbox\");\n if (textbox) {\n const txbxContent = findChild(textbox, \"w:txbxContent\");\n if (txbxContent) {\n const childList = parseChildren(txbxContent.elements ?? [], ctx);\n if (childList.length > 0) opts.children = childList;\n }\n }\n\n return opts as { style?: Record<string, string>; children?: unknown[] };\n}\n","/**\n * Body parser for DOCX documents.\n *\n * Parses w:body → SectionOptions[] by splitting at w:sectPr boundaries.\n *\n * @module\n */\nimport { attr, findChild, findDeep, findFirst, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { parseAltChunk } from \"@parts/alt-chunk/alt-chunk-parse\";\nimport { parseCustomXmlBlock } from \"@parts/custom-xml/custom-xml-parse\";\nimport { parseSectionPropertiesEl } from \"@parts/document/body/section-properties/descriptor\";\nimport type { SectionPropertiesOptions } from \"@parts/document/body/section-properties/section-properties\";\nimport type { MarkupRangeOptions, BookmarkStartOptions } from \"@parts/paragraph/links/bookmark\";\nimport { parseSdtBlock } from \"@parts/sdt/sdt-parse\";\nimport { parseSubDoc } from \"@parts/sub-doc/sub-doc-parse\";\nimport {\n parseToc,\n parseTocFieldFromElements,\n selectTocEntryElements,\n} from \"@parts/table-of-contents/toc-parse\";\nimport { tableDesc } from \"@parts/table/descriptor\";\nimport type { TableOptions } from \"@parts/table/table\";\nimport { parseTextbox } from \"@parts/textbox/textbox-parse\";\nimport type { SectionOptions } from \"@shared/section\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { parseParagraph } from \"../body\";\nimport { DocxReadContext } from \"../context\";\nimport { setBodyParseChild } from \"../parts\";\nimport { stringifyElement } from \"../util/stringify-element\";\n\n// ── Section properties parser ────────────────────────────────────────────────\n\n/** Internal parse result: section properties with extracted header/footer refs. */\ntype ParsedSectionProperties = SectionPropertiesOptions & {\n parsedHeaders?: Record<string, SectionChild[]>;\n parsedFooters?: Record<string, SectionChild[]>;\n};\n\n/**\n * Parse w:sectPr element into SectionPropertiesOptions.\n * Delegates to the section properties descriptor's parse method.\n */\nfunction parseSectionProperties(el: Element, ctx: DocxReadContext): ParsedSectionProperties {\n const opts: ParsedSectionProperties = parseSectionPropertiesEl(el);\n\n // Headers/footers - parse from references and store in a separate field\n const headerRefs: Record<string, SectionChild[]> = {};\n const footerRefs: Record<string, SectionChild[]> = {};\n\n for (const child of el.elements ?? []) {\n if (child.name === \"w:headerReference\") {\n const rId = attr(child, \"r:id\");\n const type = attr(child, \"w:type\");\n if (rId && type) {\n const headerChildren = parseHeaderFooterRef(rId, ctx);\n if (headerChildren) headerRefs[type] = headerChildren;\n }\n }\n if (child.name === \"w:footerReference\") {\n const rId = attr(child, \"r:id\");\n const type = attr(child, \"w:type\");\n if (rId && type) {\n const footerChildren = parseHeaderFooterRef(rId, ctx);\n if (footerChildren) footerRefs[type] = footerChildren;\n }\n }\n }\n\n if (Object.keys(headerRefs).length > 0) {\n opts.parsedHeaders = headerRefs;\n }\n if (Object.keys(footerRefs).length > 0) {\n opts.parsedFooters = footerRefs;\n }\n\n return opts;\n}\n\n/**\n * Parse a header/footer reference by following the relationship to its XML part.\n */\nfunction parseHeaderFooterRef(rId: string, ctx: DocxReadContext): SectionChild[] | undefined {\n const path = ctx.docx.partRefs.headers.get(rId) ?? ctx.docx.partRefs.footers.get(rId);\n if (!path) return undefined;\n\n const partEl = ctx.docx.doc.get(path);\n if (!partEl) return undefined;\n\n // The header/footer XML root element contains w:p, w:tbl, etc. Parse under\n // the part's own relationship scope so its drawings resolve images correctly.\n const children: SectionChild[] = [];\n ctx.withPart(path, () => {\n for (const child of partEl.elements ?? []) {\n const sectionChild = parseSectionChild(child, ctx);\n if (sectionChild !== undefined) {\n children.push(sectionChild);\n }\n }\n });\n\n return children.length > 0 ? children : undefined;\n}\n\n// ── Section child dispatch ───────────────────────────────────────────────────\n\n/**\n * Parse a single body child element into a SectionChild.\n */\nexport function parseSectionChild(el: Element, ctx: DocxReadContext): SectionChild {\n switch (el.name) {\n case \"w:p\": {\n // Check for textbox (w:pict containing v:textbox)\n const pict = findChild(el, \"w:pict\");\n if (pict) {\n const textbox = findFirst(pict, \"v:textbox\");\n if (textbox) {\n const textboxOpts = parseTextbox(pict, ctx, parseSectionChildrenElements);\n return { textbox: textboxOpts as SectionChild extends { textbox: infer T } ? T : never };\n }\n }\n\n return { paragraph: parseParagraph(el, ctx) };\n }\n case \"w:tbl\":\n return { table: tableDesc.parse(el, ctx) as TableOptions };\n case \"w:sdt\": {\n // Try TOC first\n const tocResult = parseToc(el, ctx, parseSectionChildrenElements);\n if (tocResult) {\n return { toc: tocResult };\n }\n // Otherwise parse as generic SDT block\n const sdtResult = parseSdtBlock(el, ctx, parseSectionChildrenElements);\n return {\n sdt: {\n properties: sdtResult.properties,\n children: sdtResult.children as SectionChild[] | undefined,\n },\n };\n }\n case \"w:altChunk\":\n return { altChunk: parseAltChunk(el, ctx) };\n case \"w:subDoc\":\n return { subDoc: parseSubDoc(el, ctx) };\n case \"w:customXml\":\n return { customXml: parseCustomXmlBlock(el, ctx, parseSectionChild) };\n case \"w:bookmarkStart\": {\n // Body-level range markers sitting between paragraphs (e.g. _Toc bookmark\n // ends grouped after a heading). Carry them as first-class children so\n // they round-trip even though they are not wrapped in a paragraph.\n const idRaw = attr(el, \"w:id\");\n const name = attr(el, \"w:name\");\n if (idRaw !== undefined && name) {\n const bookmarkStart: Partial<BookmarkStartOptions> = { id: Number(idRaw), name };\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkStart.displacedByCustomXml = disp;\n const colFirstRaw = attr(el, \"w:colFirst\");\n if (colFirstRaw !== undefined) bookmarkStart.colFirst = Number(colFirstRaw);\n const colLastRaw = attr(el, \"w:colLast\");\n if (colLastRaw !== undefined) bookmarkStart.colLast = Number(colLastRaw);\n return { bookmarkStart: bookmarkStart as BookmarkStartOptions };\n }\n return { rawXml: stringifyElement(el) };\n }\n case \"w:bookmarkEnd\": {\n const idRaw = attr(el, \"w:id\");\n if (idRaw !== undefined) {\n const bookmarkEnd: Partial<MarkupRangeOptions> = { id: Number(idRaw) };\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkEnd.displacedByCustomXml = disp;\n return { bookmarkEnd: bookmarkEnd as MarkupRangeOptions };\n }\n return { rawXml: stringifyElement(el) };\n }\n default:\n return { rawXml: stringifyElement(el) };\n }\n}\n\n// ── Body parsing with section splitting ───────────────────────────────────────\n\n/**\n * Parse w:body element into SectionOptions[].\n *\n * Splits body content at w:sectPr boundaries to create sections.\n * The last w:sectPr (child of w:body directly) defines the last section.\n * Previous w:sectPr elements appear inside w:pPr elements.\n */\nexport function parseBody(body: Element, ctx: DocxReadContext): SectionOptions[] {\n // Register the body child parser for descriptor parse callbacks\n setBodyParseChild(parseSectionChild);\n\n // Collect body children and detect section breaks\n interface SectionBoundary {\n index: number;\n sectPr: Element;\n }\n\n const bodyChildren: Element[] = [];\n const boundaries: SectionBoundary[] = [];\n\n for (const child of body.elements ?? []) {\n if (child.name === \"w:sectPr\") {\n // Final section properties (last section)\n boundaries.push({ index: bodyChildren.length, sectPr: child });\n } else {\n bodyChildren.push(child);\n\n // Check for inline sectPr in paragraph properties\n if (child.name === \"w:p\") {\n const pPr = findChild(child, \"w:pPr\");\n if (pPr) {\n const sectPr = findChild(pPr, \"w:sectPr\");\n if (sectPr) {\n boundaries.push({ index: bodyChildren.length, sectPr });\n }\n }\n }\n }\n }\n\n // If no boundaries, the whole body is one section\n if (boundaries.length === 0) {\n return [\n {\n children: parseBodyChildren(bodyChildren, ctx),\n },\n ];\n }\n\n // Split into sections\n const sections: SectionOptions[] = [];\n let start = 0;\n\n for (const boundary of boundaries) {\n // A sectPr inside a paragraph's pPr marks that paragraph as the final\n // content paragraph of its section. Its runs/drawings ARE section content\n // (e.g. an inline image), so include it in the slice — the paragraph parser\n // ignores pPr/w:sectPr, and stringify re-injects the sectPr into this same\n // paragraph's pPr. The last boundary is a body-level sectPr (never in a\n // paragraph), so boundary.index already points past every real child.\n const endIdx = boundary.index;\n const sectionElements = bodyChildren.slice(start, endIdx);\n const parsedProps = parseSectionProperties(boundary.sectPr, ctx);\n\n // Extract headers/footers that were stored as parsedHeaders/parsedFooters\n const { parsedHeaders, parsedFooters } = parsedProps;\n\n // Build clean properties without internal fields\n const cleanProps = { ...parsedProps };\n delete cleanProps.parsedHeaders;\n delete cleanProps.parsedFooters;\n\n const section = {\n children: parseBodyChildren(sectionElements, ctx),\n properties: cleanProps,\n ...(parsedHeaders ? { headers: parsedHeaders } : {}),\n ...(parsedFooters ? { footers: parsedFooters } : {}),\n } as SectionOptions;\n\n sections.push(section);\n start = boundary.index;\n }\n\n // If there are elements after the last boundary, they form the last section\n // with the body-level w:sectPr (already captured)\n // Actually the body-level sectPr IS the last boundary\n\n return sections;\n}\n\n// ── Cross-paragraph TOC field aggregation ───────────────────────────────────\n\n/**\n * Net field-nesting change across all descendant fldChar markers\n * (begin: +1, end: -1). Balances cross-paragraph field boundaries without a\n * stack — the running depth hits 0 exactly when the outermost field closes.\n */\nfunction countFieldDelta(el: Element): number {\n let delta = 0;\n const walk = (node: Element): void => {\n if (node.name === \"w:fldChar\") {\n const type = attr(node, \"w:fldCharType\");\n if (type === \"begin\") delta += 1;\n else if (type === \"end\") delta -= 1;\n }\n for (const c of node.elements ?? []) {\n if (c.type === \"element\") walk(c);\n }\n };\n walk(el);\n return delta;\n}\n\n/**\n * True when a w:p opens a bare TOC complex field: it carries a fldChar begin\n * whose instrText starts with \"TOC\". Such fields span multiple paragraphs and\n * defeat the per-paragraph field accumulator, so they are aggregated as rawXml.\n */\nfunction isTocFieldBegin(el: Element): boolean {\n if (el.name !== \"w:p\") return false;\n let hasBegin = false;\n let instr = \"\";\n const walk = (node: Element): void => {\n if (node.name === \"w:fldChar\" && attr(node, \"w:fldCharType\") === \"begin\") hasBegin = true;\n if (node.name === \"w:instrText\") instr += textOf(node);\n for (const c of node.elements ?? []) {\n if (c.type === \"element\") walk(c);\n }\n };\n walk(el);\n return hasBegin && instr.trim().toUpperCase().startsWith(\"TOC\");\n}\n\n/**\n * Parse a run of body-level elements into SectionChild[], aggregating any\n * cross-paragraph TOC complex field into a single rawXml child so its nested\n * HYPERLINK/PAGEREF fields and bookmark markers round-trip intact.\n */\nfunction parseBodyChildren(elements: Element[], ctx: DocxReadContext): SectionChild[] {\n const children: SectionChild[] = [];\n let tocBuffer: Element[] | null = null;\n let tocDepth = 0;\n\n const flushToc = (): void => {\n if (!tocBuffer) return;\n children.push(buildTocChild(tocBuffer, ctx));\n // buildTocChild preserves the rendered entries (paragraphs between the\n // separate and end markers) but not the end-closing paragraph, which often\n // carries a trailing page break (the section break before the first\n // heading). Rescue that page break as a standalone child to avoid silently\n // dropping it on round-trip.\n const lastEl = tocBuffer[tocBuffer.length - 1];\n let pageBreakCount = 0;\n for (const br of findDeep(lastEl, \"w:br\")) {\n if (attr(br, \"w:type\") === \"page\") pageBreakCount++;\n }\n for (let i = 0; i < pageBreakCount; i++) {\n children.push({ paragraph: { children: [{ pageBreak: true }] } });\n }\n tocBuffer = null;\n tocDepth = 0;\n };\n\n for (const el of elements) {\n if (tocBuffer !== null) {\n tocBuffer.push(el);\n tocDepth += countFieldDelta(el);\n if (tocDepth <= 0) flushToc();\n continue;\n }\n if (isTocFieldBegin(el)) {\n tocBuffer = [el];\n tocDepth = countFieldDelta(el);\n if (tocDepth <= 0) flushToc();\n continue;\n }\n children.push(parseSectionChild(el, ctx));\n }\n\n // Unclosed TOC field at end of content — flush what we have (best effort).\n flushToc();\n\n return children;\n}\n\n/**\n * Build a structured TOC SectionChild from a captured bare TOC field. Extracts\n * the field instruction (switches → TableOfContentsOptions) and preserves the\n * rendered entries (separate→end paragraphs) structurally so MS Office and WPS\n * both display the existing TOC. The field is emitted clean (no dirty flag).\n */\nfunction buildTocChild(els: Element[], ctx: DocxReadContext): SectionChild {\n const tocOpts = parseTocFieldFromElements(els);\n const entryEls = selectTocEntryElements(els);\n if (entryEls.length > 0) {\n tocOpts.entries = entryEls.map((el) => parseSectionChild(el, ctx));\n }\n return { toc: tocOpts };\n}\n\n/**\n * Parse a list of elements into SectionChild[].\n * Used by SDT and textbox parsers for their content.\n */\nfunction parseSectionChildrenElements(elements: Element[], ctx: DocxReadContext): SectionChild[] {\n return parseBodyChildren(elements, ctx);\n}\n","import type { ParsedArchive } from \"@office-open/core\";\nimport { parseArchive } from \"@office-open/core\";\nimport type { DataType } from \"@office-open/core\";\nimport { resolveRelationshipTarget, toUint8Array } from \"@office-open/core\";\nimport { contentTypesDesc } from \"@office-open/core\";\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { appPropertiesDesc } from \"@parts/app-properties\";\nimport { bibliographyDesc } from \"@parts/bibliography\";\nimport { setBodyParseChild } from \"@parts/bodychildren\";\nimport { commentsDesc } from \"@parts/comments\";\nimport { corePropertiesDesc } from \"@parts/core-properties\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { customPropertiesDesc } from \"@parts/custom-properties\";\nimport { endnotesDesc } from \"@parts/endnotes/descriptor\";\nimport { fontTableDesc } from \"@parts/fonts/descriptor\";\nimport type { EmbeddedFontOptionsWithKey } from \"@parts/fonts/font-wrapper\";\nimport { footnotesDesc } from \"@parts/footnotes/descriptor\";\nimport { glossaryDesc } from \"@parts/glossary-document\";\nimport { parseNumberingDefinitions } from \"@parts/numbering/numbering\";\nimport { settingsDesc } from \"@parts/settings/descriptor\";\nimport { buildStyleCache, buildNumberingCache, parseStyleDefinitions } from \"@parts/styles/styles\";\nimport { setTableParseChild } from \"@parts/table/descriptor\";\nimport { webSettingsDesc } from \"@parts/web-settings\";\n\nimport { parseParagraphProperties } from \"./body\";\nimport { DocxReadContext } from \"./context\";\nimport { parseBody, parseSectionChild } from \"./parse/body\";\nimport { replaceRelsWithPlaceholders } from \"./util/replace-media-placeholders\";\nimport { stringifyElement } from \"./util/stringify-element\";\n\nexport { parseArchive };\n\n/**\n * All part paths extracted from the DOCX package.\n * Field names correspond directly to the OOXML directory structure.\n */\nexport interface DocxPartRefs {\n /** word/headerN.xml keyed by rId */\n headers: Map<string, string>;\n /** word/footerN.xml keyed by rId */\n footers: Map<string, string>;\n /** word/footnotes.xml */\n footnotes?: string;\n /** word/endnotes.xml */\n endnotes?: string;\n /** word/comments.xml */\n comments?: string;\n /** Hyperlink targets keyed by rId (external URLs) */\n hyperlinks: Map<string, string>;\n /** word/charts/chartN.xml keyed by rId */\n charts: Map<string, string>;\n /** word/diagrams/dataN.xml keyed by rId */\n diagramData: Map<string, string>;\n /** word/diagrams/layoutN.xml keyed by rId */\n diagramLayout: Map<string, string>;\n /** word/diagrams/quickStyleN.xml keyed by rId */\n diagramQuickStyle: Map<string, string>;\n /** word/diagrams/colorsN.xml keyed by rId */\n diagramColors: Map<string, string>;\n /** word/media/* keyed by rId (from document.xml.rels) */\n media: Map<string, string>;\n /**\n * Per-part image/media relationships. Each part (document, headers, footers,\n * footnotes, …) has its own .rels with independent rId numbering, so drawings\n * inside a part must resolve images against that part's rels. Maps\n * partPath → (rId → mediaPath).\n */\n partMedia: Map<string, Map<string, string>>;\n /** Alternative format chunks (word/afchunkN.*) keyed by rId */\n afChunks: Map<string, string>;\n /** Sub-documents (word/subdocs/subdocN.docx) keyed by rId */\n subDocs: Map<string, string>;\n /** word/bibliography.xml */\n bibliography?: string;\n /** word/glossary/document.xml */\n glossary?: string;\n}\n\nexport interface DocxDocument {\n doc: ParsedArchive;\n /** word/document.xml → root w:document element */\n documentRoot: Element;\n /** word/document.xml → w:body element */\n body: Element;\n /** word/document.xml → w:background element */\n background?: Element;\n /** word/styles.xml */\n styles?: Element;\n /** word/numbering.xml */\n numbering?: Element;\n /** word/settings.xml */\n settings?: Element;\n /** word/fontTable.xml */\n fontTable?: Element;\n /** word/webSettings.xml */\n webSettings?: Element;\n partRefs: DocxPartRefs;\n /** docProps/core.xml */\n coreProps?: string;\n /** docProps/app.xml */\n appProps?: string;\n /** docProps/custom.xml */\n customProps?: string;\n /** [Content_Types].xml */\n contentTypes?: Element;\n}\n\n/**\n * Resolve each embedded font's .odttf bytes through fontTable.xml.rels.\n * Reads the binary verbatim and flags it raw so the compiler copies it as-is\n * instead of re-obfuscating (the fontKey already matches the bytes).\n */\nfunction resolveEmbeddedFontData(fonts: EmbeddedFontOptionsWithKey[], doc: ParsedArchive): void {\n const relsEl = doc.get(\"word/_rels/fontTable.xml.rels\");\n if (!relsEl) return;\n const ridToPath = new Map<string, string>();\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n if (!type.includes(\"/font\")) continue;\n const id = attr(child, \"Id\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (id && target) ridToPath.set(id, resolveRelationshipTarget(\"word/fontTable.xml\", target));\n }\n for (const font of fonts) {\n if (!font.embedRid) continue;\n const odttfPath = ridToPath.get(font.embedRid);\n if (!odttfPath) continue;\n const bytes = doc.getRaw(odttfPath);\n if (bytes) {\n font.data = Buffer.from(bytes);\n font.rawOdttf = true;\n font.odttfPath = odttfPath;\n }\n }\n}\n\nfunction parseDocPartRefs(doc: ParsedArchive): DocxPartRefs {\n const refs: DocxPartRefs = {\n headers: new Map(),\n footers: new Map(),\n hyperlinks: new Map(),\n charts: new Map(),\n diagramData: new Map(),\n diagramLayout: new Map(),\n diagramQuickStyle: new Map(),\n diagramColors: new Map(),\n media: new Map(),\n partMedia: new Map(),\n afChunks: new Map(),\n subDocs: new Map(),\n };\n\n const relsEl = doc.get(\"word/_rels/document.xml.rels\");\n if (!relsEl) return refs;\n\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n const id = attr(child, \"Id\") ?? \"\";\n if (!target) continue;\n\n const path = resolveRelationshipTarget(\"word/document.xml\", target);\n\n if (type.includes(\"/header\")) {\n refs.headers.set(id, path);\n } else if (type.includes(\"/footer\")) {\n refs.footers.set(id, path);\n } else if (type.includes(\"/footnotes\")) {\n refs.footnotes = path;\n } else if (type.includes(\"/endnotes\")) {\n refs.endnotes = path;\n } else if (type.includes(\"/comments\")) {\n refs.comments = path;\n } else if (type.includes(\"/chart\")) {\n refs.charts.set(id, path);\n } else if (type.includes(\"/diagramData\")) {\n refs.diagramData.set(id, path);\n } else if (type.includes(\"/diagramLayout\")) {\n refs.diagramLayout.set(id, path);\n } else if (type.includes(\"/diagramQuickStyle\")) {\n refs.diagramQuickStyle.set(id, path);\n } else if (type.includes(\"/diagramColors\")) {\n refs.diagramColors.set(id, path);\n } else if (type.includes(\"/image\") || type.includes(\"/media\")) {\n refs.media.set(id, path);\n } else if (type.includes(\"/aFChunk\")) {\n refs.afChunks.set(id, path);\n } else if (type.includes(\"/subDocument\")) {\n refs.subDocs.set(id, path);\n } else if (type.includes(\"/bibliography\")) {\n refs.bibliography = path;\n } else if (type.includes(\"/glossaryDocument\")) {\n refs.glossary = path;\n } else if (type.includes(\"/hyperlink\")) {\n refs.hyperlinks.set(id, target);\n }\n }\n\n // Per-part image relationships. Each part carries its own .rels with\n // independent rId numbering (document rId1 ≠ header rId1), so collect them\n // keyed by part path; drawings inside a part resolve images through its\n // own rels. Covers document, headers, footers, footnotes, endnotes, comments.\n for (const relsPath of doc.keys(\"word/_rels/\")) {\n if (!relsPath.endsWith(\".rels\")) continue;\n const relsEl = doc.get(relsPath);\n if (!relsEl) continue;\n const partPath = \"word/\" + relsPath.slice(\"word/_rels/\".length, -\".rels\".length);\n for (const rel of relsEl.elements ?? []) {\n if (rel.name !== \"Relationship\") continue;\n const type = attr(rel, \"Type\") ?? \"\";\n if (!type.includes(\"/image\") && !type.includes(\"/media\")) continue;\n const id = attr(rel, \"Id\") ?? \"\";\n const target = attr(rel, \"Target\") ?? \"\";\n if (!id || !target) continue;\n let partMap = refs.partMedia.get(partPath);\n if (!partMap) {\n partMap = new Map();\n refs.partMedia.set(partPath, partMap);\n }\n partMap.set(id, resolveRelationshipTarget(partPath, target));\n }\n }\n\n return refs;\n}\n\nfunction parseRootRels(doc: ParsedArchive): {\n coreProps?: string;\n appProps?: string;\n customProps?: string;\n} {\n const relsEl = doc.get(\"_rels/.rels\");\n if (!relsEl) return {};\n\n let coreProps: string | undefined;\n let appProps: string | undefined;\n let customProps: string | undefined;\n\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (!target) continue;\n\n const path = target.startsWith(\"/\") ? target.slice(1) : target;\n\n if (type.includes(\"/core-properties\")) {\n coreProps = path;\n } else if (type.includes(\"/extended-properties\")) {\n appProps = path;\n } else if (type.includes(\"/custom-properties\")) {\n customProps = path;\n }\n }\n\n return { coreProps, appProps, customProps };\n}\n\n/**\n * Parse a .docx file and convert it into DocumentOptions.\n *\n * This is the main public API for parsing DOCX files.\n * The returned options can be passed directly to `new Document(parsed)`\n * to recreate the document.\n *\n * @param data - Raw bytes of a .docx file\n * @returns Document options including sections and metadata\n */\nexport function parseDocument(data: DataType): DocumentOptions {\n const docx = parseDocx(data);\n const ctx = new DocxReadContext(\n docx,\n buildStyleCache(docx.styles),\n buildNumberingCache(docx.numbering),\n );\n\n // Register the child parser for table and body child descriptors\n setTableParseChild(parseSectionChild);\n setBodyParseChild(parseSectionChild);\n\n const sections = parseBody(docx.body, ctx);\n\n const opts: Partial<DocumentOptions> = { sections };\n\n // Document conformance class (w:document/@w:conformance)\n const conformance = attr(docx.documentRoot, \"w:conformance\");\n if (conformance === \"strict\" || conformance === \"transitional\") opts.conformance = conformance;\n\n // Background (w:background in document.xml)\n if (docx.background) {\n const hasChildren = (docx.background.elements ?? []).some((e) => e.type === \"element\");\n if (hasChildren) {\n // VML/structured background (e.g. v:background/v:fill pattern with a\n // texture image) that doesn't fit the color/theme model: carry the\n // element verbatim, rewriting relationship refs to {fileName} placeholders\n // so the media round-trips via the compiler's placeholder pass.\n const { rawXml, rawMedia } = replaceRelsWithPlaceholders(\n stringifyElement(docx.background),\n ctx,\n \"background\",\n );\n opts.background = rawMedia.length > 0 ? { rawXml, rawMedia } : { rawXml };\n } else {\n const bg: NonNullable<DocumentOptions[\"background\"]> = {};\n const color = attr(docx.background, \"w:color\");\n if (color) bg.color = color;\n const themeColor = attr(docx.background, \"w:themeColor\");\n if (themeColor) bg.themeColor = themeColor;\n const themeShade = attr(docx.background, \"w:themeShade\");\n if (themeShade) bg.themeShade = themeShade;\n const themeTint = attr(docx.background, \"w:themeTint\");\n if (themeTint) bg.themeTint = themeTint;\n if (Object.keys(bg).length > 0) opts.background = bg;\n }\n }\n\n // Core properties\n if (docx.coreProps) {\n const corePropsEl = docx.doc.get(docx.coreProps);\n if (corePropsEl) {\n const cp = corePropertiesDesc.parse(corePropsEl, ctx);\n if (cp.title) opts.title = cp.title;\n if (cp.subject) opts.subject = cp.subject;\n if (cp.creator) opts.creator = cp.creator;\n if (cp.keywords) opts.keywords = cp.keywords;\n if (cp.description) opts.description = cp.description;\n if (cp.lastModifiedBy) opts.lastModifiedBy = cp.lastModifiedBy;\n if (cp.revision) opts.revision = cp.revision;\n if (cp.lastPrinted) opts.lastPrinted = cp.lastPrinted;\n if (cp.created) opts.created = cp.created;\n if (cp.modified) opts.modified = cp.modified;\n }\n }\n\n // App (extended) properties\n if (docx.appProps) {\n const appPropsEl = docx.doc.get(docx.appProps);\n if (appPropsEl) {\n const ap = appPropertiesDesc.parse(appPropsEl, ctx);\n if (Object.keys(ap).length > 0) opts.appProperties = ap;\n }\n }\n\n // Settings — parse produces a structured SettingsOptions aligned with\n // generate (no verbatim rawXml fallback). Assign wholesale so context.ts\n // spreads it into _settingsOptions for the descriptor's stringify input.\n if (docx.settings) {\n opts.settings = settingsDesc.parse(docx.settings, ctx);\n }\n\n // Web settings — preserve the part on round-trip even when it has no\n // children. Dropping it leaves an orphaned Override in the passthrough\n // [Content_Types].xml (the part is gone but its Override remains), which is\n // an OPC violation; keeping presence keeps part + rel + Override in sync.\n if (docx.webSettings) {\n opts.webSettings = webSettingsDesc.parse(docx.webSettings, ctx);\n }\n\n // Custom properties\n if (docx.customProps) {\n const customPropsEl = docx.doc.get(docx.customProps);\n if (customPropsEl) {\n const cpResult = customPropertiesDesc.parse(customPropsEl, ctx);\n if (cpResult.properties && cpResult.properties.length > 0) {\n opts.customProperties = cpResult.properties;\n }\n }\n }\n\n // Comments content\n if (docx.partRefs.comments) {\n const commentsEl = docx.doc.get(docx.partRefs.comments);\n if (commentsEl) {\n const commentsResult = ctx.withPart(docx.partRefs.comments, () =>\n commentsDesc.parse(commentsEl, ctx),\n );\n const children = commentsResult.children;\n if (children && children.length > 0) {\n opts.comments = { children };\n }\n }\n }\n\n // Footnotes content\n if (docx.partRefs.footnotes) {\n const footnotesEl = docx.doc.get(docx.partRefs.footnotes);\n if (footnotesEl) {\n const fnResult = ctx.withPart(docx.partRefs.footnotes, () =>\n footnotesDesc.parse(footnotesEl, ctx),\n );\n const footnotesMap: NonNullable<DocumentOptions[\"footnotes\"]> = {};\n for (const [id, paragraphs] of fnResult.notes) {\n footnotesMap[String(id)] = { children: paragraphs };\n }\n // Preserve round-tripped separators so the generated ids stay consistent\n // with settings.footnotePr (which references them).\n if (\n Object.keys(footnotesMap).length > 0 ||\n fnResult.separator ||\n fnResult.continuationSeparator\n ) {\n if (fnResult.separator) footnotesMap.separator = fnResult.separator;\n if (fnResult.continuationSeparator)\n footnotesMap.continuationSeparator = fnResult.continuationSeparator;\n opts.footnotes = footnotesMap;\n }\n }\n }\n\n // Endnotes content\n if (docx.partRefs.endnotes) {\n const endnotesEl = docx.doc.get(docx.partRefs.endnotes);\n if (endnotesEl) {\n const enResult = ctx.withPart(docx.partRefs.endnotes, () =>\n endnotesDesc.parse(endnotesEl, ctx),\n );\n const endnotesMap: NonNullable<DocumentOptions[\"endnotes\"]> = {};\n for (const [id, paragraphs] of enResult.notes) {\n endnotesMap[String(id)] = { children: paragraphs };\n }\n if (\n Object.keys(endnotesMap).length > 0 ||\n enResult.separator ||\n enResult.continuationSeparator\n ) {\n if (enResult.separator) endnotesMap.separator = enResult.separator;\n if (enResult.continuationSeparator)\n endnotesMap.continuationSeparator = enResult.continuationSeparator;\n opts.endnotes = endnotesMap;\n }\n }\n }\n\n // Styles definitions\n if (docx.styles) {\n const styleOpts = parseStyleDefinitions(docx.styles, parseParagraphProperties, ctx);\n if (styleOpts) opts.styles = styleOpts;\n }\n\n // Numbering definitions\n if (docx.numbering) {\n const numOpts = parseNumberingDefinitions(docx.numbering, parseParagraphProperties, ctx);\n if (numOpts) opts.numbering = numOpts;\n }\n\n // Font table\n if (docx.fontTable) {\n const ftResult = fontTableDesc.parse(docx.fontTable, ctx);\n if (ftResult.fonts && ftResult.fonts.length > 0) {\n resolveEmbeddedFontData(ftResult.fonts, docx.doc);\n // embedRid is a resolve-time lookup key — the FontWrapper reassigns it\n // on generate, so it must not leak into the public options JSON.\n opts.fonts = ftResult.fonts.map(({ embedRid: _embedRid, ...font }) => font);\n }\n }\n\n // Bibliography\n if (docx.partRefs.bibliography) {\n const bibEl = docx.doc.get(docx.partRefs.bibliography);\n if (bibEl) {\n const bibResult = bibliographyDesc.parse(bibEl, ctx);\n if (bibResult.sources && bibResult.sources.length > 0) opts.bibliography = bibResult;\n }\n }\n\n // Glossary document\n if (docx.partRefs.glossary) {\n const glossaryEl = docx.doc.get(docx.partRefs.glossary);\n if (glossaryEl) {\n const glossaryResult = ctx.withPart(docx.partRefs.glossary, () =>\n glossaryDesc.parse(glossaryEl, ctx),\n );\n if (glossaryResult.parts && glossaryResult.parts.length > 0) opts.glossary = glossaryResult;\n }\n }\n\n // Content types\n if (docx.contentTypes) {\n const ctResult = contentTypesDesc.parse(docx.contentTypes, ctx);\n if (ctResult) opts.contentTypes = ctResult;\n }\n\n // Raw passthrough: parts generate() doesn't rebuild (word/theme/*, customXml/*).\n // Carried verbatim so their [Content_Types] declarations stay valid and the\n // package opens in Word. (Media/fonts/headers/etc. are rebuilt by the compiler\n // and must NOT be passed through — they'd otherwise duplicate under renamed paths.)\n const rawParts: { path: string; data: Uint8Array }[] = [];\n for (const prefix of [\"word/theme/\", \"customXml/\"]) {\n for (const p of docx.doc.keys(prefix)) {\n if (p.endsWith(\"/\")) continue;\n const data = docx.doc.getRaw(p);\n if (data) rawParts.push({ path: p, data });\n }\n }\n if (rawParts.length > 0) opts.rawParts = rawParts;\n\n return opts as DocumentOptions;\n}\n\nexport function parseDocx(data: DataType): DocxDocument {\n const uint8 = toUint8Array(data);\n const doc = parseArchive(uint8);\n\n const documentEl = doc.get(\"word/document.xml\");\n if (!documentEl) throw new Error(\"word/document.xml not found\");\n const body = documentEl.elements?.find((e) => e.name === \"w:body\");\n if (!body) throw new Error(\"w:body not found in word/document.xml\");\n const background = documentEl.elements?.find((e) => e.name === \"w:background\");\n\n const styles = doc.get(\"word/styles.xml\");\n const numbering = doc.get(\"word/numbering.xml\");\n const settings = doc.get(\"word/settings.xml\");\n const fontTable = doc.get(\"word/fontTable.xml\");\n const webSettings = doc.get(\"word/webSettings.xml\");\n\n const partRefs = parseDocPartRefs(doc);\n const { coreProps, appProps, customProps } = parseRootRels(doc);\n\n const contentTypes = doc.get(\"[Content_Types].xml\");\n\n return {\n doc,\n documentRoot: documentEl,\n body,\n background,\n styles,\n numbering,\n settings,\n fontTable,\n webSettings,\n partRefs,\n coreProps,\n appProps,\n customProps,\n contentTypes,\n };\n}\n","/**\n * Font obfuscation module for embedding fonts in WordprocessingML documents.\n *\n * This module implements the OOXML font obfuscation algorithm used to embed\n * fonts in DOCX documents. Obfuscation is required by the OOXML specification\n * to prevent simple extraction of embedded font files.\n *\n * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding)\n *\n * @module\n */\n\n/** Start offset for obfuscation in the font file */\nconst obfuscatedStartOffset = 0;\n/** End offset for obfuscation (first 32 bytes are obfuscated) */\nconst obfuscatedEndOffset = 32;\n/** Expected GUID size (32 hex characters without dashes) */\nconst guidSize = 32;\n\n/**\n * Obfuscates a TrueType font file for embedding in OOXML documents.\n *\n * The obfuscation algorithm XORs the first 32 bytes of the font file\n * with a reversed byte sequence derived from the font's GUID key.\n * This prevents simple extraction while maintaining font functionality.\n *\n * @param buf - The original font file as a byte array\n * @param fontKey - The GUID key for the font (with or without dashes)\n * @returns The obfuscated font data\n * @throws Error if the fontKey is not a valid 32-character GUID\n *\n * @example\n * ```typescript\n * const fontData = readFileSync(\"font.ttf\");\n * const fontKey = \"00000000-0000-0000-0000-000000000000\";\n * const obfuscatedData = obfuscate(fontData, fontKey);\n * ```\n *\n * @internal\n */\nexport const obfuscate = (buf: Uint8Array, fontKey: string): Uint8Array => {\n const guid = fontKey.replace(/-/g, \"\");\n if (guid.length !== guidSize) {\n throw new Error(`Error: Cannot extract GUID from font filename: ${fontKey}`);\n }\n\n const hexStrings = guid.replace(/(..)/g, \"$1 \").trim().split(\" \");\n const hexNumbers = hexStrings.map((hexString) => parseInt(hexString, 16));\n hexNumbers.reverse();\n\n const bytesToObfuscate = buf.slice(obfuscatedStartOffset, obfuscatedEndOffset);\n const obfuscatedBytes = bytesToObfuscate.map(\n (byte, i) => byte ^ hexNumbers[i % hexNumbers.length]!,\n );\n\n const out = new Uint8Array(\n obfuscatedStartOffset + obfuscatedBytes.length + Math.max(0, buf.length - obfuscatedEndOffset),\n );\n out.set(buf.slice(0, obfuscatedStartOffset));\n out.set(obfuscatedBytes, obfuscatedStartOffset);\n out.set(buf.slice(obfuscatedEndOffset), obfuscatedStartOffset + obfuscatedBytes.length);\n return out;\n};\n","/**\n * Header/Footer entry module for WordprocessingML documents.\n *\n * Replaces the former HeaderWrapper/FooterWrapper/Header/Footer/HeaderFooterBase\n * class hierarchy with a simple data structure + pure serialization function.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_HdrFtr\n *\n * @module\n */\n\nimport type { Relationships } from \"@office-open/core\";\nimport { escapeXml } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { stringifyBodyChild } from \"../body\";\nimport type { BodyContext } from \"../context\";\nimport { DocumentAttributeNamespaces } from \"./document/document-attributes\";\nimport type { DocumentAttributeNamespace } from \"./document/document-attributes\";\n\n/**\n * Reference to a header or footer from a section — just the relationship id\n * needed to emit `<w:headerReference r:id=\"...\">`. Parse fills only this;\n * the full header/footer entry (with children/relationships) is the\n * generate-side shape ({@link HeaderFooterEntry}).\n */\nexport interface HeaderFooterReference {\n referenceId: number;\n}\n\n/**\n * Simple data structure for a header or footer entry.\n *\n * Replaces HeaderWrapper/FooterWrapper — holds children, relationships,\n * and the reference ID needed for section property references.\n *\n * Children are raw SectionChild objects (plain JSON or class instances).\n */\nexport interface HeaderFooterEntry extends HeaderFooterReference {\n children: SectionChild[];\n relationships: Relationships;\n}\n\n/**\n * Namespace keys used by header elements.\n * @internal\n */\nexport const HEADER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"w16cid\",\n \"w16se\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Namespace keys used by footer elements.\n * @internal\n */\nexport const FOOTER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Serialize a header or footer to XML.\n *\n * Builds the `<w:hdr>` or `<w:ftr>` element with namespace declarations,\n * then serializes each child element via `stringifyBodyChild()`.\n *\n * @param tag - Element tag name (\"w:hdr\" or \"w:ftr\")\n * @param namespaces - Namespace keys to declare on the root element\n * @param children - Block-level child elements (raw SectionChild objects)\n * @param ctx - Body context for stringification\n */\nexport function stringifyHeaderFooter(\n tag: string,\n namespaces: DocumentAttributeNamespace[],\n children: SectionChild[],\n ctx: BodyContext,\n): string {\n const attrParts: string[] = [];\n for (const ns of namespaces) {\n attrParts.push(`xmlns:${ns}=\"${escapeXml(DocumentAttributeNamespaces[ns])}\"`);\n }\n // mc:Ignorable must declare the ignorable namespaces (w14/w15/wp14) that\n // header/footer content uses (e.g. w14:paraId). Without it, Word in\n // compatibility mode 14 rejects the part as unreadable content.\n attrParts.push('mc:Ignorable=\"w14 w15 wp14\"');\n const attrStr = attrParts.join(\" \");\n\n const childParts: string[] = [];\n for (const child of children) {\n childParts.push(stringifyBodyChild(child, ctx));\n }\n\n const body = childParts.join(\"\");\n return body.length === 0 ? `<${tag} ${attrStr}/>` : `<${tag} ${attrStr}>${body}</${tag}>`;\n}\n","/**\n * DOCX document compiler — pure function entry point.\n *\n * compileDocument() accepts DocumentOptions directly,\n * creates a DocxWriteContext internally, and produces a Zippable result.\n * All XML parts are produced via descriptors or serialize() —\n * no Formatter dependency.\n *\n * @module\n */\n\nimport {\n addBinaryFile,\n addSmartArtRelationships,\n compileMapping,\n contentTypesDesc,\n createThemeXml,\n deriveContentTypes,\n DOCX_PARTS,\n findAndReplaceImagePlaceholders,\n formatId,\n hasPlaceholders,\n optionalRelsPart,\n replaceAllPlaceholders,\n replaceNumberingPlaceholders,\n IMAGE_MEDIA_CONTENT_TYPES,\n resolverFromRegistry,\n toUint8Array,\n} from \"@office-open/core\";\nimport type { XmlifyedFile, Zippable } from \"@office-open/core\";\nimport {\n DEFAULT_DRAWING_XML,\n getColorXml,\n getLayoutXml,\n getStyleXml,\n stringifyColorDefinitionPart,\n stringifyLayoutDefinitionPart,\n stringifyStyleDefinitionPart,\n} from \"@office-open/core/smartart\";\nimport { OOXML_XML_DECLARATION } from \"@office-open/xml\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { obfuscate } from \"@parts/fonts/obfuscate-ttf-to-odttf\";\nimport { HEADER_NAMESPACES, FOOTER_NAMESPACES, stringifyHeaderFooter } from \"@parts/header-footer\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\n\nimport { stringifyDocumentXml, stringifyBodyChild, type BodyContext } from \"./body\";\nimport { DocxWriteContext } from \"./context\";\nimport {\n corePropertiesDesc,\n customPropertiesDesc,\n appPropertiesDesc,\n fontTableDesc,\n webSettingsDesc,\n commentsDesc,\n bibliographyDesc,\n settingsDesc,\n footnotesDesc,\n endnotesDesc,\n glossaryDesc,\n} from \"./parts\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\n/** XML declaration prepended to every OOXML part. */\nconst XML_DECL = OOXML_XML_DECLARATION;\n\n/** DOCX part path → content type, derived from the part registry. */\nconst DOCX_CONTENT_TYPE_RESOLVER = resolverFromRegistry(DOCX_PARTS);\n\n/** Extension → MIME for media/font/embedding Default entries. Declared only\n * for extensions actually present in the package. */\nconst DOCX_MEDIA_CONTENT_TYPES: Record<string, string> = {\n ...IMAGE_MEDIA_CONTENT_TYPES,\n odttf: \"application/vnd.openxmlformats-officedocument.obfuscatedFont\",\n bin: \"application/vnd.openxmlformats-officedocument.oleObject\",\n};\n\n/** Extended context for header/footer formatted view caching. */\ntype DocxContext = BodyContext & {\n headerFormattedViews?: Map<number, string>;\n footerFormattedViews?: Map<number, string>;\n};\n\n// ── Public API ──\n\n/**\n * Compile document options into a flat file map suitable for fflate zipSync.\n *\n * This is the primary entry point for DOCX generation — accepts DocumentOptions\n * directly.\n */\nexport function compileDocument(\n options: DocumentOptions,\n overrides: XmlifyedFile[] = [],\n mediaLevel: number = 0,\n): Zippable {\n const ctx = new DocxWriteContext(options);\n const headerFormattedViews = new Map<number, string>();\n const footerFormattedViews = new Map<number, string>();\n\n const xmlifiedFileMapping = xmlifyContext(ctx, headerFormattedViews, footerFormattedViews);\n const files = compileMapping(xmlifiedFileMapping, overrides);\n\n // Media files\n const mediaArray = ctx.media.array;\n for (const mediaData of mediaArray) {\n addBinaryFile(files, `word/media/${mediaData.fileName}`, mediaData.data, mediaLevel);\n if (mediaData.type === \"svg\") {\n addBinaryFile(\n files,\n `word/media/${mediaData.fallback.fileName}`,\n mediaData.fallback.data,\n mediaLevel,\n );\n }\n }\n\n // OLE embedding binaries (word/embeddings/oleObjectN.bin)\n for (const embedding of ctx.embeddings.array) {\n addBinaryFile(files, `word/embeddings/${embedding.fileName}`, embedding.data, mediaLevel);\n }\n\n // Font files — only fonts carrying binary data produce a .odttf part.\n // Round-tripped fonts (rawOdttf) keep their original obfuscated bytes.\n for (const font of ctx.fontTable.fontOptionsWithKey) {\n if (font.data === undefined) continue;\n const [nameWithoutExtension] = font.name.split(\".\");\n const filePath = font.odttfPath ?? `word/fonts/${nameWithoutExtension}.odttf`;\n files[filePath] = font.rawOdttf ? font.data : obfuscate(font.data, font.fontKey);\n }\n\n // Raw passthrough parts (word/theme/*, customXml/*, …) — generate doesn't\n // rebuild these, so copy their original bytes verbatim to keep [Content_Types]\n // declarations valid and the package openable in Word.\n for (const part of ctx._options.rawParts ?? []) {\n files[part.path] = toUint8Array(part.data);\n }\n\n // [Content_Types].xml is serialized last: parts register their media/fonts\n // during stringify (run by xmlifyContext above), so backfilling <Default>\n // extensions from `ctx` now sees the complete set. Building it inside\n // xmlifyContext's object literal evaluated it before header/footer/font media\n // was registered, leaving jpg/gif/odttf without a covering Default.\n files[\"[Content_Types].xml\"] = encoder.encode(buildContentTypesData(ctx, files));\n\n return files;\n}\n\n// ── Internal ──\n\n/**\n * Complete mapping of all XML files in an OOXML document package.\n */\ninterface XmlifyedFileMapping {\n Document: XmlifyedFile;\n Styles: XmlifyedFile;\n Properties: XmlifyedFile;\n Numbering?: XmlifyedFile;\n Relationships: XmlifyedFile;\n FileRelationships: XmlifyedFile;\n Headers: XmlifyedFile[];\n Footers: XmlifyedFile[];\n HeaderRelationships: XmlifyedFile[];\n FooterRelationships: XmlifyedFile[];\n CustomProperties: XmlifyedFile;\n AppProperties: XmlifyedFile;\n FootNotes?: XmlifyedFile;\n FootNotesRelationships?: XmlifyedFile;\n Endnotes?: XmlifyedFile;\n EndnotesRelationships?: XmlifyedFile;\n Settings: XmlifyedFile;\n Comments?: XmlifyedFile;\n CommentsRelationships?: XmlifyedFile;\n FontTable?: XmlifyedFile;\n FontTableRelationships?: XmlifyedFile;\n Bibliography?: XmlifyedFile;\n Charts?: XmlifyedFile[];\n DiagramData?: XmlifyedFile[];\n DiagramLayout?: XmlifyedFile[];\n DiagramStyle?: XmlifyedFile[];\n DiagramColors?: XmlifyedFile[];\n DiagramDrawing?: XmlifyedFile[];\n AltChunks?: XmlifyedFile[];\n SubDocs?: XmlifyedFile[];\n Glossary?: XmlifyedFile;\n WebSettings?: XmlifyedFile;\n}\n\n/**\n * Comments carried by the document: those the caller listed explicitly\n * (`options.comments`) plus entries registered by `{ comment }` sugar children\n * during body stringification. Drives both word/comments.xml generation and the\n * [Content_Types] comments Override, which must stay in sync (OPC consistency).\n */\nfunction mergedCommentChildren(ctx: DocxWriteContext): CommentOptions[] {\n return [...(ctx._options.comments?.children ?? []), ...ctx.comments.entries];\n}\n\n/**\n * Serialize [Content_Types].xml from the part registry, then backfill media/\n * font/embedding `<Default>` entries from the parts actually written.\n *\n * Must run after every part has been stringified (parts call `ctx.addMedia`\n * during stringify), so call this once `xmlifyContext` has finished — not from\n * inside its object literal, where ContentTypes would evaluate before the\n * later-defined header/footer/font parts have registered their media.\n */\n/**\n * Derive [Content_Types].xml from the parts actually written to the package.\n *\n * The file set is the single source of truth: every part the resolver knows\n * becomes an Override, every other file falls through to an extension Default,\n * and altChunk/sub-document parts — whose content type is data-driven, not\n * path-determinable — are injected as explicit overrides.\n *\n * Round-trip no longer passes the source [Content_Types] through: the compiler\n * regenerates every part path (altChunks get a fresh uniqueId), so deriving\n * from the written files is what keeps declarations and parts in sync.\n */\nfunction buildContentTypesData(ctx: DocxWriteContext, files: Zippable): string {\n const overrides = [\n ...ctx.altChunks.array.map((ac) => ({\n path: `word/${ac.path}`,\n contentType: ac.contentType ?? \"application/xhtml+xml\",\n })),\n ...ctx.subDocs.array.map((sd) => ({\n path: `word/${sd.path}`,\n contentType:\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\",\n })),\n ];\n const input = deriveContentTypes(Object.keys(files), {\n resolve: DOCX_CONTENT_TYPE_RESOLVER,\n mediaContentTypes: DOCX_MEDIA_CONTENT_TYPES,\n overrides,\n });\n return XML_DECL + (contentTypesDesc.stringify(input, ctx) ?? \"\");\n}\n\nfunction xmlifyContext(\n ctx: DocxWriteContext,\n headerFormattedViews: Map<number, string>,\n footerFormattedViews: Map<number, string>,\n): XmlifyedFileMapping {\n const mkCtx = (viewWrapper: DocxContext[\"viewWrapper\"] = ctx.document): DocxContext => {\n const bodyCtx: DocxContext = {\n fileData: ctx,\n file: ctx,\n viewWrapper,\n addRelationship: (type: string, target: string, mode?: string) =>\n ctx.addRelationship(type, target, mode),\n addMedia: (data: Uint8Array, type: string) => ctx.addMedia(data, type),\n addHyperlink: (key, target) => ctx.addHyperlink(key, target),\n // Assigned after the literal: stringifyBodyChild needs this context, which\n // is only bound once the literal finishes initializing.\n stringifyChild: undefined as unknown as DocxContext[\"stringifyChild\"],\n };\n bodyCtx.stringifyChild = (child) => stringifyBodyChild(child, bodyCtx);\n return bodyCtx;\n };\n\n const documentRelationshipCount = ctx.document.relationships.relationshipCount + 1;\n // Per-part media-replacement results shared between the .rels pass and the\n // body-XML pass so both use identical rId offsets. Each header/footer part\n // has its own relationship numbering (independent of the document part).\n const footerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const headerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const docCtx = mkCtx(ctx.document);\n const documentXmlData = XML_DECL + stringifyDocumentXml(ctx, docCtx);\n\n // Comments is an optional part — skip it entirely (no comments.xml, no\n // comments rels, no [Content_Types] Override) when the document carries none.\n // Emitting an empty comments.xml with a dangling relationship is the OPC\n // violation that makes Word reject the package on open.\n const mergedCommentChildrenList = mergedCommentChildren(ctx);\n const hasComments = mergedCommentChildrenList.length > 0;\n const commentRelationshipCount = hasComments\n ? ctx.comments.relationships.relationshipCount + 1\n : 0;\n const commentCtx = hasComments ? mkCtx({ relationships: ctx.comments.relationships }) : null;\n const commentXmlData = commentCtx\n ? XML_DECL + commentsDesc.stringify({ children: mergedCommentChildrenList }, commentCtx)\n : \"\";\n\n const footnoteRelationshipCount = ctx.footNotes.relationships.relationshipCount + 1;\n const footnoteCtx = mkCtx({\n relationships: ctx.footNotes.relationships,\n });\n const footnoteXmlData =\n XML_DECL +\n (footnotesDesc.stringify(\n {\n notes: ctx.footNotes.notes,\n separator: ctx.footNotes.separator,\n continuationSeparator: ctx.footNotes.continuationSeparator,\n },\n footnoteCtx,\n ) ?? \"\");\n\n const documentMedia = findAndReplaceImagePlaceholders(\n documentXmlData,\n ctx.media.array,\n documentRelationshipCount,\n );\n // OLE embeddings reuse the same {fileName} placeholder bridge as images; run\n // after media so {oleObjectN.bin} placeholders resolve against the embedding array.\n const documentEmbeddingOffset = documentRelationshipCount + documentMedia.referenced.length;\n const documentEmbeddings = findAndReplaceImagePlaceholders(\n documentMedia.xml,\n ctx.embeddings.array,\n documentEmbeddingOffset,\n );\n const commentMedia = hasComments\n ? findAndReplaceImagePlaceholders(commentXmlData, ctx.media.array, commentRelationshipCount)\n : { xml: \"\", referenced: [] as { fileName: string }[] };\n const footnoteMedia = findAndReplaceImagePlaceholders(\n footnoteXmlData,\n ctx.media.array,\n footnoteRelationshipCount,\n );\n // Register footnote media relationships eagerly so the relationshipCount used\n // to gate footnotes.xml.rels reflects the final state (see FootNotesRelationships).\n for (const [i, ref] of footnoteMedia.referenced.entries()) {\n ctx.footNotes.relationships.addRelationship(\n footnoteRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return {\n AppProperties: {\n data: XML_DECL + (appPropertiesDesc.stringify(ctx._options.appProperties ?? {}, ctx) ?? \"\"),\n path: \"docProps/app.xml\",\n },\n ...(hasComments\n ? {\n Comments: {\n data: (() => {\n const xmlData =\n commentMedia.referenced.length > 0 ? commentMedia.xml : commentXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/comments.xml\",\n },\n CommentsRelationships: (() => {\n for (const [i, ref] of commentMedia.referenced.entries()) {\n ctx.comments.relationships.addRelationship(\n commentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n return optionalRelsPart(\n ctx.comments.relationships,\n XML_DECL,\n \"word/_rels/comments.xml.rels\",\n );\n })(),\n }\n : {}),\n CustomProperties: {\n data:\n XML_DECL +\n (customPropertiesDesc.stringify({ properties: ctx._options.customProperties ?? [] }, ctx) ??\n \"\"),\n path: \"docProps/custom.xml\",\n },\n Document: {\n data: (() => {\n let xmlData = documentEmbeddings.xml;\n if (hasPlaceholders(xmlData)) {\n const mediaCount = documentMedia.referenced.length;\n const embeddingCount = documentEmbeddings.referenced.length;\n const chartKeys = ctx.charts.array.map((c) => c.key);\n const smartArtKeys = ctx.smartArts.array.map((s) => s.key);\n const chartOffset = documentRelationshipCount + mediaCount + embeddingCount;\n const smartArtOffset = chartOffset + chartKeys.length;\n\n // Build combined replacement entries for charts, smartart, and numbering\n const entries: Array<{ prefix?: string; key: string; value: string }> = [];\n for (const [i, key] of chartKeys.entries()) {\n entries.push({\n prefix: \"chart:\",\n key,\n value: formatId(chartOffset, i, \"rId\"),\n });\n }\n const saPrefixes = [\"smartart:\", \"smartart-lo:\", \"smartart-qs:\", \"smartart-cs:\"];\n for (const [i, key] of smartArtKeys.entries()) {\n for (let p = 0; p < saPrefixes.length; p++) {\n entries.push({\n prefix: saPrefixes[p],\n key,\n value: formatId(smartArtOffset + p * smartArtKeys.length, i, \"rId\"),\n });\n }\n }\n for (const { reference, instance, numId } of ctx.numbering.concreteNumbering) {\n entries.push({ key: `${reference}-${instance}`, value: numId.toString() });\n }\n xmlData = replaceAllPlaceholders(xmlData, entries);\n } else {\n xmlData = replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n }\n return xmlData;\n })(),\n path: \"word/document.xml\",\n },\n // Theme — fresh-compile emits a language-neutral default theme\n // (createThemeXml). Round-trip carries the source theme in rawParts,\n // already copied verbatim above, so skip emitting here to avoid a duplicate.\n ...(ctx._options.rawParts?.some((part) => part.path.startsWith(\"word/theme/\"))\n ? {}\n : {\n Theme: {\n data: XML_DECL + createThemeXml(),\n path: \"word/theme/theme1.xml\",\n },\n }),\n ...(ctx.hasEndnotes\n ? {\n Endnotes: {\n data: (() => {\n const endnoteCtx = mkCtx({\n relationships: ctx.endnotes.relationships,\n });\n const xmlData =\n XML_DECL +\n (endnotesDesc.stringify(\n {\n notes: ctx.endnotes.notes,\n separator: ctx.endnotes.separator,\n continuationSeparator: ctx.endnotes.continuationSeparator,\n },\n endnoteCtx,\n ) ?? \"\");\n const endnoteRelCount = ctx.endnotes.relationships.relationshipCount + 1;\n const endnoteMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n endnoteRelCount,\n );\n if (endnoteMedia.referenced.length > 0) {\n for (const [i, ref] of endnoteMedia.referenced.entries()) {\n ctx.endnotes.relationships.addRelationship(\n endnoteRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n return replaceNumberingPlaceholders(\n endnoteMedia.xml,\n ctx.numbering.concreteNumbering,\n );\n }\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/endnotes.xml\",\n },\n EndnotesRelationships:\n ctx.endnotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.endnotes.relationships.serialize(),\n path: \"word/_rels/endnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FileRelationships: {\n data: XML_DECL + ctx.fileRelationships.serialize(),\n path: \"_rels/.rels\",\n },\n FontTable: {\n data:\n XML_DECL +\n (fontTableDesc.stringify({ fonts: ctx.fontTable.fontOptionsWithKey }, ctx) ?? \"\"),\n path: \"word/fontTable.xml\",\n },\n FontTableRelationships: optionalRelsPart(\n ctx.fontTable.relationships,\n XML_DECL,\n \"word/_rels/fontTable.xml.rels\",\n ),\n ...(ctx.hasFootnotes\n ? {\n FootNotes: {\n data: (() => {\n const xmlData =\n footnoteMedia.referenced.length > 0 ? footnoteMedia.xml : footnoteXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/footnotes.xml\",\n },\n FootNotesRelationships:\n ctx.footNotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.footNotes.relationships.serialize(),\n path: \"word/_rels/footnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FooterRelationships: ctx.footers\n .map((entry, index) => {\n const footerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:ftr\", FOOTER_NAMESPACES, entry.children, footerCtx);\n footerFormattedViews.set(index, xmlData);\n // Footer images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const footerRelCount = entry.relationships.relationshipCount + 1;\n const footerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n footerRelCount,\n );\n footerMediaResults.set(index, footerMedia);\n\n for (const [i, ref] of footerMedia.referenced.entries()) {\n entry.relationships.addRelationship(\n footerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/footer${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Footers: ctx.footers.map((_entry, index) => {\n const footerMedia = footerMediaResults.get(index)!;\n const tempXmlData = footerFormattedViews.get(index)!;\n const xmlData = footerMedia.referenced.length > 0 ? footerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/footer${index + 1}.xml`,\n };\n }),\n HeaderRelationships: ctx.headers\n .map((entry, index) => {\n const headerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:hdr\", HEADER_NAMESPACES, entry.children, headerCtx);\n headerFormattedViews.set(index, xmlData);\n // Header images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const headerRelCount = entry.relationships.relationshipCount + 1;\n const headerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n headerRelCount,\n );\n headerMediaResults.set(index, headerMedia);\n\n for (const [i, ref] of headerMedia.referenced.entries()) {\n entry.relationships.addRelationship(\n headerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/header${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Headers: ctx.headers.map((_entry, index) => {\n const headerMedia = headerMediaResults.get(index)!;\n const tempXmlData = headerFormattedViews.get(index)!;\n const xmlData = headerMedia.referenced.length > 0 ? headerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/header${index + 1}.xml`,\n };\n }),\n ...(ctx.hasNumbering\n ? {\n Numbering: {\n data: ctx.numbering.serialize(),\n path: \"word/numbering.xml\",\n },\n }\n : {}),\n Properties: {\n data: XML_DECL + (corePropertiesDesc.stringify(ctx._options, ctx) ?? \"\"),\n path: \"docProps/core.xml\",\n },\n Relationships: {\n data: (() => {\n for (const [i, ref] of documentMedia.referenced.entries()) {\n ctx.document.relationships.addRelationship(\n documentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${ref.fileName}`,\n );\n }\n for (const [i, ref] of documentEmbeddings.referenced.entries()) {\n ctx.document.relationships.addRelationship(\n documentEmbeddingOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject\",\n `embeddings/${ref.fileName}`,\n );\n }\n\n const chartOffset =\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length;\n for (let i = 0; i < ctx.charts.array.length; i++) {\n ctx.document.relationships.addRelationship(\n chartOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `charts/chart${i + 1}.xml`,\n );\n }\n\n addSmartArtRelationships(\n ctx.smartArts.array.map((s) => s.key),\n (id, type, target) => {\n ctx.document.relationships.addRelationship(id, type, target);\n },\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length +\n ctx.charts.array.length,\n 0,\n {\n pathPrefix: \"\",\n styleRelType: \"http://schemas.microsoft.com/office/2007/relationships/diagramStyle\",\n },\n );\n\n ctx.document.relationships.addRelationship(\n ctx.document.relationships.relationshipCount + 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable\",\n \"fontTable.xml\",\n );\n\n return XML_DECL + ctx.document.relationships.serialize();\n })(),\n path: \"word/_rels/document.xml.rels\",\n },\n Settings: {\n data: XML_DECL + (settingsDesc.stringify(ctx._settingsOptions, ctx) ?? \"\"),\n path: \"word/settings.xml\",\n },\n Styles: {\n data: (() => {\n const xmlStyles = ctx.styles.serialize();\n return replaceNumberingPlaceholders(xmlStyles, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/styles.xml\",\n },\n ...(ctx._options.bibliography\n ? {\n Bibliography: {\n data: XML_DECL + (bibliographyDesc.stringify(ctx._options.bibliography, ctx) ?? \"\"),\n path: \"word/bibliography.xml\",\n },\n }\n : {}),\n ...(ctx.charts.array.length > 0\n ? {\n Charts: ctx.charts.array.map((chartData, i) => ({\n data: XML_DECL + chartData.chartSpaceXml,\n path: `word/charts/chart${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.smartArts.array.length > 0\n ? {\n DiagramData: ctx.smartArts.array.map((smartArtData, i) => ({\n data: XML_DECL + smartArtData.dataModelXml,\n path: `word/diagrams/data${i + 1}.xml`,\n })),\n DiagramLayout: ctx.smartArts.array.map((smartArtData, i) => ({\n data:\n typeof smartArtData.layout === \"string\"\n ? getLayoutXml(smartArtData.layout)\n : stringifyLayoutDefinitionPart(smartArtData.layout),\n path: `word/diagrams/layout${i + 1}.xml`,\n })),\n DiagramStyle: ctx.smartArts.array.map((smartArtData, i) => ({\n data:\n typeof smartArtData.style === \"string\"\n ? getStyleXml(smartArtData.style)\n : stringifyStyleDefinitionPart(smartArtData.style),\n path: `word/diagrams/quickStyle${i + 1}.xml`,\n })),\n DiagramColors: ctx.smartArts.array.map((smartArtData, i) => ({\n data:\n typeof smartArtData.color === \"string\"\n ? getColorXml(smartArtData.color)\n : stringifyColorDefinitionPart(smartArtData.color),\n path: `word/diagrams/colors${i + 1}.xml`,\n })),\n DiagramDrawing: ctx.smartArts.array.map((_, i) => ({\n data: DEFAULT_DRAWING_XML,\n path: `word/diagrams/drawing${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.altChunks.array.length > 0\n ? {\n AltChunks: ctx.altChunks.array.map((altChunkData) => ({\n data: altChunkData.data,\n path: `word/${altChunkData.path}`,\n })),\n }\n : {}),\n ...(ctx.subDocs.array.length > 0\n ? {\n SubDocs: ctx.subDocs.array.map((subDocData) => ({\n data: subDocData.data,\n path: `word/${subDocData.path}`,\n })),\n }\n : {}),\n ...(ctx.glossaryOptions\n ? {\n Glossary: {\n data: (() => {\n const glossaryCtx = mkCtx(undefined);\n return XML_DECL + (glossaryDesc.stringify(ctx.glossaryOptions!, glossaryCtx) ?? \"\");\n })(),\n path: \"word/glossary/document.xml\",\n },\n }\n : {}),\n ...(ctx.webSettings\n ? {\n WebSettings: {\n data: XML_DECL + (webSettingsDesc.stringify(ctx._options.webSettings ?? {}, ctx) ?? \"\"),\n path: \"word/webSettings.xml\",\n },\n }\n : {}),\n };\n}\n","/**\n * Pure function API for generating DOCX files.\n *\n * @module\n */\n\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\nimport type { OutputByType, OutputType, PackerOptions } from \"@office-open/core\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\n\nimport { compileDocument } from \"./compiler\";\n\n/** @internal Packer instance for DOCX generation. */\nconst Packer = createPacker<DocumentOptions>({\n compile: (options, overrides, mediaLevel) => compileDocument(options, overrides, mediaLevel),\n mimeType: OoxmlMimeType.DOCX,\n});\n\n/**\n * Generate a DOCX file from pure JSON options.\n *\n * The output format is controlled by `packerOptions.type` (default: `\"nodebuffer\"` → Buffer).\n * For synchronous generation, use {@link generateDocumentSync}. For streaming, use {@link generateDocumentStream}.\n *\n * @param options - Document options (sections, styles, numbering, etc.)\n * @param packerOptions - Optional packer configuration (type, compression, overrides, etc.)\n *\n * @example\n * ```typescript\n * import { generateDocument } from \"@office-open/docx\";\n *\n * const buffer = await generateDocument({ sections: [...] });\n * const bytes = await generateDocument({ sections: [...] }, { type: \"uint8array\" });\n * const blob = await generateDocument({ sections: [...] }, { type: \"blob\" });\n * ```\n */\nexport function generateDocument<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): Promise<OutputByType[T]> {\n return Packer.pack(options, packerOptions) as Promise<OutputByType[T]>;\n}\n\n/**\n * Synchronously generate a DOCX file from pure JSON options.\n */\nexport function generateDocumentSync<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): OutputByType[T] {\n return Packer.packSync(options, packerOptions) as OutputByType[T];\n}\n\n/**\n * Generate a DOCX file as a `ReadableStream<Uint8Array>`.\n */\nexport function generateDocumentStream(\n options: DocumentOptions,\n packerOptions?: PackerOptions,\n): ReadableStream<Uint8Array> {\n return Packer.toStream(options, packerOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,gBAAgB;;CAE3B,OAAO;;CAEP,QAAQ;;CAER,KAAK;;CAEL,MAAM;;CAEN,gBAAgB;;CAEhB,YAAY;;CAEZ,SAAS;;CAET,cAAc;;CAEd,aAAa;;CAEb,iBAAiB;;CAEjB,MAAM;;CAEN,OAAO;;CAEP,WAAW;AACb;;;;;;;;;;;;AC1DA,MAAa,YAAY;;CAEvB,QAAQ;;CAER,MAAM;AACR;;;;;;;;;;ACIA,MAAa,eAAe;;CAE1B,UAAU;;CAEV,SAAS;;CAET,OAAO;;CAEP,MAAM;AACR;;;;;;;;;;;;;;;;;ACdA,MAAa,eAAe;;CAE1B,WAAW;;CAEX,WAAW;;CAEX,WAAW;;CAEX,WAAW;;CAEX,WAAW;;CAEX,WAAW;;CAEX,OAAO;AACT;;;;;;;;;;ACGA,MAAa,cAAc;;CAEzB,MAAM;;CAEN,OAAO;;CAEP,QAAQ;;CAER,KAAK;;CAEL,OAAO;;CAEP,SAAS;;CAET,KAAK;;CAEL,KAAK;;CAEL,OAAO;AACT;;;;;;;;AASA,MAAa,aAAa;;CAExB,KAAK;;CAEL,OAAO;;CAEP,QAAQ;;CAER,YAAY;;CAEZ,MAAM;;CAEN,YAAY;AACd;;;;;;AAOA,MAAa,kBAAkB;;AAE7B,KAAK,KACP;;;;;;;;;;ACxDA,MAAa,oBAAoB;;CAE/B,KAAK;;CAEL,QAAQ;;CAER,UAAU;;CAEV,QAAQ;;CAER,MAAM;AACR;;;;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