From 14ca0454253b271fddaadd88c61e13c1832a1789 Mon Sep 17 00:00:00 2001 From: Jeffrey Aven Date: Mon, 23 Nov 2026 16:22:54 +1100 Subject: [PATCH] Opt-in structured data for provider microsites: withStructuredData and check-site withStructuredData(config, { providerName, providerTitle }) wraps a createConfig result: registers @stackql/docusaurus-plugin-structured-data by name (resolved from the site's node_modules; this module still imports nothing), sets themeConfig.structuredData (stackql.io's Organization by @id, SoftwareSourceCode, SoftwareApplication defaults, TechArticle on the default docs instance, native BreadcrumbList reused, redirect stubs excluded, no SearchAction), removes the hand-written SoftwareApplication head tag by its @type, and turns on showLastUpdateTime. Throws rather than registering the plugin twice or wrapping a non-classic preset. The slug and repo derivation moves into providerIds(), shared by both functions. createConfig output is unchanged (JSON compare against main for all 42 catalog providers). scripts/structured-data/check-site.mjs checks a build directory or live URLs against the pilot's acceptance criteria and prints a per-page table. Co-Authored-By: Claude Opus 5.5 --- README.md | 83 +++++ index.js | 161 ++++++++- scripts/structured-data/check-site.mjs | 451 +++++++++++++++++++++++++ 3 files changed, 686 insertions(+), 9 deletions(-) create mode 100644 scripts/structured-data/check-site.mjs diff --git a/README.md b/README.md index 335f6d8..7da61a9 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,10 @@ the `createConfig` factory from there. scheduled workflow that keeps the Providers menu of every deployed microsite in step with the catalog, and the scripts it runs. See "Propagation". +- `withStructuredData` (in `index.js`) and `scripts/structured-data/` - + opt-in JSON-LD for a provider microsite and the script that checks a + built or deployed site against it. Piloted on two sites. See + "Structured data". - `catalog/last-known-good.json` - the last catalog the whole fleet was verified against, written by that workflow. The baseline its plausibility guard compares a new catalog with, and an audit trail of catalog changes. @@ -284,6 +288,85 @@ const config = { - The consumer today is the query library (`query-library.stackql.io` repo), proxied at `stackql.io/docs/query-library/`. +## Structured data + +Pilot status: opt-in, used by `homebrew` (GitHub Pages) and `cloudflare` +(Netlify) only. `createConfig` output is unchanged, and every other site +builds as before. + +`withStructuredData(config, { providerName, providerTitle })` takes the +config `createConfig` returned and adds JSON-LD from +[`@stackql/docusaurus-plugin-structured-data`](https://github.com/stackql-labs/docusaurus-plugin-structured-data) +(1.9.0 or later): + +```js +import { createConfig, withStructuredData } from './.shared-config/index.js'; + +const config = withStructuredData( + createConfig({ providerName, providerTitle, prismThemes }), + { providerName, providerTitle }, +); +// site-local adjustments stay here, after the wrap +export default config; +``` + +What it does to the config: + +- Appends `'@stackql/docusaurus-plugin-structured-data'` to `plugins`, by + name, so it resolves from the site's own `node_modules` and this module + still imports nothing. **The site must add the dependency** + (`@stackql/docusaurus-plugin-structured-data@^1.9.0` in + `website/package.json`, lockfile refreshed with the site's own package + manager). +- Sets `themeConfig.structuredData`: stackql.io's Organization by `@id` + (`https://stackql.io/#organization`, with the name, url, logo and sameAs + stackql.io's own graph carries), so every `publisher` names the parent + site rather than a second organization; a `SoftwareSourceCode` node for + `stackql-registry/stackql-provider-` authored by that + Organization (no `license`: the provider repos are not all under the + same licence); `SoftwareApplication` defaults (`StackQL + Provider`, free, download link to the install page); `TechArticle` on + every doc page except the provider-intro page at `/`; the native + `BreadcrumbList` Docusaurus writes on docs pages reused rather than + duplicated; the shared redirect stubs excluded; no `SearchAction` (the + microsites have no `/search`). +- Removes the hand-written `SoftwareApplication` JSON-LD head tag (matched + by its `@type`). The plugin emits one on the provider-intro page instead, + as its `WebPage.mainEntity`, when that page's front matter has + `softwareApplication: true` (add it to + `provider-dev/docgen/provider-data/headerContent1.txt` and regenerate + the docs). +- Turns on the docs plugin's `showLastUpdateTime`, so `dateModified` is + each page's last commit. That needs full git history at build time: + `fetch-depth: 0` on the checkout step of a GitHub Pages workflow. With a + shallow clone every page carries the same date. + +It throws if the plugin is already in `plugins`, if +`themeConfig.structuredData` is already set, or if `presets[0]` is not the +classic preset. + +`scripts/structured-data/check-site.mjs` checks the result, on a build or +on the live site (Node 22 built-ins, same conventions as +`scripts/menu-sync/`; the header is its contract): + +```sh +# a local build, with dateModified compared against git for three doc pages +node scripts/structured-data/check-site.mjs ../site/website/build --git ../site/website/docs + +# the deployed site: these URLs, every sitemap URL, plus the redirect stubs and /404.html +node scripts/structured-data/check-site.mjs https://homebrew-provider.stackql.io/ --sitemap +``` + +It prints a per-page table and exits non-zero on any failure. Pages that +share a `description` are reported as a warning only. + +Building on Windows: Docusaurus 3.10's eager git lookup (selected by +`future.faster` through its `gitEagerVcs` flag) misses every file when the +working directory's drive letter is lower case (`c:\...`, as VS Code +terminals start), so every page gets the build time as `dateModified`. +Build from `C:\...` (`cd "C:/..."` in Git Bash). The Linux runners are not +affected. + ## Cross-site link behavior Shared nav and footer items that point at the main site (`Install`, diff --git a/index.js b/index.js index d8075bb..58e7b97 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,20 @@ const MAIN_SITE = 'https://stackql.io'; const providerOrigin = (name) => `https://${name}-provider.stackql.io`; +// providerName is SQL-identifier-shaped (may contain underscores, e.g. +// 'entra_id'). Underscores aren't valid in DNS labels, so derive a slug for +// URLs and hostnames. providerName itself stays unchanged in user-visible +// text (titles, labels, keywords) where the underscore is correct. +// +// providerRepo is the GitHub repo name under stackql-registry, which uses +// neither separator (e.g. 'entra_id' -> 'entraid'). +function providerIds(providerName) { + return { + providerSlug: providerName.replace(/_/g, '-'), + providerRepo: providerName.replace(/_/g, ''), + }; +} + // The Providers menu is a two-level dropdown (category -> provider) built // from the provider catalog the main site publishes at // https://stackql.io/providers.json (stackql.io repo: plugins/provider-catalog, @@ -389,15 +403,7 @@ function createConfig({ providerName, providerTitle, prismThemes, overrides = {} throw new Error('createConfig requires prismThemes (pass `themes` from prism-react-renderer)'); } - // providerName is SQL-identifier-shaped (may contain underscores, e.g. - // 'entra_id'). Underscores aren't valid in DNS labels, so derive a slug for - // URLs and hostnames. providerName itself stays unchanged in user-visible - // text (titles, labels, keywords) where the underscore is correct. - // - // providerRepo is the GitHub repo name under stackql-registry, which uses - // neither separator (e.g. 'entra_id' -> 'entraid'). - const providerSlug = providerName.replace(/_/g, '-'); - const providerRepo = providerName.replace(/_/g, ''); + const { providerSlug, providerRepo } = providerIds(providerName); const lightCodeTheme = prismThemes.github; const darkCodeTheme = prismThemes.dracula; @@ -538,8 +544,145 @@ function createConfig({ providerName, providerTitle, prismThemes, overrides = {} return { ...config, ...overrides }; } +// Structured data (JSON-LD) for a provider microsite, opt-in while it is +// piloted (README, "Structured data"). Sites that do not call this are +// unchanged. +const STRUCTURED_DATA_PLUGIN = '@stackql/docusaurus-plugin-structured-data'; +const CLASSIC_PRESETS = ['@docusaurus/preset-classic', 'classic']; + +// stackql.io's Organization, as its own graph states it (stackql.io repo: +// themeConfig.structuredData.organization, siteConfig.title and url). A +// microsite names it by @id instead of describing a second organization. +// Keep in step with that config. +const MAIN_SITE_ORGANIZATION = { + '@id': `${MAIN_SITE}/#organization`, + name: 'StackQL', + url: MAIN_SITE, + logo: { + '@type': 'ImageObject', + inLanguage: 'en-US', + '@id': `${MAIN_SITE}/#logo`, + url: `${MAIN_SITE}/android-chrome-512x512.png`, + contentUrl: `${MAIN_SITE}/android-chrome-512x512.png`, + width: 512, + height: 512, + caption: 'StackQL', + }, + sameAs: [ + 'https://twitter.com/stackql', + 'https://www.linkedin.com/company/stackql', + 'https://github.com/stackql', + 'https://www.youtube.com/@stackql', + 'https://hub.docker.com/u/stackql', + ], +}; + +const pluginName = (entry) => + typeof entry === 'string' ? entry : Array.isArray(entry) && typeof entry[0] === 'string' ? entry[0] : null; + +// A head tag that is a JSON-LD SoftwareApplication (the one createConfig +// writes by hand), recognised by its parsed @type rather than its position. +function isSoftwareApplicationJsonLd(tag) { + if (!tag || tag.tagName !== 'script') return false; + if (!tag.attributes || tag.attributes.type !== 'application/ld+json') return false; + try { + const types = [].concat(JSON.parse(tag.innerHTML)['@type']); + return types.includes('SoftwareApplication'); + } catch { + return false; + } +} + +// Adds @stackql/docusaurus-plugin-structured-data to a createConfig result, +// with the settings every provider microsite shares, and returns the config. +// +// export default withStructuredData( +// createConfig({ providerName, providerTitle, prismThemes }), +// { providerName, providerTitle }, +// ); +// +// The plugin is registered by name, so it resolves from the site's own +// node_modules (the site adds the dependency) and this module still imports +// nothing. Also: the hand-written SoftwareApplication JSON-LD head tag is +// removed (the plugin emits one on the provider-intro page instead, from its +// `softwareApplication: true` front matter), and the docs plugin's +// showLastUpdateTime is turned on so dateModified is the page's last commit. +// That needs full git history at build time (fetch-depth: 0 on GitHub +// Pages); a shallow clone gives every page the same date. +function withStructuredData(config, { providerName, providerTitle } = {}) { + if (!providerName || !providerTitle) { + throw new Error('withStructuredData requires providerName and providerTitle'); + } + if (!config || typeof config !== 'object') { + throw new Error('withStructuredData takes the config createConfig returned'); + } + const plugins = Array.isArray(config.plugins) ? config.plugins : []; + if (plugins.some((entry) => /docusaurus-plugin-structured-data/.test(pluginName(entry) || ''))) { + throw new Error( + `withStructuredData: ${STRUCTURED_DATA_PLUGIN} is already in config.plugins; remove it, or do not call withStructuredData`, + ); + } + if (config.themeConfig && config.themeConfig.structuredData) { + throw new Error('withStructuredData: config.themeConfig.structuredData is already set; withStructuredData owns it'); + } + const [preset, ...otherPresets] = Array.isArray(config.presets) ? config.presets : []; + const presetName = Array.isArray(preset) ? preset[0] : preset; + if (!CLASSIC_PRESETS.includes(presetName)) { + throw new Error( + `withStructuredData: config.presets[0] must be ['@docusaurus/preset-classic', { ... }] (got ${JSON.stringify(presetName)})`, + ); + } + const presetOptions = (Array.isArray(preset) && preset[1]) || {}; + if (presetOptions.docs === false) { + throw new Error('withStructuredData: the classic preset has docs: false; provider microsites need the docs plugin'); + } + + const { providerRepo } = providerIds(providerName); + const repo = `stackql-provider-${providerRepo}`; + + config.plugins = [...plugins, STRUCTURED_DATA_PLUGIN]; + config.headTags = (config.headTags || []).filter((tag) => !isSoftwareApplicationJsonLd(tag)); + config.presets = [ + [presetName, { ...presetOptions, docs: { ...presetOptions.docs, showLastUpdateTime: true } }], + ...otherPresets, + ]; + config.themeConfig = { + ...config.themeConfig, + structuredData: { + // Docusaurus already emits a BreadcrumbList on docs pages + nativeStructuredData: 'reuse', + // the shared redirect stubs (/install, /docs/mcp, ...) are not content + excludedRoutes: redirectRoutes(config.baseUrl || '/'), + // docs live at '/'; the /docs/* routes here are redirect stubs + techArticleRoutePrefixes: [], + techArticleDocsInstances: ['default'], + // themeConfig.image, img/stackql-featured-image.png + featuredImageDimensions: { width: 1200, height: 627 }, + // provider sites have no /search + website: { potentialAction: [] }, + organization: structuredClone(MAIN_SITE_ORGANIZATION), + softwareSourceCode: { + name: repo, + codeRepository: `https://github.com/stackql-registry/${repo}`, + author: { '@id': MAIN_SITE_ORGANIZATION['@id'] }, + }, + softwareApplication: { + name: `StackQL ${providerTitle} Provider`, + applicationCategory: 'DeveloperApplication', + operatingSystem: 'macOS, Linux, Windows', + isAccessibleForFree: true, + downloadUrl: `${MAIN_SITE}/installing-stackql`, + }, + }, + }; + return config; +} + module.exports = { createConfig, + // Opt-in structured data for a provider microsite: wraps a createConfig + // result. See README, "Structured data". + withStructuredData, // Building blocks for a site whose shape createConfig cannot express (a // non-root baseUrl, its own plugins and presets): compose the shared // chrome into your own config. See README, "Composing instead of diff --git a/scripts/structured-data/check-site.mjs b/scripts/structured-data/check-site.mjs new file mode 100644 index 0000000..c921d5e --- /dev/null +++ b/scripts/structured-data/check-site.mjs @@ -0,0 +1,451 @@ +#!/usr/bin/env node +// Check the JSON-LD a provider microsite serves against the structured-data +// pilot's acceptance criteria (withStructuredData in index.js, README +// "Structured data"). +// +// node scripts/structured-data/check-site.mjs <build dir> [options] +// node scripts/structured-data/check-site.mjs <url> [<url> ...] [options] +// +// --git <docs dir> compare dateModified with `git log -1 --format=%cI` +// for --sample doc pages; <docs dir> is the site's +// docs folder in a checkout of the deployed commit +// --sample <n> pages for the git comparison (default 3: the first, +// middle and last doc page in route order) +// --organization <iri> the Organization @id every reference must use +// (default https://stackql.io/#organization) +// --sitemap live: also check every <loc> in each origin's +// /sitemap.xml +// --no-stubs live: do not add the shared redirect routes and +// /404.html of each origin to the URLs checked +// --failures-only print only the rows that fail +// --json <file> also write the full results as JSON +// +// A build directory is walked for every .html file. Live URLs are fetched +// (cache-busted, concurrency 8); for each origin among them the shared +// redirect routes (redirectRoutes('/') from index.js) and /404.html are +// added unless --no-stubs. Each page is one of: +// +// stub a shared redirect route, or any page with a meta refresh +// 404 /404.html +// page everything else: a page the plugin processes +// +// JSON-LD blocks are every <script type=application/ld+json>, quoted or not +// (built HTML is minified with unquoted attributes; pages the plugin +// rewrote are re-serialised with quotes). The plugin's block is the one +// without data-rh whose JSON is an @graph holding a WebPage; data-rh blocks +// are Docusaurus's own ("native"). +// +// Per page (FAIL): +// every JSON-LD block parses +// page: exactly one plugin block +// page: a native BreadcrumbList means none in the plugin graph and no +// WebPage.breadcrumb; a docs page (html class docs-doc-page) must have +// a native BreadcrumbList +// page: one Organization node, @id = --organization; every `publisher` +// and SoftwareSourceCode.author is { "@id": --organization } +// page: WebSite has no potentialAction (absent, or [] - an empty array is +// no value in JSON-LD, and the plugin's documented way to drop it) +// page: SoftwareApplication in the plugin graph on / only, as +// WebPage.mainEntity +// page: TechArticle on every docs page except /, and not on / +// page: WebPage.url equals the page's <link rel=canonical> href +// stub, 404: no plugin block +// all: no SoftwareApplication in any block but the plugin's (the +// hand-written head tag createConfig adds is gone); no +// https://<slug>-provider.stackql.io/#organization anywhere in the HTML +// +// Across pages (FAIL): dateModified is not the same on every page; with +// --git, it equals the file's last commit for each sampled doc page. +// Across pages (WARN, exit code unaffected): TechArticle pages sharing a +// WebPage.description; / not among the pages checked. +// +// Prints a per-page table and a summary. Exit 0 when nothing fails, 1 when +// any check fails, 2 on bad arguments or no pages to check. +// +// Node 22 built-ins only: this repo has no package.json by design (README). + +import fs from 'node:fs'; +import path from 'node:path'; +import {execFileSync} from 'node:child_process'; +import {createRequire} from 'node:module'; +import {fileURLToPath} from 'node:url'; + +const require = createRequire(import.meta.url); +const {redirectRoutes} = require('../../index.js'); + +export const DEFAULT_ORGANIZATION = 'https://stackql.io/#organization'; +export const FETCH_TIMEOUT_MS = 20_000; +const CONCURRENCY = 8; +const PROVIDER_ORG_ID = /https?:\/\/[a-z0-9-]+-provider\.stackql\.io\/#organization/g; + +// ------------------------------------------------------------ HTML parsing + +const ENTITIES = {amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'", '#x27': "'", '#x2F': '/', '#47': '/'}; +const decode = (s) => s.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (m, e) => ENTITIES[e] ?? ENTITIES[e.toLowerCase()] ?? m); + +// Attributes of a start tag, quoted or not: `type=application/ld+json`, +// `type="application/ld+json"`, bare `data-rh`. +export function parseAttrs(text) { + const attrs = {}; + const re = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + for (const m of text.matchAll(re)) { + attrs[m[1].toLowerCase()] = decode(m[2] ?? m[3] ?? m[4] ?? ''); + } + return attrs; +} + +const tags = (html, name) => [...html.matchAll(new RegExp(`<${name}\\b([^>]*)>`, 'gi'))].map((m) => parseAttrs(m[1])); + +// Every application/ld+json block: {native, json, error}. +export function jsonLdBlocks(html) { + const blocks = []; + for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) { + const attrs = parseAttrs(m[1]); + if ((attrs.type || '').toLowerCase() !== 'application/ld+json') continue; + const block = {native: 'data-rh' in attrs, json: null, error: null}; + try { + block.json = JSON.parse(m[2]); + } catch (error) { + block.error = error.message; + } + blocks.push(block); + } + return blocks; +} + +// Top-level nodes of a block, members of a top-level @graph included. +function nodesOf(json) { + if (Array.isArray(json)) return json.flatMap(nodesOf); + if (json && typeof json === 'object') return Array.isArray(json['@graph']) ? json['@graph'].flatMap(nodesOf) : [json]; + return []; +} + +const typesOf = (node) => [].concat(node && node['@type']).filter((t) => typeof t === 'string'); +const hasType = (node, type) => typesOf(node).includes(type); + +const isPluginBlock = (block) => + !block.native && block.json && Array.isArray(block.json['@graph']) && block.json['@graph'].some((n) => hasType(n, 'WebPage')); + +// Every value of `key` anywhere inside a value, nested nodes included. +function valuesOf(value, key, found = []) { + if (Array.isArray(value)) value.forEach((v) => valuesOf(v, key, found)); + else if (value && typeof value === 'object') { + for (const [k, v] of Object.entries(value)) { + if (k === key) found.push(v); + valuesOf(v, key, found); + } + } + return found; +} + +const isRef = (value, id) => value && typeof value === 'object' && !Array.isArray(value) && value['@id'] === id; + +// ------------------------------------------------------------- one page + +export function normalizeRoute(route) { + let r = route.replace(/\/index\.html$/, '/').replace(/\.html$/, (m) => (route.endsWith('/404.html') ? m : '')); + if (r.length > 1) r = r.replace(/\/+$/, ''); + return r || '/'; +} + +// Check one page's HTML. `route` is normalised; `redirects` the shared +// redirect routes. Returns the row for the table plus what the site-level +// checks need. +export function checkPage({route, html, redirects, organization}) { + const failures = []; + const fail = (msg) => failures.push(msg); + const blocks = jsonLdBlocks(html); + const metas = tags(html, 'meta'); + const isRefresh = metas.some((m) => (m['http-equiv'] || '').toLowerCase() === 'refresh'); + const kind = route === '/404.html' ? '404' : redirects.has(route) || isRefresh ? 'stub' : 'page'; + const htmlTag = tags(html, 'html')[0] || {}; + const isDoc = (htmlTag.class || '').split(/\s+/).includes('docs-doc-page'); + + blocks.filter((b) => b.error).forEach((b) => fail(`JSON-LD does not parse (${b.error})`)); + const plugin = blocks.filter(isPluginBlock); + const native = blocks.filter((b) => b.native && b.json); + const foreign = blocks.filter((b) => !b.native && b.json && !isPluginBlock(b)); + + // everywhere: no hand-written SoftwareApplication, no microsite Organization + if ([...native, ...foreign].some((b) => nodesOf(b.json).some((n) => hasType(n, 'SoftwareApplication')))) { + fail('SoftwareApplication outside the plugin graph (hand-written head tag?)'); + } + const ownOrg = [...new Set(html.match(PROVIDER_ORG_ID) || [])].filter((id) => id !== organization); + if (ownOrg.length) fail(`names ${ownOrg.join(', ')}`); + + const row = {route, kind, doc: isDoc, plugin: plugin.length, native: native.length, other: foreign.length, main: '', dateModified: null, description: null, techArticle: false, failures}; + + if (kind !== 'page') { + if (plugin.length) fail(`${kind} carries ${plugin.length} plugin JSON-LD block(s)`); + return row; + } + if (plugin.length !== 1) { + fail(`${plugin.length} plugin JSON-LD blocks, expected 1`); + if (!plugin.length) return row; + } + + const graph = plugin[0].json['@graph']; + const one = (type) => graph.filter((n) => hasType(n, type)); + const [webPage] = one('WebPage'); + const techArticles = one('TechArticle'); + const softwareApps = one('SoftwareApplication'); + row.main = [techArticles.length ? 'TechArticle' : 'WebPage', ...(softwareApps.length ? ['+SoftwareApplication'] : [])].join(' '); + row.dateModified = webPage.dateModified || null; + row.description = webPage.description || null; + row.techArticle = techArticles.length > 0; + + // breadcrumbs + const nativeCrumbs = native.some((b) => nodesOf(b.json).some((n) => hasType(n, 'BreadcrumbList'))); + if (nativeCrumbs) { + if (one('BreadcrumbList').length) fail('plugin BreadcrumbList next to the native one'); + if ('breadcrumb' in webPage) fail('WebPage.breadcrumb set although the page has a native BreadcrumbList'); + } else if (isDoc) { + fail('docs page without a native BreadcrumbList'); + } + + // organization + const orgs = one('Organization'); + if (orgs.length !== 1) fail(`${orgs.length} Organization nodes, expected 1`); + else if (orgs[0]['@id'] !== organization) fail(`Organization @id is ${JSON.stringify(orgs[0]['@id'])}`); + const publishers = valuesOf(graph, 'publisher'); + if (!publishers.length) fail('no publisher in the graph'); + publishers.filter((p) => !isRef(p, organization)).forEach((p) => fail(`publisher is ${JSON.stringify(p)}`)); + const sources = one('SoftwareSourceCode'); + if (!sources.length) fail('no SoftwareSourceCode'); + sources.filter((s) => !isRef(s.author, organization)).forEach((s) => fail(`SoftwareSourceCode.author is ${JSON.stringify(s.author)}`)); + + // website + const sites = one('WebSite'); + if (sites.length !== 1) fail(`${sites.length} WebSite nodes, expected 1`); + sites.forEach((s) => { + const pa = s.potentialAction; + if (pa !== undefined && !(Array.isArray(pa) && pa.length === 0)) fail('WebSite has a potentialAction'); + }); + + // SoftwareApplication on / only, as WebPage.mainEntity + if (route === '/') { + if (softwareApps.length !== 1) fail(`${softwareApps.length} SoftwareApplication nodes on /, expected 1`); + else if (!isRef(webPage.mainEntity, softwareApps[0]['@id'])) fail('SoftwareApplication on / is not WebPage.mainEntity'); + } else if (softwareApps.length) { + fail('SoftwareApplication on a page other than /'); + } + + // TechArticle on docs pages other than / + if (route === '/' && techArticles.length) fail('TechArticle on /'); + if (route !== '/' && isDoc && !techArticles.length) fail('docs page without TechArticle'); + + // canonical + const canonical = tags(html, 'link').find((l) => (l.rel || '').toLowerCase().split(/\s+/).includes('canonical')); + if (!canonical) fail('no <link rel=canonical>'); + else if (canonical.href !== webPage.url) fail(`WebPage.url ${webPage.url} != canonical ${canonical.href}`); + + return row; +} + +// ------------------------------------------------------------- inputs + +function walkHtml(dir, base = dir, out = []) { + for (const entry of fs.readdirSync(dir, {withFileTypes: true})) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walkHtml(full, base, out); + else if (entry.name.endsWith('.html')) out.push(full); + } + return out; +} + +function buildPages(dir) { + return walkHtml(dir).map((file) => { + const rel = `/${path.relative(dir, file).split(path.sep).join('/')}`; + return {route: normalizeRoute(rel === '/index.html' ? '/' : rel), source: file, load: () => fs.readFileSync(file, 'utf8')}; + }); +} + +async function fetchText(url) { + const busted = new URL(url); + busted.searchParams.set('cb', String(Date.now())); + const response = await fetch(busted, { + headers: {accept: 'text/html,application/xml', 'cache-control': 'no-cache', pragma: 'no-cache', 'user-agent': 'stackql-check-site'}, + redirect: 'follow', + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return response.text(); +} + +async function livePages(urls, {sitemap, stubs, redirects}) { + const all = new Set(urls); + const origins = [...new Set(urls.map((u) => new URL(u).origin))]; + for (const origin of origins) { + if (sitemap) { + const xml = await fetchText(`${origin}/sitemap.xml`); + for (const m of xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)) all.add(decode(m[1])); + } + if (stubs) { + redirects.forEach((r) => all.add(`${origin}${r}`)); + all.add(`${origin}/404.html`); + } + } + return [...all].map((url) => ({route: normalizeRoute(new URL(url).pathname), source: url, load: () => fetchText(url)})); +} + +async function mapLimit(items, limit, fn) { + const results = new Array(items.length); + let next = 0; + await Promise.all(Array.from({length: Math.min(limit, items.length)}, async () => { + while (next < items.length) { + const i = next++; + results[i] = await fn(items[i], i); + } + })); + return results; +} + +// ------------------------------------------------------- site-level checks + +// The doc source behind a route, under the docs folder (docs at the site root). +function docFile(docsDir, route) { + const rel = route === '/' ? 'index' : route.slice(1); + return [`${rel}.md`, `${rel}.mdx`, `${rel}/index.md`, `${rel}/index.mdx`].find((f) => fs.existsSync(path.join(docsDir, f))) || null; +} + +function pickSample(rows, n) { + if (rows.length <= n) return rows; + if (n === 1) return [rows[0]]; + return Array.from({length: n}, (_, i) => rows[Math.round((i * (rows.length - 1)) / (n - 1))]); +} + +export function siteChecks(rows, {gitDir, sample}) { + const failures = []; + const warnings = []; + const notes = []; + const pages = rows.filter((r) => r.kind === 'page' && r.dateModified); + + const dates = new Set(pages.map((r) => r.dateModified)); + if (pages.length > 1 && dates.size === 1) failures.push(`dateModified is ${[...dates][0]} on all ${pages.length} pages (shallow clone, or no git dates?)`); + notes.push(`dateModified: ${dates.size} distinct value(s) across ${pages.length} page(s)`); + + if (gitDir) { + const docs = pages.filter((r) => r.doc).sort((a, b) => a.route.localeCompare(b.route)); + for (const row of pickSample(docs, sample)) { + const file = docFile(gitDir, row.route); + if (!file) { + failures.push(`git: no source file for ${row.route} under ${gitDir}`); + continue; + } + const committed = execFileSync('git', ['log', '-1', '--format=%cI', '--', file], {cwd: gitDir, encoding: 'utf8'}).trim(); + const same = committed && Date.parse(committed) === Date.parse(row.dateModified); + notes.push(`git: ${row.route} dateModified ${row.dateModified}, last commit of ${file} ${committed || 'none'} -> ${same ? 'match' : 'MISMATCH'}`); + if (!same) failures.push(`git: ${row.route} dateModified ${row.dateModified} != last commit ${committed || 'none'} (${file})`); + } + } else { + notes.push('git: skipped (no --git)'); + } + + const articles = pages.filter((r) => r.techArticle); + const byDescription = new Map(); + articles.forEach((r) => byDescription.set(r.description, [...(byDescription.get(r.description) || []), r.route])); + const shared = [...byDescription.entries()].filter(([, routes]) => routes.length > 1); + if (shared.length) { + const count = shared.reduce((n, [, routes]) => n + routes.length, 0); + warnings.push(`${count} of ${articles.length} TechArticle pages share a WebPage.description (${byDescription.size} distinct); most common: ${JSON.stringify(shared.sort((a, b) => b[1].length - a[1].length)[0][0])}`); + } + if (!rows.some((r) => r.route === '/' && r.kind === 'page')) warnings.push('/ was not among the pages checked: the SoftwareApplication check did not run'); + return {failures, warnings, notes}; +} + +// ------------------------------------------------------------------- CLI + +function parseArgs(argv) { + const args = {inputs: [], git: null, sample: 3, organization: DEFAULT_ORGANIZATION, sitemap: false, stubs: true, failuresOnly: false, json: null}; + for (let i = 0; i < argv.length; i += 1) { + const a = argv[i]; + if (a === '--git') args.git = path.resolve(argv[++i]); + else if (a === '--sample') args.sample = Math.max(1, Number(argv[++i]) || 3); + else if (a === '--organization') args.organization = argv[++i]; + else if (a === '--sitemap') args.sitemap = true; + else if (a === '--no-stubs') args.stubs = false; + else if (a === '--failures-only') args.failuresOnly = true; + else if (a === '--json') args.json = argv[++i]; + else if (a.startsWith('--')) throw new Error(`unknown option ${a}`); + else args.inputs.push(a); + } + if (!args.inputs.length) throw new Error('usage: check-site.mjs <build dir> | <url> [<url> ...] [--git <docs dir>] [--sample N] [--organization IRI] [--sitemap] [--no-stubs] [--failures-only] [--json FILE]'); + const urls = args.inputs.filter((x) => /^https?:\/\//i.test(x)); + if (urls.length && urls.length !== args.inputs.length) throw new Error('give either one build directory or a list of URLs, not both'); + if (!urls.length && args.inputs.length !== 1) throw new Error('give one build directory'); + if (!urls.length && !fs.statSync(args.inputs[0], {throwIfNoEntry: false})?.isDirectory()) throw new Error(`${args.inputs[0]} is not a directory`); + if (args.git && !fs.statSync(args.git, {throwIfNoEntry: false})?.isDirectory()) throw new Error(`--git ${args.git} is not a directory`); + args.live = urls.length > 0; + return args; +} + +function table(rows) { + const cols = [ + ['route', (r) => r.route], + ['kind', (r) => r.kind], + ['ld+json p/n/o', (r) => `${r.plugin}/${r.native}/${r.other}`], + ['main', (r) => r.main || '-'], + ['dateModified', (r) => r.dateModified || '-'], + ['result', (r) => (r.failures.length ? `FAIL: ${r.failures.join('; ')}` : 'ok')], + ]; + const cells = rows.map((r) => cols.map(([, f]) => String(f(r)))); + const widths = cols.map(([h], i) => Math.min(60, Math.max(h.length, ...cells.map((c) => (i === cols.length - 1 ? 0 : c[i].length))))); + const line = (vals) => vals.map((v, i) => (i === vals.length - 1 ? v : v.padEnd(widths[i]))).join(' '); + return [line(cols.map(([h]) => h)), line(widths.map((w, i) => '-'.repeat(i === cols.length - 1 ? 6 : w))), ...cells.map(line)].join('\n'); +} + +async function main(argv) { + let args; + try { + args = parseArgs(argv); + } catch (error) { + console.error(error.message); + process.exitCode = 2; + return; + } + const redirects = new Set(redirectRoutes('/')); + let pages; + try { + pages = args.live + ? await livePages(args.inputs, {sitemap: args.sitemap, stubs: args.stubs, redirects}) + : buildPages(args.inputs[0]); + } catch (error) { + console.error(`could not list pages: ${error.message}`); + process.exitCode = 2; + return; + } + if (!pages.length) { + console.error('no pages to check'); + process.exitCode = 2; + return; + } + + const rows = await mapLimit(pages, args.live ? CONCURRENCY : 1, async (p) => { + try { + return {source: p.source, ...checkPage({route: p.route, html: await p.load(), redirects, organization: args.organization})}; + } catch (error) { + return {source: p.source, route: p.route, kind: '?', plugin: 0, native: 0, other: 0, main: '', dateModified: null, failures: [`could not read: ${error.message}`]}; + } + }); + rows.sort((a, b) => a.route.localeCompare(b.route)); + + const site = siteChecks(rows, {gitDir: args.git, sample: args.sample}); + const failedRows = rows.filter((r) => r.failures.length); + const shown = args.failuresOnly ? failedRows : rows; + if (shown.length) console.log(`${table(shown)}\n`); + + const count = (kind) => rows.filter((r) => r.kind === kind).length; + console.log(`pages: ${rows.length} (${count('page')} processed, ${count('stub')} redirect stubs, ${count('404')} 404)`); + site.notes.forEach((n) => console.log(n)); + site.warnings.forEach((w) => console.log(`WARN ${w}`)); + site.failures.forEach((f) => console.log(`FAIL ${f}`)); + const ok = !failedRows.length && !site.failures.length; + console.log(ok ? 'result: pass' : `result: FAIL (${failedRows.length} page(s), ${site.failures.length} site-level)`); + + if (args.json) fs.writeFileSync(args.json, `${JSON.stringify({ok, rows, site}, null, 2)}\n`); + process.exitCode = ok ? 0 : 1; +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === fs.realpathSync(process.argv[1])) { + main(process.argv.slice(2)); +}