All files / src/pipeline/rfcxml bibliography.js

94.73% Statements 108/114
73.04% Branches 84/115
100% Functions 16/16
96.22% Lines 102/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240          6x 6x   6x 6x 6x 6x     11x           11x 1x   11x 1x   11x       20x 20x 20x 15x 15x             5x 5x 1x 1x             4x 4x 1x 1x             3x 2x 2x 2x             1x                 8x       26x     26x 105x 11x 11x 7x 7x 6x 6x 6x 6x 6x             105x 21x           5x 1x   4x     4x                         5x 5x   5x 5x 1x 1x   5x 4x 4x 4x       5x       6x 5x 1x   4x 4x 4x 4x 4x     4x   6x 1x   6x       6x 2x 2x   6x 6x 5x   6x       6x       10x 5x   5x       8x 3x   10x 5x               5x 10x 10x   5x 1x     4x 4x 4x 4x 4x 4x       1x 1x     1x     6x                      
/**
 * Map Spec-Up-T [[spec:]] citations and ietf.references to RFCXML bibliography entries.
 * RFCs/BCPs/STDs/I-Ds use bib.ietf.org xi:include; other works become explicit <reference> elements.
 */
 
const { el, escapeXml } = require('./xml-builder');
const { headingToAnchor } = require('./term-anchor');
 
const RFC_RE = /^(?:RFC[-\s]?)(\d+)$/i;
const BCP_RE = /^(?:BCP[-\s]?)(\d+)$/i;
const STD_RE = /^(?:STD[-\s]?)(\d+)$/i;
const DRAFT_RE = /^(?:I-D\.)?(?:draft-)?(.+)$/i;
 
function sanitizeBibliographyAnchor(name) {
    let slug = String(name ?? '')
        .trim()
        .replace(/\s+/g, '-')
        .replace(/[^A-Za-z0-9._-]/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-|-$/g, '');
    if (!slug) {
        slug = 'ref';
    }
    if (!/^[A-Za-z]/.test(slug)) {
        slug = `ref-${slug}`;
    }
    return slug;
}
 
function classifyCitation(name) {
    const trimmed = String(name ?? '').trim();
    const rfc = trimmed.match(RFC_RE);
    if (rfc) {
        const number = String(Number(rfc[1]));
        return {
            kind: 'rfc',
            number,
            anchor: `RFC${number}`,
            href: `https://bib.ietf.org/public/rfc/bibxml/reference.RFC.${number}.xml`
        };
    }
    const bcp = trimmed.match(BCP_RE);
    if (bcp) {
        const number = String(Number(bcp[1]));
        return {
            kind: 'bcp',
            number,
            anchor: `BCP${number}`,
            href: `https://bib.ietf.org/public/rfc/bibxml/reference.BCP.${number}.xml`
        };
    }
    const std = trimmed.match(STD_RE);
    if (std) {
        const number = String(Number(std[1]));
        return {
            kind: 'std',
            number,
            anchor: `STD${number}`,
            href: `https://bib.ietf.org/public/rfc/bibxml/reference.STD.${number}.xml`
        };
    }
    if (/^(I-D\.|draft-)/i.test(trimmed)) {
        const match = trimmed.match(DRAFT_RE);
        const draftName = match ? match[1].replace(/^draft-/i, '') : trimmed;
        return {
            kind: 'draft',
            name: draftName,
            anchor: `I-D.${draftName}`,
            href: `https://bib.ietf.org/public/rfc/bibxml3/reference.I-D.${draftName}.xml`
        };
    }
    return {
        kind: 'other',
        name: trimmed,
        anchor: sanitizeBibliographyAnchor(trimmed),
        title: trimmed
    };
}
 
function isNormativeSpecType(type) {
    return /^spec-normative$/i.test(type) || /^spec-required$/i.test(type);
}
 
function collectFromTokens(tokens, citations) {
    Iif (!Array.isArray(tokens)) {
        return;
    }
    for (const token of tokens) {
        if (token.type === 'template' && token.info) {
            const type = token.info.type || '';
            if (/^spec/i.test(type)) {
                const name = (token.info.args && token.info.args[0]) || '';
                if (name) {
                    const classified = classifyCitation(name);
                    const existing = citations.get(classified.anchor);
                    const group = isNormativeSpecType(type) ? 'normative' : 'informative';
                    if (!existing) {
                        citations.set(classified.anchor, { ...classified, group });
                    } else Eif (group === 'normative') {
                        existing.group = 'normative';
                    }
                }
            }
        }
        if (token.children) {
            collectFromTokens(token.children, citations);
        }
    }
}
 
