@stll/docx-core 0.22.0 → 0.24.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.
@@ -59,7 +59,9 @@ const PARSE_WARNING_CODES = {
59
59
  /** A style set defining two styles under one id. */
60
60
  styleSetDuplicateStyleId: "style-set-duplicate-style-id",
61
61
  /** A style set naming an initial paragraph style it does not contain. */
62
- styleSetInitialStyleMissing: "style-set-initial-style-missing"
62
+ styleSetInitialStyleMissing: "style-set-initial-style-missing",
63
+ /** An explicit page-break run the editable model lays out approximately. */
64
+ pageBreakProjectionApproximated: "page-break-projection-approximated"
63
65
  };
64
66
  /**
65
67
  * The cap on retained warnings per code.
@@ -735,6 +735,72 @@ type NumberingDefinitions = {
735
735
  nums: NumberingInstance[];
736
736
  };
737
737
  //#endregion
738
+ //#region src/model/preservedMarkup.d.ts
739
+ /**
740
+ * The ordered verbatim sink: where a container's unmodelled markup goes.
741
+ *
742
+ * A parser that walks a container's children, models the ones it recognises
743
+ * and lets the rest fall off the end of a `switch` loses them silently, and
744
+ * verbatim replay hides the loss until somebody edits the document. The sink
745
+ * is the other branch of that `switch`. It keeps the markup as bytes together
746
+ * with **where it was**, so the serializer puts it back between the same
747
+ * modelled siblings rather than at the end of the container, which is what the
748
+ * schema's ordered content models require.
749
+ *
750
+ * The position is recorded as a count, not a pointer: `index` is how many
751
+ * modelled children the container had read when the markup arrived. That
752
+ * survives the model being edited — inserting a paragraph shifts what comes
753
+ * after it, which is what a reader would expect — and it needs no identity on
754
+ * the modelled children.
755
+ *
756
+ * One field, `preserved`, carries both halves for every container that has a
757
+ * sink, so a reader never has to know which of two names a given container
758
+ * used.
759
+ */
760
+ /** Markup the container's model does not hold, and where it sat. */
761
+ type PreservedChild = {
762
+ /**
763
+ * Modelled children that preceded this markup in the source. `0` puts it
764
+ * before the first modelled child; the container's modelled count puts it
765
+ * after the last.
766
+ */
767
+ index: number;
768
+ /** Replayable markup for one child, as `captureVerbatimXml` wrote it. */
769
+ xml: string;
770
+ };
771
+ /**
772
+ * A container's unmodelled markup. Absent means the parser read every child
773
+ * the source carried, which is the state a fully modelled container is in; an
774
+ * empty record is never written.
775
+ */
776
+ type PreservedMarkup = {
777
+ /** Ordered by `index`, then by source order within an index. */
778
+ children?: PreservedChild[];
779
+ };
780
+ /**
781
+ * One attribute an element carried that its parser has no field for.
782
+ *
783
+ * The remainder is a sibling of the child sink, not a member of it: an
784
+ * attribute has no position among children to keep, so it rides the element's
785
+ * own model record — `Paragraph.preservedAttributes` and its siblings — and
786
+ * the serializer writes it back into the same start tag.
787
+ *
788
+ * The name is resolved, never the source's spelling. folio reads an attribute
789
+ * by namespace URI plus local name, so a remainder that kept `"w:rsidR"`
790
+ * textually would keep a second copy of the `w:rsidR` a source spelled
791
+ * `altw:rsidR` under a second binding of the same URI. `namespace` is absent
792
+ * for an unprefixed attribute, which has none; a namespace declaration is not
793
+ * an attribute of the element in this sense and is never in the remainder,
794
+ * because the rebuilt part binds its own prefixes.
795
+ */
796
+ type PreservedAttribute = {
797
+ /** Resolved namespace URI, absent for an unprefixed attribute. */
798
+ namespace?: string;
799
+ /** Local name, without the prefix the source happened to bind. */
800
+ name: string;
801
+ value: string;
802
+ };
803
+ //#endregion
738
804
  //#region src/model/content.d.ts
739
805
  /**
740
806
  * Plain text content
@@ -794,9 +860,9 @@ type FieldCharContent = {
794
860
  type: "fieldChar";
795
861
  /** Field character type */
796
862
  charType: "begin" | "separate" | "end";
797
- /** Field is locked */
863
+ /** `@w:fldLock`: absent states nothing, `false` is an explicit unlock. */
798
864
  fldLock?: boolean;
799
- /** Field is dirty (needs update) */
865
+ /** `@w:dirty`: absent states nothing, `false` explicitly forbids a recompute. */
800
866
  dirty?: boolean;
801
867
  /**
802
868
  * Cached display value from a child `<w:numberingChange w:original="…"/>`.
@@ -831,6 +897,27 @@ type NoBreakHyphenContent = {
831
897
  type RenderedPageBreakContent = {
832
898
  type: "renderedPageBreak";
833
899
  };
900
+ /**
901
+ * A run child folio does not model, kept byte-for-byte at its source position.
902
+ *
903
+ * Dropping one is worse than a loss. The parser's keep rule asks the source
904
+ * element whether a run carried a payload while the serializer writes the
905
+ * model, so an unmodelled child makes the two disagree for exactly one save:
906
+ * save 1 writes a run with nothing in it, the next parse drops that run, and
907
+ * save 2 differs from save 1. Holding the markup in the model is what makes
908
+ * parse∘serialize a fixed point for the whole class at once.
909
+ */
910
+ type PreservedXmlContent = {
911
+ type: "preservedXml";
912
+ /** Replayable markup for one run child, as `captureVerbatimXml` wrote it. */
913
+ xml: string;
914
+ /**
915
+ * The visible text the markup contributes, empty when it shows nothing.
916
+ * `w:ruby` is the case that matters: its `w:rubyBase` is the text a reader
917
+ * sees, so text extraction, markdown and layout would otherwise lose a word.
918
+ */
919
+ text: string;
920
+ };
834
921
  /** Raw XML handling modes for drawings that Folio cannot model completely. */
835
922
  declare const DRAWING_RAW_XML_MODES: {
836
923
  readonly PRESERVE_ONLY: "preserveOnly";
@@ -878,7 +965,7 @@ type ShapeContent = {
878
965
  /**
879
966
  * All possible run content types
880
967
  */
881
- type RunContent = TextContent | TabContent | BreakContent | SymbolContent | NoteReferenceContent | FieldCharContent | InstrTextContent | SoftHyphenContent | NoBreakHyphenContent | RenderedPageBreakContent | DrawingContent | ShapeContent;
968
+ type RunContent = TextContent | TabContent | BreakContent | SymbolContent | NoteReferenceContent | FieldCharContent | InstrTextContent | SoftHyphenContent | NoBreakHyphenContent | RenderedPageBreakContent | PreservedXmlContent | DrawingContent | ShapeContent;
882
969
  /**
883
970
  * A run is a contiguous region of text with the same formatting
884
971
  */
@@ -890,6 +977,15 @@ type Run = {
890
977
  propertyChanges?: RunPropertyChange[];
891
978
  /** Run content (text, tabs, breaks, etc.) */
892
979
  content: RunContent[];
980
+ /**
981
+ * Attributes `w:r` carried that this record has no field for.
982
+ *
983
+ * `CT_R` declares `w:rsidR`, `w:rsidDel` and `w:rsidRPr`, and folio rebuilt
984
+ * every run without them. The remainder survives a save; the editor has no
985
+ * run record to carry it on, which the container contract states and the
986
+ * census records as `editorProjection`.
987
+ */
988
+ preservedAttributes?: PreservedAttribute[];
893
989
  };
894
990
  /**
895
991
  * Hyperlink (w:hyperlink)
@@ -910,8 +1006,17 @@ type Hyperlink = {
910
1006
  history?: boolean;
911
1007
  /** Document location */
912
1008
  docLocation?: string;
913
- /** Child runs */
914
- children: (Run | BookmarkStart | BookmarkEnd)[];
1009
+ /**
1010
+ * The link's content: runs, bookmark boundaries, and markup folio does not
1011
+ * model kept where the source put it.
1012
+ *
1013
+ * `CT_Hyperlink` is `EG_PContent`, so a link may hold a permission range, a
1014
+ * proofing error, a smart tag or a custom-XML revision range between its
1015
+ * runs. The capture is a member of this union rather than a sink beside it
1016
+ * for the reason `PreservedInline` gives: position inside the link is what
1017
+ * decides whether the markup goes with the link when the link moves.
1018
+ */
1019
+ children: (Run | BookmarkStart | BookmarkEnd | PreservedInline)[];
915
1020
  };
916
1021
  /**
917
1022
  * Which side of a `w:customXml` element a range marker was displaced to
@@ -977,11 +1082,15 @@ type SimpleField = {
977
1082
  instruction: string;
978
1083
  /** Parsed field type */
979
1084
  fieldType: FieldType;
980
- /** Current display value */
981
- content: (Run | Hyperlink)[];
982
- /** Field is locked */
1085
+ /**
1086
+ * The field's cached display, and any markup folio does not model between
1087
+ * the runs that carry it. `CT_SimpleField` is `EG_PContent` plus
1088
+ * `w:fldData`, so everything `EG_PContent` admits can sit here.
1089
+ */
1090
+ content: (Run | Hyperlink | PreservedInline)[];
1091
+ /** `@w:fldLock`: absent states nothing, `false` is an explicit unlock. */
983
1092
  fldLock?: boolean;
984
- /** Field is dirty */
1093
+ /** `@w:dirty`: absent states nothing, `false` explicitly forbids a recompute. */
985
1094
  dirty?: boolean;
986
1095
  };
987
1096
  /**
@@ -1004,9 +1113,9 @@ type ComplexField = {
1004
1113
  * formatting lives on the field run (eigenpal/docx-editor#909).
1005
1114
  */
1006
1115
  formatting?: TextFormatting;
1007
- /** Field is locked */
1116
+ /** `@w:fldLock`: absent states nothing, `false` is an explicit unlock. */
1008
1117
  fldLock?: boolean;
1009
- /** Field is dirty */
1118
+ /** `@w:dirty`: absent states nothing, `false` explicitly forbids a recompute. */
1010
1119
  dirty?: boolean;
1011
1120
  };
1012
1121
  type Field = SimpleField | ComplexField;
