repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/parser.ts

Raw
File outline
import {
	COMMENT_PREFIXES_BY_EXTENSION,
	DISABLE_MARKER,
	MARKER,
} from "./constants";

export interface MarkerPrompt {
	marker: typeof MARKER;
	file: string;
	startLine: number;
	endLine: number;
	prompt: string;
	key: string;
	promptHash: string;
}

const commentPrefixGroupCache = new Map<string, Map<string, string[]>>();

export function parseMarkerPrompts(
	file: string,
	text: string,
	commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
): MarkerPrompt[] {
	if (!text.includes("llmiterate")) return [];
	const prefixes = prefixesForFile(file, commentPrefixes);
	if (prefixes.length === 0) return [];
	if (isLlmiterateDisabled(text, file, commentPrefixes)) return [];

	const lines = normalizeLines(text);
	const prompts: MarkerPrompt[] = [];

	for (let i = 0; i < lines.length; i++) {
		const first = parsePromptLine(lines[i] ?? "", prefixes);
		if (!first) continue;

		const startLine = i + 1;
		const body = [first];
		let endLine = startLine;

		for (let j = i + 1; j < lines.length; j++) {
			const next = parsePromptLine(lines[j] ?? "", prefixes);
			if (!next) break;
			body.push(next);
			endLine = j + 1;
			i = j;
		}

		const prompt = body.join("\n").trim();
		if (prompt) prompts.push(makePrompt(file, startLine, endLine, prompt));
	}

	return prompts;
}

export function isLlmiterateDisabled(
	text: string,
	file = "",
	commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
): boolean {
	if (!text.includes(DISABLE_MARKER)) return false;
	const prefixes = prefixesForFile(file, commentPrefixes);
	if (prefixes.length === 0) return false;
	return normalizeLines(text).some((line) => {
		const stripped = stripCommentPrefix(line, prefixes);
		return stripped !== undefined && /^!llmiterate(?:\s|$)/.test(stripped);
	});
}

export function prefixesForFile(
	file: string,
	commentPrefixes: Record<string, string[]> = COMMENT_PREFIXES_BY_EXTENSION,
): string[] {
	return normalizeCommentPrefixes(commentPrefixes[extensionKey(file)] ?? []);
}

function extensionKey(file: string): string {
	const base = (file.split(/[\\/]/).pop() ?? "").toLowerCase();
	if (!base) return "";
	if (base === "dockerfile" || base.endsWith(".dockerfile"))
		return "dockerfile";
	const dot = base.lastIndexOf(".");
	return dot === -1 ? base : base.slice(dot + 1);
}

function parsePromptLine(line: string, prefixes: string[]): string | undefined {
	const stripped = stripCommentPrefix(line, prefixes);
	if (stripped === undefined || !stripped.startsWith(MARKER)) return undefined;
	const prompt = stripped.slice(MARKER.length).trim();
	return prompt || undefined;
}

function stripCommentPrefix(
	line: string,
	prefixes: string[],
): string | undefined {
	const trimmed = line.trimStart();
	const candidates = commentPrefixGroups(prefixes).get(trimmed[0] ?? "");
	if (!candidates) return undefined;
	for (const prefix of candidates) {
		if (!startsWithCommentPrefix(trimmed, prefix)) continue;
		const suffix = commentSuffix(prefix);
		let body = trimmed.slice(prefix.length).trimStart();
		if (suffix && body.endsWith(suffix))
			body = body.slice(0, -suffix.length).trimEnd();
		return body;
	}
	return undefined;
}

function startsWithCommentPrefix(line: string, prefix: string): boolean {
	if (!line.startsWith(prefix)) return false;
	if (/^[a-z]+$/i.test(prefix)) {
		const next = line[prefix.length];
		return next === undefined || /\s/.test(next);
	}
	return true;
}

function commentPrefixGroups(prefixes: string[]): Map<string, string[]> {
	const key = prefixes.join("\0");
	const cached = commentPrefixGroupCache.get(key);
	if (cached) return cached;
	const groups = new Map<string, string[]>();
	for (const prefix of prefixes) {
		const key = prefix[0] ?? "";
		const group = groups.get(key) ?? [];
		group.push(prefix);
		groups.set(key, group);
	}
	commentPrefixGroupCache.set(key, groups);
	return groups;
}

function commentSuffix(prefix: string): string | undefined {
	if (prefix === "<!--") return "-->";
	if (prefix === "/*" || prefix === "/**") return "*/";
	return undefined;
}

function normalizeLines(text: string): string[] {
	return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
}

function makePrompt(
	file: string,
	startLine: number,
	endLine: number,
	prompt: string,
): MarkerPrompt {
	const promptHash = hashString(prompt);
	return {
		marker: MARKER,
		file,
		startLine,
		endLine,
		prompt,
		promptHash,
		key: `${file}:${startLine}:${promptHash}`,
	};
}

function hashString(input: string): string {
	let hash = 0x811c9dc5;
	for (let i = 0; i < input.length; i++) {
		hash ^= input.charCodeAt(i);
		hash = Math.imul(hash, 0x01000193);
	}
	return (hash >>> 0).toString(16).padStart(8, "0");
}

function normalizeCommentPrefixes(prefixes: string[]): string[] {
	return [...new Set(prefixes.map((p) => p.trim()).filter(Boolean))].sort(
		(a, b) => b.length - a.length,
	);
}