repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/the-system/documents.ts

Raw
File outline
import { existsSync } from "node:fs";
import path from "node:path";

export const SCHEMA_VERSION = 1;
export const STYLE_VERSION = 1;

export class SystemDocumentError extends Error {
	readonly code: string;

	constructor(code: string, message: string) {
		super(message);
		this.code = code;
		this.name = "SystemDocumentError";
	}
}

const nearestMarker = (
	cwd: string,
	marker: string,
	markerExists: (path: string) => boolean,
) => {
	let current = path.resolve(cwd);
	while (true) {
		if (markerExists(path.join(current, marker))) return current;
		const parent = path.dirname(current);
		if (parent === current) return undefined;
		current = parent;
	}
};

export function discoverProjectRoot(
	cwd: string,
	markerExists = existsSync,
): string {
	const resolvedCwd = path.resolve(cwd);
	const jj = nearestMarker(resolvedCwd, ".jj", markerExists);
	const git = nearestMarker(resolvedCwd, ".git", markerExists);
	if (jj && git && jj !== git) {
		throw new SystemDocumentError(
			"root.conflict",
			`Conflicting project roots: Git ${git}; JJ ${jj}`,
		);
	}
	return jj ?? git ?? resolvedCwd;
}

export function resolveGovernedPath(root: string, candidate: string): string {
	const normalizedRoot = path.resolve(root);
	const target = path.resolve(normalizedRoot, candidate);
	const relative = path.relative(normalizedRoot, target);
	if (
		relative === ".." ||
		relative.startsWith(`..${path.sep}`) ||
		path.isAbsolute(relative)
	) {
		throw new SystemDocumentError(
			"path.outside-root",
			`Path is outside project root: ${candidate}`,
		);
	}
	return target;
}

export const DOCUMENT_TYPES = [
	"spec",
	"roadmap",
	"plan",
	"issue",
	"research",
] as const;
export type DocumentType = (typeof DOCUMENT_TYPES)[number];
export type SystemConfig = Readonly<{
	prefix: string;
	schemaVersion: number;
	styleVersion: number;
}>;
export type ParsedDocumentId = Readonly<{
	id: string;
	prefix: string;
	type: DocumentType;
	sequence: number;
}>;
export type SpecMetadata = Readonly<{ id: string; type: "spec" }>;
export type RoadmapMetadata = Readonly<{
	id: string;
	type: "roadmap";
	spec: string;
}>;
export type PlanMetadata = Readonly<{
	id: string;
	type: "plan";
	spec: string;
	roadmap?: string;
	phase?: number;
}>;
export type IssueMetadata = Readonly<{
	id: string;
	type: "issue";
	status: "open" | "fixed";
	specs: readonly string[];
}>;
export type ResearchMetadata = Readonly<{
	id: string;
	type: "research";
	capturedAt: string;
	sources?: readonly string[];
}>;
export type DocumentMetadata =
	| SpecMetadata
	| RoadmapMetadata
	| PlanMetadata
	| IssueMetadata
	| ResearchMetadata;

const PREFIX = /^[A-Z][A-Z0-9]{1,7}$/;
const SLUG = "[a-z0-9]+(?:-[a-z0-9]+)*";
const TYPE_BY_TOKEN = new Map(
	DOCUMENT_TYPES.map((type) => [type.toUpperCase(), type]),
);
const DIRECTORY_BY_TYPE: Readonly<Record<DocumentType, string>> = {
	spec: "specs",
	roadmap: "roadmaps",
	plan: "plans",
	issue: "issues",
	research: "research",
};

const objectValue = (
	value: unknown,
	label: string,
): Record<string, unknown> => {
	if (typeof value !== "object" || value === null || Array.isArray(value)) {
		throw new SystemDocumentError(
			"json.shape",
			`${label} must be a JSON object`,
		);
	}
	return value as Record<string, unknown>;
};
const exactKeys = (
	value: Record<string, unknown>,
	required: readonly string[],
	optional: readonly string[] = [],
) => {
	const actual = Object.keys(value).sort();
	const allowed = new Set([...required, ...optional]);
	if (
		required.some((key) => !(key in value)) ||
		actual.some((key) => !allowed.has(key))
	) {
		throw new SystemDocumentError(
			"json.keys",
			`Expected keys ${[...required, ...optional].sort().join(", ")}; received ${actual.join(", ")}`,
		);
	}
};
const positiveInteger = (value: unknown) =>
	typeof value === "number" && Number.isInteger(value) && value > 0;