@@ -1158,8 +1267,26 @@ type Image = {
1158
1267
  * preserves the author's intent; undefined means "use the spec default".
1159
1268
  */
1160
1269
  allowOverlap?: boolean;
1161
- /** Whether this is a decorative image */
1270
+ /**
1271
+ * The image carries no information a reader needs, so assistive technology
1272
+ * skips it. Word writes this as an extension on `wp:docPr`
1273
+ * (`{C183D7F6-B498-43B3-948B-1728B52AA6E4}` holding
1274
+ * `adec:decorative val="1"`), not as an attribute: `CT_NonVisualDrawingProps`
1275
+ * has no `@decorative`.
1276
+ *
1277
+ * Not `hidden`. A decorative image is displayed and skipped by a screen
1278
+ * reader; a hidden one is not displayed at all.
1279
+ */
1162
1280
  decorative?: boolean;
1281
+ /** `wp:docPr @hidden`: the drawing is not displayed. */
1282
+ hidden?: boolean;
1283
+ /**
1284
+ * The `a:ext` entries of the `wp:docPr` extension list that folio does not
1285
+ * model — a creation id, a local-DPI hint — captured as XML in source order.
1286
+ * Written back beside the decorative extension so an extension folio has no
1287
+ * opinion about still survives a save.
1288
+ */
1289
+ docPrExtensions?: string[];
1163
1290
  /** Hyperlink URL for clickable image */
1164
1291
  hlinkHref?: string;
1165
1292
  /** Relationship ID for the clickable image hyperlink */
@@ -1280,8 +1407,12 @@ type Shape = {
1280
1407
  geometryAdjustments?: ShapeGeometryAdjustment[];
1281
1408
  /** Unique ID */
1282
1409
  id?: string;
1283
- /** Name */
1410
+ /** Authored non-visual drawing name (`wp:docPr@name` / `wps:cNvPr@name`) */
1284
1411
  name?: string;
1412
+ /** Alt text for accessibility (`wp:docPr@descr` / `wps:cNvPr@descr`) */
1413
+ alt?: string;
1414
+ /** Authored non-visual drawing title (`wp:docPr@title` / `wps:cNvPr@title`) */
1415
+ title?: string;
1285
1416
  /** Size in EMUs */
1286
1417
  size: ImageSize;
1287
1418
  /** Position for floating shapes */
@@ -1306,6 +1437,12 @@ type TextBox = {
1306
1437
  type: "textBox";
1307
1438
  /** Unique ID */
1308
1439
  id?: string;
1440
+ /** Authored non-visual drawing name (`wp:docPr@name` / `wps:cNvPr@name`) */
1441
+ name?: string;
1442
+ /** Alt text for accessibility (`wp:docPr@descr` / `wps:cNvPr@descr`) */
1443
+ alt?: string;
1444
+ /** Authored non-visual drawing title (`wp:docPr@title` / `wps:cNvPr@title`) */
1445
+ title?: string;
1309
1446
  /** Size */
1310
1447
  size: ImageSize;
1311
1448
  /** Position */
@@ -1347,8 +1484,16 @@ type TableCell = {
1347
1484
  propertyChanges?: TableCellPropertyChange[];
1348
1485
  /** Tracked structural changes (cell insert/delete/merge) */
1349
1486
  structuralChange?: TableStructuralChangeInfo;
1350
- /** Cell content (paragraphs, tables, etc.) */
1351
- content: (Paragraph | Table)[];
1487
+ /**
1488
+ * Cell content.
1489
+ *
1490
+ * Derived from {@link BlockContent} rather than listed, so a new block kind
1491
+ * cannot land without a decision here; `BlockSdt` is excluded because folio
1492
+ * unwraps a `w:sdt` inside a cell into its `sdtContent` children rather
1493
+ * than modelling the wrapper, and keeping the branch out of the cell keeps
1494
+ * the model's recursion out of every table.
1495
+ */
1496
+ content: TableCellBlock[];
1352
1497
  };
1353
1498
  /**
1354
1499
  * Table row
@@ -1363,6 +1508,25 @@ type TableRow = {
1363
1508
  structuralChange?: TableStructuralChangeInfo;
1364
1509
  /** Cells in this row */
1365
1510
  cells: TableCell[];
1511
+ /**
1512
+ * Row markup `cells` cannot hold, with its position among them.
1513
+ *
1514
+ * `CT_Row` declares a permission range, a proofing error, a custom-XML
1515
+ * revision range and the row-level move and comment ranges beside its
1516
+ * cells, and none of them is a cell. This is the sink case rather than the
1517
+ * union case the inline levels use: the row models one kind of child, so
1518
+ * there is no member to be, and `index` counts the cells that preceded the
1519
+ * capture.
1520
+ */
1521
+ preserved?: PreservedMarkup;
1522
+ /**
1523
+ * Attributes `w:tr` carried that this record has no field for.
1524
+ *
1525
+ * `CT_Row` declares `w:rsidR`, `w:rsidDel`, `w:rsidTr` and `w:rsidRPr`. The
1526
+ * remainder follows the record the same way a paragraph's does: a row the
1527
+ * editor creates has none, and a row split off another does not inherit one.
1528
+ */
1529
+ preservedAttributes?: PreservedAttribute[];
1366
1530
  };
1367
1531
  /**
1368
1532
  * Table (w:tbl)
@@ -1377,7 +1541,20 @@ type Table = {
1377
1541
  columnWidths?: number[];
1378
1542
  /** Table rows */
1379
1543
  rows: TableRow[];
1380
- } & BlockRangeMarkerCapture;
1544
+ /**
1545
+ * Table markup `rows` cannot hold, with its position among them.
1546
+ *
1547
+ * `CT_Tbl` declares a permission range, a proofing error, the table-level
1548
+ * comment and move ranges and the eight custom-XML revision ranges beside
1549
+ * `w:tr`, and none of them is a row. The row sink one level down has the
1550
+ * same shape for the same reason: the table models one kind of child, so
1551
+ * there is no union member to be, and `index` counts the rows that preceded
1552
+ * the capture. `w:tblPr` and `w:tblGrid` precede every row in the content
1553
+ * model and are read and written elsewhere, so they are not in the sink and
1554
+ * the index counts rows only.
1555
+ */
1556
+ preserved?: PreservedMarkup;
1557
+ };
1381
1558
  /**
1382
1559
  * A comment (w:comment) from comments.xml
1383
1560
  */
@@ -1398,6 +1575,14 @@ type Comment = {
1398
1575
  parentId?: number;
1399
1576
  /** Whether the comment is resolved/done */
1400
1577
  done?: boolean;
1578
+ /**
1579
+ * Body markup `content` cannot hold: a table, an equation, a content
1580
+ * control, a bookmark or range marker, a tracked-change wrapper. The
1581
+ * schema lets a comment body hold everything a document body can, and a
1582
+ * reviewer's words disappearing on save is not an acceptable simplification
1583
+ * of that.
1584
+ */
1585
+ preserved?: PreservedMarkup;
1401
1586
  };
1402
1587
  /**
1403
1588
  * Comment range start marker in paragraph content
@@ -1484,8 +1669,18 @@ type PropertyChangeInfo = {
1484
1669
  /** Optional revision session ID */
1485
1670
  rsid?: string;
1486
1671
  } & TrackedChangeInfo;
1487
- /** Inline content that may sit inside a run-level tracked-change wrapper. */
1488
- type TrackedRunContent = Run | Hyperlink | BookmarkStart | BookmarkEnd | SimpleField | ComplexField | MathEquation | TrackedRunChange;
1672
+ /**
1673
+ * Inline content that may sit inside a run-level tracked-change wrapper.
1674
+ *
1675
+ * The transparent wrappers belong here. A `w:bdo` / `w:dir` states how its
1676
+ * content is laid out and a `w:sdt` states what its content is bound to;
1677
+ * neither says anything about the revision, so a revision that holds one
1678
+ * holds it as content. Modelling it otherwise forces the parser to lift the
1679
+ * wrapper out to a sibling, which takes the wrapped text out of the revision
1680
+ * with it: the text is then neither inserted nor deleted, and accepting and
1681
+ * rejecting the revision both keep it.
1682
+ */
1683
+ type TrackedRunContent = Run | Hyperlink | BookmarkStart | BookmarkEnd | SimpleField | ComplexField | InlineSdt | InlineWrapper | MathEquation | PreservedInline | TrackedRunChange;
1489
1684
  /**
1490
1685
  * Insertion wrapper (w:ins) — runs inserted by tracked changes
1491
1686
  */
@@ -1543,15 +1738,19 @@ declare const BIDI_CONTROLS: {
1543
1738
  };
1544
1739
  type BidiControl = (typeof BIDI_CONTROLS)[keyof typeof BIDI_CONTROLS];
1545
1740
  /**
1546
- * A bidirectional embedding or override (w:dir, w:bdo) — ECMA-376 §17.3.2.8, §17.3.2.3.
1741
+ * A transparent inline wrapper, discriminated by what kind of wrapper it is.
1547
1742
  *
1548
- * A transparent inline wrapper: it changes how its content is laid out and
1549
- * nothing else, so it nests, it may hold anything paragraph content may hold,
1550
- * and dropping it changes what the reader sees rather than only what the file
1551
- * says.
1743
+ * Transparent means it says something about its content without constraining
1744
+ * it: it nests, it may hold anything paragraph content may hold, and dropping
1745
+ * it changes what the reader sees or what the markup states rather than what
1746
+ * the text is. `bidi` is the one kind folio parses today; a smart tag and a
1747
+ * custom-XML wrapper are the same shape and land with their parser.
1748
+ *
1749
+ * `bidi` is `w:dir` / `w:bdo` — ECMA-376 §17.3.2.8, §17.3.2.3.
1552
1750
  */
