/**
* Build-time HTML partial inclusion and route-aware navigation rewriting.
*
* The plugin emits no runtime JS: it expands `` markers
* before Vite processes scripts and assets, then converts build-only nav
* hints into `aria-current` for the canonical route.
*/
import fs from 'node:fs';
import path from 'node:path';
import type { IndexHtmlTransformContext, Plugin, ViteDevServer } from 'vite-plus';
const PARTIALS_DIRECTORY = path.join('src', 'partials');
const DEFAULT_ROOT = path.resolve(import.meta.dirname, '..');
const INCLUDE_MARKER = //gi;
// Matches quoted, unquoted, and bare `data-nav-current` attributes.
const NAV_MARKER =
/\s+data-nav-current\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))|\s+data-nav-current(?=\s|\/|>)/gi;
/** Resolve an include specifier to an absolute path inside `src/partials`. */
function resolvePartialPath(specifier: string, rootDirectory: string): string {
const normalized = specifier.replaceAll('\\', '/').replace(/^\.\//, '');
const match = /^src\/partials\/([^/]+\.html)$/i.exec(normalized);
if (!match) {
throw new Error(
`Unsupported @include "${specifier}"; only src/partials/.html is allowed`,
);
}
const partialsDirectory = path.resolve(rootDirectory, PARTIALS_DIRECTORY);
const target = path.resolve(partialsDirectory, match[1]);
const relative = path.relative(partialsDirectory, target);
// Why: an include marker must never read outside the approved partials directory.
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
throw new Error(`Unsafe @include path "${specifier}"`);
}
return target;
}
/**
* Expand every `` marker in an HTML string.
*
* @param html Source HTML that may contain include markers.
* @param rootDirectory Project root used to resolve partial files.
* @throws Error naming the unresolved partial when a referenced file is missing.
*/
export function expandHtmlPartials(html: string, rootDirectory: string = DEFAULT_ROOT): string {
return html.replace(INCLUDE_MARKER, (_marker, specifier: string) => {
const target = resolvePartialPath(specifier, rootDirectory);
if (!fs.existsSync(target)) {
throw new Error(`Unable to resolve HTML partial "${specifier}" at ${target}`);
}
return fs.readFileSync(target, 'utf8');
});
}
/** Convert a URL pathname into a canonical route key such as `/kundalini/`. */
function routeKeyFromPathname(pathname: string): string {
const segments = (pathname.split(/[?#]/, 1)[0] ?? '')
.replaceAll('\\', '/')
.replace(/^\/+|\/+$/g, '')
.split('/')
.filter(Boolean);
if (segments.at(-1) === 'index.html') {
segments.pop();
}
return segments.length === 0 ? '/' : `/${segments.join('/')}/`;
}
/** Convert an absolute build filename into the same canonical route key. */
function routeKeyFromFilename(filename: string, rootDirectory: string): string {
const relative = path.relative(rootDirectory, filename).replaceAll('\\', '/');
return routeKeyFromPathname(`/${relative}`);
}
/** Pick the reliable route source for a Vite HTML transform context. */
function resolveRouteKey(ctx: IndexHtmlTransformContext, rootDirectory: string): string {
// Why: dev ctx.filename can point to index.html for every URL, while build
// has no route path; ctx.path wins in dev and the filename wins in build.
if (ctx.server && ctx.path) {
return routeKeyFromPathname(ctx.path);
}
if (ctx.filename) {
return routeKeyFromFilename(ctx.filename, rootDirectory);
}
return routeKeyFromPathname(ctx.path || '/');
}
/** Activate the matching nav marker and remove every remaining build hint. */
function applyNavigationMarkers(html: string, routeKey: string): string {
let activeMarker = '';
if (routeKey === '/') {
activeMarker = 'home';
} else if (routeKey === '/kundalini/') {
activeMarker = 'kundalini';
}
return html.replace(NAV_MARKER, (_match, quoted, singleQuoted, unquoted) => {
const value = (quoted ?? singleQuoted ?? unquoted ?? '').toLowerCase();
if (activeMarker && value === activeMarker) {
return ' aria-current="page"';
}
// Why: build-time hints must never reach clients; only the exact active
// route gets aria-current, so other routes have no current nav item.
return '';
});
}
/** Return true when a changed file is an HTML fragment in `src/partials`. */
function isPartialFile(file: string, rootDirectory: string): boolean {
const relative = path
.relative(path.resolve(rootDirectory, PARTIALS_DIRECTORY), path.resolve(file))
.replaceAll('\\', '/');
return (
relative !== '' &&
!relative.startsWith('..') &&
!path.isAbsolute(relative) &&
relative.toLowerCase().endsWith('.html')
);
}
/**
* Create the Vite plugin that injects partials and marks the active nav item.
*
* Partials are watched for `vp dev`, where a change triggers a full page
* reload because plain HTML fragments are not module-graph entries.
*/
export function htmlPartialsPlugin(): Plugin {
let rootDirectory = DEFAULT_ROOT;
let devServer: ViteDevServer | undefined;
return {
name: 'corazoncp-html-partials',
configResolved(config) {
rootDirectory = config.root || DEFAULT_ROOT;
},
configureServer(server) {
devServer = server;
server.watcher.add(path.resolve(rootDirectory, PARTIALS_DIRECTORY));
},
handleHotUpdate(ctx) {
if (!isPartialFile(ctx.file, rootDirectory)) {
return undefined;
}
const server = ctx.server ?? devServer;
server?.ws.send({ type: 'full-reload' });
// Why: each page includes the same fragments, so a partial edit must
// reload the page instead of trying to HMR a non-module file.
return [];
},
transformIndexHtml: {
order: 'pre',
handler(html, ctx) {
const expanded = expandHtmlPartials(html, rootDirectory);
return applyNavigationMarkers(expanded, resolveRouteKey(ctx, rootDirectory));
},
},
};
}
export default htmlPartialsPlugin;