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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 5x | const cheerio = require("cheerio");
const axios = require('axios').default;
const fs = require('fs-extra');
const Logger = require('../../utils/logger.js');
const spaceRegex = /\s+/g;
function validateReferences(references, definitions, render) {
const unresolvedRefs = [];
[...new Set(references)].forEach(
ref => {
if (render.includes(`id="term:${ref.replace(spaceRegex, '-').toLowerCase()}"`)) {
// Reference is resolved
} else {
unresolvedRefs.push(ref);
}
}
);
if (unresolvedRefs.length > 0) {
Logger.warn(`Unresolved References: ${unresolvedRefs.join(',')}`, {
context: 'These terms are referenced in your spec but not defined',
hint: 'Add [[def: term]] definitions or [[tref: repo, term]] transclusion for these terms or alter existing definitions, optionally by adding aliases, in your terminology files, or check for typos in [[ref: term]] references',
details: `Count: ${unresolvedRefs.length} unresolved term(s)`
});
}
const danglingDefs = [];
definitions.forEach(def => {
// Handle both old array format and new object format
if (Array.isArray(def)) {
let found = def.some(term => render.includes(`href="#term:${term.replace(spaceRegex, '-').toLowerCase()}"`))
if (!found) {
danglingDefs.push(def[0]);
}
} else if (def.term) {
// New object format
const terms = [def.term, def.alias].filter(Boolean);
let found = terms.some(term => render.includes(`href="#term:${term.replace(spaceRegex, '-').toLowerCase()}"`))
if (!found) {
danglingDefs.push(def.term);
}
}
})
if (danglingDefs.length > 0) {
Logger.warn(`Dangling Definitions: ${danglingDefs.join(',')}`, {
context: 'These terms are defined but never referenced in your spec',
hint: 'Add [[ref: term]] references where needed.',
details: `Count: ${danglingDefs.length} unused definition(s)`
});
}
}
function findExternalSpecByKey(config, key) {
Iif (!config || !config.specs) return null;
for (const spec of config.specs) {
Eif (spec.external_specs) {
for (const externalSpec of spec.external_specs) {
Eif (externalSpec.external_spec === key) {
return externalSpec;
}
}
}
}
return null;
}
async function fetchExternalSpecs(spec) {
try {
let results = await Promise.all(
spec.external_specs.map(s => {
const url = s["gh_page"];
return axios.get(url).catch(error => ({ error, url }));
})
);
const failed = results.filter(r => r && r.error);
if (failed.length > 0) {
failed.forEach(f => {
const msg = f.error.response
? `HTTP ${f.error.response.status} for ${f.url}`
: `Network error for ${f.url}: ${f.error.message}`;
Logger.error("External spec fetch failed", {
context: `Attempting to fetch external terminology from: ${f.url}`,
hint: 'Verify the URL is correct in specs.json under external_specs[].gh_page. Ensure the external spec has published their GitHub Pages site',
details: msg
});
});
}
// Map results to extract terms instead of creating DOM HTML
const extractedTerms = [];
results
.map((r, index) =>
r && r.status === 200
? { externalSpec: spec.external_specs[index].external_spec, data: r.data }
: null
)
.filter(r => r) // Remove null values (failed fetches)
.forEach(r => {
// Extract terms from each external spec's HTML
const termsFromSpec = extractTermsFromHtml(r.externalSpec, r.data);
extractedTerms.push(...termsFromSpec);
});
return extractedTerms;
} catch (e) {
Logger.error("Unexpected error in fetchExternalSpecs", {
context: 'Failed while fetching terms from external specifications',
hint: 'Check your internet connection and verify all external_specs URLs in specs.json are valid. Run with GITHUB_API_TOKEN set if accessing private repos',
details: e.message
});
return [];
}
}
/**
* Merges xref terms from external specs into the allXTrefs structure
* @param {Array} xrefTerms - Array of xref term objects from fetchExternalSpecs
* @param {string} outputPathJSON - Path to the xtrefs-data.json file
* @param {string} outputPathJS - Path to the xtrefs-data.js file
* @returns {Promise<void>}
*/
async function mergeXrefTermsIntoAllXTrefs(xrefTerms, outputPathJSON, outputPathJS) {
try {
let allXTrefs = { xtrefs: [] };
// Load existing xtrefs data if it exists
if (fs.existsSync(outputPathJSON)) {
allXTrefs = fs.readJsonSync(outputPathJSON);
}
// Add xref terms to the allXTrefs structure
// Mark them with source: 'xref' to distinguish from tref entries
// Track how many terms were matched vs skipped for logging purposes
let matchedCount = 0;
let skippedCount = 0;
xrefTerms.forEach(xrefTerm => {
// Check if this term already exists (match by externalSpec and term only)
// Don't filter by source because entries from markdown scanning don't have source field
const existingIndex = allXTrefs.xtrefs.findIndex(existing =>
existing.externalSpec === xrefTerm.externalSpec &&
existing.term === xrefTerm.term
);
if (existingIndex >= 0) {
// Get the existing entry to check if it's a tref
const existingXtref = allXTrefs.xtrefs[existingIndex];
// Update existing entry - preserve the existing metadata but add/update content
allXTrefs.xtrefs[existingIndex] = {
...existingXtref,
content: xrefTerm.content, // Update the content from fetched HTML
classes: xrefTerm.classes || [], // Update classes from dt element
source: xrefTerm.source, // Add source field
termId: xrefTerm.termId, // Add termId if not present
lastUpdated: new Date().toISOString()
};
// Check if this is a tref to an external tref (nested tref)
// A term with 'term-external' class means it's transcluded from another spec
const isExternalTref = xrefTerm.classes && xrefTerm.classes.includes('term-external');
const isTref = existingXtref.sourceFiles && existingXtref.sourceFiles.some(sf => sf.type === 'tref');
const isXref = existingXtref.sourceFiles && existingXtref.sourceFiles.some(sf => sf.type === 'xref');
if (isExternalTref && isTref) {
// Build a readable list of source files for the error message
const sourceFilesList = existingXtref.sourceFile
? existingXtref.sourceFile
: (existingXtref.sourceFiles || []).map(sf => sf.file).join(', ');
// Construct the external repository URL
const externalRepoUrl = existingXtref.ghPageUrl || existingXtref.repoUrl || `https://github.com/${existingXtref.owner}/${existingXtref.repo}`;
Logger.error(`NESTED TREF DETECTED: Term "${existingXtref.term}" in ${existingXtref.externalSpec}`, {
context: `Origin: ${sourceFilesList} - This term is itself transcluded from another spec`,
hint: 'Avoid chaining external references (tref → tref). Reference the original source spec directly, or define the term locally in your spec',
details: `This creates a complex dependency chain. Repository: ${externalRepoUrl}`
});
}
if (isExternalTref && isXref) {
// Build a readable list of source files for the warning message
const sourceFilesList = existingXtref.sourceFile
? existingXtref.sourceFile
: (existingXtref.sourceFiles || []).map(sf => sf.file).join(', ');
// Construct the external repository URL
const externalRepoUrl = existingXtref.ghPageUrl || existingXtref.repoUrl || `https://github.com/${existingXtref.owner}/${existingXtref.repo}`;
Logger.error(`NESTED XREF DETECTED: Term "${existingXtref.term}" in ${existingXtref.externalSpec}`, {
context: `Origin: ${sourceFilesList} - This xref points to a term that is already transcluded from elsewhere`,
hint: 'Use [[xref]] only for terms directly defined in the external spec. For nested references, either reference the original source or define the term locally',
details: `This creates a chain of external references. Repository: ${externalRepoUrl}`
});
}
matchedCount++;
} else {
// Skip terms that are not referenced in the local markdown files
// This prevents bloating the xtrefs-data.json with unreferenced terms
skippedCount++;
}
});
// Write the updated data back to files
const allXTrefsStr = JSON.stringify(allXTrefs, null, 2);
fs.writeFileSync(outputPathJSON, allXTrefsStr, 'utf8');
const stringReadyForFileWrite = `const allXTrefs = ${allXTrefsStr};`;
fs.writeFileSync(outputPathJS, stringReadyForFileWrite, 'utf8');
Logger.success(`Merged xref terms: ${matchedCount} matched, ${skippedCount} skipped (not referenced). Total entries: ${allXTrefs.xtrefs.length}`);
} catch (error) {
Logger.error('Error merging xref terms into allXTrefs', {
context: 'Failed while merging external reference terms into the xtrefs cache',
hint: 'This may indicate corrupted cache files in .cache/xtrefs/. Try deleting the .cache directory and running the build again',
details: error.message
});
}
}
/**
* Extracts terms and their definitions from HTML and returns them as structured data
* @param {string} externalSpec - The external spec identifier
* @param {string} html - The HTML content to parse
* @returns {Array} Array of term objects suitable for the allXTrefs structure
*/
function extractTermsFromHtml(externalSpec, html) {
try {
const $ = cheerio.load(html);
const terms = [];
const termElements = $('dl.terms-and-definitions-list dt');
Logger.highlight(`Found ${termElements.length} term elements in ${externalSpec} (HTML size: ${Math.round(html.length / 1024)}KB)`);
// Process terms in batches to prevent stack overflow with large datasets
const BATCH_SIZE = 100;
const totalElements = termElements.length;
for (let i = 0; i < totalElements; i += BATCH_SIZE) {
const batch = termElements.slice(i, i + BATCH_SIZE);
batch.each((index, termElement) => {
try {
const $termElement = $(termElement);
// The id can be on the dt element itself OR on span(s) inside it
// Some terms have multiple nested spans with different IDs (e.g., aliases)
// We need to extract ALL term IDs from the dt element
const termIds = [];
// First check if dt itself has an id
const dtId = $termElement.attr('id');
if (dtId && dtId.includes('term:')) {
termIds.push(dtId.replace('term:', ''));
}
// Then find all spans with ids that contain 'term:'
$termElement.find('span[id*="term:"]').each((i, span) => {
const spanId = $(span).attr('id');
if (spanId && spanId.includes('term:')) {
const termName = spanId.replace('term:', '');
if (!termIds.includes(termName)) {
termIds.push(termName);
}
}
});
// Skip if no valid term IDs found
if (termIds.length === 0) {
return;
}
// Extract classes from the <dt> element to determine if it's a local or external term.
// This helps identify if a tref to an external resource is itself a tref (term-external).
const dtClasses = $termElement.attr('class');
const classArray = dtClasses ? dtClasses.split(/\s+/).filter(Boolean) : [];
const termClasses = classArray.filter(cls => cls === 'term-local' || cls === 'term-external');
// Extract ALL consecutive <dd> elements following this <dt>
// Terms can have multiple <dd> blocks for extended definitions
const ddElements = [];
let nextElement = $termElement.next();
while (nextElement.length > 0 && nextElement[0].tagName === 'dd') {
ddElements.push(nextElement);
nextElement = nextElement.next();
}
if (ddElements.length > 0) {
// Combine all <dd> elements into a single HTML string
const ddContent = ddElements.map(dd => $.html(dd)).join('\n'); // Store the complete DD content
// Create a term object for each ID found in this dt element
// This handles cases where one term definition has multiple aliases
termIds.forEach(termName => {
const termObj = {
externalSpec: externalSpec,
term: termName,
content: ddContent,
classes: termClasses, // CSS classes from dt element (term-local or term-external)
// Add metadata for consistency with tref structure
source: 'xref', // Distinguish from tref entries
termId: `term:${termName}`, // Term ID matches the actual HTML anchor format
};
terms.push(termObj);
});
}
} catch (termError) {
Logger.warn(`Error processing term in ${externalSpec}`, {
context: 'Failed to extract a specific term from external spec HTML',
hint: 'The external spec may have malformed HTML or non-standard term definitions. Contact the spec maintainer if this persists',
details: termError.message
});
}
});
// Log progress for very large datasets
if (totalElements > 1000 && i % (BATCH_SIZE * 10) === 0) {
Logger.progress(Math.min(i + BATCH_SIZE, totalElements), totalElements, `Processing terms from ${externalSpec}`);
}
}
Logger.success(`Extracted ${terms.length} terms from external spec: ${externalSpec}`);
return terms;
} catch (error) {
Logger.error(`Error extracting terms from external spec '${externalSpec}'`, {
context: 'Failed while parsing HTML from external spec to extract term definitions',
hint: 'Verify that the external spec is a valid spec-up-t generated document with a proper terms-and-definitions section',
details: error.message
});
return [];
}
}
module.exports = {
findExternalSpecByKey,
validateReferences,
fetchExternalSpecs,
extractTermsFromHtml,
mergeXrefTermsIntoAllXTrefs
}
|