@stll/docx-core 0.30.0 → 0.30.1

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.
Binary file
package/dist/index.d.ts CHANGED
@@ -177,6 +177,55 @@ type SerializeDocumentOptions = {
177
177
  */
178
178
  declare const serializeDocumentToDocx: (document: Document, options?: SerializeDocumentOptions) => Promise<ArrayBuffer>;
179
179
  //#endregion
180
+ //#region src/serialize/numericIds.d.ts
181
+ declare const InvalidOoxmlNumericIdError_base: import("better-result").TaggedErrorClass<"InvalidOoxmlNumericIdError">;
182
+ /** A writer would emit an identifier outside its OOXML schema's numeric domain. */
183
+ declare class InvalidOoxmlNumericIdError extends InvalidOoxmlNumericIdError_base<{
184
+ message: string;
185
+ partPath: string;
186
+ elementName: string;
187
+ attributeName: string;
188
+ value: string;
189
+ }> {}
190
+ type NumericIdOptions = {
191
+ value: string | number;
192
+ partPath: string;
193
+ elementName: string;
194
+ attributeName: string;
195
+ domain?: "signed32" | "unsigned32";
196
+ };
197
+ declare const isValidOoxmlNumericId: (value: string | number, domain?: "signed32" | "unsigned32") => boolean;
198
+ declare const assertValidOoxmlNumericId: ({ value, partPath, elementName, attributeName, domain }: NumericIdOptions) => void;
199
+ type NumericIdAttributeOptions = {
200
+ elementName: string;
201
+ elementNamespace: string | undefined;
202
+ attributeName: string;
203
+ attributeNamespace: string | undefined;
204
+ };
205
+ /** Shared schema classification for import normalization and writer validation. */
206
+ declare const ooxmlNumericIdDomain: ({ elementName, elementNamespace, attributeName, attributeNamespace }: NumericIdAttributeOptions) => "signed32" | "unsigned32" | undefined;
207
+ type OoxmlNumericIdAttributeOptions = {
208
+ elementName: string;
209
+ attributeName: string;
210
+ };
211
+ /** Attributes an identity scan must retain, derived from the domain classifier. */
212
+ declare const isOoxmlNumericIdAttributeName: ({ elementName, attributeName }: OoxmlNumericIdAttributeOptions) => boolean;
213
+ /** Conservative presence check; safe IDs must still be reserved during import repair. */
214
+ declare const mayContainOoxmlNumericIds: (xml: string) => boolean;
215
+ /**
216
+ * Conservative lexical preflight; namespace classification remains authoritative.
217
+ * A prefix is considered numeric if any scope binds it to WordprocessingML. This can send
218
+ * a shadowed foreign attribute to the full parser, but cannot hide a numeric one.
219
+ * Suspicious values with entity-encoded bindings or values require the authoritative scan.
220
+ */
221
+ declare const mayContainInvalidOoxmlNumericIds: (xml: string, mode?: "schema" | "range") => boolean;
222
+ /**
223
+ * Validate both authored and opaque replayed identifiers by namespace URI.
224
+ * This runs at ZIP exits too, so unchanged parts cannot bypass the writer guard.
225
+ * Permission-range ids are strings in OOXML and intentionally remain unrestricted.
226
+ */
227
+ declare const assertValidOoxmlNumericIds: (xml: string, partPath: string) => void;
228
+ //#endregion
180
229
  //#region src/serialize/xml.d.ts
181
230
  /**
182
231
  * The one writer for a `CT_OnOff` element: `w:b`, `w:cantSplit`, `w:hideMark`,
@@ -320,4 +369,4 @@ declare const validateDocxPackage: (buffer: ArrayBuffer | Uint8Array) => Promise
320
369
  declare const validateDocumentModel: (document: Document) => ValidateDocumentModelResult;
321
370
  declare const assertValidDocumentModel: (document: Document) => void;
322
371
  //#endregion
323
- export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBackground, type DocumentBackgroundDrawing, 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, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
372
+ export { type Autofix, type BlockContent, type BreakContent, type CompiledLegalDocument, DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, type Document, type DocumentBackground, type DocumentBackgroundDrawing, type DocumentBody, type DocxConformanceClass, type DocxPackage, type DocxPackageIssueCode, InvalidOoxmlNumericIdError, 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, assertValidOoxmlNumericId, assertValidOoxmlNumericIds, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, isOoxmlNumericIdAttributeName, isValidOoxmlNumericId, mayContainInvalidOoxmlNumericIds, mayContainOoxmlNumericIds, ooxmlNumericIdDomain, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { $ as paragraphNumberingReferenceId, Q as paragraphNumberingReference, U as headingOutlineLevel, Z as paragraphNumberingLevel, _ as borderStyleToken, c as isNoteReferenceId, et as paragraphNumberingSlots, l as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, x as statesNoBorder } from "./document-DdWrTPQY.js";
1
+ import { $ as paragraphNumberingReferenceId, Q as paragraphNumberingReference, U as headingOutlineLevel, Z as paragraphNumberingLevel, _ as borderStyleToken, c as isNoteReferenceId, et as paragraphNumberingSlots, i as MAX_REVISION_ID, l as isOoxmlSymbolCharacter, t as DOCX_CONFORMANCE_CLASSES, x as statesNoBorder } from "./document-DdWrTPQY.js";
2
2
  import { i as serializeSequenceChildren } from "./sequenceChildren-BIixCB49.js";
3
3
  import { i as sanitizeXmlCharacters, n as escapeXmlText, r as hasIllegalXmlCharacters, t as escapeXmlAttribute } from "./xmlEscape-T-2DeGlS.js";
4
- import { panic } from "better-result";
4
+ import { TaggedError, panic } from "better-result";
5
5
  import JSZip from "jszip";
6
6
  import { XMLParser, XMLValidator } from "fast-xml-parser";
7
7
  import { Marked } from "marked";
@@ -18,6 +18,204 @@ import { Marked } from "marked";
18
18
  */
19
19
  const requiresXmlSpacePreserve = (text) => text.startsWith(" ") || text.endsWith(" ") || text.includes(" ");
20
20
  //#endregion
21
+ //#region src/serialize/numericIds.ts
22
+ const WORD_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
23
+ const DRAWING_NAMESPACES = /* @__PURE__ */ new Set([
24
+ "http://schemas.openxmlformats.org/drawingml/2006/main",
25
+ "http://schemas.openxmlformats.org/drawingml/2006/picture",
26
+ "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
27
+ "http://purl.oclc.org/ooxml/drawingml/main",
28
+ "http://purl.oclc.org/ooxml/drawingml/picture",
29
+ "http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing",
30
+ "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
31
+ ]);
32
+ const NUMBERING_ATTRIBUTES = /* @__PURE__ */ new Set([
33
+ "numId",
34
+ "abstractNumId",
35
+ "numPicBulletId"
36
+ ]);
37
+ const ID_VALUE_ELEMENTS = /* @__PURE__ */ new Set([
38
+ "id",
39
+ "numId",
40
+ "abstractNumId",
41
+ "lvlPicBulletId"
42
+ ]);
43
+ const STRING_ID_ELEMENTS = /* @__PURE__ */ new Set(["permStart", "permEnd"]);
44
+ const MAX_UNSIGNED_ID = 4294967295;
45
+ const MIN_SIGNED_ID = -2147483648;
46
+ /** A writer would emit an identifier outside its OOXML schema's numeric domain. */
47
+ var InvalidOoxmlNumericIdError = class extends TaggedError("InvalidOoxmlNumericIdError") {};
48
+ const isValidOoxmlNumericId = (value, domain = "signed32") => {
49
+ const spelling = String(value).trim();
50
+ const numeric = Number(spelling);
51
+ const min = domain === "unsigned32" ? 0 : MIN_SIGNED_ID;
52
+ const max = domain === "unsigned32" ? MAX_UNSIGNED_ID : MAX_REVISION_ID;
53
+ return /^[+-]?\d+$/u.test(spelling) && Number.isInteger(numeric) && numeric >= min && numeric <= max;
54
+ };
55
+ const assertValidOoxmlNumericId = ({ value, partPath, elementName, attributeName, domain = "signed32" }) => {
56
+ if (isValidOoxmlNumericId(value, domain)) return;
57
+ throw new InvalidOoxmlNumericIdError({
58
+ message: `${partPath}: ${elementName} ${attributeName} must be an integer in [${domain === "unsigned32" ? 0 : MIN_SIGNED_ID}, ${domain === "unsigned32" ? MAX_UNSIGNED_ID : MAX_REVISION_ID}], got ${String(value)}`,
59
+ partPath,
60
+ elementName,
61
+ attributeName,
62
+ value: String(value)
63
+ });
64
+ };
65
+ /** Shared schema classification for import normalization and writer validation. */
66
+ const ooxmlNumericIdDomain = ({ elementName, elementNamespace, attributeName, attributeNamespace }) => {
67
+ const elementLocalName = localName$1(elementName);
68
+ const attributeLocalName = localName$1(attributeName);
69
+ if (WORD_NAMESPACES.has(attributeNamespace ?? "") && (attributeLocalName === "id" && !(WORD_NAMESPACES.has(elementNamespace ?? "") && STRING_ID_ELEMENTS.has(elementLocalName)) || NUMBERING_ATTRIBUTES.has(attributeLocalName) || attributeLocalName === "val" && WORD_NAMESPACES.has(elementNamespace ?? "") && ID_VALUE_ELEMENTS.has(elementLocalName))) return "signed32";
70
+ if (attributeName === "id" && DRAWING_NAMESPACES.has(elementNamespace ?? "") && (elementLocalName === "docPr" || elementLocalName === "cNvPr")) return "unsigned32";
71
+ };
72
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
73
+ const localName$1 = (name) => name.slice(name.indexOf(":") + 1);
74
+ const namespaceUri = (name, bindings) => {
75
+ const colon = name.indexOf(":");
76
+ return bindings.get(colon === -1 ? "" : name.slice(0, colon));
77
+ };
78
+ const decodeAttributeReferences = (value) => value.replace(/&(?:#(x[\da-f]+|\d+)|amp|lt|gt|quot|apos);/giu, (reference, digits) => {
79
+ if (digits !== void 0) {
80
+ const codePoint = digits.toLowerCase().startsWith("x") ? Number.parseInt(digits.slice(1), 16) : Number(digits);
81
+ if (codePoint <= 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) return reference;
82
+ return String.fromCodePoint(codePoint);
83
+ }
84
+ switch (reference) {
85
+ case "&amp;": return "&";
86
+ case "&lt;": return "<";
87
+ case "&gt;": return ">";
88
+ case "&quot;": return "\"";
89
+ case "&apos;": return "'";
90
+ default: return reference;
91
+ }
92
+ });
93
+ const ID_ATTRIBUTE_NAMES = ["id", ...NUMBERING_ATTRIBUTES].join("|");
94
+ const ID_ELEMENT_NAMES = [...ID_VALUE_ELEMENTS].join("|");
95
+ /** Attributes an identity scan must retain, derived from the domain classifier. */
96
+ const isOoxmlNumericIdAttributeName = ({ elementName, attributeName }) => {
97
+ const attribute = localName$1(attributeName);
98
+ return attribute === "id" || NUMBERING_ATTRIBUTES.has(attribute) || attribute === "val" && ID_VALUE_ELEMENTS.has(localName$1(elementName));
99
+ };
100
+ const ID_CANDIDATE = new RegExp(`\\b(?:${ID_ATTRIBUTE_NAMES})\\s*=|<(?:[^\\s<>/:]+:)?(?:${ID_ELEMENT_NAMES})(?:[\\s/>])`, "u");
101
+ /** Conservative presence check; safe IDs must still be reserved during import repair. */
102
+ const mayContainOoxmlNumericIds = (xml) => ID_CANDIDATE.test(xml);
103
+ const PREFIX = "[^\\s<>/:=\"']+";
104
+ const ID_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?(?:${ID_ATTRIBUTE_NAMES}))\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
105
+ const ID_VALUE_TAG = new RegExp(`<((?:${PREFIX}:)?(?:${ID_ELEMENT_NAMES}))(?=[\\s/>])((?:[^<>"']|"[^"]*"|'[^']*')*)>`, "gu");
106
+ const VALUE_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?val)\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
107
+ const RANGE_ATTRIBUTE = new RegExp(`(?:^|\\s)((?:${PREFIX}:)?(?:${ID_ATTRIBUTE_NAMES}|val))\\s*=\\s*(["'])\\s*([+-]?\\d{10,}|-\\d+|[^"'<>]*&[^"'<>]*)\\s*\\2`, "gu");
108
+ const hasRangeCandidate = (xml) => {
109
+ for (const match of xml.matchAll(RANGE_ATTRIBUTE)) {
110
+ const value = match[3] ?? "";
111
+ if (value.includes("&")) return true;
112
+ const domain = (match[1] ?? "").includes(":") ? "signed32" : "unsigned32";
113
+ if (!isValidOoxmlNumericId(value.trim(), domain)) return true;
114
+ }
115
+ return false;
116
+ };
117
+ const NAMESPACE_BINDING = new RegExp(`\\bxmlns(?::(${PREFIX}))?\\s*=\\s*(["'])([\\s\\S]*?)\\2`, "gu");
118
+ const prefixOf = (name) => {
119
+ const colon = name.indexOf(":");
120
+ return colon === -1 ? "" : name.slice(0, colon);
121
+ };
122
+ /**
123
+ * Conservative lexical preflight; namespace classification remains authoritative.
124
+ * A prefix is considered numeric if any scope binds it to WordprocessingML. This can send
125
+ * a shadowed foreign attribute to the full parser, but cannot hide a numeric one.
126
+ * Suspicious values with entity-encoded bindings or values require the authoritative scan.
127
+ */
128
+ const mayContainInvalidOoxmlNumericIds = (xml, mode = "schema") => {
129
+ if (mode === "range") {
130
+ if (!hasRangeCandidate(xml)) return false;
131
+ } else if (!mayContainOoxmlNumericIds(xml)) return false;
132
+ const wordPrefixes = /* @__PURE__ */ new Set();
133
+ for (const match of xml.matchAll(NAMESPACE_BINDING)) {
134
+ const namespace = match[3] ?? "";
135
+ if (namespace.includes("&")) return true;
136
+ if (WORD_NAMESPACES.has(namespace)) wordPrefixes.add(match[1] ?? "");
137
+ }
138
+ const needsScan = (value, domain) => {
139
+ if (value.includes("&")) return true;
140
+ if (mode === "range" && !/^[+-]?\d+$/u.test(value.trim())) return false;
141
+ return !isValidOoxmlNumericId(value, domain ?? "unsigned32");
142
+ };
143
+ for (const match of xml.matchAll(ID_ATTRIBUTE)) {
144
+ const name = match[1] ?? "";
145
+ if (name.includes(":")) {
146
+ if (wordPrefixes.has(prefixOf(name)) && needsScan(match[3] ?? "", "signed32")) return true;
147
+ continue;
148
+ }
149
+ if (name === "id" && needsScan(match[3] ?? "")) return true;
150
+ }
151
+ for (const match of xml.matchAll(ID_VALUE_TAG)) {
152
+ if (!wordPrefixes.has(prefixOf(match[1] ?? ""))) continue;
153
+ for (const attribute of (match[2] ?? "").matchAll(VALUE_ATTRIBUTE)) {
154
+ const name = attribute[1] ?? "";
155
+ if (name.includes(":") && wordPrefixes.has(prefixOf(name)) && needsScan(attribute[3] ?? "", "signed32")) return true;
156
+ }
157
+ }
158
+ return false;
159
+ };
160
+ /**
161
+ * Validate both authored and opaque replayed identifiers by namespace URI.
162
+ * This runs at ZIP exits too, so unchanged parts cannot bypass the writer guard.
163
+ * Permission-range ids are strings in OOXML and intentionally remain unrestricted.
164
+ */
165
+ const assertValidOoxmlNumericIds = (xml, partPath) => {
166
+ if (!mayContainInvalidOoxmlNumericIds(xml)) return;
167
+ const parser = new XMLParser({
168
+ preserveOrder: true,
169
+ ignoreAttributes: false,
170
+ attributeNamePrefix: "",
171
+ parseTagValue: false,
172
+ parseAttributeValue: false,
173
+ processEntities: false,
174
+ attributeValueProcessor: (_name, value) => decodeAttributeReferences(value),
175
+ htmlEntities: false,
176
+ ignoreDeclaration: true
177
+ });
178
+ const visit = (nodes, inherited) => {
179
+ if (!Array.isArray(nodes)) return;
180
+ for (const node of nodes) {
181
+ if (!isRecord$1(node)) continue;
182
+ const attributes = node[":@"];
183
+ let localBindings;
184
+ if (isRecord$1(attributes)) for (const [name, value] of Object.entries(attributes)) {
185
+ if (typeof value !== "string") continue;
186
+ if (name === "xmlns" || name.startsWith("xmlns:")) {
187
+ localBindings ??= new Map(inherited);
188
+ localBindings.set(name === "xmlns" ? "" : name.slice(6), value);
189
+ }
190
+ }
191
+ const bindings = localBindings ?? inherited;
192
+ for (const [elementName, children] of Object.entries(node)) {
193
+ if (elementName === ":@" || elementName.startsWith("#") || elementName.startsWith("?")) continue;
194
+ const elementNamespace = namespaceUri(elementName, bindings);
195
+ if (isRecord$1(attributes)) for (const [attributeName, value] of Object.entries(attributes)) {
196
+ if (typeof value !== "string" && typeof value !== "number") continue;
197
+ const attributeNamespace = attributeName.includes(":") ? namespaceUri(attributeName, bindings) : void 0;
198
+ const domain = ooxmlNumericIdDomain({
199
+ elementName,
200
+ elementNamespace,
201
+ attributeName,
202
+ attributeNamespace
203
+ });
204
+ if (domain !== void 0) assertValidOoxmlNumericId({
205
+ value,
206
+ partPath,
207
+ elementName,
208
+ attributeName,
209
+ domain
210
+ });
211
+ }
212
+ visit(children, bindings);
213
+ }
214
+ }
215
+ };
216
+ visit(parser.parse(xml), /* @__PURE__ */ new Map());
217
+ };
218
+ //#endregion
21
219
  //#region src/serialize/xml.ts