export function parseSystemConfig(source: string): SystemConfig {
	let parsed: unknown;
	try {
		parsed = JSON.parse(source);
	} catch {
		throw new SystemDocumentError("config.invalid-json", "Invalid config JSON");
	}
	const duplicates = duplicateTopLevelKeys(source);
	if (duplicates.length)
		throw new SystemDocumentError(
			"config.duplicate-key",
			`Duplicate config keys: ${duplicates.join(", ")}`,
		);
	const value = objectValue(parsed, "Config");
	exactKeys(value, ["prefix", "schemaVersion", "styleVersion"]);
	if (typeof value.prefix !== "string" || !PREFIX.test(value.prefix)) {
		throw new SystemDocumentError("config.prefix", "Invalid project prefix");
	}
	if (
		!positiveInteger(value.schemaVersion) ||
		!positiveInteger(value.styleVersion)
	) {
		throw new SystemDocumentError(
			"config.version",
			"Schema and style versions must be positive integers",
		);
	}
	return {
		prefix: value.prefix,
		schemaVersion: value.schemaVersion as number,
		styleVersion: value.styleVersion as number,
	};
}

export function parseDocumentId(
	source: string,
	expectedPrefix?: string,
): ParsedDocumentId {
	const match =
		/^([A-Z][A-Z0-9]{1,7})-(SPEC|ROADMAP|PLAN|ISSUE|RESEARCH)-([0-9]{3,})$/.exec(
			source,
		);
	const sequence = match ? Number(match[3]) : 0;
	const canonical = sequence > 0 ? String(sequence).padStart(3, "0") : "";
	if (!match || match[3] !== canonical) {
		throw new SystemDocumentError(
			"id.invalid",
			`Invalid document ID: ${source}`,
		);
	}
	if (expectedPrefix && match[1] !== expectedPrefix) {
		throw new SystemDocumentError(
			"id.prefix",
			`Document ID must use prefix ${expectedPrefix}: ${source}`,
		);
	}
	return {
		id: source,
		prefix: match[1],
		type: TYPE_BY_TOKEN.get(match[2]) as DocumentType,
		sequence,
	};
}

export function validateFilename(
	filename: string,
	metadata: DocumentMetadata,
	prefix: string,
): void {
	const parsed = parseDocumentId(metadata.id, prefix);
	const expectedDirectory = DIRECTORY_BY_TYPE[metadata.type];
	const directory = path.basename(path.dirname(filename));
	const pattern = new RegExp(`^${metadata.id}-${SLUG}\\.html$`);
	if (
		parsed.type !== metadata.type ||
		directory !== expectedDirectory ||
		!pattern.test(path.basename(filename))
	) {
		throw new SystemDocumentError(
			"document.filename",
			`Filename mismatch for ${metadata.id}: ${filename}`,
		);
	}
}

const duplicateTopLevelKeys = (source: string): string[] => {
	const keys: string[] = [];
	const duplicates = new Set<string>();
	let depth = 0;
	let index = 0;
	while (index < source.length) {
		const character = source[index];
		if (character === "{") {
			depth += 1;
			index += 1;
			continue;
		}
		if (character === "}") {
			depth -= 1;
			index += 1;
			continue;
		}
		if (character !== '"') {
			index += 1;
			continue;
		}
		const start = index;
		index += 1;
		let escaped = false;
		while (index < source.length) {
			const current = source[index++];
			if (!escaped && current === '"') break;
			escaped = !escaped && current === "\\";
			if (current !== "\\") escaped = false;
		}
		if (depth !== 1) continue;
		let cursor = index;
		while (/\s/.test(source[cursor] ?? "")) cursor += 1;
		if (source[cursor] !== ":") continue;
		const key = JSON.parse(source.slice(start, index)) as string;
		if (keys.includes(key)) duplicates.add(key);
		keys.push(key);
	}
	return [...duplicates].sort();
};

