open-agreements
Version:
Open-source legal template filling CLI and library
762 lines • 35.8 kB
JavaScript
import { z } from 'zod';
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import yaml from 'js-yaml';
import { conditionalPredicates } from './conditional-predicates.js';
import { INPUT_VALUE_FORMAT_IDS, INPUT_VALUE_FORMATS } from './input-value-formats.js';
const ConditionalPredicateSchema = z.object({
field: z.string().min(1),
equals: z.union([z.string(), z.number().finite(), z.boolean()]),
}).strict();
/**
* License values accepted by template metadata.
*
* CC-BY-4.0 and CC0-1.0 templates may be redistributed as OpenAgreements
* content. CC-BY-ND-4.0 templates are vendored only when unmodified and must
* declare `allow_derivatives: false`.
*/
export const LicenseEnum = z.enum(['CC-BY-4.0', 'CC0-1.0', 'CC-BY-ND-4.0']);
/**
* How a managed artifact ships (S3 source/rights restructure, #1249):
* `bundled` = the DOCX is committed in-repo; `linked` = only transformation
* instructions ship and the source is fetched from its upstream URL.
*/
export const DistributionEnum = z.enum(['bundled', 'linked']);
/** Whether a directory holds a fillable template or a field-selector. */
export const ArtifactTypeEnum = z.enum(['template', 'field-selector']);
/**
* Maturity / support expectation for a first-party template (open-agreements#243).
*
* Distinct from the SemVer `version`, which signals the *past* (was a release a
* breaking change?). `stability` signals the *future* support expectation:
* - `experimental` — legal logic still settling; expect change.
* - `beta` — schema and structure stable; legal text still hardening.
* - `stable` — graduated (== SemVer 1.0): DTSA parity holds where applicable,
* high-risk cover-term drafting notes are complete, and two consecutive
* minor releases have shipped without legal-text rework.
*
* First-party (`openagreements-*`) templates declare this explicitly; it is
* optional so vendored third-party templates (whose maturity is upstream-derived)
* and any pre-existing metadata still validate.
*/
export const StabilityEnum = z.enum(['experimental', 'beta', 'stable']);
/** Field kinds supported by template, external-template, and fieldSelector metadata. */
const FieldTypeEnum = z.enum(['string', 'date', 'number', 'boolean', 'enum', 'array', 'multiselect']);
const MULTISELECT_OPTION_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
export const FieldDefinitionSchema = z.lazy(() => z.object({
name: z.string(),
type: FieldTypeEnum,
description: z.string(),
display_label: z.string().optional(),
// Accept YAML-native scalar defaults (`default: false`, `default: 5`) by
// coercing to their string form before validation. Generated template
// metadata serializes booleans/numbers natively; downstream code already
// treats `default` as a string (e.g. JSON.parse(field.default), the
// `=== 'false'` checks), and String(false) === 'false' is value-preserving.
default: z.preprocess((v) => (typeof v === 'boolean' || typeof v === 'number' ? String(v) : v), z.string().optional()),
default_value_rationale: z.string().optional(),
options: z.array(z.string()).optional(),
derive_booleans: z.boolean().optional(),
section: z.string().optional(),
items: z.array(FieldDefinitionSchema).nonempty().optional(),
required_when: z.union([
ConditionalPredicateSchema,
z.object({ all_of: z.array(ConditionalPredicateSchema).min(2) }).strict()
.refine(condition => new Set(condition.all_of.map(predicate => predicate.field)).size === condition.all_of.length, 'all_of must contain unique caller field predicates'),
]).optional(),
value_format: z.enum(INPUT_VALUE_FORMAT_IDS).optional(),
statutory_compliance_representation: z.boolean().optional(),
authority_url: z.string().optional(),
confirm_note: z.string().optional(),
}).superRefine((field, ctx) => {
if (field.value_format) {
if (field.type !== 'string') {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['value_format'], message: 'value_format requires a string field' });
}
if (field.default !== undefined && !new RegExp(INPUT_VALUE_FORMATS[field.value_format].pattern).test(field.default)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['default'], message: 'Default does not match value_format' });
}
}
if ((field.type === 'enum' || field.type === 'multiselect') &&
(field.options === undefined || field.options.length === 0)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['options'],
message: `Fields with type "${field.type}" must have a non-empty options array`,
});
}
if (field.type === 'multiselect' && field.options) {
const seenOptions = new Set();
field.options.forEach((option, index) => {
if (!MULTISELECT_OPTION_RE.test(option)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['options', index],
message: 'Multiselect options must be valid identifiers matching /^[A-Za-z_][A-Za-z0-9_]*$/',
});
}
if (seenOptions.has(option)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['options', index],
message: `Duplicate multiselect option "${option}"`,
});
return;
}
seenOptions.add(option);
});
}
if (field.derive_booleans !== undefined && field.type !== 'multiselect') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['derive_booleans'],
message: 'derive_booleans is only valid for fields with type "multiselect"',
});
}
if (field.items !== undefined && field.type !== 'array') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['items'],
message: 'Only fields with type "array" may define nested items',
});
}
// `statutory_compliance_representation` is a NARROW opt-in category for the
// few boolean reps whose truth is a statutory precondition to
// enforceability. Enforce its shape so the renderer's `confirm=` mechanism
// and the get_template confirmation surface stay sound.
if (field.statutory_compliance_representation === true) {
if (field.type !== 'boolean') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['statutory_compliance_representation'],
message: 'statutory_compliance_representation is only valid on a boolean field',
});
}
if (field.default !== 'false') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: "statutory_compliance_representation fields must declare default: 'false' (a compliance fact is unconfirmed until a human confirms it)",
});
}
if (field.authority_url === undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['authority_url'],
message: 'statutory_compliance_representation fields must declare an authority_url (statute / practice-note link)',
});
}
else if (!/^https?:\/\/\S+$/.test(field.authority_url)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['authority_url'],
message: 'authority_url must be an http(s) URL',
});
}
// confirm_note is the SSOT for the rendered `[CONFIRM …]` bracket note, so
// it must be present and non-empty (after trimming) on these fields.
if (field.confirm_note === undefined || field.confirm_note.trim().length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['confirm_note'],
message: 'statutory_compliance_representation fields must declare a non-empty confirm_note (the short reason shown in the rendered [CONFIRM …] bracket)',
});
}
}
else {
// Keep these properties scoped: they have no meaning outside the
// statutory_compliance_representation category.
if (field.authority_url !== undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['authority_url'],
message: 'authority_url is only valid on a statutory_compliance_representation field',
});
}
if (field.confirm_note !== undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['confirm_note'],
message: 'confirm_note is only valid on a statutory_compliance_representation field',
});
}
}
if (field.default !== undefined) {
if (field.type === 'number' && isNaN(Number(field.default))) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: 'Default value must be valid for the declared field type',
});
}
if (field.type === 'boolean' && field.default !== 'true' && field.default !== 'false') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: 'Default value must be valid for the declared field type',
});
}
if (field.type === 'multiselect') {
let parsedDefault;
try {
parsedDefault = JSON.parse(field.default);
}
catch {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: 'Default value must be a JSON-encoded array of strings for multiselect fields',
});
return;
}
if (!Array.isArray(parsedDefault)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: 'Default value must be a JSON-encoded array of strings for multiselect fields',
});
return;
}
const seenDefaults = new Set();
parsedDefault.forEach((entry) => {
if (typeof entry !== 'string') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: 'Default value must be a JSON-encoded array of strings for multiselect fields',
});
return;
}
if (seenDefaults.has(entry)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: `Default value contains duplicate multiselect option "${entry}"`,
});
return;
}
seenDefaults.add(entry);
if (field.options && !field.options.includes(entry)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['default'],
message: `Default value references option "${entry}" which is not declared in options`,
});
}
});
}
}
}));
/** Closed set of provenance roles accepted in template `credits` entries. */
const TemplateCreditRoleEnum = z.enum([
'drafter',
'drafting_editor',
'reviewer',
'maintainer',
]);
/** Optional template provenance entry surfaced by CLI discovery output. */
const TemplateCreditSchema = z.object({
name: z.string(),
role: TemplateCreditRoleEnum,
profile_url: z.string().url().optional(),
});
export const TemplateCapabilityManifestSchema = z.object({
artifact_kind: z.enum(['agreement', 'consent', 'notice', 'letter', 'checklist', 'policy', 'other']).default('other'),
capabilities: z.array(z.enum(['create', 'review', 'render'])).nonempty().default(['review']),
party_roles: z.array(z.string().trim().min(1)).default([]),
signature_roles: z.array(z.string().trim().min(1)).default([]),
mutation_policy: z.enum(['terms', 'fields_only', 'immutable']).default('immutable'),
maturity: z.enum(['experimental', 'beta', 'stable']).default('experimental'),
});
function validatePriorityFields(fields, priorityFields, ctx) {
validateConditionalRequirements(fields, ctx);
const fieldNames = new Set(fields.map((field) => field.name));
const seen = new Set();
priorityFields.forEach((fieldName, index) => {
if (seen.has(fieldName)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['priority_fields', index],
message: `Duplicate priority field "${fieldName}"`,
});
return;
}
seen.add(fieldName);
if (!fieldNames.has(fieldName)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['priority_fields', index],
message: `Priority field "${fieldName}" is not defined in fields`,
});
}
});
}
function validateConditionalRequirements(fields, ctx) {
const byName = new Map(fields.map((field) => [field.name, field]));
const visit = (items, path, nested) => {
items.forEach((field, index) => {
const at = [...path, index];
if (field.required_when) {
for (const predicate of conditionalPredicates(field.required_when)) {
const controller = byName.get(predicate.field);
const expectedType = controller?.type === 'boolean' ? 'boolean'
: controller?.type === 'number' ? 'number' : 'string';
if (nested || !controller || controller.name === field.name ||
['array', 'multiselect'].includes(controller.type) ||
typeof predicate.equals !== expectedType ||
(controller.type === 'enum' && !controller.options?.includes(String(predicate.equals)))) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [...at, 'required_when'],
message: 'required_when must reference another top-level scalar field with a compatible equals value; nested requirements are unsupported' });
}
}
if (field.default !== undefined || ['array', 'multiselect'].includes(field.type)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [...at, 'required_when'],
message: 'Conditionally required fields must be scalar inputs without defaults' });
}
}
if (field.items)
visit(field.items, [...at, 'items'], true);
});
};
visit(fields, ['fields'], false);
}
/** Object-shaped fill data cannot represent duplicate property names. */
function validateUniqueFieldNames(fields, ctx, path = ['fields']) {
const seen = new Map();
fields.forEach((field, index) => {
const previous = seen.get(field.name);
if (previous !== undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [...path, index, 'name'],
message: `Duplicate field name "${field.name}" (first declared at index ${previous})`,
});
}
else {
seen.set(field.name, index);
}
if (field.items)
validateUniqueFieldNames(field.items, ctx, [...path, index, 'items']);
});
}
function validateDerivedBooleanCollisions(fields, ctx) {
const topLevelFieldNames = new Set(fields.map((field) => field.name));
const derivedKeyOwners = new Map();
fields.forEach((field, fieldIndex) => {
if (field.type !== 'multiselect' || field.derive_booleans !== true || !field.options) {
return;
}
field.options.forEach((option, optionIndex) => {
const derivedKey = `${option}_enabled`;
if (topLevelFieldNames.has(derivedKey)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['fields', fieldIndex, 'options', optionIndex],
message: `Derived boolean key "${derivedKey}" from multiselect "${field.name}" collides with another top-level field name`,
});
}
const existingOwner = derivedKeyOwners.get(derivedKey);
if (existingOwner) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['fields', fieldIndex, 'options', optionIndex],
message: `Derived boolean key "${derivedKey}" from multiselect "${field.name}" collides with derived key from multiselect "${existingOwner}"`,
});
return;
}
derivedKeyOwners.set(derivedKey, field.name);
});
});
}
/**
* Base metadata required for first-party and external templates.
*
* Template directories must provide `metadata.yaml` with a non-empty display
* name, source URL, version, license, derivative flag, attribution text, and
* field definitions. `category` is optional discovery grouping metadata.
* `priority_fields` reference required fill fields. `credits` records
* contributor provenance and defaults to an empty array; `derived_from` is
* expository provenance text and does not affect licensing.
*/
const TemplateMetadataBaseSchema = z.object({
name: z.string().trim().min(1, 'name must be a non-empty string (used as display_name on list_templates)'),
description: z.string().optional(),
category: z.string().optional(),
source_url: z.string().url(),
version: z.string(),
license: LicenseEnum,
allow_derivatives: z.boolean(),
attribution_text: z.string(),
// Distribution/artifact metadata surfaced by the S3 source/rights restructure
// (#1249). `distribution` records how the artifact ships (bundled DOCX vs.
// linked upstream source); `artifact_type` distinguishes a fillable template
// from a field-selector. Both are optional so pre-restructure metadata still
// validates.
distribution: DistributionEnum.optional(),
artifact_type: ArtifactTypeEnum.optional(),
// Maturity / support signal (open-agreements#243). Optional so vendored
// third-party and pre-#243 metadata still validate; first-party templates
// declare it explicitly. All first-party templates default to `experimental`
// under the 0.x posture — the `stable` label stays gated on legal-context#135.
stability: StabilityEnum.optional(),
fields: z.array(FieldDefinitionSchema),
priority_fields: z.array(z.string()).default([]),
credits: z.array(TemplateCreditSchema).default([]),
derived_from: z.string().optional(),
...TemplateCapabilityManifestSchema.shape,
});
export const TemplateMetadataSchema = TemplateMetadataBaseSchema.superRefine((meta, ctx) => {
validateUniqueFieldNames(meta.fields, ctx);
validatePriorityFields(meta.fields, meta.priority_fields, ctx);
validateDerivedBooleanCollisions(meta.fields, ctx);
});
// --- External template schemas ---
/**
* Metadata for vendored external templates.
*
* `source_sha256` records the checksum of the unmodified upstream document so
* validation can verify provenance for no-derivatives templates before local
* transient fills or CI license checks rely on that source.
*/
export const ExternalMetadataSchema = TemplateMetadataBaseSchema.extend({
source_sha256: z.string(),
}).superRefine((meta, ctx) => {
validateUniqueFieldNames(meta.fields, ctx);
validatePriorityFields(meta.fields, meta.priority_fields, ctx);
validateDerivedBooleanCollisions(meta.fields, ctx);
});
// --- FieldSelector schemas ---
/** Declarative cleaner configuration for fieldSelector DOCX preprocessing. */
export const CleanConfigSchema = z.object({
removeFootnotes: z.boolean().default(false),
removeBeforePattern: z.string().optional(),
removeParagraphPatterns: z.array(z.string()).default([]),
removeRanges: z.array(z.object({
start: z.string(),
end: z.string(),
})).default([]),
clearParts: z.array(z.string()).default([]),
/**
* Remove narrowly identified paragraphs from a header/footer story.
*
* Story cleanup is opt-in because headers and footers may contain operative
* letterhead, dates, or signature-facing text. Each rule names one OOXML
* story part, supplies a paragraph regex, and declares the exact number of
* expected matches. Source drift therefore fails closed instead of clearing
* an entire story part or silently leaving source guidance behind.
*/
removeStoryParagraphs: z.array(z.object({
id: z.string().min(1),
part: z.string().regex(/^(?:word\/)?(?:header|footer)\d+\.xml$/),
pattern: z.string().min(1),
expected_matches: z.number().int().positive(),
})).optional(),
/**
* Strip <w:drawing>/<w:pict> runs from header/footer parts whose referenced
* media exceeds the size threshold, plus the orphaned relationships and media
* parts. Targets image-only content (e.g. a full-page "how to use this
* template" screenshot anchored in a header) that text-anchored removeRanges
* cannot see. Small spacer drawings (Common Paper exports carry ~146-byte
* spacer PNGs) are preserved by the threshold.
*/
removeHeaderFooterDrawings: z.boolean().optional(),
/**
* Size threshold (bytes) for removeHeaderFooterDrawings. Drawings whose
* largest referenced media part exceeds this are stripped. Default 51200
* (50 KB): the largest benign media across the bundled corpus is 146 bytes,
* while the known-bad artifact class (instructions-page screenshots) starts
* around 125 KB.
*/
headerFooterDrawingMinBytes: z.number().int().positive().optional(),
/**
* Post-clean pass: drop leading body paragraphs that contain no text and no
* drawing/object content. Header/footer references on a removed paragraph's
* <w:sectPr> are transplanted forward onto the next section properties so
* downstream sections keep their inherited headers/footers.
*/
removeEmptyLeadingParagraphs: z.boolean().optional(),
});
/**
* Whether a clean config performs any operation capable of removing (or
* exposing) body content — and can therefore strand a textless first body
* paragraph (blank first page/section). Used to gate the verifier's
* first-body-paragraph guard so cleaner capabilities and verifier coverage
* cannot silently diverge.
*
* `removeFootnotes` is deliberately excluded: it removes footnote-reference
* runs and footnote bodies, not body paragraphs; a first body paragraph whose
* only content is a footnote reference marker does not occur in practice.
* `clearParts` is excluded because it targets whole header/footer parts, not
* the document body.
*/
export function cleanConfigRemovesBodyContent(config) {
return Boolean(config.removeEmptyLeadingParagraphs ||
config.removeBeforePattern ||
(config.removeRanges && config.removeRanges.length > 0) ||
(config.removeParagraphPatterns && config.removeParagraphPatterns.length > 0));
}
const NormalizeSourceDriftSchema = z.discriminatedUnion('stage', [
z.object({ stage: z.literal('raw_source') }).strict(),
z.object({
stage: z.literal('post_transform'),
prerequisites: z.array(z.string().min(1)).min(1),
}).strict(),
]);
export const DeclarativeParagraphNormalizeRuleSchema = z.object({
id: z.string(),
section_heading: z.string(),
section_heading_any: z.array(z.string()).optional(),
ignore_heading: z.boolean().optional(),
paragraph_contains: z.string(),
paragraph_end_contains: z.string().optional(),
replacements: z.record(z.string(), z.string()).optional(),
trim_unmatched_trailing_bracket: z.boolean().optional(),
expected_min_matches: z.number().int().nonnegative().optional(),
expected_max_matches: z.number().int().nonnegative().optional(),
source_drift: NormalizeSourceDriftSchema.optional(),
}).strict();
const BUILTIN_NORMALIZE_PREREQUISITES = new Set(['clean', 'selection', 'fill']);
const NumberingContinuationHeadingSchema = z.object({
anchor: z.string().trim().min(1),
num_id: z.string().regex(/^[1-9]\d*$/),
expected_abstract_num_id: z.string().regex(/^(0|[1-9]\d*)$/),
ilvl: z.number().int().min(1).max(8),
expected_starts: z.record(z.string().regex(/^[0-8]$/), z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)),
}).strict();
export const NumberingContinuationsSchema = z.object({
source_sha256: z.string().regex(/^[a-f0-9]{64}$/),
source_num_id: z.string().regex(/^[1-9]\d*$/),
headings: z.array(NumberingContinuationHeadingSchema).min(1),
}).strict().superRefine((config, ctx) => {
const ids = new Set();
const anchors = new Set();
config.headings.forEach((heading, index) => {
const anchor = heading.anchor.replaceAll('[', '').replaceAll(']', '').replace(/\s+/g, ' ').trim().replace(/\.$/, '');
if (!anchor || anchors.has(anchor) || ids.has(heading.num_id) || heading.num_id === config.source_num_id) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['headings', index], message: 'continuation anchors and instances must be unique and distinct from the source instance' });
}
anchors.add(anchor);
ids.add(heading.num_id);
});
});
export const NormalizeConfigSchema = z.object({
paragraph_rules: z.array(DeclarativeParagraphNormalizeRuleSchema).default([]),
numbering_continuations: NumberingContinuationsSchema.optional(),
}).strict().superRefine((config, ctx) => {
const idIndexes = new Map();
config.paragraph_rules.forEach((rule, index) => {
const indexes = idIndexes.get(rule.id) ?? [];
indexes.push(index);
idIndexes.set(rule.id, indexes);
});
for (const [id, indexes] of idIndexes) {
if (indexes.length > 1) {
for (const index of indexes) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'id'], message: `duplicate normalize rule id creates ambiguous prerequisite: ${id}` });
}
}
}
const dependencies = new Map();
config.paragraph_rules.forEach((rule, index) => {
const declaration = rule.source_drift;
if (declaration?.stage !== 'post_transform')
return;
if (rule.expected_min_matches === undefined || rule.expected_max_matches === undefined) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'source_drift'], message: 'post_transform rules require expected_min_matches and expected_max_matches' });
}
else if (rule.expected_max_matches < rule.expected_min_matches) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'expected_max_matches'], message: 'expected_max_matches must be greater than or equal to expected_min_matches' });
}
const ruleDependencies = [];
for (const prerequisite of declaration.prerequisites) {
if (BUILTIN_NORMALIZE_PREREQUISITES.has(prerequisite))
continue;
if (!prerequisite.startsWith('rule:')) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'source_drift', 'prerequisites'], message: `unknown post-transform prerequisite: ${prerequisite}` });
continue;
}
const prerequisiteId = prerequisite.slice('rule:'.length);
const prerequisiteIndexes = idIndexes.get(prerequisiteId);
if (!prerequisiteIndexes || prerequisiteIndexes.length !== 1) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'source_drift', 'prerequisites'], message: `unknown or ambiguous normalize rule prerequisite: ${prerequisite}` });
continue;
}
ruleDependencies.push(prerequisiteId);
if (prerequisiteIndexes[0] >= index) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', index, 'source_drift', 'prerequisites'], message: `normalize rule prerequisite must precede dependent rule: ${prerequisite}` });
}
}
dependencies.set(rule.id, ruleDependencies);
});
const visiting = new Set();
const visited = new Set();
const visit = (id) => {
if (visiting.has(id))
return true;
if (visited.has(id))
return false;
visiting.add(id);
for (const dependency of dependencies.get(id) ?? [])
if (visit(dependency))
return true;
visiting.delete(id);
visited.add(id);
return false;
};
for (const [id, indexes] of idIndexes) {
if (indexes.length === 1 && visit(id)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['paragraph_rules', indexes[0], 'source_drift', 'prerequisites'], message: `normalize rule prerequisite cycle includes: ${id}` });
break;
}
}
});
export const GuidanceEntrySchema = z.object({
source: z.enum(['footnote', 'pattern', 'range']),
part: z.string(),
index: z.number(),
text: z.string(),
groupId: z.string().optional(),
});
/** Machine-readable guidance artifact produced from fieldSelector cleaning inputs. */
export const GuidanceOutputSchema = z.object({
extractedFrom: z.object({
sourceHash: z.string(),
configHash: z.string(),
}),
entries: z.array(GuidanceEntrySchema),
});
const MarketDataCitationSchema = z.object({
id: z.string(),
label: z.string(),
url: z.string().optional(),
});
/**
* Metadata required for field-selector-based templates.
*
* FieldSelectors point at non-redistributable upstream source DOCX files and ship only
* transformation instructions. Required fields are `name`, `source_url`,
* `source_version`, and `license_note`; `fields` and `priority_fields` reuse
* the same field-definition semantics as template metadata and default to
* empty arrays. `optional` defaults to `false`. `source_sha256` verifies
* provenance for upstream sources when present. `market_data_citations`
* records optional external citation metadata used by fieldSelector guidance.
*/
export const StyleSeparatorSpacingProfileSchema = z.object({
boundaries: z.array(z.object({
heading_para_id: z.string().regex(/^[0-9A-F]{8}$/),
continuation_para_id: z.string().regex(/^[0-9A-F]{8}$/),
before_twips: z.number().int().positive(),
expected_layout_sha256: z.string().regex(/^[0-9a-f]{64}$/),
}).strict()).min(1),
}).strict().superRefine((profile, ctx) => {
const ids = profile.boundaries.flatMap(b => [b.heading_para_id, b.continuation_para_id]);
if (new Set(ids).size !== ids.length)
ctx.addIssue({ code: 'custom', message: 'spacing boundaries must have unique paragraph IDs' });
});
export const FieldSelectorMetadataSchema = z.object({
name: z.string().trim().min(1, 'name must be a non-empty string (used as display_name on list_templates)'),
category: z.string().optional(),
description: z.string().optional(),
source_url: z.string().url(),
source_version: z.string(),
license_note: z.string(),
optional: z.boolean().default(false),
distribution: DistributionEnum.optional(),
artifact_type: ArtifactTypeEnum.optional(),
source_sha256: z.string().optional(),
rendering: z.object({ style_separator_spacing: StyleSeparatorSpacingProfileSchema }).strict().optional(),
fields: z.array(FieldDefinitionSchema).default([]),
priority_fields: z.array(z.string()).default([]),
market_data_citations: z.array(MarketDataCitationSchema).optional(),
...TemplateCapabilityManifestSchema.shape,
}).superRefine((meta, ctx) => {
if (meta.rendering && !/^[0-9a-f]{64}$/.test(meta.source_sha256 ?? '')) {
ctx.addIssue({ code: 'custom', path: ['source_sha256'], message: 'rendering declarations require an exact source SHA-256' });
}
validateUniqueFieldNames(meta.fields, ctx);
validatePriorityFields(meta.fields, meta.priority_fields, ctx);
validateDerivedBooleanCollisions(meta.fields, ctx);
});
// --- Template loaders ---
export function loadMetadata(templateDir) {
const metadataPath = join(templateDir, 'metadata.yaml');
const raw = readFileSync(metadataPath, 'utf-8');
const parsed = yaml.load(raw);
return TemplateMetadataSchema.parse(parsed);
}
export function validateMetadata(templateDir) {
try {
loadMetadata(templateDir);
return { valid: true, errors: [] };
}
catch (err) {
if (err instanceof z.ZodError) {
return {
valid: false,
errors: err.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
};
}
return { valid: false, errors: [err.message] };
}
}
// --- External template loaders ---
export function loadExternalMetadata(externalDir) {
const metadataPath = join(externalDir, 'metadata.yaml');
const raw = readFileSync(metadataPath, 'utf-8');
const parsed = yaml.load(raw);
return ExternalMetadataSchema.parse(parsed);
}
export function validateExternalMetadata(externalDir) {
try {
loadExternalMetadata(externalDir);
return { valid: true, errors: [] };
}
catch (err) {
if (err instanceof z.ZodError) {
return {
valid: false,
errors: err.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
};
}
return { valid: false, errors: [err.message] };
}
}
// --- FieldSelector loaders ---
export function loadFieldSelectorMetadata(fieldSelectorDir) {
const metadataPath = join(fieldSelectorDir, 'metadata.yaml');
const raw = readFileSync(metadataPath, 'utf-8');
const parsed = yaml.load(raw);
return FieldSelectorMetadataSchema.parse(parsed);
}
export function loadCleanConfig(fieldSelectorDir) {
const cleanPath = join(fieldSelectorDir, 'clean.json');
if (!existsSync(cleanPath)) {
return { removeFootnotes: false, removeParagraphPatterns: [], removeRanges: [], clearParts: [] };
}
const raw = readFileSync(cleanPath, 'utf-8');
return CleanConfigSchema.parse(JSON.parse(raw));
}
export function loadNormalizeConfig(fieldSelectorDir) {
const normalizePath = join(fieldSelectorDir, 'normalize.json');
if (!existsSync(normalizePath)) {
return { paragraph_rules: [] };
}
const raw = readFileSync(normalizePath, 'utf-8');
return NormalizeConfigSchema.parse(JSON.parse(raw));
}
export function validateFieldSelectorMetadata(fieldSelectorDir) {
try {
loadFieldSelectorMetadata(fieldSelectorDir);
return { valid: true, errors: [] };
}
catch (err) {
if (err instanceof z.ZodError) {
return {
valid: false,
errors: err.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
};
}
return { valid: false, errors: [err.message] };
}
}
//# sourceMappingURL=metadata.js.map