@folijs/core 0.4.0 → 0.6.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 (153) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +10 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +125 -40
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.d.ts.map +1 -1
  11. package/dist/state/comments.js +15 -6
  12. package/dist/state/comments.js.map +1 -1
  13. package/dist/state/controls.d.ts +128 -0
  14. package/dist/state/controls.d.ts.map +1 -0
  15. package/dist/state/controls.js +1459 -0
  16. package/dist/state/controls.js.map +1 -0
  17. package/dist/state/editor.d.ts +86 -1
  18. package/dist/state/editor.d.ts.map +1 -1
  19. package/dist/state/editor.js +169 -41
  20. package/dist/state/editor.js.map +1 -1
  21. package/dist/state/fields.d.ts +79 -0
  22. package/dist/state/fields.d.ts.map +1 -0
  23. package/dist/state/fields.js +398 -0
  24. package/dist/state/fields.js.map +1 -0
  25. package/dist/state/fieldupdate.d.ts +178 -0
  26. package/dist/state/fieldupdate.d.ts.map +1 -0
  27. package/dist/state/fieldupdate.js +1574 -0
  28. package/dist/state/fieldupdate.js.map +1 -0
  29. package/dist/state/find.d.ts +68 -0
  30. package/dist/state/find.d.ts.map +1 -0
  31. package/dist/state/find.js +397 -0
  32. package/dist/state/find.js.map +1 -0
  33. package/dist/state/history.d.ts +12 -1
  34. package/dist/state/history.d.ts.map +1 -1
  35. package/dist/state/history.js +43 -7
  36. package/dist/state/history.js.map +1 -1
  37. package/dist/state/index.d.ts +15 -5
  38. package/dist/state/index.d.ts.map +1 -1
  39. package/dist/state/index.js +13 -3
  40. package/dist/state/index.js.map +1 -1
  41. package/dist/state/links.d.ts.map +1 -1
  42. package/dist/state/links.js +30 -19
  43. package/dist/state/links.js.map +1 -1
  44. package/dist/state/mark.d.ts.map +1 -1
  45. package/dist/state/mark.js +8 -1
  46. package/dist/state/mark.js.map +1 -1
  47. package/dist/state/navigation.d.ts +70 -0
  48. package/dist/state/navigation.d.ts.map +1 -0
  49. package/dist/state/navigation.js +226 -0
  50. package/dist/state/navigation.js.map +1 -0
  51. package/dist/state/notes.d.ts +94 -0
  52. package/dist/state/notes.d.ts.map +1 -0
  53. package/dist/state/notes.js +444 -0
  54. package/dist/state/notes.js.map +1 -0
  55. package/dist/state/pictures.d.ts +51 -0
  56. package/dist/state/pictures.d.ts.map +1 -0
  57. package/dist/state/pictures.js +140 -0
  58. package/dist/state/pictures.js.map +1 -0
  59. package/dist/state/review.d.ts +13 -4
  60. package/dist/state/review.d.ts.map +1 -1
  61. package/dist/state/review.js +223 -29
  62. package/dist/state/review.js.map +1 -1
  63. package/dist/state/sections.d.ts +101 -0
  64. package/dist/state/sections.d.ts.map +1 -0
  65. package/dist/state/sections.js +472 -0
  66. package/dist/state/sections.js.map +1 -0
  67. package/dist/state/selection.d.ts +12 -1
  68. package/dist/state/selection.d.ts.map +1 -1
  69. package/dist/state/selection.js +12 -0
  70. package/dist/state/selection.js.map +1 -1
  71. package/dist/state/state.d.ts +2 -0
  72. package/dist/state/state.d.ts.map +1 -1
  73. package/dist/state/state.js +4 -0
  74. package/dist/state/state.js.map +1 -1
  75. package/dist/state/stories.d.ts +41 -0
  76. package/dist/state/stories.d.ts.map +1 -0
  77. package/dist/state/stories.js +243 -0
  78. package/dist/state/stories.js.map +1 -0
  79. package/dist/state/tablecommands.d.ts +77 -0
  80. package/dist/state/tablecommands.d.ts.map +1 -0
  81. package/dist/state/tablecommands.js +675 -0
  82. package/dist/state/tablecommands.js.map +1 -0
  83. package/dist/state/tables.d.ts +110 -0
  84. package/dist/state/tables.d.ts.map +1 -0
  85. package/dist/state/tables.js +730 -0
  86. package/dist/state/tables.js.map +1 -0
  87. package/dist/state/track.d.ts +23 -0
  88. package/dist/state/track.d.ts.map +1 -1
  89. package/dist/state/track.js +113 -15
  90. package/dist/state/track.js.map +1 -1
  91. package/dist/state/word.d.ts +78 -16
  92. package/dist/state/word.d.ts.map +1 -1
  93. package/dist/state/word.js +231 -11
  94. package/dist/state/word.js.map +1 -1
  95. package/dist/state/wordclip.d.ts +15 -6
  96. package/dist/state/wordclip.d.ts.map +1 -1
  97. package/dist/state/wordclip.js +213 -18
  98. package/dist/state/wordclip.js.map +1 -1
  99. package/dist/state/wordformat.d.ts +10 -2
  100. package/dist/state/wordformat.d.ts.map +1 -1
  101. package/dist/state/wordformat.js +98 -17
  102. package/dist/state/wordformat.js.map +1 -1
  103. package/dist/v3/document.d.ts +237 -7
  104. package/dist/v3/document.d.ts.map +1 -1
  105. package/dist/v3/document.js +314 -15
  106. package/dist/v3/document.js.map +1 -1
  107. package/dist/v3/index.d.ts +2 -2
  108. package/dist/v3/index.d.ts.map +1 -1
  109. package/dist/v3/index.js +2 -2
  110. package/dist/v3/index.js.map +1 -1
  111. package/dist/v3/migrate.d.ts +2 -2
  112. package/dist/v3/migrate.d.ts.map +1 -1
  113. package/dist/v3/resolve.d.ts +57 -5
  114. package/dist/v3/resolve.d.ts.map +1 -1
  115. package/dist/v3/resolve.js +224 -16
  116. package/dist/v3/resolve.js.map +1 -1
  117. package/dist/v3/schema.d.ts +6 -0
  118. package/dist/v3/schema.d.ts.map +1 -1
  119. package/dist/v3/schema.js +254 -8
  120. package/dist/v3/schema.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/model/schema.ts +18 -2
  123. package/src/state/commands.ts +121 -32
  124. package/src/state/comments.ts +14 -6
  125. package/src/state/controls.ts +1596 -0
  126. package/src/state/editor.ts +292 -46
  127. package/src/state/fields.ts +432 -0
  128. package/src/state/fieldupdate.ts +1770 -0
  129. package/src/state/find.ts +510 -0
  130. package/src/state/history.ts +51 -7
  131. package/src/state/index.ts +157 -0
  132. package/src/state/links.ts +27 -17
  133. package/src/state/mark.ts +8 -1
  134. package/src/state/navigation.ts +305 -0
  135. package/src/state/notes.ts +519 -0
  136. package/src/state/numeric-pictures.word.json +172 -0
  137. package/src/state/pictures.ts +168 -0
  138. package/src/state/review.ts +265 -31
  139. package/src/state/sections.ts +571 -0
  140. package/src/state/selection.ts +15 -1
  141. package/src/state/state.ts +5 -0
  142. package/src/state/stories.ts +285 -0
  143. package/src/state/tablecommands.ts +741 -0
  144. package/src/state/tables.ts +761 -0
  145. package/src/state/track.ts +128 -16
  146. package/src/state/word.ts +276 -13
  147. package/src/state/wordclip.ts +231 -32
  148. package/src/state/wordformat.ts +96 -14
  149. package/src/v3/document.ts +572 -16
  150. package/src/v3/index.ts +21 -0
  151. package/src/v3/migrate.ts +2 -2
  152. package/src/v3/resolve.ts +289 -21
  153. package/src/v3/schema.ts +278 -9