1553
- type BidiWrapper = {
1554
- type: "bidiWrapper";
1751
+ type InlineWrapper = {
1752
+ type: "inlineWrapper";
1753
+ kind: "bidi";
1555
1754
  control: BidiControl;
1556
1755
  /** `w:val`; absent in the source means the wrapper states no direction. */
1557
1756
  direction?: "ltr" | "rtl";
@@ -1762,16 +1961,16 @@ type SdtProperties = {
1762
1961
  * Inline SDT (content control within a paragraph).
1763
1962
  *
1764
1963
  * OOXML allows runs, hyperlinks, simple/complex fields, nested SDTs,
1765
- * tracked insertions/deletions/moves, and math at this level. All of them must survive
1766
- * parse → edit → save so docProps-bound fields and reviewed template
1767
- * content do not lose their wrapper on round-trip.
1964
+ * tracked insertions/deletions/moves, the bidirectional controls, and math at
1965
+ * this level. All of them must survive parse → edit → save so docProps-bound
1966
+ * fields and reviewed template content do not lose their wrapper on round-trip.
1768
1967
  */
1769
1968
  type InlineSdt = {
1770
1969
  type: "inlineSdt";
1771
1970
  /** SDT properties */
1772
1971
  properties: SdtProperties;
1773
1972
  /** Inline content held inside the control */
1774
- content: (Run | Hyperlink | SimpleField | ComplexField | InlineSdt | Insertion | Deletion | MoveFrom | MoveTo | MathEquation)[];
1973
+ content: (Run | Hyperlink | SimpleField | ComplexField | InlineSdt | InlineWrapper | Insertion | Deletion | MoveFrom | MoveTo | MathEquation | PreservedInline)[];
1775
1974
  };
1776
1975
  /**
1777
1976
  * Block-level SDT (content control wrapping paragraphs/tables).
@@ -1786,11 +1985,38 @@ type BlockSdt = {
1786
1985
  properties: SdtProperties;
1787
1986
  /** Block content inside the control. */
1788
1987
  content: BlockContent[];
1789
- } & BlockRangeMarkerCapture;
1988
+ };
1989
+ /**
1990
+ * Paragraph content types
1991
+ */
1992
+ /**
1993
+ * Inline-level markup folio does not model, kept at its source position.
1994
+ *
1995
+ * The run-level twin is `PreservedXmlContent` and the block-level one is
1996
+ * `PreservedBlock`; this is the level between them. A paragraph, a run-level
1997
+ * tracked-change wrapper, a bidirectional wrapper and an inline content
1998
+ * control all admit `w:permStart`, `w:proofErr`, `w:customXml` and the eight
1999
+ * custom-XML revision ranges, none of which is a run and none of which folio
2000
+ * models. Inside a tracked-change wrapper the position is the point: markup
2001
+ * lifted out of a `w:ins` is markup the reviewer no longer accepts or rejects
2002
+ * along with the change, so the capture is a member of the wrapper's own
2003
+ * content union rather than a sibling beside it.
2004
+ *
2005
+ * Opaque, so it holds no fields and no comment anchors; `text` is what the
2006
+ * markup puts on the line, which is empty for everything except a transparent
2007
+ * wrapper such as `w:customXml`.
2008
+ */
2009
+ type PreservedInline = {
2010
+ type: "preservedInline";
2011
+ /** Replayable markup for one child, as `captureVerbatimXml` wrote it. */
2012
+ xml: string;
2013
+ /** The visible text the markup contributes, empty when it shows nothing. */
2014
+ text: string;
2015
+ };
1790
2016
  /**
1791
2017
  * Paragraph content types
1792
2018
  */
1793
- type ParagraphContent = Run | Hyperlink | BookmarkStart | BookmarkEnd | SimpleField | ComplexField | InlineSdt | CommentRangeStart | CommentRangeEnd | CommentReference | Insertion | Deletion | MoveFrom | MoveTo | MoveFromRangeStart | MoveFromRangeEnd | MoveToRangeStart | MoveToRangeEnd | BidiWrapper | MathEquation;
2019
+ type ParagraphContent = Run | Hyperlink | BookmarkStart | BookmarkEnd | SimpleField | ComplexField | InlineSdt | CommentRangeStart | CommentRangeEnd | CommentReference | Insertion | Deletion | MoveFrom | MoveTo | MoveFromRangeStart | MoveFromRangeEnd | MoveToRangeStart | MoveToRangeEnd | InlineWrapper | MathEquation | PreservedInline;
1794
2020
  /**
1795
2021
  * The kinds a paragraph-mark tracked change can be (ECMA-376 §17.13.5).
1796
2022
  *
@@ -1842,7 +2068,19 @@ type Paragraph = {
1842
2068
  renderedPageBreakBefore?: boolean;
1843
2069
  /** Section properties (if this paragraph ends a section) */
1844
2070
  sectionProperties?: SectionProperties;
1845
- } & BlockRangeMarkerCapture;
2071
+ /**
2072
+ * Attributes `w:p` carried that this record has no field for.
2073
+ *
2074
+ * Word writes a revision-session id (`w:rsidR` and its family) on nearly
2075
+ * every paragraph, and a rebuild that dropped it rewrote the document's
2076
+ * revision history. The remainder follows the record: a paragraph the
2077
+ * editor creates from scratch has none, and when an edit splits one in two
2078
+ * the half that keeps the authored identity keeps the remainder, because a
2079
+ * revision id inherited from a neighbour is a claim about history nobody
2080
+ * made.
2081
+ */
2082
+ preservedAttributes?: PreservedAttribute[];
2083
+ };
1846
2084
  /**
1847
2085
  * Header/footer type
1848
2086
  */
@@ -2016,7 +2254,7 @@ type Footnote = {
2016
2254
  * work in notes the same as they do in the main body. Mirrors the
2017
2255
  * shape upstream eigenpal/docx-editor#678 fixed for the same case.
2018
2256
  */
2019
- content: (Paragraph | Table | BlockSdt)[];
2257
+ content: BlockContent[];
2020
2258
  };
2021
2259
  /**
2022
2260
  * Endnote (w:endnote)
@@ -2031,7 +2269,7 @@ type Endnote = {
2031
2269
  * Content. Like `Footnote.content`, may carry block-level `<w:sdt>`
2032
2270
  * preserved as `BlockSdt` so SDT round-trip works inside endnotes.
2033
2271
  */
2034
- content: (Paragraph | Table | BlockSdt)[];
2272
+ content: BlockContent[];
2035
2273
  };
2036
2274
  /**
2037
2275
  * Page orientation
@@ -2169,27 +2407,42 @@ type SectionProperties = {
2169
2407
  printerSettingsRelationshipId?: string;
2170
2408
  /** Section-level tracked property changes (w:sectPrChange) */
2171
2409
  propertyChanges?: SectionPropertyChange[];
2410
+ /**
2411
+ * Attributes `w:sectPr` carried that this record has no field for.
2412
+ *
2413
+ * `AG_SectPrAttributes` declares `w:rsidR`, `w:rsidDel`, `w:rsidRPr` and
2414
+ * `w:rsidSect`, on the body's section properties and on a paragraph's alike.
2415
+ * The record travels through the editor whole, so the remainder does too.
2416
+ */
2417
+ preservedAttributes?: PreservedAttribute[];
2172
2418
  };
2173
2419
  /**
2174
- * Range markers captured verbatim from between two blocks.
2420
+ * A block-level child folio does not model, kept where it stood.
2421
+ *
2422
+ * `w:body`, `w:tc`, `w:hdr`, `w:ftr`, an SDT's content and a footnote all
2423
+ * admit more than paragraphs, tables and content controls: `w:permStart` is
2424
+ * the whole of a document-protection range, `w:altChunk` is an entire imported
2425
+ * document, `m:oMathPara` is a display equation, and a comment or move range
2426
+ * may open between two blocks. Position is their meaning, so the capture is a
2427
+ * block in its own right rather than a field riding on a neighbour: it sits
2428
+ * between the same two siblings in the model, in the editor and in the saved
2429
+ * part, and nothing has to keep an index honest as the blocks around it move.
2175
2430
  *
2176
- * `w:permStart`, `w:customXml*Range*`, and a comment or move range that opens
2177
- * or closes between blocks are all legal children of `w:body`, `w:tc` and a
2178
- * header. folio has no model for most of them, and their position is the whole
2179
- * of their meaning: a protected range that spans three paragraphs is defined
2180
- * by where its `w:permStart` sits. So they ride on the block they precede or
2181
- * follow and are replayed there.
2431
+ * Being opaque, it holds no text, no fields and no comment anchors; a walker
2432
+ * looking for any of those may skip it, and every walker that rebuilds block
2433
+ * content must write it back.
2182
2434
  */
