@folijs/docx 0.0.0-stage → 0.3.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.
Files changed (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +141 -2
  4. package/dist/export/content.d.ts +17 -0
  5. package/dist/export/content.d.ts.map +1 -0
  6. package/dist/export/content.js +165 -0
  7. package/dist/export/content.js.map +1 -0
  8. package/dist/export/index.d.ts +14 -0
  9. package/dist/export/index.d.ts.map +1 -0
  10. package/dist/export/index.js +352 -0
  11. package/dist/export/index.js.map +1 -0
  12. package/dist/export/parts.d.ts +24 -0
  13. package/dist/export/parts.d.ts.map +1 -0
  14. package/dist/export/parts.js +413 -0
  15. package/dist/export/parts.js.map +1 -0
  16. package/dist/export/properties.d.ts +39 -0
  17. package/dist/export/properties.d.ts.map +1 -0
  18. package/dist/export/properties.js +506 -0
  19. package/dist/export/properties.js.map +1 -0
  20. package/dist/export/xmlout.d.ts +63 -0
  21. package/dist/export/xmlout.d.ts.map +1 -0
  22. package/dist/export/xmlout.js +194 -0
  23. package/dist/export/xmlout.js.map +1 -0
  24. package/dist/import/content.d.ts +35 -0
  25. package/dist/import/content.d.ts.map +1 -0
  26. package/dist/import/content.js +370 -0
  27. package/dist/import/content.js.map +1 -0
  28. package/dist/import/index.d.ts +26 -0
  29. package/dist/import/index.d.ts.map +1 -0
  30. package/dist/import/index.js +96 -0
  31. package/dist/import/index.js.map +1 -0
  32. package/dist/import/ooxml.d.ts +38 -0
  33. package/dist/import/ooxml.d.ts.map +1 -0
  34. package/dist/import/ooxml.js +70 -0
  35. package/dist/import/ooxml.js.map +1 -0
  36. package/dist/import/parts.d.ts +35 -0
  37. package/dist/import/parts.d.ts.map +1 -0
  38. package/dist/import/parts.js +365 -0
  39. package/dist/import/parts.js.map +1 -0
  40. package/dist/import/properties.d.ts +50 -0
  41. package/dist/import/properties.d.ts.map +1 -0
  42. package/dist/import/properties.js +403 -0
  43. package/dist/import/properties.js.map +1 -0
  44. package/dist/import/report.d.ts +28 -0
  45. package/dist/import/report.d.ts.map +1 -0
  46. package/dist/import/report.js +42 -0
  47. package/dist/import/report.js.map +1 -0
  48. package/dist/index.d.ts +6 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +6 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/package.d.ts +70 -0
  53. package/dist/package.d.ts.map +1 -0
  54. package/dist/package.js +259 -0
  55. package/dist/package.js.map +1 -0
  56. package/dist/xml.d.ts +79 -0
  57. package/dist/xml.d.ts.map +1 -0
  58. package/dist/xml.js +384 -0
  59. package/dist/xml.js.map +1 -0
  60. package/dist/zip.d.ts +66 -0
  61. package/dist/zip.d.ts.map +1 -0
  62. package/dist/zip.js +356 -0
  63. package/dist/zip.js.map +1 -0
  64. package/package.json +36 -3
  65. package/src/export/content.ts +229 -0
  66. package/src/export/index.ts +445 -0
  67. package/src/export/parts.ts +545 -0
  68. package/src/export/properties.ts +608 -0
  69. package/src/export/xmlout.ts +225 -0
  70. package/src/import/content.ts +413 -0
  71. package/src/import/index.ts +126 -0
  72. package/src/import/ooxml.ts +77 -0
  73. package/src/import/parts.ts +423 -0
  74. package/src/import/properties.ts +504 -0
  75. package/src/import/report.ts +64 -0
  76. package/src/index.ts +24 -0
  77. package/src/package.ts +328 -0
  78. package/src/xml.ts +443 -0
  79. package/src/zip.ts +401 -0
@@ -0,0 +1,126 @@
1
+ import { type FoliDocument, parseDocument } from "@folijs/core";
2
+ import {
3
+ DocxError,
4
+ type DocxPackage,
5
+ type ReadPackageOptions,
6
+ type Relationship,
7
+ readPackage,
8
+ } from "../package.js";
9
+ import type { XmlElement } from "../xml.js";
10
+ import { blocks, type ContentContext, Moves } from "./content.js";
11
+ import { child, isW, REL, W_STRICT } from "./ooxml.js";
12
+ import { comments, numbering, styles, theme } from "./parts.js";
13
+ import { section } from "./properties.js";
14
+ import { type ImportReport, Recorder } from "./report.js";
15
+
16
+ export interface DocxImport {
17
+ /** The document in schema v3, validated. */
18
+ readonly document: FoliDocument;
19
+ /**
20
+ * The package it was read from. Export (8.5) writes the parts Foli does not edit back from
21
+ * it, unchanged; keep it with the document.
22
+ */
23
+ readonly package: DocxPackage;
24
+ readonly report: ImportReport;
25
+ }
26
+
27
+ /** Reads a `.docx` into schema v3, keeping its package for export. */
28
+ export async function importDocx(
29
+ bytes: Uint8Array,
30
+ options: ReadPackageOptions = {},
31
+ ): Promise<DocxImport> {
32
+ return importPackage(await readPackage(bytes, options));
33
+ }
34
+
35
+ /**
36
+ * The document of a package in schema v3: paragraphs with their properties, runs as text with
37
+ * marks, tracked changes, comments, styles, numbering, the theme and sections. Every element
38
+ * Foli does not model is kept verbatim (opaque nodes, `ext`, attribute bags) and counted in the
39
+ * report; a value the model cannot hold stays in its verbatim element and is reported
40
+ * (`unmodeled`); not imported is only what Word recomputes or shows nothing (`dropped`).
41
+ * Every failure is a `DocxError` (or the package's `ZipError`).
42
+ */
43
+ export function importPackage(pkg: DocxPackage): DocxImport {
44
+ const report = new Recorder();
45
+ const main = pkg.xml(pkg.mainDocument);
46
+ if (main.root.ns === W_STRICT)
47
+ throw new DocxError("Strict Open XML documents are not supported yet");
48
+ if (!isW(main.root, "document"))
49
+ throw new DocxError(`${pkg.mainDocument}: not a WordprocessingML document`);
50
+ const body = child(main.root, "body");
51
+ if (!body) throw new DocxError(`${pkg.mainDocument}: no w:body`);
52
+
53
+ const contextFor = (part: string, source: string): ContentContext => {
54
+ report.part = part;
55
+ // One lookup table per part: hyperlinks resolve in constant time.
56
+ let byId: Map<string, Relationship> | undefined;
57
+ const relationship = (id: string) => {
58
+ byId ??= new Map(pkg.relationships(part).map((r) => [r.id, r]));
59
+ return byId.get(id);
60
+ };
61
+ return { source, report, pkg, part, moves: new Moves(), relationship };
62
+ };
63
+ const related = (
64
+ type: string,
65
+ ): { name: string; root: XmlElement; source: string } | undefined => {
66
+ const relationship = pkg
67
+ .relationships(pkg.mainDocument)
68
+ .find((r) => r.type === type && !r.external);
69
+ const part = relationship?.partName ? pkg.part(relationship.partName) : undefined;
70
+ if (!part) return undefined;
71
+ const xml = pkg.xml(part.name);
72
+ return { name: part.name, root: xml.root, source: xml.source };
73
+ };
74
+
75
+ const mainContext = contextFor(pkg.mainDocument, main.source);
76
+ // The body's section: its last `w:sectPr`, whatever follows it (a bookmark end…).
77
+ const sectPr = body.children
78
+ .filter((c): c is XmlElement => c.kind === "element" && isW(c, "sectPr"))
79
+ .at(-1);
80
+ let content = blocks(body.children, mainContext, sectPr);
81
+ if (content.length === 0) content = [{ type: "paragraph" }];
82
+ const lastSection = sectPr ? section(sectPr, mainContext) : {};
83
+
84
+ const stylesPart = related(REL.styles);
85
+ const styled = stylesPart
86
+ ? styles(stylesPart.root, contextFor(stylesPart.name, stylesPart.source))
87
+ : { defaults: {}, styles: [] };
88
+ const numberingPart = related(REL.numbering);
89
+ const numbered = numberingPart
90
+ ? numbering(numberingPart.root, contextFor(numberingPart.name, numberingPart.source))
91
+ : { abstracts: [], instances: [] };
92
+ const themePart = related(REL.theme);
93
+ const themed = themePart
94
+ ? theme(themePart.root, contextFor(themePart.name, themePart.source))
95
+ : undefined;
96
+ const commentsPart = related(REL.comments);
97
+ const extended = related(REL.commentsExtended);
98
+ const commented = commentsPart
99
+ ? comments(
100
+ commentsPart.root,
101
+ extended?.root,
102
+ contextFor(commentsPart.name, commentsPart.source),
103
+ )
104
+ : [];
105
+
106
+ let document: FoliDocument;
107
+ try {
108
+ document = parseDocument({
109
+ schemaVersion: 3,
110
+ section: lastSection,
111
+ defaults: styled.defaults,
112
+ styles: styled.styles,
113
+ numbering: numbered,
114
+ ...(themed ? { theme: themed } : {}),
115
+ comments: commented,
116
+ content: { type: "doc", content },
117
+ });
118
+ } catch (error) {
119
+ // Each value was checked as it was read; what is left is beyond the model's limits (an
120
+ // element over 16 MiB kept verbatim…). A DocxError like every other import failure.
121
+ throw new DocxError(`Cannot import: ${(error as Error).message}`, { cause: error });
122
+ }
123
+ return { document, package: pkg, report: report.report() };
124
+ }
125
+
126
+ export type { ImportReport } from "./report.js";
@@ -0,0 +1,77 @@
1
+ /** WordprocessingML names and the small helpers the importer reads XML with. */
2
+
3
+ import type { XmlElement, XmlNode } from "../xml.js";
4
+
5
+ export const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
6
+ /** Strict Open XML's WordprocessingML namespace (not supported yet: other units and names). */
7
+ export const W_STRICT = "http://purl.oclc.org/ooxml/wordprocessingml/main";
8
+ export const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
9
+ export const W14 = "http://schemas.microsoft.com/office/word/2010/wordml";
10
+ export const W15 = "http://schemas.microsoft.com/office/word/2012/wordml";
11
+ export const A = "http://schemas.openxmlformats.org/drawingml/2006/main";
12
+
13
+ export const REL = {
14
+ styles: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
15
+ numbering: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
16
+ theme: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
17
+ comments: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
18
+ commentsExtended: "http://schemas.microsoft.com/office/2011/relationships/commentsExtended",
19
+ hyperlink: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
20
+ };
21
+
22
+ /** Whether `node` is the WordprocessingML element `local`. */
23
+ export function isW(node: XmlNode, local?: string): boolean {
24
+ return node.kind === "element" && node.ns === W && (local === undefined || node.local === local);
25
+ }
26
+
27
+ export function elements(element: XmlElement): XmlElement[] {
28
+ return element.children.filter((child): child is XmlElement => child.kind === "element");
29
+ }
30
+
31
+ /** The first WordprocessingML child named `local`. */
32
+ export function child(element: XmlElement, local: string): XmlElement | undefined {
33
+ return element.children.find((c): c is XmlElement => c.kind === "element" && isW(c, local));
34
+ }
35
+
36
+ /** A WordprocessingML attribute (`w:val`) of `element`. */
37
+ export function attr(element: XmlElement | undefined, local: string, ns = W): string | undefined {
38
+ return element?.attributes.find((a) => a.local === local && a.ns === ns)?.value;
39
+ }
40
+
41
+ /** The text of an element's character data children (`w:t`, `w:delText`, `w:instrText`). */
42
+ export function textOf(element: XmlElement): string {
43
+ return element.children.map((c) => (c.kind === "text" ? c.text : "")).join("");
44
+ }
45
+
46
+ /** Every `w:t` and `w:delText` of an element's descendants, in order (the text it shows). */
47
+ export function deepText(element: XmlElement): string {
48
+ let out = "";
49
+ for (const c of element.children) {
50
+ if (c.kind !== "element") continue;
51
+ out += isW(c, "t") || isW(c, "delText") ? textOf(c) : deepText(c);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** An integer as Word writes it; undefined for anything else (universal measures, decimals). */
57
+ export function integer(value: string | undefined): number | undefined {
58
+ return value !== undefined && /^-?\d+$/.test(value) ? Number.parseInt(value, 10) : undefined;
59
+ }
60
+
61
+ /**
62
+ * An on/off property (ST_OnOff): absent value is on. Undefined for a value that is not one of
63
+ * Word's spellings.
64
+ */
65
+ export function toggle(element: XmlElement): boolean | undefined {
66
+ const value = attr(element, "val");
67
+ if (value === undefined || value === "1" || value === "true" || value === "on") return true;
68
+ if (value === "0" || value === "false" || value === "off") return false;
69
+ return undefined;
70
+ }
71
+
72
+ /** `{ key: value }` without the undefined values; undefined when none remain. */
73
+ export function compact<T extends Record<string, unknown>>(object: T): Partial<T> | undefined {
74
+ const out: Record<string, unknown> = {};
75
+ for (const [key, value] of Object.entries(object)) if (value !== undefined) out[key] = value;
76
+ return Object.keys(out).length ? (out as Partial<T>) : undefined;
77
+ }
@@ -0,0 +1,423 @@
1
+ /** The parts beside the document: styles, numbering, theme, comments. */
2
+
3
+ import {
4
+ type AbstractNumberingJSON,
5
+ type CommentJSON,
6
+ type MarkJSON,
7
+ type NumberingInstanceJSON,
8
+ type NumberingLevelJSON,
9
+ RUN_PROPERTY_MARKS,
10
+ type StyleJSON,
11
+ schema,
12
+ type ThemeJSON,
13
+ } from "@folijs/core";
14
+ import type { XmlElement } from "../xml.js";
15
+ import { blocks, type ContentContext } from "./content.js";
16
+ import { A, attr, child, compact, elements, integer, isW, toggle, W14, W15 } from "./ooxml.js";
17
+ import { type Context, onOff, paragraphProperties, runProperties, sourceOf } from "./properties.js";
18
+
19
+ const STYLE_TYPES = ["paragraph", "character", "table", "numbering"];
20
+ /** Word's ids (`w:numId`, `w:abstractNumId`, comment ids): what the model holds. */
21
+ const MAX_ID = 2_147_483_647;
22
+
23
+ /**
24
+ * Run properties as a style, a level or the defaults hold them: a recorded formatting change
25
+ * (`w:rPrChange`) stays in the element's verbatim `ext`.
26
+ */
27
+ function runList(rPr: XmlElement | undefined, context: Context): MarkJSON[] {
28
+ return runProperties(rPr, context)
29
+ .filter((m) => RUN_PROPERTY_MARKS.includes(m.type))
30
+ .map((m) => schema.markFromJSON(m).toJSON()); // canonical: default values left out
31
+ }
32
+
33
+ /** An id within what the model holds; reported otherwise. */
34
+ function id(
35
+ value: string | undefined,
36
+ min: number,
37
+ element: string,
38
+ context: Context,
39
+ ): number | undefined {
40
+ const n = integer(value);
41
+ if (n === undefined || n < min || n > MAX_ID) {
42
+ context.report.unmodeled(element, `id ${value} out of range (kept in the original part)`);
43
+ return undefined;
44
+ }
45
+ return n;
46
+ }
47
+
48
+ /** `w:styles`: the document defaults and the styles (each with its element verbatim). */
49
+ export function styles(
50
+ root: XmlElement,
51
+ context: Context,
52
+ ): { defaults: Record<string, unknown>; styles: StyleJSON[] } {
53
+ const docDefaults = child(root, "docDefaults");
54
+ const defaults = docDefaults ? defaultsOf(docDefaults, context) : {};
55
+ const list: StyleJSON[] = [];
56
+ for (const el of elements(root)) {
57
+ if (!isW(el, "style")) continue;
58
+ const style = styleOf(el, context);
59
+ if (style) list.push(style);
60
+ }
61
+ breakCycles(
62
+ list,
63
+ (s) => s.id,
64
+ (s) => s.basedOn,
65
+ (s) => {
66
+ context.report.unmodeled(`w:style ${s.id}`, `w:basedOn ${s.basedOn} closes a cycle`);
67
+ delete s.basedOn;
68
+ },
69
+ );
70
+ return { defaults, styles: list };
71
+ }
72
+
73
+ /** `w:docDefaults` as the envelope's defaults (with the element verbatim). */
74
+ export function defaultsOf(docDefaults: XmlElement, context: Context): Record<string, unknown> {
75
+ const pPr = child(child(docDefaults, "pPrDefault") ?? docDefaults, "pPr");
76
+ const rPr = child(child(docDefaults, "rPrDefault") ?? docDefaults, "rPr");
77
+ const paragraph = pPr ? paragraphProperties(pPr, context, false) : {};
78
+ const run = runList(rPr, context);
79
+ return {
80
+ ...(Object.keys(paragraph).length ? { paragraph } : {}),
81
+ ...(run.length ? { run } : {}),
82
+ ext: sourceOf(context, docDefaults),
83
+ };
84
+ }
85
+
86
+ /** Whether import keeps a `w:style` (it has a usable id and type); others stay in the part only. */
87
+ export function usableStyle(el: XmlElement): boolean {
88
+ const styleId = attr(el, "styleId");
89
+ return (
90
+ !!styleId && styleId.length <= 255 && STYLE_TYPES.includes(attr(el, "type") ?? "paragraph")
91
+ );
92
+ }
93
+
94
+ /** A `w:style` as a style (with the element verbatim); undefined (reported) when unusable. */
95
+ export function styleOf(el: XmlElement, context: Context): StyleJSON | undefined {
96
+ const styleId = attr(el, "styleId");
97
+ const type = attr(el, "type") ?? "paragraph";
98
+ if (!usableStyle(el)) {
99
+ context.report.unmodeled(
100
+ `w:style ${styleId ?? ""}`,
101
+ "no usable w:styleId or w:type (kept in the original styles part)",
102
+ );
103
+ return undefined;
104
+ }
105
+ const value = (local: string) => {
106
+ const v = attr(child(el, local), "val");
107
+ return v && v.length <= 255 ? v : undefined;
108
+ };
109
+ const stylePPr = child(el, "pPr");
110
+ const props = stylePPr ? paragraphProperties(stylePPr, context, false) : {};
111
+ const marks = runList(child(el, "rPr"), context);
112
+ const name = attr(child(el, "name"), "val");
113
+ return compact({
114
+ id: styleId,
115
+ type: type as StyleJSON["type"],
116
+ name: name !== undefined && name.length <= 255 ? name : undefined,
117
+ basedOn: value("basedOn"),
118
+ next: value("next"),
119
+ link: value("link"),
120
+ isDefault: onOff(el, "default", context),
121
+ paragraph: Object.keys(props).length ? props : undefined,
122
+ run: marks.length ? marks : undefined,
123
+ ext: sourceOf(context, el),
124
+ }) as StyleJSON;
125
+ }
126
+
127
+ /**
128
+ * Following `next` from any item ends: the link that closes a cycle is removed (`cut`), as
129
+ * Word ignores it. Linear: each item is walked once. Ids that repeat resolve to the first.
130
+ */
131
+ function breakCycles<T>(
132
+ items: readonly T[],
133
+ key: (item: T) => unknown,
134
+ next: (item: T) => unknown,
135
+ cut: (item: T) => void,
136
+ ): void {
137
+ const byId = new Map<unknown, number>();
138
+ items.forEach((item, i) => {
139
+ if (!byId.has(key(item))) byId.set(key(item), i);
140
+ });
141
+ const state = new Uint8Array(items.length); // 0 unseen, 1 on the current path, 2 ends
142
+ items.forEach((_, start) => {
143
+ const path: number[] = [];
144
+ let at: number | undefined = start;
145
+ while (at !== undefined && state[at] === 0) {
146
+ state[at] = 1;
147
+ path.push(at);
148
+ const target = next(items[at] as T);
149
+ const following: number | undefined = target === undefined ? undefined : byId.get(target);
150
+ if (following !== undefined && state[following] === 1) {
151
+ cut(items[at] as T);
152
+ break;
153
+ }
154
+ at = following;
155
+ }
156
+ for (const i of path) state[i] = 2;
157
+ });
158
+ }
159
+
160
+ export function level(lvl: XmlElement, context: Context): NumberingLevelJSON | undefined {
161
+ const index = integer(attr(lvl, "ilvl"));
162
+ if (index === undefined || index < 0 || index > 8) {
163
+ context.report.unmodeled("w:lvl", `w:ilvl ${attr(lvl, "ilvl")}`);
164
+ return undefined;
165
+ }
166
+ const value = (local: string) => attr(child(lvl, local), "val");
167
+ const legal = child(lvl, "isLgl");
168
+ const pPr = child(lvl, "pPr");
169
+ const props = pPr ? paragraphProperties(pPr, context, false) : {};
170
+ const run = runList(child(lvl, "rPr"), context);
171
+ const json = compact({
172
+ level: index,
173
+ start: integer(value("start")),
174
+ format: value("numFmt"),
175
+ text: value("lvlText"),
176
+ justification: value("lvlJc"),
177
+ restart: integer(value("lvlRestart")),
178
+ legal: legal ? toggle(legal) : undefined,
179
+ suffix: value("suff"),
180
+ style: value("pStyle"),
181
+ paragraph: Object.keys(props).length ? props : undefined,
182
+ run: run.length ? run : undefined,
183
+ ext: sourceOf(context, lvl),
184
+ }) as Record<string, unknown>;
185
+ return checked(json, LEVEL_CHECKS, "w:lvl", context) as unknown as NumberingLevelJSON;
186
+ }
187
+
188
+ /** Per-field checks of a numbering level, so one bad value does not lose the level. */
189
+ const LEVEL_CHECKS: Record<string, (v: unknown) => boolean> = {
190
+ start: (v) => Number.isInteger(v) && (v as number) >= 0 && (v as number) <= MAX_ID,
191
+ format: (v) => typeof v === "string" && /^[A-Za-z][A-Za-z0-9-]{0,63}$/.test(v),
192
+ text: (v) => typeof v === "string" && v.length <= 255,
193
+ justification: (v) => ["left", "center", "right", "start", "end"].includes(v as string),
194
+ restart: (v) => Number.isInteger(v) && (v as number) >= 0 && (v as number) <= 9,
195
+ legal: (v) => typeof v === "boolean",
196
+ suffix: (v) => ["tab", "space", "nothing"].includes(v as string),
197
+ style: (v) => typeof v === "string" && v.length > 0 && v.length <= 255,
198
+ };
199
+
200
+ function checked(
201
+ json: Record<string, unknown>,
202
+ checks: Record<string, (v: unknown) => boolean>,
203
+ element: string,
204
+ context: Context,
205
+ ): Record<string, unknown> {
206
+ const out: Record<string, unknown> = { ...json };
207
+ for (const [key, ok] of Object.entries(checks)) {
208
+ if (key in out && !ok(out[key])) {
209
+ context.report.unmodeled(element, `${key} ${String(out[key])}`);
210
+ delete out[key];
211
+ }
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** `w:numbering`: abstract definitions and instances (each with its element verbatim). */
217
+ export function numbering(
218
+ root: XmlElement,
219
+ context: Context,
220
+ ): { abstracts: AbstractNumberingJSON[]; instances: NumberingInstanceJSON[] } {
221
+ const abstracts: AbstractNumberingJSON[] = [];
222
+ const instances: NumberingInstanceJSON[] = [];
223
+ for (const el of elements(root)) {
224
+ if (isW(el, "abstractNum")) {
225
+ const abstract = abstractOf(el, context);
226
+ if (abstract) abstracts.push(abstract);
227
+ } else if (isW(el, "num")) {
228
+ const instance = instanceOf(el, context);
229
+ if (instance) instances.push(instance);
230
+ }
231
+ }
232
+ return { abstracts, instances };
233
+ }
234
+
235
+ /** A `w:abstractNum` as a definition (with the element verbatim); undefined (reported) when unusable. */
236
+ export function abstractOf(el: XmlElement, context: Context): AbstractNumberingJSON | undefined {
237
+ const abstractId = id(attr(el, "abstractNumId"), 0, "w:abstractNum", context);
238
+ if (abstractId === undefined) return undefined;
239
+ const seen = new Set<number>();
240
+ const levels: NumberingLevelJSON[] = [];
241
+ for (const lvl of elements(el)) {
242
+ if (!isW(lvl, "lvl")) continue;
243
+ const json = level(lvl, context);
244
+ // A repeated level: Word uses the first.
245
+ if (json && !seen.has(json.level)) {
246
+ seen.add(json.level);
247
+ levels.push(json);
248
+ }
249
+ }
250
+ const multi = attr(child(el, "multiLevelType"), "val");
251
+ const link = (local: string) => {
252
+ const v = attr(child(el, local), "val");
253
+ return v && v.length <= 255 ? v : undefined;
254
+ };
255
+ return compact({
256
+ id: abstractId,
257
+ multiLevelType:
258
+ multi && ["singleLevel", "multilevel", "hybridMultilevel"].includes(multi)
259
+ ? multi
260
+ : undefined,
261
+ levels,
262
+ styleLink: link("styleLink"),
263
+ numStyleLink: link("numStyleLink"),
264
+ ext: sourceOf(context, el),
265
+ }) as AbstractNumberingJSON;
266
+ }
267
+
268
+ /** A `w:num` as an instance (with the element verbatim); undefined (reported) when unusable. */
269
+ export function instanceOf(el: XmlElement, context: Context): NumberingInstanceJSON | undefined {
270
+ const numId = id(attr(el, "numId"), 1, "w:num", context);
271
+ const abstract = id(attr(child(el, "abstractNumId"), "val"), 0, "w:num/w:abstractNumId", context);
272
+ if (numId === undefined || abstract === undefined) return undefined;
273
+ const seen = new Set<number>();
274
+ const overrides: NonNullable<NumberingInstanceJSON["overrides"]> = [];
275
+ for (const o of elements(el)) {
276
+ if (!isW(o, "lvlOverride")) continue;
277
+ const index = integer(attr(o, "ilvl"));
278
+ if (index === undefined || index < 0 || index > 8 || seen.has(index)) {
279
+ context.report.unmodeled("w:lvlOverride", `w:ilvl ${attr(o, "ilvl")}`);
280
+ continue;
281
+ }
282
+ seen.add(index);
283
+ const start = integer(attr(child(o, "startOverride"), "val"));
284
+ const startOk = start !== undefined && start >= 0 && start <= MAX_ID;
285
+ if (start !== undefined && !startOk) context.report.unmodeled("w:startOverride", `${start}`);
286
+ const lvl = child(o, "lvl");
287
+ const definition = lvl ? level(lvl, context) : undefined;
288
+ overrides.push(
289
+ compact({
290
+ level: index,
291
+ start: startOk ? start : undefined,
292
+ definition: definition ? { ...definition, level: index } : undefined,
293
+ }) as { level: number },
294
+ );
295
+ }
296
+ return compact({
297
+ id: numId,
298
+ abstract,
299
+ overrides: overrides.length ? overrides : undefined,
300
+ ext: sourceOf(context, el),
301
+ }) as NumberingInstanceJSON;
302
+ }
303
+
304
+ /** As core checks it (ISO 8601 date-time). */
305
+ const DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?$/;
306
+
307
+ const THEME_COLORS = [
308
+ "dk1",
309
+ "lt1",
310
+ "dk2",
311
+ "lt2",
312
+ "accent1",
313
+ "accent2",
314
+ "accent3",
315
+ "accent4",
316
+ "accent5",
317
+ "accent6",
318
+ "hlink",
319
+ "folHlink",
320
+ ];
321
+
322
+ /** `a:theme`'s fonts and colors; undefined (reported) when its fonts are missing or unusable. */
323
+ export function theme(root: XmlElement, context: Context): ThemeJSON | undefined {
324
+ const a = (el: XmlElement | undefined, local: string) =>
325
+ el?.children.find(
326
+ (c): c is XmlElement => c.kind === "element" && c.ns === A && c.local === local,
327
+ );
328
+ const elementsOf = a(root, "themeElements");
329
+ const fontScheme = a(elementsOf, "fontScheme");
330
+ const font = (local: string) => {
331
+ const f = a(fontScheme, local);
332
+ const face = (name: string) =>
333
+ a(f, name)?.attributes.find((x) => x.local === "typeface")?.value;
334
+ const latin = face("latin");
335
+ return latin === undefined
336
+ ? undefined
337
+ : compact({ latin, eastAsia: face("ea"), cs: face("cs") });
338
+ };
339
+ const major = font("majorFont");
340
+ const minor = font("minorFont");
341
+ const colors: Record<string, string> = {};
342
+ const scheme = a(elementsOf, "clrScheme");
343
+ for (const name of THEME_COLORS) {
344
+ const slot = a(scheme, name);
345
+ const color = slot?.children.find((c): c is XmlElement => c.kind === "element");
346
+ const value = color?.attributes.find(
347
+ (x) => x.local === (color.local === "sysClr" ? "lastClr" : "val"),
348
+ )?.value;
349
+ if (value && /^[0-9A-Fa-f]{6}$/.test(value)) colors[name] = value;
350
+ }
351
+ const usable = (f: Record<string, unknown> | undefined) =>
352
+ f !== undefined && Object.values(f).every((v) => typeof v === "string" && v.length <= 255);
353
+ if (!usable(major) || !usable(minor)) {
354
+ context.report.unmodeled("a:fontScheme", "no usable major and minor fonts (theme left out)");
355
+ return undefined;
356
+ }
357
+ return { fonts: { major, minor } as ThemeJSON["fonts"], colors };
358
+ }
359
+
360
+ /**
361
+ * `w:comments`, with replies and resolved state from `commentsExtended` (keyed by the
362
+ * `w14:paraId` of each comment's last paragraph). Each comment keeps its start tag verbatim
363
+ * (`ext`): values the model cannot hold (a long author, a date without a time) stay there.
364
+ */
365
+ export function comments(
366
+ root: XmlElement,
367
+ extended: XmlElement | undefined,
368
+ context: ContentContext,
369
+ ): CommentJSON[] {
370
+ const byParaId = new Map<string, CommentJSON>();
371
+ const list: CommentJSON[] = [];
372
+ for (const el of elements(root)) {
373
+ if (!isW(el, "comment")) continue;
374
+ const commentId = id(attr(el, "id"), 0, "w:comment", context);
375
+ if (commentId === undefined) continue;
376
+ const date = attr(el, "date");
377
+ const author = attr(el, "author") ?? "";
378
+ const initials = attr(el, "initials");
379
+ if (date !== undefined && !DATE.test(date)) context.report.unmodeled("w:comment@w:date", date);
380
+ if (author.length > 255) context.report.unmodeled("w:comment@w:author", "longer than 255");
381
+ if (initials !== undefined && initials.length > 9) {
382
+ context.report.unmodeled("w:comment@w:initials", "longer than 9");
383
+ }
384
+ const content = blocks(el.children, context);
385
+ const comment = compact({
386
+ id: commentId,
387
+ author: author.length <= 255 ? author : author.slice(0, 255),
388
+ initials: initials !== undefined && initials.length <= 9 ? initials : undefined,
389
+ date: date && DATE.test(date) ? date : undefined,
390
+ content: content.length ? content : [{ type: "paragraph" }],
391
+ ext: context.source.slice(el.start, el.openEnd),
392
+ }) as CommentJSON;
393
+ list.push(comment);
394
+ const paraId = elements(el)
395
+ .filter((p) => isW(p, "p"))
396
+ .at(-1)
397
+ ?.attributes.find((x) => x.ns === W14 && x.local === "paraId")?.value;
398
+ if (paraId && !byParaId.has(paraId)) byParaId.set(paraId, comment);
399
+ }
400
+ if (extended) {
401
+ for (const ex of elements(extended)) {
402
+ if (ex.ns !== W15 || ex.local !== "commentEx") continue;
403
+ const get = (local: string) =>
404
+ ex.attributes.find((x) => x.ns === W15 && x.local === local)?.value;
405
+ const comment = byParaId.get(get("paraId") ?? "");
406
+ if (!comment) continue;
407
+ const parent = byParaId.get(get("paraIdParent") ?? "");
408
+ if (parent && parent !== comment) comment.parent = parent.id;
409
+ const done = onOff(ex, "done", context, W15);
410
+ if (done !== undefined) comment.done = done;
411
+ }
412
+ breakCycles(
413
+ list,
414
+ (c) => c.id,
415
+ (c) => c.parent,
416
+ (c) => {
417
+ context.report.unmodeled(`w:comment ${c.id}`, "a reply closing a cycle of replies");
418
+ delete c.parent;
419
+ },
420
+ );
421
+ }
422
+ return list;
423
+ }