open-agreements
Version:
Open-source legal template filling CLI and library
223 lines • 8.28 kB
JavaScript
import { buildCleanToRawOffsetMap } from './document_view.js';
import { computeContentFingerprint } from './content_fingerprint.js';
const SPAN_KINDS = new Set(['regex', 'contextual', 'fingerprint']);
/** Raw visible text of a node — the fingerprint basis and offset coordinate space. */
function rawTextOf(node) {
return node.raw_text ?? node.text;
}
function dedupeFlags(flags) {
return Array.from(new Set(flags.split(''))).join('');
}
function collectRegexSpans(nodes, pattern, flags, group) {
const needIndices = group > 0;
const reFlags = dedupeFlags(`${flags ?? ''}g${needIndices ? 'd' : ''}`);
const spans = [];
for (const node of nodes) {
const re = new RegExp(pattern, reFlags);
const text = node.clean_text;
let m;
while ((m = re.exec(text)) !== null) {
let cs;
let ce;
if (needIndices) {
const idx = m.indices?.[group];
if (!idx) {
if (m.index === re.lastIndex)
re.lastIndex++;
continue;
}
cs = idx[0];
ce = idx[1];
}
else {
cs = m.index;
ce = m.index + m[0].length;
}
spans.push({ node, nodeId: node.id, cleanStart: cs, cleanEnd: ce });
if (m.index === re.lastIndex)
re.lastIndex++;
}
}
return spans;
}
function collectContextualSpans(nodes, step) {
const ctxRe = new RegExp(step.contextPattern);
const rowRe = step.rowLabelPattern ? new RegExp(step.rowLabelPattern) : null;
const spans = [];
for (const node of nodes) {
if (!ctxRe.test(node.clean_text))
continue;
if (rowRe && !rowRe.test(node.table_context?.col_header ?? ''))
continue;
const tre = new RegExp(step.targetPattern, 'g');
const text = node.clean_text;
let m;
while ((m = tre.exec(text)) !== null) {
spans.push({ node, nodeId: node.id, cleanStart: m.index, cleanEnd: m.index + m[0].length });
if (m.index === tre.lastIndex)
tre.lastIndex++;
}
}
return spans;
}
function collectFingerprintNodes(nodes, fingerprint) {
return nodes.filter((n) => computeContentFingerprint(rawTextOf(n)) === fingerprint);
}
function headingMatches(node, step) {
let matched = false;
if (step.headingStyleId !== undefined) {
if (node.paragraph_style_id !== step.headingStyleId)
return false;
matched = true;
}
if (step.headingText !== undefined) {
if (node.heading?.text !== step.headingText)
return false;
matched = true;
}
if (step.headingRegex !== undefined) {
if (!new RegExp(step.headingRegex).test(node.heading?.text ?? ''))
return false;
matched = true;
}
return matched;
}
/**
* Narrow `nodes` to the region selected by one `section` step. Returns null when
* the heading does not match EXACTLY one node (zero or many → unresolved).
*/
function narrowToSection(nodes, step) {
const headingIdx = [];
for (let i = 0; i < nodes.length; i++) {
if (headingMatches(nodes[i], step))
headingIdx.push(i);
}
if (headingIdx.length !== 1)
return null;
const start = headingIdx[0];
const startLevel = nodes[start].heading?.level ?? null;
const untilLevel = step.untilLevel ?? startLevel;
let end = nodes.length;
if (untilLevel !== null) {
for (let j = start + 1; j < nodes.length; j++) {
const lvl = nodes[j].heading?.level;
if (lvl != null && lvl <= untilLevel) {
end = j;
break;
}
}
}
return nodes.slice(start, end);
}
function narrowScope(view, scope) {
let nodes = view;
for (const step of scope) {
if (step.kind !== 'section') {
throw new Error(`Locator scope steps must be 'section'; got '${step.kind}'`);
}
const narrowed = narrowToSection(nodes, step);
if (narrowed === null)
return null;
nodes = narrowed;
}
return nodes;
}
function resolvePrimary(nodes, step) {
if (step.kind === 'fingerprint') {
const hits = collectFingerprintNodes(nodes, step.contentFingerprint);
if (hits.length !== 1)
return null;
const node = hits[0];
return { nodeId: node.id, start: 0, end: rawTextOf(node).length };
}
let spans;
if (step.kind === 'regex') {
spans = collectRegexSpans(nodes, step.pattern, step.flags, step.group ?? 0);
}
else if (step.kind === 'contextual') {
spans = collectContextualSpans(nodes, step);
}
else {
// 'section' is rejected by validateLocator before we get here.
return null;
}
if (spans.length !== 1)
return null;
const span = spans[0];
if (span.cleanEnd <= span.cleanStart)
return null; // zero-length match is invalid
const map = buildCleanToRawOffsetMap(span.node);
return { nodeId: span.nodeId, start: map[span.cleanStart], end: map[span.cleanEnd] };
}
function resolveAssertion(nodes, step, primary) {
if (step.kind === 'fingerprint') {
const hits = collectFingerprintNodes(nodes, step.contentFingerprint);
if (hits.length !== 1) {
return { ok: false, kind: 'fingerprint', detail: `expected exactly 1 node, found ${hits.length}` };
}
const ok = hits[0].id === primary.nodeId;
return { ok, kind: 'fingerprint', detail: ok ? undefined : `node ${hits[0].id} != primary node ${primary.nodeId}` };
}
let spans;
if (step.kind === 'regex') {
spans = collectRegexSpans(nodes, step.pattern, step.flags, step.group ?? 0);
}
else if (step.kind === 'contextual') {
spans = collectContextualSpans(nodes, step);
}
else {
return { ok: false, kind: step.kind, detail: "'section' is not a valid assertion kind" };
}
if (spans.length !== 1) {
return { ok: false, kind: step.kind, detail: `expected exactly 1 span, found ${spans.length}` };
}
const span = spans[0];
if (span.cleanEnd <= span.cleanStart) {
return { ok: false, kind: step.kind, detail: 'zero-length match' };
}
const map = buildCleanToRawOffsetMap(span.node);
const start = map[span.cleanStart];
const end = map[span.cleanEnd];
const ok = span.nodeId === primary.nodeId && start === primary.start && end === primary.end;
return {
ok,
kind: step.kind,
detail: ok
? undefined
: `span {${span.nodeId},${start},${end}} != primary {${primary.nodeId},${primary.start},${primary.end}}`,
};
}
function validateLocator(locator) {
if (!SPAN_KINDS.has(locator.primary.kind)) {
throw new Error(`Locator primary must be regex | contextual | fingerprint; got '${locator.primary.kind}'`);
}
for (const a of locator.assertions ?? []) {
if (!SPAN_KINDS.has(a.kind)) {
throw new Error(`Locator assertion must be regex | contextual | fingerprint; got '${a.kind}'`);
}
}
for (const s of locator.scope ?? []) {
if (s.kind !== 'section') {
throw new Error(`Locator scope steps must be 'section'; got '${s.kind}'`);
}
}
}
/**
* Resolve a {@link Locator} against a document view. Deterministic: the same
* `(view, locator)` always yields the same result, with no randomness, scoring,
* or tie-breaking.
*/
export function resolveLocator(view, locator) {
validateLocator(locator);
const scoped = locator.scope && locator.scope.length > 0 ? narrowScope(view, locator.scope) : view;
if (scoped === null) {
return { match: null, unresolved: true, assertionResults: [] };
}
const match = resolvePrimary(scoped, locator.primary);
if (match === null) {
return { match: null, unresolved: true, assertionResults: [] };
}
const assertionResults = (locator.assertions ?? []).map((a) => resolveAssertion(scoped, a, match));
return { match, unresolved: false, assertionResults };
}
//# sourceMappingURL=locator.js.map