diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index a85f751..7ae6b2e 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -37,6 +37,9 @@ jobs: - name: Validate index run: node scripts/validate-index.mjs lithe-plugin-index.json + - name: Validate recommendations + run: node scripts/validate-recommendations.mjs lithe-plugin-recommendations.json lithe-plugin-index.json + - name: Pick the base index id: base run: | diff --git a/lithe-plugin-recommendations.json b/lithe-plugin-recommendations.json new file mode 100644 index 0000000..779b461 --- /dev/null +++ b/lithe-plugin-recommendations.json @@ -0,0 +1,24 @@ +{ + "schemaVersion": 0, + "recommendations": [ + { + "pluginID": "io.github.lithe-idea.go-support", + "markers": ["go.mod", "go.work"], + "extensions": ["go"] + }, + { + "pluginID": "io.github.lithe-idea.gradle-build", + "markers": ["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"] + }, + { + "pluginID": "io.github.lithe-idea.java-support", + "markers": ["build.gradle", "build.gradle.kts", "pom.xml"], + "extensions": ["java"], + "coveredBy": ["io.github.lithe-idea.java-navigation"] + }, + { + "pluginID": "io.github.lithe-idea.maven-build", + "markers": ["pom.xml"] + } + ] +} diff --git a/scripts/store.test.mjs b/scripts/store.test.mjs index c50c8ce..7b51ff3 100644 --- a/scripts/store.test.mjs +++ b/scripts/store.test.mjs @@ -13,6 +13,7 @@ import { import { checkManifest, formatIndex, inspectArchive, readPackageManifests, validateEntry, validateIndex, verifyArchives, } from "./validate-index.mjs"; +import { validateRecommendations } from "./validate-recommendations.mjs"; // Fixtures are copied from the plugin contract (Lithe-core-rust shared/plugins/contract/v1/fixtures/marketplace) // so this validator reports the same code as Lithe's Rust Core for each case. @@ -573,3 +574,94 @@ test("overview helpers derive category, systems and truncated text", () => { test("rendering refuses a README without the overview markers", () => { assert.throws(() => renderReadme("# Lithe Store\n", { plugins: [] }), /markers/); }); + +test("recommendations validation accepts store catalog and rejects contract/policy errors", () => { + const realIndex = JSON.parse(readFileSync(new URL("../lithe-plugin-index.json", import.meta.url))); + const realRecommendations = JSON.parse( + readFileSync(new URL("../lithe-plugin-recommendations.json", import.meta.url)), + ); + assert.deepEqual(validateRecommendations(realRecommendations, realIndex), []); + + const index = { + schemaVersion: 0, + plugins: [{ id: "io.example.a" }, { id: "io.example.b" }], + }; + assert.deepEqual( + validateRecommendations( + { + schemaVersion: 0, + recommendations: [ + { pluginID: "io.example.a", markers: ["a.toml"], coveredBy: ["io.example.b"] }, + { pluginID: "io.example.b", extensions: ["b"] }, + ], + }, + index, + ), + [], + ); + + assert.match( + validateRecommendations( + { schemaVersion: 0, recommendations: [{ pluginID: "io.example.unknown", markers: ["x"] }] }, + index, + ).join(), + /unknown pluginID/, + ); + assert.match( + validateRecommendations( + { + schemaVersion: 0, + recommendations: [ + { pluginID: "io.example.a", markers: ["a"] }, + { pluginID: "io.example.a", extensions: ["a"] }, + ], + }, + index, + ).join(), + /plugin\.recommendations\.duplicate/, + ); + assert.match( + validateRecommendations( + { + schemaVersion: 0, + recommendations: [{ pluginID: "io.example.a", markers: ["a"], coveredBy: ["io.example.a"] }], + }, + index, + ).join(), + /coveredBy/, + ); + assert.match( + validateRecommendations( + { schemaVersion: 0, recommendations: [{ pluginID: "io.example.a", markers: ["../a"] }] }, + index, + ).join(), + /markers/, + ); + assert.match( + validateRecommendations( + { schemaVersion: 0, recommendations: [{ pluginID: "io.example.a", extensions: [".a"] }] }, + index, + ).join(), + /extensions/, + ); + assert.match( + validateRecommendations( + { schemaVersion: 0, recommendations: [{ pluginID: "io.example.a" }] }, + index, + ).join(), + /marker or extension/, + ); + assert.match( + validateRecommendations( + { + schemaVersion: 0, + recommendations: [ + { pluginID: "io.example.b", markers: ["b"] }, + { pluginID: "io.example.a", markers: ["a"] }, + ], + }, + index, + ).join(), + /sorted/, + ); +}); diff --git a/scripts/validate-recommendations.mjs b/scripts/validate-recommendations.mjs new file mode 100644 index 0000000..3dfbef9 --- /dev/null +++ b/scripts/validate-recommendations.mjs @@ -0,0 +1,194 @@ +#!/usr/bin/env node +// Validates lithe-plugin-recommendations.json against the Lithe plugin contract +// (plugin-recommendations.schema.json in Lithe-IDEA/Lithe-core-rust) and cross-checks +// every referenced pluginID and coveredBy entry against lithe-plugin-index.json. +// +// Usage: +// node scripts/validate-recommendations.mjs [recommendations.json] [index.json] +// node scripts/validate-recommendations.mjs [recommendations.json] [index.json] --write-format + +import { readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { formatIndex } from "./validate-index.mjs"; + +const ENTRY_FIELDS = new Set(["pluginID", "markers", "extensions", "coveredBy"]); +const PLUGIN_ID = /^[a-z0-9.-]+$/; +const EXTENSION = /^[a-z0-9][a-z0-9_-]{0,31}$/; + +function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function isValidMarker(value) { + return typeof value === "string" + && value.length > 0 + && value === value.trim() + && value !== "." + && value !== ".." + && !value.includes("/") + && !value.includes("\\"); +} + +function validateStringList(entry, field, label, checkItem, message, problems) { + if (!(field in entry)) return; + const list = entry[field]; + if (!Array.isArray(list)) { + problems.push(`${label}: plugin.recommendations.invalid: \`${field}\` must be an array`); + return; + } + const seen = new Set(); + list.forEach((item, index) => { + if (!checkItem(item)) { + problems.push(`${label}.${field}[${index}]: plugin.recommendations.invalid: ${message}`); + return; + } + if (seen.has(item)) { + problems.push(`${label}.${field}[${index}]: plugin.recommendations.invalid: duplicate value \`${item}\``); + } + seen.add(item); + }); + const sorted = [...list].filter((item) => typeof item === "string").sort(); + if (list.some((item, index) => item !== sorted[index])) { + problems.push(`store policy: ${label}.${field} must be sorted`); + } +} + +/** Validates the recommendation catalog, optionally against an index's known plugin IDs. */ +export function validateRecommendations(catalog, index = undefined) { + if (!isObject(catalog)) return ["recommendations root must be an object"]; + const problems = []; + for (const key of Object.keys(catalog)) { + if (key !== "schemaVersion" && key !== "recommendations") { + problems.push(`plugin.recommendations.invalid: unknown root field \`${key}\``); + } + } + if (catalog.schemaVersion !== 0) { + problems.push("plugin.recommendations.schemaUnsupported: `schemaVersion` must be 0"); + } + if (!Array.isArray(catalog.recommendations)) { + return [...problems, "plugin.recommendations.invalid: `recommendations` must be an array"]; + } + + let knownIDs = null; + if (index !== undefined) { + if (!isObject(index) || !Array.isArray(index.plugins)) { + problems.push("index root must hold a `plugins` array"); + } else { + knownIDs = new Set(index.plugins.map((plugin) => plugin?.id).filter((id) => typeof id === "string")); + } + } + + const seenIDs = new Set(); + const listedIDs = []; + catalog.recommendations.forEach((entry, position) => { + const label = `recommendations[${position}]${typeof entry?.pluginID === "string" ? ` (${entry.pluginID})` : ""}`; + if (!isObject(entry)) { + problems.push(`${label}: plugin.recommendations.invalid: entry must be an object`); + return; + } + for (const key of Object.keys(entry)) { + if (!ENTRY_FIELDS.has(key)) { + problems.push(`${label}: plugin.recommendations.invalid: unknown field \`${key}\``); + } + } + if (typeof entry.pluginID !== "string" || !PLUGIN_ID.test(entry.pluginID)) { + problems.push(`${label}: plugin.recommendations.invalid: \`pluginID\` must match ^[a-z0-9.-]+$`); + } else { + listedIDs.push(entry.pluginID); + if (seenIDs.has(entry.pluginID)) { + problems.push(`${label}: plugin.recommendations.duplicate: pluginID is already listed`); + } + seenIDs.add(entry.pluginID); + if (knownIDs && !knownIDs.has(entry.pluginID)) { + problems.push(`${label}: store policy: unknown pluginID \`${entry.pluginID}\` is not in index`); + } + } + + validateStringList( + entry, + "markers", + label, + isValidMarker, + "markers must be trimmed basenames without path separators", + problems, + ); + validateStringList( + entry, + "extensions", + label, + (item) => typeof item === "string" && EXTENSION.test(item), + "extensions must match ^[a-z0-9][a-z0-9_-]{0,31}$", + problems, + ); + validateStringList( + entry, + "coveredBy", + label, + (item) => typeof item === "string" && PLUGIN_ID.test(item) && item !== entry.pluginID, + "coveredBy entries must be distinct valid plugin IDs", + problems, + ); + + if (Array.isArray(entry.coveredBy) && knownIDs) { + entry.coveredBy.forEach((alternative, idx) => { + if (typeof alternative === "string" && !knownIDs.has(alternative)) { + problems.push(`${label}.coveredBy[${idx}]: store policy: unknown coveredBy ID \`${alternative}\` is not in index`); + } + }); + } + + const markerCount = Array.isArray(entry.markers) ? entry.markers.length : 0; + const extensionCount = Array.isArray(entry.extensions) ? entry.extensions.length : 0; + if (markerCount === 0 && extensionCount === 0) { + problems.push(`${label}: plugin.recommendations.invalid: entry must declare at least one marker or extension`); + } + }); + + const sortedIDs = [...listedIDs].sort(); + if (listedIDs.some((id, indexPos) => id !== sortedIDs[indexPos])) { + problems.push("store policy: `recommendations` must be sorted by pluginID"); + } + return problems; +} + +async function main(argv) { + const args = [...argv]; + const writeFormat = args.includes("--write-format"); + const files = args.filter((arg) => !arg.startsWith("--")); + const recommendationsPath = files[0] ?? "lithe-plugin-recommendations.json"; + const indexPath = files[1] ?? "lithe-plugin-index.json"; + + let catalog; + let index; + try { + catalog = JSON.parse(readFileSync(recommendationsPath, "utf8")); + } catch (error) { + console.error(`${recommendationsPath}: ${error.message}`); + return 1; + } + try { + index = JSON.parse(readFileSync(indexPath, "utf8")); + } catch (error) { + console.error(`${indexPath}: ${error.message}`); + return 1; + } + + const problems = validateRecommendations(catalog, index); + const formatted = formatIndex(catalog); + if (writeFormat) { + writeFileSync(recommendationsPath, formatted); + } else if (readFileSync(recommendationsPath, "utf8") !== formatted) { + problems.push( + `store policy: ${recommendationsPath} is not canonically formatted; run node scripts/validate-recommendations.mjs ${recommendationsPath} ${indexPath} --write-format`, + ); + } + + for (const problem of problems) console.error(`✗ ${problem}`); + if (problems.length > 0) return 1; + console.log(`✓ ${recommendationsPath}: ${catalog.recommendations.length} recommendation(s) valid`); + return 0; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + process.exitCode = await main(process.argv.slice(2)); +}