2183
- type BlockRangeMarkerCapture = {
2184
- /** Markup that stood immediately before this block. */
2185
- rawMarkersBefore?: string;
2186
- /** Markup that stood after this block, which only the last block can carry. */
2187
- rawMarkersAfter?: string;
2435
+ type PreservedBlock = {
2436
+ type: "preservedBlock";
2437
+ /** Replayable markup for one child, as `captureVerbatimXml` wrote it. */
2438
+ xml: string;
2188
2439
  };
2189
2440
  /**
2190
2441
  * Block-level content types
2191
2442
  */
2192
- type BlockContent = Paragraph | Table | BlockSdt;
2443
+ type BlockContent = Paragraph | Table | BlockSdt | PreservedBlock;
2444
+ /** {@link BlockContent} minus the branch folio does not model inside a cell. */
2445
+ type TableCellBlock = Exclude<BlockContent, BlockSdt>;
2193
2446
  /**
2194
2447
  * Section (implicit or explicit based on sectPr)
2195
2448
  */
@@ -2279,6 +2532,8 @@ declare const PARSE_WARNING_CODES: {
2279
2532
  readonly styleSetDuplicateStyleId: "style-set-duplicate-style-id";
2280
2533
  /** A style set naming an initial paragraph style it does not contain. */
2281
2534
  readonly styleSetInitialStyleMissing: "style-set-initial-style-missing";
2535
+ /** An explicit page-break run the editable model lays out approximately. */
2536
+ readonly pageBreakProjectionApproximated: "page-break-projection-approximated";
2282
2537
  };
2283
2538
  type ParseWarningCode = (typeof PARSE_WARNING_CODES)[keyof typeof PARSE_WARNING_CODES];
2284
2539
  /** Where a warning happened, as precisely as the part can say. */
@@ -2690,4 +2945,4 @@ type Document = {
2690
2945
  parseWarnings?: ParseWarning[];
2691
2946
  };
2692
2947
  //#endregion
2693
- export { FieldType as $, TableRowFormatting as $n, SectionStart as $t, BlockRangeMarkerCapture as A, ListLevel as An, NoBreakHyphenContent as At, CommentReference as B, LineSpacingRule as Bn, PictureWatermark as Bt, ParseWarning as C, TrackedRunContent as Cn, MoveBookmarkMarker as Ct, BidiControl as D, normalizeRevisionId as Dn, MoveTo as Dt, BIDI_CONTROLS as E, isOoxmlSymbolCharacter as En, MoveFromRangeStart as Et, BreakContent as F, NumberingInstance as Fn, Paragraph as Ft, DocumentBody as G, TabStop as Gn, Run as Gt, DRAWING_RAW_XML_MODES as H, ParagraphFormatting as Hn, PropertyChangeInfo as Ht, Column as I, CellMargins as In, ParagraphContent as It, Endnote as J, TableCellBorders as Jn, SdtProperties as Jt, DrawingContent as K, TabStopAlignment as Kn, RunContent as Kt, Comment as L, ConditionalFormatStyle as Ln, ParagraphMarkChange as Lt, BookmarkEnd as M, ListRendering as Mn, NoteReferenceContent as Mt, BookmarkRangeMarker as N, NumberFormat as Nn, PARAGRAPH_MARK_CHANGE_KINDS as Nt, BidiWrapper as O, AbstractNumbering as On, MoveToRangeEnd as Ot, BookmarkStart as P, NumberingDefinitions as Pn, PageOrientation as Pt, FieldCharContent as Q, TableMeasurement as Qn, SectionPropertyChange as Qt, CommentRangeEnd as R, EmphasisMark as Rn, ParagraphMarkChangeKind as Rt, PARSE_WARNING_CODES as S, TrackedRunChange as Sn, MathEquation as St, ParseWarningLocation as T, Watermark as Tn, MoveFromRangeEnd as Tt, Deletion as U, SpacingExplicit as Un, REVIEW_CARRIERS as Ut, ComplexField as V, ParagraphAlignment as Vn, PositionalTab as Vt, DisplacedByCustomXml as W, TabLeader as Wn, ReviewCarrier as Wt, EndnoteProperties as X, TableFormatting as Xn, Section as Xt, EndnotePosition as Y, TableCellFormatting as Yn, SdtType as Yt, Field as Z, TableLook as Zn, SectionProperties as Zt, Theme as _, TableStructuralChangeInfo as _n, Insertion as _t, DocxPackage as a, ShapeTextBody as an, ColorValue as ar, HeaderFooterType as at, ThemeFontScheme as b, TextWatermark as bn, MAX_REVISION_ID as bt, FontInfo as c, SoftHyphenContent as cn, ThemeColorSlot as cr, Image as ct, Relationship as d, Table as dn, ImagePadding as dt, Shape as en, TableWidthType as er, FooterReference as et, RelationshipMap as f, TableCell as fn, ImagePosition as ft, StyleType as g, TableRowPropertyChange as gn, InlineSdt as gt, StyleDefinitions as h, TableRow as hn, ImageWrap as ht, DocxConformanceClass as i, ShapeOutline as in, BorderSpec as ir, HeaderFooter as it, BlockSdt as j, ListMarkerFormatting as jn, NoteNumberRestart as jt, BlockContent as k, LevelSuffix as kn, MoveToRangeStart as kt, FontTable as l, SymbolContent as ln, ImageCrop as lt, Style as m, TablePropertyChange as mn, ImageTransform as mt, Document as n, ShapeFill as nn, TextFormatting as nr, FootnotePosition as nt, ExhaustiveFields as o, ShapeType as on, KnownBorderStyle as or, HeaderReference as ot, RelationshipType as p, TableCellPropertyChange as pn, ImageSize as pt, DrawingRawXmlMode as q, TableBorders as qn, RunPropertyChange as qt, DocumentSettings as r, ShapeGeometryAdjustment as rn, UnderlineStyle as rr, FootnoteProperties as rt, DocDefaults as s, SimpleField as sn, ShadingProperties as sr, Hyperlink as st, DOCX_CONFORMANCE_CLASSES as t, ShapeContent as tn, TextEffect as tr, Footnote as tt, MediaFile as u, TabContent as un, ImageFrameLocks as ut, ThemeColorScheme as v, TextBox as vn, InstrTextContent as vt, ParseWarningCode as w, VerticalAlign as wn, MoveFrom as wt, MAX_RETAINED_PARSE_WARNINGS_PER_CODE as x, TrackedChangeInfo as xn, MarkupRangeMarker as xt, ThemeFont as y, TextContent as yn, LineNumberRestart as yt, CommentRangeStart as z, FloatingTableProperties as zn, ParagraphPropertyChange as zt };
2948
+ export { Footnote as $, TableBorders as $n, SectionProperties as $t, BookmarkEnd as A, normalizeRevisionId as An, NoteNumberRestart as At, DRAWING_RAW_XML_MODES as B, NumberingDefinitions as Bn, PositionalTab as Bt, ParseWarning as C, TextWatermark as Cn, MoveFrom as Ct, BidiControl as D, VerticalAlign as Dn, MoveToRangeEnd as Dt, BIDI_CONTROLS as E, TrackedRunContent as En, MoveTo as Et, Comment as F, LevelSuffix as Fn, ParagraphContent as Ft, DrawingRawXmlMode as G, FloatingTableProperties as Gn, REVIEW_CARRIERS as Gt, DisplacedByCustomXml as H, CellMargins as Hn, PreservedInline as Ht, CommentRangeEnd as I, ListLevel as In, ParagraphMarkChange as It, EndnoteProperties as J, ParagraphFormatting as Jn, RunContent as Jt, Endnote as K, LineSpacingRule as Kn, ReviewCarrier as Kt, CommentRangeStart as L, ListMarkerFormatting as Ln, ParagraphMarkChangeKind as Lt, BookmarkStart as M, PreservedChild as Mn, PARAGRAPH_MARK_CHANGE_KINDS as Mt, BreakContent as N, PreservedMarkup as Nn, PageOrientation as Nt, BlockContent as O, Watermark as On, MoveToRangeStart as Ot, Column as P, AbstractNumbering as Pn, Paragraph as Pt, FooterReference as Q, TabStopAlignment as Qn, Section as Qt, CommentReference as R, ListRendering as Rn, ParagraphPropertyChange as Rt, PARSE_WARNING_CODES as S, TextContent as Sn, MoveBookmarkMarker as St, ParseWarningLocation as T, TrackedRunChange as Tn, MoveFromRangeStart as Tt, DocumentBody as U, ConditionalFormatStyle as Un, PreservedXmlContent as Ut, Deletion as V, NumberingInstance as Vn, PreservedBlock as Vt, DrawingContent as W, EmphasisMark as Wn, PropertyChangeInfo as Wt, FieldCharContent as X, TabLeader as Xn, SdtProperties as Xt, Field as Y, SpacingExplicit as Yn, RunPropertyChange as Yt, FieldType as Z, TabStop as Zn, SdtType as Zt, Theme as _, TablePropertyChange as _n, InstrTextContent as _t, DocxPackage as a, ShapeGeometryAdjustment as an, TableRowFormatting as ar, Hyperlink as at, ThemeFontScheme as b, TableStructuralChangeInfo as bn, MarkupRangeMarker as bt, FontInfo as c, ShapeType as cn, TextFormatting as cr, ImageFrameLocks as ct, Relationship as d, SymbolContent as dn, ColorValue as dr, ImageSize as dt, SectionPropertyChange as en, TableCellBorders as er, FootnotePosition as et, RelationshipMap as f, TabContent as fn, KnownBorderStyle as fr, ImageTransform as ft, StyleType as g, TableCellPropertyChange as gn, Insertion as gt, StyleDefinitions as h, TableCellBlock as hn, InlineWrapper as ht, DocxConformanceClass as i, ShapeFill as in, TableMeasurement as ir, HeaderReference as it, BookmarkRangeMarker as j, PreservedAttribute as jn, NoteReferenceContent as jt, BlockSdt as k, isOoxmlSymbolCharacter as kn, NoBreakHyphenContent as kt, FontTable as l, SimpleField as ln, UnderlineStyle as lr, ImagePadding as lt, Style as m, TableCell as mn, ThemeColorSlot as mr, InlineSdt as mt, Document as n, Shape as nn, TableFormatting as nr, HeaderFooter as nt, ExhaustiveFields as o, ShapeOutline as on, TableWidthType as or, Image as ot, RelationshipType as p, Table as pn, ShadingProperties as pr, ImageWrap as pt, EndnotePosition as q, ParagraphAlignment as qn, Run as qt, DocumentSettings as r, ShapeContent as rn, TableLook as rr, HeaderFooterType as rt, DocDefaults as s, ShapeTextBody as sn, TextEffect as sr, ImageCrop as st, DOCX_CONFORMANCE_CLASSES as t, SectionStart as tn, TableCellFormatting as tr, FootnoteProperties as tt, MediaFile as u, SoftHyphenContent as un, BorderSpec as ur, ImagePosition as ut, ThemeColorScheme as v, TableRow as vn, LineNumberRestart as vt, ParseWarningCode as w, TrackedChangeInfo as wn, MoveFromRangeEnd as wt, MAX_RETAINED_PARSE_WARNINGS_PER_CODE as x, TextBox as xn, MathEquation as xt, ThemeFont as y, TableRowPropertyChange as yn, MAX_REVISION_ID as yt, ComplexField as z, NumberFormat as zn, PictureWatermark as zt };
Binary file
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as BreakContent, Ft as Paragraph, G as DocumentBody, Gt as Run, It as ParagraphContent, Kt as RunContent, Pn as NumberingDefinitions, Vt as PositionalTab, Zt as SectionProperties, a as DocxPackage, dn as Table, fn as TableCell, hn as TableRow, i as DocxConformanceClass, k as BlockContent, m as Style, n as Document, t as DOCX_CONFORMANCE_CLASSES, yn as TextContent } from "./document-BzVhjQZZ.js";
1
+ import { $t as SectionProperties, Bn as NumberingDefinitions, Bt as PositionalTab, Ft as ParagraphContent, Jt as RunContent, N as BreakContent, O as BlockContent, Pt as Paragraph, Sn as TextContent, U as DocumentBody, a as DocxPackage, i as DocxConformanceClass, m as Style, mn as TableCell, n as Document, pn as Table, qt as Run, t as DOCX_CONFORMANCE_CLASSES, vn as TableRow } from "./document-DT_3cbkQ.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/legal-source/types.d.ts
4
4
  type LegalDocumentKind = "agreement" | "letter" | "memo" | "checklist" | "pleading" | "other";
@@ -148,8 +148,90 @@ type SerializeDocumentOptions = {
148
148
  /** BCP-47 language tag (e.g. "en", "cs", "cs-CZ"); used for footer labels. */
149
149
  language?: string;
150
150
  };
151
+ /**
152
+ * Writes a package from scratch, for a `Document` that was built rather than
153
+ * parsed: today the legal-source compiler's.
154
+ *
155
+ * It writes the subset of OOXML that compiler produces. It has no relationship
156
+ * table, no media, no verbatim capture and no namespace scope, so a **parsed**
157
+ * `Document` handed to it comes back without its drawings, its fields, its
158
+ * tracked changes or its preserved markup — `serializeRunContent` returns `""`
159
+ * for most of `RunContent`. A round trip belongs in `@stll/folio-core`'s
160
+ * `repackDocx`, which rebuilds a package against the one it read.
161
+ *
162
+ * Making that a compile error wants a branded `ConstructedDocument` that only
163
+ * a from-scratch builder can mint. It is not clean today: the two suites that
164
+ * exercise this writer (`serialize/docx.test.ts` and `core`'s
165
+ * `xmlValuePreservation.property.test.ts`) build their `Document` as a literal,
166
+ * so the brand needs a public mint, and a public mint a parsed document can be
167
+ * passed through is decoration rather than a guard. The prerequisite is a
168
+ * from-scratch document builder those suites can call; the brand follows it,
169
+ * not the other way round.
170
+ */
151
171
  declare const serializeDocumentToDocx: (document: Document, options?: SerializeDocumentOptions) => Promise<ArrayBuffer>;
152
172
  //#endregion
173
+ //#region src/serialize/xmlEscape.d.ts
174
+ /**
175
+ * The one owner of XML character escaping for every part folio writes.
176
+ *
177
+ * Two contexts, two functions. A value going into element content takes
178
+ * {@link escapeXmlText}; a value going between the quotes of an attribute
179
+ * takes {@link escapeXmlAttribute}. Nothing else escapes XML by hand: a
180
+ * second escaper always ends up disagreeing with this one about some
181
+ * character, and the disagreement is a package Word refuses to open.
182
+ *
183
+ * Both functions guarantee the same contract: **the result is always legal
184
+ * XML 1.0 character data.** That is what makes the contract checkable — a
185
+ * caller cannot produce a corrupt part by forgetting something.
186
+ *
187
+ * XML 1.0 §2.2 `Char` admits tab, LF, CR, `#x20`-`#xD7FF`, `#xE000`-`#xFFFD`
188
+ * and the astral planes. Everything else — the rest of C0, `#xFFFE`,
189
+ * `#xFFFF`, an unpaired surrogate — cannot appear in a document at all, and
190
+ * cannot be escaped into one either: `&#0;` is as illegal as a raw NUL
191
+ * (§4.1 requires a character reference to refer to a legal `Char`). The only
192
+ * output that is well-formed is one without them, so they are dropped here.
193
+ * Callers that own an input boundary sanitise before this point, with
194
+ * `sanitizeXmlCharacters`, so a user-visible value loses its illegal
195
+ * characters where something can still report it; the drop below is the last
196
+ * line of defence for a boundary nobody has covered yet.
197
+ *
198
+ * The whitespace rules are where the two contexts part:
199
+ *
200
+ * - §3.3.3 normalises tab, LF and CR in an **attribute value** to a space in
201
+ * every conformant parser, so a literal one does not survive a save. They
202
+ * are written as character references, which the same step leaves alone.
203
+ * - §2.11 normalises a literal CR (and CRLF) in **content** to LF on read, so
204
+ * CR is written as a reference there too. Tab and LF survive as themselves.
205
+ *
206
+ * Both contexts escape all five of `& < > " '`. Only `&` and `<` must be
207
+ * escaped in content, but folio has always written the full set, `>` closes
208
+ * the `]]>` hazard of §2.4 without a special case, and one lexical form
209
+ * across every writer is worth more than the bytes it costs. Every spelling
210
+ * here reads back as the character it stands for, so the rule preserves the
211
+ * value whichever context it lands in.
212
+ */
213
+ /** Escape a value for XML element content. Tab and LF survive as themselves. */
214
+ declare const escapeXmlText: (value: string) => string;
215
+ /**
216
+ * Escape a value for an XML attribute value, of either quoting. Tab, LF and CR
217
+ * become character references so attribute-value normalisation cannot flatten
218
+ * them to spaces.
219
+ */
220
+ declare const escapeXmlAttribute: (value: string) => string;
221
+ /** Whether `value` holds a character XML 1.0 cannot represent at all. */
222
+ declare const hasIllegalXmlCharacters: (value: string) => boolean;
223
+ /**
224
+ * Make a value from outside folio representable in XML: an unpaired surrogate
225
+ * becomes U+FFFD, every other character XML cannot hold is dropped.
226
+ *
227
+ * This is the rule for an input boundary — paste, a document operation, a
228
+ * markdown or legal-source compile, a template fill — where the value is still
229
+ * attached to the request that carried it and a warning still has somewhere to
230
+ * go. `escapeXmlText` and `escapeXmlAttribute` apply the same rule again
231
+ * further down, but by then nobody can say which input lost a character.
232
+ */
233
+ declare const sanitizeXmlCharacters: (value: string) => string;
234
+ //#endregion
153
235
  //#region src/serialize/textWhitespace.d.ts