@@ -17,14 +17,21 @@ import {
17
17
  } from "./check.js";
18
18
  import { migrateToV3 } from "./migrate.js";
19
19
  import {
20
+ checkCellProperties,
21
+ checkNoteProperties,
22
+ checkRowProperties,
20
23
  checkSection,
24
+ checkTableProperties,
21
25
  checkParagraphProperties as paragraphProperties,
22
26
  checkRunProperties as runProperties,
23
27
  schema,
24
28
  } from "./schema.js";
25
29
 
26
- /** The schema version of documents in the Word model (ADR-0005). */
27
- export const SCHEMA_VERSION = 3;
30
+ /**
31
+ * The schema version of documents in the Word model (ADR-0005; v4 adds tables and pictures,
32
+ * ADR-0006; v5 stories, fields, content controls and notes, ADR-0007).
33
+ */
34
+ export const SCHEMA_VERSION = 5;
28
35
 
29
36
  /** Page setup of a section, in twips (1/1440 inch). Missing parts take Word's defaults. */
30
37
  export interface SectionJSON {
@@ -43,10 +50,32 @@ export interface SectionJSON {
43
50
  /** Relationship ids of the header and footer parts (their content stays in the package until Phase 11). */
44
51
  headers?: { default?: string; first?: string; even?: string };
45
52
  footers?: { default?: string; first?: string; even?: string };
53
+ /** `w:cols` (v5). `widths` when the columns are not of equal width. */
54
+ columns?: {
55
+ count?: number;
56
+ space?: number;
57
+ equalWidth?: boolean;
58
+ separator?: boolean;
59
+ widths?: { width: number; space?: number }[];
60
+ };
61
+ /** `w:pgNumType` (v5). */
62
+ pageNumbers?: { start?: number; format?: string };
63
+ footnotes?: NotePropertiesJSON;
64
+ endnotes?: NotePropertiesJSON;
65
+ /** `w:sectPrChange`: who changed the page setup while tracking, and what it was. */
66
+ change?: { id: number; author: string; date?: string | null; previous: SectionJSON };
46
67
  /** The `w:sectPr` this was read from, verbatim. */
47
68
  ext?: string;
48
69
  }
49
70
 
71
+ /** How notes are placed and numbered (`w:footnotePr`, `w:endnotePr`). */
72
+ export interface NotePropertiesJSON {
73
+ position?: "pageBottom" | "beneathText" | "sectEnd" | "docEnd";
74
+ format?: string;
75
+ start?: number;
76
+ restart?: "continuous" | "eachSect" | "eachPage";
77
+ }
78
+
50
79
  export interface BorderJSON {
51
80
  style: string;
52
81
  size?: number;
@@ -83,6 +112,96 @@ export interface ParagraphPropertiesJSON {
83
112
  ext?: string;
84
113
  }
85
114
 
115
+ /** A table measure: twips (`dxa`), fiftieths of a percent (`pct`), or `auto`/`nil` with 0. */
116
+ export interface MeasureJSON {
117
+ value: number;
118
+ type: "auto" | "dxa" | "pct" | "nil";
119
+ }
120
+
121
+ type Sides<T, Extra extends string = never> = Partial<
122
+ Record<"top" | "left" | "bottom" | "right" | "start" | "end" | Extra, T>
123
+ >;
124
+
125
+ /** Table properties (`w:tblPr`): a table's attributes, a table style's, a row's exceptions. */
126
+ export interface TablePropertiesJSON {
127
+ style?: string;
128
+ width?: MeasureJSON;
129
+ justification?: "left" | "center" | "right" | "start" | "end";
130
+ indent?: MeasureJSON;
131
+ layout?: "fixed" | "autofit";
132
+ borders?: Sides<BorderJSON, "insideH" | "insideV">;
133
+ cellMargins?: Sides<MeasureJSON>;
134
+ cellSpacing?: MeasureJSON;
135
+ shading?: ParagraphPropertiesJSON["shading"];
136
+ look?: {
137
+ firstRow?: boolean;
138
+ lastRow?: boolean;
139
+ firstColumn?: boolean;
140
+ lastColumn?: boolean;
141
+ noHBand?: boolean;
142
+ noVBand?: boolean;
143
+ };
144
+ rowBandSize?: number;
145
+ columnBandSize?: number;
146
+ ext?: string;
147
+ }
148
+
149
+ /** Row properties (`w:trPr`). */
150
+ export interface RowPropertiesJSON {
151
+ height?: { value: number; rule?: "auto" | "exact" | "atLeast" };
152
+ cantSplit?: boolean;
153
+ header?: boolean;
154
+ gridBefore?: number;
155
+ widthBefore?: MeasureJSON;
156
+ gridAfter?: number;
157
+ widthAfter?: MeasureJSON;
158
+ ext?: string;
159
+ }
160
+
161
+ /** Cell properties (`w:tcPr`). */
162
+ export interface CellPropertiesJSON {
163
+ width?: MeasureJSON;
164
+ gridSpan?: number;
165
+ vMerge?: "restart" | "continue";
166
+ borders?: Sides<BorderJSON, "insideH" | "insideV" | "tl2br" | "tr2bl">;
167
+ shading?: ParagraphPropertiesJSON["shading"];
168
+ margins?: Sides<MeasureJSON>;
169
+ verticalAlign?: "top" | "center" | "bottom" | "both";
170
+ textDirection?: string;
171
+ noWrap?: boolean;
172
+ ext?: string;
173
+ }
174
+
175
+ /** The parts of a table style a conditional format (`w:tblStylePr`) can apply to. */
176
+ export const TABLE_CONDITIONS = [
177
+ "wholeTable",
178
+ "band1Vert",
179
+ "band2Vert",
180
+ "band1Horz",
181
+ "band2Horz",
182
+ "firstCol",
183
+ "lastCol",
184
+ "firstRow",
185
+ "lastRow",
186
+ "nwCell",
187
+ "neCell",
188
+ "swCell",
189
+ "seCell",
190
+ ] as const;
191
+ export type TableCondition = (typeof TABLE_CONDITIONS)[number];
192
+
193
+ /** A table style's conditional format (`w:tblStylePr`): what its part of the table looks like. */
194
+ export interface TableConditionJSON {
195
+ type: Exclude<TableCondition, "wholeTable">;
196
+ paragraph?: ParagraphPropertiesJSON;
197
+ run?: MarkJSON[];
198
+ table?: TablePropertiesJSON;
199
+ row?: RowPropertiesJSON;
200
+ cell?: CellPropertiesJSON;
201
+ /** The `w:tblStylePr` this was read from, verbatim. */
202
+ ext?: string;
203
+ }
204
+
86
205
  export interface StyleJSON {
87
206
  /** `w:styleId`, what paragraphs and runs reference. With duplicates, the first wins, as in Word. */
88
207
  id: string;
@@ -91,14 +210,36 @@ export interface StyleJSON {
91
210
  basedOn?: string;
92
211
  next?: string;
93
212
  link?: string;
94
- /** The default style of its type (Normal, Default Paragraph Font…). */
213
+ /** The default style of its type (Normal, Default Paragraph Font, Normal Table…). */
95
214
  isDefault?: boolean;
96
215
  paragraph?: ParagraphPropertiesJSON;
97
216
  run?: MarkJSON[];
98
- /** The `w:style` this was read from, verbatim (table properties, UI priority…). */
217
+ /** A table style's whole-table properties. */
218
+ table?: TablePropertiesJSON;
219
+ row?: RowPropertiesJSON;
220
+ cell?: CellPropertiesJSON;
221
+ /** A table style's conditional formats (first row, bands…). */
222
+ conditions?: TableConditionJSON[];
223
+ /** The `w:style` this was read from, verbatim (UI priority…). */
99
224
  ext?: string;
100
225
  }
101
226
 
227
+ /**
228
+ * Where a picture's bytes are (schema v4): a part of the original package, a URL the app gave
229
+ * (its upload hook's), or, when the app opts into it, a `data:` URL. At least one.
230
+ */
231
+ export interface ResourceJSON {
232
+ /** `image/png`, `image/jpeg`, `image/svg+xml`… */
233
+ contentType: string;
234
+ /** Bytes, when known. */
235
+ size?: number;
236
+ /** The package part (`word/media/image1.png`). */
237
+ part?: string;
238
+ url?: string;
239
+ /** A `data:` URL holding the bytes. */
240
+ data?: string;
241
+ }
242
+
102
243
  export interface NumberingLevelJSON {
103
244
  level: number;
104
245
  start?: number;
@@ -163,6 +304,74 @@ export interface CommentJSON {
163
304
  ext?: string;
164
305
  }
165
306
 
307
+ /**
308
+ * Content outside the body (schema v5, ADR-0007). `noteType` is a note's `w:type`: the separators
309
+ * and the continuation notice have no reference and are not numbered.
310
+ */
311
+ export interface StoryJSON {
312
+ kind: "header" | "footer" | "footnote" | "endnote";
313
+ noteType?: "normal" | "separator" | "continuationSeparator" | "continuationNotice";
314
+ /** A `doc` of blocks. */
315
+ content: NodeJSON;
316
+ /** What the part keeps of the story's own element, verbatim. */
317
+ ext?: string;
318
+ }
319
+
320
+ /** A content control's properties (`w:sdtPr`, schema v5), by the id its nodes refer to. */
321
+ export interface ControlJSON {
322
+ kind:
323
+ | "text"
324
+ | "richText"
325
+ | "dropDown"
326
+ | "comboBox"
327
+ | "date"
328
+ | "checkbox"
329
+ | "picture"
330
+ | "repeating"
331
+ | "repeatingItem"
332
+ | "other";
333
+ tag?: string;
334
+ alias?: string;
335
+ lock?: "sdtLocked" | "contentLocked" | "sdtContentLocked" | "unlocked";
336
+ items?: { value: string; display?: string }[];
337
+ dateFormat?: string;
338
+ /** `w:date/@w:fullDate`: the date picked, as Word writes it (`2026-03-03T00:00:00Z`). */
339
+ date?: string;
340
+ checked?: boolean;
341
+ /** A check box's glyphs (`w14:checkedState`, `w14:uncheckedState`): hex code and font. */
342
+ checkedState?: { value: string; font?: string };
343
+ uncheckedState?: { value: string; font?: string };
344
+ /** `w:text/@w:multiLine`: a plain text control that takes line breaks. */
345
+ multiLine?: boolean;
346
+ /** `w:sdtPr/w:rPr` as marks: how text put in place of the placeholder looks. */
347
+ format?: MarkJSON[];
348
+ /** `w15:doNotAllowInsertDeleteSection`: a repeating section's items are fixed. */
349
+ noInsertDelete?: boolean;
350
+ /** Deleted whole while tracking (in the editor: not written): accepting removes the control. */
351
+ deleted?: boolean;
352
+ /**
353
+ * `showing`: the content is the placeholder. `docPart`: the glossary entry it comes from.
354
+ * `text`: that entry's text, what emptying the control brings back.
355
+ */
356
+ placeholder?: { showing?: boolean; docPart?: string; text?: string };
357
+ /** `w:dataBinding`: kept, not evaluated. */
358
+ binding?: { xpath?: string; storeItemId?: string; prefixMappings?: string };
359
+ /** `w:sdtPr` and `w:sdtEndPr`, verbatim. */
360
+ ext?: string;
361
+ }
362
+
363
+ /** What `word/settings.xml` says about pages and notes (schema v5). */
364
+ export interface WordSettingsJSON {
365
+ /**
366
+ * `w:compat/w:doNotUseHTMLParagraphAutoSpacing`: the space after a paragraph and the space
367
+ * before the next add up (without it Word takes the larger, in every compatibility mode).
368
+ */
369
+ doNotUseHTMLParagraphAutoSpacing?: boolean;
370
+ evenAndOddHeaders?: boolean;
371
+ footnotes?: NotePropertiesJSON;
372
+ endnotes?: NotePropertiesJSON;
373
+ }
374
+
166
375
  /** A document in the Word model: the content tree and what Word keeps beside it. */
167
376
  export interface FoliDocument {
168
377
  schemaVersion: typeof SCHEMA_VERSION;
@@ -179,11 +388,39 @@ export interface FoliDocument {
179
388
  numbering: { abstracts: AbstractNumberingJSON[]; instances: NumberingInstanceJSON[] };
180
389
  theme?: ThemeJSON;
181
390
  comments: CommentJSON[];
391
+ /** The pictures' bytes, by the key `picture` nodes give (none when missing). */
392
+ resources?: Record<string, ResourceJSON>;
393
+ /** Headers, footers and notes, by id (a header's or footer's is its relationship id). */
394
+ stories?: Record<string, StoryJSON>;
395
+ /** Content controls' properties, by the id their nodes refer to. */
396
+ controls?: Record<string, ControlJSON>;
397
+ settings?: WordSettingsJSON;
182
398
  content: NodeJSON;
183
399
  }
184
400
 
401
+ /** A document of schema v4 (no stories, fields or content controls in the model). */
402
+ export type FoliDocumentV4 = Omit<
403
+ FoliDocument,
404
+ "schemaVersion" | "stories" | "controls" | "settings"
405
+ > & { schemaVersion: 4 };
406
+
407
+ /** A document of schema v3 (no tables or pictures in the model), as `migrateToV3` gives it. */
408
+ export type FoliDocumentV3 = Omit<FoliDocumentV4, "schemaVersion" | "resources"> & {
409
+ schemaVersion: 3;
410
+ };
411
+
412
+ /** Schema v3 → v4: the version only (a table kept opaque stays so until imported again). */
413
+ export function migrateToV4(doc: FoliDocumentV3): FoliDocumentV4 {
414
+ return { ...doc, schemaVersion: 4 };
415
+ }
416
+
417
+ /** Schema v4 → v5: the version only (what is opaque stays so until imported again). */
418
+ export function migrateToV5(doc: FoliDocumentV4): FoliDocument {
419
+ return { ...doc, schemaVersion: SCHEMA_VERSION };
420
+ }
421
+
185
422
  /**
186
- * A new document: `content` (schema v3; default: one empty paragraph) on A4 with 25.4 mm
423
+ * A new document: `content` (schema v5; default: one empty paragraph) on A4 with 25.4 mm
187
424
  * margins, with the styles and list definitions the editor's commands use (Normal, Heading 1–6,
188
425
  * List Paragraph, Hyperlink; bullets and numbers) and 11 pt Georgia, 1.5 lines: the look a
189
426
  * migrated 0.2.0 document has. `section` (in twips: `mmToTwips`) is merged over that page:
@@ -195,11 +432,11 @@ export function createDocument(
195
432
  section?: SectionJSON,
196
433
  ): FoliDocument {
197
434
  const empty = { type: "doc", content: [] } as const satisfies NodeJSON;
198
- const blank = migrateToV3({
199
- schemaVersion: 2,
200
- settings: DEFAULT_SETTINGS,
201
- content: empty as never,
202
- });
435
+ const blank = migrateToV5(
436
+ migrateToV4(
437
+ migrateToV3({ schemaVersion: 2, settings: DEFAULT_SETTINGS, content: empty as never }),
438
+ ),
439
+ );
203
440
  const base = blank.section;
204
441
  return {
205
442
  ...blank,
@@ -227,7 +464,38 @@ export function createDocument(
227
464
  export function parseDocument(input: unknown): FoliDocument {
228
465
  if (!isRecord(input)) throw new FoliDocumentError("Document must be an object");
229
466
  const version = input.schemaVersion;
230
- if (version === 1 || version === 2) return parseDocument(migrateToV3(parseDocumentV2(input)));
467
+ if (version === 1 || version === 2) {
468
+ return parseDocument(migrateToV5(migrateToV4(migrateToV3(parseDocumentV2(input)))));
469
+ }
470
+ if (version === 3 || version === 4) {
471
+ if (version === 3 && Object.hasOwn(input, "resources"))
472
+ fail("resources", "unknown key (schema 4 and later)");
473
+ for (const key of V5_KEYS)
474
+ if (Object.hasOwn(input, key)) fail(key, "unknown key (schema 5 and later)");
475
+ const doc = parseDocument({ ...input, schemaVersion: SCHEMA_VERSION });
476
+ // What a later schema added is not in a document that says it is of an earlier one.
477
+ const later = laterSection(doc.section);
478
+ if (later) fail("section", `${later} is of schema 5 (the document says schema ${version})`);
479
+ for (const [path, content] of [
480
+ ["content", doc.content],
481
+ ...doc.comments.map((c, i) => [`comments[${i}].content`, { content: c.content }] as const),
482
+ ] as const) {
483
+ const found = laterNode(content, version);
484
+ if (found)
485
+ fail(
486
+ path,
487
+ `${found.name} is a schema ${found.schema} node (the document says schema ${version})`,
488
+ );
489
+ }
490
+ if (version === 3)
491
+ doc.styles.forEach((style, i) => {
492
+ for (const key of ["table", "row", "cell", "conditions"]) {
493
+ if (Object.hasOwn(style, key))
494
+ fail(`styles[${i}]`, `unknown key ${key} (schema 4 and later)`);
495
+ }
496
+ });
497
+ return doc;
498
+ }
231
499
  if (version !== SCHEMA_VERSION) {
232
500
  const newer = Number.isInteger(version) && (version as number) > SCHEMA_VERSION;
233
501
  throw new FoliDocumentError(
@@ -255,6 +523,10 @@ export function parseDocument(input: unknown): FoliDocument {
255
523
  );
256
524
  if (input.theme !== undefined) check("theme", input.theme, checkTheme);
257
525
  check("comments", input.comments, listOf(checkComment));
526
+ if (input.resources !== undefined) check("resources", input.resources, checkResources);
527
+ if (input.stories !== undefined) check("stories", input.stories, checkStories);
528
+ if (input.controls !== undefined) check("controls", input.controls, checkControls);
529
+ if (input.settings !== undefined) check("settings", input.settings, checkSettings);
258
530
  const styles = input.styles as StyleJSON[];
259
531
  const comments = input.comments as CommentJSON[];
260
532
  noCycles(
@@ -273,6 +545,14 @@ export function parseDocument(input: unknown): FoliDocument {
273
545
  );
274
546
 
275
547
  const content = parseContent(input.content);
548
+ const stories = Object.entries((input.stories ?? {}) as Record<string, StoryJSON>).map(
549
+ ([id, story]) => {
550
+ const path = `stories[${JSON.stringify(id)}].content`;
551
+ const tree = parseContent(story.content, path);
552
+ storyRules(tree, story.kind, path);
553
+ return [id, { ...structuredClone({ ...story, content: null }), content: copied(tree) }];
554
+ },
555
+ );
276
556
  // A copy: the validated document must not change when the caller's input does.
277
557
  const envelope = structuredClone({
278
558
  section: input.section,
@@ -280,7 +560,20 @@ export function parseDocument(input: unknown): FoliDocument {
280
560
  styles,
281
561
  numbering: input.numbering,
282
562
  theme: input.theme,
283
- }) as Pick<FoliDocument, "section" | "defaults" | "styles" | "numbering" | "theme">;
563
+ resources: input.resources,
564
+ controls: input.controls,
565
+ settings: input.settings,
566
+ }) as Pick<
567
+ FoliDocument,
568
+ | "section"
569
+ | "defaults"
570
+ | "styles"
571
+ | "numbering"
572
+ | "theme"
573
+ | "resources"
574
+ | "controls"
575
+ | "settings"
576
+ >;
284
577
  return {
285
578
  schemaVersion: SCHEMA_VERSION,
286
579
  section: envelope.section,
@@ -290,20 +583,133 @@ export function parseDocument(input: unknown): FoliDocument {
290
583
  ...(envelope.theme === undefined ? {} : { theme: envelope.theme }),
291
584
  comments: comments.map((c, i) => ({
292
585
  ...structuredClone({ ...c, content: [] }),
293
- content: blocks(c.content, `comments[${i}].content`).map((block) => block.toJSON()),
586
+ content: blocks(c.content, `comments[${i}].content`).map((block) => {
587
+ block.descendants((node) => {
588
+ if (node.type.name === "noteReference")
589
+ fail(`comments[${i}].content`, "a comment cannot hold a note reference");
590
+ return true;
591
+ });
592
+ return copied(block);
593
+ }),
294
594
  })),
295
- content: content.toJSON(),
595
+ ...(envelope.resources === undefined ? {} : { resources: envelope.resources }),
596
+ ...(input.stories === undefined ? {} : { stories: Object.fromEntries(stories) }),
597
+ ...(envelope.controls === undefined ? {} : { controls: envelope.controls }),
598
+ ...(envelope.settings === undefined ? {} : { settings: envelope.settings }),
599
+ content: copied(content),
296
600
  };
297
601
  }
298
602
 
299
- /** Parses untrusted schema v3 content into a `doc` node. */
300
- export function parseContent(value: unknown, path = "content"): Node {
603
+ /** A node's JSON sharing nothing with the input its attributes came from. */
604
+ const copied = (node: Node): NodeJSON => structuredClone(node.toJSON());
605
+
606
+ /**
607
+ * Parses untrusted schema v4 content into a `doc` node, with Word's rules the content
608
+ * expressions do not say (`fragment`: content to paste, which a table may end): a table is never
609
+ * followed by a table (Word would merge them; tables in different content controls stay apart)
610
+ * nor ends the document, and a paragraph in a cell ends no section and holds no page or column
611
+ * break.
612
+ */
613
+ export function parseContent(value: unknown, path = "content", fragment = false): Node {
301
614
  const doc = schema.nodeFromJSON(value, path);
302
615
  if (doc.type !== schema.topNodeType) fail(path, 'root node must be of type "doc"');
303
616
  if (doc.marks.length) fail(`${path}.marks`, "doc cannot have marks");
617
+ wordRules(doc, path, false, fragment);
304
618
  return doc;
305
619
  }
306
620
 
621
+ function wordRules(parent: Node, path: string, inCell: boolean, fragment = false): void {
622
+ parent.forEach((node, _offset, index) => {
623
+ const at = `${path}.content[${index}]`;
624
+ if (node.type.name === "table") {
625
+ const next = parent.maybeChild(index + 1);
626
+ if (
627
+ next?.type.name === "table" &&
628
+ JSON.stringify(next.attrs.controls) === JSON.stringify(node.attrs.controls)
629
+ ) {
630
+ fail(at, "a table cannot follow a table (Word would merge them): a paragraph goes between");
631
+ }
632
+ if (!next && parent.type.name === "doc" && !fragment) {
633
+ fail(at, "a table cannot end the document: a paragraph follows it, as in Word");
634
+ }
635
+ node.forEach((row, _r, r) => {
636
+ row.forEach((cell, _c, c) => {
637
+ wordRules(cell, `${at}.content[${r}].content[${c}]`, true);
638
+ });
639
+ });
640
+ } else if (inCell && node.type.name === "paragraph") {
641
+ if (node.attrs.section)
642
+ fail(`${at}.attrs.section`, "a paragraph in a table cannot end a section");
643
+ node.forEach((inline, _i, i) => {
644
+ if (inline.type.name === "pageBreak" || inline.type.name === "columnBreak") {
645
+ fail(`${at}.content[${i}]`, `a ${inline.type.name} cannot be in a table`);
646
+ }
647
+ });
648
+ }
649
+ });
650
+ }
651
+
652
+ /** What a story may not hold (ADR-0007): import keeps such content opaque instead. */
653
+ export function storyRules(tree: Node, kind: StoryJSON["kind"], path: string): void {
654
+ tree.descendants((node) => {
655
+ const name = node.type.name;
656
+ if (node.attrs.section) fail(path, "a story cannot end a section");
657
+ if (name === "noteReference") fail(path, "a story cannot hold a note reference");
658
+ if (COMMENT_NODES.has(name)) fail(path, `a ${kind} cannot hold comments`);
659
+ if (
660
+ (kind === "footnote" || kind === "endnote") &&
661
+ (name === "pageBreak" || name === "columnBreak")
662
+ )
663
+ fail(path, `a note cannot hold a ${name}`);
664
+ return true;
665
+ });
666
+ }
667
+
668
+ const COMMENT_NODES = new Set(["commentStart", "commentEnd", "commentReference"]);
669
+
670
+ const V4_NODES = new Set(["table", "tableRow", "tableCell", "picture"]);
671
+ const V5_NODES = new Set([
672
+ "fieldStart",
673
+ "fieldCode",
674
+ "fieldSeparator",
675
+ "fieldEnd",
676
+ "controlStart",
677
+ "controlEnd",
678
+ "noteReference",
679
+ "noteMark",
680
+ ]);
681
+ const V5_KEYS = ["stories", "controls", "settings"];
682
+ const V5_SECTION_KEYS = ["columns", "pageNumbers", "footnotes", "endnotes"];
683
+
684
+ /** The first part of a section that schema 5 added, if any. */
685
+ function laterSection(section: unknown): string | undefined {
686
+ return isRecord(section) ? V5_SECTION_KEYS.find((key) => Object.hasOwn(section, key)) : undefined;
687
+ }
688
+
689
+ /**
690
+ * The first thing in validated content JSON that a schema after `version` added, if any: a node
691
+ * type, a block's `controls`, a part of a section.
692
+ */
693
+ function laterNode(
694
+ content: NodeJSON | { content: NodeJSON[] },
695
+ version: number,
696
+ ): { name: string; schema: number } | undefined {
697
+ const stack: unknown[] = [content];
698
+ while (stack.length) {
699
+ const node = stack.pop();
700
+ if (!isRecord(node)) continue;
701
+ const name = node.type as string;
702
+ if (version < 4 && V4_NODES.has(name)) return { name, schema: 4 };
703
+ if (V5_NODES.has(name)) return { name, schema: 5 };
704
+ const attrs = isRecord(node.attrs) ? node.attrs : {};
705
+ if (attrs.controls) return { name: "controls", schema: 5 };
706
+ const part = laterSection(attrs.section);
707
+ if (part) return { name: part, schema: 5 };
708
+ if (Array.isArray(node.content)) for (const child of node.content) stack.push(child);
709
+ }
710
+ return undefined;
711
+ }
712
+
307
713
  const ENVELOPE_KEYS = [
308
714
  "schemaVersion",
309
715
  "section",
@@ -312,6 +718,10 @@ const ENVELOPE_KEYS = [
312
718
  "numbering",
313
719
  "theme",
314
720
  "comments",
721
+ "resources",
722
+ "stories",
723
+ "controls",
724
+ "settings",
315
725
  "content",
316
726
  ];
317
727
 
@@ -363,6 +773,19 @@ function blocks(content: NodeJSON[], path: string): Node[] {
363
773
  return list;
364
774
  }
365
775
 
776
+ const checkCondition: Check = shape(
777
+ {
778
+ type: oneOf(TABLE_CONDITIONS.filter((c) => c !== "wholeTable")),
779
+ paragraph: paragraphProperties,
780
+ run: runProperties,
781
+ table: checkTableProperties,
782
+ row: checkRowProperties,
783
+ cell: checkCellProperties,
784
+ ext: xml,
785
+ },
786
+ ["type"],
787
+ );
788
+
366
789
  const checkStyle: Check = shape(
367
790
  {
368
791
  id: text(),
@@ -374,11 +797,144 @@ const checkStyle: Check = shape(
374
797
  isDefault: bool,
375
798
  paragraph: paragraphProperties,
376
799
  run: runProperties,
800
+ table: checkTableProperties,
801
+ row: checkRowProperties,
802
+ cell: checkCellProperties,
803
+ conditions: listOf(checkCondition, TABLE_CONDITIONS.length),
377
804
  ext: xml,
378
805
  },
379
806
  ["id", "type"],
380
807
  );
381
808
 
809
+ const SAFE_PROTOCOLS = new Set(["http:", "https:", "blob:"]);
810
+
811
+ /** A URL's scheme as a browser resolves it (a relative URL is the base's, https). */
812
+ function protocolOf(url: string): string {
813
+ try {
814
+ return new URL(url, "https://base.invalid/").protocol;
815
+ } catch {
816
+ return "";
817
+ }
818
+ }
819
+
820
+ /** Pictures only: `image/png`, `image/svg+xml`… */
821
+ const IMAGE_TYPE = /^image\/[A-Za-z0-9][\w.+-]{0,126}$/;
822
+
823
+ export const checkResource: Check = (v) => {
824
+ const error = shape(
825
+ {
826
+ contentType: (t) =>
827
+ typeof t === "string" && IMAGE_TYPE.test(t) ? undefined : "must be an image media type",
828
+ size: int(0, Number.MAX_SAFE_INTEGER),
829
+ part: text(1024),
830
+ // Relative, or http(s) or blob: no scheme that runs code (`javascript:`) where it is shown.
831
+ // Read as browsers read it (leading spaces, controls and inner tabs dropped).
832
+ url: (u) =>
833
+ text(8192)(u) ??
834
+ (SAFE_PROTOCOLS.has(protocolOf(u as string))
835
+ ? undefined
836
+ : "must be relative, http(s) or blob"),
837
+ data: (d) =>
838
+ typeof d === "string" && /^data:image\/[\w.+-]+[;,]/i.test(d) && d.length <= 67_108_864
839
+ ? undefined
840
+ : "must be a data: URL of an image",
841
+ },
842
+ ["contentType"],
843
+ )(v);
844
+ if (error) return error;
845
+ const r = v as ResourceJSON;
846
+ return r.part === undefined && r.url === undefined && r.data === undefined
847
+ ? "needs part, url or data"
848
+ : undefined;
849
+ };
850
+
851
+ /** An object keyed by ids, every value passing `check`. */
852
+ const recordOf =
853
+ (check: Check, what: string): Check =>
854
+ (v) => {
855
+ if (!isRecord(v)) return "must be an object";
856
+ const entries = Object.entries(v);
857
+ if (entries.length > 100_000) return `must have at most 100000 ${what}s`;
858
+ for (const [key, value] of entries) {
859
+ // An own `__proto__` key would read as the prototype wherever a missing key is looked up.
860
+ const keyError = key === "__proto__" ? `is not a ${what} key` : text()(key);
861
+ if (keyError) return `${key.slice(0, 64)} ${keyError}`;
862
+ const error = check(value);
863
+ if (error) return `${key} ${error}`;
864
+ }
865
+ return undefined;
866
+ };
867
+
868
+ const checkResources = recordOf(checkResource, "resource");
869
+
870
+ const NOTE_KINDS = ["footnote", "endnote"];
871
+ /** The tree is checked by `parseContent` afterwards, with its path. */
872
+ const checkStory: Check = (v) =>
873
+ shape(
874
+ {
875
+ kind: oneOf(["header", "footer", ...NOTE_KINDS]),
876
+ noteType: oneOf(["normal", "separator", "continuationSeparator", "continuationNotice"]),
877
+ content: (c) => (isRecord(c) ? undefined : "must be an object"),
878
+ ext: xml,
879
+ },
880
+ ["kind", "content"],
881
+ )(v) ??
882
+ (isRecord(v) && v.noteType !== undefined && !NOTE_KINDS.includes(v.kind as string)
883
+ ? "noteType is for notes"
884
+ : undefined);
885
+ const checkStories = recordOf(checkStory, "story");
886
+
887
+ /** A content control's properties. */
888
+ export const checkControl: Check = shape(
889
+ {
890
+ kind: oneOf([
891
+ "text",
892
+ "richText",
893
+ "dropDown",
894
+ "comboBox",
895
+ "date",
896
+ "checkbox",
897
+ "picture",
898
+ "repeating",
899
+ "repeatingItem",
900
+ "other",
901
+ ]),
902
+ tag: str(),
903
+ alias: str(),
904
+ lock: oneOf(["sdtLocked", "contentLocked", "sdtContentLocked", "unlocked"]),
905
+ items: listOf(shape({ value: str(), display: str() }, ["value"])),
906
+ dateFormat: str(),
907
+ date: str(),
908
+ checked: bool,
909
+ checkedState: shape({ value: str(), font: str() }, ["value"]),
910
+ uncheckedState: shape({ value: str(), font: str() }, ["value"]),
911
+ multiLine: bool,
912
+ format: runProperties,
913
+ noInsertDelete: bool,
914
+ deleted: bool,
915
+ placeholder: shape({ showing: bool, docPart: str(), text: str(65_535) }, [], true),
916
+ binding: shape(
917
+ { xpath: str(65_535), storeItemId: str(), prefixMappings: str(65_535) },
918
+ [],
919
+ true,
920
+ ),
921
+ ext: xml,
922
+ },
923
+ ["kind"],
924
+ );
925
+ const checkControls = recordOf(checkControl, "control");
926
+
927
+ const checkSettings: Check = shape(
928
+ {
929
+ doNotUseHTMLParagraphAutoSpacing: bool,
930
+ evenAndOddHeaders: bool,
931
+ footnotes: checkNoteProperties,
932
+ endnotes: checkNoteProperties,
933
+ },
934
+ [],
935
+ true,
936
+ );
937
+
382
938
  const checkLevel: Check = shape(
383
939
  {
384
940
  level: int(0, 8),