diff --git a/README.md b/README.md index 300cbe6..6e401d1 100644 --- a/README.md +++ b/README.md @@ -144,8 +144,9 @@ select them. A local checkout works through `GOVSTACK_SITE_RENDERER` meanwhile. - `adapters/api-guide.mjs` reads the existing `SUMMARY.md`, Markdown, `rules.yaml`, and linter coverage contract without reclassifying its rules. -- `adapters/framework.mjs` reads `metadata.yml`, `authors.yml`, `toc.yml`, - functionality frontmatter, and the declared linked/support material. +- `adapters/framework.mjs` treats root `README.md` and the pages listed in + `toc.yml` as the complete page inventory, then reads functionality frontmatter + and explicitly referenced support material. - `src/` owns the shared presentation. It contains no hand-maintained copies of either publication's prose or requirements. - `scripts/publication.mjs` normalizes adapter output into a common manifest. @@ -161,19 +162,32 @@ output, including outputs on another volume. Promotion preserves unrelated files and refuses symlink destinations or obsolete HTML routes. Use a fresh output directory when a publication intentionally removes a route. -The runtime content loader uses the manifest page allowlist. Supporting HTML and -redirects must also be declared explicitly. Generated directories are ignored; -change the input or generator rather than editing generated content. +The runtime content loader uses the manifest page allowlist. For framework +sources, a relative Markdown link must target root `README.md` or a page listed +in `toc.yml`; generation fails instead of silently adding another page. +Supporting HTML and redirects must also be declared explicitly. Generated +directories are ignored; change the input or generator rather than editing +generated content. Starlight's Markdown processing includes the generated content directory, so native heading permalinks and asides use the same transforms as ordinary docs. -Framework support files exclude hidden operational/configuration paths, including -environment files. `.well-known` publication assets and `.github` references stay -available. References or symlink aliases to excluded paths fail generation. -Static checks and output promotion also reject excluded paths, including files -left in an older output directory. Choose a fresh output rather than deleting -unrelated files. The adapter still copies other allowed non-Markdown files; -limiting those to an explicit reference/dependency graph is separate work. +Framework support files come from an explicit publication graph: page links, +images and reference definitions; raw HTML `href` and `src` attributes; +functionality `contract` and `test` values; and the source metadata downloads +`toc.yml`, `metadata.yml`, and `authors.yml`. A linked directory publishes its +allowed non-Markdown tree. Referenced YAML and JSON files add their local +`$ref` and `$dynamicRef` dependency closure. An `api-references.yml` contract +independently publishes its original source and local dependency closure as well +as the generated bundle; the configuration file itself is not a download. +Unreferenced repository files, including lockfiles and tooling, are not +published. + +Hidden operational/configuration paths, including environment files, remain +excluded. Explicit `.well-known` publication assets and `.github` references +can be published. References or symlink aliases to excluded paths fail +generation. Static checks and output promotion also reject excluded paths, +including files left in an older output directory. Choose a fresh output rather +than deleting unrelated files. ## Adapter boundary diff --git a/adapters/framework.mjs b/adapters/framework.mjs index 92e63be..80b8385 100644 --- a/adapters/framework.mjs +++ b/adapters/framework.mjs @@ -65,9 +65,9 @@ function baseUrl(base, relative = '') { return relative ? `${normalized}${relative}` : normalized; } -function safeRelativeTarget(sourceName, target) { +function safeRelativeTarget(sourceName, target, directory = path.posix.dirname(sourceName)) { const pathname = target.split(/[?#]/, 1)[0]; - const normalized = path.posix.normalize(path.posix.join(path.posix.dirname(sourceName), pathname)); + const normalized = path.posix.normalize(path.posix.join(directory, pathname)); if (path.posix.isAbsolute(normalized) || normalized === '..' || normalized.startsWith('../')) { throw new Error(`${sourceName}: relative reference escapes the source root: ${target}`); } @@ -214,16 +214,6 @@ function standaloneAnchors(tree) { return anchors; } -async function exists(file) { - try { - await stat(file); - return true; - } catch (error) { - if (error.code === 'ENOENT') return false; - throw error; - } -} - function pageLabel(sourceName, frontmatter, headings) { if (typeof frontmatter.title === 'string' && frontmatter.title.trim()) return frontmatter.title.trim(); const h1 = headings.find((heading) => heading.depth === 1); @@ -234,7 +224,7 @@ function pageLabel(sourceName, frontmatter, headings) { function localReferences(tree) { const references = []; visit(tree, (node) => { - if ((node.type === 'link' || node.type === 'image') && typeof node.url === 'string') { + if (['link', 'image', 'definition'].includes(node.type) && typeof node.url === 'string') { references.push(node.url); } if (node.type === 'html') { @@ -244,28 +234,12 @@ function localReferences(tree) { return references; } -async function discoverPages(sourceRoot, toc) { +function discoverPages(toc) { const ordered = ['README.md']; for (const [section, entries] of Object.entries(toc)) { ordered.push(...entries.map((entry) => path.posix.join(section, entry))); } - const pages = new Set(ordered); - const queue = [...ordered]; - while (queue.length) { - const sourceName = queue.shift(); - const source = await readFile(path.join(sourceRoot, sourceName), 'utf8'); - const tree = parser.parse(source); - for (const reference of localReferences(tree)) { - if (/^[A-Za-z][A-Za-z+.-]*:/.test(reference) || reference.startsWith('//') || reference.startsWith('#')) continue; - const target = safeRelativeTarget(sourceName, reference); - if (!target.endsWith('.md') || pages.has(target)) continue; - if (await exists(path.join(sourceRoot, target))) { - pages.add(target); - queue.push(target); - } - } - } - return { ordered: [...ordered, ...[...pages].filter((page) => !ordered.includes(page)).sort()], pages }; + return { ordered, pages: new Set(ordered) }; } function splitReference(url) { @@ -280,7 +254,15 @@ function splitReference(url) { }; } -function collectReferencedSupportPaths(pages) { +function decodedPathname(sourceName, pathname) { + try { + return decodeURIComponent(pathname); + } catch { + throw new Error(`${sourceName}: invalid percent-encoding in reference: ${pathname}`); + } +} + +function collectReferencedSupportPaths(pages, pageSources) { const references = new Set(); for (const page of pages) { for (const reference of localReferences(page.tree)) { @@ -293,7 +275,46 @@ function collectReferencedSupportPaths(pages) { continue; } const { pathname } = splitReference(reference); - if (pathname) references.add(safeRelativeTarget(page.sourceName, pathname)); + if (!pathname) continue; + const target = safeRelativeTarget( + page.sourceName, + decodedPathname(page.sourceName, pathname), + ); + if (target.endsWith('.md')) { + if (!pageSources.has(target)) { + throw new Error( + `${page.sourceName}: local Markdown page ${target} is not listed in toc.yml; add it to toc.yml or link to its repository URL`, + ); + } + continue; + } + const directory = target.replace(/\/+$/, ''); + if ([...pageSources].some((source) => source.startsWith(`${directory}/`))) continue; + references.add(target); + } + for (const requirement of page.frontmatter.requirements ?? []) { + for (const [field, value] of [ + ['contract', requirement?.contract], + ['test', requirement?.test], + ]) { + if (typeof value !== 'string' || /^[A-Za-z][A-Za-z+.-]*:/.test(value) || value.startsWith('//')) continue; + const { pathname } = splitReference(value); + if (!pathname) continue; + const target = safeRelativeTarget( + page.sourceName, + decodedPathname(page.sourceName, pathname), + '.', + ); + if (target.endsWith('.md')) { + if (!pageSources.has(target)) { + throw new Error( + `${page.sourceName}: requirement ${field} Markdown page ${target} is not listed in toc.yml`, + ); + } + continue; + } + references.add(target); + } } } return references; @@ -684,28 +705,16 @@ function transformBody({ page, pageRoutes, pageAnchors, base, metadata, authors, return `${generatedFrontmatter({ title, description, pagefind: isArchive ? false : undefined }, unofficial)}${body}`; } -function sidebarFromToc(toc, pagesBySource, ordered) { +function sidebarFromToc(toc, pagesBySource) { const sidebar = [{ label: 'Home', slug: '' }]; - const tocSources = new Set(['README.md']); for (const [section, entries] of Object.entries(toc)) { const items = entries.map((entry) => { const source = path.posix.join(section, entry); - tocSources.add(source); const page = pagesBySource.get(source); return { label: page.title, slug: page.route }; }); sidebar.push({ label: section[0].toUpperCase() + section.slice(1), items }); } - const extras = ordered.filter((source) => !tocSources.has(source)); - if (extras.length) { - sidebar.push({ - label: 'Linked documents', - items: extras.map((source) => ({ - label: pagesBySource.get(source).title, - slug: pagesBySource.get(source).route, - })), - }); - } return sidebar; } @@ -736,12 +745,116 @@ async function gitSourceState(sourceRoot) { return { sourceRevision: revision.trim(), sourceDirty: statusOutput.trim() !== '' }; } -async function copySupportFiles(sourceRoot, siteRoot, pageSources, snapshots, referencedPaths) { - const copied = []; +const SPECIFICATION_DOWNLOADS = ['toc.yml', 'metadata.yml', 'authors.yml']; +const STRUCTURED_SUPPORT_EXTENSIONS = new Set(['.yml', '.yaml', '.json']); + +function schemaReferences(value, found = []) { + if (Array.isArray(value)) { + for (const item of value) schemaReferences(item, found); + } else if (value && typeof value === 'object') { + for (const [key, child] of Object.entries(value)) { + if (['$ref', '$dynamicRef'].includes(key) && typeof child === 'string') found.push(child); + else schemaReferences(child, found); + } + } + return found; +} + +function parseSchemaReferences(relative, contents) { + if (!STRUCTURED_SUPPORT_EXTENSIONS.has(path.posix.extname(relative).toLowerCase())) return []; + const text = contents.toString('utf8'); + if (!text.includes('$ref') && !text.includes('$dynamicRef')) return []; + const options = { logLevel: 'error' }; + const documents = YAML.parseAllDocuments(text, options); + const failure = documents.flatMap((document) => document.errors)[0]; + if (failure) throw failure; + return documents.flatMap((document) => schemaReferences(document.toJS(options))); +} + +function relativeSchemaTargets(relative, references) { + const targets = []; + for (const reference of references) { + if ( + /^[A-Za-z][A-Za-z+.-]*:/.test(reference) + || reference.startsWith('//') + || reference.startsWith('/') + ) { + continue; + } + const { pathname } = splitReference(reference); + if (pathname) { + targets.push(safeRelativeTarget(relative, decodedPathname(relative, pathname))); + } + } + return targets; +} + +async function copySupportFiles( + sourceRoot, + siteRoot, + pageSources, + snapshots, + referencedPaths, + warnings, +) { + const copied = new Set(); const publicRoot = path.join(siteRoot, 'public'); const sourceReal = await realpath(sourceRoot); + const pending = []; + const followed = new Set(); + const walking = new Set(); + + async function publish(relative, contents, real, via, chain) { + const posixRelative = relative.split(path.sep).join('/'); + if (copied.has(posixRelative)) return; + const destination = path.join(publicRoot, relative); + await mkdir(path.dirname(destination), { recursive: true }); + await writeFile(destination, contents); + snapshots.set(posixRelative, contents); + copied.add(posixRelative); + + const followKey = `${real}\0${path.posix.dirname(posixRelative)}`; + if (followed.has(followKey)) return; + followed.add(followKey); + const chainKey = `${real}\0${path.dirname(real)}`; + if (chain.has(chainKey)) { + warnings.push(`${posixRelative}: symlink cycle, schema references are not followed`); + return; + } + let references; + try { + references = parseSchemaReferences(posixRelative, contents); + } catch (error) { + const message = `${posixRelative}: cannot parse support file to follow schema references: ${error.message}`; + if (via) throw new Error(`${message} (referenced from ${via})`); + warnings.push(message); + return; + } + for (const target of relativeSchemaTargets(posixRelative, references)) { + pending.push({ + relative: target, + from: posixRelative, + chain: new Set(chain).add(chainKey), + }); + } + } + + async function walkDirectory(real, source, relative, via, chain) { + if (walking.has(real)) { + warnings.push(`${relative.split(path.sep).join('/')}: symlink cycle, directory is already being copied`); + return; + } + walking.add(real); + try { + for (const entry of await readdir(source)) { + await walk(path.join(source, entry), path.join(relative, entry), via, chain); + } + } finally { + walking.delete(real); + } + } - async function walk(source, relative) { + async function walk(source, relative, via, chain) { const posixRelative = relative.split(path.sep).join('/'); if (!isPublishableSupportPath(posixRelative)) return; const details = await lstat(source); @@ -761,38 +874,58 @@ async function copySupportFiles(sourceRoot, siteRoot, pageSources, snapshots, re } const resolvedDetails = await stat(resolved); if (resolvedDetails.isDirectory()) { - for (const entry of await readdir(resolved)) { - await walk(path.join(resolved, entry), path.join(relative, entry)); - } - } else { - const contents = await readFile(resolved); - const destination = path.join(publicRoot, relative); - await mkdir(path.dirname(destination), { recursive: true }); - await writeFile(destination, contents); - snapshots.set(relative.split(path.sep).join('/'), contents); - copied.push(relative.split(path.sep).join('/')); + await walkDirectory(resolved, resolved, relative, via, chain); + } else if (!posixRelative.endsWith('.md') && !pageSources.has(posixRelative)) { + await publish(relative, await readFile(resolved), resolved, via, chain); } return; } if (details.isDirectory()) { - for (const entry of await readdir(source)) { - await walk(path.join(source, entry), path.join(relative, entry)); - } + await walkDirectory(await realpath(source), source, relative, via, chain); return; } if (posixRelative.endsWith('.md') || pageSources.has(posixRelative)) return; - const contents = await readFile(source); - const destination = path.join(publicRoot, relative); - await mkdir(path.dirname(destination), { recursive: true }); - await writeFile(destination, contents); - snapshots.set(posixRelative, contents); - copied.push(posixRelative); + await publish(relative, await readFile(source), await realpath(source), via, chain); } - for (const entry of await readdir(sourceRoot)) { - await walk(path.join(sourceRoot, entry), entry); + async function copyEntry({ relative, from, chain = new Set() }) { + const normalized = relative.replace(/\/+$/, ''); + if (!isPublishableSupportPath(normalized)) { + throw new Error( + `${from ? `${from}: ` : ''}Refusing referenced hidden operational/config path: ${normalized}`, + ); + } + const source = path.join(sourceRoot, normalized); + let resolved; + try { + resolved = await realpath(source); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + if (from) { + throw new Error(`${from}: schema reference target ${normalized} does not exist`); + } + return; + } + if (resolved !== sourceReal && !resolved.startsWith(`${sourceReal}${path.sep}`)) { + throw new Error(`Refusing source symlink outside repository: ${normalized}`); + } + const resolvedRelative = path.relative(sourceReal, resolved).split(path.sep).join('/'); + if (!isPublishableSupportPath(resolvedRelative)) { + throw new Error( + `Refusing referenced support symlink ${normalized}: target is hidden operational/config path ${resolvedRelative}`, + ); + } + if (from && (await stat(resolved)).isDirectory()) { + throw new Error(`${from}: schema reference target ${normalized} is a directory`); + } + await walk(source, normalized, from, chain); + } + + for (const reference of [...new Set([...SPECIFICATION_DOWNLOADS, ...referencedPaths])].sort()) { + pending.push({ relative: reference }); } - return copied.toSorted(); + while (pending.length) await copyEntry(pending.shift()); + return [...copied].toSorted(); } function redirectHtml(target, unofficial) { @@ -821,6 +954,7 @@ async function writeSupportDirectoryIndexes( pageRoutes, base, referencedPaths, + supportFiles, unofficial, ) { const indexes = []; @@ -860,50 +994,13 @@ async function writeSupportDirectoryIndexes( } } for (const directory of [...directories].sort()) { - const sourceDirectory = path.join(sourceRoot, directory); - const directoryDetails = await lstat(sourceDirectory); - if (directoryDetails.isSymbolicLink()) { - const resolved = await realpath(sourceDirectory); - if (resolved !== sourceReal && !resolved.startsWith(`${sourceReal}${path.sep}`)) { - throw new Error(`Refusing source symlink outside repository: ${directory}`); - } - const resolvedRelative = path.relative(sourceReal, resolved).split(path.sep).join('/'); - if (!isPublishableSupportPath(resolvedRelative)) { - if (referencedSupportPathIncludes(directory, referencedPaths)) { - throw new Error( - `Refusing referenced support symlink ${directory}: target is hidden operational/config path ${resolvedRelative}`, - ); - } - continue; - } - } - const entries = await readdir(sourceDirectory, { withFileTypes: true }); - const links = []; - for (const entry of entries) { - const logical = `${directory}/${entry.name}`; - if (!isPublishableSupportPath(logical)) continue; - let isDirectory = entry.isDirectory(); - if (entry.isSymbolicLink()) { - const resolved = await realpath(path.join(sourceRoot, logical)); - if (resolved !== sourceReal && !resolved.startsWith(`${sourceReal}${path.sep}`)) { - throw new Error(`Refusing source symlink outside repository: ${logical}`); - } - const resolvedRelative = path.relative(sourceReal, resolved).split(path.sep).join('/'); - if (!isPublishableSupportPath(resolvedRelative)) { - if (referencedSupportPathIncludes(logical, referencedPaths)) { - throw new Error( - `Refusing referenced support symlink ${logical}: target is hidden operational/config path ${resolvedRelative}`, - ); - } - continue; - } - isDirectory = (await stat(resolved)).isDirectory(); - } - const relative = `${logical}${isDirectory ? '/' : ''}`; - links.push( - `
  • ${htmlEscape(entry.name)}${isDirectory ? '/' : ''}
  • `, - ); - } + const prefix = `${directory}/`; + const links = supportFiles + .filter((relative) => relative.startsWith(prefix)) + .map((relative) => { + const label = relative.slice(prefix.length); + return `
  • ${htmlEscape(label)}
  • `; + }); const output = path.join(siteRoot, 'public', directory, 'index.html'); await mkdir(path.dirname(output), { recursive: true }); await writeFile( @@ -978,7 +1075,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia } if (!Array.isArray(authors?.authors)) throw new Error('authors.yml: authors list is required'); - const { ordered, pages: pageSources } = await discoverPages(absoluteSourceRoot, toc); + const { ordered, pages: pageSources } = discoverPages(toc); const warnings = []; const loaded = []; const snapshots = new Map([ @@ -1016,7 +1113,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia addArchiveCompatibilityAnchors(loaded, warnings); const pageRoutes = new Map(loaded.map((page) => [page.sourceName, page.route])); const pageAnchors = new Map(loaded.map((page) => [page.sourceName, page.anchors])); - const referencedSupportPaths = collectReferencedSupportPaths(loaded); + const referencedSupportPaths = collectReferencedSupportPaths(loaded, pageSources); assertReferencedSupportPathsAllowed(referencedSupportPaths); const supportFiles = await copySupportFiles( absoluteSourceRoot, @@ -1024,6 +1121,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia pageSources, snapshots, referencedSupportPaths, + warnings, ); const apiReferences = await prepareApiReferences({ sourceRoot: absoluteSourceRoot, @@ -1039,7 +1137,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia reference.title = page.title; reference.route = page.route; } - const sidebar = apiReferenceSidebar(sidebarFromToc(toc, pagesBySource, ordered), apiReferences.references, pagesBySource); + const sidebar = apiReferenceSidebar(sidebarFromToc(toc, pagesBySource), apiReferences.references, pagesBySource); await pruneFormerGeneratedPages(absoluteSiteRoot, loaded); @@ -1072,6 +1170,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia pageRoutes, normalizedBase, referencedSupportPaths, + supportFiles, unofficial, ); const redirects = await writeRedirects(absoluteSiteRoot, loaded, normalizedBase, unofficial); @@ -1085,7 +1184,7 @@ export async function generateSite({ sourceRoot, siteRoot, base = '/', unofficia sourceDigest: sourceDigest(snapshots), requirementCount, sidebar, - supportFiles: [...supportFiles, ...apiReferences.supportFiles], + supportFiles: [...new Set([...supportFiles, ...apiReferences.supportFiles])].toSorted(), apiReferences: apiReferences.references, supportIndexes, redirects, diff --git a/docs/building-block-integration.md b/docs/building-block-integration.md index 750e46e..a007912 100644 --- a/docs/building-block-integration.md +++ b/docs/building-block-integration.md @@ -15,6 +15,10 @@ npm run check -- --profile framework --source /absolute/path/to/building-block - ``` The source needs root `metadata.yml`, `authors.yml`, `toc.yml`, and Markdown. +Root `README.md` plus the pages listed in `toc.yml` are the complete published +page inventory. A relative Markdown link to any other source file fails the +build; add a reader-facing page to `toc.yml`, or use a repository URL for +maintainer material that is not part of the site. The template's `specification-site/` wrapper supplies the same commands from a Building Block repository, using an absolute `GOVSTACK_SITE_RENDERER` checkout. It deliberately rejects an older renderer when API references are configured. @@ -36,9 +40,13 @@ just to make a contract visible. The page displays the contract introduction, when supplied, and its operations, with its role and downloads visible and technical metadata collapsed. The full -source contract remains available to download. -Local `$ref` dependencies are bundled; remote and escaping references fail the -build. Do not copy bundled JSON or Scalar assets into the source repository. +source contract remains available to download with its original bytes and +source-relative dependency paths. Local `$ref` and `$dynamicRef` dependencies +are both published and bundled; missing, directory, remote, and escaping +references fail the build. +The declaration seeds these downloads independently, so prose does not need a +duplicate link merely to publish a contract. Do not copy bundled JSON or Scalar +assets into the source repository. OpenAPI references are optional. AsyncAPI and protocol-standard surfaces keep their existing documentation; this renderer does not convert them to OpenAPI. diff --git a/scripts/api-references.mjs b/scripts/api-references.mjs index ab4bed2..65a59af 100644 --- a/scripts/api-references.mjs +++ b/scripts/api-references.mjs @@ -148,14 +148,25 @@ export async function prepareApiReferences({ sourceRoot, siteRoot, base = '/', s const source = await realpath(sourceRoot); const documents = new Map(); for (const reference of references) await loadDependencies(source, reference.contract, snapshots, documents); + const sourceFiles = [...documents.keys()].toSorted(); + for (const output of outputs) { + if (sourceFiles.some((sourceFile) => sourceFile === output || sourceFile.startsWith(`${output}/`) || output.startsWith(`${sourceFile}/`))) { + throw new Error(`Generated API reference output collides with source contract dependency: ${output}`); + } + } const publicRoot = path.join(siteRoot, 'public'); const outputRoot = path.join(publicRoot, 'api-reference'); await mkdir(outputRoot, { recursive: true }); + for (const sourceFile of sourceFiles) { + const destination = path.join(publicRoot, sourceFile); + await mkdir(path.dirname(destination), { recursive: true }); + await writeFile(destination, snapshots.get(sourceFile)); + } const bundlerConfig = path.join(siteRoot, 'api-reference-bundler.yml'); await writeFile(bundlerConfig, 'extends: []\n'); const scriptUrl = urlFor(base, scriptPath); await copyFile(path.join(rendererRoot, 'node_modules/@scalar/api-reference/dist/browser/standalone.js'), path.join(publicRoot, scriptPath)); - const supportFiles = [scriptPath]; + const supportFiles = [...sourceFiles, scriptPath]; for (const reference of references) { const relative = `api-reference/${reference.id}.json`; const output = path.join(publicRoot, relative); diff --git a/scripts/check-built.mjs b/scripts/check-built.mjs index 07bcca7..23cad01 100644 --- a/scripts/check-built.mjs +++ b/scripts/check-built.mjs @@ -277,6 +277,23 @@ export async function checkBuilt({ distDir, manifest, base = '/' }) { source: page.source, }); } + const pageCount = documents.size; + + for (const supportIndex of manifest.supportIndexes ?? []) { + const relative = outputPath(supportIndex); + const file = relative && inside(distDir, relative); + if (!relative || !file || !(await isFile(file))) continue; + const nodes = elements(parse(await readFile(file, 'utf8'))); + const route = relative.endsWith('/index.html') + ? relative.slice(0, -'/index.html'.length) + : path.posix.dirname(relative); + documents.set(file, { + names: new Set(nodes.map((node) => attribute(node, 'id')).filter(Boolean)), + nodes, + route, + source: relative, + }); + } if (manifest.unofficial) { const supportHtml = [...(manifest.redirects ?? []).map((item) => item.legacy), ...(manifest.supportIndexes ?? [])]; @@ -355,5 +372,5 @@ export async function checkBuilt({ distDir, manifest, base = '/' }) { if (!(await isFile(path.join(distDir, 'pagefind/pagefind.js')))) { errors.push('Missing Pagefind search output'); } - return { errors, pages: documents.size, links }; + return { errors, pages: pageCount, links }; } diff --git a/tests/api-references.test.mjs b/tests/api-references.test.mjs index 8d6c4c2..9f15761 100644 --- a/tests/api-references.test.mjs +++ b/tests/api-references.test.mjs @@ -81,7 +81,7 @@ const commonSchema = `{ "data": { "type": "object", "additionalProperties": true, - "properties": { "status": { "type": "string" } } + "properties": { "status": { "$dynamicRef": "./status.schema.json#status" } } } }, "x-source-metadata": { "authority": "fixture" } @@ -90,6 +90,13 @@ const commonSchema = `{ } `; +const statusSchema = `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$dynamicAnchor": "status", + "type": "string" +} +`; + const genericContract = `openapi: 3.1.2 info: title: Another building block fixture @@ -172,13 +179,19 @@ async function fixture(t, references) { await write(sourceRoot, 'api-references.yml', config(references)); await write(sourceRoot, 'api/openapi.yaml', contract); await write(sourceRoot, 'api/common/record.schema.json', commonSchema); + await write(sourceRoot, 'api/common/status.schema.json', statusSchema); return { root, sourceRoot, siteRoot }; } async function sourceBytes(sourceRoot) { return new Map( await Promise.all( - ['api-references.yml', 'api/openapi.yaml', 'api/common/record.schema.json'].map( + [ + 'api-references.yml', + 'api/openapi.yaml', + 'api/common/record.schema.json', + 'api/common/status.schema.json', + ].map( async (relative) => [relative, await readFile(path.join(sourceRoot, relative))], ), ), @@ -255,12 +268,39 @@ test('prepares labelled references from exact published 200 examples', async (t) assert.ok(supportFiles.some((file) => /(^|\/)scalar[^/]*\.js$/.test(file)), 'local Scalar asset'); assert.ok(supportFiles.includes('api-reference/record-retrieve.json')); assert.ok(supportFiles.includes('api-reference/record-search.json')); + assert.ok(supportFiles.includes('api/openapi.yaml'), 'declared source contract download'); + assert.ok(supportFiles.includes('api/common/record.schema.json'), 'source contract dependency download'); + assert.ok(supportFiles.includes('api/common/status.schema.json'), 'dynamic source dependency download'); assert.equal(supportFiles.some((file) => file.endsWith('.html')), false); assert.equal(references[0].viewerUrl, undefined); assert.equal(references[1].viewerUrl, undefined); - for (const relative of ['api-references.yml', 'api/openapi.yaml', 'api/common/record.schema.json']) { + for (const relative of [ + 'api-references.yml', + 'api/openapi.yaml', + 'api/common/record.schema.json', + 'api/common/status.schema.json', + ]) { assert.ok(snapshots.has(relative), `${relative} must contribute to source snapshots`); } + assert.equal( + (await readFile(path.join(siteRoot, 'public/api/openapi.yaml'))).compare(before.get('api/openapi.yaml')), + 0, + 'source contract download must preserve authoring bytes', + ); + assert.equal( + (await readFile(path.join(siteRoot, 'public/api/common/record.schema.json'))).compare( + before.get('api/common/record.schema.json'), + ), + 0, + 'source dependency download must preserve authoring bytes', + ); + assert.equal( + (await readFile(path.join(siteRoot, 'public/api/common/status.schema.json'))).compare( + before.get('api/common/status.schema.json'), + ), + 0, + 'dynamic source dependency download must preserve authoring bytes', + ); await assertSourceUnchanged(sourceRoot, before); }); @@ -581,6 +621,7 @@ versions: await write(sourceRoot, 'api-references.yml', config(references)); await write(sourceRoot, 'api/openapi.yaml', contract); await write(sourceRoot, 'api/common/record.schema.json', commonSchema); + await write(sourceRoot, 'api/common/status.schema.json', statusSchema); await execFileAsync('git', ['init', '-q', sourceRoot]); await execFileAsync('git', ['-C', sourceRoot, 'add', '.']); await execFileAsync('git', [ @@ -601,6 +642,7 @@ versions: 'api-references.yml', 'api/openapi.yaml', 'api/common/record.schema.json', + 'api/common/status.schema.json', ]; const before = new Map( await Promise.all( @@ -629,6 +671,19 @@ versions: 'generic navigation remains present', ); assert.equal(manifest.apiReferences.length, 2); + for (const relative of [ + 'api/openapi.yaml', + 'api/common/record.schema.json', + 'api/common/status.schema.json', + ]) { + assert.equal(manifest.supportFiles.includes(relative), true, `${relative} source download`); + assert.equal( + (await readFile(path.join(siteRoot, 'public', relative))).compare(before.get(relative)), + 0, + `${relative} published bytes`, + ); + } + assert.equal(manifest.supportFiles.includes('api-references.yml'), false); const corePage = await readFile( path.join(siteRoot, 'src/content/docs/contracts/core.md'), 'utf8', diff --git a/tests/check-built.test.mjs b/tests/check-built.test.mjs index e5dcdcf..87feb9e 100644 --- a/tests/check-built.test.mjs +++ b/tests/check-built.test.mjs @@ -88,7 +88,20 @@ test('checks declared pages, anchors, support output, base paths, and Pagefind', ); assert.deepEqual(result.errors, []); assert.equal(result.pages, 2); - assert.equal(result.links, 4); + assert.equal(result.links, 5); +}); + +test('checks links emitted by support directory indexes', async (t) => { + const options = await builtFixture(t, { base: '/standards/example/' }); + await write( + options.distDir, + 'resources/index.html', + `${draftHead}

    Resources

    Missing`, + ); + + const errors = (await checkBuilt(options)).errors.join('\n'); + + assert.match(errors, /resources\/index\.html: missing local target.*missing\.md/i); }); test('API reference verification requires a native host, closed metadata and the exact bundled contract', async (t) => { diff --git a/tests/framework.test.mjs b/tests/framework.test.mjs index deab765..5ea28b4 100644 --- a/tests/framework.test.mjs +++ b/tests/framework.test.mjs @@ -29,6 +29,7 @@ async function fixture() { - service.md resources: - testing.md + - linked.md `); await write(sourceRoot, 'metadata.yml', `name: Digital Registries abstract: A fixture Registry specification. @@ -138,7 +139,11 @@ Run the fixture. Supporting text. `); await write(sourceRoot, 'assets/diagram.svg', 'Diagram\n'); - await write(sourceRoot, 'api/openapi.yaml', 'openapi: 3.1.0\n'); + await write( + sourceRoot, + 'api/openapi.yaml', + 'openapi: 3.1.0\ncomponents:\n schemas:\n Common:\n $ref: common/govstack-openapi-common.yaml#/components\n', + ); await write(sourceRoot, 'api/extensions/example.schema.json', '{"type":"object"}\n'); await write(sourceRoot, 'api/common/govstack-openapi-common.yaml', 'components: {}\n'); await mkdir(path.join(sourceRoot, 'resources'), { recursive: true }); @@ -187,6 +192,117 @@ test('support path policy allows public compatibility paths and rejects hidden c } }); +test('a local Markdown link outside toc.yml is rejected instead of becoming a page', async () => { + const { sourceRoot, siteRoot } = await fixture(); + await write(sourceRoot, 'resources/unlisted.md', '# Unlisted\n'); + const readmePath = path.join(sourceRoot, 'README.md'); + await writeFile( + readmePath, + `${await readFile(readmePath, 'utf8')}\n[Unlisted page](resources/unlisted.md).\n`, + ); + + await assert.rejects( + generateSite({ sourceRoot, siteRoot, base: '/' }), + /README\.md: local Markdown page resources\/unlisted\.md is not listed in toc\.yml/i, + ); +}); + +test('unreferenced repository files are not published as support downloads', async () => { + const { sourceRoot, siteRoot } = await fixture(); + await write(sourceRoot, 'package-lock.json', '{"lockfileVersion":3}\n'); + await write(sourceRoot, 'tools/validate.py', 'print("fixture")\n'); + await write(sourceRoot, 'api/unreferenced.json', '{"type":"object"}\n'); + + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + + for (const relative of ['package-lock.json', 'tools/validate.py', 'api/unreferenced.json']) { + assert.equal(manifest.supportFiles.includes(relative), false, `${relative} must not be published`); + await assert.rejects(readFile(path.join(siteRoot, 'public', relative)), { code: 'ENOENT' }); + } +}); + +test('page-linked structured files publish their local ref and dynamicRef dependencies', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const readmePath = path.join(sourceRoot, 'README.md'); + await writeFile( + readmePath, + `${await readFile(readmePath, 'utf8')}\n[Contract](contracts/root.yaml).\n`, + ); + await write( + sourceRoot, + 'contracts/root.yaml', + "ordinary:\n $ref: schemas/ordinary.json#/$defs/value\ndynamic:\n $dynamicRef: schemas/dynamic.json#value\n", + ); + await write(sourceRoot, 'contracts/schemas/ordinary.json', '{"$defs":{"value":{"type":"string"}}}\n'); + await write(sourceRoot, 'contracts/schemas/dynamic.json', '{"$dynamicAnchor":"value","type":"string"}\n'); + + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); + + for (const relative of [ + 'contracts/root.yaml', + 'contracts/schemas/ordinary.json', + 'contracts/schemas/dynamic.json', + ]) { + assert.equal(manifest.supportFiles.includes(relative), true, `${relative} must be published`); + assert.equal( + (await readFile(path.join(siteRoot, 'public', relative))).compare( + await readFile(path.join(sourceRoot, relative)), + ), + 0, + `${relative} bytes must be preserved`, + ); + } +}); + +for (const keyword of ['$ref', '$dynamicRef']) { + test(`a missing local ${keyword} target fails generation`, async () => { + const { sourceRoot, siteRoot } = await fixture(); + const readmePath = path.join(sourceRoot, 'README.md'); + await writeFile( + readmePath, + `${await readFile(readmePath, 'utf8')}\n[Contract](contracts/root.json).\n`, + ); + await write(sourceRoot, 'contracts/root.json', JSON.stringify({ [keyword]: 'missing.json' })); + + await assert.rejects( + generateSite({ sourceRoot, siteRoot, base: '/' }), + /contracts\/root\.json: schema reference target contracts\/missing\.json does not exist/i, + ); + }); +} + +test('a local schema reference to a directory fails generation', async () => { + const { sourceRoot, siteRoot } = await fixture(); + const readmePath = path.join(sourceRoot, 'README.md'); + await writeFile( + readmePath, + `${await readFile(readmePath, 'utf8')}\n[Contract](contracts/root.json).\n`, + ); + await write(sourceRoot, 'contracts/root.json', '{"$ref":"schemas/"}\n'); + await write(sourceRoot, 'contracts/schemas/value.json', '{"type":"string"}\n'); + + await assert.rejects( + generateSite({ sourceRoot, siteRoot, base: '/' }), + /contracts\/root\.json: schema reference target contracts\/schemas is a directory/i, + ); +}); + +test('a support directory index lists only files that were published', async () => { + const { sourceRoot, siteRoot } = await fixture(); + await write(sourceRoot, 'api/extensions/private-notes.md', '# Private notes\n'); + + const manifest = await generateSite({ sourceRoot, siteRoot, base: '/docs/' }); + const index = await readFile(path.join(siteRoot, 'public/api/extensions/index.html'), 'utf8'); + + assert.match(index, /example\.schema\.json/); + assert.doesNotMatch(index, /private-notes\.md/); + assert.equal(manifest.supportFiles.includes('api/extensions/private-notes.md'), false); + await assert.rejects( + readFile(path.join(siteRoot, 'public/api/extensions/private-notes.md')), + { code: 'ENOENT' }, + ); +}); + test('generator rewrites routes, renders requirement semantics, copies aliases, and records provenance', async () => { const { sourceRoot, siteRoot } = await fixture(); const manifest = await generateSite({ sourceRoot, siteRoot, base: '/' }); @@ -197,6 +313,7 @@ test('generator rewrites routes, renders requirement semantics, copies aliases, assert.match(manifest.sourceRevision, /^[0-9a-f]{40}$/); assert.match(manifest.sourceDigest, /^sha256:[0-9a-f]{64}$/); assert.deepEqual(manifest.sidebar[0], { label: 'Home', slug: '' }); + assert.equal(manifest.sidebar.some(({ label }) => label === 'Linked documents'), false); const home = await readFile(path.join(siteRoot, 'src/content/docs/index.md'), 'utf8'); assert.match(home, /\[Linked document\]\(\/resources\/linked\/#linked-heading\)/); @@ -227,7 +344,10 @@ test('generator rewrites routes, renders requirement semantics, copies aliases, assert.match(requirements, /href="\/resources\/api\.yml"/); assert.equal((await lstat(path.join(siteRoot, 'public/resources/api.yml'))).isSymbolicLink(), false); - assert.equal(await readFile(path.join(siteRoot, 'public/resources/api.yml'), 'utf8'), 'openapi: 3.1.0\n'); + assert.match( + await readFile(path.join(siteRoot, 'public/resources/api.yml'), 'utf8'), + /\$ref: common\/govstack-openapi-common\.yaml/, + ); assert.equal( await readFile(path.join(siteRoot, 'public/resources/common/govstack-openapi-common.yaml'), 'utf8'), 'components: {}\n', @@ -384,7 +504,7 @@ test('support files omit hidden operational config without changing source bytes 'utf8', ); assert.match(extensionIndex, /extra\.schema\.json/); - assert.match(extensionIndex, />\.well-known\/<\/a>/); + assert.match(extensionIndex, />\.well-known\/catalog\.json<\/a>/); assert.doesNotMatch(extensionIndex, /\.env|\.npmrc|\.secrets/); for (const [relative, contents] of before) { @@ -488,14 +608,16 @@ test('canonical source integration renders its requirements without changing sou assert.match(requirements, /Any of/); assert.match(requirements, /Minimum selections/); - for (const archive of [ - 'resources/history/release-notes.md', - 'resources/history/requirements.md', - 'api/legacy/generated-crud.md', - ]) { - const renderedArchive = await readFile(path.join(siteRoot, 'src/content/docs', archive), 'utf8'); - assert.match(renderedArchive, /^pagefind: false$/m, `${archive} must stay out of default search`); - } + const releaseNotes = 'resources/history/release-notes.md'; + const renderedReleaseNotes = await readFile( + path.join(siteRoot, 'src/content/docs', releaseNotes), + 'utf8', + ); + assert.match( + renderedReleaseNotes, + /^pagefind: false$/m, + `${releaseNotes} must stay out of default search`, + ); const [afterRevision, afterStatus] = await Promise.all([ execFileAsync('git', ['--no-optional-locks', '-C', canonicalSourceRoot, 'rev-parse', 'HEAD']),