22
220
  const attr = (name, value) => value === void 0 ? "" : ` ${name}="${escapeXmlAttribute(String(value))}"`;
23
221
  /**
@@ -173,6 +371,10 @@ const serializeDocumentToDocx = async (document, options = {}) => {
173
371
  if (hasNumbering) word?.file("numbering.xml", serializeNumbering(document.package.numbering));
174
372
  word?.file(DEFAULT_FOOTER_PART_NAME, buildFooterXml(options.language));
175
373
  word?.folder("_rels")?.file("document.xml.rels", documentRelsXml(hasNumbering));
374
+ for (const [path, file] of Object.entries(zip.files)) {
375
+ if (file.dir || !path.endsWith(".xml")) continue;
376
+ assertValidOoxmlNumericIds(await file.async("text"), path);
377
+ }
176
378
  return await zip.generateAsync({
177
379
  type: "arraybuffer",
178
380
  compression: "DEFLATE",
@@ -2847,4 +3049,4 @@ const compileMarkdownToContent = (markdown) => {
2847
3049
  };
2848
3050
  };
2849
3051
  //#endregion
2850
- export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, assertValidDocumentModel, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
3052
+ export { DOCX_CONFORMANCE_CLASSES, DOCX_PACKAGE_ISSUE_CODES, InvalidOoxmlNumericIdError, assertValidDocumentModel, assertValidOoxmlNumericId, assertValidOoxmlNumericIds, compileLegalSourceToDocument, compileLegalSourceToDocx, compileMarkdownToContent, escapeXmlAttribute, escapeXmlText, hasIllegalXmlCharacters, isOoxmlNumericIdAttributeName, isValidOoxmlNumericId, mayContainInvalidOoxmlNumericIds, mayContainOoxmlNumericIds, ooxmlNumericIdDomain, parseLegalSource, pushOnOffElement, requiresXmlSpacePreserve, sanitizeExternalUrl, sanitizeXmlCharacters, serializeDocumentToDocx, serializeOnOffElement, validateDocumentModel, validateDocxPackage, validateLegalDraft };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stll/docx-core",
3
- "version": "0.30.0",
3
+ "version": "0.30.1",
4
4
  "description": "Typed OOXML/DOCX model, validation, serialization, legal-source compilation, and browser-native package projection.",
5
5
  "keywords": [
6
6
  "document-model",