154
236
  /**
155
237
  * Whether `<w:t>` needs `xml:space="preserve"` to render the text as written.
@@ -192,4 +274,4 @@ declare const validateDocxPackage: (buffer: ArrayBuffer | Uint8Array) => Promise
192
274
  declare const validateDocumentModel: (document: Document) => ValidateDocumentModelResult;
193
275
  declare const assertValidDocumentModel: (document: Document) => void;
194
276
  //#endregion
195
- export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBody, type DocxConformanceClass, type DocxPackage, type DocxPackageIssueCode, type LegalDraft, type LegalDraftBlock, type LegalDraftDiagnostic, type LegalSourceCompileOptions, type LegalSourceCompileResult, type LegalSourceDocxCompileResult, type LegalSourceParseResult, type MarkdownContent, type Paragraph, type ParagraphContent, type PositionalTab, type Run, type RunContent, type SectionProperties, type Style, type Table, type TableCell, type TableRow, type TextContent, type ValidateDocumentModelIssue, type ValidateDocumentModelResult, type ValidateDocxPackageResult, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, parseLegalSource, requiresXmlSpacePreserve, sanitizeExternalUrl, serializeDocumentToDocx, validateDocumentModel, validateDocxPackage, validateLegalDraft };
277
+ export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBody, type DocxConformanceClass, type DocxPackage, type DocxPackageIssueCode, type LegalDraft, type LegalDraftBlock, type LegalDraftDiagnostic, type LegalSourceCompileOptions, type LegalSourceCompileResult, type LegalSourceDocxCompileResult, type LegalSourceParseResult, type MarkdownContent, type Paragraph, type ParagraphContent, type PositionalTab, type Run, type RunContent, type SectionProperties, type Style, type Table, type TableCell, type TableRow, type TextContent, type ValidateDocumentModelIssue, type ValidateDocumentModelResult, type ValidateDocxPackageResult, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, parseLegalSource, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, validateDocumentModel, validateDocxPackage, validateLegalDraft };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { s as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES } from "./document-CKwRw-01.js";
1
+ import { s as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES } from "./document-CxQxNVrK.js";
2
2
  import JSZip from "jszip";
3
3
  import { panic } from "better-result";
4
4
  import { XMLParser, XMLValidator } from "fast-xml-parser";
@@ -16,11 +16,99 @@ import { Marked } from "marked";
16
16
  */
17
17
  const requiresXmlSpacePreserve = (text) => text.startsWith(" ") || text.endsWith(" ") || text.includes(" ");
18
18
  //#endregion
19
+ //#region src/serialize/xmlEscape.ts
20
+ /**
21
+ * The one owner of XML character escaping for every part folio writes.
22
+ *
23
+ * Two contexts, two functions. A value going into element content takes
24
+ * {@link escapeXmlText}; a value going between the quotes of an attribute
25
+ * takes {@link escapeXmlAttribute}. Nothing else escapes XML by hand: a
26
+ * second escaper always ends up disagreeing with this one about some
27
+ * character, and the disagreement is a package Word refuses to open.
28
+ *
29
+ * Both functions guarantee the same contract: **the result is always legal
30
+ * XML 1.0 character data.** That is what makes the contract checkable — a
31
+ * caller cannot produce a corrupt part by forgetting something.
32
+ *
33
+ * XML 1.0 §2.2 `Char` admits tab, LF, CR, `#x20`-`#xD7FF`, `#xE000`-`#xFFFD`
34
+ * and the astral planes. Everything else — the rest of C0, `#xFFFE`,
35
+ * `#xFFFF`, an unpaired surrogate — cannot appear in a document at all, and
36
+ * cannot be escaped into one either: `&#0;` is as illegal as a raw NUL
37
+ * (§4.1 requires a character reference to refer to a legal `Char`). The only
38
+ * output that is well-formed is one without them, so they are dropped here.
39
+ * Callers that own an input boundary sanitise before this point, with
40
+ * `sanitizeXmlCharacters`, so a user-visible value loses its illegal
41
+ * characters where something can still report it; the drop below is the last
42
+ * line of defence for a boundary nobody has covered yet.
43
+ *
44
+ * The whitespace rules are where the two contexts part:
45
+ *
46
+ * - §3.3.3 normalises tab, LF and CR in an **attribute value** to a space in
47
+ * every conformant parser, so a literal one does not survive a save. They
48
+ * are written as character references, which the same step leaves alone.
49
+ * - §2.11 normalises a literal CR (and CRLF) in **content** to LF on read, so
50
+ * CR is written as a reference there too. Tab and LF survive as themselves.
51
+ *
52
+ * Both contexts escape all five of `& < > " '`. Only `&` and `<` must be
53
+ * escaped in content, but folio has always written the full set, `>` closes
54
+ * the `]]>` hazard of §2.4 without a special case, and one lexical form
55
+ * across every writer is worth more than the bytes it costs. Every spelling
56
+ * here reads back as the character it stands for, so the rule preserves the
57
+ * value whichever context it lands in.
58
+ */
59
+ /** XML 1.0 §2.2 `Char`, negated: the characters no XML document may contain. */
60
+ const ILLEGAL_XML_CHARACTER_CLASS = "[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
61
+ /**
62
+ * Unicode-mode classes match code points, so a well-formed surrogate pair is a
63
+ * single astral code point and cannot match a BMP class: this matches exactly
64
+ * the unpaired surrogates.
65
+ */
66
+ const LONE_SURROGATE_PATTERN = /[\uD800-\uDFFF]/gu;
67
+ const ILLEGAL_XML_CHARACTER_PATTERN = new RegExp(ILLEGAL_XML_CHARACTER_CLASS, "gu");
68
+ const ILLEGAL_XML_CHARACTER_PROBE = new RegExp(ILLEGAL_XML_CHARACTER_CLASS, "u");
69
+ /** What an unpaired surrogate becomes at an input boundary: U+FFFD. */
70
+ const REPLACEMENT_CHARACTER = "�";
71
+ const TEXT_ESCAPES = {
72
+ "&": "&amp;",
73
+ "<": "&lt;",
74
+ ">": "&gt;",
75
+ "\"": "&quot;",
76
+ "'": "&apos;",
77
+ "\r": "&#13;"
78
+ };
79
+ const ATTRIBUTE_ESCAPES = {
80
+ ...TEXT_ESCAPES,
81
+ " ": "&#9;",
82
+ "\n": "&#10;"
83
+ };
84
+ const TEXT_PROBE = new RegExp(`[&<>"'\\r]|${ILLEGAL_XML_CHARACTER_CLASS}`, "u");
85
+ const TEXT_PATTERN = new RegExp(`[&<>"'\\r]|${ILLEGAL_XML_CHARACTER_CLASS}`, "gu");
86
+ const ATTRIBUTE_PROBE = new RegExp(`[&<>"'\\t\\n\\r]|${ILLEGAL_XML_CHARACTER_CLASS}`, "u");
87
+ const ATTRIBUTE_PATTERN = new RegExp(`[&<>"'\\t\\n\\r]|${ILLEGAL_XML_CHARACTER_CLASS}`, "gu");
88
+ /** Escape a value for XML element content. Tab and LF survive as themselves. */
89
+ const escapeXmlText = (value) => TEXT_PROBE.test(value) ? value.replace(TEXT_PATTERN, (character) => TEXT_ESCAPES[character] ?? "") : value;
90
+ /**
91
+ * Escape a value for an XML attribute value, of either quoting. Tab, LF and CR
92
+ * become character references so attribute-value normalisation cannot flatten
93
+ * them to spaces.
94
+ */
95
+ const escapeXmlAttribute = (value) => ATTRIBUTE_PROBE.test(value) ? value.replace(ATTRIBUTE_PATTERN, (character) => ATTRIBUTE_ESCAPES[character] ?? "") : value;
96
+ /** Whether `value` holds a character XML 1.0 cannot represent at all. */
97
+ const hasIllegalXmlCharacters = (value) => ILLEGAL_XML_CHARACTER_PROBE.test(value);
98
+ /**
99
+ * Make a value from outside folio representable in XML: an unpaired surrogate
100
+ * becomes U+FFFD, every other character XML cannot hold is dropped.
101
+ *
102
+ * This is the rule for an input boundary — paste, a document operation, a
103
+ * markdown or legal-source compile, a template fill — where the value is still
104
+ * attached to the request that carried it and a warning still has somewhere to
105
+ * go. `escapeXmlText` and `escapeXmlAttribute` apply the same rule again
106
+ * further down, but by then nobody can say which input lost a character.
107
+ */
108
+ const sanitizeXmlCharacters = (value) => hasIllegalXmlCharacters(value) ? value.replace(LONE_SURROGATE_PATTERN, REPLACEMENT_CHARACTER).replace(ILLEGAL_XML_CHARACTER_PATTERN, "") : value;
109
+ //#endregion
19
110
  //#region src/serialize/xml.ts