const stringArray = (value: unknown, label: string): string[] => {
	if (!Array.isArray(value) || value.some((item) => typeof item !== "string"))
		throw new SystemDocumentError(
			"metadata.value",
			`${label} must be a string array`,
		);
	if (new Set(value).size !== value.length)
		throw new SystemDocumentError(
			"metadata.duplicate",
			`${label} must contain unique values`,
		);
	return value;
};
const validDate = (value: unknown) => {
	if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
		return false;
	const date = new Date(`${value}T00:00:00Z`);
	return (
		!Number.isNaN(date.valueOf()) && date.toISOString().slice(0, 10) === value
	);
};
const httpsUrl = (value: string) => {
	try {
		return new URL(value).protocol === "https:";
	} catch {
		return false;
	}
};
type HtmlTag = Readonly<{
	name: string;
	closing: boolean;
	start: number;
	end: number;
	attributes: ReadonlyMap<string, string | undefined>;
}>;

const withoutHtmlComments = (html: string) =>
	html.replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) =>
		comment.replace(/[^\r\n]/g, " "),
	);

const scanAttributes = (
	source: string,
): ReadonlyMap<string, string | undefined> => {
	const attributes = new Map<string, string | undefined>();
	let index = 0;
	while (index < source.length) {
		while (/\s|\//.test(source[index] ?? "")) index += 1;
		const start = index;
		while (!/[\s=/>]/.test(source[index] ?? ">")) index += 1;
		if (start === index) break;
		const name = source.slice(start, index).toLowerCase();
		while (/\s/.test(source[index] ?? "")) index += 1;
		let value: string | undefined;
		if (source[index] === "=") {
			index += 1;
			while (/\s/.test(source[index] ?? "")) index += 1;
			const quote =
				source[index] === '"' || source[index] === "'"
					? source[index++]
					: undefined;
			const valueStart = index;
			if (quote)
				while (index < source.length && source[index] !== quote) index += 1;
			else
				while (index < source.length && !/[\s>]/.test(source[index]))
					index += 1;
			value = source.slice(valueStart, index);
			if (quote && source[index] === quote) index += 1;
		}
		if (!attributes.has(name)) attributes.set(name, value);
	}
	return attributes;
};

const scanHtmlTags = (html: string): readonly HtmlTag[] => {
	const source = withoutHtmlComments(html);
	const tags: HtmlTag[] = [];
	let index = 0;
	while (index < source.length) {
		const start = source.indexOf("<", index);
		if (start < 0) break;
		let cursor = start + 1;
		const closing = source[cursor] === "/";
		if (closing) cursor += 1;
		while (/\s/.test(source[cursor] ?? "")) cursor += 1;
		const nameStart = cursor;
		while (/[A-Za-z0-9:-]/.test(source[cursor] ?? "")) cursor += 1;
		if (cursor === nameStart) {
			index = start + 1;
			continue;
		}
		const name = source.slice(nameStart, cursor).toLowerCase();
		let quote: string | undefined;
		let end = cursor;
		for (; end < source.length; end += 1) {
			const character = source[end];
			if (quote) {
				if (character === quote) quote = undefined;
			} else if (character === '"' || character === "'") quote = character;
			else if (character === ">") break;
		}
		if (end >= source.length) break;
		tags.push({
			name,
			closing,
			start,
			end: end + 1,
			attributes: closing
				? new Map()
				: scanAttributes(source.slice(cursor, end)),
		});
		index = end + 1;
	}
	return tags;
};

const namedEntities: Readonly<Record<string, string>> = {
	amp: "&",
	apos: "'",
	colon: ":",
	gt: ">",
	lt: "<",
	newline: "\n",
	quot: '"',
	tab: "\t",
};
const decodeBasicEntities = (value: string) =>
	value.replace(
		/&(?:#(\d+)|#x([\da-f]+)|([a-z][a-z\d]+));?/gi,
		(entity, decimal: string, hexadecimal: string, named: string) => {
			if (named) return namedEntities[named.toLowerCase()] ?? entity;
			const point = Number.parseInt(decimal ?? hexadecimal, decimal ? 10 : 16);
			try {
				return String.fromCodePoint(point);
			} catch {
				return "�";
			}
		},
	);
const attributeValue = (tag: HtmlTag, name: string) => {
	const value = tag.attributes.get(name);
	return value === undefined ? undefined : decodeBasicEntities(value);
};
const normalizedUrl = (value: string) =>
	decodeBasicEntities(value)
		.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
		.trim();

const scriptBlocks = (html: string, tags = scanHtmlTags(html)) => {
	const blocks: { tag: HtmlTag; content: string }[] = [];
	for (let index = 0; index < tags.length; index += 1) {
		const tag = tags[index];
		if (tag.name !== "script" || tag.closing) continue;
		const close = tags
			.slice(index + 1)
			.find((item) => item.name === "script" && item.closing);
		if (close) blocks.push({ tag, content: html.slice(tag.end, close.start) });
	}
	return blocks;
};

const metadataScripts = (html: string) =>
	scriptBlocks(html).filter(
		({ tag }) =>
			attributeValue(tag, "id")?.toLowerCase() === "system-meta" &&
			attributeValue(tag, "type")?.toLowerCase() === "application/json",
	);

export function parseDocumentMetadata(
	html: string,
	prefix: string,
): DocumentMetadata {
	const blocks = metadataScripts(html);
	if (blocks.length !== 1)
		throw new SystemDocumentError(
			"metadata.block",
			`Expected exactly one system-meta block; received ${blocks.length}`,
		);
	const json = blocks[0].content.trim();
	let parsed: unknown;
	let duplicates: string[];
	try {
		parsed = JSON.parse(json);
		duplicates = duplicateTopLevelKeys(json);
	} catch {
		throw new SystemDocumentError(
			"metadata.invalid-json",
			"Invalid system metadata JSON",
		);
	}
	if (duplicates.length)
		throw new SystemDocumentError(
			"metadata.duplicate-key",
			`Duplicate metadata keys: ${duplicates.join(", ")}`,
		);
	const value = objectValue(parsed, "Metadata");
	if (typeof value.id !== "string" || typeof value.type !== "string")
		throw new SystemDocumentError(
			"metadata.identity",
			"Metadata requires string id and type",
		);
	const ownId = parseDocumentId(value.id, prefix);
	if (ownId.type !== value.type)
		throw new SystemDocumentError(
			"metadata.identity",
			`Metadata ID/type mismatch: ${value.id} / ${value.type}`,
		);
	const reference = (key: string) => {
		if (typeof value[key] !== "string")
			throw new SystemDocumentError(
				"metadata.value",
				`${key} must be a document ID`,
			);
		parseDocumentId(value[key] as string, prefix);
		return value[key] as string;
	};
	switch (value.type) {
		case "spec":
			exactKeys(value, ["id", "type"]);
			return { id: value.id, type: "spec" };
		case "roadmap":
			exactKeys(value, ["id", "type", "spec"]);
			return { id: value.id, type: "roadmap", spec: reference("spec") };
		case "plan": {
			exactKeys(value, ["id", "type", "spec"], ["roadmap", "phase"]);
			const hasRoadmap = "roadmap" in value;
			const hasPhase = "phase" in value;
			if (
				hasRoadmap !== hasPhase ||
				(hasPhase && !positiveInteger(value.phase))
			)
				throw new SystemDocumentError(
					"metadata.plan-phase",
					"Plan roadmap and positive phase must appear together",
				);
			return hasRoadmap
				? {
						id: value.id,
						type: "plan",
						spec: reference("spec"),
						roadmap: reference("roadmap"),
						phase: value.phase as number,
					}
				: { id: value.id, type: "plan", spec: reference("spec") };
		}
		case "issue": {
			exactKeys(value, ["id", "type", "status", "specs"]);
			if (value.status !== "open" && value.status !== "fixed")
				throw new SystemDocumentError(
					"metadata.status",
					"Issue status must be open or fixed",
				);
			const specs = stringArray(value.specs, "specs");
			for (const id of specs) parseDocumentId(id, prefix);
			return { id: value.id, type: "issue", status: value.status, specs };
		}
		case "research": {
			exactKeys(value, ["id", "type", "capturedAt"], ["sources"]);
			if (!validDate(value.capturedAt))
				throw new SystemDocumentError(
					"metadata.date",
					"capturedAt must be a valid ISO date",
				);
			const sources =
				"sources" in value ? stringArray(value.sources, "sources") : undefined;
			if (sources?.some((source) => !httpsUrl(source)))
				throw new SystemDocumentError(
					"metadata.source",
					"Research sources must use HTTPS",
				);
			return sources
				? {
						id: value.id,
						type: "research",
						capturedAt: value.capturedAt as string,
						sources,
					}
				: {
						id: value.id,
						type: "research",
						capturedAt: value.capturedAt as string,
					};
		}
		default:
			throw new SystemDocumentError(
				"metadata.type",
				`Unsupported metadata type: ${value.type}`,
			);
	}
}

export type Diagnostic = Readonly<{
	code: string;
	path: string;
	message: string;
}>;
const diagnostic = (
	code: string,
	path: string,
	message: string,
): Diagnostic => ({ code, path, message });
const tagsNamed = (tags: readonly HtmlTag[], name: string, closing = false) =>
	tags.filter((tag) => tag.name === name && tag.closing === closing);
const isExecutableUrl = (value: string) =>
	/^(?:javascript|vbscript|data):/i.test(normalizedUrl(value));
const isRemoteUrl = (value: string) =>
	/^(?:https?:|\/\/)/i.test(normalizedUrl(value));
const srcsetUrls = (value: string) =>
	decodeBasicEntities(value)
		.split(",")
		.map((candidate) => candidate.trim().split(/\s+/)[0] ?? "");
const srcsetHasRemoteUrl = (value: string) =>
	srcsetUrls(value).some(isRemoteUrl);

export function validateAuthoredHtml(
	filename: string,
	html: string,
): readonly Diagnostic[] {
	const findings: Diagnostic[] = [];
	const cleanHtml = withoutHtmlComments(html);
	const tags = scanHtmlTags(html);
	const opening = (name: string) => tagsNamed(tags, name);
	const closing = (name: string) => tagsNamed(tags, name, true);
	const add = (code: string, message: string) =>
		findings.push(diagnostic(code, filename, message));

	if (!/^<!doctype html>/i.test(cleanHtml.trimStart()))
		add("document.doctype", "Document must begin with HTML doctype");

	const htmlOpen = opening("html");
	const htmlClose = closing("html");
	const headOpen = opening("head");
	const headClose = closing("head");
	const bodyOpen = opening("body");
	const bodyClose = closing("body");
	if (
		htmlOpen.length !== 1 ||
		htmlClose.length !== 1 ||
		headOpen.length !== 1 ||
		headClose.length !== 1 ||
		bodyOpen.length !== 1 ||
		bodyClose.length !== 1 ||
		!(htmlOpen[0]?.start < headOpen[0]?.start) ||
		!(headOpen[0]?.start < headClose[0]?.start) ||
		!(headClose[0]?.start < bodyOpen[0]?.start) ||
		!(bodyOpen[0]?.start < bodyClose[0]?.start) ||
		!(bodyClose[0]?.start < htmlClose[0]?.start)
	)
		add(
			"document.structure",
			"Document requires one complete html, head, and body structure",
		);

	if (
		htmlOpen.length !== 1 ||
		attributeValue(htmlOpen[0], "lang")?.toLowerCase() !== "en"
	)
		add("document.language", "Document requires one html lang=en root");

	const meta = opening("meta");
	if (
		meta.filter(
			(tag) => attributeValue(tag, "charset")?.toLowerCase() === "utf-8",
		).length !== 1
	)
		add("document.charset", "Document requires one UTF-8 charset meta");
	if (
		meta.filter(
			(tag) =>
				attributeValue(tag, "name")?.toLowerCase() === "viewport" &&
				/^width=device-width,\s*initial-scale=1$/i.test(
					attributeValue(tag, "content") ?? "",
				),
		).length !== 1
	)
		add("document.viewport", "Document requires one viewport meta");

	const titleOpen = opening("title");
	const titleClose = closing("title");
	if (
		titleOpen.length !== 1 ||
		titleClose.length !== 1 ||
		titleOpen[0].end >= titleClose[0].start ||
		!html.slice(titleOpen[0].end, titleClose[0].start).trim()
	)
		add("document.title", "Document requires one nonempty title");

	const stylesheets = opening("link").filter((tag) =>
		(attributeValue(tag, "rel") ?? "")
			.toLowerCase()
			.split(/\s+/)
			.includes("stylesheet"),
	);
	if (
		stylesheets.length !== 1 ||
		attributeValue(stylesheets[0], "href") !== "../system.css"
	)
		add(
			"document.stylesheet",
			"Document requires exactly one ../system.css stylesheet",
		);

	const semantic = {
		header: { open: opening("header"), close: closing("header") },
		main: { open: opening("main"), close: closing("main") },
		section: { open: opening("section"), close: closing("section") },
	};
	for (const name of ["header", "main", "section"] as const) {
		const pair = semantic[name];
		if (
			pair.open.length !== 1 ||
			pair.close.length !== 1 ||
			pair.open[0].start >= pair.close[0].start
		)
			add(
				"document.semantic-shell",
				`Document requires one complete ${name} element`,
			);
	}
	if (
		bodyOpen.length === 1 &&
		bodyClose.length === 1 &&
		semantic.header.open.length === 1 &&
		semantic.header.close.length === 1 &&
		semantic.main.open.length === 1 &&
		semantic.main.close.length === 1 &&
		semantic.section.open.length === 1 &&
		semantic.section.close.length === 1 &&
		!(
			bodyOpen[0].start < semantic.header.open[0].start &&
			semantic.header.close[0].start < semantic.main.open[0].start &&
			semantic.main.open[0].start < semantic.section.open[0].start &&
			semantic.section.close[0].start < semantic.main.close[0].start &&
			semantic.main.close[0].start < bodyClose[0].start
		)
	)
		add(
			"document.semantic-shell",
			"Document requires header then main with one contained section",
		);

	if (tags.some((tag) => ["iframe", "object", "embed"].includes(tag.name)))
		add("document.forbidden-tag", "iframe, object, and embed are forbidden");
	if (
		meta.some(
			(tag) => attributeValue(tag, "http-equiv")?.toLowerCase() === "refresh",
		)
	)
		add("document.meta-refresh", "Meta refresh is forbidden");
	if (
		tags.some(
			(tag) =>
				!tag.closing &&
				[...tag.attributes].some(([name]) => /^on[a-z]+$/i.test(name)),
		)
	)
		add("document.event-handler", "Event-handler attributes are forbidden");

	const urlAttributes = new Set([
		"href",
		"src",
		"srcset",
		"poster",
		"action",
		"formaction",
		"xlink:href",
	]);
	let executableUrl = false;
	let remoteResource = false;
	for (const tag of tags) {
		if (tag.closing) continue;
		for (const [name, rawValue] of tag.attributes) {
			if (!urlAttributes.has(name) || rawValue === undefined) continue;
			if (
				isExecutableUrl(rawValue) ||
				(name === "srcset" && srcsetUrls(rawValue).some(isExecutableUrl))
			)
				executableUrl = true;
			if (
				((name === "src" || name === "poster") && isRemoteUrl(rawValue)) ||
				(name === "srcset" && srcsetHasRemoteUrl(rawValue)) ||
				((name === "href" || name === "xlink:href") &&
					tag.name !== "a" &&
					tag.name !== "area" &&
					isRemoteUrl(rawValue))
			)
				remoteResource = true;
		}
	}
	if (executableUrl)
		add("document.executable-url", "Executable URL schemes are forbidden");
	if (remoteResource)
		add("document.remote-resource", "Remote runtime resources are forbidden");
	if (opening("script").some((tag) => tag.attributes.has("src")))
		add("document.external-script", "External script sources are forbidden");
	if (/(?:@import|url\s*\(\s*["']?\s*(?:https?:|data:))/i.test(cleanHtml))
		add(
			"document.css-resource",
			"CSS imports and remote/data URLs are forbidden",
		);

	const executable = scriptBlocks(html, tags)
		.filter(
			({ tag }) =>
				attributeValue(tag, "type")?.toLowerCase() !== "application/json",
		)
		.map(({ content }) => content)
		.join("\n");
	if (
		/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|importScripts|localStorage|sessionStorage|indexedDB)\b/.test(
			executable,
		) ||
		/\bimport\s*\(/.test(executable)
	)
		add(
			"document.active-api",
			"Network, import, and browser storage APIs are forbidden",
		);
	return findings.sort(compareDiagnostics);
}

const compareDiagnostics = (left: Diagnostic, right: Diagnostic) =>
	left.path.localeCompare(right.path) ||
	left.code.localeCompare(right.code) ||
	left.message.localeCompare(right.message);

export type DocumentSource = Readonly<{ path: string; html: string }>;
export type DocumentRecord = Readonly<{
	path: string;
	metadata: DocumentMetadata;
}>;
export type DocumentIndex = Readonly<{
	documents: readonly DocumentRecord[];
	diagnostics: readonly Diagnostic[];
}>;

const references = (
	metadata: DocumentMetadata,
): readonly (readonly [string, "spec" | "roadmap"])[] => {
	switch (metadata.type) {
		case "roadmap":
			return [[metadata.spec, "spec"]];
		case "plan":
			return [
				[metadata.spec, "spec"],
				...(metadata.roadmap ? [[metadata.roadmap, "roadmap"] as const] : []),
			];
		case "issue":
			return metadata.specs.map((id) => [id, "spec"] as const);
		default:
			return [];
	}
};

export function indexDocuments(
	sources: readonly DocumentSource[],
	prefix: string,
): DocumentIndex {
	const documents: DocumentRecord[] = [];
	const graphEligible: DocumentRecord[] = [];
	const diagnostics: Diagnostic[] = [];
	for (const item of [...sources].sort((left, right) =>
		left.path.localeCompare(right.path),
	)) {
		const htmlDiagnostics = validateAuthoredHtml(item.path, item.html);
		diagnostics.push(...htmlDiagnostics);
		try {
			const metadata = parseDocumentMetadata(item.html, prefix);
			let filenameValid = true;
			try {
				validateFilename(item.path, metadata, prefix);
			} catch (error) {
				filenameValid = false;
				diagnostics.push(
					diagnostic("document.filename", item.path, (error as Error).message),
				);
			}
			const record = { path: item.path, metadata };
			documents.push(record);
			if (filenameValid && htmlDiagnostics.length === 0)
				graphEligible.push(record);
		} catch (error) {
			const value = error as SystemDocumentError;
			diagnostics.push(
				diagnostic(
					"document.metadata",
					item.path,
					`${value.code}: ${value.message}`,
				),
			);
		}
	}
	const groups = new Map<string, DocumentRecord[]>();
	for (const document of graphEligible)
		groups.set(document.metadata.id, [
			...(groups.get(document.metadata.id) ?? []),
			document,
		]);
	for (const [id, records] of groups) {
		if (records.length > 1) {
			const paths = records.map((record) => record.path).sort();
			for (const record of records)
				diagnostics.push(
					diagnostic(
						"graph.duplicate-id",
						record.path,
						`Duplicate ID ${id}: ${paths.join(", ")}`,
					),
				);
		}
	}
	const unique = new Map(
		[...groups]
			.filter(([, records]) => records.length === 1)
			.map(([id, records]) => [id, records[0]]),
	);
	for (const document of graphEligible) {
		for (const [targetId, expectedType] of references(document.metadata)) {
			const referencedType = parseDocumentId(targetId, prefix).type;
			const target = unique.get(targetId);
			if (referencedType !== expectedType) {
				diagnostics.push(
					diagnostic(
						"graph.forbidden-edge",
						document.path,
						`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${referencedType}`,
					),
				);
			} else if (!target) {
				diagnostics.push(
					diagnostic(
						"graph.dangling-reference",
						document.path,
						`${document.metadata.id} references missing ${targetId}`,
					),
				);
			} else if (target.metadata.type !== expectedType) {
				diagnostics.push(
					diagnostic(
						"graph.forbidden-edge",
						document.path,
						`${document.metadata.id} must reference ${expectedType}; ${targetId} is ${target.metadata.type}`,
					),
				);
			}
		}
		if (document.metadata.type === "plan" && document.metadata.roadmap) {
			const roadmap = unique.get(document.metadata.roadmap);
			if (
				roadmap?.metadata.type === "roadmap" &&
				roadmap.metadata.spec !== document.metadata.spec
			) {
				diagnostics.push(
					diagnostic(
						"graph.forbidden-edge",
						document.path,
						`${document.metadata.roadmap} belongs to ${roadmap.metadata.spec}, not ${document.metadata.spec}`,
					),
				);
			}
		}
	}
	return { documents, diagnostics: diagnostics.sort(compareDiagnostics) };
}