open-agreements
Version:
Open-source legal template filling CLI and library
1,183 lines • 52.6 kB
JavaScript
/**
* Declarative option selection for DOCX templates.
*
* Handles radio-button `( )` and checkbox `[ ]` option groups in table cells.
* A per-template `selections.json` config defines groups, and this module
* deletes unselected options + their sub-clauses from the DOCX XML before filling.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { z } from 'zod';
import AdmZip from 'adm-zip';
import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
import { getParagraphText, replaceParagraphTextRange, SafeDocxError } from '@usejunior/docx-core';
import { copyEntriesSkippingDirs, enumerateTextParts, getGeneralTextPartNames } from './field-selector/ooxml-parts.js';
import { createParagraphNumberingResolver } from './field-selector/paragraph-numbering.js';
const W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
/** Normalize smart quotes to ASCII equivalents for matching. */
function normalizeQuotes(text) {
return text
.replace(/[\u2018\u2019\u2039\u203A]/g, "'")
.replace(/[\u201C\u201D\u201A\u201E\u00AB\u00BB]/g, '"');
}
// ---------------------------------------------------------------------------
// Schema
// ---------------------------------------------------------------------------
const TriggerSchema = z.union([
z.literal('default'),
z.object({ field: z.string(), equals: z.union([z.string(), z.boolean()]) }).strict(),
z.object({ field: z.string() }).strict(),
]);
const ApplicabilitySchema = z.object({
field: z.string().min(1),
equals: z.union([z.string(), z.boolean()]),
}).strict();
const OptionSchema = z.object({
label: z.string().optional(),
marker: z.string(),
trigger: TriggerSchema,
replaceWith: z.string().optional(),
selectedAction: z.literal('unwrap_brackets').optional(),
removal: z.discriminatedUnion('kind', [
z.object({
kind: z.literal('table'),
anchor: z.string().min(1),
removeAdjacentBlankParagraphs: z.boolean().optional(),
}).strict(),
z.object({
kind: z.literal('section'),
startAnchor: z.string().min(1),
endAnchor: z.string().min(1),
removeAdjacentBlankParagraphs: z.boolean().optional(),
}).strict(),
z.object({
kind: z.literal('paragraph'),
anchor: z.string().min(1),
match: z.enum(['exact', 'contains']).default('exact'),
expectedMatches: z.literal(1),
within: z.object({
startAnchor: z.string().min(1),
endAnchor: z.string().min(1),
match: z.enum(['exact', 'contains']).default('exact'),
expectedMatches: z.literal(1),
}).strict().optional(),
removeAdjacentBlankParagraphs: z.boolean().optional(),
}).strict(),
]).optional(),
}).strict();
const GroupSchema = z
.object({
id: z.string(),
type: z.enum(['radio', 'checkbox']),
standalone: z.boolean().optional(),
markerless: z.boolean().optional(),
inline: z.boolean().optional(),
cellContext: z.string().optional(),
subClauseStopPatterns: z.array(z.string()).optional(),
applies_when: ApplicabilitySchema.optional(),
options: z.array(OptionSchema).min(1),
}).strict()
.refine((g) => g.standalone === true || g.markerless === true || g.options.length >= 2, { message: 'Non-standalone/non-markerless groups require at least 2 options' })
.refine((g) => {
if (!g.subClauseStopPatterns)
return true;
for (const p of g.subClauseStopPatterns) {
try {
new RegExp(p, 'i');
}
catch {
return false;
}
}
return true;
}, { message: 'subClauseStopPatterns must contain valid regular expressions' })
.refine((g) => !g.inline || g.markerless === true, { message: 'inline: true requires markerless: true' })
.refine((g) => g.options.every((o) => !o.removal || (g.markerless === true && !g.inline && o.replaceWith === undefined)), { message: 'bounded removal requires markerless:true, inline:false, and no replaceWith' })
.refine((g) => g.options.every((o) => !o.selectedAction || (g.markerless === true && g.inline === true && o.marker.startsWith('[') && o.marker.endsWith(']'))), { message: 'selectedAction:unwrap_brackets requires markerless:true, inline:true, and a square-bracket-delimited marker' });
export const SelectionsConfigSchema = z.object({
groups: z.array(GroupSchema).min(1),
}).strict();
// ---------------------------------------------------------------------------
// Loader
// ---------------------------------------------------------------------------
export function loadSelectionsConfig(path) {
const raw = readFileSync(path, 'utf-8');
return SelectionsConfigSchema.parse(JSON.parse(raw));
}
// ---------------------------------------------------------------------------
// Bookmark-aware removal
// ---------------------------------------------------------------------------
/**
* Remove a set of paragraphs from the document, cleaning up any bookmark
* start/end elements whose counterparts would be orphaned.
*
* Phase A: For each doomed paragraph, find bookmarkStart/End elements.
* If the counterpart (by w:id) lives outside the doomed set, mark it
* for removal so no orphans remain.
* Phase B: Remove orphaned counterparts.
* Phase C: Remove the paragraphs themselves.
*/
function removeWithBookmarkCleanup(doc, parasToRemove) {
if (parasToRemove.size === 0)
return;
const orphanedCounterparts = [];
for (const p of parasToRemove) {
const starts = p.getElementsByTagNameNS(W_NS, 'bookmarkStart');
for (let i = 0; i < starts.length; i++) {
const id = starts[i].getAttribute('w:id');
if (!id)
continue;
const allEnds = doc.getElementsByTagNameNS(W_NS, 'bookmarkEnd');
for (let j = 0; j < allEnds.length; j++) {
if (allEnds[j].getAttribute('w:id') !== id)
continue;
const endParent = findAncestorElement(allEnds[j], 'p');
if (!endParent || !parasToRemove.has(endParent)) {
orphanedCounterparts.push(allEnds[j]);
}
break;
}
}
const ends = p.getElementsByTagNameNS(W_NS, 'bookmarkEnd');
for (let i = 0; i < ends.length; i++) {
const id = ends[i].getAttribute('w:id');
if (!id)
continue;
const allStarts = doc.getElementsByTagNameNS(W_NS, 'bookmarkStart');
for (let j = 0; j < allStarts.length; j++) {
if (allStarts[j].getAttribute('w:id') !== id)
continue;
const startParent = findAncestorElement(allStarts[j], 'p');
if (!startParent || !parasToRemove.has(startParent)) {
orphanedCounterparts.push(allStarts[j]);
}
break;
}
}
}
for (const el of orphanedCounterparts) {
el.parentNode?.removeChild(el);
}
for (const p of parasToRemove) {
p.parentNode?.removeChild(p);
}
}
/** Find the nearest ancestor element with the given local name (W namespace). */
function findAncestorElement(node, localName) {
let current = node.parentNode;
while (current) {
if (current.nodeType === 1) {
const el = current;
if (el.localName === localName && el.namespaceURI === W_NS)
return el;
}
current = current.parentNode;
}
return null;
}
function isWordElement(node, localName) {
if (!node || node.nodeType !== 1)
return false;
const el = node;
return el.namespaceURI === W_NS && (localName === undefined || el.localName === localName);
}
function elementChildren(parent) {
const result = [];
for (let i = 0; i < parent.childNodes.length; i++) {
const node = parent.childNodes[i];
if (node.nodeType === 1)
result.push(node);
}
return result;
}
function exactParagraphMatches(doc, anchor) {
const expected = normalizedParagraphText(anchor);
const matches = [];
const paragraphs = doc.getElementsByTagNameNS(W_NS, 'p');
for (let i = 0; i < paragraphs.length; i++) {
if (normalizedParagraphText(extractParagraphText(paragraphs[i])) === expected)
matches.push(paragraphs[i]);
}
return matches;
}
function normalizedParagraphText(text) {
return normalizeQuotes(text).replace(/\s+/g, ' ').trim();
}
function matchingParagraphs(paragraphs, anchor, match) {
const expected = normalizedParagraphText(anchor);
const matches = [];
for (const paragraph of paragraphs) {
const actual = normalizedParagraphText(extractParagraphText(paragraph));
if (match === 'exact' ? actual === expected : actual.includes(expected))
matches.push(paragraph);
}
return matches;
}
function allParagraphs(doc) {
return Array.from(doc.getElementsByTagNameNS(W_NS, 'p'));
}
function paragraphMatches(doc, anchor, match) {
return matchingParagraphs(allParagraphs(doc), anchor, match);
}
/**
* Resolve the body blocks strictly between an unambiguous pair of paragraph
* boundaries. The boundaries themselves are deliberately excluded so callers
* can mutate only content inside the declared region.
*/
function paragraphsWithinScope(doc, groupId, scope) {
const starts = paragraphMatches(doc, scope.startAnchor, scope.match);
const ends = paragraphMatches(doc, scope.endAnchor, scope.match);
if (starts.length !== scope.expectedMatches || ends.length !== scope.expectedMatches) {
throw new Error(`[selector] Group "${groupId}": paragraph scope boundaries matched start=${starts.length} (expected 1), ` +
`end=${ends.length} (expected 1).`);
}
const start = starts[0];
const end = ends[0];
if (start.parentNode !== end.parentNode || !start.parentNode) {
throw new Error(`[selector] Group "${groupId}": paragraph scope boundaries must be sibling blocks.`);
}
const siblings = elementChildren(start.parentNode);
const startIndex = siblings.indexOf(start);
const endIndex = siblings.indexOf(end);
if (startIndex < 0 || endIndex <= startIndex) {
throw new Error(`[selector] Group "${groupId}": paragraph scope end boundary must follow its start boundary.`);
}
const paragraphs = [];
for (const block of siblings.slice(startIndex + 1, endIndex)) {
if (isWordElement(block, 'p'))
paragraphs.push(block);
const descendants = block.getElementsByTagNameNS(W_NS, 'p');
for (let i = 0; i < descendants.length; i++)
paragraphs.push(descendants[i]);
}
return paragraphs;
}
function assertBalancedComplexFields(groupId, paragraph) {
const chars = paragraph.getElementsByTagNameNS(W_NS, 'fldChar');
let depth = 0;
for (let i = 0; i < chars.length; i++) {
const type = chars[i].getAttribute('w:fldCharType') ?? chars[i].getAttribute('fldCharType');
if (type === 'begin')
depth++;
if (type === 'end')
depth--;
if (depth < 0)
break;
}
if (depth !== 0) {
throw new Error(`[selector] Group "${groupId}": paragraph removal would split a complex Word field.`);
}
}
function isBlankParagraph(node) {
return isWordElement(node, 'p') && extractParagraphText(node) === '';
}
/** Remove complete body blocks while also deleting bookmark counterparts outside them. */
function removeBlockNodes(doc, blocks) {
const doomedParas = new Set();
for (const block of blocks) {
if (isWordElement(block, 'p'))
doomedParas.add(block);
const paras = block.getElementsByTagNameNS(W_NS, 'p');
for (let i = 0; i < paras.length; i++)
doomedParas.add(paras[i]);
}
removeWithBookmarkCleanup(doc, doomedParas);
for (const block of blocks)
block.parentNode?.removeChild(block);
}
/**
* Execute an explicit, fail-closed block removal. Section end anchors are
* preserved and must be later siblings of the start anchor, preventing a
* missing/drifted boundary from consuming the rest of the agreement.
*/
function applyBoundedRemoval(doc, groupId, removal, remove) {
if (removal.kind === 'paragraph') {
const candidates = removal.within ? paragraphsWithinScope(doc, groupId, removal.within) : allParagraphs(doc);
const matches = matchingParagraphs(candidates, removal.anchor, removal.match);
if (matches.length !== removal.expectedMatches) {
const scopeLabel = removal.within ? ' within scope' : '';
throw new Error(`[selector] Group "${groupId}": paragraph anchor "${removal.anchor}"${scopeLabel} matched ${matches.length} paragraphs (expected 1).`);
}
const paragraph = matches[0];
if (remove)
assertBalancedComplexFields(groupId, paragraph);
const parent = paragraph.parentNode;
if (!parent)
throw new Error(`[selector] Group "${groupId}": matched paragraph has no parent.`);
const siblings = elementChildren(parent);
const index = siblings.indexOf(paragraph);
const blocks = new Set([paragraph]);
if (removal.removeAdjacentBlankParagraphs !== false) {
for (let i = index - 1; i >= 0 && isBlankParagraph(siblings[i]); i--)
blocks.add(siblings[i]);
for (let i = index + 1; i < siblings.length && isBlankParagraph(siblings[i]); i++)
blocks.add(siblings[i]);
}
if (remove)
removeBlockNodes(doc, blocks);
return matches.length;
}
if (removal.kind === 'table') {
const anchors = exactParagraphMatches(doc, removal.anchor);
if (anchors.length !== 1) {
throw new Error(`[selector] Group "${groupId}": table anchor "${removal.anchor}" matched ${anchors.length} paragraphs (expected 1).`);
}
const tables = new Set(anchors.map((p) => findAncestorElement(p, 'tbl')).filter((t) => t !== null));
if (tables.size !== 1) {
throw new Error(`[selector] Group "${groupId}": table anchor must resolve to exactly one table (resolved ${tables.size}).`);
}
const table = [...tables][0];
const parent = table.parentNode;
if (!parent)
throw new Error(`[selector] Group "${groupId}": matched table has no parent.`);
const siblings = elementChildren(parent);
const index = siblings.indexOf(table);
const blocks = new Set([table]);
if (removal.removeAdjacentBlankParagraphs !== false) {
for (let i = index - 1; i >= 0 && isBlankParagraph(siblings[i]); i--)
blocks.add(siblings[i]);
for (let i = index + 1; i < siblings.length && isBlankParagraph(siblings[i]); i++)
blocks.add(siblings[i]);
}
if (remove)
removeBlockNodes(doc, blocks);
return anchors.length;
}
const starts = exactParagraphMatches(doc, removal.startAnchor);
const ends = exactParagraphMatches(doc, removal.endAnchor);
if (starts.length !== 1 || ends.length !== 1) {
throw new Error(`[selector] Group "${groupId}": section boundaries matched start=${starts.length} (expected 1), ` +
`end=${ends.length} (expected 1).`);
}
const start = starts[0];
const end = ends[0];
if (start.parentNode !== end.parentNode || !start.parentNode) {
throw new Error(`[selector] Group "${groupId}": section boundaries must be sibling body blocks.`);
}
const siblings = elementChildren(start.parentNode);
const startIndex = siblings.indexOf(start);
const endIndex = siblings.indexOf(end);
if (startIndex < 0 || endIndex <= startIndex) {
throw new Error(`[selector] Group "${groupId}": section end boundary must follow its start boundary.`);
}
const blocks = new Set(siblings.slice(startIndex, endIndex));
if (removal.removeAdjacentBlankParagraphs !== false) {
for (let i = startIndex - 1; i >= 0 && isBlankParagraph(siblings[i]); i--)
blocks.add(siblings[i]);
}
if (remove)
removeBlockNodes(doc, blocks);
return starts.length;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Extract paragraph text by concatenating all <w:t> elements. */
function extractParagraphText(para) {
if (!para.getElementsByTagNameNS)
return '';
const tElements = para.getElementsByTagNameNS(W_NS, 't');
const parts = [];
for (let i = 0; i < tElements.length; i++) {
parts.push(tElements[i].textContent ?? '');
}
return parts.join('').trim();
}
/** Extract all text from a table cell by concatenating its paragraph texts. */
function extractCellText(cell) {
const paras = cell.getElementsByTagNameNS(W_NS, 'p');
const parts = [];
for (let i = 0; i < paras.length; i++) {
parts.push(extractParagraphText(paras[i]));
}
return parts.join(' ');
}
/** Check if a paragraph's text starts with a radio or checkbox marker. */
const MARKER_RE = /^\(\s*x?\s*\)|^\[\s*x?\s*\]|^[\u2610\u2611\u2612]/i;
function hasOptionPrefix(text) {
return MARKER_RE.test(text);
}
/** Update a paragraph's marker prefix to checked state. */
function setChecked(para, type) {
const tElements = para.getElementsByTagNameNS(W_NS, 't');
if (tElements.length === 0)
return;
// Reconstruct the full text from all <w:t> elements
const fullText = extractParagraphText(para);
if (!fullText)
return;
// Unicode ballot box: swap ☐/☒ → ☑
if (/^[\u2610\u2612]/.test(fullText)) {
for (let i = 0; i < tElements.length; i++) {
const content = tElements[i].textContent ?? '';
if (/[\u2610\u2612]/.test(content)) {
tElements[i].textContent = content.replace(/[\u2610\u2612]/, '\u2611');
return;
}
}
return;
}
// Determine marker style from the paragraph text first. Some templates use
// square-bracket markers ([ ]) with radio semantics.
let openBracket = '[';
let closeBracket = ']';
if (/\(\s*[xX]?\s*\)/.test(fullText)) {
openBracket = '(';
closeBracket = ')';
}
else if (/\[\s*[xX]?\s*\]/.test(fullText)) {
openBracket = '[';
closeBracket = ']';
}
else if (type === 'radio') {
openBracket = '(';
closeBracket = ')';
}
const checkedPrefix = openBracket === '(' ? '( x )' : '[ x ]';
// Walk through <w:t> elements to find and replace the marker
let foundOpen = false;
let foundClose = false;
const tToBlank = [];
for (let i = 0; i < tElements.length; i++) {
const t = tElements[i];
const content = t.textContent ?? '';
if (!foundOpen) {
const openIdx = content.indexOf(openBracket);
if (openIdx >= 0) {
foundOpen = true;
// Check if close bracket is in the same <w:t>
const closeIdx = content.indexOf(closeBracket, openIdx + 1);
if (closeIdx >= 0) {
// Both brackets in same element — simple replacement
const before = content.substring(0, openIdx);
const after = content.substring(closeIdx + 1);
t.textContent = before + checkedPrefix + after;
foundClose = true;
break;
}
else {
// Open bracket found, close bracket in a later element
t.textContent = content.substring(0, openIdx) + checkedPrefix;
}
}
}
else if (!foundClose) {
const closeIdx = content.indexOf(closeBracket);
if (closeIdx >= 0) {
// Found the closing bracket — keep everything after it
t.textContent = content.substring(closeIdx + 1);
foundClose = true;
break;
}
else {
// Between open and close — blank out this text node
tToBlank.push(t);
}
}
}
// Blank out intermediate text nodes (between open and close brackets)
for (const t of tToBlank) {
t.textContent = '';
}
}
/** Evaluate a trigger against fill data. */
function triggerFires(trigger, data) {
if (trigger === 'default')
return false; // default never "fires" — it's the fallback
if ('equals' in trigger) {
const val = data[trigger.field];
return val !== undefined && val !== '' && String(val) === String(trigger.equals);
}
// { field: "x" } — truthy check
const val = data[trigger.field];
return val !== undefined && val !== '' && val !== false && val !== 'false';
}
function groupApplies(group, data) {
const predicate = group.applies_when;
if (!predicate)
return true;
const value = data[predicate.field];
if (value === undefined || value === '') {
throw new Error(`[selector] Group "${group.id}" applicability field "${predicate.field}" is missing`);
}
if (typeof value !== typeof predicate.equals) {
throw new Error(`[selector] Group "${group.id}" applicability field "${predicate.field}" must be ${typeof predicate.equals}, received ${typeof value}`);
}
return value === predicate.equals;
}
/** Human-readable identifier for one option in a diagnostic message. */
export function describeSelectionOption(o) {
return `${o.groupId}[${o.optionIndex}] "${o.marker}"`;
}
/** Split a selections run's per-option counts into the three anomaly classes. */
export function classifySelectionMatches(result) {
const engagedGroups = new Set();
for (const o of result.options) {
if (o.matchCount > 0)
engagedGroups.add(o.groupId);
}
const anomalies = {
unremovedInEngagedGroup: [],
unremovedInInertGroup: [],
selectedZeroMatch: [],
};
for (const o of result.options) {
if (o.selected) {
// A selected option is supposed to survive, so `appliedCount` says nothing
// about it in the markerless paths. Only its absence matters.
if (o.matchCount === 0)
anomalies.selectedZeroMatch.push(o);
continue;
}
// An unselected option is supposed to DISAPPEAR. The question is therefore
// "was anything actually done about it", not "did its marker match".
if (o.appliedCount > 0)
continue;
if (engagedGroups.has(o.groupId)) {
anomalies.unremovedInEngagedGroup.push(o);
}
else {
anomalies.unremovedInInertGroup.push(o);
}
}
return anomalies;
}
function recordOptionMatches(stats, group, selectedIndices, counts) {
for (let oi = 0; oi < group.options.length; oi++) {
const key = `${group.id}::${oi}`;
const existing = stats.get(key);
if (existing) {
existing.matchCount += counts[oi] ?? 0;
continue;
}
stats.set(key, {
groupId: group.id,
optionIndex: oi,
marker: group.options[oi].marker,
selected: selectedIndices.has(oi),
matchCount: counts[oi] ?? 0,
appliedCount: 0,
});
}
}
/**
* Add to the "paragraphs actually acted on" tally. Split from
* `recordOptionMatches` because a processor learns its match counts up front —
* before the early returns that must not lose them — but only learns what it
* acted on at the end.
*/
function recordOptionApplied(stats, group, applied) {
for (let oi = 0; oi < group.options.length; oi++) {
const existing = stats.get(`${group.id}::${oi}`);
if (existing)
existing.appliedCount += applied[oi] ?? 0;
}
}
// ---------------------------------------------------------------------------
// Core algorithm
// ---------------------------------------------------------------------------
/**
* Apply option selections to a DOCX buffer and return the modified buffer.
*
* For each group in the config:
* 1. Find option paragraphs by marker text + radio/checkbox prefix
* 2. Verify they share the same table cell
* 3. Classify paragraphs as header, option, or sub-clause
* 4. Evaluate triggers to determine selected options
* 5. Remove unselected options + sub-clauses
* 6. Mark selected options as checked
*/
export async function applySelections(inputPath, outputPath, config, data) {
const inputBuf = readFileSync(inputPath);
const zip = new AdmZip(inputBuf);
const parser = new DOMParser();
const serializer = new XMLSerializer();
const parts = enumerateTextParts(zip);
const partNames = getGeneralTextPartNames(parts);
const stats = new Map();
const stylesEntry = zip.getEntry('word/styles.xml');
const styles = stylesEntry
? parser.parseFromString(stylesEntry.getData().toString('utf-8'), 'text/xml')
: undefined;
const resolveNumbering = createParagraphNumberingResolver(styles);
for (const partName of partNames) {
const entry = zip.getEntry(partName);
if (!entry)
continue;
const xml = entry.getData().toString('utf-8');
const doc = parser.parseFromString(xml, 'text/xml');
let partModified = false;
for (const group of config.groups) {
if (!groupApplies(group, data))
continue;
const result = processGroup(doc, group, data, stats, partName === 'word/document.xml', resolveNumbering);
if (result)
partModified = true;
}
if (partModified) {
const outXml = serializer.serializeToString(doc);
zip.updateFile(partName, Buffer.from(outXml, 'utf-8'));
}
}
// Rebuild zip from scratch (adm-zip data descriptor workaround)
const outZip = new AdmZip();
copyEntriesSkippingDirs(zip, outZip);
const outBuf = outZip.toBuffer();
writeFileSync(outputPath, outBuf);
// Report in config order so diagnostics read like the config file.
const options = [];
for (const group of config.groups) {
for (let oi = 0; oi < group.options.length; oi++) {
const entry = stats.get(`${group.id}::${oi}`);
if (entry)
options.push(entry);
}
}
return { outputPath, options };
}
/**
* Process a single option group within a parsed XML document.
* Returns true if any modifications were made.
*/
function processGroup(doc, group, data, stats, isMainDocument, resolveNumbering) {
if (group.markerless) {
return processMarkerlessGroup(doc, group, data, stats, isMainDocument, resolveNumbering);
}
if (group.standalone) {
return processStandaloneGroup(doc, group, data, stats);
}
// Step 1: Find ALL candidate paragraphs for each option's marker
const allParagraphs = doc.getElementsByTagNameNS(W_NS, 'p');
const candidatesPerOption = group.options.map(() => []);
for (let oi = 0; oi < group.options.length; oi++) {
const option = group.options[oi];
for (let pi = 0; pi < allParagraphs.length; pi++) {
const para = allParagraphs[pi];
const text = extractParagraphText(para);
if (text && hasOptionPrefix(text) && text.includes(option.marker)) {
candidatesPerOption[oi].push({ para, optionIndex: oi });
}
}
}
// Record match counts before any early return or throw below (#720), so a
// group that finds no qualifying cell still reports which options matched.
// `appliedCount` stays 0 on those paths, which is the point: a group that
// resolves no qualifying cell removes NOTHING while every option still
// reports a non-zero match count, and the document keeps both alternatives.
recordOptionMatches(stats, group, evaluateTriggers(group, data), candidatesPerOption.map((c) => c.length));
// Step 2: Find a cell where ALL options have at least one candidate
// Group candidates by their parent cell
const cellCandidates = new Map();
for (const candidates of candidatesPerOption) {
for (const match of candidates) {
const cell = findAncestor(match.para, 'tc');
if (!cell)
continue;
if (!cellCandidates.has(cell))
cellCandidates.set(cell, []);
cellCandidates.get(cell).push(match);
}
}
// Collect all qualifying cells (where all options are represented)
const qualifyingCells = [];
for (const [candidateCell, matches] of cellCandidates) {
const representedOptions = new Set(matches.map((m) => m.optionIndex));
if (representedOptions.size >= 2 && representedOptions.size >= group.options.length) {
const seen = new Set();
const deduped = [];
for (const match of matches) {
if (!seen.has(match.optionIndex)) {
seen.add(match.optionIndex);
deduped.push(match);
}
}
qualifyingCells.push({ cell: candidateCell, matches: deduped });
}
}
if (qualifyingCells.length === 0)
return false;
let cell;
let optionMatches;
if (qualifyingCells.length === 1) {
cell = qualifyingCells[0].cell;
optionMatches = qualifyingCells[0].matches;
}
else if (group.cellContext) {
const filtered = qualifyingCells.filter(({ cell: c }) => {
const cellText = extractCellText(c);
return cellText.includes(group.cellContext);
});
if (filtered.length === 1) {
cell = filtered[0].cell;
optionMatches = filtered[0].matches;
}
else if (filtered.length === 0) {
throw new Error(`[selector] Group "${group.id}": cellContext "${group.cellContext}" did not match any of ${qualifyingCells.length} candidate cells.`);
}
else {
throw new Error(`[selector] Group "${group.id}": cellContext "${group.cellContext}" matched ${filtered.length} cells (expected 1). Use a more specific cellContext.`);
}
}
else {
const snippets = qualifyingCells.map(({ cell: c }, i) => {
const text = extractCellText(c);
return ` Cell ${i + 1}: "${text.substring(0, 120)}..."`;
});
throw new Error(`[selector] Group "${group.id}": ${qualifyingCells.length} candidate cells with identical markers. ` +
`Add "cellContext" to disambiguate.\nCandidates:\n${snippets.join('\n')}`);
}
// Step 3: Collect all <w:p> in this cell and classify them
const cellParas = cell.getElementsByTagNameNS(W_NS, 'p');
const classified = [];
let currentOwner = -1; // -1 = header
for (let i = 0; i < cellParas.length; i++) {
const p = cellParas[i];
const match = optionMatches.find((m) => m.para === p);
if (match) {
currentOwner = match.optionIndex;
classified.push({ para: p, ownerOptionIndex: currentOwner, isOption: true });
}
else {
classified.push({ para: p, ownerOptionIndex: currentOwner, isOption: false });
}
}
// Step 4: Evaluate triggers to determine selected options
const selectedIndices = evaluateTriggers(group, data);
// Step 5 & 6: Remove unselected options + sub-clauses, mark selected as checked
let madeChanges = false;
const parasToRemove = new Set();
const appliedCounts = group.options.map(() => 0);
for (const item of classified) {
if (item.ownerOptionIndex === -1)
continue; // header — always keep
if (selectedIndices.has(item.ownerOptionIndex)) {
// Selected: mark the option paragraph as checked
if (item.isOption) {
setChecked(item.para, group.type);
appliedCounts[item.ownerOptionIndex]++;
madeChanges = true;
}
}
else {
// Unselected: collect for bookmark-aware removal
parasToRemove.add(item.para);
appliedCounts[item.ownerOptionIndex]++;
madeChanges = true;
}
}
removeWithBookmarkCleanup(doc, parasToRemove);
recordOptionApplied(stats, group, appliedCounts);
// Ensure at least one <w:p> remains in the cell (OOXML requirement)
const remainingParas = cell.getElementsByTagNameNS(W_NS, 'p');
if (remainingParas.length === 0) {
const newP = doc.createElementNS(W_NS, 'w:p');
cell.appendChild(newP);
}
return madeChanges;
}
/**
* Evaluate triggers against fill data and return the set of selected option indices.
*/
function evaluateTriggers(group, data) {
const selectedIndices = new Set();
if (group.type === 'radio') {
// Radio: first trigger that fires wins; if none, use default
let found = false;
for (let i = 0; i < group.options.length; i++) {
if (triggerFires(group.options[i].trigger, data)) {
selectedIndices.add(i);
found = true;
break;
}
}
if (!found) {
const defaultIdx = group.options.findIndex((o) => o.trigger === 'default');
if (defaultIdx >= 0)
selectedIndices.add(defaultIdx);
}
}
else {
// Checkbox: select each option whose trigger fires
for (let i = 0; i < group.options.length; i++) {
if (group.options[i].trigger === 'default')
continue;
if (triggerFires(group.options[i].trigger, data)) {
selectedIndices.add(i);
}
}
// Handle defaults for checkbox
if (selectedIndices.size === 0) {
for (let i = 0; i < group.options.length; i++) {
if (group.options[i].trigger === 'default') {
selectedIndices.add(i);
}
}
}
}
return selectedIndices;
}
/**
* Process a standalone checkbox group where each option may be in a different
* table cell. If trigger fires → mark checked; if not → remove the option
* paragraph and any non-option sub-clause paragraphs that follow it in the
* same cell.
*/
function processStandaloneGroup(doc, group, data, stats) {
const allParagraphs = doc.getElementsByTagNameNS(W_NS, 'p');
const selectedIndices = evaluateTriggers(group, data);
const matchCounts = group.options.map(() => 0);
const appliedCounts = group.options.map(() => 0);
let madeChanges = false;
for (let oi = 0; oi < group.options.length; oi++) {
const option = group.options[oi];
// Find the marker paragraph. Every match is counted (#720) even though only
// the first is acted on, so a drifted marker reports 0 rather than nothing.
let markerPara = null;
for (let pi = 0; pi < allParagraphs.length; pi++) {
const para = allParagraphs[pi];
const text = extractParagraphText(para);
if (text && hasOptionPrefix(text) && text.includes(option.marker)) {
matchCounts[oi]++;
if (!markerPara)
markerPara = para;
}
}
if (!markerPara)
continue;
if (selectedIndices.has(oi)) {
setChecked(markerPara, group.type);
madeChanges = true;
}
else {
// Remove: marker paragraph + consecutive non-option sub-clauses in same cell
const cell = findAncestor(markerPara, 'tc');
if (cell) {
const cellParas = cell.getElementsByTagNameNS(W_NS, 'p');
// Find marker index within cell
let markerIdx = -1;
for (let ci = 0; ci < cellParas.length; ci++) {
if (cellParas[ci] === markerPara) {
markerIdx = ci;
break;
}
}
if (markerIdx >= 0) {
// Collect sub-clause paragraphs after the marker (until next option or end)
const toRemove = [markerPara];
for (let ci = markerIdx + 1; ci < cellParas.length; ci++) {
const p = cellParas[ci];
const text = extractParagraphText(p);
if (text && hasOptionPrefix(text))
break; // next option — stop
toRemove.push(p);
}
removeWithBookmarkCleanup(doc, new Set(toRemove));
// Ensure at least one <w:p> remains in cell
const remaining = cell.getElementsByTagNameNS(W_NS, 'p');
if (remaining.length === 0) {
const newP = doc.createElementNS(W_NS, 'w:p');
cell.appendChild(newP);
}
}
}
else {
// No cell parent — just remove the paragraph
removeWithBookmarkCleanup(doc, new Set([markerPara]));
}
madeChanges = true;
}
// One paragraph is acted on per option here: the first match is marked or
// removed. `matchCount > appliedCount` therefore means duplicate marker
// matches survived untouched, which the caller can see.
appliedCounts[oi]++;
}
recordOptionMatches(stats, group, selectedIndices, matchCounts);
recordOptionApplied(stats, group, appliedCounts);
return madeChanges;
}
/**
* Remove embedded Word field constructs from a paragraph so no orphaned field
* survives a text substitution. Complex fields use runs containing <w:fldChar>
* (begin/separate/end) and <w:instrText>; simple fields use <w:fldSimple>.
*
* Without this, replacing a paragraph's text (e.g. with the "[Reserved]"
* placeholder) empties a cross-reference field's cached result run but leaves
* the field machinery intact, so Word/LibreOffice re-resolves the reference
* (e.g. a `REF` field re-rendering its bookmark target like "Exhibit A").
*/
function stripFieldConstructs(para) {
// Snapshot matches into an array before removal — getElementsByTagNameNS
// returns a live NodeList that shifts as nodes are removed.
const toRemove = [];
// Remove every <w:r> that carries field machinery (fldChar or instrText).
const runs = para.getElementsByTagNameNS(W_NS, 'r');
for (let i = 0; i < runs.length; i++) {
const r = runs[i];
if (r.getElementsByTagNameNS(W_NS, 'fldChar').length > 0 ||
r.getElementsByTagNameNS(W_NS, 'instrText').length > 0) {
toRemove.push(r);
}
}
// Remove any simple fields (<w:fldSimple>) wholesale.
const simple = para.getElementsByTagNameNS(W_NS, 'fldSimple');
for (let i = 0; i < simple.length; i++)
toRemove.push(simple[i]);
for (const el of toRemove)
el.parentNode?.removeChild(el);
}
/** Replace all <w:t> content in a paragraph with new text. First node gets the text, rest get empty string. */
function replaceParagraphText(para, newText) {
stripFieldConstructs(para);
const tElements = para.getElementsByTagNameNS(W_NS, 't');
// If stripping removed every text node (e.g. the paragraph was entirely a
// <w:fldSimple>), synthesize a run so newText is never silently dropped.
if (tElements.length === 0) {
const doc = para.ownerDocument;
if (doc) {
const r = doc.createElementNS(W_NS, 'w:r');
const t = doc.createElementNS(W_NS, 'w:t');
// Preserve any leading/trailing whitespace in the placeholder, matching
// how authored runs carry xml:space="preserve".
t.setAttribute('xml:space', 'preserve');
t.textContent = newText;
r.appendChild(t);
para.appendChild(r);
}
return;
}
for (let i = 0; i < tElements.length; i++) {
tElements[i].textContent = i === 0 ? newText : '';
}
}
/**
* Process a markerless group where option paragraphs are matched by content text
* without requiring [ ] / ( ) prefix markers.
*
* When selected → keep paragraph as-is.
* When unselected + replaceWith → replace paragraph text, remove sub-clause paragraphs.
* When unselected + no replaceWith → remove paragraph + sub-clause paragraphs.
*/
function processMarkerlessGroup(doc, group, data, stats, isMainDocument, resolveNumbering) {
const selectedIndices = evaluateTriggers(group, data);
const matchCounts = group.options.map(() => 0);
const appliedCounts = group.options.map(() => 0);
let madeChanges = false;
const parasToRemove = new Set();
for (let oi = 0; oi < group.options.length; oi++) {
const option = group.options[oi];
// Selected bracket actions are body-only, like bounded removals. This
// gives their exact-one assertion a single deterministic OOXML part.
if (option.selectedAction && !isMainDocument)
continue;
if (option.removal) {
// Whole tables and sections are body-block concepts. Ignoring headers and
// footers also makes the exact-one assertion global for the only part in
// which bounded removal is valid.
if (!isMainDocument)
continue;
const selected = selectedIndices.has(oi);
const count = applyBoundedRemoval(doc, group.id, option.removal, !selected);
matchCounts[oi] += count;
if (!selected) {
appliedCounts[oi]++;
madeChanges = true;
}
continue;
}
// Snapshot all paragraphs before mutating to avoid live NodeList issues
const allParagraphs = doc.getElementsByTagNameNS(W_NS, 'p');
const matchedParas = [];
const normalizedMarkerText = normalizeQuotes(option.marker);
for (let pi = 0; pi < allParagraphs.length; pi++) {
const para = allParagraphs[pi];
const text = extractParagraphText(para);
if (text && normalizeQuotes(text).includes(normalizedMarkerText)) {
matchedParas.push(para);
}
}
matchCounts[oi] += matchedParas.length;
if (option.selectedAction && matchedParas.length !== 1) {
throw new Error(`[selector] Group "${group.id}" selected action for marker "${option.marker}" matched ${matchedParas.length} paragraphs (expected 1)`);
}
// #720: a zero-match UNSELECTED option is not a benign no-op — the
// alternative it was meant to delete survives into the filled document.
// The count recorded above is what lets the caller reject that outcome
// instead of shipping a document carrying both alternatives.
if (matchedParas.length === 0)
continue;
if (selectedIndices.has(oi)) {
if (option.selectedAction === 'unwrap_brackets') {
const markerPara = matchedParas[0];
const paragraphText = normalizeQuotes(getParagraphText(markerPara));
const markerText = normalizeQuotes(option.marker);
const start = paragraphText.indexOf(markerText);
if (start < 0) {
throw new Error(`[selector] Group "${group.id}" could not locate selected bracket marker`);
}
// Delete only the two delimiter characters. Closing-first keeps the
// opening index stable and preserves every interior run and REF field.
replaceParagraphTextRange(markerPara, start + markerText.length - 1, start + markerText.length, '');
replaceParagraphTextRange(markerPara, start, start + 1, '');
appliedCounts[oi]++;
madeChanges = true;
}
continue;
}
// Unselected — inline mode: delete/replace marker text within the paragraph
if (group.inline) {
for (const markerPara of matchedParas) {
const normalizedMarker = normalizeQuotes(option.marker);
const replacement = option.replaceWith ?? '';
const globalPara = markerPara;
let text = normalizeQuotes(getParagraphText(globalPara));
let safety = 0;
// Tracked separately from `madeChanges` so a paragraph that matched but
// could not be spliced (both the range edit and the fallback failed)
// is reported as unremoved rather than silently kept (#720).
let paraEdited = false;
while (safety++ < 50) {
const idx = text.indexOf(normalizedMarker);
if (idx === -1)
break;
try {
replaceParagraphTextRange(globalPara, idx, idx + normalizedMarker.length, replacement);
// An omitted inline option can strand its separator before the
// sentence's punctuation. Repair only this deletion boundary, not
// unrelated punctuation/spacing elsewhere in the document.
if (replacement === '') {
const remaining = getParagraphText(globalPara);
const left = remaining.slice(0, idx).match(/ +$/);
const right = remaining.slice(idx).match(/^ *(?=[.,;:!?])/);
if (right && (left || right[0])) {
const start = idx - (left?.[0].length ?? 0);
const end = idx + right[0].length;
if (start > 0) {
try {
replaceParagraphTextRange(globalPara, start, end, '');
}
catch (error) {
// Do not flatten a field result or other protected Word
// structure merely to improve whitespace.
if (!(error instanceof SafeDocxError))
throw error;
}
}
}
}
madeChanges = true;
paraEdited = true;
}
catch (e) {
if (e instanceof SafeDocxError) {
// Fallback: formatting-destructive text splice via xmldom w:t elements
const rawText = extractParagraphText(markerPara);
const rawIdx = normalizeQuotes(rawText).indexOf(normalizedMarker);
if (rawIdx !== -1) {
const newText = rawText.slice(0, rawIdx) + replacement + rawText.slice(rawIdx + normalizedMarker.length);
replaceParagraphText(markerPara, newText);
madeChanges = true;
paraEdited = true;
}
}
break;
}
text = normalizeQuotes(getParagraphText(globalPara));
}
if (paraEdited)
appliedCounts[oi]++;
}
continue;
}
// Unselected — process each matched paragraph (paragraph-level deletion)
for (const markerPara of matchedParas) {
const parent = markerPara.parentNode;
if (!parent)
continue;
// Collect sub-clause paragraphs following the match
const siblings = [];
const childNodes = parent.childNodes;
for (let ci = 0; ci < childNodes.length; ci++) {
const node = childNodes[ci];
if (node.nodeType !== 1)
continue;
const el = node;
if (el.localName !== 'p' || el.namespaceURI !== W_NS)
continue;
siblings.push(el);
}
const markerIdx = siblings.indexOf(markerPara);
if (markerIdx < 0)
continue;
// Walk forward to collect sub-clause paragraphs
const subClauses = [];
const customStopRe = group.subClauseStopPatterns?.length
? new RegExp(group.subClauseStopPatterns.map(p => `(?:${p})`).join('|'), 'i')
: null;
// Get marker paragraph's numbering level for level-aware stop
const markerIlvl = getNumberingLevel(markerPara, resolveNumbering);
for (let si = markerIdx + 1; si < siblings.length; si++) {
const p = siblings[si];
// Stop at auto-numbered paragraphs at same or higher level
if (hasAutoNumbering(p, resolveNumbering, markerIlvl !== -1 ? markerIlvl : undefined))
break;
const text = extractParagraphText(p);
// Stop at next section heading or another option's marker
if (text) {
const isAnotherMarker = group.options.some((o) => text.includes(o.marker));
// Stop at what looks like a section heading (e.g., "(c)", "1.3", "SECTION")
const isSectionHeading = /^\(?[a-z]\)|^\d+\.\d+|^SECTION\b|^ARTICLE\b/i.test(text);
const isCustomStop = customStopRe ? customStopRe.test(text) : false;
if (isAnotherMarker || isSectionHeading || isCustomStop)
break;
}
subClauses.push(p);
}
if (option.replaceWith !== undefined) {
// Replace matched paragraph text; sub-clauses deferred for removal
replaceParagraphText(markerPara, option.replaceWith);
}
else {
// Marker paragraph deferred for removal
parasToRemove.add(markerPara);
}
for (const p of subClauses) {
parasToRemove.add(p);
}
appliedCounts[oi]++;
madeChanges = true;
}
}
// Deferred removal with bookmark cleanup
removeWithBookmarkCleanup(doc, parasToRemove);
// NOTE on ordering: options are matched against the document as it stands
// when their turn comes, so an earlier option's replacement can change a
// later option's `matchCount`. That is deliberate — the counts describe what
// the processor actually saw, so `matchCount` and `appliedCount` stay
// consistent and cannot manufacture a phantom "matched but never removed".
recordOptionMatches(stats, group, selectedIndices, matchCounts);
recordOptionApplied(stats, group, appliedCounts);
return madeChanges;
}
/** Check if a paragraph has Word auto-numbering at or above the given level. */
function hasAutoNumbering(para, resolveNumbering, maxIlvl) {
const numbering = resolveNumbering(para);
return numbering !== null && (maxIlvl === undefined || numbering.ilvl <= maxIlvl);
}
/** Get the numbering level (ilvl) of a paragraph, or -1 if not numbered. */
function getNumberingLevel(para, resolveNumbering) {
return resolveNumbering(para)?.ilvl ?? -1;
}
/** Walk up the DOM to find an ancestor with the given local name. */
function findAncestor(node, localName) {
let current = node.parentNode;
while (current) {
if (current.nodeType === 1) {
const element = current;
if (element.localName === localName && element.namespaceURI === W_NS) {
return element;
}
}
current = current.parentNode;
}
return null;
}
//# sourceMappingURL=selector.js.map