function normalizeConfiguredReference(entry, defaultGroup) {
    if (typeof entry === 'string') {
        return { ...classifyCitation(entry), group: defaultGroup };
    }
    const classified = entry.anchor
        ? { kind: 'other', anchor: sanitizeBibliographyAnchor(entry.anchor), ...entry }
        : { ...classifyCitation(entry.title || entry.name || 'ref'), ...entry };
    return {
        kind: classified.kind || 'other',
        anchor: classified.anchor || sanitizeBibliographyAnchor(entry.anchor || entry.title || 'ref'),
        href: classified.href || entry.href,
        title: entry.title || classified.title || classified.anchor,
        target: entry.target,
        date: entry.date,
        authors: entry.authors || [],
        group: defaultGroup
    };
}
 
function collectCitations(tokens, ietfConfig = {}) {
    const citations = new Map();
    collectFromTokens(tokens, citations);
 
    const configured = ietfConfig.references || {};
    for (const entry of configured.normative || []) {
        const ref = normalizeConfiguredReference(entry, 'normative');
        citations.set(ref.anchor, { ...citations.get(ref.anchor), ...ref, group: 'normative' });
    }
    for (const entry of configured.informative || []) {
        const ref = normalizeConfiguredReference(entry, 'informative');
        Eif (!citations.has(ref.anchor) || citations.get(ref.anchor).group !== 'normative') {
            citations.set(ref.anchor, { ...citations.get(ref.anchor), ...ref, group: 'informative' });
        }
    }
 
    return citations;
}
 
function renderExplicitReference(ref) {
    const authors = (ref.authors || []).map(author => {
        if (typeof author === 'string') {
            return el('author', { fullname: author }, el('organization', author));
        }
        const attrs = {};
        if (author.fullname) attrs.fullname = author.fullname;
        Iif (author.initials) attrs.initials = author.initials;
        Iif (author.surname) attrs.surname = author.surname;
        const org = author.organization
            ? el('organization', escapeXml(author.organization))
            : el('organization', ' ');
        return el('author', attrs, org);
    });
    if (authors.length === 0) {
        authors.push(el('author', el('organization', ' ')));
    }
    const frontParts = [
        el('title', escapeXml(ref.title || ref.anchor)),
        ...authors
    ];
    if (ref.date) {
        const dateAttrs = typeof ref.date === 'object' ? ref.date : { year: ref.date };
        frontParts.push(el('date', dateAttrs));
    }
    const attrs = { anchor: ref.anchor };
    if (ref.target) {
        attrs.target = ref.target;
    }
    return el('reference', attrs, el('front', frontParts));
}
 
function renderXiInclude(ref) {
    return `<xi:include href="${escapeXml(ref.href)}" parse="xml"/>`;
}
 
function renderReferenceItem(ref) {
    if (ref.href && ref.kind !== 'other') {
        return renderXiInclude(ref);
    }
    return renderExplicitReference(ref);
}
 
function renderReferencesSection(name, refs) {
    if (!refs.length) {
        return null;
    }
    const sorted = [...refs].sort((a, b) => a.anchor.localeCompare(b.anchor));
    return el(
        'references',
        { anchor: headingToAnchor(name) },
        [el('name', escapeXml(name)), ...sorted.map(renderReferenceItem)]
    );
}
 
function renderBibliography(citations) {
    const all = [...citations.values()];
    const normative = all.filter(ref => ref.group === 'normative');
    const informative = all.filter(ref => ref.group !== 'normative');
 
    if (normative.length === 0 && informative.length === 0) {
        return '';
    }
 
    const sections = [];
    const normativeXml = renderReferencesSection('Normative References', normative);
    const informativeXml = renderReferencesSection('Informative References', informative);
    if (normativeXml) sections.push(normativeXml);
    Eif (informativeXml) sections.push(informativeXml);
    return sections.join('\n');
}
 
function lookupCitationAnchor(name, citations) {
    const classified = classifyCitation(name);
    Iif (citations && citations.has(classified.anchor)) {
        return classified.anchor;
    }
    return classified.anchor;
}
 
module.exports = {
    RFC_RE,
    classifyCitation,
    sanitizeBibliographyAnchor,
    isNormativeSpecType,
    collectCitations,
    renderBibliography,
    renderExplicitReference,
    renderXiInclude,
    lookupCitationAnchor
};