20
- const ILLEGAL_XML_CHARS_RE = /[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu;
21
- const stripIllegalXmlChars = (value) => value.replace(ILLEGAL_XML_CHARS_RE, "");
22
- const escapeXml = (value) => stripIllegalXmlChars(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
23
- const attr = (name, value) => value === void 0 ? "" : ` ${name}="${escapeXml(String(value))}"`;
111
+ const attr = (name, value) => value === void 0 ? "" : ` ${name}="${escapeXmlAttribute(String(value))}"`;
24
112
  //#endregion
25
113
  //#region src/serialize/docx.ts
26
114
  const DEFAULT_FOOTER_REL_ID = "rId10";
@@ -79,7 +167,7 @@ const resolveFooterLabels = (language) => {
79
167
  };
80
168
  const buildFooterXml = (language) => {
81
169
  const { page, of } = resolveFooterLabels(language);
82
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:pPr><w:pStyle w:val="Footer"/><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t xml:space="preserve">${escapeXml(page)} </w:t></w:r><w:fldSimple w:instr="PAGE \\* MERGEFORMAT"><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t>1</w:t></w:r></w:fldSimple><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t xml:space="preserve"> ${escapeXml(of)} </w:t></w:r><w:fldSimple w:instr="NUMPAGES \\* MERGEFORMAT"><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t>1</w:t></w:r></w:fldSimple></w:p></w:ftr>`;
170
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:pPr><w:pStyle w:val="Footer"/><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t xml:space="preserve">${escapeXmlText(page)} </w:t></w:r><w:fldSimple w:instr="PAGE \\* MERGEFORMAT"><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t>1</w:t></w:r></w:fldSimple><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t xml:space="preserve"> ${escapeXmlText(of)} </w:t></w:r><w:fldSimple w:instr="NUMPAGES \\* MERGEFORMAT"><w:r><w:rPr><w:sz w:val="18"/></w:rPr><w:t>1</w:t></w:r></w:fldSimple></w:p></w:ftr>`;
83
171
  };
84
172
  const contentTypesXml = (hasNumbering) => [
85
173
  "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
@@ -104,6 +192,26 @@ const documentRelsXml = (hasNumbering) => [
104
192
  "</Relationships>"
105
193
  ].join("");
106
194
  const APP_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"><Application>stella</Application></Properties>";
195
+ /**
196
+ * Writes a package from scratch, for a `Document` that was built rather than
197
+ * parsed: today the legal-source compiler's.
198
+ *
199
+ * It writes the subset of OOXML that compiler produces. It has no relationship
200
+ * table, no media, no verbatim capture and no namespace scope, so a **parsed**
201
+ * `Document` handed to it comes back without its drawings, its fields, its
202
+ * tracked changes or its preserved markup — `serializeRunContent` returns `""`
203
+ * for most of `RunContent`. A round trip belongs in `@stll/folio-core`'s
204
+ * `repackDocx`, which rebuilds a package against the one it read.
205
+ *
206
+ * Making that a compile error wants a branded `ConstructedDocument` that only
207
+ * a from-scratch builder can mint. It is not clean today: the two suites that
208
+ * exercise this writer (`serialize/docx.test.ts` and `core`'s
209
+ * `xmlValuePreservation.property.test.ts`) build their `Document` as a literal,
210
+ * so the brand needs a public mint, and a public mint a parsed document can be
211
+ * passed through is decoration rather than a guard. The prerequisite is a
212
+ * from-scratch document builder those suites can call; the brand follows it,
213
+ * not the other way round.
214
+ */
107
215
  const serializeDocumentToDocx = async (document, options = {}) => {
108
216
  const zip = new JSZip();
109
217
  const hasNumbering = hasNumberingDefinitions(document.package.numbering);
@@ -133,6 +241,7 @@ const serializeBlock = (block) => {
133
241
  case "paragraph": return serializeParagraph(block);
134
242
  case "table": return serializeTable(block);
135
243
  case "blockSdt": return "";
244
+ case "preservedBlock": return block.xml;
136
245
  default: return "";
137
246
  }
138
247
  };
@@ -143,7 +252,7 @@ const serializeParagraphProperties = (paragraph) => {
143
252
  const formatting = paragraph.formatting;
144
253
  if (!formatting && !paragraph.sectionProperties) return "";
145
254
  const parts = [];
146
- if (formatting?.styleId) parts.push(`<w:pStyle w:val="${escapeXml(formatting.styleId)}"/>`);
255
+ if (formatting?.styleId) parts.push(`<w:pStyle w:val="${escapeXmlAttribute(formatting.styleId)}"/>`);
147
256
  if (formatting?.keepNext) parts.push("<w:keepNext/>");
148
257
  if (formatting?.keepLines) parts.push("<w:keepLines/>");
149
258
  if (formatting?.pageBreakBefore) parts.push("<w:pageBreakBefore/>");
@@ -174,8 +283,9 @@ const serializeParagraphContent = (content) => {
174
283
  case "moveFromRangeEnd":
175
284
  case "moveToRangeStart":
176
285
  case "moveToRangeEnd":
177
- case "bidiWrapper":
178
- case "mathEquation": return "";
286
+ case "inlineWrapper":
287
+ case "mathEquation":
288
+ case "preservedInline": return "";
179
289
  default: return "";
180
290
  }
181
291
  };
@@ -185,7 +295,7 @@ const serializeRun = (run) => {
185
295
  const serializeRunProperties = (formatting) => {
186
296
  if (!formatting) return "";
187
297
  const parts = [];
188
- if (formatting.styleId) parts.push(`<w:rStyle w:val="${escapeXml(formatting.styleId)}"/>`);
298
+ if (formatting.styleId) parts.push(`<w:rStyle w:val="${escapeXmlAttribute(formatting.styleId)}"/>`);
189
299
  if (formatting.bold === true) parts.push("<w:b/>");
190
300
  else if (formatting.bold === false) parts.push("<w:b w:val=\"0\"/>");
191
301
  if (formatting.boldCs === true) parts.push("<w:bCs/>");
@@ -206,15 +316,16 @@ const serializeRunProperties = (formatting) => {
206
316
  };
207
317
  const serializeRunContent = (content) => {
208
318
  switch (content.type) {
209
- case "text": return `<w:t${requiresXmlSpacePreserve(content.text) ? " xml:space=\"preserve\"" : ""}>${escapeXml(content.text)}</w:t>`;
319
+ case "text": return `<w:t${requiresXmlSpacePreserve(content.text) ? " xml:space=\"preserve\"" : ""}>${escapeXmlText(content.text)}</w:t>`;
210
320
  case "tab":
211
321
  if (!content.positional) return "<w:tab/>";
212
322
  return `<w:ptab${attr("w:relativeTo", content.positional.relativeTo)}${attr("w:alignment", content.positional.alignment)}${attr("w:leader", content.positional.leader)}/>`;
213
323
  case "break": return `<w:br${attr("w:type", content.breakType)}/>`;
214
324
  case "renderedPageBreak": return "<w:lastRenderedPageBreak/>";
215
- case "symbol": return `<w:sym w:font="${escapeXml(content.font)}" w:char="${escapeXml(content.char)}"/>`;
325
+ case "symbol": return `<w:sym w:font="${escapeXmlAttribute(content.font)}" w:char="${escapeXmlAttribute(content.char)}"/>`;
216
326
  case "footnoteRef": return `<w:footnoteReference w:id="${content.id}"/>`;
217
327
  case "endnoteRef": return `<w:endnoteReference w:id="${content.id}"/>`;
328
+ case "preservedXml": return content.xml;
218
329
  case "fieldChar":
219
330
  case "instrText":
220
331
  case "softHyphen":
@@ -264,10 +375,10 @@ const renderCellBorders = (table) => {
264
375
  };
265
376
  const borderEdgeXml = (tag, spec) => {
266
377
  if (!spec) return `<${tag} w:val="nil"/>`;
267
- if (spec.style === "none" || spec.style === "nil") return `<${tag} w:val="${escapeXml(spec.style)}"/>`;
378
+ if (spec.style === "none" || spec.style === "nil") return `<${tag} w:val="${escapeXmlAttribute(spec.style)}"/>`;
268
379
  const sz = spec.size ?? 4;
269
380
  const color = spec.color?.rgb ?? "CCCCCC";
270
- return `<${tag} w:val="${escapeXml(spec.style)}" w:sz="${sz}" w:space="0" w:color="${escapeXml(color)}"/>`;
381
+ return `<${tag} w:val="${escapeXmlAttribute(spec.style)}" w:sz="${sz}" w:space="0" w:color="${escapeXmlAttribute(color)}"/>`;
271
382
  };
272
383
  /**
273
384
  * The grid this generator gives a table that declares no borders of its own.
@@ -320,10 +431,10 @@ const serializeStyle = (style) => {
320
431
  }).replace(/^<w:pPr>|<\/w:pPr>$/gu, "") : "";
321
432
  const rPr = serializeRunProperties(style.rPr);
322
433
  return [
323
- `<w:style w:type="${style.type}" w:styleId="${escapeXml(style.styleId)}"${style.default ? " w:default=\"1\"" : ""}>`,
324
- `<w:name w:val="${escapeXml(style.name ?? style.styleId)}"/>`,
325
- style.basedOn ? `<w:basedOn w:val="${escapeXml(style.basedOn)}"/>` : "",
326
- style.next ? `<w:next w:val="${escapeXml(style.next)}"/>` : "",
434
+ `<w:style w:type="${style.type}" w:styleId="${escapeXmlAttribute(style.styleId)}"${style.default ? " w:default=\"1\"" : ""}>`,
435
+ `<w:name w:val="${escapeXmlAttribute(style.name ?? style.styleId)}"/>`,
436
+ style.basedOn ? `<w:basedOn w:val="${escapeXmlAttribute(style.basedOn)}"/>` : "",
437
+ style.next ? `<w:next w:val="${escapeXmlAttribute(style.next)}"/>` : "",
327
438
  style.qFormat ? "<w:qFormat/>" : "",
328
439
  pPr ? `<w:pPr>${pPr}</w:pPr>` : "",
329
440
  rPr,
@@ -349,7 +460,7 @@ const serializeNumberingLevel = (level) => [
349
460
  `<w:numFmt w:val="${level.numFmt}"/>`,
350
461
  level.isLgl ? "<w:isLgl/>" : "",
351
462
  level.suffix ? `<w:suff w:val="${level.suffix}"/>` : "",
352
- `<w:lvlText w:val="${escapeXml(level.lvlText)}"/>`,
463
+ `<w:lvlText w:val="${escapeXmlAttribute(level.lvlText)}"/>`,
353
464
  `<w:lvlJc w:val="${level.lvlJc ?? "left"}"/>`,
354
465
  level.pPr ? serializeParagraphProperties({
355
466
  type: "paragraph",
@@ -367,7 +478,7 @@ const serializeCoreProperties = (document) => {
367
478
  const creator = properties?.creator ?? "Stella";
368
479
  const created = properties?.created?.toISOString() ?? now;
369
480
  const modified = properties?.modified?.toISOString() ?? now;
370
- return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${escapeXml(title)}</dc:title><dc:creator>${escapeXml(creator)}</dc:creator><cp:lastModifiedBy>${escapeXml(creator)}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${created}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${modified}</dcterms:modified></cp:coreProperties>`;
481
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${escapeXmlText(title)}</dc:title><dc:creator>${escapeXmlText(creator)}</dc:creator><cp:lastModifiedBy>${escapeXmlText(creator)}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${created}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${modified}</dcterms:modified></cp:coreProperties>`;
371
482
  };
372
483
  //#endregion
373
484
  //#region src/validate/docx.ts
@@ -611,6 +722,7 @@ const validateBlock = (block, path, ctx) => {
611
722
  validateTable(block, path, ctx);
612
723
  return;
613
724
  }
725
+ if (block.type === "preservedBlock") return;
614
726
  if (block.content.length === 0) {
615
727
  addWarning(ctx, `${path}.content`, "Block content control is empty.");
616
728
  return;
@@ -691,10 +803,14 @@ const validateParagraphContent = (content, path, ctx) => {
691
803
  increment(ctx.moveToEnds, content.id);
692
804
  return;
693
805
  }
694
- if (content.type === "bidiWrapper") {
806
+ if (content.type === "inlineWrapper") {
695
807
  for (const [index, child] of content.content.entries()) validateParagraphContent(child, `${path}.content[${index}]`, ctx);
696
808
  return;
697
809
  }
810
+ if (content.type === "preservedInline") {
811
+ if (content.xml.trim() === "") addError(ctx, `${path}.xml`, "Preserved inline markup must not be empty.");
812
+ return;
813
+ }
698
814
  if (content.ommlXml.trim() === "") addError(ctx, `${path}.ommlXml`, "Math equation must preserve OMML XML.");
699
815
  };
700
816
  const validateFieldChild = (child, path, ctx) => {
@@ -702,6 +818,7 @@ const validateFieldChild = (child, path, ctx) => {
702
818
  validateRun(child, path, ctx);
703
819
  return;
704
820
  }
821
+ if (child.type === "preservedInline") return;
705
822
  validateHyperlink(child, path, ctx);
706
823
  };
707
824
  const validateRuns = (runs, path, ctx) => {
@@ -711,6 +828,10 @@ const validateRun = (run, path, ctx) => {
711
828
  for (const [index, content] of run.content.entries()) validateRunContent(content, `${path}.content[${index}]`, ctx);
712
829
  };
713
830
  const validateRunContent = (content, path, ctx) => {
831
+ if (content.type === "text") {
832
+ if (hasIllegalXmlCharacters(content.text)) addWarning(ctx, `${path}.text`, "Text holds characters XML 1.0 cannot represent; they will be dropped on save.");
833
+ return;
834
+ }
714
835
  if (content.type === "drawing") {
715
836
  validateImage(content.image, `${path}.image`, ctx, { hasPreservedRawDrawing: content.rawXml?.trim() !== "" });
716
837
  return;
@@ -741,6 +862,7 @@ const validateHyperlinkChild = (child, path, ctx) => {
741
862
  increment(ctx.bookmarkStarts, child.id);
742
863
  return;
743
864
  }
865
+ if (child.type === "preservedInline") return;
744
866
  increment(ctx.bookmarkEnds, child.id);
745
867
  };
746
868
  const validateTrackedRunChange = (change, path, ctx) => {
@@ -1181,9 +1303,14 @@ const countNewlines = (text) => {
1181
1303
  /** A token that starts a new structural block, so no body may run past it. */
1182
1304
  const startsStructure = (token) => isLegalDirectiveToken(token) || isTokenType(token, "heading");
1183
1305
  const parseLegalSource = (source, options = {}) => {
1306
+ const sanitizedSource = sanitizeXmlCharacters(source);
1184
1307
  const state = {
1185
1308
  blocks: [],
1186
- diagnostics: [],
1309
+ diagnostics: hasIllegalXmlCharacters(source) ? [{
1310
+ code: "illegal-xml-characters-dropped",
1311
+ message: "The source held characters XML 1.0 cannot represent; they were dropped. An unpaired surrogate became U+FFFD.",
1312
+ severity: "warning"
1313
+ }] : [],
1187
1314
  fixes: [],
1188
1315
  meta: {
1189
1316
  kind: DEFAULT_KIND,
@@ -1195,7 +1322,7 @@ const parseLegalSource = (source, options = {}) => {
1195
1322
  },
1196
1323
  title: null
1197
1324
  },
1198
- cursor: new TokenCursor(lexLegalSource(source))
1325
+ cursor: new TokenCursor(lexLegalSource(sanitizedSource))
1199
1326
  };
1200
1327
  for (;;) {
1201
1328
  const token = state.cursor.current;
@@ -2574,9 +2701,9 @@ const compileMarkdownToContent = (markdown) => {
2574
2701
  levels: /* @__PURE__ */ new Map()
2575
2702
  };
2576
2703
  return {
2577
- content: blocksFromTokens(lexMarkdown(markdown), numIds),
2704
+ content: blocksFromTokens(lexMarkdown(sanitizeXmlCharacters(markdown)), numIds),
2578
2705
  ...numIds.levels.size > 0 && { numbering: buildNumbering(numIds.levels) }
2579
2706
  };
2580
2707
  };
2581
2708
  //#endregion
2582
- export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, parseLegalSource, requiresXmlSpacePreserve, sanitizeExternalUrl, serializeDocumentToDocx, validateDocumentModel, validateDocxPackage, validateLegalDraft };
2709
+ export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, parseLegalSource, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, validateDocumentModel, validateDocxPackage, validateLegalDraft };
@@ -1,2 +1,2 @@
1
- import { $ as FieldType, $n as TableRowFormatting, $t as SectionStart, A as BlockRangeMarkerCapture, An as ListLevel, At as NoBreakHyphenContent, B as CommentReference, Bn as LineSpacingRule, Bt as PictureWatermark, C as ParseWarning, Cn as TrackedRunContent, Ct as MoveBookmarkMarker, D as BidiControl, Dn as normalizeRevisionId, Dt as MoveTo, E as BIDI_CONTROLS, En as isOoxmlSymbolCharacter, Et as MoveFromRangeStart, F as BreakContent, Fn as NumberingInstance, Ft as Paragraph, G as DocumentBody, Gn as TabStop, Gt as Run, H as DRAWING_RAW_XML_MODES, Hn as ParagraphFormatting, Ht as PropertyChangeInfo, I as Column, In as CellMargins, It as ParagraphContent, J as Endnote, Jn as TableCellBorders, Jt as SdtProperties, K as DrawingContent, Kn as TabStopAlignment, Kt as RunContent, L as Comment, Ln as ConditionalFormatStyle, Lt as ParagraphMarkChange, M as BookmarkEnd, Mn as ListRendering, Mt as NoteReferenceContent, N as BookmarkRangeMarker, Nn as NumberFormat, Nt as PARAGRAPH_MARK_CHANGE_KINDS, O as BidiWrapper, On as AbstractNumbering, Ot as MoveToRangeEnd, P as BookmarkStart, Pn as NumberingDefinitions, Pt as PageOrientation, Q as FieldCharContent, Qn as TableMeasurement, Qt as SectionPropertyChange, R as CommentRangeEnd, Rn as EmphasisMark, Rt as ParagraphMarkChangeKind, S as PARSE_WARNING_CODES, Sn as TrackedRunChange, St as MathEquation, T as ParseWarningLocation, Tn as Watermark, Tt as MoveFromRangeEnd, U as Deletion, Un as SpacingExplicit, Ut as REVIEW_CARRIERS, V as ComplexField, Vn as ParagraphAlignment, Vt as PositionalTab, W as DisplacedByCustomXml, Wn as TabLeader, Wt as ReviewCarrier, X as EndnoteProperties, Xn as TableFormatting, Xt as Section, Y as EndnotePosition, Yn as TableCellFormatting, Yt as SdtType, Z as Field, Zn as TableLook, Zt as SectionProperties, _ as Theme, _n as TableStructuralChangeInfo, _t as Insertion, a as DocxPackage, an as ShapeTextBody, ar as ColorValue, at as HeaderFooterType, b as ThemeFontScheme, bn as TextWatermark, bt as MAX_REVISION_ID, c as FontInfo, cn as SoftHyphenContent, cr as ThemeColorSlot, ct as Image, d as Relationship, dn as Table, dt as ImagePadding, en as Shape, er as TableWidthType, et as FooterReference, f as RelationshipMap, fn as TableCell, ft as ImagePosition, g as StyleType, gn as TableRowPropertyChange, gt as InlineSdt, h as StyleDefinitions, hn as TableRow, ht as ImageWrap, i as DocxConformanceClass, in as ShapeOutline, ir as BorderSpec, it as HeaderFooter, j as BlockSdt, jn as ListMarkerFormatting, jt as NoteNumberRestart, k as BlockContent, kn as LevelSuffix, kt as MoveToRangeStart, l as FontTable, ln as SymbolContent, lt as ImageCrop, m as Style, mn as TablePropertyChange, mt as ImageTransform, n as Document, nn as ShapeFill, nr as TextFormatting, nt as FootnotePosition, o as ExhaustiveFields, on as ShapeType, or as KnownBorderStyle, ot as HeaderReference, p as RelationshipType, pn as TableCellPropertyChange, pt as ImageSize, q as DrawingRawXmlMode, qn as TableBorders, qt as RunPropertyChange, r as DocumentSettings, rn as ShapeGeometryAdjustment, rr as UnderlineStyle, rt as FootnoteProperties, s as DocDefaults, sn as SimpleField, sr as ShadingProperties, st as Hyperlink, t as DOCX_CONFORMANCE_CLASSES, tn as ShapeContent, tr as TextEffect, tt as Footnote, u as MediaFile, un as TabContent, ut as ImageFrameLocks, v as ThemeColorScheme, vn as TextBox, vt as InstrTextContent, w as ParseWarningCode, wn as VerticalAlign, wt as MoveFrom, x as MAX_RETAINED_PARSE_WARNINGS_PER_CODE, xn as TrackedChangeInfo, xt as MarkupRangeMarker, y as ThemeFont, yn as TextContent, yt as LineNumberRestart, z as CommentRangeStart, zn as FloatingTableProperties, zt as ParagraphPropertyChange } from "../document-BzVhjQZZ.js";
2
- export { type AbstractNumbering, BIDI_CONTROLS, type BidiControl, type BidiWrapper, type BlockContent, type BlockRangeMarkerCapture, type BlockSdt, type BookmarkEnd, type BookmarkRangeMarker, type BookmarkStart, type BorderSpec, type BreakContent, type CellMargins, type ColorValue, type Column, type Comment, type CommentRangeEnd, type CommentRangeStart, type CommentReference, type ComplexField, type ConditionalFormatStyle, DOCX_CONFORMANCE_CLASSES, DRAWING_RAW_XML_MODES, type Deletion, type DisplacedByCustomXml, type DocDefaults, Document, type DocumentBody, DocumentSettings, DocxConformanceClass, DocxPackage, type DrawingContent, type DrawingRawXmlMode, type EmphasisMark, type Endnote, type EndnotePosition, type EndnoteProperties, type ExhaustiveFields, type Field, type FieldCharContent, type FieldType, type FloatingTableProperties, type FontInfo, type FontTable, type FooterReference, type Footnote, type FootnotePosition, type FootnoteProperties, type HeaderFooter, type HeaderFooterType, type HeaderReference, type Hyperlink, type Image, type ImageCrop, type ImageFrameLocks, type ImagePadding, type ImagePosition, type ImageSize, type ImageTransform, type ImageWrap, type InlineSdt, type Insertion, type InstrTextContent, type KnownBorderStyle, type LevelSuffix, type LineNumberRestart, type LineSpacingRule, type ListLevel, type ListMarkerFormatting, type ListRendering, MAX_RETAINED_PARSE_WARNINGS_PER_CODE, MAX_REVISION_ID, type MarkupRangeMarker, type MathEquation, type MediaFile, type MoveBookmarkMarker, type MoveFrom, type MoveFromRangeEnd, type MoveFromRangeStart, type MoveTo, type MoveToRangeEnd, type MoveToRangeStart, type NoBreakHyphenContent, type NoteNumberRestart, type NoteReferenceContent, type NumberFormat, type NumberingDefinitions, type NumberingInstance, PARAGRAPH_MARK_CHANGE_KINDS, PARSE_WARNING_CODES, type PageOrientation, type Paragraph, type ParagraphAlignment, type ParagraphContent, type ParagraphFormatting, type ParagraphMarkChange, type ParagraphMarkChangeKind, type ParagraphPropertyChange, type ParseWarning, type ParseWarningCode, type ParseWarningLocation, type PictureWatermark, type PositionalTab, type PropertyChangeInfo, REVIEW_CARRIERS, type Relationship, type RelationshipMap, type RelationshipType, type ReviewCarrier, type Run, type RunContent, type RunPropertyChange, type SdtProperties, type SdtType, type Section, type SectionProperties, type SectionPropertyChange, type SectionStart, type ShadingProperties, type Shape, type ShapeContent, type ShapeFill, type ShapeGeometryAdjustment, type ShapeOutline, type ShapeTextBody, type ShapeType, type SimpleField, type SoftHyphenContent, type SpacingExplicit, type Style, type StyleDefinitions, type StyleType, type SymbolContent, type TabContent, type TabLeader, type TabStop, type TabStopAlignment, type Table, type TableBorders, type TableCell, type TableCellBorders, type TableCellFormatting, type TableCellPropertyChange, type TableFormatting, type TableLook, type TableMeasurement, type TablePropertyChange, type TableRow, type TableRowFormatting, type TableRowPropertyChange, type TableStructuralChangeInfo, type TableWidthType, type TextBox, type TextContent, type TextEffect, type TextFormatting, type TextWatermark, type Theme, type ThemeColorScheme, type ThemeColorSlot, type ThemeFont, type ThemeFontScheme, type TrackedChangeInfo, type TrackedRunChange, type TrackedRunContent, type UnderlineStyle, type VerticalAlign, type Watermark, isOoxmlSymbolCharacter, normalizeRevisionId };
1
+ import { $ as Footnote, $n as TableBorders, $t as SectionProperties, A as BookmarkEnd, An as normalizeRevisionId, At as NoteNumberRestart, B as DRAWING_RAW_XML_MODES, Bn as NumberingDefinitions, Bt as PositionalTab, C as ParseWarning, Cn as TextWatermark, Ct as MoveFrom, D as BidiControl, Dn as VerticalAlign, Dt as MoveToRangeEnd, E as BIDI_CONTROLS, En as TrackedRunContent, Et as MoveTo, F as Comment, Fn as LevelSuffix, Ft as ParagraphContent, G as DrawingRawXmlMode, Gn as FloatingTableProperties, Gt as REVIEW_CARRIERS, H as DisplacedByCustomXml, Hn as CellMargins, Ht as PreservedInline, I as CommentRangeEnd, In as ListLevel, It as ParagraphMarkChange, J as EndnoteProperties, Jn as ParagraphFormatting, Jt as RunContent, K as Endnote, Kn as LineSpacingRule, Kt as ReviewCarrier, L as CommentRangeStart, Ln as ListMarkerFormatting, Lt as ParagraphMarkChangeKind, M as BookmarkStart, Mn as PreservedChild, Mt as PARAGRAPH_MARK_CHANGE_KINDS, N as BreakContent, Nn as PreservedMarkup, Nt as PageOrientation, O as BlockContent, On as Watermark, Ot as MoveToRangeStart, P as Column, Pn as AbstractNumbering, Pt as Paragraph, Q as FooterReference, Qn as TabStopAlignment, Qt as Section, R as CommentReference, Rn as ListRendering, Rt as ParagraphPropertyChange, S as PARSE_WARNING_CODES, Sn as TextContent, St as MoveBookmarkMarker, T as ParseWarningLocation, Tn as TrackedRunChange, Tt as MoveFromRangeStart, U as DocumentBody, Un as ConditionalFormatStyle, Ut as PreservedXmlContent, V as Deletion, Vn as NumberingInstance, Vt as PreservedBlock, W as DrawingContent, Wn as EmphasisMark, Wt as PropertyChangeInfo, X as FieldCharContent, Xn as TabLeader, Xt as SdtProperties, Y as Field, Yn as SpacingExplicit, Yt as RunPropertyChange, Z as FieldType, Zn as TabStop, Zt as SdtType, _ as Theme, _n as TablePropertyChange, _t as InstrTextContent, a as DocxPackage, an as ShapeGeometryAdjustment, ar as TableRowFormatting, at as Hyperlink, b as ThemeFontScheme, bn as TableStructuralChangeInfo, bt as MarkupRangeMarker, c as FontInfo, cn as ShapeType, cr as TextFormatting, ct as ImageFrameLocks, d as Relationship, dn as SymbolContent, dr as ColorValue, dt as ImageSize, en as SectionPropertyChange, er as TableCellBorders, et as FootnotePosition, f as RelationshipMap, fn as TabContent, fr as KnownBorderStyle, ft as ImageTransform, g as StyleType, gn as TableCellPropertyChange, gt as Insertion, h as StyleDefinitions, hn as TableCellBlock, ht as InlineWrapper, i as DocxConformanceClass, in as ShapeFill, ir as TableMeasurement, it as HeaderReference, j as BookmarkRangeMarker, jn as PreservedAttribute, jt as NoteReferenceContent, k as BlockSdt, kn as isOoxmlSymbolCharacter, kt as NoBreakHyphenContent, l as FontTable, ln as SimpleField, lr as UnderlineStyle, lt as ImagePadding, m as Style, mn as TableCell, mr as ThemeColorSlot, mt as InlineSdt, n as Document, nn as Shape, nr as TableFormatting, nt as HeaderFooter, o as ExhaustiveFields, on as ShapeOutline, or as TableWidthType, ot as Image, p as RelationshipType, pn as Table, pr as ShadingProperties, pt as ImageWrap, q as EndnotePosition, qn as ParagraphAlignment, qt as Run, r as DocumentSettings, rn as ShapeContent, rr as TableLook, rt as HeaderFooterType, s as DocDefaults, sn as ShapeTextBody, sr as TextEffect, st as ImageCrop, t as DOCX_CONFORMANCE_CLASSES, tn as SectionStart, tr as TableCellFormatting, tt as FootnoteProperties, u as MediaFile, un as SoftHyphenContent, ur as BorderSpec, ut as ImagePosition, v as ThemeColorScheme, vn as TableRow, vt as LineNumberRestart, w as ParseWarningCode, wn as TrackedChangeInfo, wt as MoveFromRangeEnd, x as MAX_RETAINED_PARSE_WARNINGS_PER_CODE, xn as TextBox, xt as MathEquation, y as ThemeFont, yn as TableRowPropertyChange, yt as MAX_REVISION_ID, z as ComplexField, zn as NumberFormat, zt as PictureWatermark } from "../document-DT_3cbkQ.js";
2
+ export { type AbstractNumbering, BIDI_CONTROLS, type BidiControl, type BlockContent, type BlockSdt, type BookmarkEnd, type BookmarkRangeMarker, type BookmarkStart, type BorderSpec, type BreakContent, type CellMargins, type ColorValue, type Column, type Comment, type CommentRangeEnd, type CommentRangeStart, type CommentReference, type ComplexField, type ConditionalFormatStyle, DOCX_CONFORMANCE_CLASSES, DRAWING_RAW_XML_MODES, type Deletion, type DisplacedByCustomXml, type DocDefaults, Document, type DocumentBody, DocumentSettings, DocxConformanceClass, DocxPackage, type DrawingContent, type DrawingRawXmlMode, type EmphasisMark, type Endnote, type EndnotePosition, type EndnoteProperties, type ExhaustiveFields, type Field, type FieldCharContent, type FieldType, type FloatingTableProperties, type FontInfo, type FontTable, type FooterReference, type Footnote, type FootnotePosition, type FootnoteProperties, type HeaderFooter, type HeaderFooterType, type HeaderReference, type Hyperlink, type Image, type ImageCrop, type ImageFrameLocks, type ImagePadding, type ImagePosition, type ImageSize, type ImageTransform, type ImageWrap, type InlineSdt, type InlineWrapper, type Insertion, type InstrTextContent, type KnownBorderStyle, type LevelSuffix, type LineNumberRestart, type LineSpacingRule, type ListLevel, type ListMarkerFormatting, type ListRendering, MAX_RETAINED_PARSE_WARNINGS_PER_CODE, MAX_REVISION_ID, type MarkupRangeMarker, type MathEquation, type MediaFile, type MoveBookmarkMarker, type MoveFrom, type MoveFromRangeEnd, type MoveFromRangeStart, type MoveTo, type MoveToRangeEnd, type MoveToRangeStart, type NoBreakHyphenContent, type NoteNumberRestart, type NoteReferenceContent, type NumberFormat, type NumberingDefinitions, type NumberingInstance, PARAGRAPH_MARK_CHANGE_KINDS, PARSE_WARNING_CODES, type PageOrientation, type Paragraph, type ParagraphAlignment, type ParagraphContent, type ParagraphFormatting, type ParagraphMarkChange, type ParagraphMarkChangeKind, type ParagraphPropertyChange, type ParseWarning, type ParseWarningCode, type ParseWarningLocation, type PictureWatermark, type PositionalTab, type PreservedAttribute, type PreservedBlock, type PreservedChild, type PreservedInline, type PreservedMarkup, type PreservedXmlContent, type PropertyChangeInfo, REVIEW_CARRIERS, type Relationship, type RelationshipMap, type RelationshipType, type ReviewCarrier, type Run, type RunContent, type RunPropertyChange, type SdtProperties, type SdtType, type Section, type SectionProperties, type SectionPropertyChange, type SectionStart, type ShadingProperties, type Shape, type ShapeContent, type ShapeFill, type ShapeGeometryAdjustment, type ShapeOutline, type ShapeTextBody, type ShapeType, type SimpleField, type SoftHyphenContent, type SpacingExplicit, type Style, type StyleDefinitions, type StyleType, type SymbolContent, type TabContent, type TabLeader, type TabStop, type TabStopAlignment, type Table, type TableBorders, type TableCell, type TableCellBlock, type TableCellBorders, type TableCellFormatting, type TableCellPropertyChange, type TableFormatting, type TableLook, type TableMeasurement, type TablePropertyChange, type TableRow, type TableRowFormatting, type TableRowPropertyChange, type TableStructuralChangeInfo, type TableWidthType, type TextBox, type TextContent, type TextEffect, type TextFormatting, type TextWatermark, type Theme, type ThemeColorScheme, type ThemeColorSlot, type ThemeFont, type ThemeFontScheme, type TrackedChangeInfo, type TrackedRunChange, type TrackedRunContent, type UnderlineStyle, type VerticalAlign, type Watermark, isOoxmlSymbolCharacter, normalizeRevisionId };
@@ -1,2 +1,2 @@
1
- import { a as PARAGRAPH_MARK_CHANGE_KINDS, c as normalizeRevisionId, i as MAX_REVISION_ID, l as MAX_RETAINED_PARSE_WARNINGS_PER_CODE, n as BIDI_CONTROLS, o as REVIEW_CARRIERS, r as DRAWING_RAW_XML_MODES, s as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, u as PARSE_WARNING_CODES } from "../document-CKwRw-01.js";
1
+ import { a as PARAGRAPH_MARK_CHANGE_KINDS, c as normalizeRevisionId, i as MAX_REVISION_ID, l as MAX_RETAINED_PARSE_WARNINGS_PER_CODE, n as BIDI_CONTROLS, o as REVIEW_CARRIERS, r as DRAWING_RAW_XML_MODES, s as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, u as PARSE_WARNING_CODES } from "../document-CxQxNVrK.js";
2
2
  export { BIDI_CONTROLS, DOCX_CONFORMANCE_CLASSES, DRAWING_RAW_XML_MODES, MAX_RETAINED_PARSE_WARNINGS_PER_CODE, MAX_REVISION_ID, PARAGRAPH_MARK_CHANGE_KINDS, PARSE_WARNING_CODES, REVIEW_CARRIERS, isOoxmlSymbolCharacter, normalizeRevisionId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/docx-core",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Typed OOXML/DOCX model, validation, serialization, legal-source compilation, and browser-native package projection.",
5
5
  "keywords": [
6
6
  "document-model",