160 lines
6.0 KiB
TypeScript
160 lines
6.0 KiB
TypeScript
/**
|
|
* Parse and validate `mod.jsonc` manifests.
|
|
*/
|
|
import { readFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { parseJsonc } from '@wto/jsonc';
|
|
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts';
|
|
|
|
export const MOD_MANIFEST_FILE = 'mod.jsonc';
|
|
|
|
const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
const ALLOWED_ROOT_KEYS = new Set([
|
|
'format',
|
|
'id',
|
|
'name',
|
|
'version',
|
|
'author',
|
|
'description',
|
|
'api_version',
|
|
'game_versions',
|
|
'requires',
|
|
'conflicts',
|
|
'load_after',
|
|
'load_before',
|
|
'server',
|
|
]);
|
|
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
|
|
|
|
export class ModManifestError extends Error {
|
|
override name = 'ModManifestError';
|
|
}
|
|
|
|
export function readModManifest(modDir: string): ModManifest {
|
|
const filePath = join(modDir, MOD_MANIFEST_FILE);
|
|
let raw: unknown;
|
|
try {
|
|
raw = parseJsonc(readFileSync(filePath, 'utf8'));
|
|
} catch (error) {
|
|
throw new ModManifestError(`cannot parse ${MOD_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
return parseModManifest(raw, filePath);
|
|
}
|
|
|
|
export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModManifest {
|
|
const obj = expectObject(raw, where);
|
|
rejectUnknownKeys(obj, ALLOWED_ROOT_KEYS, where);
|
|
|
|
if (obj.format !== MOD_FORMAT_VERSION) {
|
|
throw new ModManifestError(`${where}: "format" must be ${MOD_FORMAT_VERSION}`);
|
|
}
|
|
const id = expectString(obj.id, `${where} "id"`);
|
|
if (!MOD_ID_PATTERN.test(id)) {
|
|
throw new ModManifestError(`${where}: "id" must match ${MOD_ID_PATTERN.source} (got "${id}")`);
|
|
}
|
|
const name = expectLocalizedText(obj.name, `${where} "name"`);
|
|
const version = expectString(obj.version, `${where} "version"`);
|
|
const author = expectString(obj.author, `${where} "author"`);
|
|
const description = obj.description === undefined ? undefined : expectLocalizedText(obj.description, `${where} "description"`);
|
|
const apiVersion = expectString(obj.api_version, `${where} "api_version"`);
|
|
const gameVersions = optionalStringList(obj.game_versions, `${where} "game_versions"`);
|
|
const requires = optionalIdList(obj.requires, `${where} "requires"`, id);
|
|
const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id);
|
|
const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id);
|
|
const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id);
|
|
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
|
|
|
|
return {
|
|
format: MOD_FORMAT_VERSION,
|
|
id,
|
|
name,
|
|
version,
|
|
author,
|
|
...(description !== undefined ? { description } : {}),
|
|
apiVersion,
|
|
gameVersions,
|
|
requires,
|
|
conflicts,
|
|
loadAfter,
|
|
loadBefore,
|
|
...(server !== undefined ? { server } : {}),
|
|
};
|
|
}
|
|
|
|
function parseServerConfig(raw: unknown, where: string): ModServerConfig {
|
|
const obj = expectObject(raw, where);
|
|
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
|
|
const entry = obj.entry === undefined ? undefined : expectSafeRelativePath(obj.entry, `${where} "entry"`);
|
|
const tuning = obj.tuning === undefined ? undefined : expectSafeRelativePath(obj.tuning, `${where} "tuning"`);
|
|
return {
|
|
...(entry !== undefined ? { entry } : {}),
|
|
...(tuning !== undefined ? { tuning } : {}),
|
|
};
|
|
}
|
|
|
|
export function expectSafeRelativePath(raw: unknown, where: string): string {
|
|
const text = expectString(raw, where).replaceAll('\\', '/');
|
|
if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) {
|
|
throw new ModManifestError(`${where}: path must be relative to the mod folder (got "${text}")`);
|
|
}
|
|
const segments = text.split('/').filter((segment) => segment.length > 0);
|
|
if (segments.length === 0 || segments.some((segment) => segment === '.' || segment === '..')) {
|
|
throw new ModManifestError(`${where}: path must not contain "." or ".." segments (got "${text}")`);
|
|
}
|
|
return segments.join('/');
|
|
}
|
|
|
|
function expectObject(value: unknown, where: string): Record<string, unknown> {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
throw new ModManifestError(`${where}: expected an object`);
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
function rejectUnknownKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
|
|
const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
|
|
if (unknown.length > 0) {
|
|
throw new ModManifestError(`${where}: unknown field(s): ${unknown.join(', ')}`);
|
|
}
|
|
}
|
|
|
|
function expectString(value: unknown, where: string): string {
|
|
if (typeof value !== 'string' || value.trim().length === 0) {
|
|
throw new ModManifestError(`${where}: must be a non-empty string`);
|
|
}
|
|
return value.trim();
|
|
}
|
|
|
|
function expectLocalizedText(value: unknown, where: string): LocalizedText {
|
|
if (typeof value === 'string') {
|
|
if (value.trim().length === 0) throw new ModManifestError(`${where}: must not be empty`);
|
|
return value.trim();
|
|
}
|
|
const obj = expectObject(value, where);
|
|
const entries = Object.entries(obj);
|
|
if (entries.length === 0) throw new ModManifestError(`${where}: localized map must not be empty`);
|
|
const out: Record<string, string> = {};
|
|
for (const [lang, text] of entries) {
|
|
out[lang] = expectString(text, `${where}.${lang}`);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function optionalStringList(value: unknown, where: string): readonly string[] {
|
|
if (value === undefined) return [];
|
|
if (!Array.isArray(value)) throw new ModManifestError(`${where}: must be an array of strings`);
|
|
return value.map((item, index) => expectString(item, `${where}[${index}]`));
|
|
}
|
|
|
|
function optionalIdList(value: unknown, where: string, selfId: string): readonly string[] {
|
|
const ids = optionalStringList(value, where);
|
|
const seen = new Set<string>();
|
|
for (const id of ids) {
|
|
if (!MOD_ID_PATTERN.test(id)) throw new ModManifestError(`${where}: invalid mod id "${id}"`);
|
|
if (id === selfId) throw new ModManifestError(`${where}: mod cannot reference itself ("${id}")`);
|
|
if (seen.has(id)) throw new ModManifestError(`${where}: duplicate mod id "${id}"`);
|
|
seen.add(id);
|
|
}
|
|
return ids;
|
|
}
|