Repository Public
1<!--2ORIX Docs3File: docs/architecture/docx.md4Description: Architecture of the DocDOCX target: files, data flow of import and export, the conventions that make round trips exact, and the security model.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# DOCX engine (`DocDOCX`)910`DocDOCX` converts between a WordprocessingML package and `DocumentModel`. It depends on `DocModel` and `DocContainer`11(ZIP reader / writer, `FormatWarning`, `ImportResult`, `ExportResult`, `FormatError`) and on Foundation only.1213## Public API1415```swift16public enum DocxImporter {17 public static func importDocument(_ data: Data, limits: ZipLimits = .standard) throws -> ImportResult18}19public struct DocxExportOptions: Sendable {20 public var citations: (any CitationFormatting)?21 public var pageOf: (@Sendable (String) -> String?)?22 public var pageCount: Int?23 public init()24}25public enum DocxExporter {26 public static func export(_ doc: DocumentModel, options: DocxExportOptions = .init()) throws -> ExportResult27 public static func preflight(_ doc: DocumentModel) -> [FormatWarning]28}29public enum MathConverter {30 public static func omml(fromLatex latex: String) -> String?31 public static func latex(fromOMML xml: String) -> String?32 public static func mathML(fromLatex latex: String, display: Bool) -> String?33}34```3536Errors are `FormatError` (`unreadable`, `tooLarge`, `integrityCheckFailed`); archive errors are mapped to it.37`preflight` runs the exporter without keeping its output and returns its warnings, most severe first, so what the user is38told before exporting is exactly what the export would report.3940## Files4142| File | Role |43|---|---|44| `XML.swift` | `XMLNode` tree, `XMLTree.parse` (Foundation `XMLParser`, no DTD, size / depth / node limits, namespace prefixes canonicalised from their URI, strict namespaces included), `XMLEscape`, `xmlTag` |45| `DocxCommon.swift` | units, colours, dates, relationship and content types, OPC path resolution, media sniffing, shared conventions (`DocxConvention`), the ORIX extras payload, `DocxStack` |46| `DocxImporter.swift` | entry point, package level: main part, theme fonts, extras, settings, core properties, classification of every remaining part (preserved / dropped with a named warning) |47| `DocxImportStyles.swift` | `rPr` / `pPr` → `CharProps` / `ParaProps`, `styles.xml`, table styles, `numbering.xml`, `sectPr` → `PageSetup` |48| `DocxImportBody.swift` | stories, blocks, paragraphs, runs, tracked changes, comment ranges, bookmarks, hyperlinks, the field state machine, notes, comments, headers / footers |49| `DocxImportObjects.swift` | tables, DrawingML pictures and shapes, text boxes, VML |50| `DocxExporter.swift` | entry point, package assembly, styles, numbering, settings, core properties, sections, headers / footers |51| `DocxExportBody.swift` | `rPr` / `pPr` writers, paragraphs, runs, fields, drawings, tables, generated blocks, notes, comments |52| `MathConverter.swift`, `MathOMML.swift`, `MathMLWriter.swift` | LaTeX parser and tree, tree ↔ OMML, tree → presentation MathML |5354## Import55561. `ZipReader` opens the archive under the caller's `ZipLimits`. `[Content_Types].xml` and the package relationships locate the main part (`.docx`, `.docm` and `.dotx` main parts are all accepted; macros are reported and ignored).572. Theme fonts are read from the theme part (which itself stays a preserved part). The ORIX extras part, if any, restores the bibliography database and document settings.583. `settings.xml`, `styles.xml`, `numbering.xml`, notes and comments parts are parsed into lookup tables. Style ids are mapped to the model's built-in ids through the Word style *name* (`heading 1` → `Heading1`), so localised documents keep their semantics.594. The body is walked once. A `DocxStory` holds the state that spans paragraphs (open comment ranges, the field stack, open bookmarks); a `DocxParaBuilder` holds one paragraph. Notes are imported when their reference is met; headers and footers when a `sectPr` refers to them.605. Sections are resolved after the walk (see below), cross-reference displays are fixed up once all bookmarks are known, core properties are read, and every part that was not interpreted is either preserved or reported.6162### Fields6364Complex fields (`w:fldChar` begin / separate / end) and `w:fldSimple` feed one state machine. At `separate` the instruction is65classified: fields the model knows become an inline object and their cached result is suppressed; `HYPERLINK` keeps its66result and marks it as a link; `TOC` becomes one `TOCBlock` and swallows its cached paragraphs; a table formula goes to the67cell; anything else keeps its displayed text and raises a warning. Nested fields are handled by the stack; a field that would68be replaced by an inline object is closed at the end of its paragraph even if its `end` mark is missing.6970### Sections7172Word stores the properties of a section in the last paragraph of that section and the last section's at the end of the body.73The model stores `pageSetup` for the first section and, on each `.sectionBreak`, the setup of the section that *starts* there.74On import the `sectPr` elements are collected in order (`S0 … Sn`); `pageSetup = S0`, and the break placed after the paragraph75that carried `Si` receives `S(i+1)` together with its `w:type` (which says how section `i+1` starts). Headers and footers a76section does not declare are copied from the previous section (new paragraph ids). On export the mapping is inverted: the77paragraph before a break carries the `sectPr` of the section it ends; when no paragraph is there, an empty one is written.7879## Export8081`DocxExportContext.prepare()` computes what must be known before the first paragraph: numbering ids, the first and last run of82every comment (comment ranges), and which paragraphs are cross-reference targets. The body is written first because it decides83which notes, pictures, table styles and header parts exist; then notes, comments, styles, numbering, settings, properties,84preserved parts and the extras part. Element order follows the ECMA-376 schema sequences (`pPr`, `rPr`, `tblPr`, `tcPr`,85`sectPr`, `settings`, `style`, `lvl`). The ZIP writer uses a fixed timestamp, so the same model and options give the same bytes86(except for `DATE` fields, whose cached text is today's date).8788## Conventions that make the round trip exact8990| Convention | Why |91|---|---|92| Hidden bookmarks `_ORIX_T_<id>`, `_ORIX_L_<id>`, `_ORIX_N_<id>` | A `CrossRef` targets a paragraph id. The bookmark covers the whole paragraph (T), the label and number of a caption (L) or the number alone (N), so Word's own REF field shows the right text, and the importer gives the paragraph its id back |93| Field `ADDIN ORIX_CITATION {json}` | Keeps the full `Citation`; Word shows the cached text and never rewrites an ADDIN field |94| Custom XML data part, root `orix:document` | Bibliography database, citation style, smart-typing settings, theme name |95| Content control tagged `ORIX_BIBLIOGRAPHY` (title in `w:alias`) | Marks the generated bibliography so it is not reimported as text |96| Table styles `ORIXTable<n>` | Carry `TableStyle` (borders, padding, header and band shading) as real Word table styles |97| Hidden one-point paragraph after a table | Word merges adjacent tables and needs a paragraph at the end of the document; the importer recognises and removes it |98| `w:aliases` on built-in styles | Word sees `heading 1`; the ORIX display name comes back |99| Superscript on note reference runs | The model draws note marks itself; the importer strips the superscript and the reference style Word puts there |100101Identifiers of paragraphs, tables, lists, notes, comments and revisions are regenerated on import (`DocID.make()`); image102assets are identified by content (`img<crc><size>`), which also deduplicates them. Tests compare models with identifiers103normalised by order of appearance (`normalized(_:)` in `TestSupport.swift`).104105## Security model106107* Input is hostile. Limits: `ZipLimits` for the archive; `XMLLimits` for each part (96 MB, depth 256, 4 million elements); custom XML and extras payloads are size-capped before parsing.108* `XMLTree.parse` refuses any part that contains `<!DOCTYPE` or `<!ENTITY` (after transcoding UTF-16), and sets `shouldResolveExternalEntities = false`. OOXML never needs a DTD.109* `OPC.resolve` maps a relationship target to a part name inside the archive, or to nil. Nothing is read from the file system or the network: external targets are strings.110* Macro, OLE and ActiveX parts are never interpreted and never put in `preservedParts`. Preservation is an allow-list of part names, each part must be well-formed XML, and its relationships must stay inside the preserved set. The exporter re-validates `preservedParts`, because a model can also come from an untrusted `.orixdoc`.111* Numbers read from XML are range-checked before conversion; numbers written from the model go through `DocxUnit.safeInt`.112* Recursion depth is bounded by the XML depth limit, and the work runs on a 32 MB stack (`DocxStack`).113114## Testing115116See `docs/compatibility/docx.md` for what is validated against which tool, and `docs/reports/docx-compatibility.md` for the117measured results. `Scripts/docx-compat.sh` regenerates the report.118119```120cd Packages/ORIXDocsKit121ORIX_ONLY=DocModel,DocContainer,DocDOCX,DocDOCXTests swift test --scratch-path /tmp/orixdocs-docx122ORIX_SLOW_TESTS=1 ORIX_ONLY=DocModel,DocContainer,DocDOCX,DocDOCXTests swift test --scratch-path /tmp/orixdocs-docx # adds LibreOffice123```124