@json-to-office/shared-docx 1.2.0 → 1.4.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.
- package/dist/{chunk-BBFR3RRN.js → chunk-37G3V2NS.js} +3 -3
- package/dist/{chunk-TODYYVZ4.js → chunk-74WV6KFK.js} +2 -2
- package/dist/{chunk-OP5PCDNN.js → chunk-BCZ26ZVH.js} +2 -2
- package/dist/{chunk-NAZDY3PK.js → chunk-CBH763W5.js} +4 -4
- package/dist/{chunk-B4STXH5L.js → chunk-EGT7UWOS.js} +2 -2
- package/dist/{chunk-5KOKA5GY.js → chunk-KGQAQE4S.js} +9 -2
- package/dist/{chunk-5KOKA5GY.js.map → chunk-KGQAQE4S.js.map} +1 -1
- package/dist/{chunk-SOI64OJZ.js → chunk-NPI34OFV.js} +6 -6
- package/dist/{chunk-6B3LHADB.js → chunk-PZ6RN72D.js} +2 -2
- package/dist/chunk-PZ6RN72D.js.map +1 -0
- package/dist/{chunk-MYLVUQCN.js → chunk-RPVVIG43.js} +2 -2
- package/dist/{chunk-A2K66URO.js → chunk-YWLLE44T.js} +161 -24
- package/dist/chunk-YWLLE44T.js.map +1 -0
- package/dist/{chunk-VX2J2KWA.js → chunk-ZKBTTJN6.js} +17 -4
- package/dist/chunk-ZKBTTJN6.js.map +1 -0
- package/dist/{chunk-45I2NASU.js → chunk-ZKFPP7QB.js} +3 -3
- package/dist/index.d.ts +18 -5
- package/dist/index.js +15 -12
- package/dist/index.js.map +1 -1
- package/dist/schemas/api.js +7 -7
- package/dist/schemas/component-defaults.js +2 -2
- package/dist/schemas/component-registry.d.ts +9 -0
- package/dist/schemas/component-registry.js +5 -5
- package/dist/schemas/components.d.ts +88 -1
- package/dist/schemas/components.js +8 -6
- package/dist/schemas/document.js +8 -8
- package/dist/schemas/export.js +6 -6
- package/dist/schemas/generator.js +6 -6
- package/dist/schemas/renderer.js +2 -2
- package/dist/schemas/theme.d.ts +0 -3
- package/dist/schemas/theme.js +3 -3
- package/dist/validation/unified/index.js +8 -8
- package/package.json +5 -5
- package/dist/chunk-6B3LHADB.js.map +0 -1
- package/dist/chunk-A2K66URO.js.map +0 -1
- package/dist/chunk-VX2J2KWA.js.map +0 -1
- /package/dist/{chunk-BBFR3RRN.js.map → chunk-37G3V2NS.js.map} +0 -0
- /package/dist/{chunk-TODYYVZ4.js.map → chunk-74WV6KFK.js.map} +0 -0
- /package/dist/{chunk-OP5PCDNN.js.map → chunk-BCZ26ZVH.js.map} +0 -0
- /package/dist/{chunk-NAZDY3PK.js.map → chunk-CBH763W5.js.map} +0 -0
- /package/dist/{chunk-B4STXH5L.js.map → chunk-EGT7UWOS.js.map} +0 -0
- /package/dist/{chunk-SOI64OJZ.js.map → chunk-NPI34OFV.js.map} +0 -0
- /package/dist/{chunk-MYLVUQCN.js.map → chunk-RPVVIG43.js.map} +0 -0
- /package/dist/{chunk-45I2NASU.js.map → chunk-ZKFPP7QB.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/diff/word-diff.ts","../src/diff/document-diff.ts","../src/index.ts","../src/validation/parsers/json.ts","../src/validation/validators/theme.ts","../src/validation/validators/component.ts","../src/validation/core/validator.ts","../src/validation/core/errors.ts","../src/types/components.ts"],"sourcesContent":["/**\n * Word-level text diff\n *\n * Tokenizes text into words and whitespace, runs an LCS diff over the\n * tokens, and emits revision segments. Pure, dependency-free.\n */\n\nimport type { RevisionSegment } from '../schemas/components/revision';\n\n/**\n * Anchored to the schema type so the diff engine can never emit segments\n * the RevisionSchema would reject.\n */\nexport type DiffSegment = RevisionSegment;\n\n/**\n * Above this many DP cells the LCS table is not worth building: fall back\n * to a whole-text replace. ~1000x1000 tokens covers any realistic paragraph.\n */\nconst MAX_LCS_CELLS = 1_000_000;\n\n/** Split into alternating word / whitespace tokens (both preserved). */\nexport function tokenizeWords(text: string): string[] {\n if (!text) return [];\n return text.split(/(\\s+)/).filter((t) => t.length > 0);\n}\n\nfunction mergeSegments(segments: DiffSegment[]): DiffSegment[] {\n const merged: DiffSegment[] = [];\n for (const seg of segments) {\n if (!seg.text) continue;\n const last = merged[merged.length - 1];\n if (last && last.type === seg.type) {\n last.text += seg.text;\n } else {\n merged.push({ ...seg });\n }\n }\n return merged;\n}\n\n/**\n * Readability pass over the raw LCS output:\n * 1. A whitespace-only equal segment flanked by changes joins the change\n * (the space is both deleted and re-inserted), so \"x y\" -> \"a b\" reads\n * as one replacement instead of three fragments.\n * 2. Within each change run, deletions are emitted before insertions.\n * The old/new reconstruction invariant is preserved.\n */\nfunction normalizeSegments(segments: DiffSegment[]): DiffSegment[] {\n const folded: DiffSegment[] = [];\n for (let k = 0; k < segments.length; k++) {\n const seg = segments[k];\n if (seg.type === 'equal' && /^\\s+$/.test(seg.text)) {\n const prev = folded[folded.length - 1];\n const next = segments[k + 1];\n if (prev && prev.type !== 'equal' && next && next.type !== 'equal') {\n folded.push(\n { type: 'delete', text: seg.text },\n { type: 'insert', text: seg.text }\n );\n continue;\n }\n }\n folded.push({ ...seg });\n }\n\n const out: DiffSegment[] = [];\n let k = 0;\n while (k < folded.length) {\n if (folded[k].type === 'equal') {\n out.push(folded[k]);\n k++;\n continue;\n }\n let deleted = '';\n let inserted = '';\n while (k < folded.length && folded[k].type !== 'equal') {\n if (folded[k].type === 'delete') deleted += folded[k].text;\n else inserted += folded[k].text;\n k++;\n }\n if (deleted) out.push({ type: 'delete', text: deleted });\n if (inserted) out.push({ type: 'insert', text: inserted });\n }\n return mergeSegments(out);\n}\n\n/**\n * Word-level diff between two strings.\n *\n * Returns merged segments in document order. Deleting everything and\n * inserting everything (whole replace) is the degenerate output for\n * completely different texts or oversized inputs.\n */\nexport function diffWords(oldText: string, newText: string): DiffSegment[] {\n if (oldText === newText) {\n return oldText ? [{ type: 'equal', text: oldText }] : [];\n }\n\n const oldTokens = tokenizeWords(oldText);\n const newTokens = tokenizeWords(newText);\n\n if (oldTokens.length === 0) {\n return mergeSegments([{ type: 'insert', text: newText }]);\n }\n if (newTokens.length === 0) {\n return mergeSegments([{ type: 'delete', text: oldText }]);\n }\n\n if (oldTokens.length * newTokens.length > MAX_LCS_CELLS) {\n return mergeSegments([\n { type: 'delete', text: oldText },\n { type: 'insert', text: newText },\n ]);\n }\n\n // Standard LCS dynamic programming table\n const n = oldTokens.length;\n const m = newTokens.length;\n // lcs[i][j] = LCS length of oldTokens[i..] and newTokens[j..]\n const lcs: Int32Array[] = Array.from(\n { length: n + 1 },\n () => new Int32Array(m + 1)\n );\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i][j] =\n oldTokens[i] === newTokens[j]\n ? lcs[i + 1][j + 1] + 1\n : Math.max(lcs[i + 1][j], lcs[i][j + 1]);\n }\n }\n\n // Backtrack\n const segments: DiffSegment[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (oldTokens[i] === newTokens[j]) {\n segments.push({ type: 'equal', text: oldTokens[i] });\n i++;\n j++;\n } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {\n segments.push({ type: 'delete', text: oldTokens[i] });\n i++;\n } else {\n segments.push({ type: 'insert', text: newTokens[j] });\n j++;\n }\n }\n while (i < n) {\n segments.push({ type: 'delete', text: oldTokens[i] });\n i++;\n }\n while (j < m) {\n segments.push({ type: 'insert', text: newTokens[j] });\n j++;\n }\n\n return normalizeSegments(segments);\n}\n\n/**\n * Strip the inline markdown the renderer understands (bold/italic markers,\n * hyperlinks) so revision segments — which render literally — never expose\n * raw markers. Uses the exact decorator regex of textParser.ts (lazy\n * [\\s\\S]*? content), so what the parser would style, this strips — including\n * content containing '*' or '_' (e.g. **snake_case**).\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '$1') // [text](url) -> text\n .replace(\n /(\\*\\*\\*|___)([\\s\\S]*?)\\1|(\\*\\*|__)([\\s\\S]*?)\\3|(\\*|_)([\\s\\S]*?)\\5/g,\n (_match, _d1, bi, _d2, b, _d3, i) => bi ?? b ?? i ?? ''\n );\n}\n","/**\n * Document diff engine\n *\n * Compares two json-to-office DOCX definitions and produces a redline\n * document: a third definition (based on the new one) where text changes\n * are expressed as `revision` segments that the renderer turns into native\n * Word tracked changes (w:ins / w:del).\n *\n * Scope (v1):\n * - paragraph / heading: word-level tracked changes\n * - list: item-level alignment, word-level tracked changes per item\n * - containers (section, columns, text-box, ...): recursed into\n * - everything else (table, image, chart, ...): block replace, reported\n * as an *untracked* change in the summary — Word has no native revision\n * for these at the fidelity docx.js supports.\n */\n\nimport { diffWords, stripMarkdown, type DiffSegment } from './word-diff';\n\n/** Structural view of any component node — schemas validate elsewhere. */\nexport interface JsonNode {\n name: string;\n props?: Record<string, unknown>;\n children?: JsonNode[];\n [key: string]: unknown;\n}\n\nexport interface DiffDocumentsOptions {\n /** Revision author shown in Word (default: \"json-to-office\") */\n author?: string;\n /** Revision timestamp, ISO 8601 (default: deterministic epoch) */\n date?: string;\n}\n\nexport interface UntrackedChange {\n /** JSON-pointer-ish location in the NEW document */\n path: string;\n kind: 'modified' | 'inserted' | 'deleted';\n component: string;\n detail: string;\n}\n\nexport interface DiffSummary {\n /** Blocks rendered with native tracked changes */\n tracked: {\n modified: number;\n inserted: number;\n deleted: number;\n };\n /** Changes the redline cannot express as native revisions */\n untracked: UntrackedChange[];\n unchangedBlocks: number;\n /** Aggregate fidelity caveats about the redline */\n notes: string[];\n}\n\nexport interface DiffDocumentsResult {\n /** Redline document definition (renderable as-is) */\n document: JsonNode;\n summary: DiffSummary;\n}\n\nconst TEXT_COMPONENTS = new Set(['paragraph', 'heading']);\n\ntype ListItem = string | { text: string; level?: number };\n\ninterface NormalizedListItem {\n /** Original item text (markdown intact) — emitted for unchanged items */\n raw: string;\n /** NFC-normalized, markdown-stripped text — used for alignment and diffing */\n text: string;\n level: number;\n}\n\ninterface DiffContext {\n author?: string;\n date?: string;\n summary: DiffSummary;\n}\n\n// Key-order sensitive: props objects with the same entries in a different\n// order compare unequal. Acceptable — inputs are machine-generated and a\n// false \"changed\" only adds a spurious untracked summary entry.\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction makeRevision(ctx: DiffContext, segments: DiffSegment[]) {\n return {\n ...(ctx.author && { author: ctx.author }),\n ...(ctx.date && { date: ctx.date }),\n segments,\n };\n}\n\n/** Raw text prop, NFC-normalized (matching the renderer's normalization). */\nfunction rawText(node: JsonNode): string {\n const text = node.props?.text;\n return typeof text === 'string' ? text.normalize('NFC') : '';\n}\n\n/** Text of a text component as it renders: NFC-normalized, markdown stripped. */\nfunction plainText(node: JsonNode): string {\n return stripMarkdown(rawText(node));\n}\n\nconst PLACEHOLDER_PATTERN = /\\{[^}]+\\}/;\n\n/** A node is rendered unless it explicitly opts out with enabled: false. */\nfunction isEnabled(node: JsonNode): boolean {\n return node.enabled !== false;\n}\n\nfunction notePlaceholdersInChanges(\n segments: DiffSegment[],\n path: string,\n component: string,\n ctx: DiffContext\n): void {\n if (\n segments.some((s) => s.type !== 'equal' && PLACEHOLDER_PATTERN.test(s.text))\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component,\n detail:\n 'placeholder (e.g. {DATE}) inside inserted/deleted text renders literally in the redline',\n });\n }\n}\n\nfunction propsWithout(\n props: Record<string, unknown> | undefined,\n ...keys: string[]\n): Record<string, unknown> {\n const copy = { ...(props || {}) };\n for (const key of keys) delete copy[key];\n return copy;\n}\n\n// ---------------------------------------------------------------------------\n// Generic LCS alignment over arrays\n// ---------------------------------------------------------------------------\n\ntype AlignOp<T> =\n | { op: 'equal'; oldItem: T; newItem: T }\n | { op: 'delete'; oldItem: T }\n | { op: 'insert'; newItem: T };\n\n/**\n * Above this many DP cells the LCS table is not worth its memory (an\n * Int32Array table lives off the V8 heap). Typical edits touch few blocks,\n * so the prefix/suffix trim below makes the table tiny in practice.\n */\nconst MAX_ALIGN_CELLS = 4_000_000;\n\n/** LCS alignment of two arrays under a stable key function. */\nfunction alignByLcs<T>(\n oldItems: T[],\n newItems: T[],\n key: (item: T) => string\n): AlignOp<T>[] {\n const oldKeys = oldItems.map(key);\n const newKeys = newItems.map(key);\n\n // Trim the common prefix and suffix — emitted as equal ops directly\n let start = 0;\n while (\n start < oldItems.length &&\n start < newItems.length &&\n oldKeys[start] === newKeys[start]\n ) {\n start++;\n }\n let oldEnd = oldItems.length;\n let newEnd = newItems.length;\n while (\n oldEnd > start &&\n newEnd > start &&\n oldKeys[oldEnd - 1] === newKeys[newEnd - 1]\n ) {\n oldEnd--;\n newEnd--;\n }\n\n const prefix: AlignOp<T>[] = [];\n for (let k = 0; k < start; k++) {\n prefix.push({ op: 'equal', oldItem: oldItems[k], newItem: newItems[k] });\n }\n const suffix: AlignOp<T>[] = [];\n for (let k = 0; k < oldItems.length - oldEnd; k++) {\n suffix.push({\n op: 'equal',\n oldItem: oldItems[oldEnd + k],\n newItem: newItems[newEnd + k],\n });\n }\n\n const n = oldEnd - start;\n const m = newEnd - start;\n const middle: AlignOp<T>[] = [];\n\n if (n * m > MAX_ALIGN_CELLS) {\n // Degenerate fallback: replace the whole middle\n for (let k = 0; k < n; k++) {\n middle.push({ op: 'delete', oldItem: oldItems[start + k] });\n }\n for (let k = 0; k < m; k++) {\n middle.push({ op: 'insert', newItem: newItems[start + k] });\n }\n return [...prefix, ...middle, ...suffix];\n }\n\n const lcs: Int32Array[] = Array.from(\n { length: n + 1 },\n () => new Int32Array(m + 1)\n );\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i][j] =\n oldKeys[start + i] === newKeys[start + j]\n ? lcs[i + 1][j + 1] + 1\n : Math.max(lcs[i + 1][j], lcs[i][j + 1]);\n }\n }\n\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (oldKeys[start + i] === newKeys[start + j]) {\n middle.push({\n op: 'equal',\n oldItem: oldItems[start + i],\n newItem: newItems[start + j],\n });\n i++;\n j++;\n } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {\n middle.push({ op: 'delete', oldItem: oldItems[start + i] });\n i++;\n } else {\n middle.push({ op: 'insert', newItem: newItems[start + j] });\n j++;\n }\n }\n while (i < n) middle.push({ op: 'delete', oldItem: oldItems[start + i++] });\n while (j < m) middle.push({ op: 'insert', newItem: newItems[start + j++] });\n\n return [...prefix, ...middle, ...suffix];\n}\n\n/**\n * Within a run of deletes+inserts between two equal anchors, pair removed\n * and added nodes that share the same component name (\"modified\" instead of\n * \"deleted + inserted\"). Pairing is greedy and order-preserving.\n */\ninterface GapPairing<T> {\n pairs: { oldItem: T; newItem: T }[];\n /** Emission plan preserving relative order */\n plan: (\n | { kind: 'deleted'; oldItem: T }\n | { kind: 'inserted'; newItem: T }\n | { kind: 'paired'; oldItem: T; newItem: T }\n )[];\n}\n\nfunction pairGap<T>(\n deleted: T[],\n inserted: T[],\n pairable: (oldItem: T, newItem: T) => boolean\n): GapPairing<T> {\n const usedOld = new Array<boolean>(deleted.length).fill(false);\n const pairing = new Array<number>(inserted.length).fill(-1);\n\n let searchFrom = 0;\n for (let j = 0; j < inserted.length; j++) {\n for (let i = searchFrom; i < deleted.length; i++) {\n if (!usedOld[i] && pairable(deleted[i], inserted[j])) {\n usedOld[i] = true;\n pairing[j] = i;\n searchFrom = i + 1; // keep pairs order-preserving\n break;\n }\n }\n }\n\n const plan: GapPairing<T>['plan'] = [];\n const pairs: GapPairing<T>['pairs'] = [];\n let emittedOld = 0;\n for (let j = 0; j < inserted.length; j++) {\n const i = pairing[j];\n if (i >= 0) {\n // Old nodes before this pair that were never matched: emit as deleted\n while (emittedOld < i) {\n if (!usedOld[emittedOld]) {\n plan.push({ kind: 'deleted', oldItem: deleted[emittedOld] });\n }\n emittedOld++;\n }\n emittedOld = i + 1;\n plan.push({ kind: 'paired', oldItem: deleted[i], newItem: inserted[j] });\n pairs.push({ oldItem: deleted[i], newItem: inserted[j] });\n } else {\n plan.push({ kind: 'inserted', newItem: inserted[j] });\n }\n }\n for (let i = emittedOld; i < deleted.length; i++) {\n if (!usedOld[i]) plan.push({ kind: 'deleted', oldItem: deleted[i] });\n }\n return { pairs, plan };\n}\n\n// ---------------------------------------------------------------------------\n// Component-level diff\n// ---------------------------------------------------------------------------\n\n/** Modified text component → new node carrying revision segments. */\nfunction diffTextComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const oldText = plainText(oldNode);\n const newText = plainText(newNode);\n\n // `comment` joins `revision` here: both are review metadata rather than\n // formatting, so a changed comment must not be reported as an untracked\n // formatting change.\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'text', 'revision', 'comment'),\n propsWithout(newNode.props, 'text', 'revision', 'comment')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'formatting/props changed (not expressible as a tracked change); new version rendered',\n });\n }\n\n if (oldText === newText) {\n // Same rendered text, but markdown-only differences (bold markers,\n // hyperlink targets) are invisible after stripping — surface them.\n if (rawText(oldNode) !== rawText(newNode)) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'inline formatting or link target changed (markdown-only); new version rendered without a tracked change',\n });\n } else if (!propsChanged) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n ctx.summary.tracked.modified++;\n const segments = diffWords(oldText, newText);\n notePlaceholdersInChanges(segments, path, newNode.name, ctx);\n // Revision segments render literally, so markdown anywhere in a modified\n // block — including its unchanged portions — is flattened to plain text\n if (rawText(oldNode) !== oldText || rawText(newNode) !== newText) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'inline formatting or links flattened to plain text in the redline (revision segments render literally)',\n });\n }\n return {\n ...newNode,\n props: {\n ...revisedTextProps(newNode, path, ctx),\n text: newText,\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\n/**\n * Props for a paragraph the redline marks as a tracked change.\n *\n * `footnotes`/`endnotes` cannot ride along: revision segments render literally,\n * so a `[^id]` marker inside them never resolves — and the renderer rejects the\n * pair outright, so emitting both would produce a redline that cannot be\n * rendered at all. Drop them and say so, the same way the differ reports every\n * other change Word cannot express.\n */\nfunction revisedTextProps(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): Record<string, unknown> {\n const props = { ...(node.props ?? {}) };\n const dropped = (['footnotes', 'endnotes'] as const).filter((kind) => {\n const notes = props[kind];\n return Array.isArray(notes) && notes.length > 0;\n });\n\n if (dropped.length === 0) return props;\n\n for (const kind of dropped) delete props[kind];\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: node.name,\n detail: `${dropped.join(' and ')} dropped from a tracked-change paragraph (note markers do not resolve inside revision text); the note bodies are not in the redline`,\n });\n return props;\n}\n\n/** Whole text component inserted/deleted → fully tracked block. */\nfunction insertedTextComponent(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n ctx.summary.tracked.inserted++;\n const text = plainText(node);\n const segments: DiffSegment[] = [{ type: 'insert', text }];\n notePlaceholdersInChanges(segments, path, node.name, ctx);\n return {\n ...node,\n props: {\n ...revisedTextProps(node, path, ctx),\n text,\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\nfunction deletedTextComponent(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n ctx.summary.tracked.deleted++;\n const text = plainText(node);\n const segments: DiffSegment[] = [{ type: 'delete', text }];\n notePlaceholdersInChanges(segments, path, node.name, ctx);\n return {\n ...node,\n props: {\n ...revisedTextProps(node, path, ctx),\n text: '',\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// List diff\n// ---------------------------------------------------------------------------\n\nfunction normalizeListItems(node: JsonNode): NormalizedListItem[] {\n const items = (node.props?.items as ListItem[] | undefined) || [];\n return items.map((item) => {\n const raw = typeof item === 'string' ? item : item.text;\n const level = typeof item === 'string' ? 0 : item.level || 0;\n return { raw, text: stripMarkdown(raw.normalize('NFC')), level };\n });\n}\n\nfunction diffListComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'items'),\n propsWithout(newNode.props, 'items')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'list',\n detail:\n 'list configuration changed (format/levels/spacing); new version rendered',\n });\n }\n\n const oldItems = normalizeListItems(oldNode);\n const newItems = normalizeListItems(newNode);\n\n const stripped = (items: NormalizedListItem[]) =>\n items.map((i) => ({ text: i.text, level: i.level }));\n if (deepEqual(stripped(oldItems), stripped(newItems))) {\n if (\n !deepEqual(\n oldItems.map((i) => i.raw),\n newItems.map((i) => i.raw)\n )\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'list',\n detail:\n 'inline formatting or link target changed in list items (markdown-only); new version rendered without a tracked change',\n });\n } else if (!propsChanged) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n const ops = alignByLcs(\n oldItems,\n newItems,\n (item) => `${item.level}:${item.text}`\n );\n\n // Collapse delete/insert runs into modified pairs (same level)\n const outItems: Array<{\n text: string;\n level?: number;\n revision?: ReturnType<typeof makeRevision>;\n }> = [];\n let changed = false;\n\n let k = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n // Unchanged item: keep the raw text so markdown/hyperlinks survive\n outItems.push({ text: op.newItem.raw, level: op.newItem.level });\n k++;\n continue;\n }\n // Collect the full delete/insert run\n const deleted: NormalizedListItem[] = [];\n const inserted: NormalizedListItem[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n const { plan } = pairGap(\n deleted,\n inserted,\n (oldItem, newItem) => oldItem.level === newItem.level\n );\n for (const step of plan) {\n changed = true;\n if (step.kind === 'paired') {\n const segments = diffWords(step.oldItem.text, step.newItem.text);\n notePlaceholdersInChanges(segments, path, 'list', ctx);\n outItems.push({\n text: step.newItem.text,\n level: step.newItem.level,\n revision: makeRevision(ctx, segments),\n });\n } else if (step.kind === 'inserted') {\n outItems.push({\n text: step.newItem.text,\n level: step.newItem.level,\n revision: makeRevision(ctx, [\n { type: 'insert', text: step.newItem.text },\n ]),\n });\n } else {\n outItems.push({\n text: '',\n level: step.oldItem.level,\n revision: makeRevision(ctx, [\n { type: 'delete', text: step.oldItem.text },\n ]),\n });\n }\n }\n }\n\n if (changed) ctx.summary.tracked.modified++;\n return {\n ...newNode,\n props: { ...newNode.props, items: outItems },\n };\n}\n\nfunction listWithAllItems(\n node: JsonNode,\n type: 'insert' | 'delete',\n ctx: DiffContext\n): JsonNode {\n if (type === 'insert') ctx.summary.tracked.inserted++;\n else ctx.summary.tracked.deleted++;\n const items = normalizeListItems(node).map((item) => ({\n text: type === 'insert' ? item.text : '',\n level: item.level,\n revision: makeRevision(ctx, [{ type, text: item.text }]),\n }));\n return { ...node, props: { ...node.props, items } };\n}\n\n// ---------------------------------------------------------------------------\n// Table diff\n// ---------------------------------------------------------------------------\n\n/** A table cell as authored: anything but `content` is styling we carry over. */\ntype TableCell = Record<string, unknown> & { content?: unknown };\n\n/** One row's cells, in column order, plus the alignment key. */\ninterface TableRowView {\n cells: (TableCell | undefined)[];\n /** Markdown-stripped cell texts joined — what rows are aligned on. */\n key: string;\n /** Cell texts with markdown intact, for spotting markdown-only edits. */\n rawKey: string;\n /**\n * Authored `props.rows[i]` for this row, carried through the diff.\n *\n * It has to travel with the row rather than by index: the diff reinserts\n * deleted rows from the old table, so the emitted order no longer matches\n * either input's `props.rows` indices.\n */\n rowProps?: Record<string, unknown>;\n}\n\n/** Text of a cell as it renders: a plain string, or a nested component's text. */\nfunction cellText(cell: TableCell | undefined): string {\n if (!cell) return '';\n const content = cell.content;\n if (typeof content === 'string')\n return stripMarkdown(content.normalize('NFC'));\n if (content && typeof content === 'object') {\n const props = (content as JsonNode).props;\n const text = props?.text;\n if (typeof text === 'string') return stripMarkdown(text.normalize('NFC'));\n }\n return '';\n}\n\n/** Cell text with markdown intact — what the author wrote. */\nfunction cellRawText(cell: TableCell | undefined): string {\n if (!cell) return '';\n const content = cell.content;\n if (typeof content === 'string') return content.normalize('NFC');\n if (content && typeof content === 'object') {\n const text = (content as JsonNode).props?.text;\n if (typeof text === 'string') return text.normalize('NFC');\n }\n return '';\n}\n\n/** True when the cell holds plain text a word-level diff can rewrite. */\nfunction isTextCell(cell: TableCell | undefined): boolean {\n if (!cell) return true;\n const content = cell.content;\n if (content === undefined || typeof content === 'string') return true;\n return (\n typeof content === 'object' && (content as JsonNode).name === 'paragraph'\n );\n}\n\n/** Turn the column-major model into rows, which is how people read a table. */\nfunction toRowView(node: JsonNode): TableRowView[] {\n const columns =\n (node.props?.columns as { cells?: TableCell[] }[] | undefined) ?? [];\n const rowCount = columns.reduce(\n (max, column) => Math.max(max, column.cells?.length ?? 0),\n 0\n );\n\n const authoredRows =\n (node.props?.rows as Record<string, unknown>[] | undefined) ?? [];\n\n return Array.from({ length: rowCount }, (_, rowIndex) => {\n const cells = columns.map((column) => column.cells?.[rowIndex]);\n return {\n cells,\n key: cells.map(cellText).join('\\u0000'),\n rawKey: cells.map(cellRawText).join('\\u0000'),\n rowProps: authoredRows[rowIndex],\n };\n });\n}\n\n/** Write a row-major set of rows back into the column-major model. */\nfunction withRows(\n node: JsonNode,\n rows: TableRowView[],\n rowProps: ({ revision?: unknown } | Record<string, never>)[]\n): JsonNode {\n const columns = (node.props?.columns as Record<string, unknown>[]) ?? [];\n // Each row keeps what it was authored with (cantSplit, tableHeader, ...);\n // the diff's own revision mark takes precedence over an authored one.\n const merged = rows.map((row, index) => ({\n ...(row.rowProps ?? {}),\n ...rowProps[index],\n }));\n return {\n ...node,\n props: {\n ...node.props,\n columns: columns.map((column, colIndex) => ({\n ...column,\n cells: rows.map((row) => row.cells[colIndex] ?? { content: '' }),\n })),\n ...(merged.some((props) => Object.keys(props).length > 0) && {\n rows: merged,\n }),\n },\n };\n}\n\n/**\n * True for the column-based table shape the differ understands. The legacy\n * `{ headers, rows }` shape is schema-invalid and only kept alive by a\n * renderer conversion, so it stays on the opaque path.\n */\nfunction isColumnTable(node: JsonNode): boolean {\n return Array.isArray(node.props?.columns) && !node.props?.headers;\n}\n\n/** A cell whose text is replaced by a word-level tracked change. */\nfunction revisedCell(\n cell: TableCell | undefined,\n oldCell: TableCell | undefined,\n oldText: string,\n newText: string,\n path: string,\n ctx: DiffContext\n): TableCell {\n const segments = diffWords(oldText, newText);\n notePlaceholdersInChanges(segments, path, 'table', ctx);\n // Revision segments render literally, so markdown anywhere in a changed cell\n // — including its unchanged portions — is flattened to plain text.\n if (cellRawText(oldCell) !== oldText || cellRawText(cell) !== newText) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'inline formatting or links flattened to plain text in a table cell (revision segments render literally)',\n });\n }\n const base = cell ?? { content: '' };\n return {\n ...base,\n // The revision carries the text, so `content` keeps the new version for\n // readers that ignore tracked changes. A component cell keeps being a\n // component — replacing it with a bare string would silently discard the\n // paragraph's font, alignment and the rest.\n content: revisedCellContent(base.content, newText, path, ctx),\n revision: makeRevision(ctx, segments),\n };\n}\n\n/**\n * The new `content` for a revised cell: a plain string stays a string, a\n * paragraph component keeps its props and only its text is rewritten.\n *\n * Notes cannot come along — the cell's revision drives the rendered runs, so a\n * `[^id]` marker in them never resolves, exactly as on a revised paragraph.\n */\nfunction revisedCellContent(\n content: unknown,\n newText: string,\n path: string,\n ctx: DiffContext\n): unknown {\n if (!content || typeof content !== 'object') return newText;\n\n const component = content as JsonNode;\n return {\n ...component,\n props: {\n ...revisedTextProps(component, path, ctx),\n text: newText,\n },\n };\n}\n\n/**\n * Diff a column-based table row by row.\n *\n * The model is column-major, so the diff builds a row-major view first: people\n * insert and delete rows, not columns. Rows are aligned on their joined,\n * markdown-stripped cell texts; unmatched runs are paired by column count so a\n * rewritten row becomes cell-level word changes rather than a delete plus an\n * insert.\n *\n * The legacy `{ headers, rows }` shape is not handled here — it is\n * schema-invalid and the renderer only converts it for backwards\n * compatibility, so it stays on the opaque block-replace path.\n */\nfunction diffTableComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const oldRows = toRowView(oldNode);\n const newRows = toRowView(newNode);\n\n const oldColumns = (oldNode.props?.columns as unknown[] | undefined) ?? [];\n const newColumns = (newNode.props?.columns as unknown[] | undefined) ?? [];\n if (oldColumns.length !== newColumns.length) {\n // Column insert/delete is a different tracked change (`w:tcPrChange` and\n // friends) that the renderer cannot express, so fall back to a replace.\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table column count changed (columns are not expressible as a tracked change); new version rendered',\n });\n return newNode;\n }\n\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'columns', 'rows'),\n propsWithout(newNode.props, 'columns', 'rows')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table configuration changed (borders/widths/defaults); new version rendered',\n });\n }\n\n const headersChanged = !deepEqual(\n oldColumns.map((column) => (column as { header?: unknown }).header),\n newColumns.map((column) => (column as { header?: unknown }).header)\n );\n if (headersChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table header row changed (headers are not row content); new version rendered',\n });\n }\n\n if (\n deepEqual(\n oldRows.map((row) => row.key),\n newRows.map((row) => row.key)\n )\n ) {\n // Same rendered text, but markdown-only differences (bold markers,\n // hyperlink targets) are invisible after stripping — surface them, as the\n // paragraph and list paths do.\n if (\n !deepEqual(\n oldRows.map((row) => row.rawKey),\n newRows.map((row) => row.rawKey)\n )\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'inline formatting or link target changed in table cells (markdown-only); new version rendered without a tracked change',\n });\n } else if (\n !propsChanged &&\n !headersChanged &&\n deepEqual(oldRows, newRows)\n ) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n const ops = alignByLcs(oldRows, newRows, (row) => row.key);\n\n const outRows: TableRowView[] = [];\n const outProps: ({ revision?: unknown } | Record<string, never>)[] = [];\n let changed = false;\n\n const push = (\n row: TableRowView,\n props: { revision?: unknown } | Record<string, never>\n ) => {\n outRows.push(row);\n outProps.push(props);\n };\n\n let k = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n push(op.newItem, {});\n k++;\n continue;\n }\n\n const deleted: TableRowView[] = [];\n const inserted: TableRowView[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n\n const { plan } = pairGap(\n deleted,\n inserted,\n (oldRow, newRow) =>\n oldRow.cells.length === newRow.cells.length &&\n oldRow.cells.every(isTextCell) &&\n newRow.cells.every(isTextCell)\n );\n\n for (const step of plan) {\n changed = true;\n if (step.kind === 'paired') {\n const cells = step.newItem.cells.map((cell, index) => {\n const oldText = cellText(step.oldItem.cells[index]);\n const newText = cellText(cell);\n return oldText === newText\n ? cell ?? { content: '' }\n : revisedCell(\n cell,\n step.oldItem.cells[index],\n oldText,\n newText,\n path,\n ctx\n );\n });\n push({ ...step.newItem, cells }, {});\n } else if (step.kind === 'inserted') {\n ctx.summary.tracked.inserted++;\n push(step.newItem, { revision: rowRevision(ctx, 'insert') });\n } else {\n ctx.summary.tracked.deleted++;\n push(step.oldItem, { revision: rowRevision(ctx, 'delete') });\n }\n }\n }\n\n if (changed) ctx.summary.tracked.modified++;\n return withRows(newNode, outRows, outProps);\n}\n\n/** Every row of a table marked inserted or deleted. */\nfunction tableWithAllRows(\n node: JsonNode,\n type: 'insert' | 'delete',\n ctx: DiffContext\n): JsonNode {\n if (type === 'insert') ctx.summary.tracked.inserted++;\n else ctx.summary.tracked.deleted++;\n\n const rows = toRowView(node);\n return withRows(\n node,\n rows,\n rows.map(() => ({ revision: rowRevision(ctx, type) }))\n );\n}\n\n/** A structural row revision (`w:trPr/w:ins` | `w:del`). */\nfunction rowRevision(ctx: DiffContext, type: 'insert' | 'delete') {\n return {\n type,\n ...(ctx.author && { author: ctx.author }),\n ...(ctx.date && { date: ctx.date }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Tree diff\n// ---------------------------------------------------------------------------\n\nfunction isContainer(node: JsonNode): boolean {\n return Array.isArray(node.children);\n}\n\nfunction nodesPairable(oldNode: JsonNode, newNode: JsonNode): boolean {\n return oldNode.name === newNode.name;\n}\n\nfunction diffPairedNode(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n // `enabled` flips change what renders without touching props: treat them\n // as content appearing (insertion) or disappearing (deletion).\n const oldEnabled = isEnabled(oldNode);\n const newEnabled = isEnabled(newNode);\n if (!oldEnabled && !newEnabled) {\n ctx.summary.unchangedBlocks++;\n return newNode;\n }\n if (!oldEnabled && newEnabled) {\n return emitInserted(newNode, path, ctx);\n }\n if (oldEnabled && !newEnabled) {\n // The disabled new node would be filtered at render; emit the old\n // content as a tracked deletion instead (where supported).\n const deletedNode = emitDeleted(oldNode, path, ctx);\n return deletedNode ?? newNode;\n }\n\n if (TEXT_COMPONENTS.has(newNode.name)) {\n return diffTextComponent(oldNode, newNode, path, ctx);\n }\n if (newNode.name === 'list') {\n return diffListComponent(oldNode, newNode, path, ctx);\n }\n if (\n newNode.name === 'table' &&\n isColumnTable(oldNode) &&\n isColumnTable(newNode)\n ) {\n return diffTableComponent(oldNode, newNode, path, ctx);\n }\n if (isContainer(newNode) || isContainer(oldNode)) {\n const propsChanged = !deepEqual(oldNode.props, newNode.props);\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail: 'container props changed; new version rendered',\n });\n }\n return {\n ...newNode,\n children: diffChildren(\n oldNode.children || [],\n newNode.children || [],\n `${path}/children`,\n ctx\n ),\n };\n }\n // Opaque component (table, image, chart, ...): block replace\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail: `\"${newNode.name}\" changed (no native tracked-change support); new version rendered`,\n });\n return newNode;\n}\n\nfunction emitInserted(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n // A disabled node renders nothing — keep it, but track nothing\n if (!isEnabled(node)) {\n return node;\n }\n if (TEXT_COMPONENTS.has(node.name)) {\n return insertedTextComponent(node, path, ctx);\n }\n if (node.name === 'list') {\n return listWithAllItems(node, 'insert', ctx);\n }\n if (node.name === 'table' && isColumnTable(node)) {\n return tableWithAllRows(node, 'insert', ctx);\n }\n if (isContainer(node)) {\n if (typeof node.props?.title === 'string') {\n ctx.summary.untracked.push({\n path,\n kind: 'inserted',\n component: node.name,\n detail: `\"${node.name}\" title rendered without insertion mark (titles are props, not text blocks)`,\n });\n }\n return {\n ...node,\n children: diffChildren([], node.children || [], `${path}/children`, ctx),\n };\n }\n ctx.summary.untracked.push({\n path,\n kind: 'inserted',\n component: node.name,\n detail: `\"${node.name}\" added (rendered, but not marked as a tracked insertion)`,\n });\n return node;\n}\n\n/** Returns the redline node for a deleted block, or null if it must be dropped. */\nfunction emitDeleted(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode | null {\n // A disabled node never rendered — drop it silently\n if (!isEnabled(node)) {\n return null;\n }\n if (TEXT_COMPONENTS.has(node.name)) {\n return deletedTextComponent(node, path, ctx);\n }\n if (node.name === 'list') {\n return listWithAllItems(node, 'delete', ctx);\n }\n if (node.name === 'table' && isColumnTable(node)) {\n // No longer null: a deleted table renders with every row marked deleted\n // rather than vanishing from the redline.\n return tableWithAllRows(node, 'delete', ctx);\n }\n if (isContainer(node)) {\n if (typeof node.props?.title === 'string') {\n ctx.summary.untracked.push({\n path,\n kind: 'deleted',\n component: node.name,\n detail: `\"${node.name}\" title still rendered without deletion mark (titles are props, not text blocks)`,\n });\n }\n const children = diffChildren(\n node.children || [],\n [],\n `${path}/children`,\n ctx\n );\n return { ...node, children };\n }\n ctx.summary.untracked.push({\n path,\n kind: 'deleted',\n component: node.name,\n detail: `\"${node.name}\" removed (dropped from the redline; Word cannot mark it as a tracked deletion)`,\n });\n return null;\n}\n\nexport function diffChildren(\n oldChildren: JsonNode[],\n newChildren: JsonNode[],\n path: string,\n ctx: DiffContext\n): JsonNode[] {\n const ops = alignByLcs(oldChildren, newChildren, (node) =>\n JSON.stringify(node)\n );\n\n const out: JsonNode[] = [];\n let k = 0;\n let newIndex = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n ctx.summary.unchangedBlocks++;\n out.push(op.newItem);\n k++;\n newIndex++;\n continue;\n }\n\n // Collect the full delete/insert run between equal anchors\n const deleted: JsonNode[] = [];\n const inserted: JsonNode[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n\n const { plan } = pairGap(deleted, inserted, nodesPairable);\n for (const step of plan) {\n if (step.kind === 'paired') {\n out.push(\n diffPairedNode(step.oldItem, step.newItem, `${path}/${newIndex}`, ctx)\n );\n newIndex++;\n } else if (step.kind === 'inserted') {\n out.push(emitInserted(step.newItem, `${path}/${newIndex}`, ctx));\n newIndex++;\n } else {\n const deletedNode = emitDeleted(\n step.oldItem,\n `${path}/${newIndex}`,\n ctx\n );\n if (deletedNode) out.push(deletedNode);\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Diff two DOCX definitions into a renderable redline document.\n *\n * Both inputs must be json-to-office DOCX definitions (root `name: \"docx\"`).\n * The result is based on the NEW document; the root gains\n * `trackRevisions: true` so Word opens it in review mode.\n */\nexport function diffDocuments(\n oldDoc: JsonNode,\n newDoc: JsonNode,\n options: DiffDocumentsOptions = {}\n): DiffDocumentsResult {\n if (!oldDoc || oldDoc.name !== 'docx') {\n throw new Error('Old document: top-level component must be \"docx\"');\n }\n if (!newDoc || newDoc.name !== 'docx') {\n throw new Error('New document: top-level component must be \"docx\"');\n }\n\n const summary: DiffSummary = {\n tracked: { modified: 0, inserted: 0, deleted: 0 },\n untracked: [],\n unchangedBlocks: 0,\n notes: [],\n };\n const ctx: DiffContext = {\n author: options.author,\n date: options.date,\n summary,\n };\n\n const rootPropsChanged = !deepEqual(\n propsWithout(oldDoc.props, 'trackRevisions'),\n propsWithout(newDoc.props, 'trackRevisions')\n );\n if (rootPropsChanged) {\n summary.untracked.push({\n path: '/props',\n kind: 'modified',\n component: 'docx',\n detail:\n 'document props changed (theme/metadata/defaults); new version used',\n });\n }\n\n const children = diffChildren(\n oldDoc.children || [],\n newDoc.children || [],\n '/children',\n ctx\n );\n\n if (summary.tracked.deleted > 0) {\n summary.notes.push(\n `${summary.tracked.deleted} fully deleted block(s): accepting all changes leaves an empty paragraph behind (OOXML paragraph-mark deletion is not supported by the renderer)`\n );\n }\n\n const document: JsonNode = {\n ...newDoc,\n props: { ...newDoc.props, trackRevisions: true },\n children,\n };\n\n return { document, summary };\n}\n","// Version information\nexport const SHARED_DOCX_VERSION = '1.0.0';\n\n// ============================================================================\n// Document diff (tracked-change redlines)\n// ============================================================================\n\nexport { diffDocuments, diffWords, stripMarkdown } from './diff';\nexport type {\n DiffDocumentsOptions,\n DiffDocumentsResult,\n DiffSummary,\n UntrackedChange,\n DiffSegment,\n JsonNode,\n} from './diff';\n\n// ============================================================================\n// Format-agnostic re-exports from @json-to-office/shared\n// ============================================================================\n\n// Types\nexport type { ComponentDefinition as SharedComponentDefinition } from '@json-to-office/shared';\nexport type {\n GenerationWarning,\n AddWarningFunction,\n} from '@json-to-office/shared';\n\n// Schema utilities\nexport {\n fixSchemaReferences,\n convertToJsonSchema,\n createComponentSchema,\n createComponentSchemaObject as sharedCreateComponentSchemaObject,\n exportSchemaToFile,\n} from '@json-to-office/shared';\nexport type { ComponentSchemaConfig } from '@json-to-office/shared';\n\n// Validation - format-agnostic from shared\nexport {\n transformValueError,\n transformValueErrors,\n formatErrorSummary,\n groupErrorsByPath,\n createJsonParseError,\n calculatePosition,\n} from '@json-to-office/shared';\nexport type { ValidationError, ValidationResult } from '@json-to-office/shared';\nexport {\n type ErrorFormatterConfig,\n DEFAULT_ERROR_CONFIG,\n createErrorConfig,\n ERROR_EMOJIS,\n formatErrorMessage,\n} from '@json-to-office/shared';\nexport {\n isUnionSchema,\n isObjectSchema,\n isLiteralSchema,\n getObjectSchemaPropertyNames,\n getLiteralValue,\n extractStandardComponentNames,\n clearComponentNamesCache,\n getSchemaMetadata,\n} from '@json-to-office/shared';\n\n// Semver utilities\nexport {\n isValidSemver,\n parseSemver,\n compareSemver,\n latestVersion,\n type ParsedSemver,\n} from '@json-to-office/shared';\n\n// ============================================================================\n// Docx-specific: Document schemas\n// ============================================================================\n\nexport {\n JsonComponentDefinitionSchema,\n JSON_SCHEMA_URLS,\n validateDocumentWithSchema,\n validateJsonComponent as validateJsonComponentDoc,\n} from './schemas/document';\n\nexport type {\n DocumentValidationResult,\n ValidationError as DocumentValidationError,\n} from './schemas/document';\n\n// ============================================================================\n// Docx-specific: Theme schemas\n// ============================================================================\n\nexport {\n ThemeConfigSchema,\n isValidThemeConfig,\n createMinimalTheme,\n} from './schemas/theme';\n\nexport type {\n ThemeConfigJson,\n StyleDefinitions,\n DocumentMargins,\n PageDimensions,\n Page,\n FontDefinition,\n Fonts,\n ComponentDefaults,\n HeadingComponentDefaults,\n ParagraphComponentDefaults,\n ImageComponentDefaults,\n StatisticComponentDefaults,\n TableComponentDefaults,\n SectionComponentDefaults,\n ColumnsComponentDefaults,\n ListComponentDefaults,\n HeadingDefinition,\n} from './schemas/theme';\n\n// ============================================================================\n// Docx-specific: API schemas\n// ============================================================================\n\nexport * from './schemas/api';\n\n// ============================================================================\n// Docx-specific: Validation utilities\n// ============================================================================\n\n// Parser utilities\nexport {\n JsonDocumentParser,\n JsonParsingError,\n JsonValidationError,\n parseJsonComponent,\n validateJsonComponent,\n parseJsonWithLineNumbers,\n} from './validation/parsers/json';\n\n// Theme validators\nexport {\n validateThemeJson,\n isValidThemeJson,\n getValidationSummary,\n} from './validation/validators/theme';\n\n// Component validators\nexport {\n validateComponentProps,\n safeValidateComponentProps,\n safeValidateComponentDefinition,\n isReportProps,\n isSectionProps,\n isHeadingProps,\n isParagraphProps,\n isColumnsProps,\n isImageProps,\n isStatisticProps,\n isTableProps,\n isListProps,\n isCustomComponentProps,\n getValidationErrors,\n} from './validation/validators/component';\n\n// Export formatValidationErrors from theme validator (works for both)\nexport { formatValidationErrors } from './validation/validators/theme';\n\n// New comprehensive validation exports\nexport {\n // Core validators\n validateComponent,\n validateComponentDefinition,\n validateComponents,\n transformAndValidate,\n createValidatedComponent,\n isValidComponent,\n // Error formatting\n formatValidationError,\n formatValidationErrorStrings,\n formatErrorReport,\n getErrorSummary,\n hasCriticalErrors,\n getValidationContext,\n} from './validation';\n\n// Export types from validation\nexport type { ThemeValidationResult } from './validation/validators/theme';\n\nexport type {\n CoreValidationResult,\n StandardComponentName,\n FormattedError,\n} from './validation';\n\n// ============================================================================\n// Docx-specific: Unified Validation System\n// ============================================================================\n\nexport * from './validation/unified';\n\n// Re-export the simple validation API as the main validation interface\nexport { validate, validateStrict } from './validation/unified';\n\n// ============================================================================\n// Docx-specific: Component schemas (JavaScript values)\n// ============================================================================\n\nexport {\n AlignmentSchema,\n JustifiedAlignmentSchema,\n HeadingLevelSchema,\n SpacingSchema,\n LineSpacingSchema,\n IndentSchema,\n ParagraphIndentSchema,\n TabStopTypeSchema,\n TabStopLeaderSchema,\n TabStopSchema,\n TabStopsSchema,\n NumberingSchema,\n BorderSchema,\n MarginsSchema,\n BaseComponentPropsSchema,\n ReportPropsSchema,\n SectionPropsSchema,\n ColumnsPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ImagePropsSchema,\n TextBoxPropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n TocPropsSchema,\n RevisionSchema,\n RevisionSegmentSchema,\n RevisionMarkSchema,\n CommentSchema,\n CommentReplySchema,\n NoteSchema,\n FootnotesSchema,\n EndnotesSchema,\n ListMarkerFontSchema,\n StandardComponentDefinitionSchema,\n ComponentDefinitionSchema,\n} from './schemas/components';\n\n// Component types - export as types only\nexport type {\n BaseComponentProps,\n ReportProps,\n SectionProps,\n ColumnsProps,\n HeadingProps,\n ParagraphProps,\n ImageProps,\n TextBoxProps,\n StatisticProps,\n TableProps,\n ListProps,\n TocProps,\n Revision,\n RevisionSegment,\n RevisionMark,\n Comment,\n CommentReply,\n Note,\n ListMarkerFont,\n Alignment,\n JustifiedAlignment,\n HeadingLevel,\n Spacing,\n LineSpacing,\n Indent,\n ParagraphIndent,\n TabStopType,\n TabStopLeader,\n TabStop,\n TabStops,\n Numbering,\n} from './schemas/components';\n\n// Export ComponentDefinition from types/components.ts (better type inference)\nexport type {\n ComponentDefinition,\n StandardComponentDefinition,\n} from './types/components';\n\nexport {\n STANDARD_COMPONENTS,\n STANDARD_COMPONENTS_SET,\n} from './types/components';\n\n// Component registry — the single source of truth for which components exist,\n// which can hold children, and what those children may be.\nexport {\n STANDARD_COMPONENTS_REGISTRY,\n getStandardComponent,\n getAllStandardComponentNames,\n} from './schemas/component-registry';\n\n// Highcharts component schema (standard component)\nexport { HighchartsPropsSchema } from './schemas/components/highcharts';\nexport type { HighchartsProps } from './schemas/components/highcharts';\n\n// Visual component schema (standard component — a rasterized pptx slide, or a\n// native Word drawing group under the `office-open` renderer)\nexport {\n VisualPropsSchema,\n VisualRasterPropsSchema,\n VisualNativePropsSchema,\n VisualCanvasSchema,\n VisualCanvasBackgroundSchema,\n NATIVE_RENDER_MODE,\n isNativeVisualProps,\n} from './schemas/components/visual';\nexport type {\n VisualProps,\n VisualRasterProps,\n VisualNativeProps,\n VisualCanvas,\n} from './schemas/components/visual';\n\n// Native visual content (the DrawingML element model)\nexport {\n NativeVisualElementSchema,\n NativeVisualCanvasSchema,\n NativeVisualTextPropsSchema,\n NativeVisualShapePropsSchema,\n NativeVisualImagePropsSchema,\n NATIVE_VISUAL_ELEMENT_NAMES,\n} from './schemas/components/visual-native';\nexport type {\n NativeVisualElement,\n NativeVisualElementName,\n NativeVisualCanvas,\n NativeVisualTextProps,\n NativeVisualShapeProps,\n NativeVisualImageProps,\n NativeVisualTextRun,\n NativeVisualTextSegment,\n NativeVisualFill,\n NativeVisualLine,\n} from './schemas/components/visual-native';\n\n// Custom component schemas\nexport {\n TextSpaceAfterPropsSchema,\n TextSpaceAfterComponentSchema,\n CustomComponentDefinitionSchema,\n} from './schemas/custom-components';\n\nexport type { TextSpaceAfterProps } from './schemas/custom-components';\n\n// Legacy support - re-export common types from schemas\nexport type { ThemeName } from './types/common';\n\n// ============================================================================\n// Docx-specific: Schema Export Utilities\n// ============================================================================\n\nexport {\n fixSchemaReferences as fixDocxSchemaReferences,\n convertToJsonSchema as convertDocxToJsonSchema,\n createComponentSchema as createDocxComponentSchema,\n exportSchemaToFile as exportDocxSchemaToFile,\n COMPONENT_METADATA,\n BASE_SCHEMA_METADATA,\n THEME_SCHEMA_METADATA,\n} from './schemas/export';\n\nexport type { ComponentSchemaConfig as DocxComponentSchemaConfig } from './schemas/export';\n\n// ============================================================================\n// Docx-specific: Unified Schema Generation\n// ============================================================================\n\nexport { generateUnifiedDocumentSchema } from './schemas/generator';\n\nexport type {\n CustomComponentInfo,\n GenerateDocumentSchemaOptions,\n} from './schemas/generator';\n\n// Renderer-discriminated schema profiles\nexport {\n DOCX_RENDERER_IDS,\n DEFAULT_DOCX_RENDERER_ID,\n collectDocxRendererErrors,\n docxComponentDefinitionName,\n} from './schemas/renderer';\nexport type { DocxRendererId } from './schemas/renderer';\n\n// ============================================================================\n// Docx-specific: Plugin System Type Support\n// ============================================================================\n\nexport {\n type ReportComponent,\n type ReportComponentFor,\n type SectionComponent,\n type ColumnsComponent,\n type HeadingComponent,\n type ParagraphComponent,\n type TextBoxComponent,\n type ImageComponent,\n type HighchartsComponent,\n type VisualComponent,\n type StatisticComponent,\n type TableComponent,\n type ListComponent,\n type TocComponent,\n type TextSpaceAfterComponent,\n isReportComponent,\n isSectionComponent,\n isColumnsComponent,\n isHeadingComponent,\n isParagraphComponent,\n isTextBoxComponent,\n isImageComponent,\n isHighchartsComponent,\n isVisualComponent,\n isStatisticComponent,\n isTableComponent,\n isListComponent,\n isTocComponent,\n isTextSpaceAfterComponent,\n} from './types/components';\n","import { Value, ValueError } from '@sinclair/typebox/value';\nimport { FormatRegistry } from '@sinclair/typebox';\nimport {\n DocumentValidationResult,\n ValidationError,\n} from '../../schemas/document';\nimport {\n ComponentDefinitionSchema,\n ComponentDefinition,\n} from '../../schemas/components';\n\n// Register format validators with TypeBox\nFormatRegistry.Set('uri', (value: string) => {\n // Accept URLs, relative paths, and file paths\n try {\n new URL(value);\n return true;\n } catch {\n // Check if it's a relative path (common for JSON schemas)\n if (\n value.includes('.json') ||\n value.includes('/') ||\n value.includes('\\\\')\n ) {\n return true;\n }\n // Check if it's an HTTP/HTTPS URL\n return /^https?:\\/\\/.+/.test(value);\n }\n});\n\nFormatRegistry.Set('date-time', (value: string) => {\n // ISO 8601 date-time format validation\n const dateTimeRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z?$/;\n return dateTimeRegex.test(value) && !isNaN(Date.parse(value));\n});\n\n/**\n * JSON parser\n * @module validation/parsers/json\n * @description\n * Advanced JSON parsing with line number tracking and detailed error reporting.\n * Provides enhanced error messages for JSON syntax and validation errors.\n */\n\n/**\n * JSON Document Parser - Handles parsing and validation of JSON report definitions\n */\nexport class JsonDocumentParser {\n private schema = ComponentDefinitionSchema;\n\n constructor() {\n // Schema is assigned above\n }\n\n /**\n * Parse JSON input (string or object) and validate against schema\n * Only supports unified ComponentDefinition structure where document IS a report component\n */\n public parse(jsonInput: string | object): ComponentDefinition {\n let parsedObject: unknown;\n\n // Step 1: Parse JSON if it's a string\n if (typeof jsonInput === 'string') {\n try {\n parsedObject = JSON.parse(jsonInput);\n } catch (error) {\n throw new JsonParsingError(\n 'Invalid JSON syntax',\n this.extractJSONSyntaxError(error as Error, jsonInput)\n );\n }\n } else {\n parsedObject = jsonInput;\n }\n\n // Step 2: Validate it's a report component\n if (\n typeof parsedObject !== 'object' ||\n parsedObject === null ||\n !('name' in parsedObject) ||\n (parsedObject as any).name !== 'docx'\n ) {\n throw new JsonValidationError(\n 'Invalid document structure: Document must be a docx component with name=\"docx\"',\n [\n {\n path: 'name',\n message: 'Document must be a docx component with name=\"docx\"',\n code: 'INVALID_STRUCTURE',\n },\n ]\n );\n }\n\n // Step 3: Validate against schema\n if (!Value.Check(this.schema, parsedObject)) {\n const errors = [...Value.Errors(this.schema, parsedObject)];\n\n throw new JsonValidationError(\n 'JSON validation failed',\n this.formatTypeBoxErrors(\n errors,\n typeof jsonInput === 'string'\n ? jsonInput\n : JSON.stringify(jsonInput, null, 2)\n )\n );\n }\n\n return parsedObject as ComponentDefinition;\n }\n\n /**\n * Validate JSON without throwing errors - returns ValidationResult\n */\n public validate(jsonInput: string | object): DocumentValidationResult {\n try {\n this.parse(jsonInput);\n return {\n valid: true,\n errors: [],\n warnings: [],\n };\n } catch (error) {\n if (\n error instanceof JsonParsingError ||\n error instanceof JsonValidationError\n ) {\n return {\n valid: false,\n errors: error.validationErrors,\n warnings: [],\n };\n }\n\n // Unexpected error\n return {\n valid: false,\n errors: [\n {\n path: '',\n message:\n error instanceof Error\n ? error.message\n : 'Unknown validation error',\n code: 'UNEXPECTED_ERROR',\n },\n ],\n warnings: [],\n };\n }\n }\n\n /**\n * Parse JSON file content with line number tracking\n */\n public parseWithLineNumbers(jsonString: string): ComponentDefinition {\n const lines = jsonString.split('\\n');\n\n try {\n return this.parse(jsonString);\n } catch (error) {\n if (\n error instanceof JsonParsingError ||\n error instanceof JsonValidationError\n ) {\n // Enhance errors with line numbers\n const enhancedErrors = error.validationErrors.map((err) => ({\n ...err,\n ...this.findLineNumber(err.path, jsonString, lines),\n }));\n\n if (error instanceof JsonParsingError) {\n throw new JsonParsingError(error.message, enhancedErrors);\n } else {\n throw new JsonValidationError(error.message, enhancedErrors);\n }\n }\n throw error;\n }\n }\n\n /**\n * Extract JSON syntax error information\n */\n private extractJSONSyntaxError(\n error: Error,\n jsonString: string\n ): ValidationError[] {\n const message = error.message;\n\n // Try to extract position from error message\n const positionMatch =\n message.match(/position\\s+(\\d+)/i) ||\n message.match(/at\\s+(\\d+)/i) ||\n message.match(/character\\s+(\\d+)/i);\n\n let line = 0;\n let column = 0;\n\n if (positionMatch) {\n const position = parseInt(positionMatch[1], 10);\n const lines = jsonString.substring(0, position).split('\\n');\n line = lines.length;\n column = lines[lines.length - 1].length + 1;\n }\n\n return [\n {\n path: '',\n message: `JSON syntax error: ${message}`,\n code: 'JSON_SYNTAX_ERROR',\n line: line || undefined,\n column: column || undefined,\n suggestions: [\n 'Check for missing commas, brackets, or quotes',\n 'Validate JSON syntax using a JSON validator',\n 'Ensure all strings are properly quoted',\n ],\n },\n ];\n }\n\n /**\n * Format TypeBox validation errors into ValidationError format\n */\n private formatTypeBoxErrors(\n errors: ValueError[],\n originalJson: string\n ): ValidationError[] {\n return errors.map((error) => {\n const path = error.path || '';\n const lineInfo = this.findLineNumber(path, originalJson);\n\n return {\n path,\n message: this.formatTypeBoxErrorMessage(error),\n code: this.getErrorCode(error),\n line: lineInfo.line,\n column: lineInfo.column,\n suggestions: this.generateSuggestions(error),\n };\n });\n }\n\n /**\n * Format individual TypeBox error message\n */\n private formatTypeBoxErrorMessage(error: ValueError): string {\n const path = error.path ? `at \"${error.path}\"` : '';\n const message = error.message;\n\n // TypeBox provides descriptive messages, so we can use them directly\n // but enhance common patterns\n if (message.includes('Expected')) {\n return `${message} ${path}`;\n } else if (message.includes('Required property')) {\n return `${message} ${path}`;\n } else if (message.includes('Unexpected property')) {\n return `${message} ${path}`;\n } else if (message.includes('minimum')) {\n return `Value is too small ${path}. ${message}`;\n } else if (message.includes('maximum')) {\n return `Value is too big ${path}. ${message}`;\n } else {\n return `${message} ${path}`;\n }\n }\n\n /**\n * Get error code from TypeBox error\n */\n private getErrorCode(error: ValueError): string {\n const baseCode = String(error.type || 'VALIDATION_ERROR').toUpperCase();\n const path = error.path ? error.path.replace(/\\//g, '_').toUpperCase() : '';\n return path ? `${baseCode}_${path}` : baseCode;\n }\n\n /**\n * Generate helpful suggestions based on error type\n */\n private generateSuggestions(error: ValueError): string[] {\n const suggestions: string[] = [];\n const message = error.message;\n\n // Parse TypeBox error messages to provide suggestions\n if (message.includes('Expected string')) {\n suggestions.push('Ensure the value is wrapped in quotes');\n } else if (message.includes('Expected number')) {\n suggestions.push('Remove quotes around numeric values');\n } else if (message.includes('Expected array')) {\n suggestions.push('Use square brackets [] for arrays');\n } else if (message.includes('Expected object')) {\n suggestions.push('Use curly braces {} for objects');\n } else if (message.includes('Expected literal')) {\n const match = message.match(/Expected literal (.+)/);\n if (match) {\n suggestions.push(`Use the exact value: ${match[1]}`);\n }\n } else if (message.includes('Unexpected property')) {\n suggestions.push('Remove unknown properties or check spelling');\n suggestions.push(\n 'Refer to the JSON schema documentation for valid properties'\n );\n } else if (message.includes('Expected union')) {\n suggestions.push(\n 'Check that the value matches one of the allowed formats'\n );\n // The component registry is itself a union, so a union failure on a node\n // in a `children` array — or on its `name` discriminator — usually is a\n // misspelt component name. Unions elsewhere (spacing, colour, size) are\n // not, and the unconditional hint sent authors hunting for a field their\n // error had nothing to do with.\n const path = error.path ?? '';\n if (/\\/children\\/\\d+$/.test(path) || path.endsWith('/name')) {\n suggestions.push('Verify the component name is spelled correctly');\n }\n } else if (message.includes('minimum')) {\n const match = message.match(/minimum.*?(\\d+)/);\n if (match) {\n if (message.includes('Array')) {\n suggestions.push(`Array must have at least ${match[1]} items`);\n } else {\n suggestions.push(`Value must be at least ${match[1]}`);\n }\n }\n } else if (message.includes('format') && message.includes('uri')) {\n suggestions.push(\n 'Ensure the URL is valid and starts with http:// or https://'\n );\n }\n\n // Generic suggestions\n if (suggestions.length === 0) {\n suggestions.push('Check the JSON schema documentation for valid values');\n suggestions.push('Verify the property name and value format');\n }\n\n return suggestions;\n }\n\n /**\n * Find line and column number for a given JSON path\n */\n private findLineNumber(\n path: string,\n jsonString: string,\n lines?: string[]\n ): { line?: number; column?: number } {\n if (!path) {\n return {};\n }\n\n const jsonLines = lines || jsonString.split('\\n');\n const pathParts = path.split('.');\n\n // Simple heuristic: find the line containing the property name\n for (let i = 0; i < jsonLines.length; i++) {\n const line = jsonLines[i];\n const lastPathPart = pathParts[pathParts.length - 1];\n\n // Look for property name in quotes\n if (line.includes(`\"${lastPathPart}\"`)) {\n const column = line.indexOf(`\"${lastPathPart}\"`) + 1;\n return {\n line: i + 1,\n column,\n };\n }\n }\n\n return {};\n }\n}\n\n/**\n * Custom error classes for better error handling\n */\nexport class JsonParsingError extends Error {\n public readonly validationErrors: ValidationError[];\n\n constructor(message: string, errors: ValidationError[]) {\n super(message);\n this.name = 'JsonParsingError';\n this.validationErrors = errors;\n }\n}\n\nexport class JsonValidationError extends Error {\n public readonly validationErrors: ValidationError[];\n\n constructor(message: string, errors: ValidationError[]) {\n super(message);\n this.name = 'JsonValidationError';\n this.validationErrors = errors;\n }\n}\n\n/**\n * Utility functions for external use\n */\n\n/**\n * Parse and validate JSON component definition\n * Only supports report components (documents)\n */\nexport function parseJsonComponent(\n jsonInput: string | object\n): ComponentDefinition {\n const parser = new JsonDocumentParser();\n return parser.parse(jsonInput);\n}\n\n/**\n * Validate JSON component definition without throwing\n * Now uses unified validation\n */\nexport { validateJsonDocument as validateJsonComponent } from '../unified/document-validator';\n\n/**\n * Parse JSON with enhanced line number error reporting\n * Only supports unified ComponentDefinition structure where document IS a report component\n */\nexport function parseJsonWithLineNumbers(\n jsonString: string\n): ComponentDefinition {\n const parser = new JsonDocumentParser();\n return parser.parseWithLineNumbers(jsonString);\n}\n","/**\n * Theme validators\n * @module validation/validators/theme\n * @description\n * Now uses unified validation system\n */\n\n// Re-export everything from unified theme validator\nexport {\n validateThemeJson,\n isValidTheme as isValidThemeJson,\n getThemeName,\n isThemeConfig,\n type ThemeValidationResult,\n} from '../unified/theme-validator';\n\n// Re-export utility for getting validation summary\nexport { getValidationSummary } from '../unified/base-validator';\n\n// For backward compatibility, provide formatValidationErrors\nexport function formatValidationErrors(errors: any[]): string[] {\n if (!Array.isArray(errors)) return [];\n\n return errors.map((error) => {\n if (typeof error === 'string') return error;\n\n const path = error.path ? `${error.path}: ` : '';\n const message = error.message || 'Validation error';\n return `${path}${message}`;\n });\n}\n","/**\n * Component validators\n * @module validation/validators/component\n * @description\n * Now uses unified validation system\n */\n\nimport {\n validateComponent as unifiedValidateComponent,\n validateComponentDefinition as unifiedValidateComponentDefinition,\n isStandardComponentName,\n} from '../unified/component-validator';\n\n// Re-export everything from unified component validator\nexport {\n validateComponent as validateComponentProps,\n validateComponentDefinition,\n validateComponents,\n validateCustomComponentProps,\n isStandardComponentName,\n // Type guards\n isReportProps,\n isSectionProps,\n isHeadingProps,\n isParagraphProps,\n isColumnsProps,\n isImageProps,\n isStatisticProps,\n isTableProps,\n isListProps,\n isCustomComponentProps,\n type StandardComponentName,\n} from '../unified/component-validator';\n\n// For backward compatibility, provide safeValidateComponentProps\nexport function safeValidateComponentProps<T>(\n name: string,\n props: unknown\n): { success: true; data: T } | { success: false; error: any[] } {\n // For non-standard types, use 'custom'\n const componentName = isStandardComponentName(name) ? name : 'custom';\n const result = unifiedValidateComponent(componentName, props);\n\n if (result.valid) {\n return { success: true, data: result.data as T };\n }\n\n return { success: false, error: result.errors || [] };\n}\n\n// For backward compatibility, provide safeValidateComponentDefinition\nexport function safeValidateComponentDefinition(\n component: unknown\n): { success: true; data: any } | { success: false; error: any[] } {\n const result = unifiedValidateComponentDefinition(component);\n\n if (result.valid) {\n return { success: true, data: result.data };\n }\n\n return { success: false, error: result.errors || [] };\n}\n\n// For backward compatibility, provide error formatting\nexport function getValidationErrors(props: unknown, name?: string): string[] {\n // For non-standard types, use 'custom'\n const componentName = name && isStandardComponentName(name) ? name : 'custom';\n const result = unifiedValidateComponent(componentName, props);\n\n if (result.valid) return [];\n\n return (result.errors || []).map((e: any) =>\n e.path ? `${e.path}: ${e.message}` : e.message\n );\n}\n","import { Value } from '@sinclair/typebox/value';\nimport { Static } from '@sinclair/typebox';\nimport {\n ComponentDefinitionSchema,\n ReportPropsSchema,\n SectionPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ColumnsPropsSchema,\n ImagePropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n} from '../../schemas/components';\nimport { CustomComponentDefinitionSchema } from '../../schemas/custom-components';\nimport {\n formatTypeBoxError,\n formatTypeBoxErrorStrings,\n formatErrorReport,\n hasCriticalErrors,\n} from './errors';\nimport type {\n CoreValidationResult,\n ValidationOptions,\n BatchValidationResult,\n ComponentValidationConfig,\n DataTransformer,\n} from './types';\n\n/**\n * Core validation engine\n * @module validation/core/validator\n * @description\n * Main validation utilities using TypeBox for runtime validation.\n * Provides comprehensive validation with error handling and data transformation.\n */\n\n/**\n * Component name to schema mapping\n */\nconst COMPONENT_SCHEMA_MAP = {\n report: ReportPropsSchema,\n section: SectionPropsSchema,\n heading: HeadingPropsSchema,\n paragraph: ParagraphPropsSchema,\n columns: ColumnsPropsSchema,\n image: ImagePropsSchema,\n statistic: StatisticPropsSchema,\n table: TablePropsSchema,\n list: ListPropsSchema,\n} as const;\n\nexport type StandardComponentName = keyof typeof COMPONENT_SCHEMA_MAP;\n\n/**\n * Validate any component configuration with comprehensive error handling\n */\nexport function validateComponent<T extends StandardComponentName>(\n name: T,\n props: unknown,\n options?: ValidationOptions\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n const schema = COMPONENT_SCHEMA_MAP[name];\n\n if (!schema) {\n // Handle custom components\n if (Value.Check(CustomComponentDefinitionSchema, props)) {\n return {\n success: true,\n data: props as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(CustomComponentDefinitionSchema, props)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n }\n\n // Validate with the schema\n if (Value.Check(schema, props)) {\n return {\n success: true,\n data: props as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(schema, props)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n}\n\n/**\n * Validate a complete component definition (with nested children)\n */\nexport function validateComponentDefinition(\n component: unknown,\n options?: ValidationOptions\n): CoreValidationResult<Static<typeof ComponentDefinitionSchema>> {\n // Check for circular references or excessive nesting\n const maxDepth = options?.maxDepth ?? 10;\n const currentDepth = options?.currentDepth ?? 0;\n\n if (currentDepth > maxDepth) {\n return {\n success: false,\n errors: [\n {\n path: 'children',\n message: `Maximum nesting depth (${maxDepth}) exceeded`,\n code: 'custom',\n suggestion: 'Reduce the nesting level of components',\n },\n ],\n errorStrings: [`Maximum nesting depth (${maxDepth}) exceeded`],\n hasCriticalErrors: true,\n };\n }\n\n if (Value.Check(ComponentDefinitionSchema, component)) {\n // Validate nested children recursively\n const data = component as any;\n const warnings: string[] = [];\n\n if (data.children && Array.isArray(data.children)) {\n for (let i = 0; i < data.children.length; i++) {\n const nestedResult = validateComponentDefinition(data.children[i], {\n ...options,\n currentDepth: currentDepth + 1,\n });\n\n if (!nestedResult.success) {\n // Add context to nested errors\n const nestedErrors = nestedResult.errors?.map((err) => ({\n ...err,\n path: `children[${i}].${err.path}`,\n }));\n\n return {\n success: false,\n errors: nestedErrors,\n errorStrings: nestedErrors?.map(\n (err) => `${err.path}: ${err.message}`\n ),\n report: options?.includeReport\n ? `Validation failed in nested component at index ${i}:\\n${nestedResult.report}`\n : undefined,\n hasCriticalErrors: nestedResult.hasCriticalErrors,\n };\n }\n\n if (nestedResult.warnings) {\n warnings.push(\n ...nestedResult.warnings.map((w) => `children[${i}]: ${w}`)\n );\n }\n }\n }\n\n return {\n success: true,\n data: component as Static<typeof ComponentDefinitionSchema>,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n\n const errors = [...Value.Errors(ComponentDefinitionSchema, component)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n}\n\n/**\n * Batch validate multiple components\n */\nexport function validateComponents(\n components: ComponentValidationConfig[],\n options?: ValidationOptions\n): BatchValidationResult {\n const results: CoreValidationResult<any>[] = [];\n let criticalCount = 0;\n\n for (const { name, props } of components) {\n const result =\n name in COMPONENT_SCHEMA_MAP\n ? validateComponent(name as StandardComponentName, props, options)\n : validateComponentDefinition(props, options);\n\n results.push(result);\n\n if (result.hasCriticalErrors) {\n criticalCount++;\n }\n\n if (!result.success && options?.stopOnFirst) {\n break;\n }\n }\n\n const valid = results.filter((r) => r.success).length;\n const invalid = results.length - valid;\n\n return {\n success: invalid === 0,\n results,\n summary: {\n total: results.length,\n valid,\n invalid,\n criticalErrors: criticalCount,\n },\n };\n}\n\n/**\n * Transform and validate data (for migration scenarios)\n */\nexport function transformAndValidate<T extends StandardComponentName>(\n name: T,\n data: unknown,\n transformer?: DataTransformer\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n try {\n // Apply custom transformation if provided\n const transformed = transformer ? transformer(data) : data;\n\n // Validate the transformed data\n return validateComponent(name, transformed, {\n includeReport: true,\n checkCritical: true,\n });\n } catch (error) {\n return {\n success: false,\n errors: [\n {\n path: 'root',\n message: `Transformation failed: ${error instanceof Error ? error.message : String(error)}`,\n code: 'custom',\n },\n ],\n errorStrings: [\n `Transformation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n hasCriticalErrors: true,\n };\n }\n}\n\n/**\n * Create a validated component with defaults\n */\nexport function createValidatedComponent<T extends StandardComponentName>(\n name: T,\n partialConfig: Partial<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>>\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n const schema = COMPONENT_SCHEMA_MAP[name];\n\n if (!schema) {\n return {\n success: false,\n errors: [\n {\n path: 'name',\n message: `Unknown component name: ${name}`,\n code: 'custom',\n suggestion: `Use one of: ${Object.keys(COMPONENT_SCHEMA_MAP).join(', ')}`,\n },\n ],\n errorStrings: [`Unknown component name: ${name}`],\n hasCriticalErrors: true,\n };\n }\n\n // Validate with TypeBox\n if (Value.Check(schema, partialConfig)) {\n return {\n success: true,\n data: partialConfig as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(schema, partialConfig)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: formatErrorReport(errors),\n hasCriticalErrors: hasCriticalErrors(errors),\n };\n}\n\n/**\n * Type guard functions with proper error context\n */\nexport function isValidComponent<T extends StandardComponentName>(\n name: T,\n props: unknown\n): props is Static<(typeof COMPONENT_SCHEMA_MAP)[T]> {\n const result = validateComponent(name, props);\n return result.success;\n}\n\n/**\n * Validate JSON string input\n */\nexport function validateJsonComponent<T extends StandardComponentName>(\n name: T,\n jsonString: string\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n try {\n const parsed = JSON.parse(jsonString);\n return validateComponent(name, parsed, {\n includeReport: true,\n checkCritical: true,\n });\n } catch (error) {\n return {\n success: false,\n errors: [\n {\n path: 'root',\n message: `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`,\n code: 'custom',\n suggestion: 'Check for syntax errors in your JSON',\n },\n ],\n errorStrings: [\n `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`,\n ],\n hasCriticalErrors: true,\n };\n }\n}\n","import { ValueError } from '@sinclair/typebox/value';\nimport type { FormattedError } from './types';\n\n/**\n * Error formatting utilities\n * @module validation/core/errors\n * @description\n * Enhanced error formatting for TypeBox validation errors.\n * Provides detailed, user-friendly error messages with context and suggestions.\n */\n\n/**\n * Format a single TypeBox error into a user-friendly error message\n */\nfunction formatSingleIssue(issue: ValueError): FormattedError {\n const path = issue.path || 'root';\n let message = issue.message;\n let suggestion: string | undefined;\n let expected: string | undefined;\n let received: string | undefined;\n let options: string[] | undefined;\n\n // Enhance error messages based on error type\n if (message.includes('Expected')) {\n const match = message.match(/Expected (.+) but received (.+)/);\n if (match) {\n expected = match[1];\n received = match[2];\n suggestion = getSuggestionForType(expected, received);\n }\n }\n\n // Handle required property errors\n if (message.includes('Required property')) {\n const match = message.match(/Required property '(.+)'/);\n if (match) {\n message = `Missing required field: ${match[1]}`;\n suggestion = `Add the required field: ${match[1]}`;\n }\n }\n\n // Handle unexpected property errors\n if (message.includes('Unexpected property')) {\n const match = message.match(/Unexpected property '(.+)'/);\n if (match) {\n message = `Unknown property: ${match[1]}`;\n suggestion = `Remove the unknown property: ${match[1]}`;\n }\n }\n\n // Handle union type errors\n if (message.includes('Expected union')) {\n message = 'Value does not match any of the expected types';\n suggestion = 'Check the documentation for valid format options';\n }\n\n // Handle literal value errors\n if (message.includes('Expected literal')) {\n const match = message.match(/Expected literal (.+)/);\n if (match) {\n expected = match[1];\n message = `Expected value: ${expected}`;\n suggestion = `Use the exact value: ${expected}`;\n }\n }\n\n // Handle string length errors\n if (message.includes('String length')) {\n const minMatch = message.match(/minimum length of (\\d+)/);\n const maxMatch = message.match(/maximum length of (\\d+)/);\n if (minMatch) {\n message = `String must be at least ${minMatch[1]} characters long`;\n suggestion = `Add more characters to meet the minimum length of ${minMatch[1]}`;\n } else if (maxMatch) {\n message = `String must be at most ${maxMatch[1]} characters long`;\n suggestion = `Reduce to ${maxMatch[1]} characters or less`;\n }\n }\n\n // Handle number range errors\n if (message.includes('Expected number')) {\n const minMatch = message.match(/minimum value of ([\\d.]+)/);\n const maxMatch = message.match(/maximum value of ([\\d.]+)/);\n if (minMatch) {\n message = `Number must be greater than or equal to ${minMatch[1]}`;\n suggestion = `Use a value of ${minMatch[1]} or higher`;\n } else if (maxMatch) {\n message = `Number must be less than or equal to ${maxMatch[1]}`;\n suggestion = `Use a value of ${maxMatch[1]} or lower`;\n }\n }\n\n // Handle array length errors\n if (message.includes('Array length')) {\n const minMatch = message.match(/minimum length of (\\d+)/);\n const maxMatch = message.match(/maximum length of (\\d+)/);\n if (minMatch) {\n message = `Array must have at least ${minMatch[1]} items`;\n suggestion = `Add more items to meet the minimum of ${minMatch[1]}`;\n } else if (maxMatch) {\n message = `Array must have at most ${maxMatch[1]} items`;\n suggestion = `Remove items to meet the maximum of ${maxMatch[1]}`;\n }\n }\n\n // Handle format errors\n if (message.includes('format')) {\n if (message.includes('email')) {\n message = 'Invalid email address format';\n suggestion = 'Use a valid email format like user@example.com';\n } else if (message.includes('uri') || message.includes('url')) {\n message = 'Invalid URL format';\n suggestion = 'Use a valid URL format like https://example.com';\n } else if (message.includes('date-time')) {\n message = 'Invalid date-time format';\n suggestion = 'Use ISO 8601 format like 2024-01-01T00:00:00Z';\n }\n }\n\n // Handle pattern errors\n if (message.includes('pattern')) {\n message = 'String does not match the required pattern';\n suggestion = 'Check the format requirements for this field';\n }\n\n return {\n path,\n message,\n code: String(issue.type || 'validation_error'),\n suggestion,\n expected,\n received,\n options,\n };\n}\n\n/**\n * Get type-specific suggestions for common type mismatches\n */\nfunction getSuggestionForType(\n expected: string,\n received: string\n): string | undefined {\n // Number/String confusion\n if (expected === 'number' && received === 'string') {\n return 'Remove quotes or convert the string to a number';\n }\n if (expected === 'string' && received === 'number') {\n return 'Add quotes or convert the number to a string';\n }\n\n // Boolean confusion\n if (expected === 'boolean') {\n return 'Use true or false (without quotes)';\n }\n\n // Array/Object confusion\n if (expected === 'array' && received === 'object') {\n return 'Use square brackets [] for arrays instead of curly braces {}';\n }\n if (expected === 'object' && received === 'array') {\n return 'Use curly braces {} for objects instead of square brackets []';\n }\n\n // Null/undefined handling\n if (received === 'null' || received === 'undefined') {\n return `Provide a valid ${expected} value or mark the field as optional`;\n }\n\n return undefined;\n}\n\n/**\n * Format TypeBox validation errors into detailed, user-friendly messages\n */\nexport function formatTypeBoxError(errors: ValueError[]): FormattedError[] {\n return errors.map(formatSingleIssue);\n}\n\n/**\n * Format errors as simple string array (backward compatible)\n */\nexport function formatTypeBoxErrorStrings(errors: ValueError[]): string[] {\n return formatTypeBoxError(errors).map((err) => {\n let msg = `${err.path}: ${err.message}`;\n if (err.suggestion) {\n msg += ` (Suggestion: ${err.suggestion})`;\n }\n return msg;\n });\n}\n\n/**\n * Get a summary of validation errors grouped by path\n */\nexport function getErrorSummary(\n errors: ValueError[]\n): Map<string, FormattedError[]> {\n const summary = new Map<string, FormattedError[]>();\n\n for (const formattedError of formatTypeBoxError(errors)) {\n const existing = summary.get(formattedError.path) || [];\n existing.push(formattedError);\n summary.set(formattedError.path, existing);\n }\n\n return summary;\n}\n\n/**\n * Format validation errors as a detailed report\n */\nexport function formatErrorReport(errors: ValueError[]): string {\n const formattedErrors = formatTypeBoxError(errors);\n const summary = getErrorSummary(errors);\n\n let report = `Validation failed with ${formattedErrors.length} error${formattedErrors.length > 1 ? 's' : ''}:\\n\\n`;\n\n for (const [path, pathErrors] of summary) {\n report += `📍 ${path}:\\n`;\n for (const err of pathErrors) {\n report += ` ❌ ${err.message}\\n`;\n if (err.suggestion) {\n report += ` 💡 ${err.suggestion}\\n`;\n }\n if (err.expected && err.received) {\n report += ` 📋 Expected: ${err.expected}, Received: ${err.received}\\n`;\n }\n if (err.options) {\n report += ` 📋 Valid options: ${err.options.join(', ')}\\n`;\n }\n }\n report += '\\n';\n }\n\n return report;\n}\n\n/**\n * Check if an error is critical (affects core functionality)\n */\nexport function hasCriticalErrors(errors: ValueError[]): boolean {\n return errors.some((issue) => {\n // Missing required fields are critical\n if (issue.message.includes('Required property')) {\n return true;\n }\n\n // Invalid component names are critical\n if (\n issue.path.includes('name') &&\n issue.message.includes('Expected literal')\n ) {\n return true;\n }\n\n // Schema structure errors are critical\n if (\n issue.message.includes('Expected union') ||\n issue.message.includes('Never')\n ) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Get validation context for better error messages\n */\nexport function getValidationContext(path: string): string {\n if (!path || path === 'root') return 'document root';\n\n const pathParts = path.split('.');\n\n // Identify component context\n if (pathParts.includes('children')) {\n const childIndex = pathParts.indexOf('children');\n if (pathParts.length > childIndex + 1) {\n const index = pathParts[childIndex + 1];\n return `component at index ${index}`;\n }\n }\n\n // Identify props context\n if (pathParts.includes('props')) {\n return 'props section';\n }\n\n // Identify theme context\n if (pathParts.includes('theme')) {\n return 'theme configuration';\n }\n\n return pathParts.join(' > ');\n}\n\n// ============================================================================\n// Legacy Compatibility Exports (for API backward compatibility)\n// ============================================================================\n\n// Primary exports - use formatTypeBoxError and formatTypeBoxErrorStrings directly\nexport const formatValidationError = formatTypeBoxError;\nexport const formatValidationErrorStrings = formatTypeBoxErrorStrings;\n","/**\n * Component Type Definitions for Plugin System\n *\n * This file provides properly typed discriminated union interfaces for all component types.\n * These types enable TypeScript to automatically infer component props based on\n * the 'name' field when building component arrays in render functions.\n */\n\nimport type { Static } from '@sinclair/typebox';\nimport type {\n ReportPropsSchema,\n SectionPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ColumnsPropsSchema,\n ImagePropsSchema,\n HighchartsPropsSchema,\n VisualPropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n TocPropsSchema,\n} from '../schemas/components';\n\nimport type { TextSpaceAfterPropsSchema } from '../schemas/custom-components';\nimport type { TextBoxPropsSchema } from '../schemas/components/text-box';\nimport type { DocxRendererId } from '../schemas/renderer';\n\n// ============================================================================\n// Standard Component Types with Discriminated Union Support\n// ============================================================================\n\n/**\n * Report component with literal name discriminator\n */\nexport interface ReportComponent {\n name: 'docx';\n id?: string;\n /** Renderer backend. Omitted defaults to docxjs. */\n renderer?: DocxRendererId;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ReportPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/** A document explicitly targeted at one renderer profile. */\nexport type ReportComponentFor<R extends DocxRendererId> = Omit<\n ReportComponent,\n 'renderer'\n> &\n (R extends 'docxjs' ? { renderer?: R } : { renderer: R });\n\n/**\n * Section component with literal name discriminator\n */\nexport interface SectionComponent {\n name: 'section';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof SectionPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * Columns component with literal name discriminator\n */\nexport interface ColumnsComponent {\n name: 'columns';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ColumnsPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * Heading component with literal name discriminator\n */\nexport interface HeadingComponent {\n name: 'heading';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof HeadingPropsSchema>;\n}\n\n/**\n * Paragraph component with literal name discriminator\n */\nexport interface ParagraphComponent {\n name: 'paragraph';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ParagraphPropsSchema>;\n}\n\n/**\n * Image component with literal name discriminator\n */\nexport interface ImageComponent {\n name: 'image';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ImagePropsSchema>;\n}\n\n/**\n * Statistic component with literal name discriminator\n */\nexport interface StatisticComponent {\n name: 'statistic';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof StatisticPropsSchema>;\n}\n\n/**\n * Table component with literal name discriminator\n */\nexport interface TableComponent {\n name: 'table';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TablePropsSchema>;\n}\n\n/**\n * Highcharts component with literal name discriminator\n */\nexport interface HighchartsComponent {\n name: 'highcharts';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof HighchartsPropsSchema>;\n}\n\n/**\n * Visual component with literal name discriminator.\n * A pptx-rendered free-canvas graphic embedded as a rasterized image.\n */\nexport interface VisualComponent {\n name: 'visual';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof VisualPropsSchema>;\n}\n\n/**\n * Text Box component with literal name discriminator\n * Container for child components with floating positioning\n */\nexport interface TextBoxComponent {\n name: 'text-box';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TextBoxPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * List component with literal name discriminator\n */\nexport interface ListComponent {\n name: 'list';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ListPropsSchema>;\n}\n\n/**\n * Table of Contents component with literal name discriminator\n */\nexport interface TocComponent {\n name: 'toc';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TocPropsSchema>;\n}\n\n// ============================================================================\n// Specific Custom Component Types\n// ============================================================================\n\n/**\n * Text Space After component with literal name discriminator\n */\nexport interface TextSpaceAfterComponent {\n name: 'text-space-after';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TextSpaceAfterPropsSchema>;\n}\n\n// ============================================================================\n// Discriminated Union Types\n// ============================================================================\n\n/**\n * Union of all standard component types\n */\nexport type StandardComponentDefinition =\n | ReportComponent\n | SectionComponent\n | ColumnsComponent\n | HeadingComponent\n | ParagraphComponent\n | TextBoxComponent\n | ImageComponent\n | HighchartsComponent\n | VisualComponent\n | StatisticComponent\n | TableComponent\n | ListComponent\n | TocComponent;\n\n/**\n * Array of all standard component names.\n * Useful for iterating, validation, or displaying available components to users.\n */\nexport const STANDARD_COMPONENTS = [\n 'columns',\n 'heading',\n 'highcharts',\n 'image',\n 'list',\n 'paragraph',\n 'docx',\n 'section',\n 'statistic',\n 'table',\n 'text-box',\n 'toc',\n 'visual',\n] as const satisfies readonly StandardComponentDefinition['name'][];\n\n/**\n * Set of all standard component names for O(1) lookup.\n */\nexport const STANDARD_COMPONENTS_SET: ReadonlySet<\n (typeof STANDARD_COMPONENTS)[number]\n> = new Set(STANDARD_COMPONENTS);\n\n// Compile-time completeness check: produces TS2344 listing the missing name(s)\n// if a standard component is added to the union but not to the array above.\ntype AssertNever<T extends never> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype _AssertAllIncluded = AssertNever<\n Exclude<\n StandardComponentDefinition['name'],\n (typeof STANDARD_COMPONENTS)[number]\n >\n>;\n\n/**\n * Complete discriminated union of all component types.\n * TypeScript will automatically narrow the type based on the 'name' field.\n *\n * @example\n * ```typescript\n * const components: ComponentDefinition[] = [\n * {\n * name: 'heading', // TypeScript knows this is HeadingComponent\n * props: {\n * level: 2, // Autocomplete works!\n * text: 'Title'\n * }\n * },\n * {\n * name: 'paragraph', // TypeScript knows this is ParagraphComponent\n * props: {\n * content: 'Hello World',\n * bold: true // Autocomplete works!\n * }\n * }\n * ];\n * ```\n */\nexport type ComponentDefinition =\n | StandardComponentDefinition\n | TextSpaceAfterComponent;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport function isReportComponent(\n component: ComponentDefinition\n): component is ReportComponent {\n return component.name === 'docx';\n}\n\nexport function isSectionComponent(\n component: ComponentDefinition\n): component is SectionComponent {\n return component.name === 'section';\n}\n\nexport function isColumnsComponent(\n component: ComponentDefinition\n): component is ColumnsComponent {\n return component.name === 'columns';\n}\n\nexport function isHeadingComponent(\n component: ComponentDefinition\n): component is HeadingComponent {\n return component.name === 'heading';\n}\n\nexport function isParagraphComponent(\n component: ComponentDefinition\n): component is ParagraphComponent {\n return component.name === 'paragraph';\n}\n\nexport function isImageComponent(\n component: ComponentDefinition\n): component is ImageComponent {\n return component.name === 'image';\n}\n\nexport function isTextBoxComponent(\n component: ComponentDefinition\n): component is TextBoxComponent {\n return component.name === 'text-box';\n}\n\nexport function isStatisticComponent(\n component: ComponentDefinition\n): component is StatisticComponent {\n return component.name === 'statistic';\n}\n\nexport function isTableComponent(\n component: ComponentDefinition\n): component is TableComponent {\n return component.name === 'table';\n}\n\nexport function isListComponent(\n component: ComponentDefinition\n): component is ListComponent {\n return component.name === 'list';\n}\n\nexport function isTocComponent(\n component: ComponentDefinition\n): component is TocComponent {\n return component.name === 'toc';\n}\n\nexport function isHighchartsComponent(\n component: ComponentDefinition\n): component is HighchartsComponent {\n return component.name === 'highcharts';\n}\n\nexport function isVisualComponent(\n component: ComponentDefinition\n): component is VisualComponent {\n return component.name === 'visual';\n}\n\nexport function isTextSpaceAfterComponent(\n component: ComponentDefinition\n): component is TextSpaceAfterComponent {\n return component.name === 'text-space-after';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,gBAAgB;AAGf,SAAS,cAA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B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,qBACd,WACiC;AACjC,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,iBACd,WAC6B;AAC7B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,gBACd,WAC4B;AAC5B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,eACd,WAC2B;AAC3B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,sBACd,WACkC;AAClC,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,kBACd,WAC8B;AAC9B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,0BACd,WACsC;AACtC,SAAO,UAAU,SAAS;AAC5B;;;AN1XO,IAAM,sBAAsB;","names":["k","i","j","i","j","fixSchemaReferences","convertToJsonSchema","createComponentSchema","exportSchemaToFile","transformValueError","transformValueErrors","Value","validateComponent","Value","errors","formattedErrors","validateComponentDefinition","validateComponents"]}
|
|
1
|
+
{"version":3,"sources":["../src/diff/word-diff.ts","../src/diff/document-diff.ts","../src/index.ts","../src/validation/parsers/json.ts","../src/validation/validators/theme.ts","../src/validation/validators/component.ts","../src/validation/core/validator.ts","../src/validation/core/errors.ts","../src/types/components.ts"],"sourcesContent":["/**\n * Word-level text diff\n *\n * Tokenizes text into words and whitespace, runs an LCS diff over the\n * tokens, and emits revision segments. Pure, dependency-free.\n */\n\nimport type { RevisionSegment } from '../schemas/components/revision';\n\n/**\n * Anchored to the schema type so the diff engine can never emit segments\n * the RevisionSchema would reject.\n */\nexport type DiffSegment = RevisionSegment;\n\n/**\n * Above this many DP cells the LCS table is not worth building: fall back\n * to a whole-text replace. ~1000x1000 tokens covers any realistic paragraph.\n */\nconst MAX_LCS_CELLS = 1_000_000;\n\n/** Split into alternating word / whitespace tokens (both preserved). */\nexport function tokenizeWords(text: string): string[] {\n if (!text) return [];\n return text.split(/(\\s+)/).filter((t) => t.length > 0);\n}\n\nfunction mergeSegments(segments: DiffSegment[]): DiffSegment[] {\n const merged: DiffSegment[] = [];\n for (const seg of segments) {\n if (!seg.text) continue;\n const last = merged[merged.length - 1];\n if (last && last.type === seg.type) {\n last.text += seg.text;\n } else {\n merged.push({ ...seg });\n }\n }\n return merged;\n}\n\n/**\n * Readability pass over the raw LCS output:\n * 1. A whitespace-only equal segment flanked by changes joins the change\n * (the space is both deleted and re-inserted), so \"x y\" -> \"a b\" reads\n * as one replacement instead of three fragments.\n * 2. Within each change run, deletions are emitted before insertions.\n * The old/new reconstruction invariant is preserved.\n */\nfunction normalizeSegments(segments: DiffSegment[]): DiffSegment[] {\n const folded: DiffSegment[] = [];\n for (let k = 0; k < segments.length; k++) {\n const seg = segments[k];\n if (seg.type === 'equal' && /^\\s+$/.test(seg.text)) {\n const prev = folded[folded.length - 1];\n const next = segments[k + 1];\n if (prev && prev.type !== 'equal' && next && next.type !== 'equal') {\n folded.push(\n { type: 'delete', text: seg.text },\n { type: 'insert', text: seg.text }\n );\n continue;\n }\n }\n folded.push({ ...seg });\n }\n\n const out: DiffSegment[] = [];\n let k = 0;\n while (k < folded.length) {\n if (folded[k].type === 'equal') {\n out.push(folded[k]);\n k++;\n continue;\n }\n let deleted = '';\n let inserted = '';\n while (k < folded.length && folded[k].type !== 'equal') {\n if (folded[k].type === 'delete') deleted += folded[k].text;\n else inserted += folded[k].text;\n k++;\n }\n if (deleted) out.push({ type: 'delete', text: deleted });\n if (inserted) out.push({ type: 'insert', text: inserted });\n }\n return mergeSegments(out);\n}\n\n/**\n * Word-level diff between two strings.\n *\n * Returns merged segments in document order. Deleting everything and\n * inserting everything (whole replace) is the degenerate output for\n * completely different texts or oversized inputs.\n */\nexport function diffWords(oldText: string, newText: string): DiffSegment[] {\n if (oldText === newText) {\n return oldText ? [{ type: 'equal', text: oldText }] : [];\n }\n\n const oldTokens = tokenizeWords(oldText);\n const newTokens = tokenizeWords(newText);\n\n if (oldTokens.length === 0) {\n return mergeSegments([{ type: 'insert', text: newText }]);\n }\n if (newTokens.length === 0) {\n return mergeSegments([{ type: 'delete', text: oldText }]);\n }\n\n if (oldTokens.length * newTokens.length > MAX_LCS_CELLS) {\n return mergeSegments([\n { type: 'delete', text: oldText },\n { type: 'insert', text: newText },\n ]);\n }\n\n // Standard LCS dynamic programming table\n const n = oldTokens.length;\n const m = newTokens.length;\n // lcs[i][j] = LCS length of oldTokens[i..] and newTokens[j..]\n const lcs: Int32Array[] = Array.from(\n { length: n + 1 },\n () => new Int32Array(m + 1)\n );\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i][j] =\n oldTokens[i] === newTokens[j]\n ? lcs[i + 1][j + 1] + 1\n : Math.max(lcs[i + 1][j], lcs[i][j + 1]);\n }\n }\n\n // Backtrack\n const segments: DiffSegment[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (oldTokens[i] === newTokens[j]) {\n segments.push({ type: 'equal', text: oldTokens[i] });\n i++;\n j++;\n } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {\n segments.push({ type: 'delete', text: oldTokens[i] });\n i++;\n } else {\n segments.push({ type: 'insert', text: newTokens[j] });\n j++;\n }\n }\n while (i < n) {\n segments.push({ type: 'delete', text: oldTokens[i] });\n i++;\n }\n while (j < m) {\n segments.push({ type: 'insert', text: newTokens[j] });\n j++;\n }\n\n return normalizeSegments(segments);\n}\n\n/**\n * Strip the inline markdown the renderer understands (bold/italic markers,\n * hyperlinks) so revision segments — which render literally — never expose\n * raw markers. Uses the exact decorator regex of textParser.ts (lazy\n * [\\s\\S]*? content), so what the parser would style, this strips — including\n * content containing '*' or '_' (e.g. **snake_case**).\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '$1') // [text](url) -> text\n .replace(\n /(\\*\\*\\*|___)([\\s\\S]*?)\\1|(\\*\\*|__)([\\s\\S]*?)\\3|(\\*|_)([\\s\\S]*?)\\5/g,\n (_match, _d1, bi, _d2, b, _d3, i) => bi ?? b ?? i ?? ''\n );\n}\n","/**\n * Document diff engine\n *\n * Compares two json-to-office DOCX definitions and produces a redline\n * document: a third definition (based on the new one) where text changes\n * are expressed as `revision` segments that the renderer turns into native\n * Word tracked changes (w:ins / w:del).\n *\n * Scope (v1):\n * - paragraph / heading: word-level tracked changes\n * - list: item-level alignment, word-level tracked changes per item\n * - containers (section, columns, text-box, ...): recursed into\n * - everything else (table, image, chart, ...): block replace, reported\n * as an *untracked* change in the summary — Word has no native revision\n * for these at the fidelity docx.js supports.\n */\n\nimport { diffWords, stripMarkdown, type DiffSegment } from './word-diff';\n\n/** Structural view of any component node — schemas validate elsewhere. */\nexport interface JsonNode {\n name: string;\n props?: Record<string, unknown>;\n children?: JsonNode[];\n [key: string]: unknown;\n}\n\nexport interface DiffDocumentsOptions {\n /** Revision author shown in Word (default: \"json-to-office\") */\n author?: string;\n /** Revision timestamp, ISO 8601 (default: deterministic epoch) */\n date?: string;\n}\n\nexport interface UntrackedChange {\n /** JSON-pointer-ish location in the NEW document */\n path: string;\n kind: 'modified' | 'inserted' | 'deleted';\n component: string;\n detail: string;\n}\n\nexport interface DiffSummary {\n /** Blocks rendered with native tracked changes */\n tracked: {\n modified: number;\n inserted: number;\n deleted: number;\n };\n /** Changes the redline cannot express as native revisions */\n untracked: UntrackedChange[];\n unchangedBlocks: number;\n /** Aggregate fidelity caveats about the redline */\n notes: string[];\n}\n\nexport interface DiffDocumentsResult {\n /** Redline document definition (renderable as-is) */\n document: JsonNode;\n summary: DiffSummary;\n}\n\nconst TEXT_COMPONENTS = new Set(['paragraph', 'heading']);\n\ntype ListItem = string | { text: string; level?: number };\n\ninterface NormalizedListItem {\n /** Original item text (markdown intact) — emitted for unchanged items */\n raw: string;\n /** NFC-normalized, markdown-stripped text — used for alignment and diffing */\n text: string;\n level: number;\n}\n\ninterface DiffContext {\n author?: string;\n date?: string;\n summary: DiffSummary;\n}\n\n// Key-order sensitive: props objects with the same entries in a different\n// order compare unequal. Acceptable — inputs are machine-generated and a\n// false \"changed\" only adds a spurious untracked summary entry.\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction makeRevision(ctx: DiffContext, segments: DiffSegment[]) {\n return {\n ...(ctx.author && { author: ctx.author }),\n ...(ctx.date && { date: ctx.date }),\n segments,\n };\n}\n\n/** Raw text prop, NFC-normalized (matching the renderer's normalization). */\nfunction rawText(node: JsonNode): string {\n const text = node.props?.text;\n return typeof text === 'string' ? text.normalize('NFC') : '';\n}\n\n/** Text of a text component as it renders: NFC-normalized, markdown stripped. */\nfunction plainText(node: JsonNode): string {\n return stripMarkdown(rawText(node));\n}\n\nconst PLACEHOLDER_PATTERN = /\\{[^}]+\\}/;\n\n/** A node is rendered unless it explicitly opts out with enabled: false. */\nfunction isEnabled(node: JsonNode): boolean {\n return node.enabled !== false;\n}\n\nfunction notePlaceholdersInChanges(\n segments: DiffSegment[],\n path: string,\n component: string,\n ctx: DiffContext\n): void {\n if (\n segments.some((s) => s.type !== 'equal' && PLACEHOLDER_PATTERN.test(s.text))\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component,\n detail:\n 'placeholder (e.g. {DATE}) inside inserted/deleted text renders literally in the redline',\n });\n }\n}\n\nfunction propsWithout(\n props: Record<string, unknown> | undefined,\n ...keys: string[]\n): Record<string, unknown> {\n const copy = { ...(props || {}) };\n for (const key of keys) delete copy[key];\n return copy;\n}\n\n// ---------------------------------------------------------------------------\n// Generic LCS alignment over arrays\n// ---------------------------------------------------------------------------\n\ntype AlignOp<T> =\n | { op: 'equal'; oldItem: T; newItem: T }\n | { op: 'delete'; oldItem: T }\n | { op: 'insert'; newItem: T };\n\n/**\n * Above this many DP cells the LCS table is not worth its memory (an\n * Int32Array table lives off the V8 heap). Typical edits touch few blocks,\n * so the prefix/suffix trim below makes the table tiny in practice.\n */\nconst MAX_ALIGN_CELLS = 4_000_000;\n\n/** LCS alignment of two arrays under a stable key function. */\nfunction alignByLcs<T>(\n oldItems: T[],\n newItems: T[],\n key: (item: T) => string\n): AlignOp<T>[] {\n const oldKeys = oldItems.map(key);\n const newKeys = newItems.map(key);\n\n // Trim the common prefix and suffix — emitted as equal ops directly\n let start = 0;\n while (\n start < oldItems.length &&\n start < newItems.length &&\n oldKeys[start] === newKeys[start]\n ) {\n start++;\n }\n let oldEnd = oldItems.length;\n let newEnd = newItems.length;\n while (\n oldEnd > start &&\n newEnd > start &&\n oldKeys[oldEnd - 1] === newKeys[newEnd - 1]\n ) {\n oldEnd--;\n newEnd--;\n }\n\n const prefix: AlignOp<T>[] = [];\n for (let k = 0; k < start; k++) {\n prefix.push({ op: 'equal', oldItem: oldItems[k], newItem: newItems[k] });\n }\n const suffix: AlignOp<T>[] = [];\n for (let k = 0; k < oldItems.length - oldEnd; k++) {\n suffix.push({\n op: 'equal',\n oldItem: oldItems[oldEnd + k],\n newItem: newItems[newEnd + k],\n });\n }\n\n const n = oldEnd - start;\n const m = newEnd - start;\n const middle: AlignOp<T>[] = [];\n\n if (n * m > MAX_ALIGN_CELLS) {\n // Degenerate fallback: replace the whole middle\n for (let k = 0; k < n; k++) {\n middle.push({ op: 'delete', oldItem: oldItems[start + k] });\n }\n for (let k = 0; k < m; k++) {\n middle.push({ op: 'insert', newItem: newItems[start + k] });\n }\n return [...prefix, ...middle, ...suffix];\n }\n\n const lcs: Int32Array[] = Array.from(\n { length: n + 1 },\n () => new Int32Array(m + 1)\n );\n for (let i = n - 1; i >= 0; i--) {\n for (let j = m - 1; j >= 0; j--) {\n lcs[i][j] =\n oldKeys[start + i] === newKeys[start + j]\n ? lcs[i + 1][j + 1] + 1\n : Math.max(lcs[i + 1][j], lcs[i][j + 1]);\n }\n }\n\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (oldKeys[start + i] === newKeys[start + j]) {\n middle.push({\n op: 'equal',\n oldItem: oldItems[start + i],\n newItem: newItems[start + j],\n });\n i++;\n j++;\n } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {\n middle.push({ op: 'delete', oldItem: oldItems[start + i] });\n i++;\n } else {\n middle.push({ op: 'insert', newItem: newItems[start + j] });\n j++;\n }\n }\n while (i < n) middle.push({ op: 'delete', oldItem: oldItems[start + i++] });\n while (j < m) middle.push({ op: 'insert', newItem: newItems[start + j++] });\n\n return [...prefix, ...middle, ...suffix];\n}\n\n/**\n * Within a run of deletes+inserts between two equal anchors, pair removed\n * and added nodes that share the same component name (\"modified\" instead of\n * \"deleted + inserted\"). Pairing is greedy and order-preserving.\n */\ninterface GapPairing<T> {\n pairs: { oldItem: T; newItem: T }[];\n /** Emission plan preserving relative order */\n plan: (\n | { kind: 'deleted'; oldItem: T }\n | { kind: 'inserted'; newItem: T }\n | { kind: 'paired'; oldItem: T; newItem: T }\n )[];\n}\n\nfunction pairGap<T>(\n deleted: T[],\n inserted: T[],\n pairable: (oldItem: T, newItem: T) => boolean\n): GapPairing<T> {\n const usedOld = new Array<boolean>(deleted.length).fill(false);\n const pairing = new Array<number>(inserted.length).fill(-1);\n\n let searchFrom = 0;\n for (let j = 0; j < inserted.length; j++) {\n for (let i = searchFrom; i < deleted.length; i++) {\n if (!usedOld[i] && pairable(deleted[i], inserted[j])) {\n usedOld[i] = true;\n pairing[j] = i;\n searchFrom = i + 1; // keep pairs order-preserving\n break;\n }\n }\n }\n\n const plan: GapPairing<T>['plan'] = [];\n const pairs: GapPairing<T>['pairs'] = [];\n let emittedOld = 0;\n for (let j = 0; j < inserted.length; j++) {\n const i = pairing[j];\n if (i >= 0) {\n // Old nodes before this pair that were never matched: emit as deleted\n while (emittedOld < i) {\n if (!usedOld[emittedOld]) {\n plan.push({ kind: 'deleted', oldItem: deleted[emittedOld] });\n }\n emittedOld++;\n }\n emittedOld = i + 1;\n plan.push({ kind: 'paired', oldItem: deleted[i], newItem: inserted[j] });\n pairs.push({ oldItem: deleted[i], newItem: inserted[j] });\n } else {\n plan.push({ kind: 'inserted', newItem: inserted[j] });\n }\n }\n for (let i = emittedOld; i < deleted.length; i++) {\n if (!usedOld[i]) plan.push({ kind: 'deleted', oldItem: deleted[i] });\n }\n return { pairs, plan };\n}\n\n// ---------------------------------------------------------------------------\n// Component-level diff\n// ---------------------------------------------------------------------------\n\n/** Modified text component → new node carrying revision segments. */\nfunction diffTextComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const oldText = plainText(oldNode);\n const newText = plainText(newNode);\n\n // `comment` joins `revision` here: both are review metadata rather than\n // formatting, so a changed comment must not be reported as an untracked\n // formatting change.\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'text', 'revision', 'comment'),\n propsWithout(newNode.props, 'text', 'revision', 'comment')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'formatting/props changed (not expressible as a tracked change); new version rendered',\n });\n }\n\n if (oldText === newText) {\n // Same rendered text, but markdown-only differences (bold markers,\n // hyperlink targets) are invisible after stripping — surface them.\n if (rawText(oldNode) !== rawText(newNode)) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'inline formatting or link target changed (markdown-only); new version rendered without a tracked change',\n });\n } else if (!propsChanged) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n ctx.summary.tracked.modified++;\n const segments = diffWords(oldText, newText);\n notePlaceholdersInChanges(segments, path, newNode.name, ctx);\n // Revision segments render literally, so markdown anywhere in a modified\n // block — including its unchanged portions — is flattened to plain text\n if (rawText(oldNode) !== oldText || rawText(newNode) !== newText) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail:\n 'inline formatting or links flattened to plain text in the redline (revision segments render literally)',\n });\n }\n return {\n ...newNode,\n props: {\n ...revisedTextProps(newNode, path, ctx),\n text: newText,\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\n/**\n * Props for a paragraph the redline marks as a tracked change.\n *\n * `footnotes`/`endnotes` cannot ride along: revision segments render literally,\n * so a `[^id]` marker inside them never resolves — and the renderer rejects the\n * pair outright, so emitting both would produce a redline that cannot be\n * rendered at all. Drop them and say so, the same way the differ reports every\n * other change Word cannot express.\n */\nfunction revisedTextProps(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): Record<string, unknown> {\n const props = { ...(node.props ?? {}) };\n const dropped = (['footnotes', 'endnotes'] as const).filter((kind) => {\n const notes = props[kind];\n return Array.isArray(notes) && notes.length > 0;\n });\n\n if (dropped.length === 0) return props;\n\n for (const kind of dropped) delete props[kind];\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: node.name,\n detail: `${dropped.join(' and ')} dropped from a tracked-change paragraph (note markers do not resolve inside revision text); the note bodies are not in the redline`,\n });\n return props;\n}\n\n/** Whole text component inserted/deleted → fully tracked block. */\nfunction insertedTextComponent(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n ctx.summary.tracked.inserted++;\n const text = plainText(node);\n const segments: DiffSegment[] = [{ type: 'insert', text }];\n notePlaceholdersInChanges(segments, path, node.name, ctx);\n return {\n ...node,\n props: {\n ...revisedTextProps(node, path, ctx),\n text,\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\nfunction deletedTextComponent(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n ctx.summary.tracked.deleted++;\n const text = plainText(node);\n const segments: DiffSegment[] = [{ type: 'delete', text }];\n notePlaceholdersInChanges(segments, path, node.name, ctx);\n return {\n ...node,\n props: {\n ...revisedTextProps(node, path, ctx),\n text: '',\n revision: makeRevision(ctx, segments),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// List diff\n// ---------------------------------------------------------------------------\n\nfunction normalizeListItems(node: JsonNode): NormalizedListItem[] {\n const items = (node.props?.items as ListItem[] | undefined) || [];\n return items.map((item) => {\n const raw = typeof item === 'string' ? item : item.text;\n const level = typeof item === 'string' ? 0 : item.level || 0;\n return { raw, text: stripMarkdown(raw.normalize('NFC')), level };\n });\n}\n\nfunction diffListComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'items'),\n propsWithout(newNode.props, 'items')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'list',\n detail:\n 'list configuration changed (format/levels/spacing); new version rendered',\n });\n }\n\n const oldItems = normalizeListItems(oldNode);\n const newItems = normalizeListItems(newNode);\n\n const stripped = (items: NormalizedListItem[]) =>\n items.map((i) => ({ text: i.text, level: i.level }));\n if (deepEqual(stripped(oldItems), stripped(newItems))) {\n if (\n !deepEqual(\n oldItems.map((i) => i.raw),\n newItems.map((i) => i.raw)\n )\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'list',\n detail:\n 'inline formatting or link target changed in list items (markdown-only); new version rendered without a tracked change',\n });\n } else if (!propsChanged) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n const ops = alignByLcs(\n oldItems,\n newItems,\n (item) => `${item.level}:${item.text}`\n );\n\n // Collapse delete/insert runs into modified pairs (same level)\n const outItems: Array<{\n text: string;\n level?: number;\n revision?: ReturnType<typeof makeRevision>;\n }> = [];\n let changed = false;\n\n let k = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n // Unchanged item: keep the raw text so markdown/hyperlinks survive\n outItems.push({ text: op.newItem.raw, level: op.newItem.level });\n k++;\n continue;\n }\n // Collect the full delete/insert run\n const deleted: NormalizedListItem[] = [];\n const inserted: NormalizedListItem[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n const { plan } = pairGap(\n deleted,\n inserted,\n (oldItem, newItem) => oldItem.level === newItem.level\n );\n for (const step of plan) {\n changed = true;\n if (step.kind === 'paired') {\n const segments = diffWords(step.oldItem.text, step.newItem.text);\n notePlaceholdersInChanges(segments, path, 'list', ctx);\n outItems.push({\n text: step.newItem.text,\n level: step.newItem.level,\n revision: makeRevision(ctx, segments),\n });\n } else if (step.kind === 'inserted') {\n outItems.push({\n text: step.newItem.text,\n level: step.newItem.level,\n revision: makeRevision(ctx, [\n { type: 'insert', text: step.newItem.text },\n ]),\n });\n } else {\n outItems.push({\n text: '',\n level: step.oldItem.level,\n revision: makeRevision(ctx, [\n { type: 'delete', text: step.oldItem.text },\n ]),\n });\n }\n }\n }\n\n if (changed) ctx.summary.tracked.modified++;\n return {\n ...newNode,\n props: { ...newNode.props, items: outItems },\n };\n}\n\nfunction listWithAllItems(\n node: JsonNode,\n type: 'insert' | 'delete',\n ctx: DiffContext\n): JsonNode {\n if (type === 'insert') ctx.summary.tracked.inserted++;\n else ctx.summary.tracked.deleted++;\n const items = normalizeListItems(node).map((item) => ({\n text: type === 'insert' ? item.text : '',\n level: item.level,\n revision: makeRevision(ctx, [{ type, text: item.text }]),\n }));\n return { ...node, props: { ...node.props, items } };\n}\n\n// ---------------------------------------------------------------------------\n// Table diff\n// ---------------------------------------------------------------------------\n\n/** A table cell as authored: anything but `content` is styling we carry over. */\ntype TableCell = Record<string, unknown> & { content?: unknown };\n\n/** One row's cells, in column order, plus the alignment key. */\ninterface TableRowView {\n cells: (TableCell | undefined)[];\n /** Markdown-stripped cell texts joined — what rows are aligned on. */\n key: string;\n /** Cell texts with markdown intact, for spotting markdown-only edits. */\n rawKey: string;\n /**\n * Authored `props.rows[i]` for this row, carried through the diff.\n *\n * It has to travel with the row rather than by index: the diff reinserts\n * deleted rows from the old table, so the emitted order no longer matches\n * either input's `props.rows` indices.\n */\n rowProps?: Record<string, unknown>;\n}\n\n/** Text of a cell as it renders: a plain string, or a nested component's text. */\nfunction cellText(cell: TableCell | undefined): string {\n if (!cell) return '';\n const content = cell.content;\n if (typeof content === 'string')\n return stripMarkdown(content.normalize('NFC'));\n if (content && typeof content === 'object') {\n const props = (content as JsonNode).props;\n const text = props?.text;\n if (typeof text === 'string') return stripMarkdown(text.normalize('NFC'));\n }\n return '';\n}\n\n/** Cell text with markdown intact — what the author wrote. */\nfunction cellRawText(cell: TableCell | undefined): string {\n if (!cell) return '';\n const content = cell.content;\n if (typeof content === 'string') return content.normalize('NFC');\n if (content && typeof content === 'object') {\n const text = (content as JsonNode).props?.text;\n if (typeof text === 'string') return text.normalize('NFC');\n }\n return '';\n}\n\n/** True when the cell holds plain text a word-level diff can rewrite. */\nfunction isTextCell(cell: TableCell | undefined): boolean {\n if (!cell) return true;\n const content = cell.content;\n if (content === undefined || typeof content === 'string') return true;\n return (\n typeof content === 'object' && (content as JsonNode).name === 'paragraph'\n );\n}\n\n/** Turn the column-major model into rows, which is how people read a table. */\nfunction toRowView(node: JsonNode): TableRowView[] {\n const columns =\n (node.props?.columns as { cells?: TableCell[] }[] | undefined) ?? [];\n const rowCount = columns.reduce(\n (max, column) => Math.max(max, column.cells?.length ?? 0),\n 0\n );\n\n const authoredRows =\n (node.props?.rows as Record<string, unknown>[] | undefined) ?? [];\n\n return Array.from({ length: rowCount }, (_, rowIndex) => {\n const cells = columns.map((column) => column.cells?.[rowIndex]);\n return {\n cells,\n key: cells.map(cellText).join('\\u0000'),\n rawKey: cells.map(cellRawText).join('\\u0000'),\n rowProps: authoredRows[rowIndex],\n };\n });\n}\n\n/** Write a row-major set of rows back into the column-major model. */\nfunction withRows(\n node: JsonNode,\n rows: TableRowView[],\n rowProps: ({ revision?: unknown } | Record<string, never>)[]\n): JsonNode {\n const columns = (node.props?.columns as Record<string, unknown>[]) ?? [];\n // Each row keeps what it was authored with (cantSplit, tableHeader, ...);\n // the diff's own revision mark takes precedence over an authored one.\n const merged = rows.map((row, index) => ({\n ...(row.rowProps ?? {}),\n ...rowProps[index],\n }));\n return {\n ...node,\n props: {\n ...node.props,\n columns: columns.map((column, colIndex) => ({\n ...column,\n cells: rows.map((row) => row.cells[colIndex] ?? { content: '' }),\n })),\n ...(merged.some((props) => Object.keys(props).length > 0) && {\n rows: merged,\n }),\n },\n };\n}\n\n/**\n * True for the column-based table shape the differ understands. The legacy\n * `{ headers, rows }` shape is schema-invalid and only kept alive by a\n * renderer conversion, so it stays on the opaque path.\n */\nfunction isColumnTable(node: JsonNode): boolean {\n return Array.isArray(node.props?.columns) && !node.props?.headers;\n}\n\n/** A cell whose text is replaced by a word-level tracked change. */\nfunction revisedCell(\n cell: TableCell | undefined,\n oldCell: TableCell | undefined,\n oldText: string,\n newText: string,\n path: string,\n ctx: DiffContext\n): TableCell {\n const segments = diffWords(oldText, newText);\n notePlaceholdersInChanges(segments, path, 'table', ctx);\n // Revision segments render literally, so markdown anywhere in a changed cell\n // — including its unchanged portions — is flattened to plain text.\n if (cellRawText(oldCell) !== oldText || cellRawText(cell) !== newText) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'inline formatting or links flattened to plain text in a table cell (revision segments render literally)',\n });\n }\n const base = cell ?? { content: '' };\n return {\n ...base,\n // The revision carries the text, so `content` keeps the new version for\n // readers that ignore tracked changes. A component cell keeps being a\n // component — replacing it with a bare string would silently discard the\n // paragraph's font, alignment and the rest.\n content: revisedCellContent(base.content, newText, path, ctx),\n revision: makeRevision(ctx, segments),\n };\n}\n\n/**\n * The new `content` for a revised cell: a plain string stays a string, a\n * paragraph component keeps its props and only its text is rewritten.\n *\n * Notes cannot come along — the cell's revision drives the rendered runs, so a\n * `[^id]` marker in them never resolves, exactly as on a revised paragraph.\n */\nfunction revisedCellContent(\n content: unknown,\n newText: string,\n path: string,\n ctx: DiffContext\n): unknown {\n if (!content || typeof content !== 'object') return newText;\n\n const component = content as JsonNode;\n return {\n ...component,\n props: {\n ...revisedTextProps(component, path, ctx),\n text: newText,\n },\n };\n}\n\n/**\n * Diff a column-based table row by row.\n *\n * The model is column-major, so the diff builds a row-major view first: people\n * insert and delete rows, not columns. Rows are aligned on their joined,\n * markdown-stripped cell texts; unmatched runs are paired by column count so a\n * rewritten row becomes cell-level word changes rather than a delete plus an\n * insert.\n *\n * The legacy `{ headers, rows }` shape is not handled here — it is\n * schema-invalid and the renderer only converts it for backwards\n * compatibility, so it stays on the opaque block-replace path.\n */\nfunction diffTableComponent(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n const oldRows = toRowView(oldNode);\n const newRows = toRowView(newNode);\n\n const oldColumns = (oldNode.props?.columns as unknown[] | undefined) ?? [];\n const newColumns = (newNode.props?.columns as unknown[] | undefined) ?? [];\n if (oldColumns.length !== newColumns.length) {\n // Column insert/delete is a different tracked change (`w:tcPrChange` and\n // friends) that the renderer cannot express, so fall back to a replace.\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table column count changed (columns are not expressible as a tracked change); new version rendered',\n });\n return newNode;\n }\n\n const propsChanged = !deepEqual(\n propsWithout(oldNode.props, 'columns', 'rows'),\n propsWithout(newNode.props, 'columns', 'rows')\n );\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table configuration changed (borders/widths/defaults); new version rendered',\n });\n }\n\n const headersChanged = !deepEqual(\n oldColumns.map((column) => (column as { header?: unknown }).header),\n newColumns.map((column) => (column as { header?: unknown }).header)\n );\n if (headersChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'table header row changed (headers are not row content); new version rendered',\n });\n }\n\n if (\n deepEqual(\n oldRows.map((row) => row.key),\n newRows.map((row) => row.key)\n )\n ) {\n // Same rendered text, but markdown-only differences (bold markers,\n // hyperlink targets) are invisible after stripping — surface them, as the\n // paragraph and list paths do.\n if (\n !deepEqual(\n oldRows.map((row) => row.rawKey),\n newRows.map((row) => row.rawKey)\n )\n ) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: 'table',\n detail:\n 'inline formatting or link target changed in table cells (markdown-only); new version rendered without a tracked change',\n });\n } else if (\n !propsChanged &&\n !headersChanged &&\n deepEqual(oldRows, newRows)\n ) {\n ctx.summary.unchangedBlocks++;\n }\n return newNode;\n }\n\n const ops = alignByLcs(oldRows, newRows, (row) => row.key);\n\n const outRows: TableRowView[] = [];\n const outProps: ({ revision?: unknown } | Record<string, never>)[] = [];\n let changed = false;\n\n const push = (\n row: TableRowView,\n props: { revision?: unknown } | Record<string, never>\n ) => {\n outRows.push(row);\n outProps.push(props);\n };\n\n let k = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n push(op.newItem, {});\n k++;\n continue;\n }\n\n const deleted: TableRowView[] = [];\n const inserted: TableRowView[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n\n const { plan } = pairGap(\n deleted,\n inserted,\n (oldRow, newRow) =>\n oldRow.cells.length === newRow.cells.length &&\n oldRow.cells.every(isTextCell) &&\n newRow.cells.every(isTextCell)\n );\n\n for (const step of plan) {\n changed = true;\n if (step.kind === 'paired') {\n const cells = step.newItem.cells.map((cell, index) => {\n const oldText = cellText(step.oldItem.cells[index]);\n const newText = cellText(cell);\n return oldText === newText\n ? cell ?? { content: '' }\n : revisedCell(\n cell,\n step.oldItem.cells[index],\n oldText,\n newText,\n path,\n ctx\n );\n });\n push({ ...step.newItem, cells }, {});\n } else if (step.kind === 'inserted') {\n ctx.summary.tracked.inserted++;\n push(step.newItem, { revision: rowRevision(ctx, 'insert') });\n } else {\n ctx.summary.tracked.deleted++;\n push(step.oldItem, { revision: rowRevision(ctx, 'delete') });\n }\n }\n }\n\n if (changed) ctx.summary.tracked.modified++;\n return withRows(newNode, outRows, outProps);\n}\n\n/** Every row of a table marked inserted or deleted. */\nfunction tableWithAllRows(\n node: JsonNode,\n type: 'insert' | 'delete',\n ctx: DiffContext\n): JsonNode {\n if (type === 'insert') ctx.summary.tracked.inserted++;\n else ctx.summary.tracked.deleted++;\n\n const rows = toRowView(node);\n return withRows(\n node,\n rows,\n rows.map(() => ({ revision: rowRevision(ctx, type) }))\n );\n}\n\n/** A structural row revision (`w:trPr/w:ins` | `w:del`). */\nfunction rowRevision(ctx: DiffContext, type: 'insert' | 'delete') {\n return {\n type,\n ...(ctx.author && { author: ctx.author }),\n ...(ctx.date && { date: ctx.date }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Tree diff\n// ---------------------------------------------------------------------------\n\nfunction isContainer(node: JsonNode): boolean {\n return Array.isArray(node.children);\n}\n\nfunction nodesPairable(oldNode: JsonNode, newNode: JsonNode): boolean {\n return oldNode.name === newNode.name;\n}\n\nfunction diffPairedNode(\n oldNode: JsonNode,\n newNode: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n // `enabled` flips change what renders without touching props: treat them\n // as content appearing (insertion) or disappearing (deletion).\n const oldEnabled = isEnabled(oldNode);\n const newEnabled = isEnabled(newNode);\n if (!oldEnabled && !newEnabled) {\n ctx.summary.unchangedBlocks++;\n return newNode;\n }\n if (!oldEnabled && newEnabled) {\n return emitInserted(newNode, path, ctx);\n }\n if (oldEnabled && !newEnabled) {\n // The disabled new node would be filtered at render; emit the old\n // content as a tracked deletion instead (where supported).\n const deletedNode = emitDeleted(oldNode, path, ctx);\n return deletedNode ?? newNode;\n }\n\n if (TEXT_COMPONENTS.has(newNode.name)) {\n return diffTextComponent(oldNode, newNode, path, ctx);\n }\n if (newNode.name === 'list') {\n return diffListComponent(oldNode, newNode, path, ctx);\n }\n if (\n newNode.name === 'table' &&\n isColumnTable(oldNode) &&\n isColumnTable(newNode)\n ) {\n return diffTableComponent(oldNode, newNode, path, ctx);\n }\n if (isContainer(newNode) || isContainer(oldNode)) {\n const propsChanged = !deepEqual(oldNode.props, newNode.props);\n if (propsChanged) {\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail: 'container props changed; new version rendered',\n });\n }\n return {\n ...newNode,\n children: diffChildren(\n oldNode.children || [],\n newNode.children || [],\n `${path}/children`,\n ctx\n ),\n };\n }\n // Opaque component (table, image, chart, ...): block replace\n ctx.summary.untracked.push({\n path,\n kind: 'modified',\n component: newNode.name,\n detail: `\"${newNode.name}\" changed (no native tracked-change support); new version rendered`,\n });\n return newNode;\n}\n\nfunction emitInserted(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode {\n // A disabled node renders nothing — keep it, but track nothing\n if (!isEnabled(node)) {\n return node;\n }\n if (TEXT_COMPONENTS.has(node.name)) {\n return insertedTextComponent(node, path, ctx);\n }\n if (node.name === 'list') {\n return listWithAllItems(node, 'insert', ctx);\n }\n if (node.name === 'table' && isColumnTable(node)) {\n return tableWithAllRows(node, 'insert', ctx);\n }\n if (isContainer(node)) {\n if (typeof node.props?.title === 'string') {\n ctx.summary.untracked.push({\n path,\n kind: 'inserted',\n component: node.name,\n detail: `\"${node.name}\" title rendered without insertion mark (titles are props, not text blocks)`,\n });\n }\n return {\n ...node,\n children: diffChildren([], node.children || [], `${path}/children`, ctx),\n };\n }\n ctx.summary.untracked.push({\n path,\n kind: 'inserted',\n component: node.name,\n detail: `\"${node.name}\" added (rendered, but not marked as a tracked insertion)`,\n });\n return node;\n}\n\n/** Returns the redline node for a deleted block, or null if it must be dropped. */\nfunction emitDeleted(\n node: JsonNode,\n path: string,\n ctx: DiffContext\n): JsonNode | null {\n // A disabled node never rendered — drop it silently\n if (!isEnabled(node)) {\n return null;\n }\n if (TEXT_COMPONENTS.has(node.name)) {\n return deletedTextComponent(node, path, ctx);\n }\n if (node.name === 'list') {\n return listWithAllItems(node, 'delete', ctx);\n }\n if (node.name === 'table' && isColumnTable(node)) {\n // No longer null: a deleted table renders with every row marked deleted\n // rather than vanishing from the redline.\n return tableWithAllRows(node, 'delete', ctx);\n }\n if (isContainer(node)) {\n if (typeof node.props?.title === 'string') {\n ctx.summary.untracked.push({\n path,\n kind: 'deleted',\n component: node.name,\n detail: `\"${node.name}\" title still rendered without deletion mark (titles are props, not text blocks)`,\n });\n }\n const children = diffChildren(\n node.children || [],\n [],\n `${path}/children`,\n ctx\n );\n return { ...node, children };\n }\n ctx.summary.untracked.push({\n path,\n kind: 'deleted',\n component: node.name,\n detail: `\"${node.name}\" removed (dropped from the redline; Word cannot mark it as a tracked deletion)`,\n });\n return null;\n}\n\nexport function diffChildren(\n oldChildren: JsonNode[],\n newChildren: JsonNode[],\n path: string,\n ctx: DiffContext\n): JsonNode[] {\n const ops = alignByLcs(oldChildren, newChildren, (node) =>\n JSON.stringify(node)\n );\n\n const out: JsonNode[] = [];\n let k = 0;\n let newIndex = 0;\n while (k < ops.length) {\n const op = ops[k];\n if (op.op === 'equal') {\n ctx.summary.unchangedBlocks++;\n out.push(op.newItem);\n k++;\n newIndex++;\n continue;\n }\n\n // Collect the full delete/insert run between equal anchors\n const deleted: JsonNode[] = [];\n const inserted: JsonNode[] = [];\n while (k < ops.length && ops[k].op !== 'equal') {\n const gapOp = ops[k];\n if (gapOp.op === 'delete') deleted.push(gapOp.oldItem);\n else if (gapOp.op === 'insert') inserted.push(gapOp.newItem);\n k++;\n }\n\n const { plan } = pairGap(deleted, inserted, nodesPairable);\n for (const step of plan) {\n if (step.kind === 'paired') {\n out.push(\n diffPairedNode(step.oldItem, step.newItem, `${path}/${newIndex}`, ctx)\n );\n newIndex++;\n } else if (step.kind === 'inserted') {\n out.push(emitInserted(step.newItem, `${path}/${newIndex}`, ctx));\n newIndex++;\n } else {\n const deletedNode = emitDeleted(\n step.oldItem,\n `${path}/${newIndex}`,\n ctx\n );\n if (deletedNode) out.push(deletedNode);\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Diff two DOCX definitions into a renderable redline document.\n *\n * Both inputs must be json-to-office DOCX definitions (root `name: \"docx\"`).\n * The result is based on the NEW document; the root gains\n * `trackRevisions: true` so Word opens it in review mode.\n */\nexport function diffDocuments(\n oldDoc: JsonNode,\n newDoc: JsonNode,\n options: DiffDocumentsOptions = {}\n): DiffDocumentsResult {\n if (!oldDoc || oldDoc.name !== 'docx') {\n throw new Error('Old document: top-level component must be \"docx\"');\n }\n if (!newDoc || newDoc.name !== 'docx') {\n throw new Error('New document: top-level component must be \"docx\"');\n }\n\n const summary: DiffSummary = {\n tracked: { modified: 0, inserted: 0, deleted: 0 },\n untracked: [],\n unchangedBlocks: 0,\n notes: [],\n };\n const ctx: DiffContext = {\n author: options.author,\n date: options.date,\n summary,\n };\n\n const rootPropsChanged = !deepEqual(\n propsWithout(oldDoc.props, 'trackRevisions'),\n propsWithout(newDoc.props, 'trackRevisions')\n );\n if (rootPropsChanged) {\n summary.untracked.push({\n path: '/props',\n kind: 'modified',\n component: 'docx',\n detail:\n 'document props changed (theme/metadata/defaults); new version used',\n });\n }\n\n const children = diffChildren(\n oldDoc.children || [],\n newDoc.children || [],\n '/children',\n ctx\n );\n\n if (summary.tracked.deleted > 0) {\n summary.notes.push(\n `${summary.tracked.deleted} fully deleted block(s): accepting all changes leaves an empty paragraph behind (OOXML paragraph-mark deletion is not supported by the renderer)`\n );\n }\n\n const document: JsonNode = {\n ...newDoc,\n props: { ...newDoc.props, trackRevisions: true },\n children,\n };\n\n return { document, summary };\n}\n","// Version information\nexport const SHARED_DOCX_VERSION = '1.0.0';\n\n// ============================================================================\n// Document diff (tracked-change redlines)\n// ============================================================================\n\nexport { diffDocuments, diffWords, stripMarkdown } from './diff';\nexport type {\n DiffDocumentsOptions,\n DiffDocumentsResult,\n DiffSummary,\n UntrackedChange,\n DiffSegment,\n JsonNode,\n} from './diff';\n\n// ============================================================================\n// Format-agnostic re-exports from @json-to-office/shared\n// ============================================================================\n\n// Types\nexport type { ComponentDefinition as SharedComponentDefinition } from '@json-to-office/shared';\nexport type {\n GenerationWarning,\n AddWarningFunction,\n} from '@json-to-office/shared';\n\n// Schema utilities\nexport {\n fixSchemaReferences,\n convertToJsonSchema,\n createComponentSchema,\n createComponentSchemaObject as sharedCreateComponentSchemaObject,\n exportSchemaToFile,\n} from '@json-to-office/shared';\nexport type { ComponentSchemaConfig } from '@json-to-office/shared';\n\n// Validation - format-agnostic from shared\nexport {\n transformValueError,\n transformValueErrors,\n formatErrorSummary,\n groupErrorsByPath,\n createJsonParseError,\n calculatePosition,\n} from '@json-to-office/shared';\nexport type { ValidationError, ValidationResult } from '@json-to-office/shared';\nexport {\n type ErrorFormatterConfig,\n DEFAULT_ERROR_CONFIG,\n createErrorConfig,\n ERROR_EMOJIS,\n formatErrorMessage,\n} from '@json-to-office/shared';\nexport {\n isUnionSchema,\n isObjectSchema,\n isLiteralSchema,\n getObjectSchemaPropertyNames,\n getLiteralValue,\n extractStandardComponentNames,\n clearComponentNamesCache,\n getSchemaMetadata,\n} from '@json-to-office/shared';\n\n// Semver utilities\nexport {\n isValidSemver,\n parseSemver,\n compareSemver,\n latestVersion,\n type ParsedSemver,\n} from '@json-to-office/shared';\n\n// ============================================================================\n// Docx-specific: Document schemas\n// ============================================================================\n\nexport {\n JsonComponentDefinitionSchema,\n JSON_SCHEMA_URLS,\n validateDocumentWithSchema,\n validateJsonComponent as validateJsonComponentDoc,\n} from './schemas/document';\n\nexport type {\n DocumentValidationResult,\n ValidationError as DocumentValidationError,\n} from './schemas/document';\n\n// ============================================================================\n// Docx-specific: Theme schemas\n// ============================================================================\n\nexport {\n ThemeConfigSchema,\n isValidThemeConfig,\n createMinimalTheme,\n} from './schemas/theme';\n\nexport type {\n ThemeConfigJson,\n StyleDefinitions,\n DocumentMargins,\n PageDimensions,\n Page,\n FontDefinition,\n Fonts,\n ComponentDefaults,\n HeadingComponentDefaults,\n ParagraphComponentDefaults,\n ImageComponentDefaults,\n StatisticComponentDefaults,\n TableComponentDefaults,\n SectionComponentDefaults,\n ColumnsComponentDefaults,\n ListComponentDefaults,\n HeadingDefinition,\n} from './schemas/theme';\n\n// ============================================================================\n// Docx-specific: API schemas\n// ============================================================================\n\nexport * from './schemas/api';\n\n// ============================================================================\n// Docx-specific: Validation utilities\n// ============================================================================\n\n// Parser utilities\nexport {\n JsonDocumentParser,\n JsonParsingError,\n JsonValidationError,\n parseJsonComponent,\n validateJsonComponent,\n parseJsonWithLineNumbers,\n} from './validation/parsers/json';\n\n// Theme validators\nexport {\n validateThemeJson,\n isValidThemeJson,\n getValidationSummary,\n} from './validation/validators/theme';\n\n// Component validators\nexport {\n validateComponentProps,\n safeValidateComponentProps,\n safeValidateComponentDefinition,\n isReportProps,\n isSectionProps,\n isHeadingProps,\n isParagraphProps,\n isColumnsProps,\n isImageProps,\n isStatisticProps,\n isTableProps,\n isListProps,\n isCustomComponentProps,\n getValidationErrors,\n} from './validation/validators/component';\n\n// Export formatValidationErrors from theme validator (works for both)\nexport { formatValidationErrors } from './validation/validators/theme';\n\n// New comprehensive validation exports\nexport {\n // Core validators\n validateComponent,\n validateComponentDefinition,\n validateComponents,\n transformAndValidate,\n createValidatedComponent,\n isValidComponent,\n // Error formatting\n formatValidationError,\n formatValidationErrorStrings,\n formatErrorReport,\n getErrorSummary,\n hasCriticalErrors,\n getValidationContext,\n} from './validation';\n\n// Export types from validation\nexport type { ThemeValidationResult } from './validation/validators/theme';\n\nexport type {\n CoreValidationResult,\n StandardComponentName,\n FormattedError,\n} from './validation';\n\n// ============================================================================\n// Docx-specific: Unified Validation System\n// ============================================================================\n\nexport * from './validation/unified';\n\n// Re-export the simple validation API as the main validation interface\nexport { validate, validateStrict } from './validation/unified';\n\n// ============================================================================\n// Docx-specific: Component schemas (JavaScript values)\n// ============================================================================\n\nexport {\n AlignmentSchema,\n JustifiedAlignmentSchema,\n HeadingLevelSchema,\n SpacingSchema,\n LineSpacingSchema,\n IndentSchema,\n ParagraphIndentSchema,\n TabStopTypeSchema,\n TabStopLeaderSchema,\n TabStopSchema,\n TabStopsSchema,\n NumberingSchema,\n BorderSchema,\n MarginsSchema,\n BaseComponentPropsSchema,\n ReportPropsSchema,\n SectionPropsSchema,\n ColumnsPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ImagePropsSchema,\n TextBoxPropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n TocPropsSchema,\n RevisionSchema,\n RevisionSegmentSchema,\n RevisionMarkSchema,\n CommentSchema,\n CommentReplySchema,\n NoteSchema,\n FootnotesSchema,\n EndnotesSchema,\n ListMarkerFontSchema,\n StandardComponentDefinitionSchema,\n ComponentDefinitionSchema,\n} from './schemas/components';\n\n// Component types - export as types only\nexport type {\n BaseComponentProps,\n ReportProps,\n SectionProps,\n ColumnsProps,\n HeadingProps,\n ParagraphProps,\n ImageProps,\n TextBoxProps,\n StatisticProps,\n TableProps,\n ListProps,\n TocProps,\n Revision,\n RevisionSegment,\n RevisionMark,\n Comment,\n CommentReply,\n Note,\n ListMarkerFont,\n Alignment,\n JustifiedAlignment,\n HeadingLevel,\n Spacing,\n LineSpacing,\n Indent,\n ParagraphIndent,\n TabStopType,\n TabStopLeader,\n TabStop,\n TabStops,\n Numbering,\n} from './schemas/components';\n\n// Export ComponentDefinition from types/components.ts (better type inference)\nexport type {\n ComponentDefinition,\n StandardComponentDefinition,\n} from './types/components';\n\nexport {\n STANDARD_COMPONENTS,\n STANDARD_COMPONENTS_SET,\n} from './types/components';\n\n// Component registry — the single source of truth for which components exist,\n// which can hold children, and what those children may be.\nexport {\n STANDARD_COMPONENTS_REGISTRY,\n getStandardComponent,\n getAllStandardComponentNames,\n} from './schemas/component-registry';\n\n// Highcharts component schema (standard component)\nexport { HighchartsPropsSchema } from './schemas/components/highcharts';\nexport type { HighchartsProps } from './schemas/components/highcharts';\nexport { ChartPropsSchema } from './schemas/components/chart';\nexport type { ChartProps } from './schemas/components/chart';\n\n// Visual component schema (standard component — a rasterized pptx slide, or a\n// native Word drawing group under the `office-open` renderer)\nexport {\n VisualPropsSchema,\n VisualRasterPropsSchema,\n VisualNativePropsSchema,\n VisualCanvasSchema,\n VisualCanvasBackgroundSchema,\n NATIVE_RENDER_MODE,\n isNativeVisualProps,\n} from './schemas/components/visual';\nexport type {\n VisualProps,\n VisualRasterProps,\n VisualNativeProps,\n VisualCanvas,\n} from './schemas/components/visual';\n\n// Native visual content (the DrawingML element model)\nexport {\n NativeVisualElementSchema,\n NativeVisualCanvasSchema,\n NativeVisualTextPropsSchema,\n NativeVisualShapePropsSchema,\n NativeVisualImagePropsSchema,\n NATIVE_VISUAL_ELEMENT_NAMES,\n} from './schemas/components/visual-native';\nexport type {\n NativeVisualElement,\n NativeVisualElementName,\n NativeVisualCanvas,\n NativeVisualTextProps,\n NativeVisualShapeProps,\n NativeVisualImageProps,\n NativeVisualTextRun,\n NativeVisualTextSegment,\n NativeVisualFill,\n NativeVisualLine,\n} from './schemas/components/visual-native';\n\n// Custom component schemas\nexport {\n TextSpaceAfterPropsSchema,\n TextSpaceAfterComponentSchema,\n CustomComponentDefinitionSchema,\n} from './schemas/custom-components';\n\nexport type { TextSpaceAfterProps } from './schemas/custom-components';\n\n// Legacy support - re-export common types from schemas\nexport type { ThemeName } from './types/common';\n\n// ============================================================================\n// Docx-specific: Schema Export Utilities\n// ============================================================================\n\nexport {\n fixSchemaReferences as fixDocxSchemaReferences,\n convertToJsonSchema as convertDocxToJsonSchema,\n createComponentSchema as createDocxComponentSchema,\n exportSchemaToFile as exportDocxSchemaToFile,\n COMPONENT_METADATA,\n BASE_SCHEMA_METADATA,\n THEME_SCHEMA_METADATA,\n} from './schemas/export';\n\nexport type { ComponentSchemaConfig as DocxComponentSchemaConfig } from './schemas/export';\n\n// ============================================================================\n// Docx-specific: Unified Schema Generation\n// ============================================================================\n\nexport { generateUnifiedDocumentSchema } from './schemas/generator';\n\nexport type {\n CustomComponentInfo,\n GenerateDocumentSchemaOptions,\n} from './schemas/generator';\n\n// Renderer-discriminated schema profiles\nexport {\n DOCX_RENDERER_IDS,\n DEFAULT_DOCX_RENDERER_ID,\n collectDocxRendererErrors,\n docxComponentDefinitionName,\n} from './schemas/renderer';\nexport type { DocxRendererId } from './schemas/renderer';\n\n// ============================================================================\n// Docx-specific: Plugin System Type Support\n// ============================================================================\n\nexport {\n type ReportComponent,\n type ReportComponentFor,\n type SectionComponent,\n type ColumnsComponent,\n type HeadingComponent,\n type ParagraphComponent,\n type TextBoxComponent,\n type ImageComponent,\n type HighchartsComponent,\n type VisualComponent,\n type StatisticComponent,\n type TableComponent,\n type ListComponent,\n type TocComponent,\n type TextSpaceAfterComponent,\n isReportComponent,\n isSectionComponent,\n isColumnsComponent,\n isHeadingComponent,\n isParagraphComponent,\n isTextBoxComponent,\n isImageComponent,\n isHighchartsComponent,\n isVisualComponent,\n isStatisticComponent,\n isTableComponent,\n isListComponent,\n isTocComponent,\n isTextSpaceAfterComponent,\n} from './types/components';\n","import { Value, ValueError } from '@sinclair/typebox/value';\nimport { FormatRegistry } from '@sinclair/typebox';\nimport {\n DocumentValidationResult,\n ValidationError,\n} from '../../schemas/document';\nimport {\n ComponentDefinitionSchema,\n ComponentDefinition,\n} from '../../schemas/components';\n\n// Register format validators with TypeBox\nFormatRegistry.Set('uri', (value: string) => {\n // Accept URLs, relative paths, and file paths\n try {\n new URL(value);\n return true;\n } catch {\n // Check if it's a relative path (common for JSON schemas)\n if (\n value.includes('.json') ||\n value.includes('/') ||\n value.includes('\\\\')\n ) {\n return true;\n }\n // Check if it's an HTTP/HTTPS URL\n return /^https?:\\/\\/.+/.test(value);\n }\n});\n\nFormatRegistry.Set('date-time', (value: string) => {\n // ISO 8601 date-time format validation\n const dateTimeRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z?$/;\n return dateTimeRegex.test(value) && !isNaN(Date.parse(value));\n});\n\n/**\n * JSON parser\n * @module validation/parsers/json\n * @description\n * Advanced JSON parsing with line number tracking and detailed error reporting.\n * Provides enhanced error messages for JSON syntax and validation errors.\n */\n\n/**\n * JSON Document Parser - Handles parsing and validation of JSON report definitions\n */\nexport class JsonDocumentParser {\n private schema = ComponentDefinitionSchema;\n\n constructor() {\n // Schema is assigned above\n }\n\n /**\n * Parse JSON input (string or object) and validate against schema\n * Only supports unified ComponentDefinition structure where document IS a report component\n */\n public parse(jsonInput: string | object): ComponentDefinition {\n let parsedObject: unknown;\n\n // Step 1: Parse JSON if it's a string\n if (typeof jsonInput === 'string') {\n try {\n parsedObject = JSON.parse(jsonInput);\n } catch (error) {\n throw new JsonParsingError(\n 'Invalid JSON syntax',\n this.extractJSONSyntaxError(error as Error, jsonInput)\n );\n }\n } else {\n parsedObject = jsonInput;\n }\n\n // Step 2: Validate it's a report component\n if (\n typeof parsedObject !== 'object' ||\n parsedObject === null ||\n !('name' in parsedObject) ||\n (parsedObject as any).name !== 'docx'\n ) {\n throw new JsonValidationError(\n 'Invalid document structure: Document must be a docx component with name=\"docx\"',\n [\n {\n path: 'name',\n message: 'Document must be a docx component with name=\"docx\"',\n code: 'INVALID_STRUCTURE',\n },\n ]\n );\n }\n\n // Step 3: Validate against schema\n if (!Value.Check(this.schema, parsedObject)) {\n const errors = [...Value.Errors(this.schema, parsedObject)];\n\n throw new JsonValidationError(\n 'JSON validation failed',\n this.formatTypeBoxErrors(\n errors,\n typeof jsonInput === 'string'\n ? jsonInput\n : JSON.stringify(jsonInput, null, 2)\n )\n );\n }\n\n return parsedObject as ComponentDefinition;\n }\n\n /**\n * Validate JSON without throwing errors - returns ValidationResult\n */\n public validate(jsonInput: string | object): DocumentValidationResult {\n try {\n this.parse(jsonInput);\n return {\n valid: true,\n errors: [],\n warnings: [],\n };\n } catch (error) {\n if (\n error instanceof JsonParsingError ||\n error instanceof JsonValidationError\n ) {\n return {\n valid: false,\n errors: error.validationErrors,\n warnings: [],\n };\n }\n\n // Unexpected error\n return {\n valid: false,\n errors: [\n {\n path: '',\n message:\n error instanceof Error\n ? error.message\n : 'Unknown validation error',\n code: 'UNEXPECTED_ERROR',\n },\n ],\n warnings: [],\n };\n }\n }\n\n /**\n * Parse JSON file content with line number tracking\n */\n public parseWithLineNumbers(jsonString: string): ComponentDefinition {\n const lines = jsonString.split('\\n');\n\n try {\n return this.parse(jsonString);\n } catch (error) {\n if (\n error instanceof JsonParsingError ||\n error instanceof JsonValidationError\n ) {\n // Enhance errors with line numbers\n const enhancedErrors = error.validationErrors.map((err) => ({\n ...err,\n ...this.findLineNumber(err.path, jsonString, lines),\n }));\n\n if (error instanceof JsonParsingError) {\n throw new JsonParsingError(error.message, enhancedErrors);\n } else {\n throw new JsonValidationError(error.message, enhancedErrors);\n }\n }\n throw error;\n }\n }\n\n /**\n * Extract JSON syntax error information\n */\n private extractJSONSyntaxError(\n error: Error,\n jsonString: string\n ): ValidationError[] {\n const message = error.message;\n\n // Try to extract position from error message\n const positionMatch =\n message.match(/position\\s+(\\d+)/i) ||\n message.match(/at\\s+(\\d+)/i) ||\n message.match(/character\\s+(\\d+)/i);\n\n let line = 0;\n let column = 0;\n\n if (positionMatch) {\n const position = parseInt(positionMatch[1], 10);\n const lines = jsonString.substring(0, position).split('\\n');\n line = lines.length;\n column = lines[lines.length - 1].length + 1;\n }\n\n return [\n {\n path: '',\n message: `JSON syntax error: ${message}`,\n code: 'JSON_SYNTAX_ERROR',\n line: line || undefined,\n column: column || undefined,\n suggestions: [\n 'Check for missing commas, brackets, or quotes',\n 'Validate JSON syntax using a JSON validator',\n 'Ensure all strings are properly quoted',\n ],\n },\n ];\n }\n\n /**\n * Format TypeBox validation errors into ValidationError format\n */\n private formatTypeBoxErrors(\n errors: ValueError[],\n originalJson: string\n ): ValidationError[] {\n return errors.map((error) => {\n const path = error.path || '';\n const lineInfo = this.findLineNumber(path, originalJson);\n\n return {\n path,\n message: this.formatTypeBoxErrorMessage(error),\n code: this.getErrorCode(error),\n line: lineInfo.line,\n column: lineInfo.column,\n suggestions: this.generateSuggestions(error),\n };\n });\n }\n\n /**\n * Format individual TypeBox error message\n */\n private formatTypeBoxErrorMessage(error: ValueError): string {\n const path = error.path ? `at \"${error.path}\"` : '';\n const message = error.message;\n\n // TypeBox provides descriptive messages, so we can use them directly\n // but enhance common patterns\n if (message.includes('Expected')) {\n return `${message} ${path}`;\n } else if (message.includes('Required property')) {\n return `${message} ${path}`;\n } else if (message.includes('Unexpected property')) {\n return `${message} ${path}`;\n } else if (message.includes('minimum')) {\n return `Value is too small ${path}. ${message}`;\n } else if (message.includes('maximum')) {\n return `Value is too big ${path}. ${message}`;\n } else {\n return `${message} ${path}`;\n }\n }\n\n /**\n * Get error code from TypeBox error\n */\n private getErrorCode(error: ValueError): string {\n const baseCode = String(error.type || 'VALIDATION_ERROR').toUpperCase();\n const path = error.path ? error.path.replace(/\\//g, '_').toUpperCase() : '';\n return path ? `${baseCode}_${path}` : baseCode;\n }\n\n /**\n * Generate helpful suggestions based on error type\n */\n private generateSuggestions(error: ValueError): string[] {\n const suggestions: string[] = [];\n const message = error.message;\n\n // Parse TypeBox error messages to provide suggestions\n if (message.includes('Expected string')) {\n suggestions.push('Ensure the value is wrapped in quotes');\n } else if (message.includes('Expected number')) {\n suggestions.push('Remove quotes around numeric values');\n } else if (message.includes('Expected array')) {\n suggestions.push('Use square brackets [] for arrays');\n } else if (message.includes('Expected object')) {\n suggestions.push('Use curly braces {} for objects');\n } else if (message.includes('Expected literal')) {\n const match = message.match(/Expected literal (.+)/);\n if (match) {\n suggestions.push(`Use the exact value: ${match[1]}`);\n }\n } else if (message.includes('Unexpected property')) {\n suggestions.push('Remove unknown properties or check spelling');\n suggestions.push(\n 'Refer to the JSON schema documentation for valid properties'\n );\n } else if (message.includes('Expected union')) {\n suggestions.push(\n 'Check that the value matches one of the allowed formats'\n );\n // The component registry is itself a union, so a union failure on a node\n // in a `children` array — or on its `name` discriminator — usually is a\n // misspelt component name. Unions elsewhere (spacing, colour, size) are\n // not, and the unconditional hint sent authors hunting for a field their\n // error had nothing to do with.\n const path = error.path ?? '';\n if (/\\/children\\/\\d+$/.test(path) || path.endsWith('/name')) {\n suggestions.push('Verify the component name is spelled correctly');\n }\n } else if (message.includes('minimum')) {\n const match = message.match(/minimum.*?(\\d+)/);\n if (match) {\n if (message.includes('Array')) {\n suggestions.push(`Array must have at least ${match[1]} items`);\n } else {\n suggestions.push(`Value must be at least ${match[1]}`);\n }\n }\n } else if (message.includes('format') && message.includes('uri')) {\n suggestions.push(\n 'Ensure the URL is valid and starts with http:// or https://'\n );\n }\n\n // Generic suggestions\n if (suggestions.length === 0) {\n suggestions.push('Check the JSON schema documentation for valid values');\n suggestions.push('Verify the property name and value format');\n }\n\n return suggestions;\n }\n\n /**\n * Find line and column number for a given JSON path\n */\n private findLineNumber(\n path: string,\n jsonString: string,\n lines?: string[]\n ): { line?: number; column?: number } {\n if (!path) {\n return {};\n }\n\n const jsonLines = lines || jsonString.split('\\n');\n const pathParts = path.split('.');\n\n // Simple heuristic: find the line containing the property name\n for (let i = 0; i < jsonLines.length; i++) {\n const line = jsonLines[i];\n const lastPathPart = pathParts[pathParts.length - 1];\n\n // Look for property name in quotes\n if (line.includes(`\"${lastPathPart}\"`)) {\n const column = line.indexOf(`\"${lastPathPart}\"`) + 1;\n return {\n line: i + 1,\n column,\n };\n }\n }\n\n return {};\n }\n}\n\n/**\n * Custom error classes for better error handling\n */\nexport class JsonParsingError extends Error {\n public readonly validationErrors: ValidationError[];\n\n constructor(message: string, errors: ValidationError[]) {\n super(message);\n this.name = 'JsonParsingError';\n this.validationErrors = errors;\n }\n}\n\nexport class JsonValidationError extends Error {\n public readonly validationErrors: ValidationError[];\n\n constructor(message: string, errors: ValidationError[]) {\n super(message);\n this.name = 'JsonValidationError';\n this.validationErrors = errors;\n }\n}\n\n/**\n * Utility functions for external use\n */\n\n/**\n * Parse and validate JSON component definition\n * Only supports report components (documents)\n */\nexport function parseJsonComponent(\n jsonInput: string | object\n): ComponentDefinition {\n const parser = new JsonDocumentParser();\n return parser.parse(jsonInput);\n}\n\n/**\n * Validate JSON component definition without throwing\n * Now uses unified validation\n */\nexport { validateJsonDocument as validateJsonComponent } from '../unified/document-validator';\n\n/**\n * Parse JSON with enhanced line number error reporting\n * Only supports unified ComponentDefinition structure where document IS a report component\n */\nexport function parseJsonWithLineNumbers(\n jsonString: string\n): ComponentDefinition {\n const parser = new JsonDocumentParser();\n return parser.parseWithLineNumbers(jsonString);\n}\n","/**\n * Theme validators\n * @module validation/validators/theme\n * @description\n * Now uses unified validation system\n */\n\n// Re-export everything from unified theme validator\nexport {\n validateThemeJson,\n isValidTheme as isValidThemeJson,\n getThemeName,\n isThemeConfig,\n type ThemeValidationResult,\n} from '../unified/theme-validator';\n\n// Re-export utility for getting validation summary\nexport { getValidationSummary } from '../unified/base-validator';\n\n// For backward compatibility, provide formatValidationErrors\nexport function formatValidationErrors(errors: any[]): string[] {\n if (!Array.isArray(errors)) return [];\n\n return errors.map((error) => {\n if (typeof error === 'string') return error;\n\n const path = error.path ? `${error.path}: ` : '';\n const message = error.message || 'Validation error';\n return `${path}${message}`;\n });\n}\n","/**\n * Component validators\n * @module validation/validators/component\n * @description\n * Now uses unified validation system\n */\n\nimport {\n validateComponent as unifiedValidateComponent,\n validateComponentDefinition as unifiedValidateComponentDefinition,\n isStandardComponentName,\n} from '../unified/component-validator';\n\n// Re-export everything from unified component validator\nexport {\n validateComponent as validateComponentProps,\n validateComponentDefinition,\n validateComponents,\n validateCustomComponentProps,\n isStandardComponentName,\n // Type guards\n isReportProps,\n isSectionProps,\n isHeadingProps,\n isParagraphProps,\n isColumnsProps,\n isImageProps,\n isStatisticProps,\n isTableProps,\n isListProps,\n isCustomComponentProps,\n type StandardComponentName,\n} from '../unified/component-validator';\n\n// For backward compatibility, provide safeValidateComponentProps\nexport function safeValidateComponentProps<T>(\n name: string,\n props: unknown\n): { success: true; data: T } | { success: false; error: any[] } {\n // For non-standard types, use 'custom'\n const componentName = isStandardComponentName(name) ? name : 'custom';\n const result = unifiedValidateComponent(componentName, props);\n\n if (result.valid) {\n return { success: true, data: result.data as T };\n }\n\n return { success: false, error: result.errors || [] };\n}\n\n// For backward compatibility, provide safeValidateComponentDefinition\nexport function safeValidateComponentDefinition(\n component: unknown\n): { success: true; data: any } | { success: false; error: any[] } {\n const result = unifiedValidateComponentDefinition(component);\n\n if (result.valid) {\n return { success: true, data: result.data };\n }\n\n return { success: false, error: result.errors || [] };\n}\n\n// For backward compatibility, provide error formatting\nexport function getValidationErrors(props: unknown, name?: string): string[] {\n // For non-standard types, use 'custom'\n const componentName = name && isStandardComponentName(name) ? name : 'custom';\n const result = unifiedValidateComponent(componentName, props);\n\n if (result.valid) return [];\n\n return (result.errors || []).map((e: any) =>\n e.path ? `${e.path}: ${e.message}` : e.message\n );\n}\n","import { Value } from '@sinclair/typebox/value';\nimport { Static } from '@sinclair/typebox';\nimport {\n ComponentDefinitionSchema,\n ReportPropsSchema,\n SectionPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ColumnsPropsSchema,\n ImagePropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n} from '../../schemas/components';\nimport { CustomComponentDefinitionSchema } from '../../schemas/custom-components';\nimport {\n formatTypeBoxError,\n formatTypeBoxErrorStrings,\n formatErrorReport,\n hasCriticalErrors,\n} from './errors';\nimport type {\n CoreValidationResult,\n ValidationOptions,\n BatchValidationResult,\n ComponentValidationConfig,\n DataTransformer,\n} from './types';\n\n/**\n * Core validation engine\n * @module validation/core/validator\n * @description\n * Main validation utilities using TypeBox for runtime validation.\n * Provides comprehensive validation with error handling and data transformation.\n */\n\n/**\n * Component name to schema mapping\n */\nconst COMPONENT_SCHEMA_MAP = {\n report: ReportPropsSchema,\n section: SectionPropsSchema,\n heading: HeadingPropsSchema,\n paragraph: ParagraphPropsSchema,\n columns: ColumnsPropsSchema,\n image: ImagePropsSchema,\n statistic: StatisticPropsSchema,\n table: TablePropsSchema,\n list: ListPropsSchema,\n} as const;\n\nexport type StandardComponentName = keyof typeof COMPONENT_SCHEMA_MAP;\n\n/**\n * Validate any component configuration with comprehensive error handling\n */\nexport function validateComponent<T extends StandardComponentName>(\n name: T,\n props: unknown,\n options?: ValidationOptions\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n const schema = COMPONENT_SCHEMA_MAP[name];\n\n if (!schema) {\n // Handle custom components\n if (Value.Check(CustomComponentDefinitionSchema, props)) {\n return {\n success: true,\n data: props as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(CustomComponentDefinitionSchema, props)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n }\n\n // Validate with the schema\n if (Value.Check(schema, props)) {\n return {\n success: true,\n data: props as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(schema, props)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n}\n\n/**\n * Validate a complete component definition (with nested children)\n */\nexport function validateComponentDefinition(\n component: unknown,\n options?: ValidationOptions\n): CoreValidationResult<Static<typeof ComponentDefinitionSchema>> {\n // Check for circular references or excessive nesting\n const maxDepth = options?.maxDepth ?? 10;\n const currentDepth = options?.currentDepth ?? 0;\n\n if (currentDepth > maxDepth) {\n return {\n success: false,\n errors: [\n {\n path: 'children',\n message: `Maximum nesting depth (${maxDepth}) exceeded`,\n code: 'custom',\n suggestion: 'Reduce the nesting level of components',\n },\n ],\n errorStrings: [`Maximum nesting depth (${maxDepth}) exceeded`],\n hasCriticalErrors: true,\n };\n }\n\n if (Value.Check(ComponentDefinitionSchema, component)) {\n // Validate nested children recursively\n const data = component as any;\n const warnings: string[] = [];\n\n if (data.children && Array.isArray(data.children)) {\n for (let i = 0; i < data.children.length; i++) {\n const nestedResult = validateComponentDefinition(data.children[i], {\n ...options,\n currentDepth: currentDepth + 1,\n });\n\n if (!nestedResult.success) {\n // Add context to nested errors\n const nestedErrors = nestedResult.errors?.map((err) => ({\n ...err,\n path: `children[${i}].${err.path}`,\n }));\n\n return {\n success: false,\n errors: nestedErrors,\n errorStrings: nestedErrors?.map(\n (err) => `${err.path}: ${err.message}`\n ),\n report: options?.includeReport\n ? `Validation failed in nested component at index ${i}:\\n${nestedResult.report}`\n : undefined,\n hasCriticalErrors: nestedResult.hasCriticalErrors,\n };\n }\n\n if (nestedResult.warnings) {\n warnings.push(\n ...nestedResult.warnings.map((w) => `children[${i}]: ${w}`)\n );\n }\n }\n }\n\n return {\n success: true,\n data: component as Static<typeof ComponentDefinitionSchema>,\n warnings: warnings.length > 0 ? warnings : undefined,\n };\n }\n\n const errors = [...Value.Errors(ComponentDefinitionSchema, component)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: options?.includeReport ? formatErrorReport(errors) : undefined,\n hasCriticalErrors: options?.checkCritical\n ? hasCriticalErrors(errors)\n : undefined,\n };\n}\n\n/**\n * Batch validate multiple components\n */\nexport function validateComponents(\n components: ComponentValidationConfig[],\n options?: ValidationOptions\n): BatchValidationResult {\n const results: CoreValidationResult<any>[] = [];\n let criticalCount = 0;\n\n for (const { name, props } of components) {\n const result =\n name in COMPONENT_SCHEMA_MAP\n ? validateComponent(name as StandardComponentName, props, options)\n : validateComponentDefinition(props, options);\n\n results.push(result);\n\n if (result.hasCriticalErrors) {\n criticalCount++;\n }\n\n if (!result.success && options?.stopOnFirst) {\n break;\n }\n }\n\n const valid = results.filter((r) => r.success).length;\n const invalid = results.length - valid;\n\n return {\n success: invalid === 0,\n results,\n summary: {\n total: results.length,\n valid,\n invalid,\n criticalErrors: criticalCount,\n },\n };\n}\n\n/**\n * Transform and validate data (for migration scenarios)\n */\nexport function transformAndValidate<T extends StandardComponentName>(\n name: T,\n data: unknown,\n transformer?: DataTransformer\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n try {\n // Apply custom transformation if provided\n const transformed = transformer ? transformer(data) : data;\n\n // Validate the transformed data\n return validateComponent(name, transformed, {\n includeReport: true,\n checkCritical: true,\n });\n } catch (error) {\n return {\n success: false,\n errors: [\n {\n path: 'root',\n message: `Transformation failed: ${error instanceof Error ? error.message : String(error)}`,\n code: 'custom',\n },\n ],\n errorStrings: [\n `Transformation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n hasCriticalErrors: true,\n };\n }\n}\n\n/**\n * Create a validated component with defaults\n */\nexport function createValidatedComponent<T extends StandardComponentName>(\n name: T,\n partialConfig: Partial<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>>\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n const schema = COMPONENT_SCHEMA_MAP[name];\n\n if (!schema) {\n return {\n success: false,\n errors: [\n {\n path: 'name',\n message: `Unknown component name: ${name}`,\n code: 'custom',\n suggestion: `Use one of: ${Object.keys(COMPONENT_SCHEMA_MAP).join(', ')}`,\n },\n ],\n errorStrings: [`Unknown component name: ${name}`],\n hasCriticalErrors: true,\n };\n }\n\n // Validate with TypeBox\n if (Value.Check(schema, partialConfig)) {\n return {\n success: true,\n data: partialConfig as Static<(typeof COMPONENT_SCHEMA_MAP)[T]>,\n };\n }\n\n const errors = [...Value.Errors(schema, partialConfig)];\n const formattedErrors = formatTypeBoxError(errors);\n return {\n success: false,\n errors: formattedErrors,\n errorStrings: formatTypeBoxErrorStrings(errors),\n report: formatErrorReport(errors),\n hasCriticalErrors: hasCriticalErrors(errors),\n };\n}\n\n/**\n * Type guard functions with proper error context\n */\nexport function isValidComponent<T extends StandardComponentName>(\n name: T,\n props: unknown\n): props is Static<(typeof COMPONENT_SCHEMA_MAP)[T]> {\n const result = validateComponent(name, props);\n return result.success;\n}\n\n/**\n * Validate JSON string input\n */\nexport function validateJsonComponent<T extends StandardComponentName>(\n name: T,\n jsonString: string\n): CoreValidationResult<Static<(typeof COMPONENT_SCHEMA_MAP)[T]>> {\n try {\n const parsed = JSON.parse(jsonString);\n return validateComponent(name, parsed, {\n includeReport: true,\n checkCritical: true,\n });\n } catch (error) {\n return {\n success: false,\n errors: [\n {\n path: 'root',\n message: `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`,\n code: 'custom',\n suggestion: 'Check for syntax errors in your JSON',\n },\n ],\n errorStrings: [\n `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`,\n ],\n hasCriticalErrors: true,\n };\n }\n}\n","import { ValueError } from '@sinclair/typebox/value';\nimport type { FormattedError } from './types';\n\n/**\n * Error formatting utilities\n * @module validation/core/errors\n * @description\n * Enhanced error formatting for TypeBox validation errors.\n * Provides detailed, user-friendly error messages with context and suggestions.\n */\n\n/**\n * Format a single TypeBox error into a user-friendly error message\n */\nfunction formatSingleIssue(issue: ValueError): FormattedError {\n const path = issue.path || 'root';\n let message = issue.message;\n let suggestion: string | undefined;\n let expected: string | undefined;\n let received: string | undefined;\n let options: string[] | undefined;\n\n // Enhance error messages based on error type\n if (message.includes('Expected')) {\n const match = message.match(/Expected (.+) but received (.+)/);\n if (match) {\n expected = match[1];\n received = match[2];\n suggestion = getSuggestionForType(expected, received);\n }\n }\n\n // Handle required property errors\n if (message.includes('Required property')) {\n const match = message.match(/Required property '(.+)'/);\n if (match) {\n message = `Missing required field: ${match[1]}`;\n suggestion = `Add the required field: ${match[1]}`;\n }\n }\n\n // Handle unexpected property errors\n if (message.includes('Unexpected property')) {\n const match = message.match(/Unexpected property '(.+)'/);\n if (match) {\n message = `Unknown property: ${match[1]}`;\n suggestion = `Remove the unknown property: ${match[1]}`;\n }\n }\n\n // Handle union type errors\n if (message.includes('Expected union')) {\n message = 'Value does not match any of the expected types';\n suggestion = 'Check the documentation for valid format options';\n }\n\n // Handle literal value errors\n if (message.includes('Expected literal')) {\n const match = message.match(/Expected literal (.+)/);\n if (match) {\n expected = match[1];\n message = `Expected value: ${expected}`;\n suggestion = `Use the exact value: ${expected}`;\n }\n }\n\n // Handle string length errors\n if (message.includes('String length')) {\n const minMatch = message.match(/minimum length of (\\d+)/);\n const maxMatch = message.match(/maximum length of (\\d+)/);\n if (minMatch) {\n message = `String must be at least ${minMatch[1]} characters long`;\n suggestion = `Add more characters to meet the minimum length of ${minMatch[1]}`;\n } else if (maxMatch) {\n message = `String must be at most ${maxMatch[1]} characters long`;\n suggestion = `Reduce to ${maxMatch[1]} characters or less`;\n }\n }\n\n // Handle number range errors\n if (message.includes('Expected number')) {\n const minMatch = message.match(/minimum value of ([\\d.]+)/);\n const maxMatch = message.match(/maximum value of ([\\d.]+)/);\n if (minMatch) {\n message = `Number must be greater than or equal to ${minMatch[1]}`;\n suggestion = `Use a value of ${minMatch[1]} or higher`;\n } else if (maxMatch) {\n message = `Number must be less than or equal to ${maxMatch[1]}`;\n suggestion = `Use a value of ${maxMatch[1]} or lower`;\n }\n }\n\n // Handle array length errors\n if (message.includes('Array length')) {\n const minMatch = message.match(/minimum length of (\\d+)/);\n const maxMatch = message.match(/maximum length of (\\d+)/);\n if (minMatch) {\n message = `Array must have at least ${minMatch[1]} items`;\n suggestion = `Add more items to meet the minimum of ${minMatch[1]}`;\n } else if (maxMatch) {\n message = `Array must have at most ${maxMatch[1]} items`;\n suggestion = `Remove items to meet the maximum of ${maxMatch[1]}`;\n }\n }\n\n // Handle format errors\n if (message.includes('format')) {\n if (message.includes('email')) {\n message = 'Invalid email address format';\n suggestion = 'Use a valid email format like user@example.com';\n } else if (message.includes('uri') || message.includes('url')) {\n message = 'Invalid URL format';\n suggestion = 'Use a valid URL format like https://example.com';\n } else if (message.includes('date-time')) {\n message = 'Invalid date-time format';\n suggestion = 'Use ISO 8601 format like 2024-01-01T00:00:00Z';\n }\n }\n\n // Handle pattern errors\n if (message.includes('pattern')) {\n message = 'String does not match the required pattern';\n suggestion = 'Check the format requirements for this field';\n }\n\n return {\n path,\n message,\n code: String(issue.type || 'validation_error'),\n suggestion,\n expected,\n received,\n options,\n };\n}\n\n/**\n * Get type-specific suggestions for common type mismatches\n */\nfunction getSuggestionForType(\n expected: string,\n received: string\n): string | undefined {\n // Number/String confusion\n if (expected === 'number' && received === 'string') {\n return 'Remove quotes or convert the string to a number';\n }\n if (expected === 'string' && received === 'number') {\n return 'Add quotes or convert the number to a string';\n }\n\n // Boolean confusion\n if (expected === 'boolean') {\n return 'Use true or false (without quotes)';\n }\n\n // Array/Object confusion\n if (expected === 'array' && received === 'object') {\n return 'Use square brackets [] for arrays instead of curly braces {}';\n }\n if (expected === 'object' && received === 'array') {\n return 'Use curly braces {} for objects instead of square brackets []';\n }\n\n // Null/undefined handling\n if (received === 'null' || received === 'undefined') {\n return `Provide a valid ${expected} value or mark the field as optional`;\n }\n\n return undefined;\n}\n\n/**\n * Format TypeBox validation errors into detailed, user-friendly messages\n */\nexport function formatTypeBoxError(errors: ValueError[]): FormattedError[] {\n return errors.map(formatSingleIssue);\n}\n\n/**\n * Format errors as simple string array (backward compatible)\n */\nexport function formatTypeBoxErrorStrings(errors: ValueError[]): string[] {\n return formatTypeBoxError(errors).map((err) => {\n let msg = `${err.path}: ${err.message}`;\n if (err.suggestion) {\n msg += ` (Suggestion: ${err.suggestion})`;\n }\n return msg;\n });\n}\n\n/**\n * Get a summary of validation errors grouped by path\n */\nexport function getErrorSummary(\n errors: ValueError[]\n): Map<string, FormattedError[]> {\n const summary = new Map<string, FormattedError[]>();\n\n for (const formattedError of formatTypeBoxError(errors)) {\n const existing = summary.get(formattedError.path) || [];\n existing.push(formattedError);\n summary.set(formattedError.path, existing);\n }\n\n return summary;\n}\n\n/**\n * Format validation errors as a detailed report\n */\nexport function formatErrorReport(errors: ValueError[]): string {\n const formattedErrors = formatTypeBoxError(errors);\n const summary = getErrorSummary(errors);\n\n let report = `Validation failed with ${formattedErrors.length} error${formattedErrors.length > 1 ? 's' : ''}:\\n\\n`;\n\n for (const [path, pathErrors] of summary) {\n report += `📍 ${path}:\\n`;\n for (const err of pathErrors) {\n report += ` ❌ ${err.message}\\n`;\n if (err.suggestion) {\n report += ` 💡 ${err.suggestion}\\n`;\n }\n if (err.expected && err.received) {\n report += ` 📋 Expected: ${err.expected}, Received: ${err.received}\\n`;\n }\n if (err.options) {\n report += ` 📋 Valid options: ${err.options.join(', ')}\\n`;\n }\n }\n report += '\\n';\n }\n\n return report;\n}\n\n/**\n * Check if an error is critical (affects core functionality)\n */\nexport function hasCriticalErrors(errors: ValueError[]): boolean {\n return errors.some((issue) => {\n // Missing required fields are critical\n if (issue.message.includes('Required property')) {\n return true;\n }\n\n // Invalid component names are critical\n if (\n issue.path.includes('name') &&\n issue.message.includes('Expected literal')\n ) {\n return true;\n }\n\n // Schema structure errors are critical\n if (\n issue.message.includes('Expected union') ||\n issue.message.includes('Never')\n ) {\n return true;\n }\n\n return false;\n });\n}\n\n/**\n * Get validation context for better error messages\n */\nexport function getValidationContext(path: string): string {\n if (!path || path === 'root') return 'document root';\n\n const pathParts = path.split('.');\n\n // Identify component context\n if (pathParts.includes('children')) {\n const childIndex = pathParts.indexOf('children');\n if (pathParts.length > childIndex + 1) {\n const index = pathParts[childIndex + 1];\n return `component at index ${index}`;\n }\n }\n\n // Identify props context\n if (pathParts.includes('props')) {\n return 'props section';\n }\n\n // Identify theme context\n if (pathParts.includes('theme')) {\n return 'theme configuration';\n }\n\n return pathParts.join(' > ');\n}\n\n// ============================================================================\n// Legacy Compatibility Exports (for API backward compatibility)\n// ============================================================================\n\n// Primary exports - use formatTypeBoxError and formatTypeBoxErrorStrings directly\nexport const formatValidationError = formatTypeBoxError;\nexport const formatValidationErrorStrings = formatTypeBoxErrorStrings;\n","/**\n * Component Type Definitions for Plugin System\n *\n * This file provides properly typed discriminated union interfaces for all component types.\n * These types enable TypeScript to automatically infer component props based on\n * the 'name' field when building component arrays in render functions.\n */\n\nimport type { Static } from '@sinclair/typebox';\nimport type {\n ReportPropsSchema,\n SectionPropsSchema,\n HeadingPropsSchema,\n ParagraphPropsSchema,\n ColumnsPropsSchema,\n ImagePropsSchema,\n HighchartsPropsSchema,\n ChartPropsSchema,\n VisualPropsSchema,\n StatisticPropsSchema,\n TablePropsSchema,\n ListPropsSchema,\n TocPropsSchema,\n} from '../schemas/components';\n\nimport type { TextSpaceAfterPropsSchema } from '../schemas/custom-components';\nimport type { TextBoxPropsSchema } from '../schemas/components/text-box';\nimport type { DocxRendererId } from '../schemas/renderer';\n\n// ============================================================================\n// Standard Component Types with Discriminated Union Support\n// ============================================================================\n\n/**\n * Report component with literal name discriminator\n */\nexport interface ReportComponent {\n name: 'docx';\n id?: string;\n /** Renderer backend. Omitted defaults to docxjs. */\n renderer?: DocxRendererId;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ReportPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/** A document explicitly targeted at one renderer profile. */\nexport type ReportComponentFor<R extends DocxRendererId> = Omit<\n ReportComponent,\n 'renderer'\n> &\n (R extends 'docxjs' ? { renderer?: R } : { renderer: R });\n\n/**\n * Section component with literal name discriminator\n */\nexport interface SectionComponent {\n name: 'section';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof SectionPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * Columns component with literal name discriminator\n */\nexport interface ColumnsComponent {\n name: 'columns';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ColumnsPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * Heading component with literal name discriminator\n */\nexport interface HeadingComponent {\n name: 'heading';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof HeadingPropsSchema>;\n}\n\n/**\n * Paragraph component with literal name discriminator\n */\nexport interface ParagraphComponent {\n name: 'paragraph';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ParagraphPropsSchema>;\n}\n\n/**\n * Image component with literal name discriminator\n */\nexport interface ImageComponent {\n name: 'image';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ImagePropsSchema>;\n}\n\n/**\n * Statistic component with literal name discriminator\n */\nexport interface StatisticComponent {\n name: 'statistic';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof StatisticPropsSchema>;\n}\n\n/**\n * Table component with literal name discriminator\n */\nexport interface TableComponent {\n name: 'table';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TablePropsSchema>;\n}\n\n/**\n * Native chart component with literal name discriminator.\n *\n * Only `office-open` draws it; the schema for every other renderer omits the\n * component entirely.\n */\nexport interface ChartComponent {\n name: 'chart';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ChartPropsSchema>;\n}\n\n/**\n * Highcharts component with literal name discriminator\n */\nexport interface HighchartsComponent {\n name: 'highcharts';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof HighchartsPropsSchema>;\n}\n\n/**\n * Visual component with literal name discriminator.\n * A pptx-rendered free-canvas graphic embedded as a rasterized image.\n */\nexport interface VisualComponent {\n name: 'visual';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof VisualPropsSchema>;\n}\n\n/**\n * Text Box component with literal name discriminator\n * Container for child components with floating positioning\n */\nexport interface TextBoxComponent {\n name: 'text-box';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TextBoxPropsSchema>;\n children?: ComponentDefinition[];\n}\n\n/**\n * List component with literal name discriminator\n */\nexport interface ListComponent {\n name: 'list';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof ListPropsSchema>;\n}\n\n/**\n * Table of Contents component with literal name discriminator\n */\nexport interface TocComponent {\n name: 'toc';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TocPropsSchema>;\n}\n\n// ============================================================================\n// Specific Custom Component Types\n// ============================================================================\n\n/**\n * Text Space After component with literal name discriminator\n */\nexport interface TextSpaceAfterComponent {\n name: 'text-space-after';\n id?: string;\n /** When false, this component is filtered out and not rendered. Defaults to true */\n enabled?: boolean;\n props: Static<typeof TextSpaceAfterPropsSchema>;\n}\n\n// ============================================================================\n// Discriminated Union Types\n// ============================================================================\n\n/**\n * Union of all standard component types\n */\nexport type StandardComponentDefinition =\n | ReportComponent\n | SectionComponent\n | ColumnsComponent\n | HeadingComponent\n | ParagraphComponent\n | TextBoxComponent\n | ImageComponent\n | HighchartsComponent\n | ChartComponent\n | VisualComponent\n | StatisticComponent\n | TableComponent\n | ListComponent\n | TocComponent;\n\n/**\n * Array of all standard component names.\n * Useful for iterating, validation, or displaying available components to users.\n */\nexport const STANDARD_COMPONENTS = [\n 'chart',\n 'columns',\n 'heading',\n 'highcharts',\n 'image',\n 'list',\n 'paragraph',\n 'docx',\n 'section',\n 'statistic',\n 'table',\n 'text-box',\n 'toc',\n 'visual',\n] as const satisfies readonly StandardComponentDefinition['name'][];\n\n/**\n * Set of all standard component names for O(1) lookup.\n */\nexport const STANDARD_COMPONENTS_SET: ReadonlySet<\n (typeof STANDARD_COMPONENTS)[number]\n> = new Set(STANDARD_COMPONENTS);\n\n// Compile-time completeness check: produces TS2344 listing the missing name(s)\n// if a standard component is added to the union but not to the array above.\ntype AssertNever<T extends never> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype _AssertAllIncluded = AssertNever<\n Exclude<\n StandardComponentDefinition['name'],\n (typeof STANDARD_COMPONENTS)[number]\n >\n>;\n\n/**\n * Complete discriminated union of all component types.\n * TypeScript will automatically narrow the type based on the 'name' field.\n *\n * @example\n * ```typescript\n * const components: ComponentDefinition[] = [\n * {\n * name: 'heading', // TypeScript knows this is HeadingComponent\n * props: {\n * level: 2, // Autocomplete works!\n * text: 'Title'\n * }\n * },\n * {\n * name: 'paragraph', // TypeScript knows this is ParagraphComponent\n * props: {\n * content: 'Hello World',\n * bold: true // Autocomplete works!\n * }\n * }\n * ];\n * ```\n */\nexport type ComponentDefinition =\n | StandardComponentDefinition\n | TextSpaceAfterComponent;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nexport function isReportComponent(\n component: ComponentDefinition\n): component is ReportComponent {\n return component.name === 'docx';\n}\n\nexport function isSectionComponent(\n component: ComponentDefinition\n): component is SectionComponent {\n return component.name === 'section';\n}\n\nexport function isColumnsComponent(\n component: ComponentDefinition\n): component is ColumnsComponent {\n return component.name === 'columns';\n}\n\nexport function isHeadingComponent(\n component: ComponentDefinition\n): component is HeadingComponent {\n return component.name === 'heading';\n}\n\nexport function isParagraphComponent(\n component: ComponentDefinition\n): component is ParagraphComponent {\n return component.name === 'paragraph';\n}\n\nexport function isImageComponent(\n component: ComponentDefinition\n): component is ImageComponent {\n return component.name === 'image';\n}\n\nexport function isTextBoxComponent(\n component: ComponentDefinition\n): component is TextBoxComponent {\n return component.name === 'text-box';\n}\n\nexport function isStatisticComponent(\n component: ComponentDefinition\n): component is StatisticComponent {\n return component.name === 'statistic';\n}\n\nexport function isTableComponent(\n component: ComponentDefinition\n): component is TableComponent {\n return component.name === 'table';\n}\n\nexport function isListComponent(\n component: ComponentDefinition\n): component is ListComponent {\n return component.name === 'list';\n}\n\nexport function isTocComponent(\n component: ComponentDefinition\n): component is TocComponent {\n return component.name === 'toc';\n}\n\nexport function isHighchartsComponent(\n component: ComponentDefinition\n): component is HighchartsComponent {\n return component.name === 'highcharts';\n}\n\nexport function isVisualComponent(\n component: ComponentDefinition\n): component is VisualComponent {\n return component.name === 'visual';\n}\n\nexport function isTextSpaceAfterComponent(\n component: ComponentDefinition\n): component is TextSpaceAfterComponent {\n return component.name === 'text-space-after';\n}\n"],"mappings":";;;;;;;;;;;;;;;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O,UAAU,SAAS;AAC5B;AAEO,SAAS,mBACd,WAC+B;AAC/B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,qBACd,WACiC;AACjC,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,iBACd,WAC6B;AAC7B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,mBACd,WAC+B;AAC/B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,qBACd,WACiC;AACjC,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,iBACd,WAC6B;AAC7B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,gBACd,WAC4B;AAC5B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,eACd,WAC2B;AAC3B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,sBACd,WACkC;AAClC,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,kBACd,WAC8B;AAC9B,SAAO,UAAU,SAAS;AAC5B;AAEO,SAAS,0BACd,WACsC;AACtC,SAAO,UAAU,SAAS;AAC5B;;;AN3YO,IAAM,sBAAsB;","names":["k","i","j","i","j","fixSchemaReferences","convertToJsonSchema","createComponentSchema","exportSchemaToFile","transformValueError","transformValueErrors","Value","validateComponent","Value","errors","formattedErrors","validateComponentDefinition","validateComponents"]}
|