@stll/docx-core 0.22.0 → 0.23.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.
@@ -1158,8 +1158,26 @@ type Image = {
1158
1158
  * preserves the author's intent; undefined means "use the spec default".
1159
1159
  */
1160
1160
  allowOverlap?: boolean;
1161
- /** Whether this is a decorative image */
1161
+ /**
1162
+ * The image carries no information a reader needs, so assistive technology
1163
+ * skips it. Word writes this as an extension on `wp:docPr`
1164
+ * (`{C183D7F6-B498-43B3-948B-1728B52AA6E4}` holding
1165
+ * `adec:decorative val="1"`), not as an attribute: `CT_NonVisualDrawingProps`
1166
+ * has no `@decorative`.
1167
+ *
1168
+ * Not `hidden`. A decorative image is displayed and skipped by a screen
1169
+ * reader; a hidden one is not displayed at all.
1170
+ */
1162
1171
  decorative?: boolean;
1172
+ /** `wp:docPr @hidden`: the drawing is not displayed. */
1173
+ hidden?: boolean;
1174
+ /**
1175
+ * The `a:ext` entries of the `wp:docPr` extension list that folio does not
1176
+ * model — a creation id, a local-DPI hint — captured as XML in source order.
1177
+ * Written back beside the decorative extension so an extension folio has no
1178
+ * opinion about still survives a save.
1179
+ */
1180
+ docPrExtensions?: string[];
1163
1181
  /** Hyperlink URL for clickable image */
1164
1182
  hlinkHref?: string;
1165
1183
  /** Relationship ID for the clickable image hyperlink */
@@ -1280,8 +1298,12 @@ type Shape = {
1280
1298
  geometryAdjustments?: ShapeGeometryAdjustment[];
1281
1299
  /** Unique ID */
1282
1300
  id?: string;
1283
- /** Name */
1301
+ /** Authored non-visual drawing name (`wp:docPr@name` / `wps:cNvPr@name`) */
1284
1302
  name?: string;
1303
+ /** Alt text for accessibility (`wp:docPr@descr` / `wps:cNvPr@descr`) */
1304
+ alt?: string;
1305
+ /** Authored non-visual drawing title (`wp:docPr@title` / `wps:cNvPr@title`) */
1306
+ title?: string;
1285
1307
  /** Size in EMUs */
1286
1308
  size: ImageSize;
1287
1309
  /** Position for floating shapes */
@@ -1306,6 +1328,12 @@ type TextBox = {
1306
1328
  type: "textBox";
1307
1329
  /** Unique ID */
1308
1330
  id?: string;
1331
+ /** Authored non-visual drawing name (`wp:docPr@name` / `wps:cNvPr@name`) */
1332
+ name?: string;
1333
+ /** Alt text for accessibility (`wp:docPr@descr` / `wps:cNvPr@descr`) */
1334
+ alt?: string;
1335
+ /** Authored non-visual drawing title (`wp:docPr@title` / `wps:cNvPr@title`) */
1336
+ title?: string;
1309
1337
  /** Size */
1310
1338
  size: ImageSize;
1311
1339
  /** Position */
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 { 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-o2RiAASq.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";
@@ -150,6 +150,68 @@ type SerializeDocumentOptions = {
150
150
  };
151
151
  declare const serializeDocumentToDocx: (document: Document, options?: SerializeDocumentOptions) => Promise<ArrayBuffer>;
152
152
  //#endregion
153
+ //#region src/serialize/xmlEscape.d.ts
154
+ /**
155
+ * The one owner of XML character escaping for every part folio writes.
156
+ *
157
+ * Two contexts, two functions. A value going into element content takes
158
+ * {@link escapeXmlText}; a value going between the quotes of an attribute
159
+ * takes {@link escapeXmlAttribute}. Nothing else escapes XML by hand: a
160
+ * second escaper always ends up disagreeing with this one about some
161
+ * character, and the disagreement is a package Word refuses to open.
162
+ *
163
+ * Both functions guarantee the same contract: **the result is always legal
164
+ * XML 1.0 character data.** That is what makes the contract checkable — a
165
+ * caller cannot produce a corrupt part by forgetting something.
166
+ *
167
+ * XML 1.0 §2.2 `Char` admits tab, LF, CR, `#x20`-`#xD7FF`, `#xE000`-`#xFFFD`
168
+ * and the astral planes. Everything else — the rest of C0, `#xFFFE`,
169
+ * `#xFFFF`, an unpaired surrogate — cannot appear in a document at all, and
170
+ * cannot be escaped into one either: `&#0;` is as illegal as a raw NUL
171
+ * (§4.1 requires a character reference to refer to a legal `Char`). The only
172
+ * output that is well-formed is one without them, so they are dropped here.
173
+ * Callers that own an input boundary sanitise before this point, with
174
+ * `sanitizeXmlCharacters`, so a user-visible value loses its illegal
175
+ * characters where something can still report it; the drop below is the last
176
+ * line of defence for a boundary nobody has covered yet.
177
+ *
178
+ * The whitespace rules are where the two contexts part:
179
+ *
180
+ * - §3.3.3 normalises tab, LF and CR in an **attribute value** to a space in
181
+ * every conformant parser, so a literal one does not survive a save. They
182
+ * are written as character references, which the same step leaves alone.
183
+ * - §2.11 normalises a literal CR (and CRLF) in **content** to LF on read, so
184
+ * CR is written as a reference there too. Tab and LF survive as themselves.
185
+ *
186
+ * Both contexts escape all five of `& < > " '`. Only `&` and `<` must be
187
+ * escaped in content, but folio has always written the full set, `>` closes
188
+ * the `]]>` hazard of §2.4 without a special case, and one lexical form
189
+ * across every writer is worth more than the bytes it costs. Every spelling
190
+ * here reads back as the character it stands for, so the rule preserves the
191
+ * value whichever context it lands in.
192
+ */
193
+ /** Escape a value for XML element content. Tab and LF survive as themselves. */
194
+ declare const escapeXmlText: (value: string) => string;
195
+ /**
196
+ * Escape a value for an XML attribute value, of either quoting. Tab, LF and CR
197
+ * become character references so attribute-value normalisation cannot flatten
198
+ * them to spaces.
199
+ */
200
+ declare const escapeXmlAttribute: (value: string) => string;
201
+ /** Whether `value` holds a character XML 1.0 cannot represent at all. */
202
+ declare const hasIllegalXmlCharacters: (value: string) => boolean;
203
+ /**
204
+ * Make a value from outside folio representable in XML: an unpaired surrogate
205
+ * becomes U+FFFD, every other character XML cannot hold is dropped.
206
+ *
207
+ * This is the rule for an input boundary — paste, a document operation, a
208
+ * markdown or legal-source compile, a template fill — where the value is still
209
+ * attached to the request that carried it and a warning still has somewhere to
210
+ * go. `escapeXmlText` and `escapeXmlAttribute` apply the same rule again
211
+ * further down, but by then nobody can say which input lost a character.
212
+ */
213
+ declare const sanitizeXmlCharacters: (value: string) => string;
214
+ //#endregion
153
215
  //#region src/serialize/textWhitespace.d.ts
154
216
  /**
155
217
  * Whether `<w:t>` needs `xml:space="preserve"` to render the text as written.
@@ -192,4 +254,4 @@ declare const validateDocxPackage: (buffer: ArrayBuffer | Uint8Array) => Promise
192
254
  declare const validateDocumentModel: (document: Document) => ValidateDocumentModelResult;
193
255
  declare const assertValidDocumentModel: (document: Document) => void;
194
256
  //#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 };
257
+ 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
@@ -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\"?>",
@@ -143,7 +231,7 @@ const serializeParagraphProperties = (paragraph) => {
143
231
  const formatting = paragraph.formatting;
144
232
  if (!formatting && !paragraph.sectionProperties) return "";
145
233
  const parts = [];
146
- if (formatting?.styleId) parts.push(`<w:pStyle w:val="${escapeXml(formatting.styleId)}"/>`);
234
+ if (formatting?.styleId) parts.push(`<w:pStyle w:val="${escapeXmlAttribute(formatting.styleId)}"/>`);
147
235
  if (formatting?.keepNext) parts.push("<w:keepNext/>");
148
236
  if (formatting?.keepLines) parts.push("<w:keepLines/>");
149
237
  if (formatting?.pageBreakBefore) parts.push("<w:pageBreakBefore/>");
@@ -185,7 +273,7 @@ const serializeRun = (run) => {
185
273
  const serializeRunProperties = (formatting) => {
186
274
  if (!formatting) return "";
187
275
  const parts = [];
188
- if (formatting.styleId) parts.push(`<w:rStyle w:val="${escapeXml(formatting.styleId)}"/>`);
276
+ if (formatting.styleId) parts.push(`<w:rStyle w:val="${escapeXmlAttribute(formatting.styleId)}"/>`);
189
277
  if (formatting.bold === true) parts.push("<w:b/>");
190
278
  else if (formatting.bold === false) parts.push("<w:b w:val=\"0\"/>");
191
279
  if (formatting.boldCs === true) parts.push("<w:bCs/>");
@@ -206,13 +294,13 @@ const serializeRunProperties = (formatting) => {
206
294
  };
207
295
  const serializeRunContent = (content) => {
208
296
  switch (content.type) {
209
- case "text": return `<w:t${requiresXmlSpacePreserve(content.text) ? " xml:space=\"preserve\"" : ""}>${escapeXml(content.text)}</w:t>`;
297
+ case "text": return `<w:t${requiresXmlSpacePreserve(content.text) ? " xml:space=\"preserve\"" : ""}>${escapeXmlText(content.text)}</w:t>`;
210
298
  case "tab":
211
299
  if (!content.positional) return "<w:tab/>";
212
300
  return `<w:ptab${attr("w:relativeTo", content.positional.relativeTo)}${attr("w:alignment", content.positional.alignment)}${attr("w:leader", content.positional.leader)}/>`;
213
301
  case "break": return `<w:br${attr("w:type", content.breakType)}/>`;
214
302
  case "renderedPageBreak": return "<w:lastRenderedPageBreak/>";
215
- case "symbol": return `<w:sym w:font="${escapeXml(content.font)}" w:char="${escapeXml(content.char)}"/>`;
303
+ case "symbol": return `<w:sym w:font="${escapeXmlAttribute(content.font)}" w:char="${escapeXmlAttribute(content.char)}"/>`;
216
304
  case "footnoteRef": return `<w:footnoteReference w:id="${content.id}"/>`;
217
305
  case "endnoteRef": return `<w:endnoteReference w:id="${content.id}"/>`;
218
306
  case "fieldChar":
@@ -264,10 +352,10 @@ const renderCellBorders = (table) => {
264
352
  };
265
353
  const borderEdgeXml = (tag, spec) => {
266
354
  if (!spec) return `<${tag} w:val="nil"/>`;
267
- if (spec.style === "none" || spec.style === "nil") return `<${tag} w:val="${escapeXml(spec.style)}"/>`;
355
+ if (spec.style === "none" || spec.style === "nil") return `<${tag} w:val="${escapeXmlAttribute(spec.style)}"/>`;
268
356
  const sz = spec.size ?? 4;
269
357
  const color = spec.color?.rgb ?? "CCCCCC";
270
- return `<${tag} w:val="${escapeXml(spec.style)}" w:sz="${sz}" w:space="0" w:color="${escapeXml(color)}"/>`;
358
+ return `<${tag} w:val="${escapeXmlAttribute(spec.style)}" w:sz="${sz}" w:space="0" w:color="${escapeXmlAttribute(color)}"/>`;
271
359
  };
272
360
  /**
273
361
  * The grid this generator gives a table that declares no borders of its own.
@@ -320,10 +408,10 @@ const serializeStyle = (style) => {
320
408
  }).replace(/^<w:pPr>|<\/w:pPr>$/gu, "") : "";
321
409
  const rPr = serializeRunProperties(style.rPr);
322
410
  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)}"/>` : "",
411
+ `<w:style w:type="${style.type}" w:styleId="${escapeXmlAttribute(style.styleId)}"${style.default ? " w:default=\"1\"" : ""}>`,
412
+ `<w:name w:val="${escapeXmlAttribute(style.name ?? style.styleId)}"/>`,
413
+ style.basedOn ? `<w:basedOn w:val="${escapeXmlAttribute(style.basedOn)}"/>` : "",
414
+ style.next ? `<w:next w:val="${escapeXmlAttribute(style.next)}"/>` : "",
327
415
  style.qFormat ? "<w:qFormat/>" : "",
328
416
  pPr ? `<w:pPr>${pPr}</w:pPr>` : "",
329
417
  rPr,
@@ -349,7 +437,7 @@ const serializeNumberingLevel = (level) => [
349
437
  `<w:numFmt w:val="${level.numFmt}"/>`,
350
438
  level.isLgl ? "<w:isLgl/>" : "",
351
439
  level.suffix ? `<w:suff w:val="${level.suffix}"/>` : "",
352
- `<w:lvlText w:val="${escapeXml(level.lvlText)}"/>`,
440
+ `<w:lvlText w:val="${escapeXmlAttribute(level.lvlText)}"/>`,
353
441
  `<w:lvlJc w:val="${level.lvlJc ?? "left"}"/>`,
354
442
  level.pPr ? serializeParagraphProperties({
355
443
  type: "paragraph",
@@ -367,7 +455,7 @@ const serializeCoreProperties = (document) => {
367
455
  const creator = properties?.creator ?? "Stella";
368
456
  const created = properties?.created?.toISOString() ?? now;
369
457
  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>`;
458
+ 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
459
  };
372
460
  //#endregion
373
461
  //#region src/validate/docx.ts
@@ -711,6 +799,10 @@ const validateRun = (run, path, ctx) => {
711
799
  for (const [index, content] of run.content.entries()) validateRunContent(content, `${path}.content[${index}]`, ctx);
712
800
  };
713
801
  const validateRunContent = (content, path, ctx) => {
802
+ if (content.type === "text") {
803
+ if (hasIllegalXmlCharacters(content.text)) addWarning(ctx, `${path}.text`, "Text holds characters XML 1.0 cannot represent; they will be dropped on save.");
804
+ return;
805
+ }
714
806
  if (content.type === "drawing") {
715
807
  validateImage(content.image, `${path}.image`, ctx, { hasPreservedRawDrawing: content.rawXml?.trim() !== "" });
716
808
  return;
@@ -1181,9 +1273,14 @@ const countNewlines = (text) => {
1181
1273
  /** A token that starts a new structural block, so no body may run past it. */
1182
1274
  const startsStructure = (token) => isLegalDirectiveToken(token) || isTokenType(token, "heading");
1183
1275
  const parseLegalSource = (source, options = {}) => {
1276
+ const sanitizedSource = sanitizeXmlCharacters(source);
1184
1277
  const state = {
1185
1278
  blocks: [],
1186
- diagnostics: [],
1279
+ diagnostics: hasIllegalXmlCharacters(source) ? [{
1280
+ code: "illegal-xml-characters-dropped",
1281
+ message: "The source held characters XML 1.0 cannot represent; they were dropped. An unpaired surrogate became U+FFFD.",
1282
+ severity: "warning"
1283
+ }] : [],
1187
1284
  fixes: [],
1188
1285
  meta: {
1189
1286
  kind: DEFAULT_KIND,
@@ -1195,7 +1292,7 @@ const parseLegalSource = (source, options = {}) => {
1195
1292
  },
1196
1293
  title: null
1197
1294
  },
1198
- cursor: new TokenCursor(lexLegalSource(source))
1295
+ cursor: new TokenCursor(lexLegalSource(sanitizedSource))
1199
1296
  };
1200
1297
  for (;;) {
1201
1298
  const token = state.cursor.current;
@@ -2574,9 +2671,9 @@ const compileMarkdownToContent = (markdown) => {
2574
2671
  levels: /* @__PURE__ */ new Map()
2575
2672
  };
2576
2673
  return {
2577
- content: blocksFromTokens(lexMarkdown(markdown), numIds),
2674
+ content: blocksFromTokens(lexMarkdown(sanitizeXmlCharacters(markdown)), numIds),
2578
2675
  ...numIds.levels.size > 0 && { numbering: buildNumbering(numIds.levels) }
2579
2676
  };
2580
2677
  };
2581
2678
  //#endregion
2582
- export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, parseLegalSource, requiresXmlSpacePreserve, sanitizeExternalUrl, serializeDocumentToDocx, validateDocumentModel, validateDocxPackage, validateLegalDraft };
2679
+ 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";
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-o2RiAASq.js";
2
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/docx-core",
3
- "version": "0.22.0",
3
+ "version": "0.23.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",