@duffcloudservices/cms 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/serveDefineInject.ts","../../src/plugins/motionTokens.ts","../../src/plugins/agentWidget.ts","../../src/plugins/dcsContentPlugin.ts","../../src/plugins/dcsResponsiveImageLint.ts","../../src/plugins/dcsDirIndex.ts","../../src/seo/playwrightRenderer.ts","../../src/plugins/routeLastmod.ts","../../src/plugins/dcsSeoPlugin.ts","../../src/plugins/dcsEditorPlugin.ts","../../src/plugins/dcsPreviewPlugin.ts","../../src/plugins/dcsCdnImagePlugin.ts","../../src/plugins/responsiveImagePlugin.ts"],"names":["path","fs","yaml","config","h","hit","escapeHtml","isVectorImageUrl"],"mappings":";;;;;;;;;;;;;AAiCO,SAAS,cAAA,CAAe,aAAqB,OAAA,EAA2B;AAC7E,EAAA,OAAO;AAAA,IACLA,KAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,OAAO,CAAA;AAAA,IACjCA,KAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,IAAA,EAAM,OAAO,CAAA;AAAA,IACvCA,KAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,GAAA,IAAO,OAAO;AAAA,GACrC;AACF;AAGO,SAAS,cAAA,CAAe,aAAqB,OAAA,EAAqC;AACvF,EAAA,OAAO,cAAA,CAAe,WAAA,EAAa,OAAO,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,KAAMC,GAAA,CAAG,UAAA,CAAW,CAAC,CAAC,CAAA;AAC1E;AAOO,SAAS,gBAAA,CACd,WAAA,EACA,OAAA,EACA,KAAA,EACA,QAAQ,KAAA,EACO;AACf,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,WAAA,EAAa,OAAO,CAAA;AACjD,EAAA,IAAI,CAAC,KAAA,EAAO;AACV,IAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAA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IAAA,CAAK,WAAA,CAAY,MAAA,EAAQ,GAAA,EAAK,OAAO,CAAA;AAAA,IAC9C;AAEA,IAAA,MAAM,GAAG,QAAA,EAAU,IAAI,CAAA,GAAI,KAAA;AAE3B,IAAA,MAAM,MAAA,GAAS;AAAA,MACb,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,aAAA,CAAA;AAAA,MAClB,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,cAAA,CAAA;AAAA,MAClB,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,cAAA;AAAA,KACpB,CAAE,KAAK,IAAI,CAAA;AAEX,IAAA,MAAM,UAAA,GAAaD,YAAW,GAAG,CAAA;AASjC,IAAA,MAAM,eAAA,GAAkBA,YAAW,GAAG,CAAA;AACtC,IAAA,MAAM,OAAA,GACJ,+BAA+B,eAAe,CAAA,4EAAA,CAAA;AAGhD,IAAA,OAAO;AAAA,MACL,WAAA;AAAA,MACA,qBAAqB,MAAM,CAAA,gEAAA,CAAA;AAAA,MAC3B,eAAe,QAAQ,CAAA,EAAG,IAAI,CAAA,eAAA,EAAkB,UAAU,8CAA8C,OAAO,CAAA,IAAA,CAAA;AAAA,MAC/G;AAAA,KACF,CAAE,KAAK,IAAI,CAAA;AAAA,EACb,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Shared serve-mode helpers for the DCS content + SEO Vite plugins.\n *\n * In a production build the plugins bake the `.dcs/*.yaml` payload into a Vite\n * `define` literal (`define: { __DCS_X__: JSON.stringify(data) }`) so the SSG /\n * SPA bundle inlines it exactly as before.\n *\n * In dev (`vite` / `vitepress dev`, i.e. the portal preview) baking a literal\n * is wrong: the value is frozen at server-start and only a `server.restart()`\n * would refresh it — and that restart is exactly what triggers VitePress's\n * MiniSearch rebuild and the duplicate-heading \"server restart failed\" crash.\n *\n * Instead, in serve mode the plugins:\n * 1. redirect the `__DCS_X__` define to a browser global\n * (`define: { __DCS_X__: 'globalThis.__DCS_X__' }`), and\n * 2. inject an inline classic `<script>` at the top of `<head>` on every HTML\n * request that assigns the FRESH on-disk YAML to that global.\n *\n * Because `transformIndexHtml` re-runs on every dev HTML request, a plain\n * iframe reload (the portal's `?_hc` hard reload) reflects the latest on-disk\n * content with NO `server.restart()` and NO module-graph surgery. The consumer\n * is untouched: it still reads the bare `__DCS_X__` identifier, which the define\n * rewrites to `globalThis.__DCS_X__`.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\n\n/**\n * The three `.dcs` search locations the plugins have always used. VitePress\n * projects have the `docs/` folder as root, so the parent is checked too.\n */\nexport function dcsSearchPaths(projectRoot: string, relPath: string): string[] {\n return [\n path.resolve(projectRoot, relPath),\n path.resolve(projectRoot, '..', relPath),\n path.resolve(process.cwd(), relPath),\n ]\n}\n\n/** First existing `.dcs` file from the standard search, or `undefined`. */\nexport function resolveDcsFile(projectRoot: string, relPath: string): string | undefined {\n return dcsSearchPaths(projectRoot, relPath).find((p) => fs.existsSync(p))\n}\n\n/**\n * Read + parse a `.dcs` YAML file FRESH from disk on every call (no caching).\n * Returns the parsed value, or `undefined` when the file is missing or\n * unparseable. Never throws — a dev HTML request must never 500 on bad YAML.\n */\nexport function readDcsYamlFresh<T = unknown>(\n projectRoot: string,\n relPath: string,\n label: string,\n debug = false\n): T | undefined {\n const found = resolveDcsFile(projectRoot, relPath)\n if (!found) {\n if (debug) console.log(`[${label}] serve: no ${relPath} found; global left unset`)\n return undefined\n }\n try {\n return yaml.load(fs.readFileSync(found, 'utf8')) as T\n } catch (error) {\n console.warn(`[${label}] serve: failed to parse ${relPath}:`, error)\n return undefined\n }\n}\n\n/**\n * Build a safe inline `<script>` body that assigns a JSON-serialisable value to\n * a browser global. Every `<` is escaped to its `<` unicode form so an\n * embedded `</script>` (or `<!--`) inside the content data can never break out\n * of the inline script.\n */\nexport function buildGlobalAssignScript(globalName: string, value: unknown): string {\n const json = JSON.stringify(value ?? null).replace(/</g, '\\\\u003c')\n return `globalThis.${globalName} = ${json};`\n}\n","import type { HtmlTagDescriptor } from 'vite'\n\n/**\n * DCS motion tokens — the customer-site copy of the shared motion vocabulary.\n *\n * Injected as a constant `<style>` into every DCS site's `<head>` by\n * `dcsContentPlugin` (see its `transformIndexHtml`). This is the fleet-wide\n * seam: every site (vue-spa and VitePress) already wires `dcsContentPlugin`,\n * so a cms version bump ships these tokens to the whole fleet with zero\n * per-site source edits.\n *\n * Source of truth is the platform copy at\n * `packages/dcs-ui/src/styles/motion.css` and the `dcs-product-motion` skill —\n * keep the values here in lockstep. Values ONLY: reduced-motion stays a\n * per-component responsibility so no blanket `!important` rule leaks into a\n * site's isolated `.<slug>-page` design subtree.\n */\nexport const DCS_MOTION_TOKENS_CSS = `:root {\n --motion-duration-stagger: 40ms;\n --motion-duration-micro: 80ms;\n --motion-duration-quick: 150ms;\n --motion-duration-fast: 250ms;\n --motion-duration-medium: 350ms;\n --motion-duration-slow: 400ms;\n --motion-duration-very-slow: 500ms;\n --motion-ease-out: cubic-bezier(0.22, 1, 0.36, 1);\n --motion-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);\n --motion-ease-linear: linear;\n --motion-ease-bounce: cubic-bezier(0.34, 1.36, 0.64, 1);\n --motion-ease-bounce-strong: cubic-bezier(0.34, 3.85, 0.64, 1);\n --motion-distance-xs: 4px;\n --motion-distance-sm: 8px;\n --motion-distance-md: 12px;\n --motion-distance-lg: 24px;\n --motion-scale-lg: 0.96;\n --motion-scale-md: 0.97;\n --motion-scale-sm: 0.98;\n --motion-scale-xs: 0.99;\n --motion-blur-sm: 2px;\n --motion-blur-md: 3px;\n --motion-blur-lg: 8px;\n}`\n\n/**\n * The `<head>` tag descriptor for the motion-token block.\n *\n * `injectTo: 'head'`, NOT `'head-prepend'` — C-414. Vite's `head-prepend`\n * inserts immediately after the `<head>` open tag, i.e. AHEAD of the site's own\n * `<meta charset>`. This block is 858 bytes, so it pushed the encoding\n * declaration to byte 910 of the HTML spec's 1024-byte encoding-sniffing window\n * on every site in the fleet (measured on Iron Oak and Bryan's 2026-07-27, and\n * re-measured identical here), leaving ~90 bytes of headroom before every DCS\n * site silently mojibakes.\n *\n * `'head'` appends to the END of the `<head>` the site authored — which is\n * still ABOVE Vite's own build-time `<link rel=stylesheet>` / entry `<script>`,\n * because those are injected AFTER this `order: 'pre'` hook's tags. So the\n * per-site `:root` override still wins the cascade (that was the original\n * reason for `head-prepend`) AND the charset lands at byte ~46 with ~954 bytes\n * of headroom. Measured, not assumed — see `verify-honesty-rails.mjs` P12.\n *\n * If you ever move this back to `head-prepend`, the P12 rail in\n * `scripts/verify-honesty-rails.mjs` will fail: it asserts the charset comes\n * FIRST straight out of `dcsContentPlugin`, with no `dcsSeoPlugin` hoist.\n */\nexport function dcsMotionTokensStyleTag(): HtmlTagDescriptor {\n return {\n tag: 'style',\n attrs: { 'data-dcs-motion-tokens': '' },\n children: DCS_MOTION_TOKENS_CSS,\n injectTo: 'head',\n }\n}\n","/**\n * DCS AI-assistant widget loader — the cms head-inject seam for Phase 3 of the\n * Managed Site AI Agents plan (.docs/archive/plans/managed-site-ai-agents/plan.md).\n *\n * This rides the same always-on `dcsContentPlugin.transformIndexHtml` seam that\n * ships the motion tokens: every DCS site already wires `dcsContentPlugin`, so a\n * cms version bump delivers this loader to the whole fleet with ZERO per-site\n * source edits, and the portal per-site toggle turns the widget on/off at\n * runtime with no rebuild.\n *\n * What gets injected is a tiny (<2 KB) inline `<script>` — NOT the widget. On\n * idle it fetches the public agent config for this site; only if the agent is\n * enabled (HTTP 200) does it publish `window.__DCS_AGENT_BOOTSTRAP__` and inject\n * the real widget bundle from the CDN. The loader is **fail-silent**: a disabled\n * agent (404), a dead backend, a blocked request, or a malformed response all\n * result in no mount and no console error, so the assistant can never break a\n * customer page.\n *\n * Build-only: the loader is injected into the production build output (the fleet\n * delivery), not into `vite dev`. In local dev the config fetch would hit the\n * prod API from a non-whitelisted `localhost` origin and log an uncatchable CORS\n * error for every site developer — so, unlike the constant motion-token block,\n * this network-touching loader stays out of the dev server.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport yaml from 'js-yaml'\nimport type { HtmlTagDescriptor } from 'vite'\n\nimport { config as packageConfig } from '../../package.json'\n\n/**\n * DCS API origin the loader calls when the build passes none (dcsContentPlugin\n * feeds `process.env.VITE_API_BASE_URL` first). The value lives in this\n * package's `package.json` `config` block (C-1062: no production URL as a source\n * literal); the exported name is unchanged for consumers.\n */\nexport const DEFAULT_AGENT_API_BASE_URL: string = packageConfig.agentApiBaseUrl\n\n/**\n * Versioned CDN URL of the widget bundle. Both `cdn.` (branding CDN, CorsAllowAll)\n * and the already-live `files.` route serve the same `sgdcs` blob origin with an\n * identical `/agent-widget/v1/...` layout, so this is a plain classic-script\n * include that needs no CORS on the bundle host. Defaults to `files.` because the\n * `cdn.` Front Door route is still provisioning-gated (enableCdnDomain=false) —\n * flip the default only after that domain is live, or pass cdnScriptUrl. The\n * value lives in `package.json` `config.agentWidgetScriptUrl` (C-1062).\n */\nexport const DEFAULT_AGENT_WIDGET_SCRIPT_URL: string = packageConfig.agentWidgetScriptUrl\n\nexport interface DcsAgentWidgetLoaderOptions {\n /** Owning site slug — baked into the loader so it can build the config URL. */\n siteSlug: string\n /** DCS API base (default: the shared portal origin). */\n apiBaseUrl?: string\n /** Full URL of the CDN widget bundle. */\n cdnScriptUrl?: string\n /**\n * Where the loader asks for the agent config (C-1941). `'same-origin'`\n * (default, unchanged) probes the page host's slug-free `/api/v1/agent/config`\n * first, then falls back to the platform slug route. `'platform'` goes\n * straight to the platform slug route and never probes the page host. Use it\n * for a site whose production host has no `/api` route, such as an SWA\n * default hostname. There the same-origin probe always 404s and leaves an\n * uncatchable console line on every page load.\n */\n configOrigin?: AgentConfigOrigin\n}\n\n/** The values `.dcs/site.yaml` `agent_config_origin` accepts (C-1941). */\nexport const AGENT_CONFIG_ORIGINS = ['same-origin', 'platform'] as const\nexport type AgentConfigOrigin = (typeof AGENT_CONFIG_ORIGINS)[number]\n\nconst trimTrailingSlash = (value: string): string => value.replace(/\\/+$/, '')\n\n/**\n * JSON-encodes a value for safe embedding inside an inline `<script>` body.\n * `JSON.stringify` alone stops JS string-literal breakout but NOT the HTML\n * parser: a raw `</script>` (or a U+2028/U+2029 line separator, which is a valid\n * JS line terminator) inside the string would still terminate the element. So we\n * additionally escape `<`, `>`, and the two separators to their `\\uXXXX` forms —\n * defense-in-depth even though today every embedded value is build-time DCS\n * provisioning identity (DNS-label slug + platform URLs).\n */\nconst encodeForInlineScript = (value: string): string =>\n JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n\n/**\n * Builds the inline loader script body. Slug + URLs are HTML-safe-encoded (see\n * encodeForInlineScript) so no value can break out of the string literal OR the\n * `<script>` element. Kept intentionally compact to stay under the ~2 KB perf\n * budget (G4).\n */\nexport function buildAgentWidgetLoaderScript(options: DcsAgentWidgetLoaderOptions): string {\n const slug = encodeForInlineScript(options.siteSlug)\n const api = encodeForInlineScript(trimTrailingSlash(options.apiBaseUrl || DEFAULT_AGENT_API_BASE_URL))\n const cdn = encodeForInlineScript(options.cdnScriptUrl || DEFAULT_AGENT_WIDGET_SCRIPT_URL)\n // The platform (legacy, slug-carrying) config route. With configOrigin\n // 'platform' it is the ONLY config request; otherwise it is the fallback arm.\n const platformProbe = 'p(A+\"/api/v1/sites/\"+encodeURIComponent(S)+\"/agent/config\")'\n const configChain =\n options.configOrigin === 'platform'\n ? platformProbe\n : 'p(\"/api/v1/agent/config\").then(function(c){return c===null?' + platformProbe + ':c;})'\n\n return (\n '(function(){try{' +\n 'if(window.__DCS_AGENT_LOADER__)return;window.__DCS_AGENT_LOADER__=1;' +\n // Suppression parity with PreviewRibbon: skip the editor iframe (self!==top,\n // cross-origin access throws → treated as framed) and the ?dcs-hide-widget\n // screenshot/perf suppressor.\n 'try{if(window.self!==window.top)return;}catch(e){return;}' +\n 'if(/[?&]dcs-hide-widget(?:[=&]|$)/.test(location.search))return;' +\n 'var S=' + slug + ',A=' + api + ',C=' + cdn + ';' +\n 'var go=function(){try{' +\n // C-180: slug-free bootstrap probe. The loader runs on the customer's own\n // page, so a SAME-ORIGIN /api/v1/agent/config carries the customer Host and\n // SiteContextMiddleware resolves the site server-side — no slug in the path.\n // (Baking the slug into A+\"/api/v1/sites/\"+S+... hit the shared portal Host,\n // which cannot resolve a customer site.) A (apiBaseUrl) and S (slug) are still\n // handed to the widget bundle below for the chat/contact calls, which remain\n // slug-based against the legacy routes until they are migrated too.\n //\n // FALLBACK (2026-07-09 live finding): not every customer apex proxies\n // /api/v1/* to an API — kept's apex serves it from the STATIC origin (200\n // text/html SPA fallback), so the same-origin probe gets HTML and json()\n // rejects. When the slug-free probe yields nothing, retry the legacy\n // cross-origin slug route so the widget keeps mounting on proxy-less sites.\n //\n // C-290 (2026-07-25, probe matrix\n // .docs/plans/dynamic-site-resolution/evidence/agent-config-cors-matrix-2026-07-25.json):\n // the two arms were ALREADY sequential — the defect was that p() collapsed\n // \"no API on this route\" and \"the API answered, there is no agent\" into the\n // same null, so a site whose API authoritatively 404s fired a SECOND\n // guaranteed-404 request and logged a second uncatchable browser console\n // error on every page load. p() now distinguishes them:\n // null -> no API reached (network error, or a non-JSON body = SPA\n // fallback) => the legacy arm is worth trying\n // 0 -> a JSON API answered but the agent is off/absent => STOP, the\n // legacy arm can only 404 too\n // 0 is falsy, so the mount gate below is unchanged.\n 'var p=function(u){return fetch(u,{headers:{Accept:\"application/json\"}})' +\n // NB: no `<` / `>` anywhere in this body — the inline script must stay\n // angle-bracket-free so nothing can terminate the <script> element\n // (asserted by the HTML-hostile-slug test), hence indexOf(...)===-1.\n '.then(function(r){if(!r||(r.headers.get(\"content-type\")||\"\").indexOf(\"json\")===-1)return null;' +\n 'return r.ok?r.json()[\"catch\"](function(){return null;}):0;})' +\n '[\"catch\"](function(){return null;});};' +\n // C-1941: configOrigin 'platform' drops the same-origin arm entirely.\n configChain +\n '.then(function(c){if(!c||!c.enabled)return;' +\n 'window.__DCS_AGENT_BOOTSTRAP__={siteSlug:S,apiBaseUrl:A,config:c};' +\n 'var s=document.createElement(\"script\");s.src=C;s.async=true;s.setAttribute(\"data-dcs-agent-slug\",S);' +\n '(document.head||document.documentElement).appendChild(s);})' +\n '.catch(function(){});' +\n '}catch(e){}};' +\n 'if(\"requestIdleCallback\"in window){requestIdleCallback(go,{timeout:4000});}else{setTimeout(go,1200);}' +\n '}catch(e){}})();'\n )\n}\n\nconst SITE_YAML_CANDIDATES = ['.dcs/site.yaml', '../.dcs/site.yaml']\n\n/**\n * Reads `site_slug` from the site's `.dcs/site.yaml` (the same identity file the\n * announcements/provisioning path uses). Returns null when no site.yaml exists\n * or it carries no slug — the caller then injects nothing (silence for non-DCS\n * builds).\n */\nexport function readSiteSlug(projectRoot: string): string | null {\n return readSiteYaml(projectRoot)?.slug ?? null\n}\n\ninterface SiteYamlAgentFields {\n site_slug?: unknown\n agent_config_origin?: unknown\n}\n\n/**\n * The first `.dcs/site.yaml` candidate that parses and carries a `site_slug`,\n * or null. Both readers use it, so the slug and the config origin always come\n * from the same file.\n */\nfunction readSiteYaml(projectRoot: string): { slug: string; fields: SiteYamlAgentFields } | null {\n const candidates = [\n ...SITE_YAML_CANDIDATES.map((rel) => path.resolve(projectRoot, rel)),\n path.resolve(process.cwd(), '.dcs/site.yaml'),\n ]\n for (const candidate of candidates) {\n try {\n if (!fs.existsSync(candidate)) continue\n const parsed = yaml.load(fs.readFileSync(candidate, 'utf8')) as SiteYamlAgentFields | null\n const slug = parsed && typeof parsed.site_slug === 'string' ? parsed.site_slug.trim() : ''\n if (parsed && slug) return { slug, fields: parsed }\n } catch {\n // Unreadable/unparseable — try the next candidate, else return null.\n }\n }\n return null\n}\n\n/**\n * Reads `agent_config_origin` from `.dcs/site.yaml` (C-1941). If the key is\n * absent it returns null, and the loader keeps its same-origin-first default. A\n * value outside AGENT_CONFIG_ORIGINS is ignored with ONE build-time\n * console.warn. It never fails the build and never changes the served loader.\n */\nexport function readAgentConfigOrigin(projectRoot: string): AgentConfigOrigin | null {\n const raw = readSiteYaml(projectRoot)?.fields.agent_config_origin\n if (raw === undefined || raw === null) return null\n const value = typeof raw === 'string' ? raw.trim() : raw\n if (typeof value === 'string' && (AGENT_CONFIG_ORIGINS as readonly string[]).includes(value)) {\n return value as AgentConfigOrigin\n }\n console.warn(\n `[dcs-agent-widget] ignoring .dcs/site.yaml agent_config_origin=${JSON.stringify(raw)}; ` +\n `expected one of ${AGENT_CONFIG_ORIGINS.join(', ')}. The loader keeps the same-origin-first probe.`,\n )\n return null\n}\n\nexport interface DcsAgentWidgetTagOptions {\n /** Vite project root used to resolve the site slug. */\n projectRoot: string\n /** Override the DCS API base (default: process.env.VITE_API_BASE_URL, else the shared origin). */\n apiBaseUrl?: string\n /** Override the CDN bundle URL. */\n cdnScriptUrl?: string\n}\n\n/**\n * The `<head>` tag descriptor for the loader, or `null` when this build is not a\n * DCS-managed site (no resolvable slug) — in which case nothing is injected.\n */\nexport function dcsAgentWidgetLoaderTag(options: DcsAgentWidgetTagOptions): HtmlTagDescriptor | null {\n const siteSlug = readSiteSlug(options.projectRoot)\n if (!siteSlug) return null\n const configOrigin = readAgentConfigOrigin(options.projectRoot)\n\n return {\n tag: 'script',\n // The config-origin attribute only marks the served HTML, so audits and live\n // proofs can read it. The behaviour itself is baked into the loader body.\n attrs:\n configOrigin === 'platform'\n ? { 'data-dcs-agent-loader': '', 'data-dcs-agent-config-origin': 'platform' }\n : { 'data-dcs-agent-loader': '' },\n children: buildAgentWidgetLoaderScript({\n siteSlug,\n apiBaseUrl: options.apiBaseUrl,\n cdnScriptUrl: options.cdnScriptUrl,\n configOrigin: configOrigin ?? undefined,\n }),\n injectTo: 'head',\n }\n}\n","/**\n * DCS Content Plugin for Vite\n *\n * Reads `.dcs/content.yaml` at build time and injects content\n * as `__DCS_CONTENT__` global variable for use by useTextContent.\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { dcsContentPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsContentPlugin({ debug: true })\n * ]\n * })\n * ```\n *\n * For VitePress:\n * ```typescript\n * // .vitepress/config.ts\n * import { defineConfig } from 'vitepress'\n * import { dcsContentPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * vite: {\n * plugins: [\n * dcsContentPlugin()\n * ]\n * }\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { Plugin, ResolvedConfig, HtmlTagDescriptor } from 'vite'\nimport type { DcsContentFile } from '../types/content'\nimport { readDcsYamlFresh, buildGlobalAssignScript } from './serveDefineInject'\nimport { dcsMotionTokensStyleTag } from './motionTokens'\nimport { dcsAgentWidgetLoaderTag } from './agentWidget'\n\nexport interface DcsContentPluginOptions {\n /** Path to content.yaml relative to project root (default: '.dcs/content.yaml') */\n contentPath?: string\n /** Enable debug logging */\n debug?: boolean\n}\n\n/**\n * Packages that MUST be bundled into the SSR build (noExternal) rather than\n * externalized to `node_modules`.\n *\n * WHY: this plugin injects the site's content as the `__DCS_CONTENT__` Vite\n * `define`. A `define` is a compile-time text substitution that Vite applies\n * ONLY to source that passes through its transform pipeline. When a package is\n * SSR-externalized (loaded by Node's native resolver at server-render time), the\n * substitution never happens — `__DCS_CONTENT__` stays an undefined global on\n * the server. The content composables (`useReviewContent`, `useTextContent`)\n * then fall back to their empty/placeholder branch during SSR while the client\n * (where the define DID apply) renders the real content — producing the\n * \"Hydration completed but contains mismatches\" bug and, worse, baking\n * fabricated fallback content into the crawler-visible SSR HTML.\n *\n * Forcing the cms package `noExternal` bundles it into the SSR graph so the\n * define reaches the composables server-side, keeping SSR and client in lockstep\n * and putting the REAL content in the pre-rendered HTML. This is applied by the\n * plugin itself (merged into the user's Vite config) so every VitePress / vite\n * consumer inherits the fix on a cms bump — no per-site config knob to forget.\n */\nconst DCS_SSR_NO_EXTERNAL = ['@duffcloudservices/cms']\n\n/**\n * Vite plugin that injects .dcs/content.yaml at build time.\n *\n * @param options - Plugin configuration\n * @returns Vite plugin\n */\nexport function dcsContentPlugin(options: DcsContentPluginOptions = {}): Plugin {\n const { contentPath = '.dcs/content.yaml', debug = false } = options\n\n let resolvedConfig: ResolvedConfig\n // Captured during configResolved — gates the serve-only inline HTML inject.\n let isDev = false\n\n return {\n name: 'dcs-content',\n\n configResolved(config) {\n resolvedConfig = config\n isDev = config.command === 'serve'\n },\n\n config(config, env) {\n // ── Dev / preview (serve) ──────────────────────────────────────────────\n // Don't bake content into the bundle. Redirect the `__DCS_CONTENT__`\n // define to a browser global that `transformIndexHtml` (below) refreshes\n // from disk on every HTML request — so a plain iframe reload reflects the\n // latest on-disk content with NO server.restart() and NO module-graph\n // surgery. The consumer is untouched: it still reads the bare\n // `__DCS_CONTENT__` identifier, which this define rewrites to\n // `globalThis.__DCS_CONTENT__`.\n if (env.command === 'serve') {\n return {\n define: {\n __DCS_CONTENT__: 'globalThis.__DCS_CONTENT__',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n\n // ── Production build ───────────────────────────────────────────────────\n // Unchanged: read content.yaml now and bake it into the bundle as a\n // JSON literal so the SSG / SPA output inlines content exactly as before.\n const projectRoot = config.root || process.cwd()\n\n // Try to find content.yaml in multiple locations\n // VitePress projects have the docs folder as root, so check parent too\n const possiblePaths = [\n path.resolve(projectRoot, contentPath),\n path.resolve(projectRoot, '..', contentPath),\n path.resolve(process.cwd(), contentPath),\n ]\n\n let foundPath: string | undefined\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n foundPath = testPath\n break\n }\n }\n\n if (!foundPath) {\n if (debug) {\n console.log('[dcs-content] No content.yaml found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n console.log('[dcs-content] Using defaults only')\n }\n return {\n define: {\n __DCS_CONTENT__: 'undefined',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n\n try {\n const fileContent = fs.readFileSync(foundPath, 'utf8')\n const content = yaml.load(fileContent) as DcsContentFile\n\n if (debug) {\n console.log(`[dcs-content] Loaded ${foundPath}`)\n console.log(`[dcs-content] Version: ${content.version}`)\n console.log(`[dcs-content] Pages: ${Object.keys(content.pages ?? {}).join(', ') || '(none)'}`)\n console.log(`[dcs-content] Global keys: ${Object.keys(content.global ?? {}).length}`)\n }\n\n return {\n define: {\n __DCS_CONTENT__: JSON.stringify(content),\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n } catch (error) {\n console.warn('[dcs-content] Failed to parse content.yaml:', error)\n return {\n define: {\n __DCS_CONTENT__: 'undefined',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n },\n\n /**\n * Inject into `<head>` on every HTML request. Two concerns:\n *\n * 1. The constant DCS motion-token `:root` block (`DCS_MOTION_TOKENS_CSS`)\n * — the fleet-wide seam that gives every DCS site the shared `--motion-*`\n * vocabulary. It carries no per-site data, so (unlike the content inject)\n * it is NOT gated on `isDev`: it runs in both `serve` and `build`.\n * It is injected `head` (append), NOT `head-prepend` — C-414. Appending\n * still lands it ABOVE the bundled site CSS (Vite injects the build's\n * `<link rel=stylesheet>` AFTER this `order: 'pre'` hook's tags), so a\n * site's own `:root` (theme `tailwind.css` / `style.css`) can still\n * override a token — while leaving the site's `<meta charset>` first in\n * `<head>` instead of 858 bytes deep. See `motionTokens.ts`.\n *\n * 2. Dev-only: the FRESH on-disk `content.yaml` as an inline\n * `globalThis.__DCS_CONTENT__ = {…}` classic script. Runs on every dev\n * HTML request, so the portal's `?_hc` hard reload re-reads the YAML with\n * no restart. A classic `<script>` in `<head>` executes before the\n * deferred module app entry, so the global is set before the consumer's\n * `useTextContent` setup reads it. Gated on `isDev` so it never runs in\n * `vite`/`vitepress build` (the build path keeps the baked `define`).\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n // (1) Always-on, per the note above: the constant motion-token block.\n const tags: HtmlTagDescriptor[] = [dcsMotionTokensStyleTag()]\n\n // (1b) Build-only: the AI-assistant widget loader. Rides this same\n // fleet-wide seam (a cms bump ships it everywhere with no per-site\n // edits) but is NOT injected into `vite dev` — its idle config\n // fetch would hit the prod API from a non-whitelisted localhost\n // origin and log an uncatchable CORS error for every site dev. The\n // loader is fail-silent and returns null for non-DCS builds (no\n // resolvable site slug), so nothing is injected there.\n if (!isDev) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const agentTag = dcsAgentWidgetLoaderTag({\n projectRoot,\n apiBaseUrl: process.env.VITE_API_BASE_URL,\n })\n if (agentTag) tags.push(agentTag)\n }\n\n // (2) Dev-only fresh content inject.\n if (isDev) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const content = readDcsYamlFresh<DcsContentFile>(\n projectRoot,\n contentPath,\n 'dcs-content',\n debug\n )\n // No file (or unparseable) ⇒ leave the global unset; the consumer's\n // `typeof globalThis.__DCS_CONTENT__` check falls back to defaults.\n if (content !== undefined) {\n if (debug) {\n console.log('[dcs-content] serve: injecting fresh __DCS_CONTENT__ into <head>')\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_CONTENT__', content),\n injectTo: 'head-prepend',\n })\n }\n }\n\n return { html, tags }\n },\n },\n\n // Watch for changes in development.\n //\n // Downgraded from `server.restart()` to a debounced client `full-reload`:\n // freshness already comes from `transformIndexHtml` re-reading the YAML on\n // every HTML request, so all we need on change is to nudge the browser to\n // reload. A `server.restart()` would rebuild VitePress's dev MiniSearch\n // index and can throw \"server restart failed\" on a duplicate heading id —\n // exactly the fragility this fix removes. A `full-reload` does neither.\n configureServer(server) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n\n const watchPaths = [\n path.resolve(projectRoot, contentPath),\n path.resolve(projectRoot, '..', contentPath),\n ].map((p) => path.normalize(p))\n\n watchPaths.forEach((watchPath) => {\n if (fs.existsSync(watchPath)) {\n server.watcher.add(watchPath)\n }\n })\n\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n server.watcher.on('change', (changedPath) => {\n if (!watchPaths.includes(path.normalize(changedPath))) return\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n if (debug) {\n console.log('[dcs-content] content.yaml changed, sending full-reload')\n }\n server.ws.send({ type: 'full-reload' })\n }, 100)\n })\n },\n }\n}\n","/**\n * Build-time responsive-variant lint for DCS customer sites.\n *\n * The 2026-07-03 flagship-excellence review (P7) found desktop pages shipping\n * un-suffixed **full-size** CDN images (e.g. a 321.9 KB hero `47af1e8f….webp`)\n * instead of a `-md`/`-lg` responsive step. That happens when an image reaches\n * the output HTML through a path that does NOT run the `<img>` → `<picture>`\n * transform — content injected via `__DCS_CONTENT__` and then swapped to the\n * base `cdnUrl` by `dcsCdnBuildEnd`, or a hand-authored `<img src>` pointing at\n * a base CDN asset URL.\n *\n * A DCS CDN asset URL has the shape\n * `https://files.<host>/[content/]<slug>/assets/[<dir>/]<uuid>.<ext>`\n * Responsive variants insert a `-sm`/`-md`/`-lg` suffix before the extension\n * (`…<uuid>-md.webp`). Those suffixes contain non-hex letters, so a URL that\n * still matches the *base* pattern below is, by definition, an un-suffixed\n * full-size asset. This lint scans the built HTML's `<img src>` and\n * `<source srcset>` attributes for such URLs and reports (or fails on) them.\n *\n * It is intentionally a **static-output** lint (VitePress generates HTML after\n * both Vite builds finish, so a Vite plugin hook cannot see the SSG output) and\n * is registered via VitePress `buildEnd`.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnBuildEnd, dcsResponsiveImageLint, chainBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * // run the CDN rewrite first, then lint the result\n * buildEnd: chainBuildEnd(dcsCdnBuildEnd(), dcsResponsiveImageLint()),\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n// ────────────────────────────────────────────────────────────────────────────\n// Detector (pure — unit-testable without a build)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Anchored matcher for a **base** (un-suffixed, full-size) DCS CDN asset URL.\n * Kept aligned with `responsiveImagePlugin`'s `CDN_PATTERN`: the filename stem\n * is `[a-f0-9-]+` (hex UUID), so a responsive variant — `…-sm.webp`,\n * `…-md.webp`, `…-lg.webp` — never matches (each suffix carries a non-hex\n * letter). Query strings / fragments are tolerated after the extension.\n */\nconst BASE_CDN_ASSET =\n /^https?:\\/\\/files\\.[^/]+\\/(?:content\\/)?[^/]+\\/assets\\/(?:[^/]+\\/)*[a-f0-9-]+\\.\\w+(?:[?#].*)?$/i\n\nexport interface ResponsiveImageViolation {\n /** The un-suffixed full-size CDN URL that should have been a responsive variant. */\n url: string\n /** Which element referenced it. */\n tag: 'img' | 'source'\n}\n\n/** True when `url` is a base (un-suffixed, full-size) DCS CDN asset URL. */\nexport function isFullSizeCdnUrl(url: string): boolean {\n return BASE_CDN_ASSET.test(url.trim())\n}\n\nfunction readAttr(tag: string, name: string): string | null {\n const m = tag.match(new RegExp(`\\\\b${name}=(\"([^\"]*)\"|'([^']*)')`, 'i'))\n if (!m) return null\n return m[2] ?? m[3] ?? ''\n}\n\n/**\n * Scan an HTML string and return every `<img src>` / `<source srcset>` reference\n * that resolves to a base (un-suffixed) full-size DCS CDN asset. `srcset`\n * candidates are split on commas and only the URL portion (before the width /\n * density descriptor) is tested. `onerror` and other attributes are ignored —\n * only the actual `src` / `srcset` sources are inspected.\n */\nexport function findFullSizeCdnImages(html: string): ResponsiveImageViolation[] {\n const violations: ResponsiveImageViolation[] = []\n\n for (const m of html.matchAll(/<img\\b[^>]*>/gi)) {\n const src = readAttr(m[0], 'src')\n if (src && isFullSizeCdnUrl(src)) {\n violations.push({ url: src.trim(), tag: 'img' })\n }\n }\n\n for (const m of html.matchAll(/<source\\b[^>]*>/gi)) {\n const srcset = readAttr(m[0], 'srcset')\n if (!srcset) continue\n for (const candidate of srcset.split(',')) {\n const url = candidate.trim().split(/\\s+/)[0]\n if (url && isFullSizeCdnUrl(url)) {\n violations.push({ url, tag: 'source' })\n }\n }\n }\n\n return violations\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// VitePress buildEnd hook\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface DcsResponsiveImageLintOptions {\n /**\n * Throw (fail the build) when full-size images are found. Default `false`\n * (warn only) so the guard can land ahead of the per-site cleanup; flip to\n * `true` in CI once a site's output is clean to prevent regressions.\n */\n failOnViolation?: boolean\n /** File extensions to scan in the output directory. Default `['.html']`. */\n extensions?: string[]\n /** Enable per-file debug logging. */\n debug?: boolean\n}\n\nexport interface ResponsiveImageLintReport {\n filesScanned: number\n violations: Array<ResponsiveImageViolation & { file: string }>\n}\n\n/**\n * VitePress `buildEnd` factory that lints the generated HTML for un-suffixed\n * full-size CDN images. Returns the report (also useful for tests) and either\n * warns or throws depending on `failOnViolation`.\n */\nexport function dcsResponsiveImageLint(options: DcsResponsiveImageLintOptions = {}) {\n const { failOnViolation = false, extensions = ['.html'], debug = false } = options\n\n return async (siteConfig: { outDir: string }): Promise<ResponsiveImageLintReport> => {\n const report: ResponsiveImageLintReport = { filesScanned: 0, violations: [] }\n const outDir = siteConfig.outDir\n if (!outDir || !fs.existsSync(outDir)) return report\n\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(full)\n } else if (extensions.some((ext) => entry.name.endsWith(ext))) {\n report.filesScanned++\n const html = fs.readFileSync(full, 'utf8')\n if (!html.includes('/assets/')) continue\n const rel = path.relative(outDir, full)\n for (const v of findFullSizeCdnImages(html)) {\n report.violations.push({ ...v, file: rel })\n if (debug) {\n console.log(`[dcs-responsive-lint] ${rel}: <${v.tag}> full-size ${v.url}`)\n }\n }\n }\n }\n }\n\n walk(outDir)\n\n if (report.violations.length > 0) {\n const lines = report.violations\n .map((v) => ` ${v.file}: <${v.tag}> ${v.url}`)\n .join('\\n')\n const summary =\n `[dcs-responsive-lint] ${report.violations.length} full-size CDN image(s) ` +\n `shipped without a -sm/-md/-lg responsive variant across ${report.filesScanned} file(s):\\n${lines}`\n if (failOnViolation) {\n throw new Error(summary)\n }\n console.warn(summary)\n } else if (debug) {\n console.log(\n `[dcs-responsive-lint] clean — scanned ${report.filesScanned} file(s), no full-size images.`\n )\n }\n\n return report\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// buildEnd composition helper\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Compose multiple VitePress `buildEnd` hooks into one (VitePress accepts a\n * single `buildEnd`). Hooks run sequentially in the order given, so a rewrite\n * hook (`dcsCdnBuildEnd`) can precede a lint (`dcsResponsiveImageLint`).\n */\nexport function chainBuildEnd<T>(\n ...hooks: Array<((siteConfig: T) => unknown | Promise<unknown>) | undefined | null>\n): (siteConfig: T) => Promise<void> {\n const active = hooks.filter(\n (h): h is (siteConfig: T) => unknown | Promise<unknown> => typeof h === 'function'\n )\n return async (siteConfig: T) => {\n for (const hook of active) {\n await hook(siteConfig)\n }\n }\n}\n","/**\n * DCS directory-index twins for VitePress `cleanUrls` builds (C-1965).\n *\n * THE DEFECT. A VitePress site built with `cleanUrls: true` emits every\n * non-index page flat: `contact.md` -> `dist/contact.html`. On an Azure Static\n * Web App with no `trailingSlash` rule, `/contact` answers 200 but `/contact/`\n * answers `301 Location: https://<swa-default-host>/contact` - an ABSOLUTE\n * redirect to the `*.azurestaticapps.net` host, because Front Door sends that\n * host as the origin Host and a Free SWA ignores `X-Forwarded-Host`. Measured\n * live on kimduffhomes.com, nateduff.com, bryanduffhomes.com and bryanduff.com\n * (.workboard/records/2026-10-27-lead-C1965-swa-fixture.md section 1).\n *\n * THE FIX, PROVEN ON A DISPOSABLE FREE SWA (same record, section 3f): when both\n * `x.html` and `x/index.html` exist, SWA serves `x.html` for `/x` and\n * `x/index.html` for `/x/`, both 200, no `Location`, in either direction. So for\n * every flat page this writes `<page>/index.html` as a BYTE-IDENTICAL twin of\n * `<page>.html`.\n *\n * WHY STRICT. The two URLs are served by two different files, so a twin that\n * differs from its flat page shows visitors and crawlers two different\n * documents on `/x` and `/x/`. An existing `<page>/index.html` with different\n * bytes is therefore a BUILD FAILURE, never a skip. A page VitePress says it\n * rendered whose `.html` is missing is also fatal: the emitter's model of the\n * build would be wrong.\n *\n * NO CANONICAL OF ITS OWN. The flat page already carries the cms factory's\n * absolute, slash-less canonical (`vitepressTransform.ts`), and a byte copy\n * carries it too, so `/contact/` consolidates onto `/contact`. A self-canonical\n * `/contact/` would split the signal.\n *\n * ORDER. The twin must copy the FINAL bytes. VitePress applies `transformHtml`\n * before it writes each page, and the site's own `buildEnd` (CDN rewrite,\n * site files, pre-launch stamps) runs next; the emitter is chained AFTER that\n * hook. The canonical deploy workflow then injects GA into every `*.html` and\n * re-checks the pairs (site-deploy.yml, \"Assert directory-index twin parity\").\n *\n * THE MANIFEST (C-1965 roll-blocker N2). When `DCS_DIR_INDEX_MANIFEST` names a\n * file, every emitter run writes there the list of twins it validated (twin\n * path, source path, sha256 of the bytes it copied), so the deploy workflow\n * checks the pairs the cms OWNS instead of inferring pairs from the dist. The\n * canonical workflow points it at a run-unique file under `$RUNNER_TEMP`:\n * outside the SWA upload directory (nothing new is served) and outside the\n * site repo (nothing new to ignore or commit). Unset (a local build), nothing\n * is written.\n *\n * TWO ENTRY POINTS, ONE GUARD. `dcsSeoPlugin` installs the emitter\n * automatically on a VitePress build (`dirIndex: false` opts out). A site that\n * wants explicit composition can chain `dcsDirIndexBuildEnd()` into its own\n * `buildEnd`. Both go through the registry symbol\n * `Symbol.for('dcs.cms.dirIndex.installed')` on VitePress's `siteConfig`, which\n * is the same object for the client and the SSR config resolution, so the\n * emitter runs exactly once however many times it is registered.\n *\n * @example Explicit composition (optional - dcsSeoPlugin already installs it)\n * ```ts\n * // .vitepress/config.ts\n * import { chainBuildEnd, dcsCdnBuildEnd, dcsDirIndexBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * cleanUrls: true,\n * buildEnd: chainBuildEnd(dcsCdnBuildEnd(), dcsDirIndexBuildEnd()),\n * })\n * ```\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { chainBuildEnd } from './dcsResponsiveImageLint'\n\n/**\n * The idempotency guard. A REGISTRY symbol (`Symbol.for`), not `Symbol()`: it\n * must be the same key across module instances (the plugin barrel and a\n * site-local import can be two copies) and across the client and SSR config\n * resolutions.\n */\nexport const DIR_INDEX_INSTALLED: unique symbol = Symbol.for('dcs.cms.dirIndex.installed')\n\n/**\n * The environment variable that names the twin manifest file. Read at emit\n * time; an empty or unset value writes no manifest.\n */\nexport const DIR_INDEX_MANIFEST_ENV = 'DCS_DIR_INDEX_MANIFEST'\n\n/** The manifest's `schema` value; the workflow step refuses any other. */\nexport const DIR_INDEX_MANIFEST_SCHEMA = 'dcs.cms.dir-index-manifest/v1'\n\n/** One twin the emitter validated (written, or already present and identical). */\nexport interface DirIndexManifestEntry {\n /** `<page>/index.html`, relative to `outDir`, forward slashes. */\n twin: string\n /** `<page>.html`, relative to `outDir`, forward slashes. */\n source: string\n /** sha256 (hex) of the bytes copied, i.e. the source as the emitter read it. */\n sha256: string\n}\n\n/** The file `DCS_DIR_INDEX_MANIFEST` names, written on every emitter run. */\nexport interface DirIndexManifest {\n schema: typeof DIR_INDEX_MANIFEST_SCHEMA\n /** Absolute build output directory the twins live in. */\n outDir: string\n /** Whether the build had `cleanUrls` on (off: `twins` is empty). */\n cleanUrls: boolean\n /** Sorted by `twin`. */\n twins: DirIndexManifestEntry[]\n}\n\nexport interface EmitDirectoryIndexesOptions {\n /**\n * Where to write the twin manifest. Defaults to\n * `process.env.DCS_DIR_INDEX_MANIFEST`; when neither is set, nothing is\n * written. Relative paths resolve against `process.cwd()`.\n */\n manifestPath?: string\n}\n\n/** Exact index-page exclusion: `index.md` and `foo/index.md`, NOT `reindex.md`. */\nconst INDEX_PAGE = /(^|\\/)index\\.md$/\n\n/** The subset of VitePress's resolved `SiteConfig` the emitter reads. */\nexport interface DirIndexSiteConfig {\n /** Absolute build output directory. */\n outDir: string\n /** Source pages relative to `srcDir`, e.g. `contact.md`, `blogs/post.md`. */\n pages: string[]\n /** VitePress rewrites; a page renders at `rewrites.map[page] ?? page`. */\n rewrites?: { map?: Record<string, string | undefined> }\n /** Twins are emitted only when `cleanUrls` is on. */\n cleanUrls?: boolean\n /** VitePress's single `buildEnd` hook. */\n buildEnd?: (siteConfig: never) => unknown\n}\n\nexport interface DirIndexResult {\n /** Twins written by this run. */\n written: number\n /** Twins already present with identical bytes (left untouched). */\n identical: number\n /** The twin paths (relative to `outDir`, forward slashes) written or found identical. */\n twins: string[]\n /** Absolute path of the manifest written by this run, when one was requested. */\n manifestPath?: string\n}\n\ninterface DirIndexState {\n /** Which entry point installed the guard first. */\n owner: 'auto' | 'manual'\n /** Set once the emitter has run for this build. */\n emitted: boolean\n}\n\ntype GuardedSiteConfig = DirIndexSiteConfig & { [DIR_INDEX_INSTALLED]?: DirIndexState }\n\n/** Thrown for a missing source page or an unequal `<page>/index.html` collision. */\nexport class DirIndexError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DirIndexError'\n }\n}\n\n/**\n * The flat pages that get a twin: every mapped page except index pages\n * (`(^|/)index\\.md$`) and the root `404.md`. Returned as mapped `.md` paths.\n */\nexport function dirIndexCandidates(siteConfig: Pick<DirIndexSiteConfig, 'pages' | 'rewrites'>): string[] {\n const map = siteConfig.rewrites?.map ?? {}\n const out: string[] = []\n for (const page of siteConfig.pages) {\n const mapped = (map[page] || page).replace(/\\\\/g, '/')\n if (!mapped.endsWith('.md')) continue\n if (INDEX_PAGE.test(mapped)) continue\n if (mapped === '404.md') continue\n out.push(mapped)\n }\n return [...new Set(out)].sort()\n}\n\n/** Resolve the manifest destination: the explicit option, else the env var, else none. */\nfunction resolveManifestPath(options: EmitDirectoryIndexesOptions): string | undefined {\n const raw = options.manifestPath ?? process.env[DIR_INDEX_MANIFEST_ENV]\n return raw ? path.resolve(raw) : undefined\n}\n\n/**\n * `p` with its nearest EXISTING ancestor replaced by that ancestor's realpath,\n * so a symlinked or junctioned directory that points into `outDir` is seen as\n * inside it even when the file itself does not exist yet.\n */\nfunction realpathNearest(p: string): string {\n let cur = path.resolve(p)\n const tail: string[] = []\n while (!fs.existsSync(cur)) {\n const parent = path.dirname(cur)\n if (parent === cur) break\n tail.unshift(path.basename(cur))\n cur = parent\n }\n let real = cur\n try {\n real = fs.realpathSync.native(cur)\n } catch {\n /* keep the resolved path */\n }\n return path.join(real, ...tail)\n}\n\n/**\n * Is `p` inside (or equal to) `dir`? Decided on PATH SEGMENTS after resolving\n * symlinked ancestors: `dist/..manifest.json` is inside `dist` (its first\n * segment is `..manifest.json`, not `..`), `dist/../m.json` is not.\n */\nexport function isInsideDir(dir: string, p: string): boolean {\n // The DESTINATION's final component is never followed: the emitter removes\n // and replaces that entry, so a symlink at <outDir>/m.json pointing outside\n // is still a file written INSIDE outDir. Resolve its PARENT, keep its name.\n const abs = path.resolve(p)\n const dest = path.join(realpathNearest(path.dirname(abs)), path.basename(abs))\n const rel = path.relative(realpathNearest(dir), dest)\n if (rel === '') return true\n if (path.isAbsolute(rel)) return false\n return !(rel === '..' || rel.startsWith('..' + path.sep))\n}\n\n/**\n * Remove a manifest left at `DCS_DIR_INDEX_MANIFEST` by an earlier build, for a\n * build whose emitter is DISABLED (`dirIndex: false`). Removal, not an empty\n * manifest: a disabled emitter owns nothing and validated nothing, and \"no\n * manifest\" is exactly how the deploy step reads that (no pairs passes, any\n * pair is un-owned and fails), so a stale list from another build can never\n * vouch for this dist. A regular file or a symlink (unlinked, never followed)\n * is removed; a directory is not. Returns the path removed.\n */\nexport function clearDirIndexManifest(manifestPath = process.env[DIR_INDEX_MANIFEST_ENV]): string | undefined {\n if (!manifestPath) return undefined\n const file = path.resolve(manifestPath)\n try {\n const st = fs.lstatSync(file)\n if (!st.isFile() && !st.isSymbolicLink()) return undefined\n } catch {\n return undefined\n }\n // unlink, never follow: a symlinked stale manifest goes, its target stays.\n fs.unlinkSync(file)\n return file\n}\n\nconst sha256 = (bytes: Buffer) => crypto.createHash('sha256').update(bytes).digest('hex')\n\n/** Write the manifest (tmp + rename, so a reader never sees half a file). */\nfunction writeManifest(file: string, manifest: DirIndexManifest): void {\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(manifest, null, 2)}\\n`)\n fs.renameSync(tmp, file)\n}\n\n/**\n * Write a byte-identical `<page>/index.html` for every flat page of a\n * `cleanUrls` VitePress build. Validates every pair BEFORE writing anything,\n * so a failing build leaves `outDir` exactly as VitePress produced it.\n *\n * When a manifest path is set (option or `DCS_DIR_INDEX_MANIFEST`), any file\n * already there is removed first and a fresh manifest is written on success,\n * including the `cleanUrls: false` no-op (an empty list). A refused build\n * leaves no manifest. A manifest path inside `outDir` is refused: it would\n * ship with the site.\n */\nexport function emitDirectoryIndexes(\n siteConfig: DirIndexSiteConfig,\n options: EmitDirectoryIndexesOptions = {}\n): DirIndexResult {\n const outDir = siteConfig.outDir\n const manifestPath = resolveManifestPath(options)\n if (manifestPath) {\n if (isInsideDir(outDir, manifestPath)) {\n throw new DirIndexError(\n `[dcs-dir-index] ${DIR_INDEX_MANIFEST_ENV}=${manifestPath} is inside outDir ${outDir}; ` +\n `the manifest must not ship with the site. Point it outside the build output.`\n )\n }\n fs.rmSync(manifestPath, { force: true })\n }\n\n if (siteConfig.cleanUrls !== true) {\n if (!manifestPath) return { written: 0, identical: 0, twins: [] }\n writeManifest(manifestPath, { schema: DIR_INDEX_MANIFEST_SCHEMA, outDir: path.resolve(outDir), cleanUrls: false, twins: [] })\n return { written: 0, identical: 0, twins: [], manifestPath }\n }\n\n const missing: string[] = []\n const unequal: string[] = []\n const toWrite: Array<{ src: string; dst: string; rel: string; srcRel: string; bytes: Buffer }> = []\n const identicalRel: string[] = []\n const entries: DirIndexManifestEntry[] = []\n\n for (const page of dirIndexCandidates(siteConfig)) {\n const stem = page.slice(0, -'.md'.length)\n const srcRel = `${stem}.html`\n const dstRel = `${stem}/index.html`\n const src = path.join(outDir, srcRel)\n const dst = path.join(outDir, dstRel)\n\n if (!fs.existsSync(src) || !fs.statSync(src).isFile()) {\n missing.push(`${page} -> ${srcRel}`)\n continue\n }\n const bytes = fs.readFileSync(src)\n\n if (fs.existsSync(dst)) {\n const existing = fs.statSync(dst).isFile() ? fs.readFileSync(dst) : null\n if (existing && existing.equals(bytes)) {\n identicalRel.push(dstRel)\n entries.push({ twin: dstRel, source: srcRel, sha256: sha256(bytes) })\n } else {\n unequal.push(`${srcRel} != ${dstRel}`)\n }\n continue\n }\n toWrite.push({ src, dst, rel: dstRel, srcRel, bytes })\n }\n\n const problems: string[] = []\n if (missing.length > 0) {\n problems.push(\n `${missing.length} page(s) VitePress lists have no rendered flat HTML:\\n` +\n missing.map((m) => ` ${m}`).join('\\n')\n )\n }\n if (unequal.length > 0) {\n problems.push(\n `${unequal.length} existing directory index(es) differ from their flat page. SWA serves ` +\n `<page>.html for /page and <page>/index.html for /page/, so these would publish two ` +\n `different documents on one route:\\n` +\n unequal.map((u) => ` ${u}`).join('\\n')\n )\n }\n if (problems.length > 0) {\n throw new DirIndexError(`[dcs-dir-index] build refused (nothing written).\\n${problems.join('\\n')}`)\n }\n\n for (const t of toWrite) {\n fs.mkdirSync(path.dirname(t.dst), { recursive: true })\n fs.writeFileSync(t.dst, t.bytes)\n entries.push({ twin: t.rel, source: t.srcRel, sha256: sha256(t.bytes) })\n }\n\n const twins = [...toWrite.map((t) => t.rel), ...identicalRel].sort()\n console.log(`[dcs-dir-index] twins written=${toWrite.length} identical=${identicalRel.length}`)\n if (!manifestPath) return { written: toWrite.length, identical: identicalRel.length, twins }\n\n entries.sort((a, b) => (a.twin < b.twin ? -1 : a.twin > b.twin ? 1 : 0))\n writeManifest(manifestPath, { schema: DIR_INDEX_MANIFEST_SCHEMA, outDir: path.resolve(outDir), cleanUrls: true, twins: entries })\n console.log(`[dcs-dir-index] manifest ${manifestPath} (${entries.length} twin(s))`)\n return { written: toWrite.length, identical: identicalRel.length, twins, manifestPath }\n}\n\n/** Run the emitter at most once per build (per `siteConfig`). */\nfunction emitOnce(siteConfig: GuardedSiteConfig): DirIndexResult | undefined {\n const state = siteConfig[DIR_INDEX_INSTALLED]\n if (state?.emitted) return undefined\n if (state) state.emitted = true\n return emitDirectoryIndexes(siteConfig)\n}\n\n/** Duck-type check: is this a VitePress resolved `SiteConfig`? */\nexport function isVitePressSiteConfig(value: unknown): value is DirIndexSiteConfig {\n if (!value || typeof value !== 'object') return false\n const v = value as Partial<DirIndexSiteConfig>\n return typeof v.outDir === 'string' && Array.isArray(v.pages)\n}\n\n/**\n * The AUTOMATIC entry point (called by `dcsSeoPlugin` on a VitePress build).\n * Wraps `siteConfig.buildEnd` so the site's own hook runs FIRST and the\n * emitter copies its final output. Returns `false` when already installed\n * (the client and SSR builds both resolve config; a second plugin instance\n * may also call this).\n */\nexport function installDirIndex(siteConfig: DirIndexSiteConfig): boolean {\n const guarded = siteConfig as GuardedSiteConfig\n if (guarded[DIR_INDEX_INSTALLED]) return false\n guarded[DIR_INDEX_INSTALLED] = { owner: 'auto', emitted: false }\n const original = siteConfig.buildEnd as ((sc: GuardedSiteConfig) => unknown) | undefined\n siteConfig.buildEnd = chainBuildEnd<GuardedSiteConfig>(\n original ? (sc) => original.call(sc, sc) : undefined,\n (sc) => {\n emitOnce(sc)\n }\n ) as DirIndexSiteConfig['buildEnd']\n return true\n}\n\n/**\n * The MANUAL entry point: a VitePress `buildEnd` hook for sites that compose\n * their hooks explicitly. It shares the automatic guard:\n *\n * - If `dcsSeoPlugin` already installed the emitter, this DEFERS to it (the\n * automatic wrapper runs after the site's whole `buildEnd`, so it copies the\n * final bytes) and does nothing itself.\n * - Otherwise it claims the guard and emits, once, however many times it is\n * chained.\n */\nexport function dcsDirIndexBuildEnd(): (siteConfig: DirIndexSiteConfig) => Promise<void> {\n return async (siteConfig: DirIndexSiteConfig) => {\n const guarded = siteConfig as GuardedSiteConfig\n const state = guarded[DIR_INDEX_INSTALLED]\n if (state?.owner === 'auto') return\n if (!state) guarded[DIR_INDEX_INSTALLED] = { owner: 'manual', emitted: false }\n emitOnce(guarded)\n }\n}\n","/**\n * The production {@link RouteRenderer}: a headless-Playwright renderer that\n * drives the JUST-BUILT SPA from `dist/` and returns each route's rendered\n * `#app` body.\n *\n * Design choices (see `bodyPrerender.ts` for the why):\n * - **Renders the PRODUCTION bundle**, so `import.meta.env.DEV` is already\n * `false` and the dev-only fabrication gates render their honest empty state\n * (A-34 safety by construction — no separate SSR bundle to leak defaults).\n * - **Playwright is dynamically imported and OPTIONAL.** If it (or a browser)\n * is unavailable, the factory returns `null` and the caller no-ops (the head\n * + JSON-LD emit is untouched, so the build never breaks on missing infra).\n * Playwright is already a universal devDependency of the DCS site fleet\n * (snapshot capture), so this activates on a cms bump with no per-site edit.\n * - **Offline + deterministic.** A tiny built-in static server serves `dist/`;\n * every EXTERNAL request (CDN images, App Insights, the site-auth probe) is\n * aborted. The DOM still carries those `<img>`/`<link>` tags (crawler-visible)\n * while the render stays fast and free of expected offline network noise.\n * - **Nothing leaves, not even at page close (C-1962).** The same static\n * server is Chromium's only proxy, and it refuses every request that is not\n * for its own origin. `page.route` alone is not enough: its interception\n * belongs to the page target, and a `sendBeacon` / keepalive `fetch` fired\n * from `pagehide`/`visibilitychange` during `page.close()` is dispatched after\n * that interception is gone. The proxy lives in the browser's network\n * service, which carries those sends too.\n * - **Crash-only fail-loud.** Only an uncaught page exception or a failed mount\n * is reported as a fatal error; benign offline console errors are not. The\n * caller turns a fatal error into a red build.\n */\n\nimport http from 'node:http'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { AddressInfo } from 'node:net'\nimport type { Duplex } from 'node:stream'\nimport type { RenderedRoute, RouteRenderer } from './bodyPrerender'\n\n/**\n * The URL the renderer navigates to for a route (C-1553).\n *\n * The prerender drives the site's PRODUCTION bundle, connection string and all.\n * Every external request is aborted by the route filter below, but Chromium's\n * `navigator.sendBeacon` is not routed through `page.route`, so the telemetry\n * SDK's unload flush still reached the customer's production App Insights\n * component: measured 2026-09-08 on ai-boogie-babies (22 rows in 30 d) and\n * ai-mi-handyman (33), every one `HeadlessChrome` with `Target 127.0.0.1:<port>`,\n * one burst per deploy. Marking the navigation with the C-614 synthetic-capture\n * parameter makes the site's telemetry boot decline BEFORE the SDK exists, which\n * is the same contract the snapshot capture already honours. The marker is a\n * query parameter the head emitter never reads (canonical/og:url come from the\n * site config, not `location`), so the baked head is unchanged.\n */\nexport function prerenderNavigationUrl(origin: string, routePath: string): string {\n const url = new URL(routePath, origin)\n url.searchParams.set('dcs-no-telemetry', '')\n return url.toString()\n}\n\n/** A started static server plus its `http://127.0.0.1:<port>` origin. */\ninterface StaticServer {\n origin: string\n /** Requests the gate refused (`METHOD host/path`, no query), oldest first. */\n blocked: string[]\n close: () => Promise<void>\n}\n\n/** Cap on the refused-request log so a chatty site cannot grow it unbounded. */\nconst BLOCKED_LOG_CAP = 1000\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.gif': 'image/gif',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain; charset=utf-8',\n '.xml': 'application/xml; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n}\n\n/**\n * Serve `dist/` over loopback with directory-index resolution\n * (`/services` → `/services/index.html`) and an SPA fallback to the root\n * `index.html` for any path with no matching file/dir. Bound to `127.0.0.1:0`\n * so the OS assigns a free port; nothing is exposed off-box.\n *\n * It is ALSO the browser's proxy (C-1962): Chromium sends every request here in\n * absolute form (`POST http://host/path`), including loopback ones (Playwright\n * forces `<-loopback>` into the bypass list) and `CONNECT host:443` for TLS. A\n * request for any origin other than this server's own is answered 403 and\n * logged; a `CONNECT` is refused by destroying the socket. Nothing is ever\n * forwarded, so no request can leave the box whatever the page does or when.\n */\nasync function startStaticServer(outDir: string): Promise<StaticServer> {\n let origin = ''\n const blocked: string[] = []\n const refuse = (entry: string) => {\n if (blocked.length < BLOCKED_LOG_CAP) blocked.push(entry)\n }\n\n const server = http.createServer((req, res) => {\n let url: URL\n try {\n url = new URL(req.url ?? '/', origin)\n } catch {\n res.writeHead(400, { Connection: 'close' })\n res.end()\n return\n }\n // Absolute-form request for another origin (another host OR another port on\n // loopback): the page asked the proxy to reach off-origin. Refuse it.\n if (url.origin !== origin) {\n refuse(`${req.method ?? 'GET'} ${url.host}${url.pathname}`)\n res.writeHead(403, { Connection: 'close' })\n res.end()\n return\n }\n\n let pathname = '/'\n try {\n pathname = decodeURIComponent(url.pathname)\n } catch {\n pathname = '/'\n }\n\n // Resolve within outDir; reject path traversal.\n const resolved = path.resolve(outDir, '.' + pathname)\n if (resolved !== outDir && !resolved.startsWith(outDir + path.sep)) {\n res.writeHead(403)\n res.end()\n return\n }\n\n let filePath = resolved\n try {\n const stat = fs.statSync(filePath)\n if (stat.isDirectory()) filePath = path.join(filePath, 'index.html')\n } catch {\n // Missing path: a request for an asset (has an extension) is a genuine 404;\n // a route-shaped request falls back to the SPA shell.\n if (path.extname(pathname)) {\n res.writeHead(404)\n res.end()\n return\n }\n filePath = path.join(outDir, 'index.html')\n }\n\n fs.readFile(filePath, (err, buf) => {\n if (err) {\n res.writeHead(404)\n res.end()\n return\n }\n res.writeHead(200, {\n 'Content-Type': CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream',\n })\n res.end(buf)\n })\n })\n\n // TLS (and ws/wss) through a proxy arrives as CONNECT; this server never\n // tunnels, so every one of them is off-origin by definition.\n server.on('connect', (req: http.IncomingMessage, socket: Duplex) => {\n refuse(`CONNECT ${req.url ?? ''}`)\n socket.destroy()\n })\n\n await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))\n const addr = server.address() as AddressInfo\n origin = `http://127.0.0.1:${addr.port}`\n\n return {\n origin,\n blocked,\n close: () =>\n new Promise<void>((resolve) => {\n server.close(() => resolve())\n // Drop idle proxy keep-alive sockets so close() cannot hang on them.\n server.closeAllConnections()\n }),\n }\n}\n\n/** Options for {@link createPlaywrightRenderer}. */\nexport interface PlaywrightRendererOptions {\n /** Absolute path to the built SPA output directory (`dist`). */\n outDir: string\n /** Per-route navigation + settle budget (ms). Default 30000 nav, 15000 mount. */\n navTimeoutMs?: number\n mountTimeoutMs?: number\n /** Extra quiet settle after mount for post-render microtasks (ms). Default 250. */\n settleMs?: number\n debug?: boolean\n}\n\n/** A ready renderer plus a `close()` that tears down the browser + server. */\nexport interface PlaywrightRendererHandle {\n renderer: RouteRenderer\n close: () => Promise<void>\n /**\n * Off-origin requests the proxy gate refused so far (`METHOD host/path`, or\n * `CONNECT host:port`), oldest first, capped. Requests `page.route` aborted\n * before they reached the network are not in it: this is what got PAST the\n * page-level block and was stopped at the browser level.\n */\n blockedRequests: () => readonly string[]\n}\n\n// Minimal structural types for the OPTIONAL, dynamically-imported `playwright`\n// surface — avoids a hard type/dependency on the package (it is not a cms\n// devDependency; it resolves from the consuming site at build time).\ninterface PwConsoleMessage {\n type(): string\n text(): string\n}\ninterface PwPage {\n on(event: 'pageerror', cb: (err: Error) => void): void\n on(event: 'console', cb: (msg: PwConsoleMessage) => void): void\n route(url: string, handler: (route: PwRoute) => unknown): Promise<void>\n goto(url: string, opts: { waitUntil: string; timeout: number }): Promise<unknown>\n waitForFunction(fn: () => unknown, arg?: unknown, opts?: { timeout: number }): Promise<unknown>\n waitForTimeout(ms: number): Promise<void>\n $eval(sel: string, fn: (el: Element) => string): Promise<string>\n evaluate<T>(fn: () => T): Promise<T>\n close(): Promise<void>\n}\ninterface PwRoute {\n request(): { url(): string }\n abort(): Promise<void>\n continue(): Promise<void>\n}\ninterface PwContext {\n newPage(): Promise<PwPage>\n close(): Promise<void>\n}\ninterface PwBrowser {\n newContext(opts?: unknown): Promise<PwContext>\n close(): Promise<void>\n}\n\n/**\n * Build the headless-Playwright renderer, or return `null` when Playwright / a\n * browser is unavailable (the caller then no-ops — head + JSON-LD are already\n * emitted, so the build is unaffected). Never throws on missing infra.\n */\nexport async function createPlaywrightRenderer(\n options: PlaywrightRendererOptions\n): Promise<PlaywrightRendererHandle | null> {\n const {\n outDir,\n navTimeoutMs = 30000,\n mountTimeoutMs = 15000,\n settleMs = 250,\n debug = false,\n } = options\n\n // Optional dependency: resolve `playwright` from the consuming site. The\n // computed specifier keeps the bundler from trying to resolve it at build time.\n let chromium: { launch(opts?: unknown): Promise<PwBrowser> } | undefined\n try {\n const specifier = 'playwright'\n const pw = (await import(/* @vite-ignore */ specifier)) as {\n chromium?: { launch(opts?: unknown): Promise<PwBrowser> }\n }\n chromium = pw.chromium\n } catch {\n console.warn(\n '[dcs-seo] body-prerender: `playwright` is not installed; skipping body ' +\n 'prerender (head + JSON-LD still emitted). `pnpm add -D playwright` to enable.'\n )\n return null\n }\n if (!chromium) {\n console.warn('[dcs-seo] body-prerender: playwright has no chromium export; skipping.')\n return null\n }\n\n // The server starts FIRST because it is also the browser's proxy (C-1962):\n // Chromium is launched pointing at it, so it must exist before the launch.\n const server = await startStaticServer(outDir)\n\n let browser: PwBrowser\n try {\n browser = await chromium.launch({ headless: true, proxy: { server: server.origin } })\n } catch (err) {\n await server.close().catch(() => {})\n console.warn(\n '[dcs-seo] body-prerender: failed to launch Chromium (run ' +\n '`npx playwright install chromium`); skipping body prerender:',\n err instanceof Error ? err.message : err\n )\n return null\n }\n\n // From here on a LIVE Chromium process is owned by this function, and the only\n // thing that can ever close it is the `close()` returned at the bottom. If any\n // step between the launch and that return throws, the caller receives a\n // rejection and no handle — so nothing is left holding a reference to the\n // browser, and it survives as an orphan process plus the open handles that\n // keep its host alive (a `vite build`, or a vitest worker). C-488: unwind what\n // we managed to construct, in reverse, before letting the error out.\n let context: PwContext\n try {\n context = await browser.newContext({ reducedMotion: 'reduce' })\n } catch (err) {\n await browser.close().catch(() => {})\n await server.close().catch(() => {})\n throw err\n }\n\n const renderer: RouteRenderer = {\n async renderRoute(routePath: string): Promise<RenderedRoute> {\n const page = await context.newPage()\n const errors: string[] = []\n page.on('pageerror', (err) => errors.push(`pageerror: ${err.message}`))\n if (debug) {\n page.on('console', (msg) => {\n if (msg.type() === 'error') console.log(`[dcs-seo] (console) ${msg.text()}`)\n })\n }\n\n // Keep the render offline + fast: serve our own origin, abort everything\n // else. The DOM keeps external <img>/<link> tags regardless. Compare the\n // parsed origin, not a string prefix — `http://127.0.0.1:<port>@evil.com/…`\n // starts with our origin but resolves to evil.com. (Perf/noise gate, not a\n // security boundary — the trust boundary is that we run the site's own\n // production bundle.)\n await page.route('**/*', (route) => {\n let sameOrigin = false\n try {\n sameOrigin = new URL(route.request().url()).origin === server.origin\n } catch {\n sameOrigin = false\n }\n // Swallow the continue/abort rejection that races page.close (\"Route is\n // already handled\" / target closed) — an unhandled rejection would crash\n // the vite process under Node's throw-on-unhandled default.\n if (sameOrigin) {\n route.continue().catch(() => {})\n } else {\n route.abort().catch(() => {})\n }\n })\n\n try {\n await page.goto(prerenderNavigationUrl(server.origin, routePath), {\n waitUntil: 'load',\n timeout: navTimeoutMs,\n })\n // The app mounts into #app; wait until it has real children (a failed\n // mount / crash never satisfies this → timeout → fatal error below).\n await page.waitForFunction(\n () => {\n const el = document.querySelector('#app')\n return !!el && el.children.length > 0\n },\n undefined,\n { timeout: mountTimeoutMs }\n )\n if (settleMs > 0) await page.waitForTimeout(settleMs)\n const bodyHtml = await page.$eval('#app', (el) => el.innerHTML)\n // P1: read the POST-MOUNT <head> from the same render. This is what a\n // JS-rendering crawler (and every human) sees, and it is compared against\n // the baked <head> already on disk — see `headHonesty.ts`. The LAST\n // description wins because that is what unhead leaves in place after it\n // replaces the baked one; the count is carried so a duplicate is visible.\n const head = await page.evaluate(() => {\n const metas = Array.from(\n document.querySelectorAll('meta[name=\"description\" i]')\n ) as HTMLMetaElement[]\n return {\n title: document.title ?? null,\n description: metas.length ? metas[metas.length - 1].getAttribute('content') : null,\n descriptionCount: metas.length,\n }\n })\n return { bodyHtml: bodyHtml ?? '', errors, head }\n } catch (err) {\n // A nav/mount timeout is itself a fatal render failure — report it so the\n // caller fails the build loud rather than shipping an empty body.\n errors.push(err instanceof Error ? err.message : String(err))\n return { bodyHtml: '', errors }\n } finally {\n await page.close()\n }\n },\n }\n\n // C-488: `close()` is called from a `finally` (see `runBodyPrerender`), and a\n // caller that also closes defensively — or an error path and a normal path\n // that both reach the same `finally` — can call it twice. Memoise the teardown\n // so it is idempotent: the second caller awaits the SAME settled promise\n // instead of re-entering `context.close()` / `browser.close()` on already-torn-\n // down handles and racing the first teardown that is still in flight. Each step\n // is individually caught, so teardown reports success once everything it owns\n // is down and never surfaces a shutdown error as a build failure.\n let teardown: Promise<void> | null = null\n\n return {\n renderer,\n blockedRequests: () => server.blocked.slice(),\n close() {\n teardown ??= (async () => {\n try {\n await context.close()\n } catch {\n /* ignore */\n }\n try {\n await browser.close()\n } catch {\n /* ignore */\n }\n try {\n await server.close()\n } catch {\n /* ignore */\n }\n })()\n return teardown\n },\n }\n}\n","/**\n * Per-route sitemap `<lastmod>` derived from git (RFQ-002427 L1a, cms 0.14.0).\n *\n * OPT-IN AND BEST-EFFORT. The factory never infers a lastmod by default: a URL\n * carries its per-route `.dcs/pages.yaml` date or no `<lastmod>`. This walk\n * runs only for a site that sets `.dcs/seo.yaml` `sitemap.lastmodFromGit:\n * true` (or the `gitLastmod` option). Known gaps the opt-in accepts:\n * composables/stores/lib/utils are excluded, not inspected (content a page\n * reads through them is not dated unless re-included via `lastmodExclude`\n * `!glob`); markdown includes (`<!--@include:-->`) are not traced; a VitePress\n * page with a custom frontmatter `layout:` is omitted, not traced; runtime\n * data (API fetches, live artifacts) is never dated.\n *\n * The sitemap rule: a `<lastmod>` is accurate for its URL, or it is omitted.\n * Never a build-time stamp, and never one site-wide date on every URL (the\n * kineticenergypt F4 defect: all 52 URLs carried seo.yaml `lastUpdated`, stale\n * on 100 % of them).\n *\n * INVARIANT: a route gets a git-derived lastmod only when EVERY material\n * content source of that route is tracked and dated; otherwise that route's\n * lastmod is omitted.\n *\n * Precedence, applied by `buildSitemapXml`:\n * 1. a per-route `lastmod` / `lastUpdated` / `dateModified` on the\n * `.dcs/pages.yaml` entry (validated);\n * 2. the git-derived date from here = the NEWEST of\n * (a) the route's view or markdown file,\n * (b) every local module reachable from it through other content modules\n * (transitive, shared or not), never counting or walking into the\n * non-content exclusions ({@link DEFAULT_LASTMOD_EXCLUDE} plus\n * `.dcs/seo.yaml` `sitemap.lastmodExclude`),\n * (c) the route's own content in `.dcs/content.yaml`: the newest commit\n * that changed `pages.<slug>` or a `global` key the route's sources\n * reference by name (parsed-subtree diff, commit by commit, capped at\n * {@link CONTENT_WALK_LIMIT} commits);\n * 3. nothing: `<lastmod>` is omitted.\n *\n * A route is omitted (no git date) when any material source cannot be\n * accounted for: no resolvable view, an import that resolves to no file and is\n * not an installed package (virtual modules, unknown aliases), a VitePress\n * markdown component tag with no theme registration, a VitePress data loader\n * whose inputs are not literal globs, an untracked or locally modified source,\n * or a content.yaml walk that hit the cap without finding the change.\n *\n * Git-derived dates are withheld for ALL routes when git is unavailable, the\n * clone is shallow (`git rev-parse --is-shallow-repository`), or 3+ dated\n * routes ALL share one single date (the uniform-stamp signature). A partial\n * overlap from a real bulk commit is accurate and kept.\n *\n * Modelled on lane L3's web/scripts/generate-sitemap.mjs (169eb73f8,\n * acebc7a75: transitive content-module walk, NON_CONTENT_SOURCES, one\n * `git log --name-only --cc` prime walk so merge resolutions count).\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { builtinModules } from 'node:module'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { PageRouteEntry } from '../seo/pagesManifest'\n\n/** Runs `git <args>` in `cwd` and returns stdout; throws on any failure. */\nexport type GitRunner = (args: string[], cwd: string) => string\n\n/** Why git-derived dates were withheld for the whole site (undefined = used). */\nexport type RouteLastmodWithheld = 'git-unavailable' | 'shallow' | 'identical-dates'\n\n/** Why ONE route got no git-derived date. */\nexport type RouteLastmodOmitted =\n | 'no-source'\n | 'unresolved-import'\n | 'unresolved-component'\n | 'untracked-source'\n | 'data-loader'\n | 'undated-source'\n | 'content-walk-cap'\n | 'content-untracked'\n | 'custom-layout'\n\n/** With this many or more dated routes all on ONE date, every git date is withheld. */\nexport const IDENTICAL_LASTMOD_ROUTE_LIMIT = 3\n\n/** content.yaml commits walked per site before an unanswered route is omitted. */\nexport const CONTENT_WALK_LIMIT = 300\n\n/**\n * Local modules that never count toward a page's lastmod and are not walked\n * into: app shell and chrome, non-content code, styles, tests, and the `.dcs`\n * metadata files (content.yaml is dated per route by (c) instead). Globs are\n * matched against the path relative to `projectRoot`; a glob without `/`\n * matches the basename. A site extends this with `.dcs/seo.yaml`\n * `sitemap.lastmodExclude`, where a `!glob` entry re-includes.\n */\nexport const DEFAULT_LASTMOD_EXCLUDE: readonly string[] = [\n // App shell, routing, entry points\n 'App.vue',\n 'main.{ts,js,mts,mjs}',\n '**/router/**',\n // Layouts (VitePress theme Layout.vue, any layouts/ dir) and theme/config shell\n 'Layout.vue',\n '**/layouts/**',\n '**/.vitepress/config.*',\n '**/.vitepress/theme/index.*',\n // Site-wide header / footer / nav / banner chrome\n '{App,Site,Main,Global,Top,Page,The,Mobile,}{Header,Footer,Nav,NavBar,Navbar,Navigation,NavMenu,Banner,AnnouncementBanner}.vue',\n // Non-content code\n '**/composables/**',\n '**/stores/**',\n '**/lib/**',\n '**/utils/**',\n '**/components/ui/**',\n // Styles and tests\n '*.{css,scss,sass,less,styl,pcss,postcss}',\n '*.{test,spec}.*',\n '**/__tests__/**',\n // DCS metadata: seo/pages/site are head + registry, content is dated per route\n '**/.dcs/{seo,pages,site,content}.yaml',\n '**/node_modules/**',\n]\n\nexport interface DeriveRouteLastmodsOptions {\n routes: PageRouteEntry[]\n /** Directory the source paths resolve against. */\n projectRoot: string\n /**\n * Site override for a route's ENTRY files (absolute, or relative to\n * `projectRoot`); the content-module walk still runs from them. Return\n * `undefined` for the default mapping, `[]` to give the route no git date.\n */\n sourcesForRoute?: (route: PageRouteEntry) => string[] | undefined\n /** `.dcs/content.yaml` path (absolute or projectRoot-relative). Default: searched. */\n contentPath?: string\n /** Extra exclusion globs (`.dcs/seo.yaml` `sitemap.lastmodExclude`); `!glob` re-includes. */\n exclude?: string[]\n /** content.yaml commits to walk (default {@link CONTENT_WALK_LIMIT}). */\n contentWalkLimit?: number\n /** Injectable git runner (tests). Defaults to a real `git` subprocess. */\n git?: GitRunner\n debug?: boolean\n}\n\nexport interface DeriveRouteLastmodsResult {\n /** route.path → ISO-8601 committer date of the newest change to its material sources. */\n lastmods: Map<string, string>\n /** Set when every git-derived date was withheld, with the reason. */\n withheld?: RouteLastmodWithheld\n /** route.path → why that route got no date (only routes the walk reached). */\n omitted: Map<string, RouteLastmodOmitted>\n /** route.path → the material source files that were dated (absolute). */\n sources: Map<string, string[]>\n}\n\nconst defaultGit: GitRunner = (args, cwd) =>\n execFileSync('git', args, {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n timeout: 60_000,\n maxBuffer: 256 * 1024 * 1024,\n windowsHide: true,\n })\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Route → entry file\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `how-it-works` → `HowItWorks`; `home` → `Home`. */\nfunction toPascal(value: string): string {\n return value\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n}\n\n/**\n * The conventional entry files for a route, relative to `projectRoot`, in\n * priority order. Covers the SPA layout (`src/views/<Name>View.vue`,\n * `src/pages/<Name>.vue`) and the VitePress layout (`<path>.md`,\n * `<path>/index.md`, under the root or `docs/`). The FIRST that exists is the\n * route's entry.\n */\nexport function defaultRouteSourceCandidates(route: PageRouteEntry): string[] {\n const rel = route.path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n const isHome = rel === ''\n const names = new Set<string>()\n const slugName = toPascal(route.slug || '')\n if (slugName) names.add(slugName)\n const lastSegment = rel.split('/').pop() ?? ''\n const segName = toPascal(lastSegment)\n if (segName) names.add(segName)\n if (isHome) names.add('Home')\n\n const out: string[] = []\n for (const name of names) {\n out.push(`src/views/${name}View.vue`, `src/views/${name}.vue`, `src/pages/${name}.vue`, `src/pages/${name}View.vue`)\n }\n if (isHome) {\n out.push('index.md', 'docs/index.md')\n } else {\n out.push(`${rel}.md`, `${rel}/index.md`, `docs/${rel}.md`, `docs/${rel}/index.md`)\n }\n return out\n}\n\nfunction isFile(abs: string): boolean {\n try {\n return fs.statSync(abs).isFile()\n } catch {\n return false\n }\n}\n\nfunction routeEntries(\n route: PageRouteEntry,\n projectRoot: string,\n sourcesForRoute: DeriveRouteLastmodsOptions['sourcesForRoute']\n): string[] {\n const custom = sourcesForRoute?.(route)\n if (custom) {\n return [...new Set(custom.filter((c) => typeof c === 'string' && c).map((c) => path.resolve(projectRoot, c)))].filter(isFile)\n }\n const first = defaultRouteSourceCandidates(route)\n .map((c) => path.resolve(projectRoot, c))\n .find(isFile)\n return first ? [first] : []\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Globs\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/** Minimal glob → RegExp: `**`, `*`, `?`, `{a,b}` (alternatives literal or wildcard). */\nexport function lastmodGlobToRegExp(glob: string): RegExp {\n const convert = (g: string): string => {\n let re = ''\n for (let i = 0; i < g.length; i++) {\n const c = g[i]\n if (c === '*') {\n if (g[i + 1] === '*') {\n if (g[i + 2] === '/') {\n re += '(?:.*/)?'\n i += 2\n } else {\n re += '.*'\n i += 1\n }\n } else {\n re += '[^/]*'\n }\n } else if (c === '?') {\n re += '[^/]'\n } else if (c === '{') {\n const end = g.indexOf('}', i)\n if (end > i) {\n re += '(?:' + g.slice(i + 1, end).split(',').map(convert).join('|') + ')'\n i = end\n } else {\n re += '\\\\{'\n }\n } else {\n re += escapeRe(c)\n }\n }\n return re\n }\n return new RegExp('^' + convert(glob) + '$')\n}\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/')\n}\n\nfunction makeExcluder(projectRoot: string, extra: string[], alsoExcludeAbs: string[]) {\n const plain = [...DEFAULT_LASTMOD_EXCLUDE, ...extra.filter((g) => !g.startsWith('!'))].map((g) => ({\n re: lastmodGlobToRegExp(g),\n base: !g.includes('/'),\n }))\n const reinclude = extra\n .filter((g) => g.startsWith('!'))\n .map((g) => ({ re: lastmodGlobToRegExp(g.slice(1)), base: !g.slice(1).includes('/') }))\n const fixed = new Set(alsoExcludeAbs.map((a) => path.resolve(a).toLowerCase()))\n const test = (rules: Array<{ re: RegExp; base: boolean }>, rel: string) =>\n rules.some((r) => r.re.test(r.base ? rel.split('/').pop() ?? rel : rel))\n return (abs: string): boolean => {\n if (fixed.has(path.resolve(abs).toLowerCase())) return true\n const rel = toPosix(path.relative(projectRoot, abs))\n if (!test(plain, rel)) return false\n return !test(reinclude, rel)\n }\n}\n\n/** Expand a glob (absolute, posix) to existing files. */\nfunction expandGlob(absPattern: string): string[] {\n const posix = toPosix(absPattern)\n const firstWild = posix.search(/[*?{]/)\n if (firstWild < 0) return isFile(absPattern) ? [path.resolve(absPattern)] : []\n const baseDir = posix.slice(0, posix.lastIndexOf('/', firstWild))\n const re = lastmodGlobToRegExp(posix)\n const out: string[] = []\n const walk = (dir: string, depth: number) => {\n if (depth > 12) return\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const e of entries) {\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = path.join(dir, e.name)\n if (e.isDirectory()) walk(full, depth + 1)\n else if (e.isFile() && re.test(toPosix(full))) out.push(path.resolve(full))\n }\n }\n walk(baseDir || '/', 0)\n return out\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Content-module walk\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst CODE_EXT = /\\.(vue|[cm]?[jt]sx?|md)$/i\nconst RESOLVE_EXTENSIONS = ['', '.ts', '.js', '.mts', '.mjs', '.tsx', '.jsx', '.vue', '.json', '/index.ts', '/index.js', '/index.vue']\nconst BUILTINS = new Set(builtinModules)\n/** VitePress built-in components a markdown page may use without registration. */\nconst VITEPRESS_BUILTIN_TAGS = new Set(['Badge', 'Content', 'ClientOnly'])\n/** VitePress built-in frontmatter layouts (anything else is a custom theme layout). */\nconst VITEPRESS_BUILTIN_LAYOUTS = new Set(['doc', 'home', 'page', 'false'])\n\n/** Strip block comments and whole-line `//` comments (URLs inside strings survive). */\nfunction stripComments(src: string): string {\n return src.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/^\\s*\\/\\/.*$/gm, '')\n}\n\nfunction findSrcDir(file: string): string | undefined {\n let dir = path.dirname(file)\n for (let i = 0; i < 12; i++) {\n if (fs.existsSync(path.join(dir, '.vitepress'))) return dir\n const up = path.dirname(dir)\n if (up === dir) return undefined\n dir = up\n }\n return undefined\n}\n\nfunction hasPackage(specifier: string, fromFile: string): boolean {\n const parts = specifier.split('/')\n const pkg = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]\n let dir = path.dirname(fromFile)\n for (let i = 0; i < 40; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', pkg))) return true\n const up = path.dirname(dir)\n if (up === dir) return false\n dir = up\n }\n return false\n}\n\nfunction resolveWithExtensions(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const c = base + ext\n if (isFile(c)) return path.resolve(c)\n }\n return undefined\n}\n\ntype ImportResolution = { kind: 'file'; file: string } | { kind: 'package' } | { kind: 'unresolved' }\n\nfunction resolveImport(specifierRaw: string, fromFile: string, projectRoot: string): ImportResolution {\n const specifier = specifierRaw.replace(/[?#].*$/, '')\n if (!specifier) return { kind: 'unresolved' }\n if (specifier.startsWith('node:') || BUILTINS.has(specifier)) return { kind: 'package' }\n if (specifier.startsWith('virtual:') || specifier.startsWith('\\0')) return { kind: 'unresolved' }\n let base: string | undefined\n if (specifier.startsWith('.')) base = path.resolve(path.dirname(fromFile), specifier)\n else if (specifier.startsWith('@/') || specifier.startsWith('~/')) base = path.join(projectRoot, 'src', specifier.slice(2))\n else if (specifier.startsWith('@theme/')) {\n const srcDir = findSrcDir(fromFile)\n if (srcDir) base = path.join(srcDir, '.vitepress', 'theme', specifier.slice('@theme/'.length))\n } else if (specifier.startsWith('/')) {\n const srcDir = findSrcDir(fromFile)\n const hit = resolveWithExtensions(path.join(projectRoot, specifier)) ?? (srcDir ? resolveWithExtensions(path.join(srcDir, specifier)) : undefined)\n return hit ? { kind: 'file', file: hit } : { kind: 'unresolved' }\n } else {\n return hasPackage(specifier, fromFile) ? { kind: 'package' } : { kind: 'unresolved' }\n }\n if (!base) return { kind: 'unresolved' }\n const hit = resolveWithExtensions(base)\n return hit ? { kind: 'file', file: hit } : { kind: 'unresolved' }\n}\n\n/** `Name` → file, from a VitePress theme's `app.component('Name', Ident)` registrations. */\nfunction themeRegistry(srcDir: string, cache: Map<string, Map<string, string>>): Map<string, string> {\n const hit = cache.get(srcDir)\n if (hit) return hit\n const reg = new Map<string, string>()\n const themeDir = path.join(srcDir, '.vitepress', 'theme')\n const indexFile = ['index.ts', 'index.js', 'index.mts', 'index.mjs'].map((f) => path.join(themeDir, f)).find(isFile)\n if (indexFile) {\n const src = stripComments(fs.readFileSync(indexFile, 'utf8'))\n const idents = new Map<string, string>()\n for (const m of src.matchAll(/^\\s*import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/gm)) idents.set(m[1], m[2])\n for (const m of src.matchAll(/\\.component\\(\\s*['\"]([\\w-]+)['\"]\\s*,\\s*(\\w+)\\s*\\)/g)) {\n const spec = idents.get(m[2])\n if (!spec) continue\n const r = resolveImport(spec, indexFile, srcDir)\n if (r.kind === 'file') {\n reg.set(m[1], r.file)\n reg.set(toPascal(m[1]), r.file)\n }\n }\n }\n cache.set(srcDir, reg)\n return reg\n}\n\n/** Literal glob patterns of a VitePress data loader (`createContentLoader`, `watch`). */\nfunction dataLoaderInputs(src: string, loaderFile: string): string[] | null {\n const srcDir = findSrcDir(loaderFile) ?? path.dirname(loaderFile)\n const literals = (s: string) => [...s.matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1])\n const out: string[] = []\n let found = false\n for (const m of src.matchAll(/createContentLoader\\(\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n found = true\n for (const g of literals(m[1])) out.push(...expandGlob(path.resolve(srcDir, g)))\n }\n for (const m of src.matchAll(/\\bwatch\\s*:\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n found = true\n for (const g of literals(m[1])) {\n const base = g.startsWith('.') ? path.dirname(loaderFile) : srcDir\n out.push(...expandGlob(path.resolve(base, g)))\n }\n }\n return found ? out : null\n}\n\ninterface WalkResult {\n files: string[]\n omitted?: RouteLastmodOmitted\n}\n\nfunction walkContentModules(\n entries: string[],\n projectRoot: string,\n isExcluded: (abs: string) => boolean,\n registryCache: Map<string, Map<string, string>>,\n fileCache: Map<string, { deps: string[]; bad?: RouteLastmodOmitted }>\n): WalkResult {\n const seen = new Set<string>()\n const queue: string[] = []\n for (const e of entries) {\n if (!seen.has(e)) {\n seen.add(e)\n queue.push(e)\n }\n }\n while (queue.length > 0) {\n const file = queue.shift() as string\n let info = fileCache.get(file)\n if (!info) {\n info = scanFile(file, projectRoot, registryCache)\n fileCache.set(file, info)\n }\n if (info.bad) return { files: [...seen], omitted: info.bad }\n for (const dep of info.deps) {\n if (seen.has(dep) || isExcluded(dep)) continue\n seen.add(dep)\n queue.push(dep)\n }\n }\n return { files: [...seen] }\n}\n\n/** One file's local dependencies (not yet exclusion-filtered), or why it cannot be accounted for. */\nfunction scanFile(\n file: string,\n projectRoot: string,\n registryCache: Map<string, Map<string, string>>\n): { deps: string[]; bad?: RouteLastmodOmitted } {\n if (!CODE_EXT.test(file)) return { deps: [] }\n let raw: string\n try {\n raw = fs.readFileSync(file, 'utf8')\n } catch {\n return { deps: [], bad: 'unresolved-import' }\n }\n const isMd = /\\.md$/i.test(file)\n // A VitePress page whose frontmatter selects a custom layout is rendered by\n // that layout through the theme's dispatch, which this walk cannot see:\n // omit it rather than date it by its markdown alone (judge A1).\n if (isMd) {\n const fm = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/)\n const layout = fm?.[1].match(/^layout\\s*:\\s*(.*?)\\s*$/m)?.[1].replace(/^['\"]|['\"]$/g, '')\n if (layout && !VITEPRESS_BUILTIN_LAYOUTS.has(layout)) return { deps: [], bad: 'custom-layout' }\n }\n // Markdown: only <script> blocks carry imports; fenced code is not markup.\n const body = isMd ? raw.replace(/^(```|~~~)[\\s\\S]*?^\\1/gm, '') : raw\n const code = isMd ? [...body.matchAll(/<script\\b[^>]*>([\\s\\S]*?)<\\/script>/gi)].map((m) => m[1]).join('\\n') : body\n const src = stripComments(code)\n const deps = new Set<string>()\n\n if (/\\.data\\.[cm]?[jt]s$/i.test(file)) {\n const inputs = dataLoaderInputs(src, file)\n if (inputs === null) return { deps: [], bad: 'data-loader' }\n for (const f of inputs) deps.add(f)\n }\n\n for (const m of src.matchAll(/(?:\\bfrom\\s*|\\bimport\\s*\\(\\s*|^\\s*import\\s+)['\"]([^'\"]+)['\"]/gm)) {\n const r = resolveImport(m[1], file, projectRoot)\n if (r.kind === 'unresolved') return { deps: [], bad: 'unresolved-import' }\n if (r.kind === 'file' && r.file !== path.resolve(file)) deps.add(r.file)\n }\n\n for (const m of src.matchAll(/import\\.meta\\.glob(?:<[^>]*>)?\\(\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n for (const lit of [...m[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((x) => x[1])) {\n if (lit.startsWith('!')) continue\n const abs = lit.startsWith('/') ? path.join(projectRoot, lit) : path.resolve(path.dirname(file), lit)\n for (const f of expandGlob(abs)) deps.add(f)\n }\n }\n\n // VitePress: components registered globally by the theme and used as tags.\n const srcDir = findSrcDir(file)\n if (srcDir) {\n const reg = themeRegistry(srcDir, registryCache)\n const markup = isMd\n ? body.replace(/<script\\b[\\s\\S]*?<\\/script>/gi, '').replace(/`[^`\\n]*`/g, '')\n : (raw.match(/<template\\b[\\s\\S]*<\\/template>/i)?.[0] ?? '')\n const tags = new Set<string>()\n for (const m of markup.matchAll(/<([A-Z][A-Za-z0-9]*)\\b/g)) tags.add(m[1])\n for (const m of markup.matchAll(/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\b/g)) tags.add(toPascal(m[1]))\n for (const tag of tags) {\n const target = reg.get(tag)\n if (target) deps.add(target)\n else if (isMd && !VITEPRESS_BUILTIN_TAGS.has(tag)) return { deps: [], bad: 'unresolved-component' }\n }\n }\n return { deps: [...deps] }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// content.yaml (c)\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface ContentEntry {\n date: string\n oldBlob: string\n newBlob: string\n}\n\nconst ZERO_BLOB = /^0+$/\n\nfunction findContentFile(projectRoot: string, contentPath: string | undefined): string | undefined {\n const rel = contentPath ?? '.dcs/content.yaml'\n if (path.isAbsolute(rel)) return isFile(rel) ? path.resolve(rel) : undefined\n return [path.resolve(projectRoot, rel), path.resolve(projectRoot, '..', rel), path.resolve(process.cwd(), rel)].find(isFile)\n}\n\n/** Global content.yaml keys a route's sources reference as string literals. */\nfunction referencedGlobalKeys(files: string[], globalKeys: string[]): string[] {\n if (globalKeys.length === 0) return []\n const text = files\n .filter((f) => CODE_EXT.test(f))\n .map((f) => {\n try {\n return fs.readFileSync(f, 'utf8')\n } catch {\n return ''\n }\n })\n .join('\\n')\n return globalKeys.filter((k) => text.includes(`'${k}'`) || text.includes(`\"${k}\"`) || text.includes(`\\`${k}\\``))\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Main\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Derive per-route `<lastmod>` values from git. Never throws: any git failure\n * withholds the git-derived dates (the sitemap then omits `<lastmod>` for\n * routes without a pages.yaml date).\n */\nexport function deriveRouteLastmods(options: DeriveRouteLastmodsOptions): DeriveRouteLastmodsResult {\n const {\n routes,\n projectRoot,\n sourcesForRoute,\n contentPath,\n exclude = [],\n contentWalkLimit = CONTENT_WALK_LIMIT,\n git = defaultGit,\n debug = false,\n } = options\n const omitted = new Map<string, RouteLastmodOmitted>()\n const sources = new Map<string, string[]>()\n const empty = (withheld: RouteLastmodWithheld): DeriveRouteLastmodsResult => {\n if (debug) console.log(`[dcs-seo] git-derived <lastmod> withheld: ${withheld}`)\n return { lastmods: new Map(), withheld, omitted, sources }\n }\n\n let shallow: string\n try {\n shallow = git(['rev-parse', '--is-shallow-repository'], projectRoot).trim()\n } catch {\n return empty('git-unavailable')\n }\n if (shallow === 'true') return empty('shallow')\n // Anything but a literal `false` (e.g. a git too old to know the flag echoes\n // it back) is not proof of full history.\n if (shallow !== 'false') return empty('git-unavailable')\n\n let top: string\n try {\n top = path.resolve(git(['rev-parse', '--show-toplevel'], projectRoot).trim())\n } catch {\n return empty('git-unavailable')\n }\n const relTop = (abs: string) => toPosix(path.relative(top, abs))\n\n const contentFile = findContentFile(projectRoot, contentPath)\n const isExcluded = makeExcluder(projectRoot, exclude, contentFile ? [contentFile] : [])\n\n // ── (a) + (b): per-route material source sets ─────────────────────────────\n const registryCache = new Map<string, Map<string, string>>()\n const fileCache = new Map<string, { deps: string[]; bad?: RouteLastmodOmitted }>()\n const routeFiles = new Map<string, string[]>()\n for (const route of routes) {\n if (routeFiles.has(route.path) || omitted.has(route.path)) continue\n const entries = routeEntries(route, projectRoot, sourcesForRoute)\n if (entries.length === 0) {\n omitted.set(route.path, 'no-source')\n continue\n }\n const walked = walkContentModules(entries, projectRoot, isExcluded, registryCache, fileCache)\n if (walked.omitted) {\n omitted.set(route.path, walked.omitted)\n continue\n }\n routeFiles.set(route.path, walked.files)\n }\n\n const allFiles = [...new Set([...routeFiles.values()].flat())]\n const material = contentFile ? [...allFiles, contentFile] : allFiles\n\n // Tracked and clean: an untracked or locally modified source has no commit date.\n const tracked = new Set<string>()\n const dirty = new Set<string>()\n const newest = new Map<string, string>()\n if (material.length > 0) {\n const rels = [...new Set(material.map(relTop))]\n try {\n // Whole-repo listings (no pathspec): a long pathspec can exceed the\n // Windows command-line limit on a site with hundreds of posts.\n for (const line of git(['-c', 'core.quotepath=off', 'ls-files'], top).split('\\n')) {\n if (line.trim()) tracked.add(line.trim())\n }\n for (const line of git(['-c', 'core.quotepath=off', 'status', '--porcelain=v1', '--untracked-files=all'], top).split('\\n')) {\n if (line.length <= 3) continue\n for (const part of line.slice(3).trim().split(' -> ')) dirty.add(part.replace(/^\"|\"$/g, ''))\n }\n // Dating walk, in batches; `--cc` makes a merge that changed a file (a\n // conflict resolution) list it, so such a page is not dated older.\n const dated = rels.filter((r) => tracked.has(r))\n for (let i = 0; i < dated.length; i += 150) {\n const out = git(\n ['-c', 'core.quotepath=off', 'log', '--format=%x01%cI', '--name-only', '--cc', '--', ...dated.slice(i, i + 150)],\n top\n )\n let date: string | null = null\n for (const line of out.split('\\n')) {\n const t = line.trim()\n if (t.startsWith('\\u0001')) {\n date = t.slice(1)\n continue\n }\n if (!t || !date) continue\n const known = newest.get(t)\n if (!known || Date.parse(date) > Date.parse(known)) newest.set(t, date)\n }\n }\n } catch {\n return empty('git-unavailable')\n }\n }\n const isClean = (abs: string) => tracked.has(relTop(abs)) && !dirty.has(relTop(abs))\n\n // ── (c) content.yaml: per-route subtree change dates ──────────────────────\n let contentEntries: ContentEntry[] = []\n let contentCapped = false\n let contentOk = true\n const blobCache = new Map<string, Record<string, unknown> | null>()\n let globalKeys: string[] = []\n if (contentFile) {\n if (!isClean(contentFile)) {\n contentOk = false\n } else {\n try {\n const out = git(\n ['log', '--first-parent', '-m', `-n${contentWalkLimit + 1}`, '--format=%x01%cI', '--raw', '--no-abbrev', '--', relTop(contentFile)],\n top\n )\n let date: string | null = null\n for (const line of out.split('\\n')) {\n const t = line.trim()\n if (t.startsWith('\\u0001')) {\n date = t.slice(1)\n continue\n }\n const m = t.match(/^:\\d+ \\d+ ([0-9a-f]+) ([0-9a-f]+) /)\n if (m && date) contentEntries.push({ date, oldBlob: m[1], newBlob: m[2] })\n }\n } catch {\n return empty('git-unavailable')\n }\n if (contentEntries.length > contentWalkLimit) {\n contentCapped = true\n contentEntries = contentEntries.slice(0, contentWalkLimit)\n }\n try {\n const head = yaml.load(fs.readFileSync(contentFile, 'utf8')) as { global?: Record<string, unknown> } | null\n globalKeys = Object.keys(head?.global ?? {})\n } catch {\n contentOk = false\n }\n }\n }\n const loadBlob = (blob: string): Record<string, unknown> | null => {\n if (ZERO_BLOB.test(blob)) return null\n if (blobCache.has(blob)) return blobCache.get(blob) ?? null\n let doc: Record<string, unknown> | null = null\n try {\n doc = (yaml.load(git(['cat-file', '-p', blob], top)) as Record<string, unknown> | null) ?? null\n } catch {\n doc = null\n }\n blobCache.set(blob, doc)\n return doc\n }\n const subtreeKey = (doc: Record<string, unknown> | null, slug: string, keys: string[]): string => {\n const pages = (doc?.pages ?? {}) as Record<string, unknown>\n const global = (doc?.global ?? {}) as Record<string, unknown>\n return JSON.stringify({ page: pages[slug] ?? null, global: keys.map((k) => [k, global[k] ?? null]) })\n }\n\n // ── Combine ────────────────────────────────────────────────────────────────\n const lastmods = new Map<string, string>()\n for (const route of routes) {\n const files = routeFiles.get(route.path)\n if (!files || lastmods.has(route.path)) continue\n if (!files.every(isClean)) {\n omitted.set(route.path, 'untracked-source')\n continue\n }\n let best: string | null = null\n let undated = false\n for (const f of files) {\n const d = newest.get(relTop(f))\n if (!d) {\n undated = true\n break\n }\n if (best === null || Date.parse(d) > Date.parse(best)) best = d\n }\n if (undated || best === null) {\n omitted.set(route.path, 'undated-source')\n continue\n }\n if (contentFile) {\n if (!contentOk) {\n omitted.set(route.path, 'content-untracked')\n continue\n }\n const keys = referencedGlobalKeys(files, globalKeys)\n let contentDate: string | null = null\n for (const e of contentEntries) {\n if (subtreeKey(loadBlob(e.newBlob), route.slug, keys) !== subtreeKey(loadBlob(e.oldBlob), route.slug, keys)) {\n contentDate = e.date\n break\n }\n }\n if (contentDate === null && contentCapped) {\n omitted.set(route.path, 'content-walk-cap')\n continue\n }\n if (contentDate && Date.parse(contentDate) > Date.parse(best)) best = contentDate\n }\n lastmods.set(route.path, best)\n sources.set(route.path, contentFile ? [...files, contentFile] : files)\n }\n\n // Uniform-stamp signature: 3+ dated routes that ALL share one single date\n // (e.g. every file's history collapsed onto one graft/import commit). A\n // partial overlap from a real bulk commit is accurate and kept.\n if (lastmods.size >= IDENTICAL_LASTMOD_ROUTE_LIMIT && new Set(lastmods.values()).size === 1) {\n return empty('identical-dates')\n }\n\n if (debug) {\n for (const [p, why] of omitted) console.log(`[dcs-seo] <lastmod> omitted for ${p}: ${why}`)\n }\n return { lastmods, omitted, sources }\n}\n","/**\n * DCS SEO Plugin for Vite\n *\n * Two responsibilities, both driven by `.dcs/seo.yaml`:\n *\n * 1. **Build-time define** (always on): reads `.dcs/seo.yaml` and injects it as\n * the `__DCS_SEO__` global for the runtime `useSEO` composable.\n *\n * 2. **Static `<head>` emitter** (opt-in via `emitStaticHtml: true`, default\n * OFF): after the bundle is written, reads the SPA's built `index.html`,\n * and for every route in `.dcs/pages.yaml` writes a per-route\n * `dist/<path>/index.html` whose `<head>` carries the resolved title, meta,\n * canonical, Open Graph, Twitter, and JSON-LD tags. This gives a Vue SPA\n * per-route static SEO **without** vite-ssg.\n *\n * VitePress sites already bake SEO via their own config, so they leave this\n * option OFF and are completely unaffected.\n *\n * @example Runtime define only (default — safe for VitePress)\n * ```typescript\n * // vite.config.ts\n * import { dcsSeoPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [dcsSeoPlugin({ debug: true })]\n * })\n * ```\n *\n * @example Vue SPA with per-route static <head> emission\n * ```typescript\n * // vite.config.ts\n * import { dcsSeoPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsSeoPlugin({\n * emitStaticHtml: true, // turn the emitter ON\n * pagesPath: '.dcs/pages.yaml', // route manifest (default)\n * noindex: ['account', 'projects'], // robots: noindex,nofollow\n * exclude: ['/preview'], // skip these routes entirely\n * })\n * ]\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { Plugin, ResolvedConfig, HtmlTagDescriptor } from 'vite'\nimport type { SeoConfiguration, SeoHonestyBlock } from '../types/seo'\nimport { readDcsYamlFresh, buildGlobalAssignScript } from './serveDefineInject'\nimport { clearDirIndexManifest, installDirIndex, isVitePressSiteConfig } from './dcsDirIndex'\nimport { buildHeadTags } from '../seo/headTags'\nimport { spliceHeadHtml } from '../seo/spliceHeadHtml'\nimport {\n loadPagesManifest,\n routeExclusionReason,\n isRouteEmitted,\n type PageRouteEntry,\n} from '../seo/pagesManifest'\nimport {\n findDuplicateNormalizedPaths,\n formatDuplicateNormalizedPaths,\n} from '../seo/installSeoHead'\nimport {\n prerenderBodies,\n isBodyPrerenderEnabled,\n routeToOutputFile,\n} from '../seo/bodyPrerender'\nimport { createPlaywrightRenderer } from '../seo/playwrightRenderer'\nimport { deriveRouteLastmods, type GitRunner } from './routeLastmod'\nimport {\n assertHeadHonesty,\n assertHeadHonestyExecuted,\n findHeadHonestyViolations,\n resolveHonestyMode,\n type HeadObservation,\n type HonestyMode,\n} from '../seo/headHonesty'\nimport {\n collectEmittedUrlsFromFiles,\n dedupeUrls,\n classifyUrl,\n auditSameOriginAssets,\n checkRemoteAssets,\n formatEmittedUrlReport,\n formatEmittedUrlAudit,\n auditCheckedTotal,\n EmittedUrlError,\n EmittedUrlNotRunError,\n type ClassifiedUrl,\n type EmittedUrlAudit,\n type EmittedUrlViolation,\n} from '../seo/emittedUrls'\nimport {\n hoistCharsetMeta,\n checkCharsetBudget,\n formatCharsetHeadroomWarning,\n CharsetBudgetError,\n} from '../seo/charsetBudget'\nimport {\n buildSitemapXml,\n buildRobotsTxt,\n buildLlmsTxt,\n isHandAuthoredRobotsAcceptable,\n appendAiTrainingOptOut,\n findAiTrainingRobotsConflicts,\n RobotsAiTrainingConflictError,\n type DcsRobotsOptions,\n} from '../seo/sitemap'\nimport {\n breadcrumbTrailFromRoute,\n findReviewItemsForPage,\n findBusinessLicense,\n findPostalAddressGaps,\n formatPostalAddressGapReport,\n type ContentConfig,\n type ReviewSource,\n type BlogMeta,\n type FaqSource,\n} from '../seo/schemaGraph'\n\nexport interface DcsSeoPluginOptions {\n /** Path to seo.yaml relative to project root (default: '.dcs/seo.yaml') */\n seoPath?: string\n /** Enable debug logging */\n debug?: boolean\n\n /**\n * Opt-in: emit per-route static `<head>` (meta + JSON-LD) into the built\n * `dist/` at the end of the build. Default `false` — VitePress sites and any\n * site that bakes its own SEO are unaffected when this is off.\n */\n emitStaticHtml?: boolean\n\n /**\n * Build-time BODY prerender: after the per-route `<head>` is emitted, render\n * each indexable route's real DOM from the just-built SPA (headless Chromium\n * via the site's `playwright`) and splice it into the mount container so non-JS\n * AI crawlers see the page's body prose — not just `<div id=\"app\"></div>`.\n *\n * Defaults to whatever `emitStaticHtml` is, so every SPA already emitting\n * per-route HTML gains crawler-visible bodies on a cms bump with no per-site\n * edit. Set `false` here to keep head-only emission. It is ALSO overridable\n * per-site (no code change / no cms republish) via `.dcs/seo.yaml`\n * `prerenderBody: false`. noindex/auth-gated routes are never body-prerendered;\n * a route that crashes at render time fails the build loud rather than shipping\n * a broken body. Requires `playwright` in the site (already the fleet default);\n * absent ⇒ graceful no-op (head + JSON-LD still emitted).\n */\n prerenderBody?: boolean\n\n /**\n * Path to the route manifest relative to project root, used only when\n * `emitStaticHtml` is true. Default `'.dcs/pages.yaml'`.\n */\n pagesPath?: string\n\n /**\n * Path to `content.yaml` relative to project root, used only when\n * `emitStaticHtml` is true. Threads REAL reviews into the honest\n * Review/aggregateRating on the per-route LocalBusiness node. Default\n * `'.dcs/content.yaml'`. Missing/unparseable ⇒ no reviews emitted.\n */\n contentPath?: string\n\n /**\n * Routes to skip entirely (no per-route HTML written). Matched against the\n * route `path` (e.g. `'/preview'`) OR the route `slug` (e.g. `'account'`).\n */\n exclude?: string[]\n\n /**\n * Routes that should receive `robots: noindex, nofollow`. Matched against the\n * route `path` OR `slug`. The home route (`/`) still overwrites\n * `dist/index.html`.\n *\n * This is a PREDICATE OVER `pages.yaml`, not a standalone directive about a\n * URL. An entry that matches no page is a **build error**\n * (`NoindexOrphanError`, C-416) — with no matching page nothing is emitted for\n * it, so the entry would silently do nothing while the URL stayed\n * `index, follow`. Matched raw, so `'/account/'` does not match a `'/account'`\n * route; matched against the full manifest, so an entry that is also in\n * `exclude` is fine.\n */\n noindex?: string[]\n\n /**\n * Opt-in: emit the site-wide static files `dist/sitemap.xml`,\n * `dist/robots.txt`, and `dist/llms.txt` after the per-route HTML loop.\n *\n * Defaults to whatever `emitStaticHtml` is — so every site already calling\n * `dcsSeoPlugin({ emitStaticHtml: true })` gets sitemap/robots/llms for free\n * with zero per-site edits. Set explicitly to `false` to keep emitting\n * per-route HTML without the site files. The whole block is wrapped in the\n * same try/catch + existsSync guards, so it can never break a build.\n */\n emitSiteFiles?: boolean\n\n /**\n * Canonical production origin, e.g. `https://ironoakcontractors.com`. Used as\n * the sitemap/llms base and the absolute `Sitemap:` line in robots.txt. When\n * absent, falls back to `seo.yaml`'s `global.siteUrl`; if neither is known and\n * no per-page canonicals exist, the sitemap + llms.txt no-op (robots still\n * emits). Never guessed.\n */\n siteUrl?: string\n\n /** robots.txt override hooks (disallow/allow/extra/aiBots/force). */\n robots?: DcsRobotsOptions\n\n /**\n * Preview / staging gate. When `true`, robots.txt becomes `Disallow: /` (no\n * `Sitemap:` line) and neither sitemap.xml nor llms.txt is emitted (privacy).\n * Detected ONLY via this explicit option — never guessed.\n */\n preview?: boolean\n\n /** Emit `dist/llms.txt` (default `true`; always off in preview mode). */\n llms?: boolean\n\n /**\n * Opt in to git-derived sitemap `<lastmod>` (BEST-EFFORT; default OFF).\n * Without it the factory never infers a date: a URL carries its per-route\n * `.dcs/pages.yaml` `lastmod`, or no `<lastmod>`. The site-level switch is\n * `.dcs/seo.yaml` `sitemap.lastmodFromGit: true`; this option, when set,\n * overrides it for one build. See `deriveRouteLastmods` for what the walk\n * does and does not see.\n */\n gitLastmod?: boolean\n\n /**\n * Override a route's source files (absolute or project-root relative) for\n * the git-derived `<lastmod>`. Return `undefined` for the default mapping\n * (`src/views/<Name>View.vue`, `src/pages/<Name>.vue`, `<path>.md`, ...).\n */\n lastmodSources?: (route: PageRouteEntry) => string[] | undefined\n\n // ── SEO emission honesty rails (C-334) ────────────────────────────────────\n // Three asserts against one failure class: a capability that exists is\n // silently undone downstream and nothing notices. All three default ON\n // (severity `error`) whenever `emitStaticHtml` is on, and all three can be\n // lowered per-site from `.dcs/seo.yaml` (portal-owned) or per-build from an\n // env var that prints in the log. There is no silent off switch.\n\n /**\n * P1 — assert that each route's BAKED `<title>`/description equals what the\n * app leaves in the `<head>` after it mounts. Rides the prerender browser, so\n * the marginal cost is one `page.evaluate()` per route.\n *\n * Env override: `DCS_SEO_HEAD_HONESTY=error|warn|off`.\n * seo.yaml override: `headHonesty: warn` or `headHonesty: { mode, allow }`.\n */\n headHonesty?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * P2 — assert that every URL the factory publishes (JSON-LD logo/image IRIs,\n * `og:image`, icon links, sitemap `<loc>`s, llms.txt links) resolves to what it\n * promises. Same-origin assets are proven against `dist/` with no network;\n * cross-origin assets are probed under a cache + time budget and only a\n * DEFINITIVE wrong answer fails the build.\n *\n * Env override: `DCS_SEO_URL_HONESTY=error|warn|off`,\n * `DCS_SEO_URL_HONESTY_NETWORK=off` to skip the cross-origin probes.\n */\n urlHonesty?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * P12 — hoist `<meta charset>` to the top of `<head>` and assert it lands\n * inside the spec's 1024-byte encoding-sniffing window.\n *\n * Env override: `DCS_SEO_CHARSET_BUDGET=error|warn|off`.\n */\n charsetBudget?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * C-1965: on a VitePress `cleanUrls` BUILD, write a byte-identical\n * `<page>/index.html` twin of every flat `<page>.html` (index pages and the\n * root `404.md` excluded) after the site's own `buildEnd`, so `/page/`\n * answers 200 on an Azure Static Web App instead of 301-ing to the\n * `*.azurestaticapps.net` default host. Default `true`; non-VitePress builds\n * and `vitepress dev` are never touched. An existing `<page>/index.html` with\n * different bytes FAILS the build. See `dcsDirIndex.ts`. On by default\n * because every DCS cleanUrls consumer is an Azure SWA; on another host the\n * twins change what `/page/` serves (README, \"Directory-index twins\"), and\n * `false` keeps the pre-0.13.14 output.\n */\n dirIndex?: boolean\n}\n\n/** Split a `boolean | mode | { mode, allow, … }` option into its parts. */\nfunction readHonestyBlock(\n value: boolean | HonestyMode | SeoHonestyBlock | undefined\n): { mode?: HonestyMode | boolean; allow: string[]; checkDescription?: boolean; network?: boolean } {\n if (value === undefined) return { allow: [] }\n if (typeof value === 'boolean' || typeof value === 'string') return { mode: value, allow: [] }\n return {\n mode: value.mode,\n allow: Array.isArray(value.allow) ? value.allow : [],\n checkDescription: value.checkDescription,\n network: value.network,\n }\n}\n\n/** Resolve the SPA output directory from Vite config (absolute path). */\nfunction resolveOutDir(config: ResolvedConfig): string {\n const out = config.build?.outDir || 'dist'\n return path.isAbsolute(out) ? out : path.resolve(config.root || process.cwd(), out)\n}\n\n/**\n * Load + parse seo.yaml from the usual `.dcs` locations.\n * Returns `{ config, foundPath }` or `null` (missing/unparseable).\n */\nfunction loadSeoConfig(\n projectRoot: string,\n seoPath: string,\n debug: boolean\n): { config: SeoConfiguration; foundPath: string } | null {\n const possiblePaths = [\n path.resolve(projectRoot, seoPath),\n path.resolve(projectRoot, '..', seoPath),\n path.resolve(process.cwd(), seoPath),\n ]\n\n let foundPath: string | undefined\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n foundPath = testPath\n break\n }\n }\n\n if (!foundPath) {\n if (debug) {\n console.log('[dcs-seo] No seo.yaml found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n console.log('[dcs-seo] Using defaults only')\n }\n return null\n }\n\n try {\n const fileContent = fs.readFileSync(foundPath, 'utf8')\n const config = yaml.load(fileContent) as SeoConfiguration\n return { config, foundPath }\n } catch (error) {\n console.warn('[dcs-seo] Failed to parse seo.yaml:', error)\n return null\n }\n}\n\n/**\n * Load + parse `.dcs/content.yaml` from the usual `.dcs` locations. Returns the\n * parsed config or `undefined` (missing/unparseable). Used to thread REAL\n * reviews into the honest Review/aggregateRating builder. Never throws.\n */\nfunction loadContentConfig(\n projectRoot: string,\n contentRelPath: string,\n debug: boolean\n): ContentConfig | undefined {\n const possiblePaths = [\n path.resolve(projectRoot, contentRelPath),\n path.resolve(projectRoot, '..', contentRelPath),\n path.resolve(process.cwd(), contentRelPath),\n ]\n const foundPath = possiblePaths.find((p) => fs.existsSync(p))\n if (!foundPath) {\n if (debug) console.log(`[dcs-seo] No content.yaml found (reviews disabled)`)\n return undefined\n }\n try {\n const parsed = yaml.load(fs.readFileSync(foundPath, 'utf8'))\n if (!parsed || typeof parsed !== 'object') return undefined\n return parsed as ContentConfig\n } catch (error) {\n console.warn('[dcs-seo] Failed to parse content.yaml (reviews disabled):', error)\n return undefined\n }\n}\n\n/** Extract the optional top-level `excluded:` glob list from pages.yaml. */\nfunction loadExcludedGlobs(projectRoot: string, pagesPath: string): string[] {\n const possiblePaths = [\n path.resolve(projectRoot, pagesPath),\n path.resolve(projectRoot, '..', pagesPath),\n path.resolve(process.cwd(), pagesPath),\n ]\n const found = possiblePaths.find((p) => fs.existsSync(p))\n if (!found) return []\n try {\n const raw = yaml.load(fs.readFileSync(found, 'utf8')) as { excluded?: unknown } | null\n const excluded = raw?.excluded\n if (!Array.isArray(excluded)) return []\n return excluded.filter((e): e is string => typeof e === 'string')\n } catch {\n return []\n }\n}\n\n/**\n * Refuse a manifest whose route paths collide after trailing-slash\n * normalization (C-361 F6).\n *\n * ONE OF TWO PLACES THE PLUGIN DELIBERATELY THROWS (the other is\n * {@link assertNoOrphanNoindexEntries}). Everything else in the\n * emit path is defensive by design — a missing or unparseable input warns and\n * no-ops, because a bad input must never break a production build. A duplicate\n * normalized path is a different animal: it is not a missing input, it is an\n * input for which every possible behaviour is wrong. The emitter's last write\n * wins the file on disk; the runtime lookup's first entry wins the head. Picking\n * a side ships a GUARANTEED baked/runtime divergence and calls it success —\n * exactly the silent-wrong-answer class this plan exists to kill — and the two\n * colliding entries have different slugs, so only the owner knows which page\n * that URL is. A red build is the cheap failure here; a green one is not.\n *\n * Thrown from `config()`, so it fails before a single byte is emitted.\n */\nfunction assertNoDuplicateRoutePaths(routes: PageRouteEntry[]): void {\n const dupes = findDuplicateNormalizedPaths(routes)\n if (dupes.length === 0) return\n throw new Error(`[dcs-seo] ${formatDuplicateNormalizedPaths(dupes)}`)\n}\n\n/**\n * Every key a `noindex` entry can legitimately match.\n *\n * The plugin's contract for `noindex` is a PREDICATE OVER THE ROUTE MANIFEST,\n * never a directive about a bare URL. Every consumer asks the question\n * route-first and identically —\n * `noindexSet.has(route.path) || (route.slug && noindexSet.has(route.slug))` —\n * in {@link emitStaticSeoHtml}, in the sitemap/llms `isRouteIndexable`\n * predicate, and in the baked `__DCS_PAGES__` manifest the runtime re-assert\n * reads. So the set of entries that can ever do anything is exactly the union\n * of the manifest's paths and slugs, and this function is the exact inverse of\n * that same relation rather than a second, drifting implementation of it.\n */\nexport function collectNoindexMatchKeys(routes: PageRouteEntry[]): Set<string> {\n const keys = new Set<string>()\n for (const route of routes) {\n if (route.path) keys.add(route.path)\n if (route.slug) keys.add(route.slug)\n }\n return keys\n}\n\n/**\n * `noindex` entries that match no route in the manifest — i.e. entries that\n * are, today, silent no-ops.\n *\n * Matched with the SAME raw string equality the consumers use, deliberately:\n * a `'/account/'` entry against a `'/account'` route does not match in\n * `emitStaticSeoHtml`, so it must not \"match\" here either, or the check would\n * bless the very entry the emitter is about to ignore.\n */\nexport function findOrphanNoindexEntries(\n noindex: string[],\n routes: PageRouteEntry[]\n): string[] {\n const known = collectNoindexMatchKeys(routes)\n const seen = new Set<string>()\n const orphans: string[] = []\n for (const entry of noindex) {\n if (known.has(entry) || seen.has(entry)) continue\n seen.add(entry)\n orphans.push(entry)\n }\n return orphans\n}\n\n/** Thrown when a `noindex` entry names nothing in `pages.yaml` (C-416). */\nexport class NoindexOrphanError extends Error {\n readonly orphans: string[]\n readonly knownKeys: string[]\n constructor(orphans: string[], knownKeys: string[]) {\n super(\n `[dcs-seo] noindex entr${orphans.length === 1 ? 'y' : 'ies'} matching NO page in the ` +\n `route manifest: ${orphans.map((o) => JSON.stringify(o)).join(', ')}. ` +\n `A noindex entry is a predicate over pages.yaml, not a standalone directive: ` +\n `with no matching page NOTHING is emitted for that route, so the entry is a ` +\n `silent no-op and the URL stays \"index, follow\" to crawlers — which is exactly ` +\n `how six homepage-clone URLs on KEPT stayed indexable. ` +\n `Fix it by adding the page to pages.yaml (it then gets a real ` +\n `robots: noindex, nofollow document, sitemap/llms omission, and a runtime ` +\n `re-assert), or by deleting the stale entry. ` +\n `Matchable keys are the manifest's paths and slugs: ` +\n `${knownKeys.map((k) => JSON.stringify(k)).join(', ') || '(manifest is empty)'}`\n )\n this.name = 'NoindexOrphanError'\n this.orphans = orphans\n this.knownKeys = knownKeys\n }\n}\n\n/**\n * Refuse a `noindex` list containing an entry that matches no page (C-416).\n *\n * THE SECOND PLACE THE PLUGIN DELIBERATELY THROWS, and for the same reason as\n * {@link assertNoDuplicateRoutePaths}: this is not a missing input to be\n * defended against, it is an input whose only possible behaviour is wrong.\n *\n * Why a hard error and NOT \"emit a noindex document for it instead\":\n * - An entry is allowed to be a bare SLUG (`'account'`), and a slug carries no\n * URL. Synthesizing a document would mean inventing a path — inventing a\n * crawlable URL to paper over a config typo is strictly worse than the bug\n * being fixed.\n * - Even for the path form, writing `dist/<path>/index.html` for a route the\n * SPA does not have MANUFACTURES a real, fetchable URL that would otherwise\n * never resolve. The remedy would create crawl surface, not remove it.\n * - Adding the page to `pages.yaml` is the operator action that makes the\n * directive real everywhere at once (emitted document + sitemap/llms\n * omission + runtime re-assert). Anything the plugin could synthesize on its\n * own would cover only the first of those three, i.e. a second partial\n * capability with nothing watching — the class this whole rail family exists\n * to kill.\n *\n * There is deliberately NO severity knob / escape hatch (unlike the C-334\n * rails, which measure emitted artifacts and can hit network or environment\n * flake). There is no legitimate orphan: the fix is always \"add the page\" or\n * \"delete the row\", both free.\n *\n * Matched against the FULL manifest, BEFORE `exclude` / `excluded:` globs are\n * applied. A route that is both excluded and noindexed names a real page, and\n * an excluded route publishes no document to be indexable — erroring there\n * would be a false positive that pushes operators to delete honest rows.\n *\n * Thrown from `config()`, so it fails before a single byte is emitted — and,\n * critically, OUTSIDE the `writeBundle` emit try/catch, which downgrades\n * everything it wraps to a `console.warn`. A version of this check placed\n * inside that catch would be vacuously green.\n */\nfunction assertNoOrphanNoindexEntries(noindex: string[], routes: PageRouteEntry[]): void {\n if (noindex.length === 0) return\n const orphans = findOrphanNoindexEntries(noindex, routes)\n if (orphans.length === 0) return\n throw new NoindexOrphanError(orphans, [...collectNoindexMatchKeys(routes)].sort())\n}\n\n/**\n * Core site-file emitter, separated from Vite so it is unit-testable.\n *\n * Writes the site-wide static files into `outDir`, reusing the SAME routes +\n * seoConfig already loaded by the per-route HTML loop (no second manifest read):\n * - `sitemap.xml` (skipped in preview, or when no absolute base is derivable)\n * - `robots.txt` (always; preview = `Disallow: /`; don't-clobber unless force)\n * - `llms.txt` (skipped in preview, or when nothing indexable)\n *\n * Returns the list of relative filenames written. Pure aside from `fs` writes —\n * deterministic + idempotent. Throws only {@link RobotsAiTrainingConflictError}\n * (a hand-authored robots.txt that contradicts `robots.aiTraining: false`),\n * which the plugin's emit catch re-throws so the build fails; nothing else is\n * thrown.\n */\nexport function emitSiteFiles(params: {\n outDir: string\n projectRoot: string\n pagesPath: string\n routes: PageRouteEntry[]\n seoConfig: SeoConfiguration | undefined\n siteUrl?: string\n exclude?: string[]\n noindex?: string[]\n preview?: boolean\n robots?: DcsRobotsOptions\n llms?: boolean\n /**\n * Opt in to git-derived sitemap `<lastmod>` (BEST-EFFORT; default OFF).\n * Without it the factory never infers a date: a URL carries its per-route\n * `.dcs/pages.yaml` `lastmod`, or no `<lastmod>`. The site-level switch is\n * `.dcs/seo.yaml` `sitemap.lastmodFromGit: true`; this option, when set,\n * overrides it for one build. See `deriveRouteLastmods` for what the walk\n * does and does not see.\n */\n gitLastmod?: boolean\n /** Override a route's ENTRY files for the git-derived `<lastmod>` (the content walk still runs). */\n lastmodSources?: (route: PageRouteEntry) => string[] | undefined\n /**\n * `.dcs/content.yaml` path (projectRoot-relative or absolute), used to date\n * each route's own content subtree. Default: searched like pages.yaml.\n */\n contentPath?: string\n /** Injectable git runner (tests only). */\n git?: GitRunner\n debug?: boolean\n}): string[] {\n const {\n outDir,\n projectRoot,\n pagesPath,\n routes,\n seoConfig,\n siteUrl,\n exclude = [],\n noindex = [],\n preview = false,\n robots = {},\n llms = true,\n gitLastmod,\n lastmodSources,\n contentPath,\n git,\n debug = false,\n } = params\n\n const written: string[] = []\n\n const effectiveSiteUrl = siteUrl || seoConfig?.global?.siteUrl\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n // Per-route <lastmod>: the route's own pages.yaml date, else omitted. The\n // factory never infers a date by default (cms 0.14.0). Git-derived dates are\n // a per-site, best-effort opt-in: seo.yaml `sitemap.lastmodFromGit: true`\n // (or the `gitLastmod` option). Never a site-wide `lastUpdated` stamp.\n const gitOptIn = gitLastmod ?? seoConfig?.sitemap?.lastmodFromGit === true\n const routeLastmods =\n !preview && gitOptIn\n ? deriveRouteLastmods({\n routes,\n projectRoot,\n sourcesForRoute: lastmodSources,\n contentPath,\n exclude: Array.isArray(seoConfig?.sitemap?.lastmodExclude)\n ? seoConfig.sitemap.lastmodExclude.filter((g): g is string => typeof g === 'string')\n : [],\n git,\n debug,\n }).lastmods\n : undefined\n\n // ── sitemap.xml (not in preview) ──────────────────────────────────────────\n let wroteSitemap = false\n if (!preview) {\n const xml = buildSitemapXml({\n routes,\n siteUrl: effectiveSiteUrl,\n seoConfig,\n exclude,\n noindex,\n excludedGlobs,\n routeLastmods,\n })\n if (xml) {\n fs.writeFileSync(path.join(outDir, 'sitemap.xml'), xml, 'utf8')\n wroteSitemap = true\n written.push('sitemap.xml')\n if (debug) console.log('[dcs-seo] wrote sitemap.xml')\n } else if (debug) {\n console.log('[dcs-seo] no absolute <loc> derivable; sitemap.xml not written')\n }\n }\n\n // ── robots.txt (always, unless robots.enabled is false) ───────────────────\n // `aiTraining`: an explicit plugin option wins, else `.dcs/seo.yaml`\n // `robots.aiTraining` (portal-owned), else `true` (owner R-Q2 = A).\n const seoAiTraining = seoConfig?.robots?.aiTraining\n const effectiveRobots: DcsRobotsOptions = {\n ...robots,\n aiTraining: robots.aiTraining ?? (typeof seoAiTraining === 'boolean' ? seoAiTraining : true),\n }\n if (robots.enabled ?? true) {\n const robotsPath = path.join(outDir, 'robots.txt')\n // Factory-as-single-source (validated override): a hand-authored\n // public/robots.txt Vite copied into dist is KEPT when it meets the factory\n // floor (`isHandAuthoredRobotsAcceptable`: a real `User-agent: *` group and\n // not an HTML page). A stub (`Sitemap:`-only, like just-posh) or an\n // SPA-shell HTML page fails the floor and is REPLACED with factory robots.\n // `force` always overwrites; an absent file is always written.\n const existing =\n fs.existsSync(robotsPath) && !robots.force ? fs.readFileSync(robotsPath, 'utf8') : null\n const keepHandAuthored = existing !== null && isHandAuthoredRobotsAcceptable(existing)\n if (keepHandAuthored) {\n // A floor-meeting hand-authored robots.txt is not replaced. An\n // `aiTraining: false` opt-out is honoured by APPENDING a `Disallow: /`\n // group for each training bot / control token it does not name; every\n // existing line is preserved. A bot it DOES name must already be exactly\n // `Disallow: /`, else the build fails (never silently keep allowing it).\n if (effectiveRobots.aiTraining === false && !preview) {\n const conflicts = findAiTrainingRobotsConflicts(existing)\n if (conflicts.length > 0) throw new RobotsAiTrainingConflictError(robotsPath, conflicts)\n const { text, added } = appendAiTrainingOptOut(existing)\n if (added.length > 0) {\n fs.writeFileSync(robotsPath, text, 'utf8')\n written.push('robots.txt')\n }\n if (debug) console.log(`[dcs-seo] dist/robots.txt is hand-authored; appended AI training opt-out for ${added.join(', ') || '(none)'}`)\n } else if (debug) {\n console.log('[dcs-seo] dist/robots.txt is hand-authored and meets the floor; leaving it')\n }\n } else {\n const txt = buildRobotsTxt({\n siteUrl: effectiveSiteUrl,\n preview,\n robots: effectiveRobots,\n hasSitemap: wroteSitemap,\n })\n fs.writeFileSync(robotsPath, txt, 'utf8')\n written.push('robots.txt')\n if (debug) {\n console.log(\n existing !== null\n ? '[dcs-seo] dist/robots.txt failed the factory floor; overwrote with emitted robots'\n : '[dcs-seo] wrote robots.txt'\n )\n }\n }\n }\n\n // ── llms.txt (not in preview) ─────────────────────────────────────────────\n if (llms && !preview) {\n const txt = buildLlmsTxt({\n routes,\n siteUrl: effectiveSiteUrl,\n seoConfig,\n exclude,\n noindex,\n excludedGlobs,\n })\n if (txt) {\n fs.writeFileSync(path.join(outDir, 'llms.txt'), txt, 'utf8')\n written.push('llms.txt')\n if (debug) console.log('[dcs-seo] wrote llms.txt')\n } else if (debug) {\n console.log('[dcs-seo] nothing indexable; llms.txt not written')\n }\n }\n\n return written\n}\n\n/**\n * Pick a structured FAQ array (`[{ q, a }]`) for a page from content.yaml, if\n * one exists under a `faq` key (page-scoped, then global). Returns `undefined`\n * when there is no structured Q&A — a `<FaqPage />` component is NOT a source,\n * so its pages correctly yield nothing (honesty).\n */\nfunction pickPageFaq(\n content: ContentConfig | undefined,\n pageSlug: string\n): FaqSource[] | undefined {\n if (!content) return undefined\n const fromBlock = (block: Record<string, unknown> | undefined): FaqSource[] | undefined => {\n if (!block) return undefined\n const v = block['faq']\n return Array.isArray(v) ? (v as FaqSource[]) : undefined\n }\n return fromBlock(content.pages?.[pageSlug]) ?? fromBlock(content.global)\n}\n\n/**\n * Core emitter, separated from Vite so it is unit-testable.\n *\n * For each route: build the head tags from the shared resolver, splice them\n * into the shell HTML, and write `dist/<path>/index.html`. Returns the number\n * of files written. Pure aside from `fs` writes — deterministic + idempotent.\n */\nexport function emitStaticSeoHtml(params: {\n outDir: string\n shellHtml: string\n routes: PageRouteEntry[]\n seoConfig: SeoConfiguration | undefined\n /**\n * Parsed `.dcs/content.yaml` — threads REAL review items (honesty-gated) into\n * the per-route LocalBusiness node. Optional; omit ⇒ no Review/aggregateRating.\n */\n contentConfig?: ContentConfig\n exclude?: string[]\n noindex?: string[]\n /** `pages.yaml` top-level `excluded:` globs — routes matching are NOT emitted. */\n excludedGlobs?: string[]\n debug?: boolean\n}): number {\n const {\n outDir,\n shellHtml,\n routes,\n seoConfig,\n contentConfig,\n exclude = [],\n noindex = [],\n excludedGlobs = [],\n debug = false,\n } = params\n\n const noindexSet = new Set(noindex)\n\n // Route → human title map (for breadcrumb hop labels), from the manifest.\n const siteUrl = seoConfig?.global?.siteUrl ?? ''\n const routeTitles: Record<string, string> = { '/': 'Home' }\n for (const r of routes) {\n if (r.title && r.path) routeTitles[r.path.replace(/\\/+$/, '') || '/'] = r.title\n }\n\n let written = 0\n for (const route of routes) {\n // Exclusion goes through the SHARED predicate (`routeExclusionReason`), the\n // same one that filters the `__DCS_PAGES__` runtime manifest. Two agreeing\n // implementations is how a private `/dev-*` route came to be never-baked but\n // still runtime-asserted (C-361 F5); one predicate is why it cannot recur.\n // An excluded route must NOT get a per-route index.html, or it becomes a\n // crawlable/indexable page despite being intentionally hidden — a privacy\n // and crawl-budget leak. Same glob semantics as the sitemap path.\n const exclusion = routeExclusionReason(route, { exclude, excludedGlobs })\n if (exclusion) {\n if (debug) {\n console.log(\n `[dcs-seo] skip (${exclusion === 'excluded-glob' ? 'excluded glob' : 'excluded'}): ${route.path}`\n )\n }\n continue\n }\n\n const forceNoindex =\n noindexSet.has(route.path) || (route.slug && noindexSet.has(route.slug))\n\n // Breadcrumb trail from route depth (home ⇒ none); titles from the manifest.\n const breadcrumbTrail = siteUrl\n ? breadcrumbTrailFromRoute(route.path, siteUrl, routeTitles)\n : undefined\n\n // REAL reviews for this page from content.yaml (honesty-gated downstream).\n const reviews: ReviewSource[] | undefined = contentConfig\n ? findReviewItemsForPage(contentConfig, route.slug)\n : undefined\n\n // Trade/occupational license from content.yaml `business.license` (dark when\n // the key is empty/absent — no hasCredential is emitted). Honesty-gated in\n // buildHasCredential downstream.\n const license: string | undefined = contentConfig\n ? findBusinessLicense(contentConfig, route.slug)\n : undefined\n\n // BlogPosting for a blog post route — only when seo.yaml has NOT already\n // hand-authored one (buildHeadTags skips ours if it has). A blog post is a\n // route nested under `/blog/` (depth ≥ 2) with a manifest title.\n const isBlogPost = /^\\/blog\\/.+/.test(route.path) && !!route.title\n const blogMeta: BlogMeta | undefined = isBlogPost\n ? { headline: route.title, url: breadcrumbTrail?.[breadcrumbTrail.length - 1]?.item }\n : undefined\n\n // FAQ from a structured `.dcs/faq.yaml`-style block on the content page, if\n // present (honesty-gated). Component-only FAQ pages carry no such data.\n const faq: FaqSource[] | undefined = pickPageFaq(contentConfig, route.slug)\n\n const tags = buildHeadTags(route.slug, route.path, seoConfig, {\n includeKeywords: true,\n fallbackTitle: route.title,\n robots: forceNoindex ? 'noindex, nofollow' : undefined,\n emitGraph: true,\n breadcrumbTrail,\n reviews,\n license,\n blogMeta,\n faq,\n })\n\n const html = spliceHeadHtml(shellHtml, tags)\n const outFile = routeToOutputFile(outDir, route.path)\n\n fs.mkdirSync(path.dirname(outFile), { recursive: true })\n fs.writeFileSync(outFile, html, 'utf8')\n written++\n\n if (debug) {\n console.log(\n `[dcs-seo] wrote ${path.relative(outDir, outFile)} (title=\"${tags.title}\"${\n forceNoindex ? ', noindex' : ''\n })`\n )\n }\n }\n\n return written\n}\n\n/**\n * What the render pass produced, INCLUDING whether it ran at all. The\n * `rendererAvailable` / `eligibleRoutes` fields are what make the P1 rail\n * provably executed rather than silently skipped (C-338).\n */\ninterface BodyPrerenderOutcome {\n rendererAvailable: boolean\n headObservations: HeadObservation[]\n eligibleRoutes: string[]\n filteredRoutes: Array<{ route: string; reason: string }>\n}\n\n/**\n * Run the body-prerender pass: bring up the headless renderer, fill each\n * indexable route's `<div id=\"app\">` with its real rendered DOM, then tear the\n * renderer down. Missing infra (no playwright / no browser) makes the BODY pass\n * a no-op but is reported back so the P1 rail can fail loud instead of passing\n * green having checked nothing; a render crash propagates a `BodyPrerenderError`.\n */\nasync function runBodyPrerender(\n ctx: { outDir: string; routes: PageRouteEntry[]; excludedGlobs: string[] },\n opts: {\n exclude: string[]\n noindex: string[]\n debug: boolean\n /** `false` ⇒ render for OBSERVATION only (P1) and leave `dist/` untouched. */\n spliceBody: boolean\n }\n): Promise<BodyPrerenderOutcome> {\n // Kill-test hook (C-338): forces the renderer-absent path so the P1 execution\n // assertion can be proven to FAIL a build. NOT an escape hatch — with the\n // assertion in place, setting this in `error` mode turns the build RED.\n const forcedAbsent = process.env.DCS_SEO_FORCE_NO_RENDERER === '1'\n if (forcedAbsent) {\n console.warn(\n '[dcs-seo] DCS_SEO_FORCE_NO_RENDERER=1 — pretending the headless renderer is absent ' +\n '(kill-test hook; in error mode this MUST fail the build).'\n )\n }\n const handle = forcedAbsent\n ? null\n : await createPlaywrightRenderer({ outDir: ctx.outDir, debug: opts.debug })\n if (!handle) {\n // playwright/browser unavailable. Say so explicitly — without a renderer the\n // P1 head-honesty rail cannot run either, and a rail that silently does not\n // run is the exact class this work exists to close. The CALLER turns this\n // into a hard failure in `error` mode (see `assertHeadHonestyExecuted`).\n console.warn(\n '[dcs-seo] no headless renderer available: body prerender AND the P1 ' +\n 'baked-vs-rendered <head> assert were both SKIPPED for this build.'\n )\n return {\n rendererAvailable: false,\n headObservations: [],\n eligibleRoutes: [],\n filteredRoutes: [],\n }\n }\n\n console.log(\n opts.spliceBody\n ? '[dcs-seo] body-prerender: rendering routes via headless Chromium…'\n : '[dcs-seo] head-honesty: rendering routes via headless Chromium (observe-only)…'\n )\n try {\n const result = await prerenderBodies({\n outDir: ctx.outDir,\n routes: ctx.routes,\n renderer: handle.renderer,\n exclude: opts.exclude,\n noindex: opts.noindex,\n excludedGlobs: ctx.excludedGlobs,\n spliceBody: opts.spliceBody,\n debug: opts.debug,\n })\n if (opts.spliceBody) {\n console.log(\n `[dcs-seo] body-prerender: ${result.prerendered} route(s) now have ` +\n `crawler-visible body content (${result.skipped} skipped)`\n )\n }\n return {\n rendererAvailable: true,\n headObservations: result.headObservations,\n eligibleRoutes: result.eligibleRoutes,\n filteredRoutes: result.filteredRoutes,\n }\n } finally {\n await handle.close()\n }\n}\n\n/**\n * P2 — collect every URL the just-completed emit published and assert it\n * resolves to what it promises.\n *\n * Deliberately two-phase, because the two halves have different reliability:\n * the same-origin half is proven against `dist/` with no network and is\n * therefore a hard gate; the cross-origin half asks the network and only fails\n * on a definitive wrong answer. See `emittedUrls.ts` for the verdict table.\n */\nasync function runEmittedUrlHonesty(params: {\n outDir: string\n projectRoot: string\n routes: PageRouteEntry[]\n siteUrl: string | undefined\n base: string\n mode: HonestyMode\n allow: string[]\n network: boolean\n debug: boolean\n /** Receives the audit BEFORE any throw, so the report survives a red build. */\n sink?: (audit: EmittedUrlAudit, violations: EmittedUrlViolation[]) => void\n}): Promise<EmittedUrlAudit | null> {\n const { outDir, projectRoot, routes, siteUrl, base, mode, allow, network, debug, sink } = params\n if (mode === 'off') {\n console.warn(\n '[dcs-seo] emitted-URL honesty is OFF for this build — nothing is checking that the ' +\n 'logo/og:image/sitemap URLs this site publishes actually resolve.'\n )\n return null\n }\n if (allow.length > 0) {\n console.warn(\n `[dcs-seo] emitted-URL honesty: ${allow.length} URL(s) EXEMPTED: ${allow.join(', ')}`\n )\n }\n\n const files: Array<{ path: string; from: string; kind: 'html' | 'sitemap' | 'llms' }> = []\n for (const route of routes) {\n files.push({ path: routeToOutputFile(outDir, route.path), from: route.path, kind: 'html' })\n }\n files.push({ path: path.join(outDir, 'sitemap.xml'), from: 'sitemap.xml', kind: 'sitemap' })\n files.push({ path: path.join(outDir, 'llms.txt'), from: 'llms.txt', kind: 'llms' })\n\n const collected = dedupeUrls(collectEmittedUrlsFromFiles(files))\n const classified: ClassifiedUrl[] = collected.map((u) => classifyUrl(u, siteUrl))\n\n const sameOrigin = auditSameOriginAssets({ urls: classified, outDir, base, allow })\n const violations: EmittedUrlViolation[] = [...sameOrigin.violations]\n\n // Every count below comes from the CHECKER, never from `classified.length` —\n // that conflation is what let C-334's log claim page URLs were verified when\n // both checkers only ever look at assets (C-338).\n const audit: EmittedUrlAudit = {\n collected: classified.length,\n sameOriginAssetsChecked: sameOrigin.checked,\n remoteAssetsChecked: 0,\n remoteProbed: 0,\n remoteCached: 0,\n unknown: 0,\n pagesUnverified: classified.filter((u) => u.expectation === 'page').length,\n unfetchable: classified.filter((u) => u.locality === 'unfetchable').length,\n exempted: sameOrigin.exempted,\n failed: 0,\n }\n\n if (network) {\n const remote = await checkRemoteAssets(classified, { projectRoot, allow, debug })\n violations.push(...remote.violations)\n for (const w of remote.warnings) {\n console.warn(`[dcs-seo] emitted-URL honesty (UNKNOWN, not a failure): ${w.url} — ${w.reason}`)\n }\n audit.remoteAssetsChecked = remote.checked ?? 0\n audit.remoteProbed = remote.probed\n audit.remoteCached = remote.cached\n audit.unknown = remote.warnings.length\n audit.exempted += remote.exempted ?? 0\n if (debug) {\n console.log(\n `[dcs-seo] emitted-URL honesty: remote probes — ${remote.probed} network, ${remote.cached} cached`\n )\n }\n } else {\n // Probing off ⇒ every remote asset is UNKNOWN. It must not be silently\n // absorbed into a \"verified\" total.\n audit.unknown = classified.filter(\n (u) => u.locality === 'remote' && u.expectation === 'asset'\n ).length\n console.log(\n '[dcs-seo] emitted-URL honesty: cross-origin probes disabled — ' +\n `${audit.unknown} remote asset URL(s) are UNCHECKED this build; same-origin still enforced`\n )\n }\n\n audit.failed = violations.length\n sink?.(audit, violations)\n const checkedTotal = auditCheckedTotal(audit)\n\n // Execution assertion: collecting nothing means the rail did not run. In\n // `error` mode that is a hard failure, not a green build.\n if (audit.collected === 0) {\n const err = new EmittedUrlNotRunError(\n audit,\n `0 URLs were collected from ${files.length} emitted artifact(s)`\n )\n if (mode === 'error') throw err\n console.warn(err.message)\n console.warn('[dcs-seo] emitted-URL honesty is in WARN mode; this build is NOT gated on the above.')\n return audit\n }\n // Collected-but-checked-nothing is legal (a site can publish only page URLs)\n // but must never read as a pass. Say it in every mode.\n if (checkedTotal === 0) {\n console.warn(\n `[dcs-seo] emitted-URL honesty VERIFIED NOTHING this build: ${audit.collected} URL(s) were ` +\n `collected but none was a checkable asset (${audit.pagesUnverified} page(s), ` +\n `${audit.unknown} unknown, ${audit.exempted} exempted, ${audit.unfetchable} unfetchable).`\n )\n }\n\n if (violations.length === 0) {\n console.log(formatEmittedUrlAudit(audit, routes.length))\n return audit\n }\n\n if (mode === 'warn') {\n console.warn(formatEmittedUrlReport(violations))\n console.warn(formatEmittedUrlAudit(audit, routes.length))\n console.warn('[dcs-seo] emitted-URL honesty is in WARN mode; this build is NOT gated on the above.')\n return audit\n }\n throw new EmittedUrlError(violations)\n}\n\n/**\n * P12 — assert the encoding declaration lands inside the 1024-byte sniffing\n * window in every emitted document.\n *\n * The hoist in `emitStaticSeoHtml`'s shell should make this unfailable; the\n * assert exists so that if the hoist is ever bypassed (a new head injector, a\n * post-processing plugin that runs later, a hand-rolled shell), the build says so\n * instead of shipping a document whose encoding is a coin flip.\n */\nfunction runCharsetBudget(params: {\n outDir: string\n routes: PageRouteEntry[]\n mode: HonestyMode\n debug: boolean\n /** Receives the counts BEFORE any throw, so the report survives a red build. */\n sink?: (summary: { checked: number; failed: number; worstOffset: number }) => void\n}): void {\n const { outDir, routes, mode, debug, sink } = params\n if (mode === 'off') return\n\n const checked: string[] = []\n let failed = 0\n let worstOffset = 0\n const emit = () => sink?.({ checked: checked.length, failed, worstOffset })\n for (const route of routes) {\n const file = routeToOutputFile(outDir, route.path)\n let html: string\n try {\n html = fs.readFileSync(file, 'utf8')\n } catch {\n continue\n }\n const rel = path.relative(outDir, file)\n const result = checkCharsetBudget(html)\n worstOffset = Math.max(worstOffset, result.offset)\n if (!result.ok) {\n failed += 1\n if (mode === 'warn') {\n console.warn(new CharsetBudgetError(rel, result).message)\n continue\n }\n emit()\n throw new CharsetBudgetError(rel, result)\n }\n const warning = formatCharsetHeadroomWarning(rel, result)\n if (warning) console.warn(warning)\n checked.push(rel)\n }\n emit()\n if (debug || checked.length > 0) {\n console.log(\n `[dcs-seo] charset budget: ${checked.length} emitted document(s) declare their encoding ` +\n `inside the first 1024 bytes`\n )\n }\n}\n\n/**\n * Vite plugin that injects .dcs/seo.yaml at build time and, optionally, emits\n * per-route static `<head>` HTML for SPA SEO.\n *\n * @param options - Plugin configuration\n * @returns Vite plugin\n */\nexport function dcsSeoPlugin(options: DcsSeoPluginOptions = {}): Plugin {\n const {\n seoPath = '.dcs/seo.yaml',\n debug = false,\n emitStaticHtml = false,\n prerenderBody,\n pagesPath = '.dcs/pages.yaml',\n contentPath = '.dcs/content.yaml',\n exclude = [],\n noindex = [],\n // Site files default ON whenever per-route HTML emission is on, so the\n // sites already using emitStaticHtml gain sitemap/robots/llms with no edit.\n emitSiteFiles: emitSiteFilesOpt = emitStaticHtml,\n siteUrl,\n headHonesty: headHonestyOpt,\n urlHonesty: urlHonestyOpt,\n charsetBudget: charsetBudgetOpt,\n robots = {},\n // Self-detect preview builds from DCS_PREVIEW (mirrors dcsEditorPlugin) so a\n // release/** SWA preview build never body-prerenders; an explicit option wins.\n preview = process.env.DCS_PREVIEW === 'true',\n llms = true,\n gitLastmod,\n lastmodSources,\n dirIndex = true,\n } = options\n\n let resolvedConfig: ResolvedConfig\n // Captured during configResolved — gates the serve-only inline HTML inject.\n let isDev = false\n\n return {\n name: 'dcs-seo',\n\n configResolved(config) {\n resolvedConfig = config\n isDev = config.command === 'serve'\n // C-1965: VitePress exposes its resolved SiteConfig as `config.vitepress`\n // (the same object for the client and the SSR resolution). Installing is\n // guarded on that object, so the second resolution is a no-op.\n if (config.command === 'build') {\n const siteConfig = (config as ResolvedConfig & { vitepress?: unknown }).vitepress\n if (isVitePressSiteConfig(siteConfig)) {\n // dirIndex:false: the emitter is off, so a manifest an earlier build\n // left at DCS_DIR_INDEX_MANIFEST must not survive to vouch for this\n // dist (removed here, before any buildEnd can write one).\n if (dirIndex !== false) installDirIndex(siteConfig)\n else clearDirIndexManifest()\n }\n }\n },\n\n config(config, env) {\n // ── Dev / preview (serve) ──────────────────────────────────────────────\n // Don't bake seo.yaml into the bundle. Redirect the `__DCS_SEO__` define\n // to a browser global that `transformIndexHtml` (below) refreshes from\n // disk on every HTML request — live preview with NO server.restart().\n // The consumer is untouched: it still reads the bare `__DCS_SEO__`\n // identifier, which this define rewrites to `globalThis.__DCS_SEO__`.\n // (VitePress treats `useSEO` as a no-op and bakes SEO via\n // transformPageData, so this only affects the runtime `useSEO` SPA path.)\n if (env.command === 'serve') {\n return {\n define: {\n __DCS_SEO__: 'globalThis.__DCS_SEO__',\n __DCS_PAGES__: 'globalThis.__DCS_PAGES__',\n },\n }\n }\n\n // ── Production build ───────────────────────────────────────────────────\n // Unchanged: read seo.yaml now and bake it into the bundle as a literal.\n const projectRoot = config.root || process.cwd()\n\n // The ROUTE MANIFEST for the runtime re-assert (`installSeoHead`).\n //\n // It is baked here — not read from `pages.yaml` at runtime — so the router\n // hook resolves against the SAME map the build-time emitter walked. The\n // `noindex` list rides along because it is a plugin OPTION, not a file:\n // without it the runtime cannot know a route was baked `noindex, nofollow`\n // and would republish `index, follow` over it (measured live on iron-oak\n // /account and /projects, C-357).\n //\n // Emitted unconditionally, independent of the seo.yaml branch below —\n // `installSeoHead` needs it in BOTH cases, and a bare `__DCS_PAGES__`\n // identifier with no define is a ReferenceError in a consumer bundle.\n // IT MODELS WHAT THE EMITTER WRITES, NOT WHAT pages.yaml DECLARES\n // (C-361 F5). Routes the emitter SKIPS — `exclude` entries and `excluded:`\n // globs — are omitted here too, through the SAME `routeExclusionReason`\n // predicate the emit loop calls. Without that filter a private `/dev-*`\n // route was never baked (correct) yet still runtime-asserted with a\n // canonical and `index, follow` on the first in-app navigation (wrong):\n // the manifest promised the runtime a page the build had deliberately\n // refused to publish. Omitting is chosen over carrying exclude semantics\n // into the browser because it needs no glob engine at runtime and cannot\n // disagree with the emitter by construction.\n const pagesDefine = ((): string => {\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (!routes) {\n // No manifest ⇒ no per-route emission and no runtime manifest, so a\n // noindex list here is inert everywhere. Not a hard failure (the\n // missing manifest is its own, already-warned condition), but say so\n // rather than let the operator believe the directive landed.\n if (noindex.length > 0) {\n console.warn(\n `[dcs-seo] noindex has ${noindex.length} entr${noindex.length === 1 ? 'y' : 'ies'} ` +\n `but ${pagesPath} is missing or empty — the list matches nothing and is inert.`\n )\n }\n return 'undefined'\n }\n // C-416: a noindex entry naming no page emits NO document, so the\n // directive silently does nothing and the URL stays crawlable. Checked\n // against the FULL manifest, before exclusion, and thrown from here so\n // it cannot be swallowed by the writeBundle emit try/catch.\n assertNoOrphanNoindexEntries(noindex, routes)\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n const emitted = routes.filter((r) =>\n isRouteEmitted(r, { exclude, excludedGlobs })\n )\n assertNoDuplicateRoutePaths(emitted)\n return JSON.stringify({\n routes: emitted.map((r) => ({\n slug: r.slug,\n path: r.path,\n ...(r.title ? { title: r.title } : {}),\n })),\n noindex,\n })\n })()\n\n const loaded = loadSeoConfig(projectRoot, seoPath, debug)\n if (!loaded) {\n return {\n define: {\n __DCS_SEO__: 'undefined',\n __DCS_PAGES__: pagesDefine,\n },\n }\n }\n\n if (debug) {\n console.log(`[dcs-seo] Loaded ${loaded.foundPath}`)\n console.log(`[dcs-seo] Version: ${loaded.config.version}`)\n console.log(`[dcs-seo] Site Name: ${loaded.config.global?.siteName || '(not set)'}`)\n console.log(\n `[dcs-seo] Pages: ${Object.keys(loaded.config.pages ?? {}).join(', ') || '(none)'}`\n )\n }\n\n return {\n define: {\n __DCS_SEO__: JSON.stringify(loaded.config),\n __DCS_PAGES__: pagesDefine,\n },\n }\n },\n\n /**\n * Build-time static `<head>` emitter (opt-in via `emitStaticHtml`).\n *\n * Runs after the bundle is written so the built `index.html` shell exists\n * on disk. For an SPA, Vite emits a single `index.html`; we fan it out to\n * per-route files with route-specific `<head>` content.\n *\n * Fully defensive: any missing/unparseable input logs a warning and\n * no-ops. Never throws (so it can never break a production build).\n */\n async writeBundle() {\n if (!emitStaticHtml) {\n // The whole emit path is gated on emitStaticHtml. If the operator\n // explicitly asked for site files (`emitSiteFiles: true`) while\n // emitStaticHtml is off, that request is silently inert — warn so it's\n // not mistaken for \"robots/sitemap were emitted\".\n if (options.emitSiteFiles === true) {\n console.warn(\n '[dcs-seo] emitSiteFiles:true is ignored because emitStaticHtml is false; ' +\n 'set emitStaticHtml:true to emit sitemap.xml/robots.txt/llms.txt'\n )\n }\n return\n }\n\n // Captured inside the never-break emit below, consumed by the separately\n // guarded body-prerender step after it (so a fabrication/crash there can\n // fail the build loud instead of being swallowed by the emit try/catch).\n let bodyPrerenderCtx:\n | { outDir: string; routes: PageRouteEntry[]; excludedGlobs: string[] }\n | null = null\n\n /** P12 shell measurement (before/after the charset hoist), for the report. */\n let charsetShell: {\n hoisted: boolean\n beforeOffset: number\n beforeHeadroom: number\n beforeOk: boolean\n afterOffset: number\n afterHeadroom: number\n afterOk: boolean\n } | null = null\n\n // Same pattern for the C-334 honesty rails: gathered inside the\n // never-break emit, EXECUTED outside it. An emitter that fails is a\n // degraded build; a rail that fails is a build that must go red — so the\n // rails must not be swallowed by the emitter's defensive catch. (That\n // swallow is precisely how a check becomes vacuously green.)\n let honestyCtx:\n | {\n outDir: string\n projectRoot: string\n routes: PageRouteEntry[]\n siteUrl: string | undefined\n base: string\n headMode: HonestyMode\n headAllow: string[]\n headCheckDescription: boolean\n urlMode: HonestyMode\n urlAllow: string[]\n urlNetwork: boolean\n charsetMode: HonestyMode\n /** `true` when the render pass runs only to feed the P1 rail. */\n renderForHonestyOnly: boolean\n }\n | null = null\n\n try {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const outDir = resolveOutDir(resolvedConfig)\n\n if (!fs.existsSync(outDir)) {\n console.warn(`[dcs-seo] emitStaticHtml: outDir not found (${outDir}); skipping`)\n return\n }\n\n const shellPath = path.join(outDir, 'index.html')\n if (!fs.existsSync(shellPath)) {\n console.warn(\n `[dcs-seo] emitStaticHtml: no index.html in ${outDir}; nothing to emit`\n )\n return\n }\n\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (!routes) {\n console.warn(\n `[dcs-seo] emitStaticHtml: ${pagesPath} missing or empty; skipping per-route emission`\n )\n return\n }\n\n const loaded = loadSeoConfig(projectRoot, seoPath, debug)\n if (!loaded) {\n // seo.yaml is optional for emission — routes still get baked with\n // global/runtime defaults (which here means just the shell title and\n // a derived canonical-less head). Warn so the operator knows.\n console.warn(\n `[dcs-seo] emitStaticHtml: ${seoPath} missing or unparseable; emitting with defaults only`\n )\n }\n\n // ── P12: hoist <meta charset> before anything is fanned out ─────────\n // The motion-token <style> is injected `head-prepend`, which lands it\n // ABOVE the site's own <meta charset> and pushes the encoding\n // declaration to byte ~910 of the spec's 1024-byte sniffing window\n // (measured identical on two fleet sites, 2026-07-26). Fixing the SHELL\n // fixes every per-route file the loop below writes from it, in one place,\n // with no per-site edit. `hoistCharsetMeta` is idempotent, so a shell\n // that is already correct is untouched.\n const rawShellHtml = fs.readFileSync(shellPath, 'utf8')\n const shellHtml = hoistCharsetMeta(rawShellHtml)\n // Recorded for the honesty report: the BEFORE/AFTER byte offsets are the\n // P12 measurement the fleet matrix asks for, per site.\n {\n const b = checkCharsetBudget(rawShellHtml)\n const a = checkCharsetBudget(shellHtml)\n charsetShell = {\n hoisted: shellHtml !== rawShellHtml,\n beforeOffset: b.offset,\n beforeHeadroom: b.headroom,\n beforeOk: b.ok,\n afterOffset: a.offset,\n afterHeadroom: a.headroom,\n afterOk: a.ok,\n }\n }\n if (shellHtml !== rawShellHtml) {\n // Write it back too: `dist/index.html` is what the host serves as the\n // SPA fallback for every unmatched path, and a route manifest without\n // `/` would otherwise leave the shell un-hoisted.\n fs.writeFileSync(shellPath, shellHtml, 'utf8')\n const before = checkCharsetBudget(rawShellHtml)\n const after = checkCharsetBudget(shellHtml)\n console.log(\n `[dcs-seo] charset budget: hoisted <meta charset> from byte ${before.offset} ` +\n `to byte ${after.offset} (${after.headroom} bytes of the 1024-byte ` +\n `encoding-sniffing window now free)`\n )\n }\n\n // pages.yaml top-level `excluded:` globs gate BOTH the per-route HTML\n // emission below and the sitemap/llms set inside emitSiteFiles, so an\n // excluded route is never written as a crawlable index.html.\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n // Optional: load content.yaml so REAL reviews can feed the honest\n // Review/aggregateRating on the per-route LocalBusiness node. Absent or\n // unparseable ⇒ undefined ⇒ no reviews emitted (no synthesis).\n const contentConfig = loadContentConfig(projectRoot, contentPath, debug)\n\n // C-1260 finding 3 — a LocalBusiness `address` that is PRESENT BUT\n // PARTIAL is spread verbatim into the @graph by `buildGlobalGraph`, so\n // it reaches crawlers looking finished. WARN only: the emitted shape is\n // deliberately unchanged (removing a half-address would silently drop\n // authored data), and an ABSENT address is never reported because a\n // service-area business is supposed to omit it.\n const addressGaps = findPostalAddressGaps(loaded?.config?.global ?? {})\n if (addressGaps.length > 0) {\n console.warn(formatPostalAddressGapReport(addressGaps))\n }\n\n const written = emitStaticSeoHtml({\n outDir,\n shellHtml,\n routes,\n seoConfig: loaded?.config,\n contentConfig,\n exclude,\n noindex,\n excludedGlobs,\n debug,\n })\n\n if (debug) {\n console.log(`[dcs-seo] emitStaticHtml: wrote ${written} per-route HTML file(s)`)\n }\n\n // ── site-wide static files (sitemap.xml, robots.txt, llms.txt) ──────\n // Emitted AFTER the per-route HTML loop so canonicals/routes are\n // resolved and the shell exists. Reuses the already-loaded routes +\n // seoConfig (no second manifest read). Same outDir/existsSync guard +\n // the outer try/catch — so it can never break a production build.\n if (emitSiteFilesOpt) {\n const siteFiles = emitSiteFiles({\n outDir,\n projectRoot,\n pagesPath,\n routes,\n seoConfig: loaded?.config,\n siteUrl,\n exclude,\n noindex,\n preview,\n robots,\n llms,\n gitLastmod,\n lastmodSources,\n contentPath,\n debug,\n })\n if (debug) {\n console.log(\n `[dcs-seo] emitSiteFiles: wrote ${siteFiles.length} site file(s): ${\n siteFiles.join(', ') || '(none)'\n }`\n )\n }\n }\n\n // Body prerender runs only when enabled for this build (default ON when\n // emitting; off via the `prerenderBody` option, the seo.yaml escape\n // hatch, or preview mode). Stash what it needs so it executes under its\n // own fail-loud guard below, NOT this swallow-catch.\n // Extra guard: the prerender server serves the built assets from root,\n // so a non-root `base` (subpath preview deploys like /kept/) would 404\n // every asset → the app never mounts → a spurious build failure. Skip\n // (loudly) rather than fail — head + JSON-LD are already emitted.\n const buildBase = resolvedConfig?.base ?? '/'\n const baseIsRoot = buildBase === '/' || buildBase === './' || buildBase === ''\n const bodyPrerenderOn = isBodyPrerenderEnabled({\n emitStaticHtml,\n prerenderBodyOption: prerenderBody,\n preview,\n seoPrerenderBody: loaded?.config?.prerenderBody,\n })\n if (bodyPrerenderOn) {\n if (baseIsRoot) {\n bodyPrerenderCtx = { outDir, routes, excludedGlobs }\n } else {\n console.warn(\n `[dcs-seo] body prerender skipped: non-root base \"${buildBase}\" ` +\n '(assets would not resolve through the prerender server; head + JSON-LD still emitted)',\n )\n }\n }\n\n // ── C-334 honesty rails: resolve severities, stash the context ───────\n // Resolution order is env > seo.yaml > plugin option > default `error`,\n // so the most operator-visible signal wins and a lowered gate always\n // shows up either in git (seo.yaml) or in the build log (env).\n // `*OptBlock` = the vite.config option; `seo*Block` = the .dcs/seo.yaml\n // escape hatch. Kept in matching pairs so the precedence below reads at a\n // glance and a future edit cannot silently swap the two sources.\n const headOptBlock = readHonestyBlock(headHonestyOpt)\n const urlOptBlock = readHonestyBlock(urlHonestyOpt)\n const charsetOptBlock = readHonestyBlock(charsetBudgetOpt)\n const seoHeadBlock = readHonestyBlock(loaded?.config?.headHonesty ?? undefined)\n const seoUrlBlock = readHonestyBlock(loaded?.config?.urlHonesty ?? undefined)\n const seoCharsetBlock = readHonestyBlock(loaded?.config?.charsetBudget ?? undefined)\n\n const headMode = resolveHonestyMode({\n env: process.env.DCS_SEO_HEAD_HONESTY,\n seoYaml: seoHeadBlock.mode,\n option: headOptBlock.mode,\n fallback: 'error',\n })\n const urlMode = resolveHonestyMode({\n env: process.env.DCS_SEO_URL_HONESTY,\n seoYaml: seoUrlBlock.mode,\n option: urlOptBlock.mode,\n fallback: 'error',\n })\n const charsetMode = resolveHonestyMode({\n env: process.env.DCS_SEO_CHARSET_BUDGET,\n seoYaml: seoCharsetBlock.mode,\n option: charsetOptBlock.mode,\n fallback: 'error',\n })\n\n // The P1 rail needs a render. If body prerender is already running, it\n // rides along for free; if the site opted out of body prerender we still\n // render — in OBSERVE-ONLY mode, so `dist/` is untouched — because the\n // alternative is a gate that quietly does not exist on that site.\n const renderForHonestyOnly = !bodyPrerenderOn && headMode !== 'off' && baseIsRoot\n if (renderForHonestyOnly) {\n bodyPrerenderCtx = { outDir, routes, excludedGlobs }\n }\n if (headMode !== 'off' && !baseIsRoot) {\n console.warn(\n `[dcs-seo] head honesty SKIPPED: non-root base \"${buildBase}\" (the prerender ` +\n 'server cannot serve this build, so the rendered <head> cannot be observed)'\n )\n }\n\n honestyCtx = {\n outDir,\n projectRoot,\n routes,\n siteUrl: siteUrl || loaded?.config?.global?.siteUrl,\n base: buildBase,\n headMode: baseIsRoot ? headMode : 'off',\n headAllow: [...headOptBlock.allow, ...seoHeadBlock.allow],\n headCheckDescription:\n seoHeadBlock.checkDescription ?? headOptBlock.checkDescription ?? true,\n urlMode,\n urlAllow: [...urlOptBlock.allow, ...seoUrlBlock.allow],\n urlNetwork:\n process.env.DCS_SEO_URL_HONESTY_NETWORK?.toLowerCase() === 'off'\n ? false\n : (seoUrlBlock.network ?? urlOptBlock.network ?? true),\n charsetMode,\n renderForHonestyOnly,\n }\n } catch (error) {\n // A robots.txt that contradicts `robots.aiTraining: false` is a policy\n // conflict the site must resolve: it fails the build (never swallowed).\n if (error instanceof RobotsAiTrainingConflictError) throw error\n // Never break the build on any other SEO emission failure.\n console.warn('[dcs-seo] emitStaticHtml failed; build output left unchanged:', error)\n }\n\n // ── Body prerender + P1 (SEPARATE guard — fail loud) ─────────────────────\n // Deliberately OUTSIDE the swallow-catch above: missing infra (no\n // playwright / no browser) degrades gracefully to a no-op, but a route that\n // crashes or would ship broken content throws BodyPrerenderError and FAILS\n // the build. Head + JSON-LD are already on disk regardless.\n let headObservations: HeadObservation[] = []\n // Execution facts for the P1 assertion below. `rendererAvailable` starts\n // FALSE: if the render pass never ran, the rail must say so rather than\n // inherit an optimistic default.\n let rendererAvailable = false\n let eligibleRoutes: string[] = []\n let filteredRoutes: Array<{ route: string; reason: string }> = []\n if (bodyPrerenderCtx) {\n const outcome = await runBodyPrerender(bodyPrerenderCtx, {\n exclude,\n noindex,\n debug,\n spliceBody: !(honestyCtx?.renderForHonestyOnly ?? false),\n })\n headObservations = outcome.headObservations\n rendererAvailable = outcome.rendererAvailable\n eligibleRoutes = outcome.eligibleRoutes\n filteredRoutes = outcome.filteredRoutes\n }\n\n if (honestyCtx) {\n const ctx = honestyCtx\n // Machine-readable execution record (C-338). Written only when\n // DCS_SEO_HONESTY_REPORT names a path, so normal builds are untouched;\n // the fleet candidate-matrix harness sets it and reads counts from JSON\n // instead of scraping the build log. Written in a `finally` so a RED\n // build still leaves its measurement behind.\n const reportPath = process.env.DCS_SEO_HONESTY_REPORT\n const report: Record<string, unknown> = {\n schema: 1,\n generatedAt: new Date().toISOString(),\n projectRoot: ctx.projectRoot,\n outDir: ctx.outDir,\n siteUrl: ctx.siteUrl ?? null,\n base: ctx.base,\n routes: ctx.routes.length,\n p1: {\n mode: ctx.headMode,\n rendererAvailable,\n eligible: eligibleRoutes.length,\n observed: headObservations.length,\n unobserved: eligibleRoutes.filter(\n (r) => !headObservations.some((o) => o.route === r)\n ),\n filtered: filteredRoutes,\n exempted: ctx.headAllow.length,\n divergent: null as number | null,\n executed: false,\n },\n p12: { mode: ctx.charsetMode, shell: charsetShell, checked: 0, failed: 0, worstOffset: 0 },\n p2: { mode: ctx.urlMode, network: ctx.urlNetwork, audit: null as unknown },\n }\n const p1 = report.p1 as Record<string, unknown>\n try {\n // P1 — baked <head> == rendered <head>, per route. The EXECUTION\n // assertion runs first: in `error` mode a missing renderer, zero\n // eligible routes, or an eligible route with no observation is a hard\n // failure. C-334 warned and skipped here, which is how an\n // error-severity rail passed a build having checked nothing (C-338).\n const shouldCompare = assertHeadHonestyExecuted(\n {\n rendererAvailable,\n eligibleRoutes,\n observedRoutes: headObservations.map((o) => o.route),\n filteredRoutes,\n totalRoutes: ctx.routes.length,\n },\n { mode: ctx.headMode }\n )\n p1.executed = shouldCompare\n if (shouldCompare || ctx.headMode === 'off') {\n // In `error` mode this throws — record the divergences FIRST so a red\n // build still leaves the operator the list of what diverged.\n const found = findHeadHonestyViolations(headObservations, {\n allow: ctx.headAllow,\n checkDescription: ctx.headCheckDescription,\n })\n p1.divergent = found.length\n p1.violations = found\n assertHeadHonesty(headObservations, {\n mode: ctx.headMode,\n allow: ctx.headAllow,\n checkDescription: ctx.headCheckDescription,\n debug,\n })\n }\n\n // P12 — the encoding declaration is inside the sniffing window.\n runCharsetBudget({\n outDir: ctx.outDir,\n routes: ctx.routes,\n mode: ctx.charsetMode,\n debug,\n sink: (s) => Object.assign(report.p12 as object, s),\n })\n\n // P2 — every published URL resolves to what it promises. Runs LAST\n // because it is the only rail that can touch the network.\n await runEmittedUrlHonesty({\n outDir: ctx.outDir,\n projectRoot: ctx.projectRoot,\n routes: ctx.routes,\n siteUrl: ctx.siteUrl,\n base: ctx.base,\n mode: ctx.urlMode,\n allow: ctx.urlAllow,\n network: ctx.urlNetwork,\n debug,\n sink: (a, v) => {\n const p2 = report.p2 as Record<string, unknown>\n p2.audit = a\n p2.violations = v\n },\n })\n } finally {\n if (reportPath) {\n try {\n fs.mkdirSync(path.dirname(path.resolve(reportPath)), { recursive: true })\n fs.writeFileSync(path.resolve(reportPath), JSON.stringify(report, null, 2), 'utf8')\n console.log(`[dcs-seo] honesty report written: ${path.resolve(reportPath)}`)\n } catch (err) {\n console.warn('[dcs-seo] could not write honesty report:', err)\n }\n }\n }\n }\n },\n\n /**\n * Dev-only: inject the FRESH on-disk `seo.yaml` as an inline\n * `globalThis.__DCS_SEO__ = {…}` classic script at the top of `<head>`,\n * mirroring dcsContentPlugin. Lets the runtime `useSEO` SPA path reflect\n * on-disk SEO edits on the portal's `?_hc` hard reload with no restart.\n * Gated on `isDev` so it never runs in `vite`/`vitepress build` (the build\n * path keeps the baked `define` literal + the `writeBundle` emitter).\n *\n * `__DCS_PAGES__` (the `installSeoHead` route manifest) rides the same\n * refresh. It is injected INDEPENDENTLY of seo.yaml: a site can have a\n * pages.yaml and no seo.yaml, and returning early on a missing seo.yaml\n * would leave the router hook manifest-less (and therefore inert) in dev\n * only — a dev/prod behaviour split is exactly the kind of divergence this\n * plan exists to stop.\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n if (!isDev) return html\n\n const projectRoot = resolvedConfig?.root || process.cwd()\n const tags: HtmlTagDescriptor[] = []\n\n const config = readDcsYamlFresh<SeoConfiguration>(projectRoot, seoPath, 'dcs-seo', debug)\n // No file (or unparseable) ⇒ leave the global unset; the consumer's\n // `typeof globalThis.__DCS_SEO__` check falls back to defaults.\n if (config !== undefined) {\n if (debug) {\n console.log('[dcs-seo] serve: injecting fresh __DCS_SEO__ into <head>')\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_SEO__', config),\n injectTo: 'head-prepend',\n })\n }\n\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (routes) {\n // SAME exclusion filter as the build define above. A dev-only manifest\n // that carried excluded routes would make `installSeoHead` behave\n // differently in dev than in prod — the dev/prod split this whole\n // inject exists to avoid.\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n const emitted = routes.filter((r) => isRouteEmitted(r, { exclude, excludedGlobs }))\n // Dev REPORTS the colliding manifest; the BUILD is the gate that\n // refuses it. Throwing from `transformIndexHtml` would replace a\n // precise message with a blank dev-server page.\n const dupes = findDuplicateNormalizedPaths(emitted)\n if (dupes.length > 0) {\n console.error(\n `[dcs-seo] serve: ${formatDuplicateNormalizedPaths(dupes)}\\n` +\n `[dcs-seo] serve: this is reported here and FAILS the production build.`\n )\n }\n if (debug) {\n console.log(\n `[dcs-seo] serve: injecting fresh __DCS_PAGES__ (${emitted.length} of ` +\n `${routes.length} route(s), excluded ones omitted) into <head>`\n )\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_PAGES__', {\n routes: emitted.map((r) => ({\n slug: r.slug,\n path: r.path,\n ...(r.title ? { title: r.title } : {}),\n })),\n noindex,\n }),\n injectTo: 'head-prepend',\n })\n }\n\n if (tags.length === 0) return html\n return { html, tags }\n },\n },\n\n // Watch for changes in development.\n //\n // Downgraded from `server.restart()` to a debounced client `full-reload`:\n // freshness already comes from `transformIndexHtml` re-reading the YAML on\n // every HTML request, so all we need on change is a browser reload. A\n // `server.restart()` would rebuild VitePress's dev MiniSearch index and can\n // throw \"server restart failed\" on a duplicate heading id — the fragility\n // this fix removes. A `full-reload` does neither.\n configureServer(server) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n\n const watchPaths = [\n path.resolve(projectRoot, seoPath),\n path.resolve(projectRoot, '..', seoPath),\n ].map((p) => path.normalize(p))\n\n watchPaths.forEach((watchPath) => {\n if (fs.existsSync(watchPath)) {\n server.watcher.add(watchPath)\n }\n })\n\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n server.watcher.on('change', (changedPath) => {\n if (!watchPaths.includes(path.normalize(changedPath))) return\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n if (debug) {\n console.log('[dcs-seo] seo.yaml changed, sending full-reload')\n }\n server.ws.send({ type: 'full-reload' })\n }, 100)\n })\n },\n }\n}\n","/**\n * DCS Editor Plugin for Vite\n *\n * Injects the editor bridge script into customer sites when running\n * in portal preview mode (inside the visual editor iframe).\n *\n * The bridge enables:\n * - Inline text editing via contenteditable\n * - Section hover highlights and AI ✨ buttons\n * - postMessage communication with the portal\n *\n * This plugin should only be active in development/preview mode.\n * It's safe to include in production builds — it does nothing unless\n * the page detects it's inside an iframe.\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { dcsEditorPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsEditorPlugin()\n * ]\n * })\n * ```\n */\n\nimport type { Plugin } from 'vite'\n\nexport interface DcsEditorPluginOptions {\n /** Enable debug logging */\n debug?: boolean\n}\n\n/** The build variable that names the one portal origin the bridge trusts (C-2064 S4a-1). */\nexport const PORTAL_ORIGIN_ENV = 'VITE_DCS_PORTAL_ORIGIN'\n\n/**\n * The virtual module that starts the editor bridge. The configured portal\n * origin is written in as a literal: `undefined` when the variable is not set\n * (the bridge then uses its built-in origin on a sandbox host, or legacy\n * inference), otherwise the value as a string, valid or not. An invalid value\n * is NOT dropped here: the bridge must see that the variable was set, so that\n * it refuses every message instead of falling back.\n */\nexport function editorBridgeModuleSource(portalOrigin: unknown): string {\n const literal = portalOrigin === undefined ? 'undefined' : JSON.stringify(String(portalOrigin))\n return `\nimport { initEditorBridge } from '@duffcloudservices/cms/editor'\nconst startBridge = () => initEditorBridge({ portalOrigin: ${literal} })\n// The bridge only activates inside an iframe (portal preview)\nif (window.parent !== window) {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => setTimeout(startBridge, 200))\n } else {\n setTimeout(startBridge, 200)\n }\n}\n`\n}\n\n/**\n * Vite plugin that injects the editor bridge script for portal preview integration.\n *\n * The bridge auto-initializes only when the page detects it's running inside an iframe,\n * so it's safe to include in all builds — it's a no-op in standalone browsing.\n *\n * Uses a virtual module (`/__dcs-editor-bridge.js`) served through Vite's dev server\n * so that bare module specifiers (like `@duffcloudservices/cms/editor`) are properly\n * resolved through Vite's module graph rather than hitting the browser's native ESM\n * resolver, which can't handle bare specifiers.\n */\nexport function dcsEditorPlugin(options: DcsEditorPluginOptions = {}): Plugin {\n const { debug = false } = options\n const VIRTUAL_PATH = '/__dcs-editor-bridge.js'\n const RIBBON_VIRTUAL_PATH = '/__dcs-preview-ribbon.js'\n\n // Captured during configResolved — used to gate HTML injection.\n let isDev = false\n let basePath = '/'\n let isPreview = false\n // C-2064 S4a-1: the site build's VITE_DCS_PORTAL_ORIGIN, exactly as Vite\n // resolved it (process env and .env files), or undefined when it is not set.\n // The bridge validates it; this plugin only carries it across.\n let portalOrigin: unknown\n\n return {\n name: 'dcs-editor-bridge',\n\n // Preview only: stop Vite running an unreachable HMR WebSocket server.\n // Freshness comes from the cms content/seo plugins (fresh transformIndexHtml\n // re-read) + the portal's ?_hc hard reload, not HMR. NOTE: this alone does\n // NOT silence the browser — Vite still injects @vite/client and calls\n // connect(); the client-side stub in transformIndexHtml is what removes the\n // console errors. A normal local `vite dev` (no DCS_PREVIEW) keeps full HMR.\n config(_config, env) {\n if (env.command === 'serve' && process.env.DCS_PREVIEW === 'true') {\n return { server: { hmr: false } }\n }\n },\n\n configResolved(config) {\n isDev = config.command === 'serve'\n basePath = config.base ?? '/'\n isPreview = process.env.DCS_PREVIEW === 'true'\n portalOrigin = (config.env as Record<string, unknown> | undefined)?.[PORTAL_ORIGIN_ENV]\n },\n\n resolveId(id) {\n if (id === VIRTUAL_PATH || id === RIBBON_VIRTUAL_PATH) {\n return id\n }\n },\n\n load(id) {\n if (id === VIRTUAL_PATH) {\n return editorBridgeModuleSource(portalOrigin)\n }\n\n if (id === RIBBON_VIRTUAL_PATH) {\n return `\nimport { createApp } from 'vue'\nimport PreviewRibbon from '@duffcloudservices/cms/components'\n\nfunction mountRibbon() {\n // Create a detached mount point\n const el = document.createElement('div')\n el.id = 'dcs-preview-ribbon-root'\n document.body.appendChild(el)\n\n const app = createApp(PreviewRibbon)\n app.mount(el)\n}\n\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', mountRibbon)\n} else {\n mountRibbon()\n}\n`\n }\n },\n\n /**\n * Only inject the editor bridge and ribbon scripts when:\n * 1. Running in dev mode (Vite dev server), AND\n * 2. The app is served at the root path (base === '/')\n *\n * These are virtual modules resolved via absolute paths (e.g.\n * `/__dcs-editor-bridge.js`). When base !== '/', the app is served at a\n * sub-path (e.g. /iron-oak-contractors/) and the absolute virtual paths are NOT\n * routed to the Vite dev server by the reverse proxy — they hit the main\n * DCS server instead and get redirected to portal.duffcloudservices.com\n * (no CORS headers), causing browser console errors.\n *\n * In production builds, App.vue imports and mounts PreviewRibbon\n * directly, so virtual script injection is always redundant anyway.\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n if (!isDev || basePath !== '/') return html\n\n if (debug) {\n console.log('[dcs-editor] Injecting editor bridge + preview ribbon script tags')\n }\n\n // Inject both the editor bridge and preview ribbon scripts\n const editorTag = `<script type=\"module\" src=\"${VIRTUAL_PATH}\"></script>`\n const ribbonTag = `<script type=\"module\" src=\"${RIBBON_VIRTUAL_PATH}\"></script>`\n const bodyHtml = html.replace('</body>', `${editorTag}\\n${ribbonTag}\\n</body>`)\n\n if (!isPreview) return bodyHtml\n\n // Preview only: neutralise Vite's HMR WebSocket. Vite always injects\n // @vite/client and unconditionally calls transport.connect(); behind the\n // preview proxy chain there is no reachable HMR WS, so it logs\n // WebSocket connection to 'wss://<portal>/?token=…' failed\n // WebSocket connection to 'wss://localhost:<port>/?token=…' failed\n // [vite] failed to connect to websocket\n // server.hmr:false does NOT stop this (the client is still injected). A\n // classic <script> in <head> runs during parse, BEFORE the deferred\n // @vite/client module, so returning an inert socket for the 'vite-hmr'\n // subprotocol silences the attempt with zero effect on app/runtime\n // WebSockets. No-op outside preview / in production builds.\n const wsStub =\n `(function(){try{var N=window.WebSocket;if(!N)return;` +\n `function hmr(p){return p==='vite-hmr'||(Array.isArray(p)&&p.indexOf('vite-hmr')!==-1)}` +\n `function Inert(){this.readyState=0}` +\n `Inert.prototype.send=function(){};Inert.prototype.close=function(){};` +\n `Inert.prototype.addEventListener=function(){};Inert.prototype.removeEventListener=function(){};` +\n `var W=function(u,p){if(hmr(p))return new Inert();return new N(u,p)};` +\n `W.prototype=N.prototype;W.CONNECTING=N.CONNECTING;W.OPEN=N.OPEN;W.CLOSING=N.CLOSING;W.CLOSED=N.CLOSED;` +\n `window.WebSocket=W}catch(e){}})()`\n\n return {\n html: bodyHtml,\n tags: [{ tag: 'script', children: wsStub, injectTo: 'head-prepend' }],\n }\n },\n },\n }\n}\n","/**\n * DCS Preview Plugin for Vue\n *\n * Registers a supplied ribbon component as a global `DcsPreviewRibbon`\n * component. The ribbon handles its own visibility — it only renders on\n * `preview.duffcloudservices.com` and hides everywhere else (localhost,\n * production domains, and inside the visual page editor iframe).\n *\n * Why does the caller pass the component in? Because this file is compiled\n * by tsup (esbuild) which has no `.vue` SFC loader. Keeping the raw `.vue`\n * import out of the compiled plugins bundle avoids the build error while\n * still letting consumer code (which *does* run through Vite) resolve the\n * SFC at dev/build time.\n *\n * @example VitePress theme/index.ts\n * ```typescript\n * import { dcsPreviewPlugin } from '@duffcloudservices/cms/plugins'\n * import PreviewRibbon from '@duffcloudservices/cms/components'\n *\n * export default {\n * Layout,\n * enhanceApp({ app }) {\n * app.use(dcsPreviewPlugin(PreviewRibbon))\n * }\n * }\n * ```\n */\n\nimport { defineComponent, h, type App, type Component, type Plugin } from 'vue'\n\nexport interface DcsPreviewPluginOptions {\n /**\n * Override the version string displayed on the ribbon.\n * If omitted, the ribbon auto-detects from VITE_SITE_VERSION or the API.\n */\n version?: string | null\n}\n\n/**\n * Creates and returns the DCS Preview plugin.\n *\n * When installed, it registers the supplied ribbon component as a global\n * `DcsPreviewRibbon` component. Add `<DcsPreviewRibbon />` to your root\n * Layout, or use the `dcsEditorPlugin` Vite plugin which injects it via\n * `transformIndexHtml`.\n *\n * @param ribbonComponent - The PreviewRibbon SFC (imported by the consumer)\n * @param options - Optional configuration\n */\nexport function dcsPreviewPlugin(\n ribbonComponent: Component,\n options: DcsPreviewPluginOptions = {},\n): Plugin {\n const Wrapper = defineComponent({\n name: 'DcsPreviewRibbon',\n setup() {\n return () => h(ribbonComponent, { version: options.version ?? null })\n },\n })\n\n return {\n install(app: App) {\n app.component('DcsPreviewRibbon', Wrapper)\n\n if (options.version !== undefined) {\n app.provide('__dcs_preview_version__', options.version)\n }\n },\n }\n}\n","/**\n * DCS CDN Image Plugin for Vite\n *\n * Rewrites local static image references (e.g. `/images/staff/photo.jpg`)\n * to CDN URLs at build time using the `.dcs/cdn-image-map.json` mapping file\n * generated by the `image-migrate adopt` CLI command.\n *\n * For raster images with WebP variants, `<img>` elements are transformed into\n * responsive `<picture>` elements with `srcset` for optimised delivery.\n * SVGs receive a simple URL swap with no variant handling.\n *\n * **In development mode this plugin is a no-op** — local `/images/` paths\n * continue to work via Vite's static asset serving so hot-reload is unaffected.\n *\n * The plugin handles two in-pipeline replacement vectors:\n *\n * 1. **Module transform** (`transform` hook) — rewrites `<img>` tags and\n * string literals in Vue SFCs, TS, JS, CSS, MD, and HTML modules.\n * 2. **Chunk rendering** (`renderChunk` hook) — rewrites image paths in\n * final rendered JS/CSS chunks AFTER Vite's `define` substitution.\n * This catches data injected by `dcsContentPlugin` via `__DCS_CONTENT__`\n * (from `.dcs/content.yaml`) which bypasses the `transform` hook.\n *\n * A third vector — **post-build file processing** — is handled by the\n * companion `dcsCdnBuildEnd` hook, which must be registered separately in\n * VitePress config. VitePress generates HTML *after* both Vite builds\n * complete, so Vite plugin hooks (`closeBundle`, `transformIndexHtml`)\n * cannot catch SSR-rendered `<head>` tags or static `public/` files like\n * `service-worker.js`.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnImagePlugin, dcsCdnBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * vite: {\n * plugins: [\n * dcsCdnImagePlugin()\n * ]\n * },\n * buildEnd: dcsCdnBuildEnd()\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { Plugin } from 'vite'\nimport { isVectorImageUrl } from '@duffcloudservices/cms-core'\n\n// ────────────────────────────────────────────────────────────────────────────\n// Types\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface CdnImageMapVariant {\n suffix: string\n blobPath: string\n cdnUrl: string\n width: number\n height: number\n size: number\n}\n\nexport interface CdnImageMapEntry {\n localPath: string\n blobPath: string\n cdnUrl: string\n fileName: string\n contentType: string\n originalSize: number\n width?: number\n height?: number\n hash: string\n variants?: CdnImageMapVariant[]\n}\n\nexport interface CdnImageMap {\n generated: string\n site: string\n cdnBase: string\n images: CdnImageMapEntry[]\n}\n\nexport interface DcsCdnImagePluginOptions {\n /** Path to cdn-image-map.json relative to project root (default: '.dcs/cdn-image-map.json') */\n mapPath?: string\n\n /**\n * Patterns to match for replacement. Each must be a **leading-slash path prefix**\n * that appears in source code (e.g. `/images/`). The `localPath` field in the\n * mapping file is compared *without* a leading slash.\n *\n * Default: `['/images/']`\n */\n pathPrefixes?: string[]\n\n /**\n * Default `sizes` attribute for responsive `<picture>` elements.\n * Override per-context via the `data-sizes` attribute on the original `<img>`.\n *\n * Default: `'(max-width: 1024px) 100vw, 1024px'`\n */\n defaultSizes?: string\n\n /** Enable debug logging */\n debug?: boolean\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ────────────────────────────────────────────────────────────────────────────\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\n/**\n * Build the ` width=\"W\" height=\"H\"` attribute fragment for a map entry — the\n * CLS layout-shift hint (Phase 1). Dimensions are read from the entry's\n * intrinsic `width`/`height`; they are aspect-ratio hints, so emitting the\n * source dimensions on an `<img>` whose `src` is a resized variant is correct\n * (the ratio is scale-invariant and CSS still controls the rendered size).\n *\n * Emitted ONLY when both are known and strictly positive. Older image-map\n * entries carry no top-level dimensions (and variant `height` is often `0`) —\n * in that case NO hint is emitted rather than a fabricated/wrong ratio.\n */\nfunction dimensionAttrs(entry: CdnImageMapEntry): string {\n const w = entry.width\n const h = entry.height\n if (typeof w === 'number' && w > 0 && typeof h === 'number' && h > 0) {\n return ` width=\"${w}\" height=\"${h}\"`\n }\n return ''\n}\n\n/**\n * Build a responsive `<picture>` element for a raster image that has\n * WebP variants.\n */\nfunction buildPictureElement(\n entry: CdnImageMapEntry,\n alt: string,\n extraAttrs: string,\n sizes: string\n): string {\n const variants = entry.variants ?? []\n const dims = dimensionAttrs(entry)\n\n // Collect only the display-relevant variants (not thumb, not og)\n const displayVariants = variants.filter(\n (v) => v.suffix === '-sm' || v.suffix === '-md' || v.suffix === '-lg'\n )\n\n if (displayVariants.length === 0) {\n // No display variants — fall back to original CDN URL as plain <img>\n return `<img src=\"${escapeHtml(entry.cdnUrl)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dims} loading=\"lazy\" decoding=\"async\" />`\n }\n\n const srcset = displayVariants\n .map((v) => `${v.cdnUrl} ${v.width}w`)\n .join(', ')\n\n // Pick the -md variant as the default src, or fall through to original\n const mdVariant = variants.find((v) => v.suffix === '-md')\n const fallbackSrc = mdVariant ? mdVariant.cdnUrl : entry.cdnUrl\n\n return [\n '<picture>',\n ` <source srcset=\"${srcset}\" type=\"image/webp\" sizes=\"${escapeHtml(sizes)}\" />`,\n ` <img src=\"${escapeHtml(fallbackSrc)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dims} loading=\"lazy\" decoding=\"async\" />`,\n '</picture>',\n ].join('\\n')\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Shared helpers\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Try to find and load the CDN image map from common locations.\n * VitePress nests docs under a subfolder, so we check parent dirs too.\n */\nfunction loadCdnImageMap(\n projectRoot: string,\n relativeMapPath: string,\n debug: boolean\n): Map<string, CdnImageMapEntry> | null {\n const possiblePaths = [\n path.resolve(projectRoot, relativeMapPath),\n path.resolve(projectRoot, '..', relativeMapPath),\n path.resolve(process.cwd(), relativeMapPath),\n ]\n\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n try {\n const raw = fs.readFileSync(testPath, 'utf8')\n const data: CdnImageMap = JSON.parse(raw)\n\n const map = new Map<string, CdnImageMapEntry>()\n for (const entry of data.images) {\n // Store both with and without leading slash for flexible matching\n map.set(entry.localPath, entry)\n if (!entry.localPath.startsWith('/')) {\n map.set('/' + entry.localPath, entry)\n }\n }\n\n if (debug) {\n console.log(`[dcs-cdn-image] Loaded ${data.images.length} entries from ${testPath}`)\n }\n return map\n } catch (error) {\n console.warn(`[dcs-cdn-image] Failed to parse ${testPath}:`, error)\n }\n }\n }\n\n if (debug) {\n console.log('[dcs-cdn-image] No cdn-image-map.json found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n }\n return null\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Vite Plugin\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that rewrites static `/images/` paths to CDN URLs at build time.\n */\nexport function dcsCdnImagePlugin(options: DcsCdnImagePluginOptions = {}): Plugin {\n const {\n mapPath = '.dcs/cdn-image-map.json',\n pathPrefixes = ['/images/'],\n defaultSizes = '(max-width: 1024px) 100vw, 1024px',\n debug = false,\n } = options\n\n // Lookup map built from the JSON file: key = localPath (no leading slash)\n let imageMap: Map<string, CdnImageMapEntry> | null = null\n let isProduction = false\n\n /**\n * Check whether a source code string contains any of the path prefixes\n * we care about. Quick bail-out for files that don't reference images.\n */\n function hasImageReferences(code: string): boolean {\n return pathPrefixes.some((prefix) => code.includes(prefix))\n }\n\n /**\n * Replace image path references in any string value with CDN URLs.\n * Used for code transforms and renderChunk post-processing.\n */\n function replaceImagePaths(str: string): string {\n if (!imageMap || imageMap.size === 0) return str\n let result = str\n for (const prefix of pathPrefixes) {\n // Global replace: matches prefix followed by a relative path bounded\n // by quotes, parens, or whitespace. Allows spaces in filenames.\n const regex = new RegExp(\n `([\"'\\`(])${escapeRegex(prefix)}([^\"'\\`()]+)`,\n 'g'\n )\n result = result.replace(regex, (match, quote, relPath) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n return `${quote}${entry.cdnUrl}`\n })\n }\n return result\n }\n\n /**\n * Replace standalone URL references in JS/TS string literals and Vue template\n * attributes. This handles patterns like:\n * src=\"/images/foo.jpg\"\n * { src: '/images/foo.jpg' }\n * url(/images/foo.svg)\n *\n * For `<img>` tags with raster images that have variants, the entire tag is\n * replaced with a `<picture>` element.\n */\n function transformCode(code: string): string {\n if (!imageMap || imageMap.size === 0) return code\n\n // ── Pass 1: Replace <img> tags that reference mapped raster images ──────\n // Matches: <img ... src=\"/images/foo.jpg\" ... /> or <img ... src=\"/images/foo.jpg\" ... >\n const imgTagRegex = /<img\\b([^>]*?)src=[\"'](\\/(images\\/[^\"']+))[\"']([^>]*?)\\/?>/gi\n code = code.replace(imgTagRegex, (_match, beforeSrc, _srcWithSlash, localPath, afterSrc) => {\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return _match\n\n // Extract alt from the existing attributes\n const altMatch = (beforeSrc + afterSrc).match(/alt=[\"']([^\"']*)[\"']/)\n const alt = altMatch ? altMatch[1] : ''\n\n // Collect other attributes (not src, alt, loading, decoding — we set those)\n let otherAttrs = (beforeSrc + afterSrc)\n .replace(/\\balt=[\"'][^\"']*[\"']/gi, '')\n .replace(/\\bloading=[\"'][^\"']*[\"']/gi, '')\n .replace(/\\bdecoding=[\"'][^\"']*[\"']/gi, '')\n .trim()\n\n // When the map entry carries intrinsic dimensions, dimensionAttrs() will\n // emit width/height — strip any hand-authored ones (quoted or bare) so the\n // output doesn't carry DUPLICATE width/height attributes (a Vue compiler\n // duplicate-attribute error). Without entry dims, keep the author's.\n if (dimensionAttrs(entry)) {\n otherAttrs = otherAttrs\n .replace(/\\b(?:width|height)=(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>/]+)/gi, '')\n .replace(/\\s{2,}/g, ' ')\n .trim()\n }\n\n const extraAttrs = otherAttrs ? ' ' + otherAttrs : ''\n\n // Extract custom sizes if specified\n const sizesMatch = (beforeSrc + afterSrc).match(/data-sizes=[\"']([^\"']*)[\"']/)\n const sizes = sizesMatch ? sizesMatch[1] : defaultSizes\n\n // SVGs and images without variants → simple URL swap <img>. The vector\n // check is explicit (C-1803): the pipeline makes no variants for an SVG,\n // so even a map entry that lists some (hand-made files) must not become a\n // srcset. Same predicate as cms-core's resolveResponsiveImage.\n if (!entry.variants || entry.variants.length === 0 || isVectorImageUrl(entry.cdnUrl)) {\n return `<img src=\"${escapeHtml(entry.cdnUrl)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dimensionAttrs(entry)} loading=\"lazy\" decoding=\"async\" />`\n }\n\n // Raster with variants → <picture>\n return buildPictureElement(entry, alt, extraAttrs, sizes)\n })\n\n // ── Pass 2: Replace remaining string literal / CSS url() references ─────\n code = replaceImagePaths(code)\n\n return code\n }\n\n return {\n name: 'dcs-cdn-image',\n enforce: 'pre',\n\n configResolved(config) {\n isProduction = config.command === 'build'\n if (!isProduction) {\n if (debug) {\n console.log('[dcs-cdn-image] Dev mode — plugin disabled (local images served by Vite)')\n }\n return\n }\n imageMap = loadCdnImageMap(config.root, mapPath, debug)\n },\n\n transform(code, id) {\n // Only run in production builds\n if (!isProduction || !imageMap) return\n\n // Only process relevant file types\n if (!/\\.(vue|ts|tsx|js|jsx|css|scss|md|html)(\\?.*)?$/.test(id)) return\n\n // Quick bail — skip files with no image path references\n if (!hasImageReferences(code)) return\n\n const transformed = transformCode(code)\n if (transformed !== code) {\n return { code: transformed, map: null }\n }\n },\n\n /**\n * Replace image paths in final rendered JS/CSS chunks.\n *\n * This fires AFTER Vite's `define` substitution, catching paths that were\n * injected via `define` values (e.g. `__DCS_CONTENT__` set by\n * `dcsContentPlugin` from `.dcs/content.yaml`). Those paths bypass the\n * `transform` hook because `define` replacement happens at bundle time.\n */\n renderChunk(code, _chunk) {\n if (!isProduction || !imageMap) return null\n if (!hasImageReferences(code)) return null\n\n const replaced = replaceImagePaths(code)\n if (replaced !== code) {\n if (debug) {\n console.log(`[dcs-cdn-image] renderChunk: rewrote image paths in ${_chunk.fileName}`)\n }\n return { code: replaced, map: null }\n }\n return null\n },\n\n /**\n * Transform HTML output to catch references injected outside the module\n * pipeline — e.g. VitePress `head` config tags (favicons, OG images).\n *\n * Note: In VitePress, this hook fires for the `index.html` template but\n * NOT for SSR-rendered per-page HTML. Use `dcsCdnBuildEnd` for full\n * coverage of generated HTML files.\n */\n transformIndexHtml(html) {\n if (!isProduction || !imageMap) return html\n if (!hasImageReferences(html)) return html\n\n // Replace href/src/content attributes that reference mapped images\n for (const prefix of pathPrefixes) {\n const attrRegex = new RegExp(\n `((?:href|src|content)=[\"'])${escapeRegex(prefix)}([^\"']+)([\"'])`,\n 'gi'\n )\n html = html.replace(attrRegex, (match, pre, relPath, post) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n return `${pre}${entry.cdnUrl}${post}`\n })\n }\n\n return html\n },\n }\n}\n\n/**\n * Escape a string for use in a RegExp.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// VitePress buildEnd hook\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface DcsCdnBuildEndOptions {\n /** Path to cdn-image-map.json relative to project root (default: '.dcs/cdn-image-map.json') */\n mapPath?: string\n\n /**\n * Patterns to match for replacement.\n * Default: `['/images/']`\n */\n pathPrefixes?: string[]\n\n /** Enable debug logging */\n debug?: boolean\n\n /**\n * File extensions to process in the output directory.\n * Default: `['.html', '.js']`\n */\n extensions?: string[]\n}\n\n/**\n * VitePress `buildEnd` hook factory that post-processes generated HTML and\n * static files in the output directory to replace remaining `/images/` paths\n * with CDN URLs.\n *\n * VitePress generates HTML **after** both Vite builds complete, so Vite\n * plugin hooks (`closeBundle`, `transformIndexHtml`) cannot catch\n * SSR-rendered `<head>` tags (favicons, OG images). This hook runs after all\n * HTML files are written to disk.\n *\n * Also rewrites static files (e.g. `service-worker.js`) copied from\n * `public/` that are not part of Vite's module pipeline.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * buildEnd: dcsCdnBuildEnd({ debug: true })\n * })\n * ```\n */\nexport function dcsCdnBuildEnd(options: DcsCdnBuildEndOptions = {}) {\n const {\n mapPath = '.dcs/cdn-image-map.json',\n pathPrefixes = ['/images/'],\n debug = false,\n extensions = ['.html', '.js'],\n } = options\n\n return async (siteConfig: { root: string; outDir: string }) => {\n const imageMap = loadCdnImageMap(siteConfig.root, mapPath, debug)\n if (!imageMap) {\n if (debug) {\n console.log('[dcs-cdn-image] buildEnd: no image map found')\n }\n return\n }\n\n const outDir = siteConfig.outDir\n if (!fs.existsSync(outDir)) return\n\n let filesProcessed = 0\n let refsReplaced = 0\n\n function walkDir(dir: string) {\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n walkDir(fullPath)\n } else if (extensions.some((ext) => entry.name.endsWith(ext))) {\n processFile(fullPath)\n }\n }\n }\n\n function processFile(filePath: string) {\n let content = fs.readFileSync(filePath, 'utf8')\n if (!pathPrefixes.some((p) => content.includes(p))) return\n\n let changed = false\n\n if (filePath.endsWith('.html')) {\n // HTML: replace href/src/content attribute values\n for (const prefix of pathPrefixes) {\n const attrRegex = new RegExp(\n `((?:href|src|content)=[\"'])${escapeRegex(prefix)}([^\"']+)([\"'])`,\n 'gi'\n )\n content = content.replace(attrRegex, (match, pre, relPath, post) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const mapEntry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!mapEntry) return match\n changed = true\n refsReplaced++\n return `${pre}${mapEntry.cdnUrl}${post}`\n })\n }\n } else {\n // JS/other: replace quoted string paths\n for (const prefix of pathPrefixes) {\n const regex = new RegExp(\n `([\"'\\`(])${escapeRegex(prefix)}([^\"'\\`()]+)`,\n 'g'\n )\n content = content.replace(regex, (match, quote, relPath) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n changed = true\n refsReplaced++\n return `${quote}${entry.cdnUrl}`\n })\n }\n }\n\n if (changed) {\n fs.writeFileSync(filePath, content, 'utf8')\n filesProcessed++\n }\n }\n\n walkDir(outDir)\n\n if (debug) {\n console.log(\n `[dcs-cdn-image] buildEnd: post-processed ${filesProcessed} files, replaced ${refsReplaced} references`\n )\n }\n }\n}","/**\n * markdown-it plugin that transforms standard `![alt](url)` image syntax\n * into responsive `<picture>` elements when the URL matches the DCS CDN\n * asset pattern.\n *\n * Non-CDN images are rendered with the default image renderer (plain `<img>`).\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { responsiveImagePlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * markdown: {\n * config: (md) => {\n * md.use(responsiveImagePlugin)\n * },\n * },\n * })\n * ```\n *\n * Input markdown:\n * ```md\n * ![Physical therapy session](https://files.duffcloudservices.com/kept/assets/blog/abc-123.jpg)\n * ```\n *\n * Rendered HTML:\n * ```html\n * <picture>\n * <source srcset=\"...abc-123-sm.webp 640w, ...abc-123-md.webp 1024w, ...abc-123-lg.webp 1920w\"\n * type=\"image/webp\"\n * sizes=\"(max-width: 1024px) 100vw, 1024px\" />\n * <img src=\"...abc-123-md.webp\" alt=\"Physical therapy session\" loading=\"lazy\" decoding=\"async\" />\n * </picture>\n * ```\n */\n\nimport type MarkdownIt from 'markdown-it'\nimport { isVectorImageUrl } from '@duffcloudservices/cms-core'\n\n/**\n * Matches DCS CDN asset URLs: base path / UUID . extension.\n *\n * Aligned with `@duffcloudservices/cms-core` `responsive-image.ts`: the\n * `(?:content\\/)?` group covers the content-container shape\n * `https://files.duffcloudservices.com/content/{slug}/assets/...` in addition\n * to the branding-container shape `.../{slug}/assets/...`. The group is\n * non-capturing, so the captured base path / UUID / extension are unchanged.\n */\nconst CDN_PATTERN = /^(https?:\\/\\/files\\.[^/]+\\/(?:content\\/)?[^/]+\\/assets\\/(?:[^/]+\\/)*)([a-f0-9-]+)\\.(\\w+)$/\n\n/**\n * Escapes HTML special characters for safe attribute embedding.\n * Falls back to a simple replace chain when `md.utils.escapeHtml` is unavailable.\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\nexport function responsiveImagePlugin(md: MarkdownIt): void {\n const defaultImageRenderer = md.renderer.rules.image\n\n md.renderer.rules.image = (tokens, idx, options, env, self) => {\n const token = tokens[idx]\n const src = token.attrGet('src') ?? ''\n const alt = token.content ?? ''\n\n const match = src.match(CDN_PATTERN)\n // C-1803: the pipeline generates no WebP variants for a vector source, so\n // an SVG renders as its original URL — the same rule as cms-core.\n if (!match || isVectorImageUrl(src)) {\n // Not a CDN raster image — render normally\n if (defaultImageRenderer) {\n return defaultImageRenderer(tokens, idx, options, env, self)\n }\n return self.renderToken(tokens, idx, options)\n }\n\n const [, basePath, uuid] = match\n\n const srcset = [\n `${basePath}${uuid}-sm.webp 640w`,\n `${basePath}${uuid}-md.webp 1024w`,\n `${basePath}${uuid}-lg.webp 1920w`,\n ].join(', ')\n\n const escapedAlt = escapeHtml(alt)\n\n // Self-heal: this plugin emits a STATIC HTML string at build time (no Vue\n // runtime), so the fallback must be an inline onerror. A fit-variant\n // (`-md`/`-lg`) may legitimately be absent (internal/imaging variants.go\n // skips variants by DIMENSION). On the first error, swap the `<img>` to the\n // ORIGINAL url AND strip the sibling `<source>` elements — a `<picture>`\n // does NOT re-resolve after a `<source>` 404s, so the variant set must be\n // removed for the original to display. (`this.onerror=null` prevents loops.)\n const escapedOriginal = escapeHtml(src)\n const onError =\n `this.onerror=null;this.src='${escapedOriginal}';` +\n `this.closest('picture')?.querySelectorAll('source').forEach(s=>s.remove())`\n\n return [\n '<picture>',\n ` <source srcset=\"${srcset}\" type=\"image/webp\" sizes=\"(max-width: 1024px) 100vw, 1024px\" />`,\n ` <img src=\"${basePath}${uuid}-md.webp\" alt=\"${escapedAlt}\" loading=\"lazy\" decoding=\"async\" onerror=\"${onError}\" />`,\n '</picture>',\n ].join('\\n')\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/plugins/serveDefineInject.ts","../../src/plugins/motionTokens.ts","../../src/plugins/agentWidget.ts","../../src/plugins/dcsContentPlugin.ts","../../src/plugins/dcsResponsiveImageLint.ts","../../src/plugins/dcsDirIndex.ts","../../src/seo/playwrightRenderer.ts","../../src/plugins/routeLastmod.ts","../../src/plugins/dcsSeoPlugin.ts","../../src/plugins/dcsEditorPlugin.ts","../../src/plugins/dcsPreviewPlugin.ts","../../src/plugins/dcsCdnImagePlugin.ts","../../src/plugins/responsiveImagePlugin.ts"],"names":["path","fs","yaml","config","h","hit","escapeHtml","isVectorImageUrl"],"mappings":";;;;;;;;;;;;;AAiCO,SAAS,cAAA,CAAe,aAAqB,OAAA,EAA2B;AAC7E,EAAA,OAAO;AAAA,IACLA,KAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,O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AAK,IAAI,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,IAAA,CAAK,WAAA,CAAY,MAAA,EAAQ,GAAA,EAAK,OAAO,CAAA;AAAA,IAC9C;AAEA,IAAA,MAAM,GAAG,QAAA,EAAU,IAAI,CAAA,GAAI,KAAA;AAE3B,IAAA,MAAM,MAAA,GAAS;AAAA,MACb,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,aAAA,CAAA;AAAA,MAClB,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,cAAA,CAAA;AAAA,MAClB,CAAA,EAAG,QAAQ,CAAA,EAAG,IAAI,CAAA,cAAA;AAAA,KACpB,CAAE,KAAK,IAAI,CAAA;AAEX,IAAA,MAAM,UAAA,GAAaD,YAAW,GAAG,CAAA;AASjC,IAAA,MAAM,eAAA,GAAkBA,YAAW,GAAG,CAAA;AACtC,IAAA,MAAM,OAAA,GACJ,+BAA+B,eAAe,CAAA,4EAAA,CAAA;AAGhD,IAAA,OAAO;AAAA,MACL,WAAA;AAAA,MACA,qBAAqB,MAAM,CAAA,gEAAA,CAAA;AAAA,MAC3B,eAAe,QAAQ,CAAA,EAAG,IAAI,CAAA,eAAA,EAAkB,UAAU,8CAA8C,OAAO,CAAA,IAAA,CAAA;AAAA,MAC/G;AAAA,KACF,CAAE,KAAK,IAAI,CAAA;AAAA,EACb,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Shared serve-mode helpers for the DCS content + SEO Vite plugins.\n *\n * In a production build the plugins bake the `.dcs/*.yaml` payload into a Vite\n * `define` literal (`define: { __DCS_X__: JSON.stringify(data) }`) so the SSG /\n * SPA bundle inlines it exactly as before.\n *\n * In dev (`vite` / `vitepress dev`, i.e. the portal preview) baking a literal\n * is wrong: the value is frozen at server-start and only a `server.restart()`\n * would refresh it — and that restart is exactly what triggers VitePress's\n * MiniSearch rebuild and the duplicate-heading \"server restart failed\" crash.\n *\n * Instead, in serve mode the plugins:\n * 1. redirect the `__DCS_X__` define to a browser global\n * (`define: { __DCS_X__: 'globalThis.__DCS_X__' }`), and\n * 2. inject an inline classic `<script>` at the top of `<head>` on every HTML\n * request that assigns the FRESH on-disk YAML to that global.\n *\n * Because `transformIndexHtml` re-runs on every dev HTML request, a plain\n * iframe reload (the portal's `?_hc` hard reload) reflects the latest on-disk\n * content with NO `server.restart()` and NO module-graph surgery. The consumer\n * is untouched: it still reads the bare `__DCS_X__` identifier, which the define\n * rewrites to `globalThis.__DCS_X__`.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\n\n/**\n * The three `.dcs` search locations the plugins have always used. VitePress\n * projects have the `docs/` folder as root, so the parent is checked too.\n */\nexport function dcsSearchPaths(projectRoot: string, relPath: string): string[] {\n return [\n path.resolve(projectRoot, relPath),\n path.resolve(projectRoot, '..', relPath),\n path.resolve(process.cwd(), relPath),\n ]\n}\n\n/** First existing `.dcs` file from the standard search, or `undefined`. */\nexport function resolveDcsFile(projectRoot: string, relPath: string): string | undefined {\n return dcsSearchPaths(projectRoot, relPath).find((p) => fs.existsSync(p))\n}\n\n/**\n * Read + parse a `.dcs` YAML file FRESH from disk on every call (no caching).\n * Returns the parsed value, or `undefined` when the file is missing or\n * unparseable. Never throws — a dev HTML request must never 500 on bad YAML.\n */\nexport function readDcsYamlFresh<T = unknown>(\n projectRoot: string,\n relPath: string,\n label: string,\n debug = false\n): T | undefined {\n const found = resolveDcsFile(projectRoot, relPath)\n if (!found) {\n if (debug) console.log(`[${label}] serve: no ${relPath} found; global left unset`)\n return undefined\n }\n try {\n return yaml.load(fs.readFileSync(found, 'utf8')) as T\n } catch (error) {\n console.warn(`[${label}] serve: failed to parse ${relPath}:`, error)\n return undefined\n }\n}\n\n/**\n * Build a safe inline `<script>` body that assigns a JSON-serialisable value to\n * a browser global. Every `<` is escaped to its `<` unicode form so an\n * embedded `</script>` (or `<!--`) inside the content data can never break out\n * of the inline script.\n */\nexport function buildGlobalAssignScript(globalName: string, value: unknown): string {\n const json = JSON.stringify(value ?? null).replace(/</g, '\\\\u003c')\n return `globalThis.${globalName} = ${json};`\n}\n","import type { HtmlTagDescriptor } from 'vite'\n\n/**\n * DCS motion tokens — the customer-site copy of the shared motion vocabulary.\n *\n * Injected as a constant `<style>` into every DCS site's `<head>` by\n * `dcsContentPlugin` (see its `transformIndexHtml`). This is the fleet-wide\n * seam: every site (vue-spa and VitePress) already wires `dcsContentPlugin`,\n * so a cms version bump ships these tokens to the whole fleet with zero\n * per-site source edits.\n *\n * Source of truth is the platform copy at\n * `packages/dcs-ui/src/styles/motion.css` and the `dcs-product-motion` skill —\n * keep the values here in lockstep. Values ONLY: reduced-motion stays a\n * per-component responsibility so no blanket `!important` rule leaks into a\n * site's isolated `.<slug>-page` design subtree.\n */\nexport const DCS_MOTION_TOKENS_CSS = `:root {\n --motion-duration-stagger: 40ms;\n --motion-duration-micro: 80ms;\n --motion-duration-quick: 150ms;\n --motion-duration-fast: 250ms;\n --motion-duration-medium: 350ms;\n --motion-duration-slow: 400ms;\n --motion-duration-very-slow: 500ms;\n --motion-ease-out: cubic-bezier(0.22, 1, 0.36, 1);\n --motion-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1);\n --motion-ease-linear: linear;\n --motion-ease-bounce: cubic-bezier(0.34, 1.36, 0.64, 1);\n --motion-ease-bounce-strong: cubic-bezier(0.34, 3.85, 0.64, 1);\n --motion-distance-xs: 4px;\n --motion-distance-sm: 8px;\n --motion-distance-md: 12px;\n --motion-distance-lg: 24px;\n --motion-scale-lg: 0.96;\n --motion-scale-md: 0.97;\n --motion-scale-sm: 0.98;\n --motion-scale-xs: 0.99;\n --motion-blur-sm: 2px;\n --motion-blur-md: 3px;\n --motion-blur-lg: 8px;\n}`\n\n/**\n * The `<head>` tag descriptor for the motion-token block.\n *\n * `injectTo: 'head'`, NOT `'head-prepend'` — C-414. Vite's `head-prepend`\n * inserts immediately after the `<head>` open tag, i.e. AHEAD of the site's own\n * `<meta charset>`. This block is 858 bytes, so it pushed the encoding\n * declaration to byte 910 of the HTML spec's 1024-byte encoding-sniffing window\n * on every site in the fleet (measured on Iron Oak and Bryan's 2026-07-27, and\n * re-measured identical here), leaving ~90 bytes of headroom before every DCS\n * site silently mojibakes.\n *\n * `'head'` appends to the END of the `<head>` the site authored — which is\n * still ABOVE Vite's own build-time `<link rel=stylesheet>` / entry `<script>`,\n * because those are injected AFTER this `order: 'pre'` hook's tags. So the\n * per-site `:root` override still wins the cascade (that was the original\n * reason for `head-prepend`) AND the charset lands at byte ~46 with ~954 bytes\n * of headroom. Measured, not assumed — see `verify-honesty-rails.mjs` P12.\n *\n * If you ever move this back to `head-prepend`, the P12 rail in\n * `scripts/verify-honesty-rails.mjs` will fail: it asserts the charset comes\n * FIRST straight out of `dcsContentPlugin`, with no `dcsSeoPlugin` hoist.\n */\nexport function dcsMotionTokensStyleTag(): HtmlTagDescriptor {\n return {\n tag: 'style',\n attrs: { 'data-dcs-motion-tokens': '' },\n children: DCS_MOTION_TOKENS_CSS,\n injectTo: 'head',\n }\n}\n","/**\n * DCS AI-assistant widget loader — the cms head-inject seam for Phase 3 of the\n * Managed Site AI Agents plan (.docs/archive/plans/managed-site-ai-agents/plan.md).\n *\n * This rides the same always-on `dcsContentPlugin.transformIndexHtml` seam that\n * ships the motion tokens: every DCS site already wires `dcsContentPlugin`, so a\n * cms version bump delivers this loader to the whole fleet with ZERO per-site\n * source edits, and the portal per-site toggle turns the widget on/off at\n * runtime with no rebuild.\n *\n * What gets injected is a tiny (<2 KB) inline `<script>` — NOT the widget. On\n * idle it fetches the public agent config for this site; only if the agent is\n * enabled (HTTP 200) does it publish `window.__DCS_AGENT_BOOTSTRAP__` and inject\n * the real widget bundle from the CDN. The loader is **fail-silent**: a disabled\n * agent (404), a dead backend, a blocked request, or a malformed response all\n * result in no mount and no console error, so the assistant can never break a\n * customer page.\n *\n * Build-only: the loader is injected into the production build output (the fleet\n * delivery), not into `vite dev`. In local dev the config fetch would hit the\n * prod API from a non-whitelisted `localhost` origin and log an uncatchable CORS\n * error for every site developer — so, unlike the constant motion-token block,\n * this network-touching loader stays out of the dev server.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport yaml from 'js-yaml'\nimport type { HtmlTagDescriptor } from 'vite'\n\nimport { config as packageConfig } from '../../package.json'\n\n/**\n * DCS API origin the loader calls when the build passes none (dcsContentPlugin\n * feeds `process.env.VITE_API_BASE_URL` first). The value lives in this\n * package's `package.json` `config` block (C-1062: no production URL as a source\n * literal); the exported name is unchanged for consumers.\n */\nexport const DEFAULT_AGENT_API_BASE_URL: string = packageConfig.agentApiBaseUrl\n\n/**\n * Versioned CDN URL of the widget bundle. Both `cdn.` (branding CDN, CorsAllowAll)\n * and the already-live `files.` route serve the same `sgdcs` blob origin with an\n * identical `/agent-widget/v1/...` layout, so this is a plain classic-script\n * include that needs no CORS on the bundle host. Defaults to `files.` because the\n * `cdn.` Front Door route is still provisioning-gated (enableCdnDomain=false) —\n * flip the default only after that domain is live, or pass cdnScriptUrl. The\n * value lives in `package.json` `config.agentWidgetScriptUrl` (C-1062).\n */\nexport const DEFAULT_AGENT_WIDGET_SCRIPT_URL: string = packageConfig.agentWidgetScriptUrl\n\nexport interface DcsAgentWidgetLoaderOptions {\n /** Owning site slug — baked into the loader so it can build the config URL. */\n siteSlug: string\n /** DCS API base (default: the shared portal origin). */\n apiBaseUrl?: string\n /** Full URL of the CDN widget bundle. */\n cdnScriptUrl?: string\n /**\n * Where the loader asks for the agent config (C-1941). `'same-origin'`\n * (default, unchanged) probes the page host's slug-free `/api/v1/agent/config`\n * first, then falls back to the platform slug route. `'platform'` goes\n * straight to the platform slug route and never probes the page host. Use it\n * for a site whose production host has no `/api` route, such as an SWA\n * default hostname. There the same-origin probe always 404s and leaves an\n * uncatchable console line on every page load.\n */\n configOrigin?: AgentConfigOrigin\n}\n\n/** The values `.dcs/site.yaml` `agent_config_origin` accepts (C-1941). */\nexport const AGENT_CONFIG_ORIGINS = ['same-origin', 'platform'] as const\nexport type AgentConfigOrigin = (typeof AGENT_CONFIG_ORIGINS)[number]\n\nconst trimTrailingSlash = (value: string): string => value.replace(/\\/+$/, '')\n\n/**\n * JSON-encodes a value for safe embedding inside an inline `<script>` body.\n * `JSON.stringify` alone stops JS string-literal breakout but NOT the HTML\n * parser: a raw `</script>` (or a U+2028/U+2029 line separator, which is a valid\n * JS line terminator) inside the string would still terminate the element. So we\n * additionally escape `<`, `>`, and the two separators to their `\\uXXXX` forms —\n * defense-in-depth even though today every embedded value is build-time DCS\n * provisioning identity (DNS-label slug + platform URLs).\n */\nconst encodeForInlineScript = (value: string): string =>\n JSON.stringify(value)\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n\n/**\n * Builds the inline loader script body. Slug + URLs are HTML-safe-encoded (see\n * encodeForInlineScript) so no value can break out of the string literal OR the\n * `<script>` element. Kept intentionally compact to stay under the ~2 KB perf\n * budget (G4).\n */\nexport function buildAgentWidgetLoaderScript(options: DcsAgentWidgetLoaderOptions): string {\n const slug = encodeForInlineScript(options.siteSlug)\n const api = encodeForInlineScript(trimTrailingSlash(options.apiBaseUrl || DEFAULT_AGENT_API_BASE_URL))\n const cdn = encodeForInlineScript(options.cdnScriptUrl || DEFAULT_AGENT_WIDGET_SCRIPT_URL)\n // The platform (legacy, slug-carrying) config route. With configOrigin\n // 'platform' it is the ONLY config request; otherwise it is the fallback arm.\n const platformProbe = 'p(A+\"/api/v1/sites/\"+encodeURIComponent(S)+\"/agent/config\")'\n const configChain =\n options.configOrigin === 'platform'\n ? platformProbe\n : 'p(\"/api/v1/agent/config\").then(function(c){return c===null?' + platformProbe + ':c;})'\n\n return (\n '(function(){try{' +\n 'if(window.__DCS_AGENT_LOADER__)return;window.__DCS_AGENT_LOADER__=1;' +\n // Suppression parity with PreviewRibbon: skip the editor iframe (self!==top,\n // cross-origin access throws → treated as framed) and the ?dcs-hide-widget\n // screenshot/perf suppressor.\n 'try{if(window.self!==window.top)return;}catch(e){return;}' +\n 'if(/[?&]dcs-hide-widget(?:[=&]|$)/.test(location.search))return;' +\n 'var S=' + slug + ',A=' + api + ',C=' + cdn + ';' +\n 'var go=function(){try{' +\n // C-180: slug-free bootstrap probe. The loader runs on the customer's own\n // page, so a SAME-ORIGIN /api/v1/agent/config carries the customer Host and\n // SiteContextMiddleware resolves the site server-side — no slug in the path.\n // (Baking the slug into A+\"/api/v1/sites/\"+S+... hit the shared portal Host,\n // which cannot resolve a customer site.) A (apiBaseUrl) and S (slug) are still\n // handed to the widget bundle below for the chat/contact calls, which remain\n // slug-based against the legacy routes until they are migrated too.\n //\n // FALLBACK (2026-07-09 live finding): not every customer apex proxies\n // /api/v1/* to an API — kept's apex serves it from the STATIC origin (200\n // text/html SPA fallback), so the same-origin probe gets HTML and json()\n // rejects. When the slug-free probe yields nothing, retry the legacy\n // cross-origin slug route so the widget keeps mounting on proxy-less sites.\n //\n // C-290 (2026-07-25, probe matrix\n // .docs/plans/dynamic-site-resolution/evidence/agent-config-cors-matrix-2026-07-25.json):\n // the two arms were ALREADY sequential — the defect was that p() collapsed\n // \"no API on this route\" and \"the API answered, there is no agent\" into the\n // same null, so a site whose API authoritatively 404s fired a SECOND\n // guaranteed-404 request and logged a second uncatchable browser console\n // error on every page load. p() now distinguishes them:\n // null -> no API reached (network error, or a non-JSON body = SPA\n // fallback) => the legacy arm is worth trying\n // 0 -> a JSON API answered but the agent is off/absent => STOP, the\n // legacy arm can only 404 too\n // 0 is falsy, so the mount gate below is unchanged.\n 'var p=function(u){return fetch(u,{headers:{Accept:\"application/json\"}})' +\n // NB: no `<` / `>` anywhere in this body — the inline script must stay\n // angle-bracket-free so nothing can terminate the <script> element\n // (asserted by the HTML-hostile-slug test), hence indexOf(...)===-1.\n '.then(function(r){if(!r||(r.headers.get(\"content-type\")||\"\").indexOf(\"json\")===-1)return null;' +\n 'return r.ok?r.json()[\"catch\"](function(){return null;}):0;})' +\n '[\"catch\"](function(){return null;});};' +\n // C-1941: configOrigin 'platform' drops the same-origin arm entirely.\n configChain +\n '.then(function(c){if(!c||!c.enabled)return;' +\n 'window.__DCS_AGENT_BOOTSTRAP__={siteSlug:S,apiBaseUrl:A,config:c};' +\n 'var s=document.createElement(\"script\");s.src=C;s.async=true;s.setAttribute(\"data-dcs-agent-slug\",S);' +\n '(document.head||document.documentElement).appendChild(s);})' +\n '.catch(function(){});' +\n '}catch(e){}};' +\n 'if(\"requestIdleCallback\"in window){requestIdleCallback(go,{timeout:4000});}else{setTimeout(go,1200);}' +\n '}catch(e){}})();'\n )\n}\n\nconst SITE_YAML_CANDIDATES = ['.dcs/site.yaml', '../.dcs/site.yaml']\n\n/**\n * Reads `site_slug` from the site's `.dcs/site.yaml` (the same identity file the\n * announcements/provisioning path uses). Returns null when no site.yaml exists\n * or it carries no slug — the caller then injects nothing (silence for non-DCS\n * builds).\n */\nexport function readSiteSlug(projectRoot: string): string | null {\n return readSiteYaml(projectRoot)?.slug ?? null\n}\n\ninterface SiteYamlAgentFields {\n site_slug?: unknown\n agent_config_origin?: unknown\n}\n\n/**\n * The first `.dcs/site.yaml` candidate that parses and carries a `site_slug`,\n * or null. Both readers use it, so the slug and the config origin always come\n * from the same file.\n */\nfunction readSiteYaml(projectRoot: string): { slug: string; fields: SiteYamlAgentFields } | null {\n const candidates = [\n ...SITE_YAML_CANDIDATES.map((rel) => path.resolve(projectRoot, rel)),\n path.resolve(process.cwd(), '.dcs/site.yaml'),\n ]\n for (const candidate of candidates) {\n try {\n if (!fs.existsSync(candidate)) continue\n const parsed = yaml.load(fs.readFileSync(candidate, 'utf8')) as SiteYamlAgentFields | null\n const slug = parsed && typeof parsed.site_slug === 'string' ? parsed.site_slug.trim() : ''\n if (parsed && slug) return { slug, fields: parsed }\n } catch {\n // Unreadable/unparseable — try the next candidate, else return null.\n }\n }\n return null\n}\n\n/**\n * Reads `agent_config_origin` from `.dcs/site.yaml` (C-1941). If the key is\n * absent it returns null, and the loader keeps its same-origin-first default. A\n * value outside AGENT_CONFIG_ORIGINS is ignored with ONE build-time\n * console.warn. It never fails the build and never changes the served loader.\n */\nexport function readAgentConfigOrigin(projectRoot: string): AgentConfigOrigin | null {\n const raw = readSiteYaml(projectRoot)?.fields.agent_config_origin\n if (raw === undefined || raw === null) return null\n const value = typeof raw === 'string' ? raw.trim() : raw\n if (typeof value === 'string' && (AGENT_CONFIG_ORIGINS as readonly string[]).includes(value)) {\n return value as AgentConfigOrigin\n }\n console.warn(\n `[dcs-agent-widget] ignoring .dcs/site.yaml agent_config_origin=${JSON.stringify(raw)}; ` +\n `expected one of ${AGENT_CONFIG_ORIGINS.join(', ')}. The loader keeps the same-origin-first probe.`,\n )\n return null\n}\n\nexport interface DcsAgentWidgetTagOptions {\n /** Vite project root used to resolve the site slug. */\n projectRoot: string\n /** Override the DCS API base (default: process.env.VITE_API_BASE_URL, else the shared origin). */\n apiBaseUrl?: string\n /** Override the CDN bundle URL. */\n cdnScriptUrl?: string\n}\n\n/**\n * The `<head>` tag descriptor for the loader, or `null` when this build is not a\n * DCS-managed site (no resolvable slug) — in which case nothing is injected.\n */\nexport function dcsAgentWidgetLoaderTag(options: DcsAgentWidgetTagOptions): HtmlTagDescriptor | null {\n const siteSlug = readSiteSlug(options.projectRoot)\n if (!siteSlug) return null\n const configOrigin = readAgentConfigOrigin(options.projectRoot)\n\n return {\n tag: 'script',\n // The config-origin attribute only marks the served HTML, so audits and live\n // proofs can read it. The behaviour itself is baked into the loader body.\n attrs:\n configOrigin === 'platform'\n ? { 'data-dcs-agent-loader': '', 'data-dcs-agent-config-origin': 'platform' }\n : { 'data-dcs-agent-loader': '' },\n children: buildAgentWidgetLoaderScript({\n siteSlug,\n apiBaseUrl: options.apiBaseUrl,\n cdnScriptUrl: options.cdnScriptUrl,\n configOrigin: configOrigin ?? undefined,\n }),\n injectTo: 'head',\n }\n}\n","/**\n * DCS Content Plugin for Vite\n *\n * Reads `.dcs/content.yaml` at build time and injects content\n * as `__DCS_CONTENT__` global variable for use by useTextContent.\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { dcsContentPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsContentPlugin({ debug: true })\n * ]\n * })\n * ```\n *\n * For VitePress:\n * ```typescript\n * // .vitepress/config.ts\n * import { defineConfig } from 'vitepress'\n * import { dcsContentPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * vite: {\n * plugins: [\n * dcsContentPlugin()\n * ]\n * }\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { Plugin, ResolvedConfig, HtmlTagDescriptor } from 'vite'\nimport type { DcsContentFile } from '../types/content'\nimport { readDcsYamlFresh, buildGlobalAssignScript } from './serveDefineInject'\nimport { dcsMotionTokensStyleTag } from './motionTokens'\nimport { dcsAgentWidgetLoaderTag } from './agentWidget'\n\nexport interface DcsContentPluginOptions {\n /** Path to content.yaml relative to project root (default: '.dcs/content.yaml') */\n contentPath?: string\n /** Enable debug logging */\n debug?: boolean\n}\n\n/**\n * Packages that MUST be bundled into the SSR build (noExternal) rather than\n * externalized to `node_modules`.\n *\n * WHY: this plugin injects the site's content as the `__DCS_CONTENT__` Vite\n * `define`. A `define` is a compile-time text substitution that Vite applies\n * ONLY to source that passes through its transform pipeline. When a package is\n * SSR-externalized (loaded by Node's native resolver at server-render time), the\n * substitution never happens — `__DCS_CONTENT__` stays an undefined global on\n * the server. The content composables (`useReviewContent`, `useTextContent`)\n * then fall back to their empty/placeholder branch during SSR while the client\n * (where the define DID apply) renders the real content — producing the\n * \"Hydration completed but contains mismatches\" bug and, worse, baking\n * fabricated fallback content into the crawler-visible SSR HTML.\n *\n * Forcing the cms package `noExternal` bundles it into the SSR graph so the\n * define reaches the composables server-side, keeping SSR and client in lockstep\n * and putting the REAL content in the pre-rendered HTML. This is applied by the\n * plugin itself (merged into the user's Vite config) so every VitePress / vite\n * consumer inherits the fix on a cms bump — no per-site config knob to forget.\n */\nconst DCS_SSR_NO_EXTERNAL = ['@duffcloudservices/cms']\n\n/**\n * Vite plugin that injects .dcs/content.yaml at build time.\n *\n * @param options - Plugin configuration\n * @returns Vite plugin\n */\nexport function dcsContentPlugin(options: DcsContentPluginOptions = {}): Plugin {\n const { contentPath = '.dcs/content.yaml', debug = false } = options\n\n let resolvedConfig: ResolvedConfig\n // Captured during configResolved — gates the serve-only inline HTML inject.\n let isDev = false\n\n return {\n name: 'dcs-content',\n\n configResolved(config) {\n resolvedConfig = config\n isDev = config.command === 'serve'\n },\n\n config(config, env) {\n // ── Dev / preview (serve) ──────────────────────────────────────────────\n // Don't bake content into the bundle. Redirect the `__DCS_CONTENT__`\n // define to a browser global that `transformIndexHtml` (below) refreshes\n // from disk on every HTML request — so a plain iframe reload reflects the\n // latest on-disk content with NO server.restart() and NO module-graph\n // surgery. The consumer is untouched: it still reads the bare\n // `__DCS_CONTENT__` identifier, which this define rewrites to\n // `globalThis.__DCS_CONTENT__`.\n if (env.command === 'serve') {\n return {\n define: {\n __DCS_CONTENT__: 'globalThis.__DCS_CONTENT__',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n\n // ── Production build ───────────────────────────────────────────────────\n // Unchanged: read content.yaml now and bake it into the bundle as a\n // JSON literal so the SSG / SPA output inlines content exactly as before.\n const projectRoot = config.root || process.cwd()\n\n // Try to find content.yaml in multiple locations\n // VitePress projects have the docs folder as root, so check parent too\n const possiblePaths = [\n path.resolve(projectRoot, contentPath),\n path.resolve(projectRoot, '..', contentPath),\n path.resolve(process.cwd(), contentPath),\n ]\n\n let foundPath: string | undefined\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n foundPath = testPath\n break\n }\n }\n\n if (!foundPath) {\n if (debug) {\n console.log('[dcs-content] No content.yaml found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n console.log('[dcs-content] Using defaults only')\n }\n return {\n define: {\n __DCS_CONTENT__: 'undefined',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n\n try {\n const fileContent = fs.readFileSync(foundPath, 'utf8')\n const content = yaml.load(fileContent) as DcsContentFile\n\n if (debug) {\n console.log(`[dcs-content] Loaded ${foundPath}`)\n console.log(`[dcs-content] Version: ${content.version}`)\n console.log(`[dcs-content] Pages: ${Object.keys(content.pages ?? {}).join(', ') || '(none)'}`)\n console.log(`[dcs-content] Global keys: ${Object.keys(content.global ?? {}).length}`)\n }\n\n return {\n define: {\n __DCS_CONTENT__: JSON.stringify(content),\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n } catch (error) {\n console.warn('[dcs-content] Failed to parse content.yaml:', error)\n return {\n define: {\n __DCS_CONTENT__: 'undefined',\n },\n ssr: { noExternal: DCS_SSR_NO_EXTERNAL },\n }\n }\n },\n\n /**\n * Inject into `<head>` on every HTML request. Two concerns:\n *\n * 1. The constant DCS motion-token `:root` block (`DCS_MOTION_TOKENS_CSS`)\n * — the fleet-wide seam that gives every DCS site the shared `--motion-*`\n * vocabulary. It carries no per-site data, so (unlike the content inject)\n * it is NOT gated on `isDev`: it runs in both `serve` and `build`.\n * It is injected `head` (append), NOT `head-prepend` — C-414. Appending\n * still lands it ABOVE the bundled site CSS (Vite injects the build's\n * `<link rel=stylesheet>` AFTER this `order: 'pre'` hook's tags), so a\n * site's own `:root` (theme `tailwind.css` / `style.css`) can still\n * override a token — while leaving the site's `<meta charset>` first in\n * `<head>` instead of 858 bytes deep. See `motionTokens.ts`.\n *\n * 2. Dev-only: the FRESH on-disk `content.yaml` as an inline\n * `globalThis.__DCS_CONTENT__ = {…}` classic script. Runs on every dev\n * HTML request, so the portal's `?_hc` hard reload re-reads the YAML with\n * no restart. A classic `<script>` in `<head>` executes before the\n * deferred module app entry, so the global is set before the consumer's\n * `useTextContent` setup reads it. Gated on `isDev` so it never runs in\n * `vite`/`vitepress build` (the build path keeps the baked `define`).\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n // (1) Always-on, per the note above: the constant motion-token block.\n const tags: HtmlTagDescriptor[] = [dcsMotionTokensStyleTag()]\n\n // (1b) Build-only: the AI-assistant widget loader. Rides this same\n // fleet-wide seam (a cms bump ships it everywhere with no per-site\n // edits) but is NOT injected into `vite dev` — its idle config\n // fetch would hit the prod API from a non-whitelisted localhost\n // origin and log an uncatchable CORS error for every site dev. The\n // loader is fail-silent and returns null for non-DCS builds (no\n // resolvable site slug), so nothing is injected there.\n if (!isDev) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const agentTag = dcsAgentWidgetLoaderTag({\n projectRoot,\n apiBaseUrl: process.env.VITE_API_BASE_URL,\n })\n if (agentTag) tags.push(agentTag)\n }\n\n // (2) Dev-only fresh content inject.\n if (isDev) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const content = readDcsYamlFresh<DcsContentFile>(\n projectRoot,\n contentPath,\n 'dcs-content',\n debug\n )\n // No file (or unparseable) ⇒ leave the global unset; the consumer's\n // `typeof globalThis.__DCS_CONTENT__` check falls back to defaults.\n if (content !== undefined) {\n if (debug) {\n console.log('[dcs-content] serve: injecting fresh __DCS_CONTENT__ into <head>')\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_CONTENT__', content),\n injectTo: 'head-prepend',\n })\n }\n }\n\n return { html, tags }\n },\n },\n\n // Watch for changes in development.\n //\n // Downgraded from `server.restart()` to a debounced client `full-reload`:\n // freshness already comes from `transformIndexHtml` re-reading the YAML on\n // every HTML request, so all we need on change is to nudge the browser to\n // reload. A `server.restart()` would rebuild VitePress's dev MiniSearch\n // index and can throw \"server restart failed\" on a duplicate heading id —\n // exactly the fragility this fix removes. A `full-reload` does neither.\n configureServer(server) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n\n const watchPaths = [\n path.resolve(projectRoot, contentPath),\n path.resolve(projectRoot, '..', contentPath),\n ].map((p) => path.normalize(p))\n\n watchPaths.forEach((watchPath) => {\n if (fs.existsSync(watchPath)) {\n server.watcher.add(watchPath)\n }\n })\n\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n server.watcher.on('change', (changedPath) => {\n if (!watchPaths.includes(path.normalize(changedPath))) return\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n if (debug) {\n console.log('[dcs-content] content.yaml changed, sending full-reload')\n }\n server.ws.send({ type: 'full-reload' })\n }, 100)\n })\n },\n }\n}\n","/**\n * Build-time responsive-variant lint for DCS customer sites.\n *\n * The 2026-07-03 flagship-excellence review (P7) found desktop pages shipping\n * un-suffixed **full-size** CDN images (e.g. a 321.9 KB hero `47af1e8f….webp`)\n * instead of a `-md`/`-lg` responsive step. That happens when an image reaches\n * the output HTML through a path that does NOT run the `<img>` → `<picture>`\n * transform — content injected via `__DCS_CONTENT__` and then swapped to the\n * base `cdnUrl` by `dcsCdnBuildEnd`, or a hand-authored `<img src>` pointing at\n * a base CDN asset URL.\n *\n * A DCS CDN asset URL has the shape\n * `https://files.<host>/[content/]<slug>/assets/[<dir>/]<uuid>.<ext>`\n * Responsive variants insert a `-sm`/`-md`/`-lg` suffix before the extension\n * (`…<uuid>-md.webp`). Those suffixes contain non-hex letters, so a URL that\n * still matches the *base* pattern below is, by definition, an un-suffixed\n * full-size asset. This lint scans the built HTML's `<img src>` and\n * `<source srcset>` attributes for such URLs and reports (or fails on) them.\n *\n * It is intentionally a **static-output** lint (VitePress generates HTML after\n * both Vite builds finish, so a Vite plugin hook cannot see the SSG output) and\n * is registered via VitePress `buildEnd`.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnBuildEnd, dcsResponsiveImageLint, chainBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * // run the CDN rewrite first, then lint the result\n * buildEnd: chainBuildEnd(dcsCdnBuildEnd(), dcsResponsiveImageLint()),\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\n// ────────────────────────────────────────────────────────────────────────────\n// Detector (pure — unit-testable without a build)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Anchored matcher for a **base** (un-suffixed, full-size) DCS CDN asset URL.\n * Kept aligned with `responsiveImagePlugin`'s `CDN_PATTERN`: the filename stem\n * is `[a-f0-9-]+` (hex UUID), so a responsive variant — `…-sm.webp`,\n * `…-md.webp`, `…-lg.webp` — never matches (each suffix carries a non-hex\n * letter). Query strings / fragments are tolerated after the extension.\n */\nconst BASE_CDN_ASSET =\n /^https?:\\/\\/files\\.[^/]+\\/(?:content\\/)?[^/]+\\/assets\\/(?:[^/]+\\/)*[a-f0-9-]+\\.\\w+(?:[?#].*)?$/i\n\nexport interface ResponsiveImageViolation {\n /** The un-suffixed full-size CDN URL that should have been a responsive variant. */\n url: string\n /** Which element referenced it. */\n tag: 'img' | 'source'\n}\n\n/** True when `url` is a base (un-suffixed, full-size) DCS CDN asset URL. */\nexport function isFullSizeCdnUrl(url: string): boolean {\n return BASE_CDN_ASSET.test(url.trim())\n}\n\nfunction readAttr(tag: string, name: string): string | null {\n const m = tag.match(new RegExp(`\\\\b${name}=(\"([^\"]*)\"|'([^']*)')`, 'i'))\n if (!m) return null\n return m[2] ?? m[3] ?? ''\n}\n\n/**\n * Scan an HTML string and return every `<img src>` / `<source srcset>` reference\n * that resolves to a base (un-suffixed) full-size DCS CDN asset. `srcset`\n * candidates are split on commas and only the URL portion (before the width /\n * density descriptor) is tested. `onerror` and other attributes are ignored —\n * only the actual `src` / `srcset` sources are inspected.\n */\nexport function findFullSizeCdnImages(html: string): ResponsiveImageViolation[] {\n const violations: ResponsiveImageViolation[] = []\n\n for (const m of html.matchAll(/<img\\b[^>]*>/gi)) {\n const src = readAttr(m[0], 'src')\n if (src && isFullSizeCdnUrl(src)) {\n violations.push({ url: src.trim(), tag: 'img' })\n }\n }\n\n for (const m of html.matchAll(/<source\\b[^>]*>/gi)) {\n const srcset = readAttr(m[0], 'srcset')\n if (!srcset) continue\n for (const candidate of srcset.split(',')) {\n const url = candidate.trim().split(/\\s+/)[0]\n if (url && isFullSizeCdnUrl(url)) {\n violations.push({ url, tag: 'source' })\n }\n }\n }\n\n return violations\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// VitePress buildEnd hook\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface DcsResponsiveImageLintOptions {\n /**\n * Throw (fail the build) when full-size images are found. Default `false`\n * (warn only) so the guard can land ahead of the per-site cleanup; flip to\n * `true` in CI once a site's output is clean to prevent regressions.\n */\n failOnViolation?: boolean\n /** File extensions to scan in the output directory. Default `['.html']`. */\n extensions?: string[]\n /** Enable per-file debug logging. */\n debug?: boolean\n}\n\nexport interface ResponsiveImageLintReport {\n filesScanned: number\n violations: Array<ResponsiveImageViolation & { file: string }>\n}\n\n/**\n * VitePress `buildEnd` factory that lints the generated HTML for un-suffixed\n * full-size CDN images. Returns the report (also useful for tests) and either\n * warns or throws depending on `failOnViolation`.\n */\nexport function dcsResponsiveImageLint(options: DcsResponsiveImageLintOptions = {}) {\n const { failOnViolation = false, extensions = ['.html'], debug = false } = options\n\n return async (siteConfig: { outDir: string }): Promise<ResponsiveImageLintReport> => {\n const report: ResponsiveImageLintReport = { filesScanned: 0, violations: [] }\n const outDir = siteConfig.outDir\n if (!outDir || !fs.existsSync(outDir)) return report\n\n const walk = (dir: string) => {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n walk(full)\n } else if (extensions.some((ext) => entry.name.endsWith(ext))) {\n report.filesScanned++\n const html = fs.readFileSync(full, 'utf8')\n if (!html.includes('/assets/')) continue\n const rel = path.relative(outDir, full)\n for (const v of findFullSizeCdnImages(html)) {\n report.violations.push({ ...v, file: rel })\n if (debug) {\n console.log(`[dcs-responsive-lint] ${rel}: <${v.tag}> full-size ${v.url}`)\n }\n }\n }\n }\n }\n\n walk(outDir)\n\n if (report.violations.length > 0) {\n const lines = report.violations\n .map((v) => ` ${v.file}: <${v.tag}> ${v.url}`)\n .join('\\n')\n const summary =\n `[dcs-responsive-lint] ${report.violations.length} full-size CDN image(s) ` +\n `shipped without a -sm/-md/-lg responsive variant across ${report.filesScanned} file(s):\\n${lines}`\n if (failOnViolation) {\n throw new Error(summary)\n }\n console.warn(summary)\n } else if (debug) {\n console.log(\n `[dcs-responsive-lint] clean — scanned ${report.filesScanned} file(s), no full-size images.`\n )\n }\n\n return report\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// buildEnd composition helper\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Compose multiple VitePress `buildEnd` hooks into one (VitePress accepts a\n * single `buildEnd`). Hooks run sequentially in the order given, so a rewrite\n * hook (`dcsCdnBuildEnd`) can precede a lint (`dcsResponsiveImageLint`).\n */\nexport function chainBuildEnd<T>(\n ...hooks: Array<((siteConfig: T) => unknown | Promise<unknown>) | undefined | null>\n): (siteConfig: T) => Promise<void> {\n const active = hooks.filter(\n (h): h is (siteConfig: T) => unknown | Promise<unknown> => typeof h === 'function'\n )\n return async (siteConfig: T) => {\n for (const hook of active) {\n await hook(siteConfig)\n }\n }\n}\n","/**\n * DCS directory-index twins for VitePress `cleanUrls` builds (C-1965).\n *\n * THE DEFECT. A VitePress site built with `cleanUrls: true` emits every\n * non-index page flat: `contact.md` -> `dist/contact.html`. On an Azure Static\n * Web App with no `trailingSlash` rule, `/contact` answers 200 but `/contact/`\n * answers `301 Location: https://<swa-default-host>/contact` - an ABSOLUTE\n * redirect to the `*.azurestaticapps.net` host, because Front Door sends that\n * host as the origin Host and a Free SWA ignores `X-Forwarded-Host`. Measured\n * live on kimduffhomes.com, nateduff.com, bryanduffhomes.com and bryanduff.com\n * (.workboard/records/2026-10-27-lead-C1965-swa-fixture.md section 1).\n *\n * THE FIX, PROVEN ON A DISPOSABLE FREE SWA (same record, section 3f): when both\n * `x.html` and `x/index.html` exist, SWA serves `x.html` for `/x` and\n * `x/index.html` for `/x/`, both 200, no `Location`, in either direction. So for\n * every flat page this writes `<page>/index.html` as a BYTE-IDENTICAL twin of\n * `<page>.html`.\n *\n * WHY STRICT. The two URLs are served by two different files, so a twin that\n * differs from its flat page shows visitors and crawlers two different\n * documents on `/x` and `/x/`. An existing `<page>/index.html` with different\n * bytes is therefore a BUILD FAILURE, never a skip. A page VitePress says it\n * rendered whose `.html` is missing is also fatal: the emitter's model of the\n * build would be wrong.\n *\n * NO CANONICAL OF ITS OWN. The flat page already carries the cms factory's\n * absolute, slash-less canonical (`vitepressTransform.ts`), and a byte copy\n * carries it too, so `/contact/` consolidates onto `/contact`. A self-canonical\n * `/contact/` would split the signal.\n *\n * ORDER. The twin must copy the FINAL bytes. VitePress applies `transformHtml`\n * before it writes each page, and the site's own `buildEnd` (CDN rewrite,\n * site files, pre-launch stamps) runs next; the emitter is chained AFTER that\n * hook. The canonical deploy workflow then injects GA into every `*.html` and\n * re-checks the pairs (site-deploy.yml, \"Assert directory-index twin parity\").\n *\n * THE MANIFEST (C-1965 roll-blocker N2). When `DCS_DIR_INDEX_MANIFEST` names a\n * file, every emitter run writes there the list of twins it validated (twin\n * path, source path, sha256 of the bytes it copied), so the deploy workflow\n * checks the pairs the cms OWNS instead of inferring pairs from the dist. The\n * canonical workflow points it at a run-unique file under `$RUNNER_TEMP`:\n * outside the SWA upload directory (nothing new is served) and outside the\n * site repo (nothing new to ignore or commit). Unset (a local build), nothing\n * is written.\n *\n * TWO ENTRY POINTS, ONE GUARD. `dcsSeoPlugin` installs the emitter\n * automatically on a VitePress build (`dirIndex: false` opts out). A site that\n * wants explicit composition can chain `dcsDirIndexBuildEnd()` into its own\n * `buildEnd`. Both go through the registry symbol\n * `Symbol.for('dcs.cms.dirIndex.installed')` on VitePress's `siteConfig`, which\n * is the same object for the client and the SSR config resolution, so the\n * emitter runs exactly once however many times it is registered.\n *\n * @example Explicit composition (optional - dcsSeoPlugin already installs it)\n * ```ts\n * // .vitepress/config.ts\n * import { chainBuildEnd, dcsCdnBuildEnd, dcsDirIndexBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * cleanUrls: true,\n * buildEnd: chainBuildEnd(dcsCdnBuildEnd(), dcsDirIndexBuildEnd()),\n * })\n * ```\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { chainBuildEnd } from './dcsResponsiveImageLint'\n\n/**\n * The idempotency guard. A REGISTRY symbol (`Symbol.for`), not `Symbol()`: it\n * must be the same key across module instances (the plugin barrel and a\n * site-local import can be two copies) and across the client and SSR config\n * resolutions.\n */\nexport const DIR_INDEX_INSTALLED: unique symbol = Symbol.for('dcs.cms.dirIndex.installed')\n\n/**\n * The environment variable that names the twin manifest file. Read at emit\n * time; an empty or unset value writes no manifest.\n */\nexport const DIR_INDEX_MANIFEST_ENV = 'DCS_DIR_INDEX_MANIFEST'\n\n/** The manifest's `schema` value; the workflow step refuses any other. */\nexport const DIR_INDEX_MANIFEST_SCHEMA = 'dcs.cms.dir-index-manifest/v1'\n\n/** One twin the emitter validated (written, or already present and identical). */\nexport interface DirIndexManifestEntry {\n /** `<page>/index.html`, relative to `outDir`, forward slashes. */\n twin: string\n /** `<page>.html`, relative to `outDir`, forward slashes. */\n source: string\n /** sha256 (hex) of the bytes copied, i.e. the source as the emitter read it. */\n sha256: string\n}\n\n/** The file `DCS_DIR_INDEX_MANIFEST` names, written on every emitter run. */\nexport interface DirIndexManifest {\n schema: typeof DIR_INDEX_MANIFEST_SCHEMA\n /** Absolute build output directory the twins live in. */\n outDir: string\n /** Whether the build had `cleanUrls` on (off: `twins` is empty). */\n cleanUrls: boolean\n /** Sorted by `twin`. */\n twins: DirIndexManifestEntry[]\n}\n\nexport interface EmitDirectoryIndexesOptions {\n /**\n * Where to write the twin manifest. Defaults to\n * `process.env.DCS_DIR_INDEX_MANIFEST`; when neither is set, nothing is\n * written. Relative paths resolve against `process.cwd()`.\n */\n manifestPath?: string\n}\n\n/** Exact index-page exclusion: `index.md` and `foo/index.md`, NOT `reindex.md`. */\nconst INDEX_PAGE = /(^|\\/)index\\.md$/\n\n/** The subset of VitePress's resolved `SiteConfig` the emitter reads. */\nexport interface DirIndexSiteConfig {\n /** Absolute build output directory. */\n outDir: string\n /** Source pages relative to `srcDir`, e.g. `contact.md`, `blogs/post.md`. */\n pages: string[]\n /** VitePress rewrites; a page renders at `rewrites.map[page] ?? page`. */\n rewrites?: { map?: Record<string, string | undefined> }\n /** Twins are emitted only when `cleanUrls` is on. */\n cleanUrls?: boolean\n /** VitePress's single `buildEnd` hook. */\n buildEnd?: (siteConfig: never) => unknown\n}\n\nexport interface DirIndexResult {\n /** Twins written by this run. */\n written: number\n /** Twins already present with identical bytes (left untouched). */\n identical: number\n /** The twin paths (relative to `outDir`, forward slashes) written or found identical. */\n twins: string[]\n /** Absolute path of the manifest written by this run, when one was requested. */\n manifestPath?: string\n}\n\ninterface DirIndexState {\n /** Which entry point installed the guard first. */\n owner: 'auto' | 'manual'\n /** Set once the emitter has run for this build. */\n emitted: boolean\n}\n\ntype GuardedSiteConfig = DirIndexSiteConfig & { [DIR_INDEX_INSTALLED]?: DirIndexState }\n\n/** Thrown for a missing source page or an unequal `<page>/index.html` collision. */\nexport class DirIndexError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DirIndexError'\n }\n}\n\n/**\n * The flat pages that get a twin: every mapped page except index pages\n * (`(^|/)index\\.md$`) and the root `404.md`. Returned as mapped `.md` paths.\n */\nexport function dirIndexCandidates(siteConfig: Pick<DirIndexSiteConfig, 'pages' | 'rewrites'>): string[] {\n const map = siteConfig.rewrites?.map ?? {}\n const out: string[] = []\n for (const page of siteConfig.pages) {\n const mapped = (map[page] || page).replace(/\\\\/g, '/')\n if (!mapped.endsWith('.md')) continue\n if (INDEX_PAGE.test(mapped)) continue\n if (mapped === '404.md') continue\n out.push(mapped)\n }\n return [...new Set(out)].sort()\n}\n\n/** Resolve the manifest destination: the explicit option, else the env var, else none. */\nfunction resolveManifestPath(options: EmitDirectoryIndexesOptions): string | undefined {\n const raw = options.manifestPath ?? process.env[DIR_INDEX_MANIFEST_ENV]\n return raw ? path.resolve(raw) : undefined\n}\n\n/**\n * `p` with its nearest EXISTING ancestor replaced by that ancestor's realpath,\n * so a symlinked or junctioned directory that points into `outDir` is seen as\n * inside it even when the file itself does not exist yet.\n */\nfunction realpathNearest(p: string): string {\n let cur = path.resolve(p)\n const tail: string[] = []\n while (!fs.existsSync(cur)) {\n const parent = path.dirname(cur)\n if (parent === cur) break\n tail.unshift(path.basename(cur))\n cur = parent\n }\n let real = cur\n try {\n real = fs.realpathSync.native(cur)\n } catch {\n /* keep the resolved path */\n }\n return path.join(real, ...tail)\n}\n\n/**\n * Is `p` inside (or equal to) `dir`? Decided on PATH SEGMENTS after resolving\n * symlinked ancestors: `dist/..manifest.json` is inside `dist` (its first\n * segment is `..manifest.json`, not `..`), `dist/../m.json` is not.\n */\nexport function isInsideDir(dir: string, p: string): boolean {\n // The DESTINATION's final component is never followed: the emitter removes\n // and replaces that entry, so a symlink at <outDir>/m.json pointing outside\n // is still a file written INSIDE outDir. Resolve its PARENT, keep its name.\n const abs = path.resolve(p)\n const dest = path.join(realpathNearest(path.dirname(abs)), path.basename(abs))\n const rel = path.relative(realpathNearest(dir), dest)\n if (rel === '') return true\n if (path.isAbsolute(rel)) return false\n return !(rel === '..' || rel.startsWith('..' + path.sep))\n}\n\n/**\n * Remove a manifest left at `DCS_DIR_INDEX_MANIFEST` by an earlier build, for a\n * build whose emitter is DISABLED (`dirIndex: false`). Removal, not an empty\n * manifest: a disabled emitter owns nothing and validated nothing, and \"no\n * manifest\" is exactly how the deploy step reads that (no pairs passes, any\n * pair is un-owned and fails), so a stale list from another build can never\n * vouch for this dist. A regular file or a symlink (unlinked, never followed)\n * is removed; a directory is not. Returns the path removed.\n */\nexport function clearDirIndexManifest(manifestPath = process.env[DIR_INDEX_MANIFEST_ENV]): string | undefined {\n if (!manifestPath) return undefined\n const file = path.resolve(manifestPath)\n try {\n const st = fs.lstatSync(file)\n if (!st.isFile() && !st.isSymbolicLink()) return undefined\n } catch {\n return undefined\n }\n // unlink, never follow: a symlinked stale manifest goes, its target stays.\n fs.unlinkSync(file)\n return file\n}\n\nconst sha256 = (bytes: Buffer) => crypto.createHash('sha256').update(bytes).digest('hex')\n\n/** Write the manifest (tmp + rename, so a reader never sees half a file). */\nfunction writeManifest(file: string, manifest: DirIndexManifest): void {\n fs.mkdirSync(path.dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n fs.writeFileSync(tmp, `${JSON.stringify(manifest, null, 2)}\\n`)\n fs.renameSync(tmp, file)\n}\n\n/**\n * Write a byte-identical `<page>/index.html` for every flat page of a\n * `cleanUrls` VitePress build. Validates every pair BEFORE writing anything,\n * so a failing build leaves `outDir` exactly as VitePress produced it.\n *\n * When a manifest path is set (option or `DCS_DIR_INDEX_MANIFEST`), any file\n * already there is removed first and a fresh manifest is written on success,\n * including the `cleanUrls: false` no-op (an empty list). A refused build\n * leaves no manifest. A manifest path inside `outDir` is refused: it would\n * ship with the site.\n */\nexport function emitDirectoryIndexes(\n siteConfig: DirIndexSiteConfig,\n options: EmitDirectoryIndexesOptions = {}\n): DirIndexResult {\n const outDir = siteConfig.outDir\n const manifestPath = resolveManifestPath(options)\n if (manifestPath) {\n if (isInsideDir(outDir, manifestPath)) {\n throw new DirIndexError(\n `[dcs-dir-index] ${DIR_INDEX_MANIFEST_ENV}=${manifestPath} is inside outDir ${outDir}; ` +\n `the manifest must not ship with the site. Point it outside the build output.`\n )\n }\n fs.rmSync(manifestPath, { force: true })\n }\n\n if (siteConfig.cleanUrls !== true) {\n if (!manifestPath) return { written: 0, identical: 0, twins: [] }\n writeManifest(manifestPath, { schema: DIR_INDEX_MANIFEST_SCHEMA, outDir: path.resolve(outDir), cleanUrls: false, twins: [] })\n return { written: 0, identical: 0, twins: [], manifestPath }\n }\n\n const missing: string[] = []\n const unequal: string[] = []\n const toWrite: Array<{ src: string; dst: string; rel: string; srcRel: string; bytes: Buffer }> = []\n const identicalRel: string[] = []\n const entries: DirIndexManifestEntry[] = []\n\n for (const page of dirIndexCandidates(siteConfig)) {\n const stem = page.slice(0, -'.md'.length)\n const srcRel = `${stem}.html`\n const dstRel = `${stem}/index.html`\n const src = path.join(outDir, srcRel)\n const dst = path.join(outDir, dstRel)\n\n if (!fs.existsSync(src) || !fs.statSync(src).isFile()) {\n missing.push(`${page} -> ${srcRel}`)\n continue\n }\n const bytes = fs.readFileSync(src)\n\n if (fs.existsSync(dst)) {\n const existing = fs.statSync(dst).isFile() ? fs.readFileSync(dst) : null\n if (existing && existing.equals(bytes)) {\n identicalRel.push(dstRel)\n entries.push({ twin: dstRel, source: srcRel, sha256: sha256(bytes) })\n } else {\n unequal.push(`${srcRel} != ${dstRel}`)\n }\n continue\n }\n toWrite.push({ src, dst, rel: dstRel, srcRel, bytes })\n }\n\n const problems: string[] = []\n if (missing.length > 0) {\n problems.push(\n `${missing.length} page(s) VitePress lists have no rendered flat HTML:\\n` +\n missing.map((m) => ` ${m}`).join('\\n')\n )\n }\n if (unequal.length > 0) {\n problems.push(\n `${unequal.length} existing directory index(es) differ from their flat page. SWA serves ` +\n `<page>.html for /page and <page>/index.html for /page/, so these would publish two ` +\n `different documents on one route:\\n` +\n unequal.map((u) => ` ${u}`).join('\\n')\n )\n }\n if (problems.length > 0) {\n throw new DirIndexError(`[dcs-dir-index] build refused (nothing written).\\n${problems.join('\\n')}`)\n }\n\n for (const t of toWrite) {\n fs.mkdirSync(path.dirname(t.dst), { recursive: true })\n fs.writeFileSync(t.dst, t.bytes)\n entries.push({ twin: t.rel, source: t.srcRel, sha256: sha256(t.bytes) })\n }\n\n const twins = [...toWrite.map((t) => t.rel), ...identicalRel].sort()\n console.log(`[dcs-dir-index] twins written=${toWrite.length} identical=${identicalRel.length}`)\n if (!manifestPath) return { written: toWrite.length, identical: identicalRel.length, twins }\n\n entries.sort((a, b) => (a.twin < b.twin ? -1 : a.twin > b.twin ? 1 : 0))\n writeManifest(manifestPath, { schema: DIR_INDEX_MANIFEST_SCHEMA, outDir: path.resolve(outDir), cleanUrls: true, twins: entries })\n console.log(`[dcs-dir-index] manifest ${manifestPath} (${entries.length} twin(s))`)\n return { written: toWrite.length, identical: identicalRel.length, twins, manifestPath }\n}\n\n/** Run the emitter at most once per build (per `siteConfig`). */\nfunction emitOnce(siteConfig: GuardedSiteConfig): DirIndexResult | undefined {\n const state = siteConfig[DIR_INDEX_INSTALLED]\n if (state?.emitted) return undefined\n if (state) state.emitted = true\n return emitDirectoryIndexes(siteConfig)\n}\n\n/** Duck-type check: is this a VitePress resolved `SiteConfig`? */\nexport function isVitePressSiteConfig(value: unknown): value is DirIndexSiteConfig {\n if (!value || typeof value !== 'object') return false\n const v = value as Partial<DirIndexSiteConfig>\n return typeof v.outDir === 'string' && Array.isArray(v.pages)\n}\n\n/**\n * The AUTOMATIC entry point (called by `dcsSeoPlugin` on a VitePress build).\n * Wraps `siteConfig.buildEnd` so the site's own hook runs FIRST and the\n * emitter copies its final output. Returns `false` when already installed\n * (the client and SSR builds both resolve config; a second plugin instance\n * may also call this).\n */\nexport function installDirIndex(siteConfig: DirIndexSiteConfig): boolean {\n const guarded = siteConfig as GuardedSiteConfig\n if (guarded[DIR_INDEX_INSTALLED]) return false\n guarded[DIR_INDEX_INSTALLED] = { owner: 'auto', emitted: false }\n const original = siteConfig.buildEnd as ((sc: GuardedSiteConfig) => unknown) | undefined\n siteConfig.buildEnd = chainBuildEnd<GuardedSiteConfig>(\n original ? (sc) => original.call(sc, sc) : undefined,\n (sc) => {\n emitOnce(sc)\n }\n ) as DirIndexSiteConfig['buildEnd']\n return true\n}\n\n/**\n * The MANUAL entry point: a VitePress `buildEnd` hook for sites that compose\n * their hooks explicitly. It shares the automatic guard:\n *\n * - If `dcsSeoPlugin` already installed the emitter, this DEFERS to it (the\n * automatic wrapper runs after the site's whole `buildEnd`, so it copies the\n * final bytes) and does nothing itself.\n * - Otherwise it claims the guard and emits, once, however many times it is\n * chained.\n */\nexport function dcsDirIndexBuildEnd(): (siteConfig: DirIndexSiteConfig) => Promise<void> {\n return async (siteConfig: DirIndexSiteConfig) => {\n const guarded = siteConfig as GuardedSiteConfig\n const state = guarded[DIR_INDEX_INSTALLED]\n if (state?.owner === 'auto') return\n if (!state) guarded[DIR_INDEX_INSTALLED] = { owner: 'manual', emitted: false }\n emitOnce(guarded)\n }\n}\n","/**\n * The production {@link RouteRenderer}: a headless-Playwright renderer that\n * drives the JUST-BUILT SPA from `dist/` and returns each route's rendered\n * `#app` body.\n *\n * Design choices (see `bodyPrerender.ts` for the why):\n * - **Renders the PRODUCTION bundle**, so `import.meta.env.DEV` is already\n * `false` and the dev-only fabrication gates render their honest empty state\n * (A-34 safety by construction — no separate SSR bundle to leak defaults).\n * - **Playwright is dynamically imported and OPTIONAL.** If it (or a browser)\n * is unavailable, the factory returns `null` and the caller no-ops (the head\n * + JSON-LD emit is untouched, so the build never breaks on missing infra).\n * Playwright is already a universal devDependency of the DCS site fleet\n * (snapshot capture), so this activates on a cms bump with no per-site edit.\n * - **Offline + deterministic.** A tiny built-in static server serves `dist/`;\n * every EXTERNAL request (CDN images, App Insights, the site-auth probe) is\n * aborted. The DOM still carries those `<img>`/`<link>` tags (crawler-visible)\n * while the render stays fast and free of expected offline network noise.\n * - **Nothing leaves, not even at page close (C-1962).** The same static\n * server is Chromium's only proxy, and it refuses every request that is not\n * for its own origin. `page.route` alone is not enough: its interception\n * belongs to the page target, and a `sendBeacon` / keepalive `fetch` fired\n * from `pagehide`/`visibilitychange` during `page.close()` is dispatched after\n * that interception is gone. The proxy lives in the browser's network\n * service, which carries those sends too.\n * - **Crash-only fail-loud.** Only an uncaught page exception or a failed mount\n * is reported as a fatal error; benign offline console errors are not. The\n * caller turns a fatal error into a red build.\n */\n\nimport http from 'node:http'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { AddressInfo } from 'node:net'\nimport type { Duplex } from 'node:stream'\nimport type { RenderedRoute, RouteRenderer } from './bodyPrerender'\n\n/**\n * The URL the renderer navigates to for a route (C-1553).\n *\n * The prerender drives the site's PRODUCTION bundle, connection string and all.\n * Every external request is aborted by the route filter below, but Chromium's\n * `navigator.sendBeacon` is not routed through `page.route`, so the telemetry\n * SDK's unload flush still reached the customer's production App Insights\n * component: measured 2026-09-08 on ai-boogie-babies (22 rows in 30 d) and\n * ai-mi-handyman (33), every one `HeadlessChrome` with `Target 127.0.0.1:<port>`,\n * one burst per deploy. Marking the navigation with the C-614 synthetic-capture\n * parameter makes the site's telemetry boot decline BEFORE the SDK exists, which\n * is the same contract the snapshot capture already honours. The marker is a\n * query parameter the head emitter never reads (canonical/og:url come from the\n * site config, not `location`), so the baked head is unchanged.\n */\nexport function prerenderNavigationUrl(origin: string, routePath: string): string {\n const url = new URL(routePath, origin)\n url.searchParams.set('dcs-no-telemetry', '')\n return url.toString()\n}\n\n/** A started static server plus its `http://127.0.0.1:<port>` origin. */\ninterface StaticServer {\n origin: string\n /** Requests the gate refused (`METHOD host/path`, no query), oldest first. */\n blocked: string[]\n close: () => Promise<void>\n}\n\n/** Cap on the refused-request log so a chatty site cannot grow it unbounded. */\nconst BLOCKED_LOG_CAP = 1000\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.gif': 'image/gif',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain; charset=utf-8',\n '.xml': 'application/xml; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n}\n\n/**\n * Serve `dist/` over loopback with directory-index resolution\n * (`/services` → `/services/index.html`) and an SPA fallback to the root\n * `index.html` for any path with no matching file/dir. Bound to `127.0.0.1:0`\n * so the OS assigns a free port; nothing is exposed off-box.\n *\n * It is ALSO the browser's proxy (C-1962): Chromium sends every request here in\n * absolute form (`POST http://host/path`), including loopback ones (Playwright\n * forces `<-loopback>` into the bypass list) and `CONNECT host:443` for TLS. A\n * request for any origin other than this server's own is answered 403 and\n * logged; a `CONNECT` is refused by destroying the socket. Nothing is ever\n * forwarded, so no request can leave the box whatever the page does or when.\n */\nasync function startStaticServer(outDir: string): Promise<StaticServer> {\n let origin = ''\n const blocked: string[] = []\n const refuse = (entry: string) => {\n if (blocked.length < BLOCKED_LOG_CAP) blocked.push(entry)\n }\n\n const server = http.createServer((req, res) => {\n let url: URL\n try {\n url = new URL(req.url ?? '/', origin)\n } catch {\n res.writeHead(400, { Connection: 'close' })\n res.end()\n return\n }\n // Absolute-form request for another origin (another host OR another port on\n // loopback): the page asked the proxy to reach off-origin. Refuse it.\n if (url.origin !== origin) {\n refuse(`${req.method ?? 'GET'} ${url.host}${url.pathname}`)\n res.writeHead(403, { Connection: 'close' })\n res.end()\n return\n }\n\n let pathname = '/'\n try {\n pathname = decodeURIComponent(url.pathname)\n } catch {\n pathname = '/'\n }\n\n // Resolve within outDir; reject path traversal.\n const resolved = path.resolve(outDir, '.' + pathname)\n if (resolved !== outDir && !resolved.startsWith(outDir + path.sep)) {\n res.writeHead(403)\n res.end()\n return\n }\n\n let filePath = resolved\n try {\n const stat = fs.statSync(filePath)\n if (stat.isDirectory()) filePath = path.join(filePath, 'index.html')\n } catch {\n // Missing path: a request for an asset (has an extension) is a genuine 404;\n // a route-shaped request falls back to the SPA shell.\n if (path.extname(pathname)) {\n res.writeHead(404)\n res.end()\n return\n }\n filePath = path.join(outDir, 'index.html')\n }\n\n fs.readFile(filePath, (err, buf) => {\n if (err) {\n res.writeHead(404)\n res.end()\n return\n }\n res.writeHead(200, {\n 'Content-Type': CONTENT_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream',\n })\n res.end(buf)\n })\n })\n\n // TLS (and ws/wss) through a proxy arrives as CONNECT; this server never\n // tunnels, so every one of them is off-origin by definition.\n server.on('connect', (req: http.IncomingMessage, socket: Duplex) => {\n refuse(`CONNECT ${req.url ?? ''}`)\n socket.destroy()\n })\n\n await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))\n const addr = server.address() as AddressInfo\n origin = `http://127.0.0.1:${addr.port}`\n\n return {\n origin,\n blocked,\n close: () =>\n new Promise<void>((resolve) => {\n server.close(() => resolve())\n // Drop idle proxy keep-alive sockets so close() cannot hang on them.\n server.closeAllConnections()\n }),\n }\n}\n\n/** Options for {@link createPlaywrightRenderer}. */\nexport interface PlaywrightRendererOptions {\n /** Absolute path to the built SPA output directory (`dist`). */\n outDir: string\n /** Per-route navigation + settle budget (ms). Default 30000 nav, 15000 mount. */\n navTimeoutMs?: number\n mountTimeoutMs?: number\n /** Extra quiet settle after mount for post-render microtasks (ms). Default 250. */\n settleMs?: number\n debug?: boolean\n}\n\n/** A ready renderer plus a `close()` that tears down the browser + server. */\nexport interface PlaywrightRendererHandle {\n renderer: RouteRenderer\n close: () => Promise<void>\n /**\n * Off-origin requests the proxy gate refused so far (`METHOD host/path`, or\n * `CONNECT host:port`), oldest first, capped. Requests `page.route` aborted\n * before they reached the network are not in it: this is what got PAST the\n * page-level block and was stopped at the browser level.\n */\n blockedRequests: () => readonly string[]\n}\n\n// Minimal structural types for the OPTIONAL, dynamically-imported `playwright`\n// surface — avoids a hard type/dependency on the package (it is not a cms\n// devDependency; it resolves from the consuming site at build time).\ninterface PwConsoleMessage {\n type(): string\n text(): string\n}\ninterface PwPage {\n on(event: 'pageerror', cb: (err: Error) => void): void\n on(event: 'console', cb: (msg: PwConsoleMessage) => void): void\n route(url: string, handler: (route: PwRoute) => unknown): Promise<void>\n goto(url: string, opts: { waitUntil: string; timeout: number }): Promise<unknown>\n waitForFunction(fn: () => unknown, arg?: unknown, opts?: { timeout: number }): Promise<unknown>\n waitForTimeout(ms: number): Promise<void>\n $eval(sel: string, fn: (el: Element) => string): Promise<string>\n evaluate<T>(fn: () => T): Promise<T>\n close(): Promise<void>\n}\ninterface PwRoute {\n request(): { url(): string }\n abort(): Promise<void>\n continue(): Promise<void>\n}\ninterface PwContext {\n newPage(): Promise<PwPage>\n close(): Promise<void>\n}\ninterface PwBrowser {\n newContext(opts?: unknown): Promise<PwContext>\n close(): Promise<void>\n}\n\n/**\n * Build the headless-Playwright renderer, or return `null` when Playwright / a\n * browser is unavailable (the caller then no-ops — head + JSON-LD are already\n * emitted, so the build is unaffected). Never throws on missing infra.\n */\nexport async function createPlaywrightRenderer(\n options: PlaywrightRendererOptions\n): Promise<PlaywrightRendererHandle | null> {\n const {\n outDir,\n navTimeoutMs = 30000,\n mountTimeoutMs = 15000,\n settleMs = 250,\n debug = false,\n } = options\n\n // Optional dependency: resolve `playwright` from the consuming site. The\n // computed specifier keeps the bundler from trying to resolve it at build time.\n let chromium: { launch(opts?: unknown): Promise<PwBrowser> } | undefined\n try {\n const specifier = 'playwright'\n const pw = (await import(/* @vite-ignore */ specifier)) as {\n chromium?: { launch(opts?: unknown): Promise<PwBrowser> }\n }\n chromium = pw.chromium\n } catch {\n console.warn(\n '[dcs-seo] body-prerender: `playwright` is not installed; skipping body ' +\n 'prerender (head + JSON-LD still emitted). `pnpm add -D playwright` to enable.'\n )\n return null\n }\n if (!chromium) {\n console.warn('[dcs-seo] body-prerender: playwright has no chromium export; skipping.')\n return null\n }\n\n // The server starts FIRST because it is also the browser's proxy (C-1962):\n // Chromium is launched pointing at it, so it must exist before the launch.\n const server = await startStaticServer(outDir)\n\n let browser: PwBrowser\n try {\n browser = await chromium.launch({ headless: true, proxy: { server: server.origin } })\n } catch (err) {\n await server.close().catch(() => {})\n console.warn(\n '[dcs-seo] body-prerender: failed to launch Chromium (run ' +\n '`npx playwright install chromium`); skipping body prerender:',\n err instanceof Error ? err.message : err\n )\n return null\n }\n\n // From here on a LIVE Chromium process is owned by this function, and the only\n // thing that can ever close it is the `close()` returned at the bottom. If any\n // step between the launch and that return throws, the caller receives a\n // rejection and no handle — so nothing is left holding a reference to the\n // browser, and it survives as an orphan process plus the open handles that\n // keep its host alive (a `vite build`, or a vitest worker). C-488: unwind what\n // we managed to construct, in reverse, before letting the error out.\n let context: PwContext\n try {\n context = await browser.newContext({ reducedMotion: 'reduce' })\n } catch (err) {\n await browser.close().catch(() => {})\n await server.close().catch(() => {})\n throw err\n }\n\n const renderer: RouteRenderer = {\n async renderRoute(routePath: string): Promise<RenderedRoute> {\n const page = await context.newPage()\n const errors: string[] = []\n page.on('pageerror', (err) => errors.push(`pageerror: ${err.message}`))\n if (debug) {\n page.on('console', (msg) => {\n if (msg.type() === 'error') console.log(`[dcs-seo] (console) ${msg.text()}`)\n })\n }\n\n // Keep the render offline + fast: serve our own origin, abort everything\n // else. The DOM keeps external <img>/<link> tags regardless. Compare the\n // parsed origin, not a string prefix — `http://127.0.0.1:<port>@evil.com/…`\n // starts with our origin but resolves to evil.com. (Perf/noise gate, not a\n // security boundary — the trust boundary is that we run the site's own\n // production bundle.)\n await page.route('**/*', (route) => {\n let sameOrigin = false\n try {\n sameOrigin = new URL(route.request().url()).origin === server.origin\n } catch {\n sameOrigin = false\n }\n // Swallow the continue/abort rejection that races page.close (\"Route is\n // already handled\" / target closed) — an unhandled rejection would crash\n // the vite process under Node's throw-on-unhandled default.\n if (sameOrigin) {\n route.continue().catch(() => {})\n } else {\n route.abort().catch(() => {})\n }\n })\n\n try {\n await page.goto(prerenderNavigationUrl(server.origin, routePath), {\n waitUntil: 'load',\n timeout: navTimeoutMs,\n })\n // The app mounts into #app; wait until it has real children (a failed\n // mount / crash never satisfies this → timeout → fatal error below).\n await page.waitForFunction(\n () => {\n const el = document.querySelector('#app')\n return !!el && el.children.length > 0\n },\n undefined,\n { timeout: mountTimeoutMs }\n )\n if (settleMs > 0) await page.waitForTimeout(settleMs)\n const bodyHtml = await page.$eval('#app', (el) => el.innerHTML)\n // P1: read the POST-MOUNT <head> from the same render. This is what a\n // JS-rendering crawler (and every human) sees, and it is compared against\n // the baked <head> already on disk — see `headHonesty.ts`. The LAST\n // description wins because that is what unhead leaves in place after it\n // replaces the baked one; the count is carried so a duplicate is visible.\n const head = await page.evaluate(() => {\n const metas = Array.from(\n document.querySelectorAll('meta[name=\"description\" i]')\n ) as HTMLMetaElement[]\n return {\n title: document.title ?? null,\n description: metas.length ? metas[metas.length - 1].getAttribute('content') : null,\n descriptionCount: metas.length,\n }\n })\n return { bodyHtml: bodyHtml ?? '', errors, head }\n } catch (err) {\n // A nav/mount timeout is itself a fatal render failure — report it so the\n // caller fails the build loud rather than shipping an empty body.\n errors.push(err instanceof Error ? err.message : String(err))\n return { bodyHtml: '', errors }\n } finally {\n await page.close()\n }\n },\n }\n\n // C-488: `close()` is called from a `finally` (see `runBodyPrerender`), and a\n // caller that also closes defensively — or an error path and a normal path\n // that both reach the same `finally` — can call it twice. Memoise the teardown\n // so it is idempotent: the second caller awaits the SAME settled promise\n // instead of re-entering `context.close()` / `browser.close()` on already-torn-\n // down handles and racing the first teardown that is still in flight. Each step\n // is individually caught, so teardown reports success once everything it owns\n // is down and never surfaces a shutdown error as a build failure.\n let teardown: Promise<void> | null = null\n\n return {\n renderer,\n blockedRequests: () => server.blocked.slice(),\n close() {\n teardown ??= (async () => {\n try {\n await context.close()\n } catch {\n /* ignore */\n }\n try {\n await browser.close()\n } catch {\n /* ignore */\n }\n try {\n await server.close()\n } catch {\n /* ignore */\n }\n })()\n return teardown\n },\n }\n}\n","/**\n * Per-route sitemap `<lastmod>` derived from git (RFQ-002427 L1a, cms 0.14.0).\n *\n * OPT-IN AND BEST-EFFORT. The factory never infers a lastmod by default: a URL\n * carries its per-route `.dcs/pages.yaml` date or no `<lastmod>`. This walk\n * runs only for a site that sets `.dcs/seo.yaml` `sitemap.lastmodFromGit:\n * true` (or the `gitLastmod` option). Known gaps the opt-in accepts:\n * composables/stores/lib/utils are excluded, not inspected (content a page\n * reads through them is not dated unless re-included via `lastmodExclude`\n * `!glob`); markdown includes (`<!--@include:-->`) are not traced; a VitePress\n * page with a custom frontmatter `layout:` is omitted, not traced; runtime\n * data (API fetches, live artifacts) is never dated.\n *\n * The sitemap rule: a `<lastmod>` is accurate for its URL, or it is omitted.\n * Never a build-time stamp, and never one site-wide date on every URL (the\n * kineticenergypt F4 defect: all 52 URLs carried seo.yaml `lastUpdated`, stale\n * on 100 % of them).\n *\n * INVARIANT: a route gets a git-derived lastmod only when EVERY material\n * content source of that route is tracked and dated; otherwise that route's\n * lastmod is omitted.\n *\n * Precedence, applied by `buildSitemapXml`:\n * 1. a per-route `lastmod` / `lastUpdated` / `dateModified` on the\n * `.dcs/pages.yaml` entry (validated);\n * 2. the git-derived date from here = the NEWEST of\n * (a) the route's view or markdown file,\n * (b) every local module reachable from it through other content modules\n * (transitive, shared or not), never counting or walking into the\n * non-content exclusions ({@link DEFAULT_LASTMOD_EXCLUDE} plus\n * `.dcs/seo.yaml` `sitemap.lastmodExclude`),\n * (c) the route's own content in `.dcs/content.yaml`: the newest commit\n * that changed `pages.<slug>` or a `global` key the route's sources\n * reference by name (parsed-subtree diff, commit by commit, capped at\n * {@link CONTENT_WALK_LIMIT} commits);\n * 3. nothing: `<lastmod>` is omitted.\n *\n * A route is omitted (no git date) when any material source cannot be\n * accounted for: no resolvable view, an import that resolves to no file and is\n * not an installed package (virtual modules, unknown aliases), a VitePress\n * markdown component tag with no theme registration, a VitePress data loader\n * whose inputs are not literal globs, an untracked or locally modified source,\n * or a content.yaml walk that hit the cap without finding the change.\n *\n * Git-derived dates are withheld for ALL routes when git is unavailable, the\n * clone is shallow (`git rev-parse --is-shallow-repository`), or 3+ dated\n * routes ALL share one single date (the uniform-stamp signature). A partial\n * overlap from a real bulk commit is accurate and kept.\n *\n * Modelled on lane L3's web/scripts/generate-sitemap.mjs (169eb73f8,\n * acebc7a75: transitive content-module walk, NON_CONTENT_SOURCES, one\n * `git log --name-only --cc` prime walk so merge resolutions count).\n */\n\nimport { execFileSync } from 'node:child_process'\nimport { builtinModules } from 'node:module'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { PageRouteEntry } from '../seo/pagesManifest'\n\n/** Runs `git <args>` in `cwd` and returns stdout; throws on any failure. */\nexport type GitRunner = (args: string[], cwd: string) => string\n\n/** Why git-derived dates were withheld for the whole site (undefined = used). */\nexport type RouteLastmodWithheld = 'git-unavailable' | 'shallow' | 'identical-dates'\n\n/** Why ONE route got no git-derived date. */\nexport type RouteLastmodOmitted =\n | 'no-source'\n | 'unresolved-import'\n | 'unresolved-component'\n | 'untracked-source'\n | 'data-loader'\n | 'undated-source'\n | 'content-walk-cap'\n | 'content-untracked'\n | 'custom-layout'\n\n/** With this many or more dated routes all on ONE date, every git date is withheld. */\nexport const IDENTICAL_LASTMOD_ROUTE_LIMIT = 3\n\n/** content.yaml commits walked per site before an unanswered route is omitted. */\nexport const CONTENT_WALK_LIMIT = 300\n\n/**\n * Local modules that never count toward a page's lastmod and are not walked\n * into: app shell and chrome, non-content code, styles, tests, and the `.dcs`\n * metadata files (content.yaml is dated per route by (c) instead). Globs are\n * matched against the path relative to `projectRoot`; a glob without `/`\n * matches the basename. A site extends this with `.dcs/seo.yaml`\n * `sitemap.lastmodExclude`, where a `!glob` entry re-includes.\n */\nexport const DEFAULT_LASTMOD_EXCLUDE: readonly string[] = [\n // App shell, routing, entry points\n 'App.vue',\n 'main.{ts,js,mts,mjs}',\n '**/router/**',\n // Layouts (VitePress theme Layout.vue, any layouts/ dir) and theme/config shell\n 'Layout.vue',\n '**/layouts/**',\n '**/.vitepress/config.*',\n '**/.vitepress/theme/index.*',\n // Site-wide header / footer / nav / banner chrome\n '{App,Site,Main,Global,Top,Page,The,Mobile,}{Header,Footer,Nav,NavBar,Navbar,Navigation,NavMenu,Banner,AnnouncementBanner}.vue',\n // Non-content code\n '**/composables/**',\n '**/stores/**',\n '**/lib/**',\n '**/utils/**',\n '**/components/ui/**',\n // Styles and tests\n '*.{css,scss,sass,less,styl,pcss,postcss}',\n '*.{test,spec}.*',\n '**/__tests__/**',\n // DCS metadata: seo/pages/site are head + registry, content is dated per route\n '**/.dcs/{seo,pages,site,content}.yaml',\n '**/node_modules/**',\n]\n\nexport interface DeriveRouteLastmodsOptions {\n routes: PageRouteEntry[]\n /** Directory the source paths resolve against. */\n projectRoot: string\n /**\n * Site override for a route's ENTRY files (absolute, or relative to\n * `projectRoot`); the content-module walk still runs from them. Return\n * `undefined` for the default mapping, `[]` to give the route no git date.\n */\n sourcesForRoute?: (route: PageRouteEntry) => string[] | undefined\n /** `.dcs/content.yaml` path (absolute or projectRoot-relative). Default: searched. */\n contentPath?: string\n /** Extra exclusion globs (`.dcs/seo.yaml` `sitemap.lastmodExclude`); `!glob` re-includes. */\n exclude?: string[]\n /** content.yaml commits to walk (default {@link CONTENT_WALK_LIMIT}). */\n contentWalkLimit?: number\n /** Injectable git runner (tests). Defaults to a real `git` subprocess. */\n git?: GitRunner\n debug?: boolean\n}\n\nexport interface DeriveRouteLastmodsResult {\n /** route.path → ISO-8601 committer date of the newest change to its material sources. */\n lastmods: Map<string, string>\n /** Set when every git-derived date was withheld, with the reason. */\n withheld?: RouteLastmodWithheld\n /** route.path → why that route got no date (only routes the walk reached). */\n omitted: Map<string, RouteLastmodOmitted>\n /** route.path → the material source files that were dated (absolute). */\n sources: Map<string, string[]>\n}\n\nconst defaultGit: GitRunner = (args, cwd) =>\n execFileSync('git', args, {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n timeout: 60_000,\n maxBuffer: 256 * 1024 * 1024,\n windowsHide: true,\n })\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Route → entry file\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `how-it-works` → `HowItWorks`; `home` → `Home`. */\nfunction toPascal(value: string): string {\n return value\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n}\n\n/**\n * The conventional entry files for a route, relative to `projectRoot`, in\n * priority order. Covers the SPA layout (`src/views/<Name>View.vue`,\n * `src/pages/<Name>.vue`) and the VitePress layout (`<path>.md`,\n * `<path>/index.md`, under the root or `docs/`). The FIRST that exists is the\n * route's entry.\n */\nexport function defaultRouteSourceCandidates(route: PageRouteEntry): string[] {\n const rel = route.path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n const isHome = rel === ''\n const names = new Set<string>()\n const slugName = toPascal(route.slug || '')\n if (slugName) names.add(slugName)\n const lastSegment = rel.split('/').pop() ?? ''\n const segName = toPascal(lastSegment)\n if (segName) names.add(segName)\n if (isHome) names.add('Home')\n\n const out: string[] = []\n for (const name of names) {\n out.push(`src/views/${name}View.vue`, `src/views/${name}.vue`, `src/pages/${name}.vue`, `src/pages/${name}View.vue`)\n }\n if (isHome) {\n out.push('index.md', 'docs/index.md')\n } else {\n out.push(`${rel}.md`, `${rel}/index.md`, `docs/${rel}.md`, `docs/${rel}/index.md`)\n }\n return out\n}\n\nfunction isFile(abs: string): boolean {\n try {\n return fs.statSync(abs).isFile()\n } catch {\n return false\n }\n}\n\nfunction routeEntries(\n route: PageRouteEntry,\n projectRoot: string,\n sourcesForRoute: DeriveRouteLastmodsOptions['sourcesForRoute']\n): string[] {\n const custom = sourcesForRoute?.(route)\n if (custom) {\n return [...new Set(custom.filter((c) => typeof c === 'string' && c).map((c) => path.resolve(projectRoot, c)))].filter(isFile)\n }\n const first = defaultRouteSourceCandidates(route)\n .map((c) => path.resolve(projectRoot, c))\n .find(isFile)\n return first ? [first] : []\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Globs\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/** Minimal glob → RegExp: `**`, `*`, `?`, `{a,b}` (alternatives literal or wildcard). */\nexport function lastmodGlobToRegExp(glob: string): RegExp {\n const convert = (g: string): string => {\n let re = ''\n for (let i = 0; i < g.length; i++) {\n const c = g[i]\n if (c === '*') {\n if (g[i + 1] === '*') {\n if (g[i + 2] === '/') {\n re += '(?:.*/)?'\n i += 2\n } else {\n re += '.*'\n i += 1\n }\n } else {\n re += '[^/]*'\n }\n } else if (c === '?') {\n re += '[^/]'\n } else if (c === '{') {\n const end = g.indexOf('}', i)\n if (end > i) {\n re += '(?:' + g.slice(i + 1, end).split(',').map(convert).join('|') + ')'\n i = end\n } else {\n re += '\\\\{'\n }\n } else {\n re += escapeRe(c)\n }\n }\n return re\n }\n return new RegExp('^' + convert(glob) + '$')\n}\n\nfunction toPosix(p: string): string {\n return p.split(path.sep).join('/')\n}\n\nfunction makeExcluder(projectRoot: string, extra: string[], alsoExcludeAbs: string[]) {\n const plain = [...DEFAULT_LASTMOD_EXCLUDE, ...extra.filter((g) => !g.startsWith('!'))].map((g) => ({\n re: lastmodGlobToRegExp(g),\n base: !g.includes('/'),\n }))\n const reinclude = extra\n .filter((g) => g.startsWith('!'))\n .map((g) => ({ re: lastmodGlobToRegExp(g.slice(1)), base: !g.slice(1).includes('/') }))\n const fixed = new Set(alsoExcludeAbs.map((a) => path.resolve(a).toLowerCase()))\n const test = (rules: Array<{ re: RegExp; base: boolean }>, rel: string) =>\n rules.some((r) => r.re.test(r.base ? rel.split('/').pop() ?? rel : rel))\n return (abs: string): boolean => {\n if (fixed.has(path.resolve(abs).toLowerCase())) return true\n const rel = toPosix(path.relative(projectRoot, abs))\n if (!test(plain, rel)) return false\n return !test(reinclude, rel)\n }\n}\n\n/** Expand a glob (absolute, posix) to existing files. */\nfunction expandGlob(absPattern: string): string[] {\n const posix = toPosix(absPattern)\n const firstWild = posix.search(/[*?{]/)\n if (firstWild < 0) return isFile(absPattern) ? [path.resolve(absPattern)] : []\n const baseDir = posix.slice(0, posix.lastIndexOf('/', firstWild))\n const re = lastmodGlobToRegExp(posix)\n const out: string[] = []\n const walk = (dir: string, depth: number) => {\n if (depth > 12) return\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const e of entries) {\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = path.join(dir, e.name)\n if (e.isDirectory()) walk(full, depth + 1)\n else if (e.isFile() && re.test(toPosix(full))) out.push(path.resolve(full))\n }\n }\n walk(baseDir || '/', 0)\n return out\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Content-module walk\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst CODE_EXT = /\\.(vue|[cm]?[jt]sx?|md)$/i\nconst RESOLVE_EXTENSIONS = ['', '.ts', '.js', '.mts', '.mjs', '.tsx', '.jsx', '.vue', '.json', '/index.ts', '/index.js', '/index.vue']\nconst BUILTINS = new Set(builtinModules)\n/** VitePress built-in components a markdown page may use without registration. */\nconst VITEPRESS_BUILTIN_TAGS = new Set(['Badge', 'Content', 'ClientOnly'])\n/** VitePress built-in frontmatter layouts (anything else is a custom theme layout). */\nconst VITEPRESS_BUILTIN_LAYOUTS = new Set(['doc', 'home', 'page', 'false'])\n\n/** Strip block comments and whole-line `//` comments (URLs inside strings survive). */\nfunction stripComments(src: string): string {\n return src.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '').replace(/^\\s*\\/\\/.*$/gm, '')\n}\n\nfunction findSrcDir(file: string): string | undefined {\n let dir = path.dirname(file)\n for (let i = 0; i < 12; i++) {\n if (fs.existsSync(path.join(dir, '.vitepress'))) return dir\n const up = path.dirname(dir)\n if (up === dir) return undefined\n dir = up\n }\n return undefined\n}\n\nfunction hasPackage(specifier: string, fromFile: string): boolean {\n const parts = specifier.split('/')\n const pkg = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]\n let dir = path.dirname(fromFile)\n for (let i = 0; i < 40; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', pkg))) return true\n const up = path.dirname(dir)\n if (up === dir) return false\n dir = up\n }\n return false\n}\n\nfunction resolveWithExtensions(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const c = base + ext\n if (isFile(c)) return path.resolve(c)\n }\n return undefined\n}\n\ntype ImportResolution = { kind: 'file'; file: string } | { kind: 'package' } | { kind: 'unresolved' }\n\nfunction resolveImport(specifierRaw: string, fromFile: string, projectRoot: string): ImportResolution {\n const specifier = specifierRaw.replace(/[?#].*$/, '')\n if (!specifier) return { kind: 'unresolved' }\n if (specifier.startsWith('node:') || BUILTINS.has(specifier)) return { kind: 'package' }\n if (specifier.startsWith('virtual:') || specifier.startsWith('\\0')) return { kind: 'unresolved' }\n let base: string | undefined\n if (specifier.startsWith('.')) base = path.resolve(path.dirname(fromFile), specifier)\n else if (specifier.startsWith('@/') || specifier.startsWith('~/')) base = path.join(projectRoot, 'src', specifier.slice(2))\n else if (specifier.startsWith('@theme/')) {\n const srcDir = findSrcDir(fromFile)\n if (srcDir) base = path.join(srcDir, '.vitepress', 'theme', specifier.slice('@theme/'.length))\n } else if (specifier.startsWith('/')) {\n const srcDir = findSrcDir(fromFile)\n const hit = resolveWithExtensions(path.join(projectRoot, specifier)) ?? (srcDir ? resolveWithExtensions(path.join(srcDir, specifier)) : undefined)\n return hit ? { kind: 'file', file: hit } : { kind: 'unresolved' }\n } else {\n return hasPackage(specifier, fromFile) ? { kind: 'package' } : { kind: 'unresolved' }\n }\n if (!base) return { kind: 'unresolved' }\n const hit = resolveWithExtensions(base)\n return hit ? { kind: 'file', file: hit } : { kind: 'unresolved' }\n}\n\n/** `Name` → file, from a VitePress theme's `app.component('Name', Ident)` registrations. */\nfunction themeRegistry(srcDir: string, cache: Map<string, Map<string, string>>): Map<string, string> {\n const hit = cache.get(srcDir)\n if (hit) return hit\n const reg = new Map<string, string>()\n const themeDir = path.join(srcDir, '.vitepress', 'theme')\n const indexFile = ['index.ts', 'index.js', 'index.mts', 'index.mjs'].map((f) => path.join(themeDir, f)).find(isFile)\n if (indexFile) {\n const src = stripComments(fs.readFileSync(indexFile, 'utf8'))\n const idents = new Map<string, string>()\n for (const m of src.matchAll(/^\\s*import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/gm)) idents.set(m[1], m[2])\n for (const m of src.matchAll(/\\.component\\(\\s*['\"]([\\w-]+)['\"]\\s*,\\s*(\\w+)\\s*\\)/g)) {\n const spec = idents.get(m[2])\n if (!spec) continue\n const r = resolveImport(spec, indexFile, srcDir)\n if (r.kind === 'file') {\n reg.set(m[1], r.file)\n reg.set(toPascal(m[1]), r.file)\n }\n }\n }\n cache.set(srcDir, reg)\n return reg\n}\n\n/** Literal glob patterns of a VitePress data loader (`createContentLoader`, `watch`). */\nfunction dataLoaderInputs(src: string, loaderFile: string): string[] | null {\n const srcDir = findSrcDir(loaderFile) ?? path.dirname(loaderFile)\n const literals = (s: string) => [...s.matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1])\n const out: string[] = []\n let found = false\n for (const m of src.matchAll(/createContentLoader\\(\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n found = true\n for (const g of literals(m[1])) out.push(...expandGlob(path.resolve(srcDir, g)))\n }\n for (const m of src.matchAll(/\\bwatch\\s*:\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n found = true\n for (const g of literals(m[1])) {\n const base = g.startsWith('.') ? path.dirname(loaderFile) : srcDir\n out.push(...expandGlob(path.resolve(base, g)))\n }\n }\n return found ? out : null\n}\n\ninterface WalkResult {\n files: string[]\n omitted?: RouteLastmodOmitted\n}\n\nfunction walkContentModules(\n entries: string[],\n projectRoot: string,\n isExcluded: (abs: string) => boolean,\n registryCache: Map<string, Map<string, string>>,\n fileCache: Map<string, { deps: string[]; bad?: RouteLastmodOmitted }>\n): WalkResult {\n const seen = new Set<string>()\n const queue: string[] = []\n for (const e of entries) {\n if (!seen.has(e)) {\n seen.add(e)\n queue.push(e)\n }\n }\n while (queue.length > 0) {\n const file = queue.shift() as string\n let info = fileCache.get(file)\n if (!info) {\n info = scanFile(file, projectRoot, registryCache)\n fileCache.set(file, info)\n }\n if (info.bad) return { files: [...seen], omitted: info.bad }\n for (const dep of info.deps) {\n if (seen.has(dep) || isExcluded(dep)) continue\n seen.add(dep)\n queue.push(dep)\n }\n }\n return { files: [...seen] }\n}\n\n/** One file's local dependencies (not yet exclusion-filtered), or why it cannot be accounted for. */\nfunction scanFile(\n file: string,\n projectRoot: string,\n registryCache: Map<string, Map<string, string>>\n): { deps: string[]; bad?: RouteLastmodOmitted } {\n if (!CODE_EXT.test(file)) return { deps: [] }\n let raw: string\n try {\n raw = fs.readFileSync(file, 'utf8')\n } catch {\n return { deps: [], bad: 'unresolved-import' }\n }\n const isMd = /\\.md$/i.test(file)\n // A VitePress page whose frontmatter selects a custom layout is rendered by\n // that layout through the theme's dispatch, which this walk cannot see:\n // omit it rather than date it by its markdown alone (judge A1).\n if (isMd) {\n const fm = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/)\n const layout = fm?.[1].match(/^layout\\s*:\\s*(.*?)\\s*$/m)?.[1].replace(/^['\"]|['\"]$/g, '')\n if (layout && !VITEPRESS_BUILTIN_LAYOUTS.has(layout)) return { deps: [], bad: 'custom-layout' }\n }\n // Markdown: only <script> blocks carry imports; fenced code is not markup.\n const body = isMd ? raw.replace(/^(```|~~~)[\\s\\S]*?^\\1/gm, '') : raw\n const code = isMd ? [...body.matchAll(/<script\\b[^>]*>([\\s\\S]*?)<\\/script>/gi)].map((m) => m[1]).join('\\n') : body\n const src = stripComments(code)\n const deps = new Set<string>()\n\n if (/\\.data\\.[cm]?[jt]s$/i.test(file)) {\n const inputs = dataLoaderInputs(src, file)\n if (inputs === null) return { deps: [], bad: 'data-loader' }\n for (const f of inputs) deps.add(f)\n }\n\n for (const m of src.matchAll(/(?:\\bfrom\\s*|\\bimport\\s*\\(\\s*|^\\s*import\\s+)['\"]([^'\"]+)['\"]/gm)) {\n const r = resolveImport(m[1], file, projectRoot)\n if (r.kind === 'unresolved') return { deps: [], bad: 'unresolved-import' }\n if (r.kind === 'file' && r.file !== path.resolve(file)) deps.add(r.file)\n }\n\n for (const m of src.matchAll(/import\\.meta\\.glob(?:<[^>]*>)?\\(\\s*(\\[[^\\]]*\\]|['\"][^'\"]+['\"])/g)) {\n for (const lit of [...m[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((x) => x[1])) {\n if (lit.startsWith('!')) continue\n const abs = lit.startsWith('/') ? path.join(projectRoot, lit) : path.resolve(path.dirname(file), lit)\n for (const f of expandGlob(abs)) deps.add(f)\n }\n }\n\n // VitePress: components registered globally by the theme and used as tags.\n const srcDir = findSrcDir(file)\n if (srcDir) {\n const reg = themeRegistry(srcDir, registryCache)\n const markup = isMd\n ? body.replace(/<script\\b[\\s\\S]*?<\\/script>/gi, '').replace(/`[^`\\n]*`/g, '')\n : (raw.match(/<template\\b[\\s\\S]*<\\/template>/i)?.[0] ?? '')\n const tags = new Set<string>()\n for (const m of markup.matchAll(/<([A-Z][A-Za-z0-9]*)\\b/g)) tags.add(m[1])\n for (const m of markup.matchAll(/<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\\b/g)) tags.add(toPascal(m[1]))\n for (const tag of tags) {\n const target = reg.get(tag)\n if (target) deps.add(target)\n else if (isMd && !VITEPRESS_BUILTIN_TAGS.has(tag)) return { deps: [], bad: 'unresolved-component' }\n }\n }\n return { deps: [...deps] }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// content.yaml (c)\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface ContentEntry {\n date: string\n oldBlob: string\n newBlob: string\n}\n\nconst ZERO_BLOB = /^0+$/\n\nfunction findContentFile(projectRoot: string, contentPath: string | undefined): string | undefined {\n const rel = contentPath ?? '.dcs/content.yaml'\n if (path.isAbsolute(rel)) return isFile(rel) ? path.resolve(rel) : undefined\n return [path.resolve(projectRoot, rel), path.resolve(projectRoot, '..', rel), path.resolve(process.cwd(), rel)].find(isFile)\n}\n\n/** Global content.yaml keys a route's sources reference as string literals. */\nfunction referencedGlobalKeys(files: string[], globalKeys: string[]): string[] {\n if (globalKeys.length === 0) return []\n const text = files\n .filter((f) => CODE_EXT.test(f))\n .map((f) => {\n try {\n return fs.readFileSync(f, 'utf8')\n } catch {\n return ''\n }\n })\n .join('\\n')\n return globalKeys.filter((k) => text.includes(`'${k}'`) || text.includes(`\"${k}\"`) || text.includes(`\\`${k}\\``))\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Main\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Derive per-route `<lastmod>` values from git. Never throws: any git failure\n * withholds the git-derived dates (the sitemap then omits `<lastmod>` for\n * routes without a pages.yaml date).\n */\nexport function deriveRouteLastmods(options: DeriveRouteLastmodsOptions): DeriveRouteLastmodsResult {\n const {\n routes,\n projectRoot,\n sourcesForRoute,\n contentPath,\n exclude = [],\n contentWalkLimit = CONTENT_WALK_LIMIT,\n git = defaultGit,\n debug = false,\n } = options\n const omitted = new Map<string, RouteLastmodOmitted>()\n const sources = new Map<string, string[]>()\n const empty = (withheld: RouteLastmodWithheld): DeriveRouteLastmodsResult => {\n if (debug) console.log(`[dcs-seo] git-derived <lastmod> withheld: ${withheld}`)\n return { lastmods: new Map(), withheld, omitted, sources }\n }\n\n let shallow: string\n try {\n shallow = git(['rev-parse', '--is-shallow-repository'], projectRoot).trim()\n } catch {\n return empty('git-unavailable')\n }\n if (shallow === 'true') return empty('shallow')\n // Anything but a literal `false` (e.g. a git too old to know the flag echoes\n // it back) is not proof of full history.\n if (shallow !== 'false') return empty('git-unavailable')\n\n let top: string\n try {\n top = path.resolve(git(['rev-parse', '--show-toplevel'], projectRoot).trim())\n } catch {\n return empty('git-unavailable')\n }\n const relTop = (abs: string) => toPosix(path.relative(top, abs))\n\n const contentFile = findContentFile(projectRoot, contentPath)\n const isExcluded = makeExcluder(projectRoot, exclude, contentFile ? [contentFile] : [])\n\n // ── (a) + (b): per-route material source sets ─────────────────────────────\n const registryCache = new Map<string, Map<string, string>>()\n const fileCache = new Map<string, { deps: string[]; bad?: RouteLastmodOmitted }>()\n const routeFiles = new Map<string, string[]>()\n for (const route of routes) {\n if (routeFiles.has(route.path) || omitted.has(route.path)) continue\n const entries = routeEntries(route, projectRoot, sourcesForRoute)\n if (entries.length === 0) {\n omitted.set(route.path, 'no-source')\n continue\n }\n const walked = walkContentModules(entries, projectRoot, isExcluded, registryCache, fileCache)\n if (walked.omitted) {\n omitted.set(route.path, walked.omitted)\n continue\n }\n routeFiles.set(route.path, walked.files)\n }\n\n const allFiles = [...new Set([...routeFiles.values()].flat())]\n const material = contentFile ? [...allFiles, contentFile] : allFiles\n\n // Tracked and clean: an untracked or locally modified source has no commit date.\n const tracked = new Set<string>()\n const dirty = new Set<string>()\n const newest = new Map<string, string>()\n if (material.length > 0) {\n const rels = [...new Set(material.map(relTop))]\n try {\n // Whole-repo listings (no pathspec): a long pathspec can exceed the\n // Windows command-line limit on a site with hundreds of posts.\n for (const line of git(['-c', 'core.quotepath=off', 'ls-files'], top).split('\\n')) {\n if (line.trim()) tracked.add(line.trim())\n }\n for (const line of git(['-c', 'core.quotepath=off', 'status', '--porcelain=v1', '--untracked-files=all'], top).split('\\n')) {\n if (line.length <= 3) continue\n for (const part of line.slice(3).trim().split(' -> ')) dirty.add(part.replace(/^\"|\"$/g, ''))\n }\n // Dating walk, in batches; `--cc` makes a merge that changed a file (a\n // conflict resolution) list it, so such a page is not dated older.\n const dated = rels.filter((r) => tracked.has(r))\n for (let i = 0; i < dated.length; i += 150) {\n const out = git(\n ['-c', 'core.quotepath=off', 'log', '--format=%x01%cI', '--name-only', '--cc', '--', ...dated.slice(i, i + 150)],\n top\n )\n let date: string | null = null\n for (const line of out.split('\\n')) {\n const t = line.trim()\n if (t.startsWith('\\u0001')) {\n date = t.slice(1)\n continue\n }\n if (!t || !date) continue\n const known = newest.get(t)\n if (!known || Date.parse(date) > Date.parse(known)) newest.set(t, date)\n }\n }\n } catch {\n return empty('git-unavailable')\n }\n }\n const isClean = (abs: string) => tracked.has(relTop(abs)) && !dirty.has(relTop(abs))\n\n // ── (c) content.yaml: per-route subtree change dates ──────────────────────\n let contentEntries: ContentEntry[] = []\n let contentCapped = false\n let contentOk = true\n const blobCache = new Map<string, Record<string, unknown> | null>()\n let globalKeys: string[] = []\n if (contentFile) {\n if (!isClean(contentFile)) {\n contentOk = false\n } else {\n try {\n const out = git(\n ['log', '--first-parent', '-m', `-n${contentWalkLimit + 1}`, '--format=%x01%cI', '--raw', '--no-abbrev', '--', relTop(contentFile)],\n top\n )\n let date: string | null = null\n for (const line of out.split('\\n')) {\n const t = line.trim()\n if (t.startsWith('\\u0001')) {\n date = t.slice(1)\n continue\n }\n const m = t.match(/^:\\d+ \\d+ ([0-9a-f]+) ([0-9a-f]+) /)\n if (m && date) contentEntries.push({ date, oldBlob: m[1], newBlob: m[2] })\n }\n } catch {\n return empty('git-unavailable')\n }\n if (contentEntries.length > contentWalkLimit) {\n contentCapped = true\n contentEntries = contentEntries.slice(0, contentWalkLimit)\n }\n try {\n const head = yaml.load(fs.readFileSync(contentFile, 'utf8')) as { global?: Record<string, unknown> } | null\n globalKeys = Object.keys(head?.global ?? {})\n } catch {\n contentOk = false\n }\n }\n }\n const loadBlob = (blob: string): Record<string, unknown> | null => {\n if (ZERO_BLOB.test(blob)) return null\n if (blobCache.has(blob)) return blobCache.get(blob) ?? null\n let doc: Record<string, unknown> | null = null\n try {\n doc = (yaml.load(git(['cat-file', '-p', blob], top)) as Record<string, unknown> | null) ?? null\n } catch {\n doc = null\n }\n blobCache.set(blob, doc)\n return doc\n }\n const subtreeKey = (doc: Record<string, unknown> | null, slug: string, keys: string[]): string => {\n const pages = (doc?.pages ?? {}) as Record<string, unknown>\n const global = (doc?.global ?? {}) as Record<string, unknown>\n return JSON.stringify({ page: pages[slug] ?? null, global: keys.map((k) => [k, global[k] ?? null]) })\n }\n\n // ── Combine ────────────────────────────────────────────────────────────────\n const lastmods = new Map<string, string>()\n for (const route of routes) {\n const files = routeFiles.get(route.path)\n if (!files || lastmods.has(route.path)) continue\n if (!files.every(isClean)) {\n omitted.set(route.path, 'untracked-source')\n continue\n }\n let best: string | null = null\n let undated = false\n for (const f of files) {\n const d = newest.get(relTop(f))\n if (!d) {\n undated = true\n break\n }\n if (best === null || Date.parse(d) > Date.parse(best)) best = d\n }\n if (undated || best === null) {\n omitted.set(route.path, 'undated-source')\n continue\n }\n if (contentFile) {\n if (!contentOk) {\n omitted.set(route.path, 'content-untracked')\n continue\n }\n const keys = referencedGlobalKeys(files, globalKeys)\n let contentDate: string | null = null\n for (const e of contentEntries) {\n if (subtreeKey(loadBlob(e.newBlob), route.slug, keys) !== subtreeKey(loadBlob(e.oldBlob), route.slug, keys)) {\n contentDate = e.date\n break\n }\n }\n if (contentDate === null && contentCapped) {\n omitted.set(route.path, 'content-walk-cap')\n continue\n }\n if (contentDate && Date.parse(contentDate) > Date.parse(best)) best = contentDate\n }\n lastmods.set(route.path, best)\n sources.set(route.path, contentFile ? [...files, contentFile] : files)\n }\n\n // Uniform-stamp signature: 3+ dated routes that ALL share one single date\n // (e.g. every file's history collapsed onto one graft/import commit). A\n // partial overlap from a real bulk commit is accurate and kept.\n if (lastmods.size >= IDENTICAL_LASTMOD_ROUTE_LIMIT && new Set(lastmods.values()).size === 1) {\n return empty('identical-dates')\n }\n\n if (debug) {\n for (const [p, why] of omitted) console.log(`[dcs-seo] <lastmod> omitted for ${p}: ${why}`)\n }\n return { lastmods, omitted, sources }\n}\n","/**\n * DCS SEO Plugin for Vite\n *\n * Two responsibilities, both driven by `.dcs/seo.yaml`:\n *\n * 1. **Build-time define** (always on): reads `.dcs/seo.yaml` and injects it as\n * the `__DCS_SEO__` global for the runtime `useSEO` composable.\n *\n * 2. **Static `<head>` emitter** (opt-in via `emitStaticHtml: true`, default\n * OFF): after the bundle is written, reads the SPA's built `index.html`,\n * and for every route in `.dcs/pages.yaml` writes a per-route\n * `dist/<path>/index.html` whose `<head>` carries the resolved title, meta,\n * canonical, Open Graph, Twitter, and JSON-LD tags. This gives a Vue SPA\n * per-route static SEO **without** vite-ssg.\n *\n * VitePress sites already bake SEO via their own config, so they leave this\n * option OFF and are completely unaffected.\n *\n * @example Runtime define only (default — safe for VitePress)\n * ```typescript\n * // vite.config.ts\n * import { dcsSeoPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [dcsSeoPlugin({ debug: true })]\n * })\n * ```\n *\n * @example Vue SPA with per-route static <head> emission\n * ```typescript\n * // vite.config.ts\n * import { dcsSeoPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsSeoPlugin({\n * emitStaticHtml: true, // turn the emitter ON\n * pagesPath: '.dcs/pages.yaml', // route manifest (default)\n * noindex: ['account', 'projects'], // robots: noindex,nofollow\n * exclude: ['/preview'], // skip these routes entirely\n * })\n * ]\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport yaml from 'js-yaml'\nimport type { Plugin, ResolvedConfig, HtmlTagDescriptor } from 'vite'\nimport type { SeoConfiguration, SeoHonestyBlock } from '../types/seo'\nimport { readDcsYamlFresh, buildGlobalAssignScript } from './serveDefineInject'\nimport { clearDirIndexManifest, installDirIndex, isVitePressSiteConfig } from './dcsDirIndex'\nimport { buildHeadTags } from '../seo/headTags'\nimport { spliceHeadHtml } from '../seo/spliceHeadHtml'\nimport {\n loadPagesManifest,\n routeExclusionReason,\n isRouteEmitted,\n type PageRouteEntry,\n} from '../seo/pagesManifest'\nimport {\n findDuplicateNormalizedPaths,\n formatDuplicateNormalizedPaths,\n} from '../seo/installSeoHead'\nimport {\n prerenderBodies,\n isBodyPrerenderEnabled,\n routeToOutputFile,\n} from '../seo/bodyPrerender'\nimport { createPlaywrightRenderer } from '../seo/playwrightRenderer'\nimport { deriveRouteLastmods, type GitRunner } from './routeLastmod'\nimport {\n assertHeadHonesty,\n assertHeadHonestyExecuted,\n findHeadHonestyViolations,\n resolveHonestyMode,\n type HeadObservation,\n type HonestyMode,\n} from '../seo/headHonesty'\nimport {\n collectEmittedUrlsFromFiles,\n dedupeUrls,\n classifyUrl,\n auditSameOriginAssets,\n checkRemoteAssets,\n formatEmittedUrlReport,\n formatEmittedUrlAudit,\n auditCheckedTotal,\n EmittedUrlError,\n EmittedUrlNotRunError,\n type ClassifiedUrl,\n type EmittedUrlAudit,\n type EmittedUrlViolation,\n} from '../seo/emittedUrls'\nimport {\n hoistCharsetMeta,\n checkCharsetBudget,\n formatCharsetHeadroomWarning,\n CharsetBudgetError,\n} from '../seo/charsetBudget'\nimport {\n buildSitemapXml,\n buildRobotsTxt,\n buildLlmsTxt,\n isHandAuthoredRobotsAcceptable,\n appendAiTrainingOptOut,\n findAiTrainingRobotsConflicts,\n RobotsAiTrainingConflictError,\n type DcsRobotsOptions,\n} from '../seo/sitemap'\nimport {\n breadcrumbTrailFromRoute,\n findReviewItemsForPage,\n findBusinessLicense,\n findPostalAddressGaps,\n formatPostalAddressGapReport,\n type ContentConfig,\n type ReviewSource,\n type BlogMeta,\n type FaqSource,\n} from '../seo/schemaGraph'\n\nexport interface DcsSeoPluginOptions {\n /** Path to seo.yaml relative to project root (default: '.dcs/seo.yaml') */\n seoPath?: string\n /** Enable debug logging */\n debug?: boolean\n\n /**\n * Opt-in: emit per-route static `<head>` (meta + JSON-LD) into the built\n * `dist/` at the end of the build. Default `false` — VitePress sites and any\n * site that bakes its own SEO are unaffected when this is off.\n */\n emitStaticHtml?: boolean\n\n /**\n * Build-time BODY prerender: after the per-route `<head>` is emitted, render\n * each indexable route's real DOM from the just-built SPA (headless Chromium\n * via the site's `playwright`) and splice it into the mount container so non-JS\n * AI crawlers see the page's body prose — not just `<div id=\"app\"></div>`.\n *\n * Defaults to whatever `emitStaticHtml` is, so every SPA already emitting\n * per-route HTML gains crawler-visible bodies on a cms bump with no per-site\n * edit. Set `false` here to keep head-only emission. It is ALSO overridable\n * per-site (no code change / no cms republish) via `.dcs/seo.yaml`\n * `prerenderBody: false`. noindex/auth-gated routes are never body-prerendered;\n * a route that crashes at render time fails the build loud rather than shipping\n * a broken body. Requires `playwright` in the site (already the fleet default);\n * absent ⇒ graceful no-op (head + JSON-LD still emitted).\n */\n prerenderBody?: boolean\n\n /**\n * Path to the route manifest relative to project root, used only when\n * `emitStaticHtml` is true. Default `'.dcs/pages.yaml'`.\n */\n pagesPath?: string\n\n /**\n * Path to `content.yaml` relative to project root, used only when\n * `emitStaticHtml` is true. Threads REAL reviews into the honest\n * Review/aggregateRating on the per-route LocalBusiness node. Default\n * `'.dcs/content.yaml'`. Missing/unparseable ⇒ no reviews emitted.\n */\n contentPath?: string\n\n /**\n * Routes to skip entirely (no per-route HTML written). Matched against the\n * route `path` (e.g. `'/preview'`) OR the route `slug` (e.g. `'account'`).\n */\n exclude?: string[]\n\n /**\n * Routes that should receive `robots: noindex, nofollow`. Matched against the\n * route `path` OR `slug`. The home route (`/`) still overwrites\n * `dist/index.html`.\n *\n * This is a PREDICATE OVER `pages.yaml`, not a standalone directive about a\n * URL. An entry that matches no page is a **build error**\n * (`NoindexOrphanError`, C-416) — with no matching page nothing is emitted for\n * it, so the entry would silently do nothing while the URL stayed\n * `index, follow`. Matched raw, so `'/account/'` does not match a `'/account'`\n * route; matched against the full manifest, so an entry that is also in\n * `exclude` is fine.\n */\n noindex?: string[]\n\n /**\n * Opt-in: emit the site-wide static files `dist/sitemap.xml`,\n * `dist/robots.txt`, and `dist/llms.txt` after the per-route HTML loop.\n *\n * Defaults to whatever `emitStaticHtml` is — so every site already calling\n * `dcsSeoPlugin({ emitStaticHtml: true })` gets sitemap/robots/llms for free\n * with zero per-site edits. Set explicitly to `false` to keep emitting\n * per-route HTML without the site files. The whole block is wrapped in the\n * same try/catch + existsSync guards, so it can never break a build.\n */\n emitSiteFiles?: boolean\n\n /**\n * Canonical production origin, e.g. `https://ironoakcontractors.com`. Used as\n * the sitemap/llms base and the absolute `Sitemap:` line in robots.txt. When\n * absent, falls back to `seo.yaml`'s `global.siteUrl`; if neither is known and\n * no per-page canonicals exist, the sitemap + llms.txt no-op (robots still\n * emits). Never guessed.\n */\n siteUrl?: string\n\n /** robots.txt override hooks (disallow/allow/extra/aiBots/force). */\n robots?: DcsRobotsOptions\n\n /**\n * Preview / staging gate. When `true`, robots.txt becomes `Disallow: /` (no\n * `Sitemap:` line) and neither sitemap.xml nor llms.txt is emitted (privacy).\n * Detected ONLY via this explicit option — never guessed.\n */\n preview?: boolean\n\n /** Emit `dist/llms.txt` (default `true`; always off in preview mode). */\n llms?: boolean\n\n /**\n * Opt in to git-derived sitemap `<lastmod>` (BEST-EFFORT; default OFF).\n * Without it the factory never infers a date: a URL carries its per-route\n * `.dcs/pages.yaml` `lastmod`, or no `<lastmod>`. The site-level switch is\n * `.dcs/seo.yaml` `sitemap.lastmodFromGit: true`; this option, when set,\n * overrides it for one build. See `deriveRouteLastmods` for what the walk\n * does and does not see.\n */\n gitLastmod?: boolean\n\n /**\n * Override a route's source files (absolute or project-root relative) for\n * the git-derived `<lastmod>`. Return `undefined` for the default mapping\n * (`src/views/<Name>View.vue`, `src/pages/<Name>.vue`, `<path>.md`, ...).\n */\n lastmodSources?: (route: PageRouteEntry) => string[] | undefined\n\n // ── SEO emission honesty rails (C-334) ────────────────────────────────────\n // Three asserts against one failure class: a capability that exists is\n // silently undone downstream and nothing notices. All three default ON\n // (severity `error`) whenever `emitStaticHtml` is on, and all three can be\n // lowered per-site from `.dcs/seo.yaml` (portal-owned) or per-build from an\n // env var that prints in the log. There is no silent off switch.\n\n /**\n * P1 — assert that each route's BAKED `<title>`/description equals what the\n * app leaves in the `<head>` after it mounts. Rides the prerender browser, so\n * the marginal cost is one `page.evaluate()` per route.\n *\n * Env override: `DCS_SEO_HEAD_HONESTY=error|warn|off`.\n * seo.yaml override: `headHonesty: warn` or `headHonesty: { mode, allow }`.\n */\n headHonesty?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * P2 — assert that every URL the factory publishes (JSON-LD logo/image IRIs,\n * `og:image`, icon links, sitemap `<loc>`s, llms.txt links) resolves to what it\n * promises. Same-origin assets are proven against `dist/` with no network;\n * cross-origin assets are probed under a cache + time budget and only a\n * DEFINITIVE wrong answer fails the build.\n *\n * Env override: `DCS_SEO_URL_HONESTY=error|warn|off`,\n * `DCS_SEO_URL_HONESTY_NETWORK=off` to skip the cross-origin probes.\n */\n urlHonesty?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * P12 — hoist `<meta charset>` to the top of `<head>` and assert it lands\n * inside the spec's 1024-byte encoding-sniffing window.\n *\n * Env override: `DCS_SEO_CHARSET_BUDGET=error|warn|off`.\n */\n charsetBudget?: boolean | HonestyMode | SeoHonestyBlock\n\n /**\n * C-1965: on a VitePress `cleanUrls` BUILD, write a byte-identical\n * `<page>/index.html` twin of every flat `<page>.html` (index pages and the\n * root `404.md` excluded) after the site's own `buildEnd`, so `/page/`\n * answers 200 on an Azure Static Web App instead of 301-ing to the\n * `*.azurestaticapps.net` default host. Default `true`; non-VitePress builds\n * and `vitepress dev` are never touched. An existing `<page>/index.html` with\n * different bytes FAILS the build. See `dcsDirIndex.ts`. On by default\n * because every DCS cleanUrls consumer is an Azure SWA; on another host the\n * twins change what `/page/` serves (README, \"Directory-index twins\"), and\n * `false` keeps the pre-0.13.14 output.\n */\n dirIndex?: boolean\n}\n\n/** Split a `boolean | mode | { mode, allow, … }` option into its parts. */\nfunction readHonestyBlock(\n value: boolean | HonestyMode | SeoHonestyBlock | undefined\n): { mode?: HonestyMode | boolean; allow: string[]; checkDescription?: boolean; network?: boolean } {\n if (value === undefined) return { allow: [] }\n if (typeof value === 'boolean' || typeof value === 'string') return { mode: value, allow: [] }\n return {\n mode: value.mode,\n allow: Array.isArray(value.allow) ? value.allow : [],\n checkDescription: value.checkDescription,\n network: value.network,\n }\n}\n\n/** Resolve the SPA output directory from Vite config (absolute path). */\nfunction resolveOutDir(config: ResolvedConfig): string {\n const out = config.build?.outDir || 'dist'\n return path.isAbsolute(out) ? out : path.resolve(config.root || process.cwd(), out)\n}\n\n/**\n * Load + parse seo.yaml from the usual `.dcs` locations.\n * Returns `{ config, foundPath }` or `null` (missing/unparseable).\n */\nfunction loadSeoConfig(\n projectRoot: string,\n seoPath: string,\n debug: boolean\n): { config: SeoConfiguration; foundPath: string } | null {\n const possiblePaths = [\n path.resolve(projectRoot, seoPath),\n path.resolve(projectRoot, '..', seoPath),\n path.resolve(process.cwd(), seoPath),\n ]\n\n let foundPath: string | undefined\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n foundPath = testPath\n break\n }\n }\n\n if (!foundPath) {\n if (debug) {\n console.log('[dcs-seo] No seo.yaml found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n console.log('[dcs-seo] Using defaults only')\n }\n return null\n }\n\n try {\n const fileContent = fs.readFileSync(foundPath, 'utf8')\n const config = yaml.load(fileContent) as SeoConfiguration\n return { config, foundPath }\n } catch (error) {\n console.warn('[dcs-seo] Failed to parse seo.yaml:', error)\n return null\n }\n}\n\n/**\n * Load + parse `.dcs/content.yaml` from the usual `.dcs` locations. Returns the\n * parsed config or `undefined` (missing/unparseable). Used to thread REAL\n * reviews into the honest Review/aggregateRating builder. Never throws.\n */\nfunction loadContentConfig(\n projectRoot: string,\n contentRelPath: string,\n debug: boolean\n): ContentConfig | undefined {\n const possiblePaths = [\n path.resolve(projectRoot, contentRelPath),\n path.resolve(projectRoot, '..', contentRelPath),\n path.resolve(process.cwd(), contentRelPath),\n ]\n const foundPath = possiblePaths.find((p) => fs.existsSync(p))\n if (!foundPath) {\n if (debug) console.log(`[dcs-seo] No content.yaml found (reviews disabled)`)\n return undefined\n }\n try {\n const parsed = yaml.load(fs.readFileSync(foundPath, 'utf8'))\n if (!parsed || typeof parsed !== 'object') return undefined\n return parsed as ContentConfig\n } catch (error) {\n console.warn('[dcs-seo] Failed to parse content.yaml (reviews disabled):', error)\n return undefined\n }\n}\n\n/** Extract the optional top-level `excluded:` glob list from pages.yaml. */\nfunction loadExcludedGlobs(projectRoot: string, pagesPath: string): string[] {\n const possiblePaths = [\n path.resolve(projectRoot, pagesPath),\n path.resolve(projectRoot, '..', pagesPath),\n path.resolve(process.cwd(), pagesPath),\n ]\n const found = possiblePaths.find((p) => fs.existsSync(p))\n if (!found) return []\n try {\n const raw = yaml.load(fs.readFileSync(found, 'utf8')) as { excluded?: unknown } | null\n const excluded = raw?.excluded\n if (!Array.isArray(excluded)) return []\n return excluded.filter((e): e is string => typeof e === 'string')\n } catch {\n return []\n }\n}\n\n/**\n * Refuse a manifest whose route paths collide after trailing-slash\n * normalization (C-361 F6).\n *\n * ONE OF TWO PLACES THE PLUGIN DELIBERATELY THROWS (the other is\n * {@link assertNoOrphanNoindexEntries}). Everything else in the\n * emit path is defensive by design — a missing or unparseable input warns and\n * no-ops, because a bad input must never break a production build. A duplicate\n * normalized path is a different animal: it is not a missing input, it is an\n * input for which every possible behaviour is wrong. The emitter's last write\n * wins the file on disk; the runtime lookup's first entry wins the head. Picking\n * a side ships a GUARANTEED baked/runtime divergence and calls it success —\n * exactly the silent-wrong-answer class this plan exists to kill — and the two\n * colliding entries have different slugs, so only the owner knows which page\n * that URL is. A red build is the cheap failure here; a green one is not.\n *\n * Thrown from `config()`, so it fails before a single byte is emitted.\n */\nfunction assertNoDuplicateRoutePaths(routes: PageRouteEntry[]): void {\n const dupes = findDuplicateNormalizedPaths(routes)\n if (dupes.length === 0) return\n throw new Error(`[dcs-seo] ${formatDuplicateNormalizedPaths(dupes)}`)\n}\n\n/**\n * Every key a `noindex` entry can legitimately match.\n *\n * The plugin's contract for `noindex` is a PREDICATE OVER THE ROUTE MANIFEST,\n * never a directive about a bare URL. Every consumer asks the question\n * route-first and identically —\n * `noindexSet.has(route.path) || (route.slug && noindexSet.has(route.slug))` —\n * in {@link emitStaticSeoHtml}, in the sitemap/llms `isRouteIndexable`\n * predicate, and in the baked `__DCS_PAGES__` manifest the runtime re-assert\n * reads. So the set of entries that can ever do anything is exactly the union\n * of the manifest's paths and slugs, and this function is the exact inverse of\n * that same relation rather than a second, drifting implementation of it.\n */\nexport function collectNoindexMatchKeys(routes: PageRouteEntry[]): Set<string> {\n const keys = new Set<string>()\n for (const route of routes) {\n if (route.path) keys.add(route.path)\n if (route.slug) keys.add(route.slug)\n }\n return keys\n}\n\n/**\n * `noindex` entries that match no route in the manifest — i.e. entries that\n * are, today, silent no-ops.\n *\n * Matched with the SAME raw string equality the consumers use, deliberately:\n * a `'/account/'` entry against a `'/account'` route does not match in\n * `emitStaticSeoHtml`, so it must not \"match\" here either, or the check would\n * bless the very entry the emitter is about to ignore.\n */\nexport function findOrphanNoindexEntries(\n noindex: string[],\n routes: PageRouteEntry[]\n): string[] {\n const known = collectNoindexMatchKeys(routes)\n const seen = new Set<string>()\n const orphans: string[] = []\n for (const entry of noindex) {\n if (known.has(entry) || seen.has(entry)) continue\n seen.add(entry)\n orphans.push(entry)\n }\n return orphans\n}\n\n/** Thrown when a `noindex` entry names nothing in `pages.yaml` (C-416). */\nexport class NoindexOrphanError extends Error {\n readonly orphans: string[]\n readonly knownKeys: string[]\n constructor(orphans: string[], knownKeys: string[]) {\n super(\n `[dcs-seo] noindex entr${orphans.length === 1 ? 'y' : 'ies'} matching NO page in the ` +\n `route manifest: ${orphans.map((o) => JSON.stringify(o)).join(', ')}. ` +\n `A noindex entry is a predicate over pages.yaml, not a standalone directive: ` +\n `with no matching page NOTHING is emitted for that route, so the entry is a ` +\n `silent no-op and the URL stays \"index, follow\" to crawlers — which is exactly ` +\n `how six homepage-clone URLs on KEPT stayed indexable. ` +\n `Fix it by adding the page to pages.yaml (it then gets a real ` +\n `robots: noindex, nofollow document, sitemap/llms omission, and a runtime ` +\n `re-assert), or by deleting the stale entry. ` +\n `Matchable keys are the manifest's paths and slugs: ` +\n `${knownKeys.map((k) => JSON.stringify(k)).join(', ') || '(manifest is empty)'}`\n )\n this.name = 'NoindexOrphanError'\n this.orphans = orphans\n this.knownKeys = knownKeys\n }\n}\n\n/**\n * Refuse a `noindex` list containing an entry that matches no page (C-416).\n *\n * THE SECOND PLACE THE PLUGIN DELIBERATELY THROWS, and for the same reason as\n * {@link assertNoDuplicateRoutePaths}: this is not a missing input to be\n * defended against, it is an input whose only possible behaviour is wrong.\n *\n * Why a hard error and NOT \"emit a noindex document for it instead\":\n * - An entry is allowed to be a bare SLUG (`'account'`), and a slug carries no\n * URL. Synthesizing a document would mean inventing a path — inventing a\n * crawlable URL to paper over a config typo is strictly worse than the bug\n * being fixed.\n * - Even for the path form, writing `dist/<path>/index.html` for a route the\n * SPA does not have MANUFACTURES a real, fetchable URL that would otherwise\n * never resolve. The remedy would create crawl surface, not remove it.\n * - Adding the page to `pages.yaml` is the operator action that makes the\n * directive real everywhere at once (emitted document + sitemap/llms\n * omission + runtime re-assert). Anything the plugin could synthesize on its\n * own would cover only the first of those three, i.e. a second partial\n * capability with nothing watching — the class this whole rail family exists\n * to kill.\n *\n * There is deliberately NO severity knob / escape hatch (unlike the C-334\n * rails, which measure emitted artifacts and can hit network or environment\n * flake). There is no legitimate orphan: the fix is always \"add the page\" or\n * \"delete the row\", both free.\n *\n * Matched against the FULL manifest, BEFORE `exclude` / `excluded:` globs are\n * applied. A route that is both excluded and noindexed names a real page, and\n * an excluded route publishes no document to be indexable — erroring there\n * would be a false positive that pushes operators to delete honest rows.\n *\n * Thrown from `config()`, so it fails before a single byte is emitted — and,\n * critically, OUTSIDE the `writeBundle` emit try/catch, which downgrades\n * everything it wraps to a `console.warn`. A version of this check placed\n * inside that catch would be vacuously green.\n */\nfunction assertNoOrphanNoindexEntries(noindex: string[], routes: PageRouteEntry[]): void {\n if (noindex.length === 0) return\n const orphans = findOrphanNoindexEntries(noindex, routes)\n if (orphans.length === 0) return\n throw new NoindexOrphanError(orphans, [...collectNoindexMatchKeys(routes)].sort())\n}\n\n/**\n * Core site-file emitter, separated from Vite so it is unit-testable.\n *\n * Writes the site-wide static files into `outDir`, reusing the SAME routes +\n * seoConfig already loaded by the per-route HTML loop (no second manifest read):\n * - `sitemap.xml` (skipped in preview, or when no absolute base is derivable)\n * - `robots.txt` (always; preview = `Disallow: /`; don't-clobber unless force)\n * - `llms.txt` (skipped in preview, or when nothing indexable)\n *\n * Returns the list of relative filenames written. Pure aside from `fs` writes —\n * deterministic + idempotent. Throws only {@link RobotsAiTrainingConflictError}\n * (a hand-authored robots.txt that contradicts `robots.aiTraining: false`),\n * which the plugin's emit catch re-throws so the build fails; nothing else is\n * thrown.\n */\nexport function emitSiteFiles(params: {\n outDir: string\n projectRoot: string\n pagesPath: string\n routes: PageRouteEntry[]\n seoConfig: SeoConfiguration | undefined\n siteUrl?: string\n exclude?: string[]\n noindex?: string[]\n preview?: boolean\n robots?: DcsRobotsOptions\n llms?: boolean\n /**\n * Opt in to git-derived sitemap `<lastmod>` (BEST-EFFORT; default OFF).\n * Without it the factory never infers a date: a URL carries its per-route\n * `.dcs/pages.yaml` `lastmod`, or no `<lastmod>`. The site-level switch is\n * `.dcs/seo.yaml` `sitemap.lastmodFromGit: true`; this option, when set,\n * overrides it for one build. See `deriveRouteLastmods` for what the walk\n * does and does not see.\n */\n gitLastmod?: boolean\n /** Override a route's ENTRY files for the git-derived `<lastmod>` (the content walk still runs). */\n lastmodSources?: (route: PageRouteEntry) => string[] | undefined\n /**\n * `.dcs/content.yaml` path (projectRoot-relative or absolute), used to date\n * each route's own content subtree. Default: searched like pages.yaml.\n */\n contentPath?: string\n /** Injectable git runner (tests only). */\n git?: GitRunner\n debug?: boolean\n}): string[] {\n const {\n outDir,\n projectRoot,\n pagesPath,\n routes,\n seoConfig,\n siteUrl,\n exclude = [],\n noindex = [],\n preview = false,\n robots = {},\n llms = true,\n gitLastmod,\n lastmodSources,\n contentPath,\n git,\n debug = false,\n } = params\n\n const written: string[] = []\n\n const effectiveSiteUrl = siteUrl || seoConfig?.global?.siteUrl\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n // Per-route <lastmod>: the route's own pages.yaml date, else omitted. The\n // factory never infers a date by default (cms 0.14.0). Git-derived dates are\n // a per-site, best-effort opt-in: seo.yaml `sitemap.lastmodFromGit: true`\n // (or the `gitLastmod` option). Never a site-wide `lastUpdated` stamp.\n const gitOptIn = gitLastmod ?? seoConfig?.sitemap?.lastmodFromGit === true\n const routeLastmods =\n !preview && gitOptIn\n ? deriveRouteLastmods({\n routes,\n projectRoot,\n sourcesForRoute: lastmodSources,\n contentPath,\n exclude: Array.isArray(seoConfig?.sitemap?.lastmodExclude)\n ? seoConfig.sitemap.lastmodExclude.filter((g): g is string => typeof g === 'string')\n : [],\n git,\n debug,\n }).lastmods\n : undefined\n\n // ── sitemap.xml (not in preview) ──────────────────────────────────────────\n let wroteSitemap = false\n if (!preview) {\n const xml = buildSitemapXml({\n routes,\n siteUrl: effectiveSiteUrl,\n seoConfig,\n exclude,\n noindex,\n excludedGlobs,\n routeLastmods,\n })\n if (xml) {\n fs.writeFileSync(path.join(outDir, 'sitemap.xml'), xml, 'utf8')\n wroteSitemap = true\n written.push('sitemap.xml')\n if (debug) console.log('[dcs-seo] wrote sitemap.xml')\n } else if (debug) {\n console.log('[dcs-seo] no absolute <loc> derivable; sitemap.xml not written')\n }\n }\n\n // ── robots.txt (always, unless robots.enabled is false) ───────────────────\n // `aiTraining`: an explicit plugin option wins, else `.dcs/seo.yaml`\n // `robots.aiTraining` (portal-owned), else `true` (owner R-Q2 = A).\n const seoAiTraining = seoConfig?.robots?.aiTraining\n const effectiveRobots: DcsRobotsOptions = {\n ...robots,\n aiTraining: robots.aiTraining ?? (typeof seoAiTraining === 'boolean' ? seoAiTraining : true),\n }\n if (robots.enabled ?? true) {\n const robotsPath = path.join(outDir, 'robots.txt')\n // Factory-as-single-source (validated override): a hand-authored\n // public/robots.txt Vite copied into dist is KEPT when it meets the factory\n // floor (`isHandAuthoredRobotsAcceptable`: a real `User-agent: *` group and\n // not an HTML page). A stub (`Sitemap:`-only, like just-posh) or an\n // SPA-shell HTML page fails the floor and is REPLACED with factory robots.\n // `force` always overwrites; an absent file is always written.\n const existing =\n fs.existsSync(robotsPath) && !robots.force ? fs.readFileSync(robotsPath, 'utf8') : null\n const keepHandAuthored = existing !== null && isHandAuthoredRobotsAcceptable(existing)\n if (keepHandAuthored) {\n // A floor-meeting hand-authored robots.txt is not replaced. An\n // `aiTraining: false` opt-out is honoured by APPENDING a `Disallow: /`\n // group for each training bot / control token it does not name; every\n // existing line is preserved. A bot it DOES name must already be exactly\n // `Disallow: /`, else the build fails (never silently keep allowing it).\n if (effectiveRobots.aiTraining === false && !preview) {\n const conflicts = findAiTrainingRobotsConflicts(existing)\n if (conflicts.length > 0) throw new RobotsAiTrainingConflictError(robotsPath, conflicts)\n const { text, added } = appendAiTrainingOptOut(existing)\n if (added.length > 0) {\n fs.writeFileSync(robotsPath, text, 'utf8')\n written.push('robots.txt')\n }\n if (debug) console.log(`[dcs-seo] dist/robots.txt is hand-authored; appended AI training opt-out for ${added.join(', ') || '(none)'}`)\n } else if (debug) {\n console.log('[dcs-seo] dist/robots.txt is hand-authored and meets the floor; leaving it')\n }\n } else {\n const txt = buildRobotsTxt({\n siteUrl: effectiveSiteUrl,\n preview,\n robots: effectiveRobots,\n hasSitemap: wroteSitemap,\n })\n fs.writeFileSync(robotsPath, txt, 'utf8')\n written.push('robots.txt')\n if (debug) {\n console.log(\n existing !== null\n ? '[dcs-seo] dist/robots.txt failed the factory floor; overwrote with emitted robots'\n : '[dcs-seo] wrote robots.txt'\n )\n }\n }\n }\n\n // ── llms.txt (not in preview) ─────────────────────────────────────────────\n if (llms && !preview) {\n const txt = buildLlmsTxt({\n routes,\n siteUrl: effectiveSiteUrl,\n seoConfig,\n exclude,\n noindex,\n excludedGlobs,\n })\n if (txt) {\n fs.writeFileSync(path.join(outDir, 'llms.txt'), txt, 'utf8')\n written.push('llms.txt')\n if (debug) console.log('[dcs-seo] wrote llms.txt')\n } else if (debug) {\n console.log('[dcs-seo] nothing indexable; llms.txt not written')\n }\n }\n\n return written\n}\n\n/**\n * Pick a structured FAQ array (`[{ q, a }]`) for a page from content.yaml, if\n * one exists under a `faq` key (page-scoped, then global). Returns `undefined`\n * when there is no structured Q&A — a `<FaqPage />` component is NOT a source,\n * so its pages correctly yield nothing (honesty).\n */\nfunction pickPageFaq(\n content: ContentConfig | undefined,\n pageSlug: string\n): FaqSource[] | undefined {\n if (!content) return undefined\n const fromBlock = (block: Record<string, unknown> | undefined): FaqSource[] | undefined => {\n if (!block) return undefined\n const v = block['faq']\n return Array.isArray(v) ? (v as FaqSource[]) : undefined\n }\n return fromBlock(content.pages?.[pageSlug]) ?? fromBlock(content.global)\n}\n\n/**\n * Core emitter, separated from Vite so it is unit-testable.\n *\n * For each route: build the head tags from the shared resolver, splice them\n * into the shell HTML, and write `dist/<path>/index.html`. Returns the number\n * of files written. Pure aside from `fs` writes — deterministic + idempotent.\n */\nexport function emitStaticSeoHtml(params: {\n outDir: string\n shellHtml: string\n routes: PageRouteEntry[]\n seoConfig: SeoConfiguration | undefined\n /**\n * Parsed `.dcs/content.yaml` — threads REAL review items (honesty-gated) into\n * the per-route LocalBusiness node. Optional; omit ⇒ no Review/aggregateRating.\n */\n contentConfig?: ContentConfig\n exclude?: string[]\n noindex?: string[]\n /** `pages.yaml` top-level `excluded:` globs — routes matching are NOT emitted. */\n excludedGlobs?: string[]\n debug?: boolean\n}): number {\n const {\n outDir,\n shellHtml,\n routes,\n seoConfig,\n contentConfig,\n exclude = [],\n noindex = [],\n excludedGlobs = [],\n debug = false,\n } = params\n\n const noindexSet = new Set(noindex)\n\n // Route → human title map (for breadcrumb hop labels), from the manifest.\n const siteUrl = seoConfig?.global?.siteUrl ?? ''\n const routeTitles: Record<string, string> = { '/': 'Home' }\n for (const r of routes) {\n if (r.title && r.path) routeTitles[r.path.replace(/\\/+$/, '') || '/'] = r.title\n }\n\n let written = 0\n for (const route of routes) {\n // Exclusion goes through the SHARED predicate (`routeExclusionReason`), the\n // same one that filters the `__DCS_PAGES__` runtime manifest. Two agreeing\n // implementations is how a private `/dev-*` route came to be never-baked but\n // still runtime-asserted (C-361 F5); one predicate is why it cannot recur.\n // An excluded route must NOT get a per-route index.html, or it becomes a\n // crawlable/indexable page despite being intentionally hidden — a privacy\n // and crawl-budget leak. Same glob semantics as the sitemap path.\n const exclusion = routeExclusionReason(route, { exclude, excludedGlobs })\n if (exclusion) {\n if (debug) {\n console.log(\n `[dcs-seo] skip (${exclusion === 'excluded-glob' ? 'excluded glob' : 'excluded'}): ${route.path}`\n )\n }\n continue\n }\n\n const forceNoindex =\n noindexSet.has(route.path) || (route.slug && noindexSet.has(route.slug))\n\n // Breadcrumb trail from route depth (home ⇒ none); titles from the manifest.\n const breadcrumbTrail = siteUrl\n ? breadcrumbTrailFromRoute(route.path, siteUrl, routeTitles)\n : undefined\n\n // REAL reviews for this page from content.yaml (honesty-gated downstream).\n const reviews: ReviewSource[] | undefined = contentConfig\n ? findReviewItemsForPage(contentConfig, route.slug)\n : undefined\n\n // Trade/occupational license from content.yaml `business.license` (dark when\n // the key is empty/absent — no hasCredential is emitted). Honesty-gated in\n // buildHasCredential downstream.\n const license: string | undefined = contentConfig\n ? findBusinessLicense(contentConfig, route.slug)\n : undefined\n\n // BlogPosting for a blog post route — only when seo.yaml has NOT already\n // hand-authored one (buildHeadTags skips ours if it has). A blog post is a\n // route nested under `/blog/` (depth ≥ 2) with a manifest title.\n const isBlogPost = /^\\/blog\\/.+/.test(route.path) && !!route.title\n const blogMeta: BlogMeta | undefined = isBlogPost\n ? { headline: route.title, url: breadcrumbTrail?.[breadcrumbTrail.length - 1]?.item }\n : undefined\n\n // FAQ from a structured `.dcs/faq.yaml`-style block on the content page, if\n // present (honesty-gated). Component-only FAQ pages carry no such data.\n const faq: FaqSource[] | undefined = pickPageFaq(contentConfig, route.slug)\n\n const tags = buildHeadTags(route.slug, route.path, seoConfig, {\n includeKeywords: true,\n fallbackTitle: route.title,\n robots: forceNoindex ? 'noindex, nofollow' : undefined,\n emitGraph: true,\n breadcrumbTrail,\n reviews,\n license,\n blogMeta,\n faq,\n })\n\n const html = spliceHeadHtml(shellHtml, tags)\n const outFile = routeToOutputFile(outDir, route.path)\n\n fs.mkdirSync(path.dirname(outFile), { recursive: true })\n fs.writeFileSync(outFile, html, 'utf8')\n written++\n\n if (debug) {\n console.log(\n `[dcs-seo] wrote ${path.relative(outDir, outFile)} (title=\"${tags.title}\"${\n forceNoindex ? ', noindex' : ''\n })`\n )\n }\n }\n\n return written\n}\n\n/**\n * What the render pass produced, INCLUDING whether it ran at all. The\n * `rendererAvailable` / `eligibleRoutes` fields are what make the P1 rail\n * provably executed rather than silently skipped (C-338).\n */\ninterface BodyPrerenderOutcome {\n rendererAvailable: boolean\n headObservations: HeadObservation[]\n eligibleRoutes: string[]\n filteredRoutes: Array<{ route: string; reason: string }>\n}\n\n/**\n * Run the body-prerender pass: bring up the headless renderer, fill each\n * indexable route's `<div id=\"app\">` with its real rendered DOM, then tear the\n * renderer down. Missing infra (no playwright / no browser) makes the BODY pass\n * a no-op but is reported back so the P1 rail can fail loud instead of passing\n * green having checked nothing; a render crash propagates a `BodyPrerenderError`.\n */\nasync function runBodyPrerender(\n ctx: { outDir: string; routes: PageRouteEntry[]; excludedGlobs: string[] },\n opts: {\n exclude: string[]\n noindex: string[]\n debug: boolean\n /** `false` ⇒ render for OBSERVATION only (P1) and leave `dist/` untouched. */\n spliceBody: boolean\n }\n): Promise<BodyPrerenderOutcome> {\n // Kill-test hook (C-338): forces the renderer-absent path so the P1 execution\n // assertion can be proven to FAIL a build. NOT an escape hatch — with the\n // assertion in place, setting this in `error` mode turns the build RED.\n const forcedAbsent = process.env.DCS_SEO_FORCE_NO_RENDERER === '1'\n if (forcedAbsent) {\n console.warn(\n '[dcs-seo] DCS_SEO_FORCE_NO_RENDERER=1 — pretending the headless renderer is absent ' +\n '(kill-test hook; in error mode this MUST fail the build).'\n )\n }\n const handle = forcedAbsent\n ? null\n : await createPlaywrightRenderer({ outDir: ctx.outDir, debug: opts.debug })\n if (!handle) {\n // playwright/browser unavailable. Say so explicitly — without a renderer the\n // P1 head-honesty rail cannot run either, and a rail that silently does not\n // run is the exact class this work exists to close. The CALLER turns this\n // into a hard failure in `error` mode (see `assertHeadHonestyExecuted`).\n console.warn(\n '[dcs-seo] no headless renderer available: body prerender AND the P1 ' +\n 'baked-vs-rendered <head> assert were both SKIPPED for this build.'\n )\n return {\n rendererAvailable: false,\n headObservations: [],\n eligibleRoutes: [],\n filteredRoutes: [],\n }\n }\n\n console.log(\n opts.spliceBody\n ? '[dcs-seo] body-prerender: rendering routes via headless Chromium…'\n : '[dcs-seo] head-honesty: rendering routes via headless Chromium (observe-only)…'\n )\n try {\n const result = await prerenderBodies({\n outDir: ctx.outDir,\n routes: ctx.routes,\n renderer: handle.renderer,\n exclude: opts.exclude,\n noindex: opts.noindex,\n excludedGlobs: ctx.excludedGlobs,\n spliceBody: opts.spliceBody,\n debug: opts.debug,\n })\n if (opts.spliceBody) {\n console.log(\n `[dcs-seo] body-prerender: ${result.prerendered} route(s) now have ` +\n `crawler-visible body content (${result.skipped} skipped)`\n )\n }\n return {\n rendererAvailable: true,\n headObservations: result.headObservations,\n eligibleRoutes: result.eligibleRoutes,\n filteredRoutes: result.filteredRoutes,\n }\n } finally {\n await handle.close()\n }\n}\n\n/**\n * P2 — collect every URL the just-completed emit published and assert it\n * resolves to what it promises.\n *\n * Deliberately two-phase, because the two halves have different reliability:\n * the same-origin half is proven against `dist/` with no network and is\n * therefore a hard gate; the cross-origin half asks the network and only fails\n * on a definitive wrong answer. See `emittedUrls.ts` for the verdict table.\n */\nasync function runEmittedUrlHonesty(params: {\n outDir: string\n projectRoot: string\n routes: PageRouteEntry[]\n siteUrl: string | undefined\n base: string\n mode: HonestyMode\n allow: string[]\n network: boolean\n debug: boolean\n /** Receives the audit BEFORE any throw, so the report survives a red build. */\n sink?: (audit: EmittedUrlAudit, violations: EmittedUrlViolation[]) => void\n}): Promise<EmittedUrlAudit | null> {\n const { outDir, projectRoot, routes, siteUrl, base, mode, allow, network, debug, sink } = params\n if (mode === 'off') {\n console.warn(\n '[dcs-seo] emitted-URL honesty is OFF for this build — nothing is checking that the ' +\n 'logo/og:image/sitemap URLs this site publishes actually resolve.'\n )\n return null\n }\n if (allow.length > 0) {\n console.warn(\n `[dcs-seo] emitted-URL honesty: ${allow.length} URL(s) EXEMPTED: ${allow.join(', ')}`\n )\n }\n\n const files: Array<{ path: string; from: string; kind: 'html' | 'sitemap' | 'llms' }> = []\n for (const route of routes) {\n files.push({ path: routeToOutputFile(outDir, route.path), from: route.path, kind: 'html' })\n }\n files.push({ path: path.join(outDir, 'sitemap.xml'), from: 'sitemap.xml', kind: 'sitemap' })\n files.push({ path: path.join(outDir, 'llms.txt'), from: 'llms.txt', kind: 'llms' })\n\n const collected = dedupeUrls(collectEmittedUrlsFromFiles(files))\n const classified: ClassifiedUrl[] = collected.map((u) => classifyUrl(u, siteUrl))\n\n const sameOrigin = auditSameOriginAssets({ urls: classified, outDir, base, allow })\n const violations: EmittedUrlViolation[] = [...sameOrigin.violations]\n\n // Every count below comes from the CHECKER, never from `classified.length` —\n // that conflation is what let C-334's log claim page URLs were verified when\n // both checkers only ever look at assets (C-338).\n const audit: EmittedUrlAudit = {\n collected: classified.length,\n sameOriginAssetsChecked: sameOrigin.checked,\n remoteAssetsChecked: 0,\n remoteProbed: 0,\n remoteCached: 0,\n unknown: 0,\n pagesUnverified: classified.filter((u) => u.expectation === 'page').length,\n unfetchable: classified.filter((u) => u.locality === 'unfetchable').length,\n exempted: sameOrigin.exempted,\n failed: 0,\n }\n\n if (network) {\n const remote = await checkRemoteAssets(classified, { projectRoot, allow, debug })\n violations.push(...remote.violations)\n for (const w of remote.warnings) {\n console.warn(`[dcs-seo] emitted-URL honesty (UNKNOWN, not a failure): ${w.url} — ${w.reason}`)\n }\n audit.remoteAssetsChecked = remote.checked ?? 0\n audit.remoteProbed = remote.probed\n audit.remoteCached = remote.cached\n audit.unknown = remote.warnings.length\n audit.exempted += remote.exempted ?? 0\n if (debug) {\n console.log(\n `[dcs-seo] emitted-URL honesty: remote probes — ${remote.probed} network, ${remote.cached} cached`\n )\n }\n } else {\n // Probing off ⇒ every remote asset is UNKNOWN. It must not be silently\n // absorbed into a \"verified\" total.\n audit.unknown = classified.filter(\n (u) => u.locality === 'remote' && u.expectation === 'asset'\n ).length\n console.log(\n '[dcs-seo] emitted-URL honesty: cross-origin probes disabled — ' +\n `${audit.unknown} remote asset URL(s) are UNCHECKED this build; same-origin still enforced`\n )\n }\n\n audit.failed = violations.length\n sink?.(audit, violations)\n const checkedTotal = auditCheckedTotal(audit)\n\n // Execution assertion: collecting nothing means the rail did not run. In\n // `error` mode that is a hard failure, not a green build.\n if (audit.collected === 0) {\n const err = new EmittedUrlNotRunError(\n audit,\n `0 URLs were collected from ${files.length} emitted artifact(s)`\n )\n if (mode === 'error') throw err\n console.warn(err.message)\n console.warn('[dcs-seo] emitted-URL honesty is in WARN mode; this build is NOT gated on the above.')\n return audit\n }\n // Collected-but-checked-nothing is legal (a site can publish only page URLs)\n // but must never read as a pass. Say it in every mode.\n if (checkedTotal === 0) {\n console.warn(\n `[dcs-seo] emitted-URL honesty VERIFIED NOTHING this build: ${audit.collected} URL(s) were ` +\n `collected but none was a checkable asset (${audit.pagesUnverified} page(s), ` +\n `${audit.unknown} unknown, ${audit.exempted} exempted, ${audit.unfetchable} unfetchable).`\n )\n }\n\n if (violations.length === 0) {\n console.log(formatEmittedUrlAudit(audit, routes.length))\n return audit\n }\n\n if (mode === 'warn') {\n console.warn(formatEmittedUrlReport(violations))\n console.warn(formatEmittedUrlAudit(audit, routes.length))\n console.warn('[dcs-seo] emitted-URL honesty is in WARN mode; this build is NOT gated on the above.')\n return audit\n }\n throw new EmittedUrlError(violations)\n}\n\n/**\n * P12 — assert the encoding declaration lands inside the 1024-byte sniffing\n * window in every emitted document.\n *\n * The hoist in `emitStaticSeoHtml`'s shell should make this unfailable; the\n * assert exists so that if the hoist is ever bypassed (a new head injector, a\n * post-processing plugin that runs later, a hand-rolled shell), the build says so\n * instead of shipping a document whose encoding is a coin flip.\n */\nfunction runCharsetBudget(params: {\n outDir: string\n routes: PageRouteEntry[]\n mode: HonestyMode\n debug: boolean\n /** Receives the counts BEFORE any throw, so the report survives a red build. */\n sink?: (summary: { checked: number; failed: number; worstOffset: number }) => void\n}): void {\n const { outDir, routes, mode, debug, sink } = params\n if (mode === 'off') return\n\n const checked: string[] = []\n let failed = 0\n let worstOffset = 0\n const emit = () => sink?.({ checked: checked.length, failed, worstOffset })\n for (const route of routes) {\n const file = routeToOutputFile(outDir, route.path)\n let html: string\n try {\n html = fs.readFileSync(file, 'utf8')\n } catch {\n continue\n }\n const rel = path.relative(outDir, file)\n const result = checkCharsetBudget(html)\n worstOffset = Math.max(worstOffset, result.offset)\n if (!result.ok) {\n failed += 1\n if (mode === 'warn') {\n console.warn(new CharsetBudgetError(rel, result).message)\n continue\n }\n emit()\n throw new CharsetBudgetError(rel, result)\n }\n const warning = formatCharsetHeadroomWarning(rel, result)\n if (warning) console.warn(warning)\n checked.push(rel)\n }\n emit()\n if (debug || checked.length > 0) {\n console.log(\n `[dcs-seo] charset budget: ${checked.length} emitted document(s) declare their encoding ` +\n `inside the first 1024 bytes`\n )\n }\n}\n\n/**\n * Vite plugin that injects .dcs/seo.yaml at build time and, optionally, emits\n * per-route static `<head>` HTML for SPA SEO.\n *\n * @param options - Plugin configuration\n * @returns Vite plugin\n */\nexport function dcsSeoPlugin(options: DcsSeoPluginOptions = {}): Plugin {\n const {\n seoPath = '.dcs/seo.yaml',\n debug = false,\n emitStaticHtml = false,\n prerenderBody,\n pagesPath = '.dcs/pages.yaml',\n contentPath = '.dcs/content.yaml',\n exclude = [],\n noindex = [],\n // Site files default ON whenever per-route HTML emission is on, so the\n // sites already using emitStaticHtml gain sitemap/robots/llms with no edit.\n emitSiteFiles: emitSiteFilesOpt = emitStaticHtml,\n siteUrl,\n headHonesty: headHonestyOpt,\n urlHonesty: urlHonestyOpt,\n charsetBudget: charsetBudgetOpt,\n robots = {},\n // Self-detect preview builds from DCS_PREVIEW (mirrors dcsEditorPlugin) so a\n // release/** SWA preview build never body-prerenders; an explicit option wins.\n preview = process.env.DCS_PREVIEW === 'true',\n llms = true,\n gitLastmod,\n lastmodSources,\n dirIndex = true,\n } = options\n\n let resolvedConfig: ResolvedConfig\n // Captured during configResolved — gates the serve-only inline HTML inject.\n let isDev = false\n\n return {\n name: 'dcs-seo',\n\n configResolved(config) {\n resolvedConfig = config\n isDev = config.command === 'serve'\n // C-1965: VitePress exposes its resolved SiteConfig as `config.vitepress`\n // (the same object for the client and the SSR resolution). Installing is\n // guarded on that object, so the second resolution is a no-op.\n if (config.command === 'build') {\n const siteConfig = (config as ResolvedConfig & { vitepress?: unknown }).vitepress\n if (isVitePressSiteConfig(siteConfig)) {\n // dirIndex:false: the emitter is off, so a manifest an earlier build\n // left at DCS_DIR_INDEX_MANIFEST must not survive to vouch for this\n // dist (removed here, before any buildEnd can write one).\n if (dirIndex !== false) installDirIndex(siteConfig)\n else clearDirIndexManifest()\n }\n }\n },\n\n config(config, env) {\n // ── Dev / preview (serve) ──────────────────────────────────────────────\n // Don't bake seo.yaml into the bundle. Redirect the `__DCS_SEO__` define\n // to a browser global that `transformIndexHtml` (below) refreshes from\n // disk on every HTML request — live preview with NO server.restart().\n // The consumer is untouched: it still reads the bare `__DCS_SEO__`\n // identifier, which this define rewrites to `globalThis.__DCS_SEO__`.\n // (VitePress treats `useSEO` as a no-op and bakes SEO via\n // transformPageData, so this only affects the runtime `useSEO` SPA path.)\n if (env.command === 'serve') {\n return {\n define: {\n __DCS_SEO__: 'globalThis.__DCS_SEO__',\n __DCS_PAGES__: 'globalThis.__DCS_PAGES__',\n },\n }\n }\n\n // ── Production build ───────────────────────────────────────────────────\n // Unchanged: read seo.yaml now and bake it into the bundle as a literal.\n const projectRoot = config.root || process.cwd()\n\n // The ROUTE MANIFEST for the runtime re-assert (`installSeoHead`).\n //\n // It is baked here — not read from `pages.yaml` at runtime — so the router\n // hook resolves against the SAME map the build-time emitter walked. The\n // `noindex` list rides along because it is a plugin OPTION, not a file:\n // without it the runtime cannot know a route was baked `noindex, nofollow`\n // and would republish `index, follow` over it (measured live on iron-oak\n // /account and /projects, C-357).\n //\n // Emitted unconditionally, independent of the seo.yaml branch below —\n // `installSeoHead` needs it in BOTH cases, and a bare `__DCS_PAGES__`\n // identifier with no define is a ReferenceError in a consumer bundle.\n // IT MODELS WHAT THE EMITTER WRITES, NOT WHAT pages.yaml DECLARES\n // (C-361 F5). Routes the emitter SKIPS — `exclude` entries and `excluded:`\n // globs — are omitted here too, through the SAME `routeExclusionReason`\n // predicate the emit loop calls. Without that filter a private `/dev-*`\n // route was never baked (correct) yet still runtime-asserted with a\n // canonical and `index, follow` on the first in-app navigation (wrong):\n // the manifest promised the runtime a page the build had deliberately\n // refused to publish. Omitting is chosen over carrying exclude semantics\n // into the browser because it needs no glob engine at runtime and cannot\n // disagree with the emitter by construction.\n const pagesDefine = ((): string => {\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (!routes) {\n // No manifest ⇒ no per-route emission and no runtime manifest, so a\n // noindex list here is inert everywhere. Not a hard failure (the\n // missing manifest is its own, already-warned condition), but say so\n // rather than let the operator believe the directive landed.\n if (noindex.length > 0) {\n console.warn(\n `[dcs-seo] noindex has ${noindex.length} entr${noindex.length === 1 ? 'y' : 'ies'} ` +\n `but ${pagesPath} is missing or empty — the list matches nothing and is inert.`\n )\n }\n return 'undefined'\n }\n // C-416: a noindex entry naming no page emits NO document, so the\n // directive silently does nothing and the URL stays crawlable. Checked\n // against the FULL manifest, before exclusion, and thrown from here so\n // it cannot be swallowed by the writeBundle emit try/catch.\n assertNoOrphanNoindexEntries(noindex, routes)\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n const emitted = routes.filter((r) =>\n isRouteEmitted(r, { exclude, excludedGlobs })\n )\n assertNoDuplicateRoutePaths(emitted)\n return JSON.stringify({\n routes: emitted.map((r) => ({\n slug: r.slug,\n path: r.path,\n ...(r.title ? { title: r.title } : {}),\n })),\n noindex,\n })\n })()\n\n const loaded = loadSeoConfig(projectRoot, seoPath, debug)\n if (!loaded) {\n return {\n define: {\n __DCS_SEO__: 'undefined',\n __DCS_PAGES__: pagesDefine,\n },\n }\n }\n\n if (debug) {\n console.log(`[dcs-seo] Loaded ${loaded.foundPath}`)\n console.log(`[dcs-seo] Version: ${loaded.config.version}`)\n console.log(`[dcs-seo] Site Name: ${loaded.config.global?.siteName || '(not set)'}`)\n console.log(\n `[dcs-seo] Pages: ${Object.keys(loaded.config.pages ?? {}).join(', ') || '(none)'}`\n )\n }\n\n return {\n define: {\n __DCS_SEO__: JSON.stringify(loaded.config),\n __DCS_PAGES__: pagesDefine,\n },\n }\n },\n\n /**\n * Build-time static `<head>` emitter (opt-in via `emitStaticHtml`).\n *\n * Runs after the bundle is written so the built `index.html` shell exists\n * on disk. For an SPA, Vite emits a single `index.html`; we fan it out to\n * per-route files with route-specific `<head>` content.\n *\n * Fully defensive: any missing/unparseable input logs a warning and\n * no-ops. Never throws (so it can never break a production build).\n */\n async writeBundle() {\n if (!emitStaticHtml) {\n // The whole emit path is gated on emitStaticHtml. If the operator\n // explicitly asked for site files (`emitSiteFiles: true`) while\n // emitStaticHtml is off, that request is silently inert — warn so it's\n // not mistaken for \"robots/sitemap were emitted\".\n if (options.emitSiteFiles === true) {\n console.warn(\n '[dcs-seo] emitSiteFiles:true is ignored because emitStaticHtml is false; ' +\n 'set emitStaticHtml:true to emit sitemap.xml/robots.txt/llms.txt'\n )\n }\n return\n }\n\n // Captured inside the never-break emit below, consumed by the separately\n // guarded body-prerender step after it (so a fabrication/crash there can\n // fail the build loud instead of being swallowed by the emit try/catch).\n let bodyPrerenderCtx:\n | { outDir: string; routes: PageRouteEntry[]; excludedGlobs: string[] }\n | null = null\n\n /** P12 shell measurement (before/after the charset hoist), for the report. */\n let charsetShell: {\n hoisted: boolean\n beforeOffset: number\n beforeHeadroom: number\n beforeOk: boolean\n afterOffset: number\n afterHeadroom: number\n afterOk: boolean\n } | null = null\n\n // Same pattern for the C-334 honesty rails: gathered inside the\n // never-break emit, EXECUTED outside it. An emitter that fails is a\n // degraded build; a rail that fails is a build that must go red — so the\n // rails must not be swallowed by the emitter's defensive catch. (That\n // swallow is precisely how a check becomes vacuously green.)\n let honestyCtx:\n | {\n outDir: string\n projectRoot: string\n routes: PageRouteEntry[]\n siteUrl: string | undefined\n base: string\n headMode: HonestyMode\n headAllow: string[]\n headCheckDescription: boolean\n urlMode: HonestyMode\n urlAllow: string[]\n urlNetwork: boolean\n charsetMode: HonestyMode\n /** `true` when the render pass runs only to feed the P1 rail. */\n renderForHonestyOnly: boolean\n }\n | null = null\n\n try {\n const projectRoot = resolvedConfig?.root || process.cwd()\n const outDir = resolveOutDir(resolvedConfig)\n\n if (!fs.existsSync(outDir)) {\n console.warn(`[dcs-seo] emitStaticHtml: outDir not found (${outDir}); skipping`)\n return\n }\n\n const shellPath = path.join(outDir, 'index.html')\n if (!fs.existsSync(shellPath)) {\n console.warn(\n `[dcs-seo] emitStaticHtml: no index.html in ${outDir}; nothing to emit`\n )\n return\n }\n\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (!routes) {\n console.warn(\n `[dcs-seo] emitStaticHtml: ${pagesPath} missing or empty; skipping per-route emission`\n )\n return\n }\n\n const loaded = loadSeoConfig(projectRoot, seoPath, debug)\n if (!loaded) {\n // seo.yaml is optional for emission — routes still get baked with\n // global/runtime defaults (which here means just the shell title and\n // a derived canonical-less head). Warn so the operator knows.\n console.warn(\n `[dcs-seo] emitStaticHtml: ${seoPath} missing or unparseable; emitting with defaults only`\n )\n }\n\n // ── P12: hoist <meta charset> before anything is fanned out ─────────\n // The motion-token <style> is injected `head-prepend`, which lands it\n // ABOVE the site's own <meta charset> and pushes the encoding\n // declaration to byte ~910 of the spec's 1024-byte sniffing window\n // (measured identical on two fleet sites, 2026-07-26). Fixing the SHELL\n // fixes every per-route file the loop below writes from it, in one place,\n // with no per-site edit. `hoistCharsetMeta` is idempotent, so a shell\n // that is already correct is untouched.\n const rawShellHtml = fs.readFileSync(shellPath, 'utf8')\n const shellHtml = hoistCharsetMeta(rawShellHtml)\n // Recorded for the honesty report: the BEFORE/AFTER byte offsets are the\n // P12 measurement the fleet matrix asks for, per site.\n {\n const b = checkCharsetBudget(rawShellHtml)\n const a = checkCharsetBudget(shellHtml)\n charsetShell = {\n hoisted: shellHtml !== rawShellHtml,\n beforeOffset: b.offset,\n beforeHeadroom: b.headroom,\n beforeOk: b.ok,\n afterOffset: a.offset,\n afterHeadroom: a.headroom,\n afterOk: a.ok,\n }\n }\n if (shellHtml !== rawShellHtml) {\n // Write it back too: `dist/index.html` is what the host serves as the\n // SPA fallback for every unmatched path, and a route manifest without\n // `/` would otherwise leave the shell un-hoisted.\n fs.writeFileSync(shellPath, shellHtml, 'utf8')\n const before = checkCharsetBudget(rawShellHtml)\n const after = checkCharsetBudget(shellHtml)\n console.log(\n `[dcs-seo] charset budget: hoisted <meta charset> from byte ${before.offset} ` +\n `to byte ${after.offset} (${after.headroom} bytes of the 1024-byte ` +\n `encoding-sniffing window now free)`\n )\n }\n\n // pages.yaml top-level `excluded:` globs gate BOTH the per-route HTML\n // emission below and the sitemap/llms set inside emitSiteFiles, so an\n // excluded route is never written as a crawlable index.html.\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n // Optional: load content.yaml so REAL reviews can feed the honest\n // Review/aggregateRating on the per-route LocalBusiness node. Absent or\n // unparseable ⇒ undefined ⇒ no reviews emitted (no synthesis).\n const contentConfig = loadContentConfig(projectRoot, contentPath, debug)\n\n // C-1260 finding 3 — a LocalBusiness `address` that is PRESENT BUT\n // PARTIAL is spread verbatim into the @graph by `buildGlobalGraph`, so\n // it reaches crawlers looking finished. WARN only: the emitted shape is\n // deliberately unchanged (removing a half-address would silently drop\n // authored data), and an ABSENT address is never reported because a\n // service-area business is supposed to omit it.\n const addressGaps = findPostalAddressGaps(loaded?.config?.global ?? {})\n if (addressGaps.length > 0) {\n console.warn(formatPostalAddressGapReport(addressGaps))\n }\n\n const written = emitStaticSeoHtml({\n outDir,\n shellHtml,\n routes,\n seoConfig: loaded?.config,\n contentConfig,\n exclude,\n noindex,\n excludedGlobs,\n debug,\n })\n\n if (debug) {\n console.log(`[dcs-seo] emitStaticHtml: wrote ${written} per-route HTML file(s)`)\n }\n\n // ── site-wide static files (sitemap.xml, robots.txt, llms.txt) ──────\n // Emitted AFTER the per-route HTML loop so canonicals/routes are\n // resolved and the shell exists. Reuses the already-loaded routes +\n // seoConfig (no second manifest read). Same outDir/existsSync guard +\n // the outer try/catch — so it can never break a production build.\n if (emitSiteFilesOpt) {\n const siteFiles = emitSiteFiles({\n outDir,\n projectRoot,\n pagesPath,\n routes,\n seoConfig: loaded?.config,\n siteUrl,\n exclude,\n noindex,\n preview,\n robots,\n llms,\n gitLastmod,\n lastmodSources,\n contentPath,\n debug,\n })\n if (debug) {\n console.log(\n `[dcs-seo] emitSiteFiles: wrote ${siteFiles.length} site file(s): ${\n siteFiles.join(', ') || '(none)'\n }`\n )\n }\n }\n\n // Body prerender runs only when enabled for this build (default ON when\n // emitting; off via the `prerenderBody` option, the seo.yaml escape\n // hatch, or preview mode). Stash what it needs so it executes under its\n // own fail-loud guard below, NOT this swallow-catch.\n // Extra guard: the prerender server serves the built assets from root,\n // so a non-root `base` (subpath preview deploys like /kept/) would 404\n // every asset → the app never mounts → a spurious build failure. Skip\n // (loudly) rather than fail — head + JSON-LD are already emitted.\n const buildBase = resolvedConfig?.base ?? '/'\n const baseIsRoot = buildBase === '/' || buildBase === './' || buildBase === ''\n const bodyPrerenderOn = isBodyPrerenderEnabled({\n emitStaticHtml,\n prerenderBodyOption: prerenderBody,\n preview,\n seoPrerenderBody: loaded?.config?.prerenderBody,\n })\n if (bodyPrerenderOn) {\n if (baseIsRoot) {\n bodyPrerenderCtx = { outDir, routes, excludedGlobs }\n } else {\n console.warn(\n `[dcs-seo] body prerender skipped: non-root base \"${buildBase}\" ` +\n '(assets would not resolve through the prerender server; head + JSON-LD still emitted)',\n )\n }\n }\n\n // ── C-334 honesty rails: resolve severities, stash the context ───────\n // Resolution order is env > seo.yaml > plugin option > default `error`,\n // so the most operator-visible signal wins and a lowered gate always\n // shows up either in git (seo.yaml) or in the build log (env).\n // `*OptBlock` = the vite.config option; `seo*Block` = the .dcs/seo.yaml\n // escape hatch. Kept in matching pairs so the precedence below reads at a\n // glance and a future edit cannot silently swap the two sources.\n const headOptBlock = readHonestyBlock(headHonestyOpt)\n const urlOptBlock = readHonestyBlock(urlHonestyOpt)\n const charsetOptBlock = readHonestyBlock(charsetBudgetOpt)\n const seoHeadBlock = readHonestyBlock(loaded?.config?.headHonesty ?? undefined)\n const seoUrlBlock = readHonestyBlock(loaded?.config?.urlHonesty ?? undefined)\n const seoCharsetBlock = readHonestyBlock(loaded?.config?.charsetBudget ?? undefined)\n\n const headMode = resolveHonestyMode({\n env: process.env.DCS_SEO_HEAD_HONESTY,\n seoYaml: seoHeadBlock.mode,\n option: headOptBlock.mode,\n fallback: 'error',\n })\n const urlMode = resolveHonestyMode({\n env: process.env.DCS_SEO_URL_HONESTY,\n seoYaml: seoUrlBlock.mode,\n option: urlOptBlock.mode,\n fallback: 'error',\n })\n const charsetMode = resolveHonestyMode({\n env: process.env.DCS_SEO_CHARSET_BUDGET,\n seoYaml: seoCharsetBlock.mode,\n option: charsetOptBlock.mode,\n fallback: 'error',\n })\n\n // The P1 rail needs a render. If body prerender is already running, it\n // rides along for free; if the site opted out of body prerender we still\n // render — in OBSERVE-ONLY mode, so `dist/` is untouched — because the\n // alternative is a gate that quietly does not exist on that site.\n const renderForHonestyOnly = !bodyPrerenderOn && headMode !== 'off' && baseIsRoot\n if (renderForHonestyOnly) {\n bodyPrerenderCtx = { outDir, routes, excludedGlobs }\n }\n if (headMode !== 'off' && !baseIsRoot) {\n console.warn(\n `[dcs-seo] head honesty SKIPPED: non-root base \"${buildBase}\" (the prerender ` +\n 'server cannot serve this build, so the rendered <head> cannot be observed)'\n )\n }\n\n honestyCtx = {\n outDir,\n projectRoot,\n routes,\n siteUrl: siteUrl || loaded?.config?.global?.siteUrl,\n base: buildBase,\n headMode: baseIsRoot ? headMode : 'off',\n headAllow: [...headOptBlock.allow, ...seoHeadBlock.allow],\n headCheckDescription:\n seoHeadBlock.checkDescription ?? headOptBlock.checkDescription ?? true,\n urlMode,\n urlAllow: [...urlOptBlock.allow, ...seoUrlBlock.allow],\n urlNetwork:\n process.env.DCS_SEO_URL_HONESTY_NETWORK?.toLowerCase() === 'off'\n ? false\n : (seoUrlBlock.network ?? urlOptBlock.network ?? true),\n charsetMode,\n renderForHonestyOnly,\n }\n } catch (error) {\n // A robots.txt that contradicts `robots.aiTraining: false` is a policy\n // conflict the site must resolve: it fails the build (never swallowed).\n if (error instanceof RobotsAiTrainingConflictError) throw error\n // Never break the build on any other SEO emission failure.\n console.warn('[dcs-seo] emitStaticHtml failed; build output left unchanged:', error)\n }\n\n // ── Body prerender + P1 (SEPARATE guard — fail loud) ─────────────────────\n // Deliberately OUTSIDE the swallow-catch above: missing infra (no\n // playwright / no browser) degrades gracefully to a no-op, but a route that\n // crashes or would ship broken content throws BodyPrerenderError and FAILS\n // the build. Head + JSON-LD are already on disk regardless.\n let headObservations: HeadObservation[] = []\n // Execution facts for the P1 assertion below. `rendererAvailable` starts\n // FALSE: if the render pass never ran, the rail must say so rather than\n // inherit an optimistic default.\n let rendererAvailable = false\n let eligibleRoutes: string[] = []\n let filteredRoutes: Array<{ route: string; reason: string }> = []\n if (bodyPrerenderCtx) {\n const outcome = await runBodyPrerender(bodyPrerenderCtx, {\n exclude,\n noindex,\n debug,\n spliceBody: !(honestyCtx?.renderForHonestyOnly ?? false),\n })\n headObservations = outcome.headObservations\n rendererAvailable = outcome.rendererAvailable\n eligibleRoutes = outcome.eligibleRoutes\n filteredRoutes = outcome.filteredRoutes\n }\n\n if (honestyCtx) {\n const ctx = honestyCtx\n // Machine-readable execution record (C-338). Written only when\n // DCS_SEO_HONESTY_REPORT names a path, so normal builds are untouched;\n // the fleet candidate-matrix harness sets it and reads counts from JSON\n // instead of scraping the build log. Written in a `finally` so a RED\n // build still leaves its measurement behind.\n const reportPath = process.env.DCS_SEO_HONESTY_REPORT\n const report: Record<string, unknown> = {\n schema: 1,\n generatedAt: new Date().toISOString(),\n projectRoot: ctx.projectRoot,\n outDir: ctx.outDir,\n siteUrl: ctx.siteUrl ?? null,\n base: ctx.base,\n routes: ctx.routes.length,\n p1: {\n mode: ctx.headMode,\n rendererAvailable,\n eligible: eligibleRoutes.length,\n observed: headObservations.length,\n unobserved: eligibleRoutes.filter(\n (r) => !headObservations.some((o) => o.route === r)\n ),\n filtered: filteredRoutes,\n exempted: ctx.headAllow.length,\n divergent: null as number | null,\n executed: false,\n },\n p12: { mode: ctx.charsetMode, shell: charsetShell, checked: 0, failed: 0, worstOffset: 0 },\n p2: { mode: ctx.urlMode, network: ctx.urlNetwork, audit: null as unknown },\n }\n const p1 = report.p1 as Record<string, unknown>\n try {\n // P1 — baked <head> == rendered <head>, per route. The EXECUTION\n // assertion runs first: in `error` mode a missing renderer, zero\n // eligible routes, or an eligible route with no observation is a hard\n // failure. C-334 warned and skipped here, which is how an\n // error-severity rail passed a build having checked nothing (C-338).\n const shouldCompare = assertHeadHonestyExecuted(\n {\n rendererAvailable,\n eligibleRoutes,\n observedRoutes: headObservations.map((o) => o.route),\n filteredRoutes,\n totalRoutes: ctx.routes.length,\n },\n { mode: ctx.headMode }\n )\n p1.executed = shouldCompare\n if (shouldCompare || ctx.headMode === 'off') {\n // In `error` mode this throws — record the divergences FIRST so a red\n // build still leaves the operator the list of what diverged.\n const found = findHeadHonestyViolations(headObservations, {\n allow: ctx.headAllow,\n checkDescription: ctx.headCheckDescription,\n })\n p1.divergent = found.length\n p1.violations = found\n assertHeadHonesty(headObservations, {\n mode: ctx.headMode,\n allow: ctx.headAllow,\n checkDescription: ctx.headCheckDescription,\n debug,\n })\n }\n\n // P12 — the encoding declaration is inside the sniffing window.\n runCharsetBudget({\n outDir: ctx.outDir,\n routes: ctx.routes,\n mode: ctx.charsetMode,\n debug,\n sink: (s) => Object.assign(report.p12 as object, s),\n })\n\n // P2 — every published URL resolves to what it promises. Runs LAST\n // because it is the only rail that can touch the network.\n await runEmittedUrlHonesty({\n outDir: ctx.outDir,\n projectRoot: ctx.projectRoot,\n routes: ctx.routes,\n siteUrl: ctx.siteUrl,\n base: ctx.base,\n mode: ctx.urlMode,\n allow: ctx.urlAllow,\n network: ctx.urlNetwork,\n debug,\n sink: (a, v) => {\n const p2 = report.p2 as Record<string, unknown>\n p2.audit = a\n p2.violations = v\n },\n })\n } finally {\n if (reportPath) {\n try {\n fs.mkdirSync(path.dirname(path.resolve(reportPath)), { recursive: true })\n fs.writeFileSync(path.resolve(reportPath), JSON.stringify(report, null, 2), 'utf8')\n console.log(`[dcs-seo] honesty report written: ${path.resolve(reportPath)}`)\n } catch (err) {\n console.warn('[dcs-seo] could not write honesty report:', err)\n }\n }\n }\n }\n },\n\n /**\n * Dev-only: inject the FRESH on-disk `seo.yaml` as an inline\n * `globalThis.__DCS_SEO__ = {…}` classic script at the top of `<head>`,\n * mirroring dcsContentPlugin. Lets the runtime `useSEO` SPA path reflect\n * on-disk SEO edits on the portal's `?_hc` hard reload with no restart.\n * Gated on `isDev` so it never runs in `vite`/`vitepress build` (the build\n * path keeps the baked `define` literal + the `writeBundle` emitter).\n *\n * `__DCS_PAGES__` (the `installSeoHead` route manifest) rides the same\n * refresh. It is injected INDEPENDENTLY of seo.yaml: a site can have a\n * pages.yaml and no seo.yaml, and returning early on a missing seo.yaml\n * would leave the router hook manifest-less (and therefore inert) in dev\n * only — a dev/prod behaviour split is exactly the kind of divergence this\n * plan exists to stop.\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n if (!isDev) return html\n\n const projectRoot = resolvedConfig?.root || process.cwd()\n const tags: HtmlTagDescriptor[] = []\n\n const config = readDcsYamlFresh<SeoConfiguration>(projectRoot, seoPath, 'dcs-seo', debug)\n // No file (or unparseable) ⇒ leave the global unset; the consumer's\n // `typeof globalThis.__DCS_SEO__` check falls back to defaults.\n if (config !== undefined) {\n if (debug) {\n console.log('[dcs-seo] serve: injecting fresh __DCS_SEO__ into <head>')\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_SEO__', config),\n injectTo: 'head-prepend',\n })\n }\n\n const routes = loadPagesManifest(projectRoot, pagesPath, debug)\n if (routes) {\n // SAME exclusion filter as the build define above. A dev-only manifest\n // that carried excluded routes would make `installSeoHead` behave\n // differently in dev than in prod — the dev/prod split this whole\n // inject exists to avoid.\n const excludedGlobs = loadExcludedGlobs(projectRoot, pagesPath)\n const emitted = routes.filter((r) => isRouteEmitted(r, { exclude, excludedGlobs }))\n // Dev REPORTS the colliding manifest; the BUILD is the gate that\n // refuses it. Throwing from `transformIndexHtml` would replace a\n // precise message with a blank dev-server page.\n const dupes = findDuplicateNormalizedPaths(emitted)\n if (dupes.length > 0) {\n console.error(\n `[dcs-seo] serve: ${formatDuplicateNormalizedPaths(dupes)}\\n` +\n `[dcs-seo] serve: this is reported here and FAILS the production build.`\n )\n }\n if (debug) {\n console.log(\n `[dcs-seo] serve: injecting fresh __DCS_PAGES__ (${emitted.length} of ` +\n `${routes.length} route(s), excluded ones omitted) into <head>`\n )\n }\n tags.push({\n tag: 'script',\n children: buildGlobalAssignScript('__DCS_PAGES__', {\n routes: emitted.map((r) => ({\n slug: r.slug,\n path: r.path,\n ...(r.title ? { title: r.title } : {}),\n })),\n noindex,\n }),\n injectTo: 'head-prepend',\n })\n }\n\n if (tags.length === 0) return html\n return { html, tags }\n },\n },\n\n // Watch for changes in development.\n //\n // Downgraded from `server.restart()` to a debounced client `full-reload`:\n // freshness already comes from `transformIndexHtml` re-reading the YAML on\n // every HTML request, so all we need on change is a browser reload. A\n // `server.restart()` would rebuild VitePress's dev MiniSearch index and can\n // throw \"server restart failed\" on a duplicate heading id — the fragility\n // this fix removes. A `full-reload` does neither.\n configureServer(server) {\n const projectRoot = resolvedConfig?.root || process.cwd()\n\n const watchPaths = [\n path.resolve(projectRoot, seoPath),\n path.resolve(projectRoot, '..', seoPath),\n ].map((p) => path.normalize(p))\n\n watchPaths.forEach((watchPath) => {\n if (fs.existsSync(watchPath)) {\n server.watcher.add(watchPath)\n }\n })\n\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n server.watcher.on('change', (changedPath) => {\n if (!watchPaths.includes(path.normalize(changedPath))) return\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n if (debug) {\n console.log('[dcs-seo] seo.yaml changed, sending full-reload')\n }\n server.ws.send({ type: 'full-reload' })\n }, 100)\n })\n },\n }\n}\n","/**\n * DCS Editor Plugin for Vite\n *\n * Injects the editor bridge script into customer sites when running\n * in portal preview mode (inside the visual editor iframe).\n *\n * The bridge enables:\n * - Inline text editing via contenteditable\n * - Section hover highlights and AI ✨ buttons\n * - postMessage communication with the portal\n *\n * This plugin should only be active in development/preview mode.\n * It's safe to include in production builds — it does nothing unless\n * the page detects it's inside an iframe.\n *\n * @example\n * ```typescript\n * // vite.config.ts\n * import { dcsEditorPlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * plugins: [\n * dcsEditorPlugin()\n * ]\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { Plugin, ViteDevServer } from 'vite'\n\nexport interface DcsEditorPluginOptions {\n /** Enable debug logging */\n debug?: boolean\n}\n\n/** The build variable that names the one portal origin the bridge trusts (C-2064 S4a-1). */\nexport const PORTAL_ORIGIN_ENV = 'VITE_DCS_PORTAL_ORIGIN'\n\n/**\n * The virtual module that starts the editor bridge. The configured portal\n * origin is written in as a literal: `undefined` when the variable is not set\n * (the bridge then uses its built-in origin on a sandbox host, or legacy\n * inference), otherwise the value as a string, valid or not. An invalid value\n * is NOT dropped here: the bridge must see that the variable was set, so that\n * it refuses every message instead of falling back.\n */\nexport function editorBridgeModuleSource(portalOrigin: unknown): string {\n const literal = portalOrigin === undefined ? 'undefined' : JSON.stringify(String(portalOrigin))\n return `\nimport { initEditorBridge } from '@duffcloudservices/cms/editor'\nconst startBridge = () => initEditorBridge({ portalOrigin: ${literal} })\n// The bridge only activates inside an iframe (portal preview)\nif (window.parent !== window) {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => setTimeout(startBridge, 200))\n } else {\n setTimeout(startBridge, 200)\n }\n}\n`\n}\n\n/**\n * A VitePress content-loader / static-data module id (`posts.data.ts`,\n * `x.data.mjs`, ...), with or without a query. VitePress's own matcher is\n * `/\\.data\\.m?(j|t)s($|\\?)/`; this one also takes `.cts`/`.cjs`.\n */\nconst CONTENT_LOADER_ID = /\\.data\\.[cm]?[jt]s(?:$|\\?)/\n\nexport function isContentLoaderId(id: string): boolean {\n return CONTENT_LOADER_ID.test(id)\n}\n\nfunction isInside(dir: string, file: string): boolean {\n const rel = path.relative(dir, file)\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/**\n * C-2583: preview only. Invalidate every loaded content-loader module when a\n * file under the site's srcDir (Vite's root) or its `.dcs/` changes.\n *\n * Why: the `config` hook below turns HMR off in the DCS preview. With HMR off,\n * Vite still updates the module graph for the changed file itself, but it\n * never calls any plugin's `handleHotUpdate`, and VitePress's staticDataPlugin\n * only invalidates a loader from there. The cached transform of each\n * `*.data.ts` was then served until the dev unit restarted, so a blog title or\n * card saved from the portal never reached a listing page.\n *\n * The dev server's file watcher runs with or without HMR, so the refresh hangs\n * off it. Invalidation is lazy (the loader re-runs on the next request for it),\n * so it is done on every event rather than debounced: a burst of N events costs\n * N cheap graph walks and no loader runs, and the first page load after a save\n * is never served from a not-yet-fired timer. Nothing is sent to the client\n * (under hmr:false there is no HMR channel), so this cannot cause a reload loop,\n * and a site-level plugin doing the same invalidation is harmless.\n *\n * Every loader is invalidated, not only the ones whose watch globs match:\n * VitePress keeps those globs in internal state, a loader can read files with\n * fs and no `watch` at all, and `.dcs/*.yaml` sits outside Vite's root. The\n * cost is one loader re-run per loader on the next request after a save.\n */\nfunction invalidateContentLoadersOnChange(server: ViteDevServer): void {\n const root = path.resolve(server.config.root || process.cwd())\n const dcsDirs = [...new Set([\n path.resolve(root, '.dcs'),\n path.resolve(root, '..', '.dcs'),\n path.resolve(process.cwd(), '.dcs'),\n ])].filter((dir) => fs.existsSync(dir))\n // `.dcs/` is usually a sibling of the VitePress srcDir, so outside what Vite\n // watches by default (aismb's loaders read `.dcs/*.yaml`).\n for (const dir of dcsDirs) {\n if (!isInside(root, dir)) server.watcher.add(dir)\n }\n const scopes = [root, ...dcsDirs]\n\n const onFile = (file: string) => {\n const abs = path.resolve(file)\n if (!scopes.some((dir) => isInside(dir, abs))) return\n for (const [id, mod] of server.moduleGraph.idToModuleMap) {\n if (isContentLoaderId(id)) server.moduleGraph.invalidateModule(mod)\n }\n }\n for (const event of ['change', 'add', 'unlink'] as const) server.watcher.on(event, onFile)\n}\n\n/**\n * Vite plugin that injects the editor bridge script for portal preview integration.\n *\n * The bridge auto-initializes only when the page detects it's running inside an iframe,\n * so it's safe to include in all builds — it's a no-op in standalone browsing.\n *\n * Uses a virtual module (`/__dcs-editor-bridge.js`) served through Vite's dev server\n * so that bare module specifiers (like `@duffcloudservices/cms/editor`) are properly\n * resolved through Vite's module graph rather than hitting the browser's native ESM\n * resolver, which can't handle bare specifiers.\n */\nexport function dcsEditorPlugin(options: DcsEditorPluginOptions = {}): Plugin {\n const { debug = false } = options\n const VIRTUAL_PATH = '/__dcs-editor-bridge.js'\n const RIBBON_VIRTUAL_PATH = '/__dcs-preview-ribbon.js'\n\n // Captured during configResolved — used to gate HTML injection.\n let isDev = false\n let basePath = '/'\n let isPreview = false\n // C-2064 S4a-1: the site build's VITE_DCS_PORTAL_ORIGIN, exactly as Vite\n // resolved it (process env and .env files), or undefined when it is not set.\n // The bridge validates it; this plugin only carries it across.\n let portalOrigin: unknown\n\n return {\n name: 'dcs-editor-bridge',\n\n // Preview only: stop Vite running an unreachable HMR WebSocket server.\n // Freshness comes from the cms content/seo plugins (fresh transformIndexHtml\n // re-read) + the portal's ?_hc hard reload, not HMR. NOTE: this alone does\n // NOT silence the browser — Vite still injects @vite/client and calls\n // connect(); the client-side stub in transformIndexHtml is what removes the\n // console errors. A normal local `vite dev` (no DCS_PREVIEW) keeps full HMR.\n config(_config, env) {\n if (env.command === 'serve' && process.env.DCS_PREVIEW === 'true') {\n return { server: { hmr: false } }\n }\n },\n\n configResolved(config) {\n isDev = config.command === 'serve'\n basePath = config.base ?? '/'\n isPreview = process.env.DCS_PREVIEW === 'true'\n portalOrigin = (config.env as Record<string, unknown> | undefined)?.[PORTAL_ORIGIN_ENV]\n },\n\n // Dev server only (Vite never calls configureServer for a build or for\n // `vite preview`). Active only in the DCS preview with HMR off; with HMR on,\n // VitePress refreshes its loaders from handleHotUpdate itself.\n configureServer(server) {\n if (process.env.DCS_PREVIEW !== 'true' || server.config.server.hmr !== false) return\n invalidateContentLoadersOnChange(server)\n },\n\n resolveId(id) {\n if (id === VIRTUAL_PATH || id === RIBBON_VIRTUAL_PATH) {\n return id\n }\n },\n\n load(id) {\n if (id === VIRTUAL_PATH) {\n return editorBridgeModuleSource(portalOrigin)\n }\n\n if (id === RIBBON_VIRTUAL_PATH) {\n return `\nimport { createApp } from 'vue'\nimport PreviewRibbon from '@duffcloudservices/cms/components'\n\nfunction mountRibbon() {\n // Create a detached mount point\n const el = document.createElement('div')\n el.id = 'dcs-preview-ribbon-root'\n document.body.appendChild(el)\n\n const app = createApp(PreviewRibbon)\n app.mount(el)\n}\n\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', mountRibbon)\n} else {\n mountRibbon()\n}\n`\n }\n },\n\n /**\n * Only inject the editor bridge and ribbon scripts when:\n * 1. Running in dev mode (Vite dev server), AND\n * 2. The app is served at the root path (base === '/')\n *\n * These are virtual modules resolved via absolute paths (e.g.\n * `/__dcs-editor-bridge.js`). When base !== '/', the app is served at a\n * sub-path (e.g. /iron-oak-contractors/) and the absolute virtual paths are NOT\n * routed to the Vite dev server by the reverse proxy — they hit the main\n * DCS server instead and get redirected to portal.duffcloudservices.com\n * (no CORS headers), causing browser console errors.\n *\n * In production builds, App.vue imports and mounts PreviewRibbon\n * directly, so virtual script injection is always redundant anyway.\n */\n transformIndexHtml: {\n order: 'pre',\n handler(html) {\n if (!isDev || basePath !== '/') return html\n\n if (debug) {\n console.log('[dcs-editor] Injecting editor bridge + preview ribbon script tags')\n }\n\n // Inject both the editor bridge and preview ribbon scripts\n const editorTag = `<script type=\"module\" src=\"${VIRTUAL_PATH}\"></script>`\n const ribbonTag = `<script type=\"module\" src=\"${RIBBON_VIRTUAL_PATH}\"></script>`\n const bodyHtml = html.replace('</body>', `${editorTag}\\n${ribbonTag}\\n</body>`)\n\n if (!isPreview) return bodyHtml\n\n // Preview only: neutralise Vite's HMR WebSocket. Vite always injects\n // @vite/client and unconditionally calls transport.connect(); behind the\n // preview proxy chain there is no reachable HMR WS, so it logs\n // WebSocket connection to 'wss://<portal>/?token=…' failed\n // WebSocket connection to 'wss://localhost:<port>/?token=…' failed\n // [vite] failed to connect to websocket\n // server.hmr:false does NOT stop this (the client is still injected). A\n // classic <script> in <head> runs during parse, BEFORE the deferred\n // @vite/client module, so returning an inert socket for the 'vite-hmr'\n // subprotocol silences the attempt with zero effect on app/runtime\n // WebSockets. No-op outside preview / in production builds.\n const wsStub =\n `(function(){try{var N=window.WebSocket;if(!N)return;` +\n `function hmr(p){return p==='vite-hmr'||(Array.isArray(p)&&p.indexOf('vite-hmr')!==-1)}` +\n `function Inert(){this.readyState=0}` +\n `Inert.prototype.send=function(){};Inert.prototype.close=function(){};` +\n `Inert.prototype.addEventListener=function(){};Inert.prototype.removeEventListener=function(){};` +\n `var W=function(u,p){if(hmr(p))return new Inert();return new N(u,p)};` +\n `W.prototype=N.prototype;W.CONNECTING=N.CONNECTING;W.OPEN=N.OPEN;W.CLOSING=N.CLOSING;W.CLOSED=N.CLOSED;` +\n `window.WebSocket=W}catch(e){}})()`\n\n return {\n html: bodyHtml,\n tags: [{ tag: 'script', children: wsStub, injectTo: 'head-prepend' }],\n }\n },\n },\n }\n}\n","/**\n * DCS Preview Plugin for Vue\n *\n * Registers a supplied ribbon component as a global `DcsPreviewRibbon`\n * component. The ribbon handles its own visibility — it only renders on\n * `preview.duffcloudservices.com` and hides everywhere else (localhost,\n * production domains, and inside the visual page editor iframe).\n *\n * Why does the caller pass the component in? Because this file is compiled\n * by tsup (esbuild) which has no `.vue` SFC loader. Keeping the raw `.vue`\n * import out of the compiled plugins bundle avoids the build error while\n * still letting consumer code (which *does* run through Vite) resolve the\n * SFC at dev/build time.\n *\n * @example VitePress theme/index.ts\n * ```typescript\n * import { dcsPreviewPlugin } from '@duffcloudservices/cms/plugins'\n * import PreviewRibbon from '@duffcloudservices/cms/components'\n *\n * export default {\n * Layout,\n * enhanceApp({ app }) {\n * app.use(dcsPreviewPlugin(PreviewRibbon))\n * }\n * }\n * ```\n */\n\nimport { defineComponent, h, type App, type Component, type Plugin } from 'vue'\n\nexport interface DcsPreviewPluginOptions {\n /**\n * Override the version string displayed on the ribbon.\n * If omitted, the ribbon auto-detects from VITE_SITE_VERSION or the API.\n */\n version?: string | null\n}\n\n/**\n * Creates and returns the DCS Preview plugin.\n *\n * When installed, it registers the supplied ribbon component as a global\n * `DcsPreviewRibbon` component. Add `<DcsPreviewRibbon />` to your root\n * Layout, or use the `dcsEditorPlugin` Vite plugin which injects it via\n * `transformIndexHtml`.\n *\n * @param ribbonComponent - The PreviewRibbon SFC (imported by the consumer)\n * @param options - Optional configuration\n */\nexport function dcsPreviewPlugin(\n ribbonComponent: Component,\n options: DcsPreviewPluginOptions = {},\n): Plugin {\n const Wrapper = defineComponent({\n name: 'DcsPreviewRibbon',\n setup() {\n return () => h(ribbonComponent, { version: options.version ?? null })\n },\n })\n\n return {\n install(app: App) {\n app.component('DcsPreviewRibbon', Wrapper)\n\n if (options.version !== undefined) {\n app.provide('__dcs_preview_version__', options.version)\n }\n },\n }\n}\n","/**\n * DCS CDN Image Plugin for Vite\n *\n * Rewrites local static image references (e.g. `/images/staff/photo.jpg`)\n * to CDN URLs at build time using the `.dcs/cdn-image-map.json` mapping file\n * generated by the `image-migrate adopt` CLI command.\n *\n * For raster images with WebP variants, `<img>` elements are transformed into\n * responsive `<picture>` elements with `srcset` for optimised delivery.\n * SVGs receive a simple URL swap with no variant handling.\n *\n * **In development mode this plugin is a no-op** — local `/images/` paths\n * continue to work via Vite's static asset serving so hot-reload is unaffected.\n *\n * The plugin handles two in-pipeline replacement vectors:\n *\n * 1. **Module transform** (`transform` hook) — rewrites `<img>` tags and\n * string literals in Vue SFCs, TS, JS, CSS, MD, and HTML modules.\n * 2. **Chunk rendering** (`renderChunk` hook) — rewrites image paths in\n * final rendered JS/CSS chunks AFTER Vite's `define` substitution.\n * This catches data injected by `dcsContentPlugin` via `__DCS_CONTENT__`\n * (from `.dcs/content.yaml`) which bypasses the `transform` hook.\n *\n * A third vector — **post-build file processing** — is handled by the\n * companion `dcsCdnBuildEnd` hook, which must be registered separately in\n * VitePress config. VitePress generates HTML *after* both Vite builds\n * complete, so Vite plugin hooks (`closeBundle`, `transformIndexHtml`)\n * cannot catch SSR-rendered `<head>` tags or static `public/` files like\n * `service-worker.js`.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnImagePlugin, dcsCdnBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * vite: {\n * plugins: [\n * dcsCdnImagePlugin()\n * ]\n * },\n * buildEnd: dcsCdnBuildEnd()\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { Plugin } from 'vite'\nimport { isVectorImageUrl } from '@duffcloudservices/cms-core'\n\n// ────────────────────────────────────────────────────────────────────────────\n// Types\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface CdnImageMapVariant {\n suffix: string\n blobPath: string\n cdnUrl: string\n width: number\n height: number\n size: number\n}\n\nexport interface CdnImageMapEntry {\n localPath: string\n blobPath: string\n cdnUrl: string\n fileName: string\n contentType: string\n originalSize: number\n width?: number\n height?: number\n hash: string\n variants?: CdnImageMapVariant[]\n}\n\nexport interface CdnImageMap {\n generated: string\n site: string\n cdnBase: string\n images: CdnImageMapEntry[]\n}\n\nexport interface DcsCdnImagePluginOptions {\n /** Path to cdn-image-map.json relative to project root (default: '.dcs/cdn-image-map.json') */\n mapPath?: string\n\n /**\n * Patterns to match for replacement. Each must be a **leading-slash path prefix**\n * that appears in source code (e.g. `/images/`). The `localPath` field in the\n * mapping file is compared *without* a leading slash.\n *\n * Default: `['/images/']`\n */\n pathPrefixes?: string[]\n\n /**\n * Default `sizes` attribute for responsive `<picture>` elements.\n * Override per-context via the `data-sizes` attribute on the original `<img>`.\n *\n * Default: `'(max-width: 1024px) 100vw, 1024px'`\n */\n defaultSizes?: string\n\n /** Enable debug logging */\n debug?: boolean\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ────────────────────────────────────────────────────────────────────────────\n\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\n/**\n * Build the ` width=\"W\" height=\"H\"` attribute fragment for a map entry — the\n * CLS layout-shift hint (Phase 1). Dimensions are read from the entry's\n * intrinsic `width`/`height`; they are aspect-ratio hints, so emitting the\n * source dimensions on an `<img>` whose `src` is a resized variant is correct\n * (the ratio is scale-invariant and CSS still controls the rendered size).\n *\n * Emitted ONLY when both are known and strictly positive. Older image-map\n * entries carry no top-level dimensions (and variant `height` is often `0`) —\n * in that case NO hint is emitted rather than a fabricated/wrong ratio.\n */\nfunction dimensionAttrs(entry: CdnImageMapEntry): string {\n const w = entry.width\n const h = entry.height\n if (typeof w === 'number' && w > 0 && typeof h === 'number' && h > 0) {\n return ` width=\"${w}\" height=\"${h}\"`\n }\n return ''\n}\n\n/**\n * Build a responsive `<picture>` element for a raster image that has\n * WebP variants.\n */\nfunction buildPictureElement(\n entry: CdnImageMapEntry,\n alt: string,\n extraAttrs: string,\n sizes: string\n): string {\n const variants = entry.variants ?? []\n const dims = dimensionAttrs(entry)\n\n // Collect only the display-relevant variants (not thumb, not og)\n const displayVariants = variants.filter(\n (v) => v.suffix === '-sm' || v.suffix === '-md' || v.suffix === '-lg'\n )\n\n if (displayVariants.length === 0) {\n // No display variants — fall back to original CDN URL as plain <img>\n return `<img src=\"${escapeHtml(entry.cdnUrl)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dims} loading=\"lazy\" decoding=\"async\" />`\n }\n\n const srcset = displayVariants\n .map((v) => `${v.cdnUrl} ${v.width}w`)\n .join(', ')\n\n // Pick the -md variant as the default src, or fall through to original\n const mdVariant = variants.find((v) => v.suffix === '-md')\n const fallbackSrc = mdVariant ? mdVariant.cdnUrl : entry.cdnUrl\n\n return [\n '<picture>',\n ` <source srcset=\"${srcset}\" type=\"image/webp\" sizes=\"${escapeHtml(sizes)}\" />`,\n ` <img src=\"${escapeHtml(fallbackSrc)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dims} loading=\"lazy\" decoding=\"async\" />`,\n '</picture>',\n ].join('\\n')\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Shared helpers\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Try to find and load the CDN image map from common locations.\n * VitePress nests docs under a subfolder, so we check parent dirs too.\n */\nfunction loadCdnImageMap(\n projectRoot: string,\n relativeMapPath: string,\n debug: boolean\n): Map<string, CdnImageMapEntry> | null {\n const possiblePaths = [\n path.resolve(projectRoot, relativeMapPath),\n path.resolve(projectRoot, '..', relativeMapPath),\n path.resolve(process.cwd(), relativeMapPath),\n ]\n\n for (const testPath of possiblePaths) {\n if (fs.existsSync(testPath)) {\n try {\n const raw = fs.readFileSync(testPath, 'utf8')\n const data: CdnImageMap = JSON.parse(raw)\n\n const map = new Map<string, CdnImageMapEntry>()\n for (const entry of data.images) {\n // Store both with and without leading slash for flexible matching\n map.set(entry.localPath, entry)\n if (!entry.localPath.startsWith('/')) {\n map.set('/' + entry.localPath, entry)\n }\n }\n\n if (debug) {\n console.log(`[dcs-cdn-image] Loaded ${data.images.length} entries from ${testPath}`)\n }\n return map\n } catch (error) {\n console.warn(`[dcs-cdn-image] Failed to parse ${testPath}:`, error)\n }\n }\n }\n\n if (debug) {\n console.log('[dcs-cdn-image] No cdn-image-map.json found at:')\n possiblePaths.forEach((p) => console.log(` - ${p}`))\n }\n return null\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Vite Plugin\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that rewrites static `/images/` paths to CDN URLs at build time.\n */\nexport function dcsCdnImagePlugin(options: DcsCdnImagePluginOptions = {}): Plugin {\n const {\n mapPath = '.dcs/cdn-image-map.json',\n pathPrefixes = ['/images/'],\n defaultSizes = '(max-width: 1024px) 100vw, 1024px',\n debug = false,\n } = options\n\n // Lookup map built from the JSON file: key = localPath (no leading slash)\n let imageMap: Map<string, CdnImageMapEntry> | null = null\n let isProduction = false\n\n /**\n * Check whether a source code string contains any of the path prefixes\n * we care about. Quick bail-out for files that don't reference images.\n */\n function hasImageReferences(code: string): boolean {\n return pathPrefixes.some((prefix) => code.includes(prefix))\n }\n\n /**\n * Replace image path references in any string value with CDN URLs.\n * Used for code transforms and renderChunk post-processing.\n */\n function replaceImagePaths(str: string): string {\n if (!imageMap || imageMap.size === 0) return str\n let result = str\n for (const prefix of pathPrefixes) {\n // Global replace: matches prefix followed by a relative path bounded\n // by quotes, parens, or whitespace. Allows spaces in filenames.\n const regex = new RegExp(\n `([\"'\\`(])${escapeRegex(prefix)}([^\"'\\`()]+)`,\n 'g'\n )\n result = result.replace(regex, (match, quote, relPath) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n return `${quote}${entry.cdnUrl}`\n })\n }\n return result\n }\n\n /**\n * Replace standalone URL references in JS/TS string literals and Vue template\n * attributes. This handles patterns like:\n * src=\"/images/foo.jpg\"\n * { src: '/images/foo.jpg' }\n * url(/images/foo.svg)\n *\n * For `<img>` tags with raster images that have variants, the entire tag is\n * replaced with a `<picture>` element.\n */\n function transformCode(code: string): string {\n if (!imageMap || imageMap.size === 0) return code\n\n // ── Pass 1: Replace <img> tags that reference mapped raster images ──────\n // Matches: <img ... src=\"/images/foo.jpg\" ... /> or <img ... src=\"/images/foo.jpg\" ... >\n const imgTagRegex = /<img\\b([^>]*?)src=[\"'](\\/(images\\/[^\"']+))[\"']([^>]*?)\\/?>/gi\n code = code.replace(imgTagRegex, (_match, beforeSrc, _srcWithSlash, localPath, afterSrc) => {\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return _match\n\n // Extract alt from the existing attributes\n const altMatch = (beforeSrc + afterSrc).match(/alt=[\"']([^\"']*)[\"']/)\n const alt = altMatch ? altMatch[1] : ''\n\n // Collect other attributes (not src, alt, loading, decoding — we set those)\n let otherAttrs = (beforeSrc + afterSrc)\n .replace(/\\balt=[\"'][^\"']*[\"']/gi, '')\n .replace(/\\bloading=[\"'][^\"']*[\"']/gi, '')\n .replace(/\\bdecoding=[\"'][^\"']*[\"']/gi, '')\n .trim()\n\n // When the map entry carries intrinsic dimensions, dimensionAttrs() will\n // emit width/height — strip any hand-authored ones (quoted or bare) so the\n // output doesn't carry DUPLICATE width/height attributes (a Vue compiler\n // duplicate-attribute error). Without entry dims, keep the author's.\n if (dimensionAttrs(entry)) {\n otherAttrs = otherAttrs\n .replace(/\\b(?:width|height)=(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>/]+)/gi, '')\n .replace(/\\s{2,}/g, ' ')\n .trim()\n }\n\n const extraAttrs = otherAttrs ? ' ' + otherAttrs : ''\n\n // Extract custom sizes if specified\n const sizesMatch = (beforeSrc + afterSrc).match(/data-sizes=[\"']([^\"']*)[\"']/)\n const sizes = sizesMatch ? sizesMatch[1] : defaultSizes\n\n // SVGs and images without variants → simple URL swap <img>. The vector\n // check is explicit (C-1803): the pipeline makes no variants for an SVG,\n // so even a map entry that lists some (hand-made files) must not become a\n // srcset. Same predicate as cms-core's resolveResponsiveImage.\n if (!entry.variants || entry.variants.length === 0 || isVectorImageUrl(entry.cdnUrl)) {\n return `<img src=\"${escapeHtml(entry.cdnUrl)}\" alt=\"${escapeHtml(alt)}\"${extraAttrs}${dimensionAttrs(entry)} loading=\"lazy\" decoding=\"async\" />`\n }\n\n // Raster with variants → <picture>\n return buildPictureElement(entry, alt, extraAttrs, sizes)\n })\n\n // ── Pass 2: Replace remaining string literal / CSS url() references ─────\n code = replaceImagePaths(code)\n\n return code\n }\n\n return {\n name: 'dcs-cdn-image',\n enforce: 'pre',\n\n configResolved(config) {\n isProduction = config.command === 'build'\n if (!isProduction) {\n if (debug) {\n console.log('[dcs-cdn-image] Dev mode — plugin disabled (local images served by Vite)')\n }\n return\n }\n imageMap = loadCdnImageMap(config.root, mapPath, debug)\n },\n\n transform(code, id) {\n // Only run in production builds\n if (!isProduction || !imageMap) return\n\n // Only process relevant file types\n if (!/\\.(vue|ts|tsx|js|jsx|css|scss|md|html)(\\?.*)?$/.test(id)) return\n\n // Quick bail — skip files with no image path references\n if (!hasImageReferences(code)) return\n\n const transformed = transformCode(code)\n if (transformed !== code) {\n return { code: transformed, map: null }\n }\n },\n\n /**\n * Replace image paths in final rendered JS/CSS chunks.\n *\n * This fires AFTER Vite's `define` substitution, catching paths that were\n * injected via `define` values (e.g. `__DCS_CONTENT__` set by\n * `dcsContentPlugin` from `.dcs/content.yaml`). Those paths bypass the\n * `transform` hook because `define` replacement happens at bundle time.\n */\n renderChunk(code, _chunk) {\n if (!isProduction || !imageMap) return null\n if (!hasImageReferences(code)) return null\n\n const replaced = replaceImagePaths(code)\n if (replaced !== code) {\n if (debug) {\n console.log(`[dcs-cdn-image] renderChunk: rewrote image paths in ${_chunk.fileName}`)\n }\n return { code: replaced, map: null }\n }\n return null\n },\n\n /**\n * Transform HTML output to catch references injected outside the module\n * pipeline — e.g. VitePress `head` config tags (favicons, OG images).\n *\n * Note: In VitePress, this hook fires for the `index.html` template but\n * NOT for SSR-rendered per-page HTML. Use `dcsCdnBuildEnd` for full\n * coverage of generated HTML files.\n */\n transformIndexHtml(html) {\n if (!isProduction || !imageMap) return html\n if (!hasImageReferences(html)) return html\n\n // Replace href/src/content attributes that reference mapped images\n for (const prefix of pathPrefixes) {\n const attrRegex = new RegExp(\n `((?:href|src|content)=[\"'])${escapeRegex(prefix)}([^\"']+)([\"'])`,\n 'gi'\n )\n html = html.replace(attrRegex, (match, pre, relPath, post) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n return `${pre}${entry.cdnUrl}${post}`\n })\n }\n\n return html\n },\n }\n}\n\n/**\n * Escape a string for use in a RegExp.\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// VitePress buildEnd hook\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface DcsCdnBuildEndOptions {\n /** Path to cdn-image-map.json relative to project root (default: '.dcs/cdn-image-map.json') */\n mapPath?: string\n\n /**\n * Patterns to match for replacement.\n * Default: `['/images/']`\n */\n pathPrefixes?: string[]\n\n /** Enable debug logging */\n debug?: boolean\n\n /**\n * File extensions to process in the output directory.\n * Default: `['.html', '.js']`\n */\n extensions?: string[]\n}\n\n/**\n * VitePress `buildEnd` hook factory that post-processes generated HTML and\n * static files in the output directory to replace remaining `/images/` paths\n * with CDN URLs.\n *\n * VitePress generates HTML **after** both Vite builds complete, so Vite\n * plugin hooks (`closeBundle`, `transformIndexHtml`) cannot catch\n * SSR-rendered `<head>` tags (favicons, OG images). This hook runs after all\n * HTML files are written to disk.\n *\n * Also rewrites static files (e.g. `service-worker.js`) copied from\n * `public/` that are not part of Vite's module pipeline.\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { dcsCdnBuildEnd } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * buildEnd: dcsCdnBuildEnd({ debug: true })\n * })\n * ```\n */\nexport function dcsCdnBuildEnd(options: DcsCdnBuildEndOptions = {}) {\n const {\n mapPath = '.dcs/cdn-image-map.json',\n pathPrefixes = ['/images/'],\n debug = false,\n extensions = ['.html', '.js'],\n } = options\n\n return async (siteConfig: { root: string; outDir: string }) => {\n const imageMap = loadCdnImageMap(siteConfig.root, mapPath, debug)\n if (!imageMap) {\n if (debug) {\n console.log('[dcs-cdn-image] buildEnd: no image map found')\n }\n return\n }\n\n const outDir = siteConfig.outDir\n if (!fs.existsSync(outDir)) return\n\n let filesProcessed = 0\n let refsReplaced = 0\n\n function walkDir(dir: string) {\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name)\n if (entry.isDirectory()) {\n walkDir(fullPath)\n } else if (extensions.some((ext) => entry.name.endsWith(ext))) {\n processFile(fullPath)\n }\n }\n }\n\n function processFile(filePath: string) {\n let content = fs.readFileSync(filePath, 'utf8')\n if (!pathPrefixes.some((p) => content.includes(p))) return\n\n let changed = false\n\n if (filePath.endsWith('.html')) {\n // HTML: replace href/src/content attribute values\n for (const prefix of pathPrefixes) {\n const attrRegex = new RegExp(\n `((?:href|src|content)=[\"'])${escapeRegex(prefix)}([^\"']+)([\"'])`,\n 'gi'\n )\n content = content.replace(attrRegex, (match, pre, relPath, post) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const mapEntry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!mapEntry) return match\n changed = true\n refsReplaced++\n return `${pre}${mapEntry.cdnUrl}${post}`\n })\n }\n } else {\n // JS/other: replace quoted string paths\n for (const prefix of pathPrefixes) {\n const regex = new RegExp(\n `([\"'\\`(])${escapeRegex(prefix)}([^\"'\\`()]+)`,\n 'g'\n )\n content = content.replace(regex, (match, quote, relPath) => {\n const localPath = prefix.replace(/^\\//, '') + relPath\n const entry = imageMap!.get(localPath) || imageMap!.get('/' + localPath)\n if (!entry) return match\n changed = true\n refsReplaced++\n return `${quote}${entry.cdnUrl}`\n })\n }\n }\n\n if (changed) {\n fs.writeFileSync(filePath, content, 'utf8')\n filesProcessed++\n }\n }\n\n walkDir(outDir)\n\n if (debug) {\n console.log(\n `[dcs-cdn-image] buildEnd: post-processed ${filesProcessed} files, replaced ${refsReplaced} references`\n )\n }\n }\n}","/**\n * markdown-it plugin that transforms standard `![alt](url)` image syntax\n * into responsive `<picture>` elements when the URL matches the DCS CDN\n * asset pattern.\n *\n * Non-CDN images are rendered with the default image renderer (plain `<img>`).\n *\n * @example\n * ```ts\n * // .vitepress/config.ts\n * import { responsiveImagePlugin } from '@duffcloudservices/cms/plugins'\n *\n * export default defineConfig({\n * markdown: {\n * config: (md) => {\n * md.use(responsiveImagePlugin)\n * },\n * },\n * })\n * ```\n *\n * Input markdown:\n * ```md\n * ![Physical therapy session](https://files.duffcloudservices.com/kept/assets/blog/abc-123.jpg)\n * ```\n *\n * Rendered HTML:\n * ```html\n * <picture>\n * <source srcset=\"...abc-123-sm.webp 640w, ...abc-123-md.webp 1024w, ...abc-123-lg.webp 1920w\"\n * type=\"image/webp\"\n * sizes=\"(max-width: 1024px) 100vw, 1024px\" />\n * <img src=\"...abc-123-md.webp\" alt=\"Physical therapy session\" loading=\"lazy\" decoding=\"async\" />\n * </picture>\n * ```\n */\n\nimport type MarkdownIt from 'markdown-it'\nimport { isVectorImageUrl } from '@duffcloudservices/cms-core'\n\n/**\n * Matches DCS CDN asset URLs: base path / UUID . extension.\n *\n * Aligned with `@duffcloudservices/cms-core` `responsive-image.ts`: the\n * `(?:content\\/)?` group covers the content-container shape\n * `https://files.duffcloudservices.com/content/{slug}/assets/...` in addition\n * to the branding-container shape `.../{slug}/assets/...`. The group is\n * non-capturing, so the captured base path / UUID / extension are unchanged.\n */\nconst CDN_PATTERN = /^(https?:\\/\\/files\\.[^/]+\\/(?:content\\/)?[^/]+\\/assets\\/(?:[^/]+\\/)*)([a-f0-9-]+)\\.(\\w+)$/\n\n/**\n * Escapes HTML special characters for safe attribute embedding.\n * Falls back to a simple replace chain when `md.utils.escapeHtml` is unavailable.\n */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n}\n\nexport function responsiveImagePlugin(md: MarkdownIt): void {\n const defaultImageRenderer = md.renderer.rules.image\n\n md.renderer.rules.image = (tokens, idx, options, env, self) => {\n const token = tokens[idx]\n const src = token.attrGet('src') ?? ''\n const alt = token.content ?? ''\n\n const match = src.match(CDN_PATTERN)\n // C-1803: the pipeline generates no WebP variants for a vector source, so\n // an SVG renders as its original URL — the same rule as cms-core.\n if (!match || isVectorImageUrl(src)) {\n // Not a CDN raster image — render normally\n if (defaultImageRenderer) {\n return defaultImageRenderer(tokens, idx, options, env, self)\n }\n return self.renderToken(tokens, idx, options)\n }\n\n const [, basePath, uuid] = match\n\n const srcset = [\n `${basePath}${uuid}-sm.webp 640w`,\n `${basePath}${uuid}-md.webp 1024w`,\n `${basePath}${uuid}-lg.webp 1920w`,\n ].join(', ')\n\n const escapedAlt = escapeHtml(alt)\n\n // Self-heal: this plugin emits a STATIC HTML string at build time (no Vue\n // runtime), so the fallback must be an inline onerror. A fit-variant\n // (`-md`/`-lg`) may legitimately be absent (internal/imaging variants.go\n // skips variants by DIMENSION). On the first error, swap the `<img>` to the\n // ORIGINAL url AND strip the sibling `<source>` elements — a `<picture>`\n // does NOT re-resolve after a `<source>` 404s, so the variant set must be\n // removed for the original to display. (`this.onerror=null` prevents loops.)\n const escapedOriginal = escapeHtml(src)\n const onError =\n `this.onerror=null;this.src='${escapedOriginal}';` +\n `this.closest('picture')?.querySelectorAll('source').forEach(s=>s.remove())`\n\n return [\n '<picture>',\n ` <source srcset=\"${srcset}\" type=\"image/webp\" sizes=\"(max-width: 1024px) 100vw, 1024px\" />`,\n ` <img src=\"${basePath}${uuid}-md.webp\" alt=\"${escapedAlt}\" loading=\"lazy\" decoding=\"async\" onerror=\"${onError}\" />`,\n '</picture>',\n ].join('\\n')\n }\n}\n"]}