import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { extractPackageSurface, type ApiExport, type ApiPackage } from "./apiSurface"; import { PACKAGE_SKILLS, SKILL_DIRS, skillForModule } from "./skillRouting"; import { npmNameOfFolder } from "./packageNames"; const OUT_NAME = "api.md"; const GENERATED_HEADER = ""; interface ModuleRef { importPath: string; pkg: string; srcFile: string; exports: ApiExport[]; } type SkillModules = Map; function collectSkillModules(root: string): SkillModules { const skills: SkillModules = new Map(SKILL_DIRS.map((s) => [s, []])); const packages = ["core", ...Object.keys(PACKAGE_SKILLS)]; for (const pkg of packages) { const surface: ApiPackage = extractPackageSurface(join(root, "packages", pkg)); for (const module of surface.modules) { const skill = skillForModule(pkg, module.path); if (skill === null) continue; const importPath = `${npmNameOfFolder(pkg)}/${module.path}`.replace(/\/index$/, ""); const srcBase = join(root, "packages", pkg, "src", module.path); const srcFile = existsSync(`${srcBase}.tsx`) ? `${srcBase}.tsx` : `${srcBase}.ts`; skills.get(skill)?.push({ importPath, pkg, srcFile, exports: module.exports }); } } for (const refs of skills.values()) refs.sort((a, b) => (a.importPath < b.importPath ? -1 : a.importPath > b.importPath ? 1 : 0)); return skills; } const MAX_FIELDS_LENGTH = 240; const MAX_USER_DOC_LENGTH = 140; function clip(text: string, max: number): string { return text.length > max ? `${text.slice(0, max)}…` : text; } function continuesOnNextLine(current: string, source: string, next: number): boolean { const tail = current.trimEnd(); if (tail === "") return false; if (/(?:[:|&]|=>)$/.test(tail)) return true; const following = source.slice(next).trimStart()[0]; return following === "|" || following === "&" || following === "."; } /** Top-level members of the interface body that starts at `open` (the index of its `{`). */ function interfaceMembers(source: string, open: number): string[] { const members: string[] = []; let depth = 0; let current = ""; for (let i = open + 1; i < source.length; i++) { const ch = source[i]!; if (ch === "{" || ch === "(" || ch === "[" || (ch === "<" && source[i + 1] !== "=")) depth++; else if (ch === "}" || ch === ")" || ch === "]" || (ch === ">" && source[i - 1] !== "=")) { if (depth === 0 && ch === "}") break; depth--; } if (depth === 0 && ch === "\n" && continuesOnNextLine(current, source, i + 1)) current += " "; else if (depth === 0 && (ch === ";" || ch === "," || ch === "\n")) { members.push(current); current = ""; } else current += ch; } members.push(current); return members .map((m) => m.replace(/\s+/g, " ").replace(/([([{<]) /g, "$1").replace(/,? ([)\]}>])/g, "$1").trim()) .filter((m) => m !== ""); } /** Field lists for every interface declared in a module source, keyed by name. */ function interfaceFields(srcFile: string): Map { const fields = new Map(); if (!existsSync(srcFile)) return fields; const source = readFileSync(srcFile, "utf8") .replace(/\/\*[\s\S]*?\*\//g, "") .replace(/(^|\s)\/\/.*$/gm, "$1"); for (const match of source.matchAll(/\binterface\s+([A-Za-z_$][\w$]*)/g)) { let i = (match.index ?? 0) + match[0].length; let angle = 0; for (; i < source.length; i++) { const ch = source[i]!; if (ch === "<") angle++; else if (ch === ">" && source[i - 1] !== "=") angle--; else if (ch === "{" && angle === 0) break; } if (i >= source.length) continue; const members = interfaceMembers(source, i); fields.set(match[1]!, members.length === 0 ? "{}" : clip(`{ ${members.join("; ")} }`, MAX_FIELDS_LENGTH)); } return fields; } interface Consumer { name: string; importPath: string; doc: string; } /** * Documented functions/classes/consts whose signature names a type, so an undocumented options or * result type points at the call that gives it meaning instead of forcing a source read. */ function buildConsumerIndex(all: readonly ModuleRef[]): (name: string, importPath: string) => Consumer | undefined { const documented: Consumer[] = []; const signatures: string[] = []; for (const module of all) { for (const e of module.exports) { if (e.kind !== "function" && e.kind !== "class" && e.kind !== "const") continue; if (e.doc === undefined || e.doc === "") continue; documented.push({ name: e.name, importPath: module.importPath, doc: e.doc }); signatures.push(e.signature); } } return (name, importPath) => { const word = new RegExp(`(^|[^\\w$])${name.replace(/\$/g, "\\$")}([^\\w$]|$)`); let fallback: Consumer | undefined; for (let i = 0; i < documented.length; i++) { const candidate = documented[i]!; if (candidate.name === name || !word.test(signatures[i]!)) continue; if (candidate.importPath === importPath) return candidate; fallback ??= candidate; } return fallback; }; } function undocumentedNote(e: ApiExport, module: ModuleRef, consumerOf: ReturnType): string { if (e.kind !== "interface" && e.kind !== "type") return "⚠ undocumented"; const consumer = consumerOf(e.name, module.importPath); if (consumer === undefined) return "⚠ undocumented"; const where = consumer.importPath === module.importPath ? "" : ` (${consumer.importPath})`; const [sentence] = consumer.doc.split(/(?<=\.)\s/); return `⚠ undocumented · used by \`${consumer.name}\`${where}: ${clip(sentence ?? consumer.doc, MAX_USER_DOC_LENGTH)}`; } /** Interface bodies declared anywhere in a package, for exports re-exported through a barrel; ambiguous names map to undefined. */ function buildPackageFields(all: readonly ModuleRef[]): (pkg: string, name: string) => string | undefined { const byPackage = new Map>(); const seenFiles = new Set(); for (const module of all) { if (seenFiles.has(module.srcFile)) continue; seenFiles.add(module.srcFile); const names = byPackage.get(module.pkg) ?? new Map(); byPackage.set(module.pkg, names); for (const [name, body] of interfaceFields(module.srcFile)) { names.set(name, names.has(name) && names.get(name) !== body ? undefined : body); } } return (pkg, name) => byPackage.get(pkg)?.get(name); } function renderSkillApi( skill: string, modules: ModuleRef[], consumerOf: ReturnType, packageFields: ReturnType, ): string { const lines: string[] = [GENERATED_HEADER, "", `# ${skill} — exported API surface`, ""]; for (const module of modules) { lines.push(`## ${module.importPath}`); lines.push(""); let fields: Map | undefined; for (const e of module.exports) { const documented = e.doc !== undefined && e.doc !== ""; let signature = e.signature; if (!documented && e.kind === "interface") { fields ??= interfaceFields(module.srcFile); const body = fields.get(e.name) ?? packageFields(module.pkg, e.name); if (body !== undefined && !signature.endsWith("…")) signature = `${signature} ${body}`; } const doc = documented ? e.doc : undocumentedNote(e, module, consumerOf); lines.push(`- \`${e.name}\` (${e.kind}): ${signature} — ${doc}`); } lines.push(""); } return `${lines.join("\n").trimEnd()}\n`; } function main(): void { const check = process.argv.includes("--check"); const root = fileURLToPath(new URL("..", import.meta.url)); const failures: string[] = []; const skills = collectSkillModules(root); const outDir = check ? mkdtempSync(join(tmpdir(), "jg-skill-api-")) : undefined; const allModules = [...skills.values()].flat(); const consumerOf = buildConsumerIndex(allModules); const packageFields = buildPackageFields(allModules); for (const skill of SKILL_DIRS) { const modules = skills.get(skill) ?? []; const content = renderSkillApi(skill, modules, consumerOf, packageFields); const committedPath = join(root, ".claude", "skills", skill, OUT_NAME); if (check) { const committed = existsSync(committedPath) ? readFileSync(committedPath, "utf8") : ""; if (committed !== content) { writeFileSync(join(outDir ?? tmpdir(), `${skill}.api.md`), content); failures.push(`.claude/skills/${skill}/${OUT_NAME} is stale — run: bun run gen skill-api`); } } else { writeFileSync(committedPath, content); console.log(`OK ${skill}: ${modules.length} modules -> .claude/skills/${skill}/${OUT_NAME}`); } } if (failures.length > 0) { console.error(`\ncheck-skill-api failed:\n${failures.map((f) => ` ${f}`).join("\n")}\n`); process.exit(1); } const total = [...skills.values()].reduce((n, m) => n + m.length, 0); console.log(`skill-api ok: ${total} modules across ${SKILL_DIRS.length} skills`); } if (import.meta.main) main();