334 lines
10 KiB
TypeScript
334 lines
10 KiB
TypeScript
/**
|
|
* Resolve effective mod load order, check dependencies/conflicts/version compatibility,
|
|
* detect overlapping pack or companion file targets, and offer topological auto-sorting.
|
|
*/
|
|
import {
|
|
MOD_API_VERSION,
|
|
type ClientModsConfig,
|
|
type DiscoveredMod,
|
|
type ModIssue,
|
|
type ResolvedModLoadOrder,
|
|
} from './types.ts';
|
|
|
|
export function emptyClientModsConfig(): ClientModsConfig {
|
|
return {
|
|
format: 1,
|
|
order: [],
|
|
enabled: {},
|
|
activePresetId: null,
|
|
presets: [],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Reconcile a saved client config with the currently discovered mods:
|
|
* keep saved order for known mods, append newly discovered mods alphabetically (disabled by default),
|
|
* and drop removed mod ids from the active ordering without destroying saved presets.
|
|
*/
|
|
export function normalizeClientModsConfig(
|
|
config: ClientModsConfig,
|
|
discovered: readonly DiscoveredMod[],
|
|
): ClientModsConfig {
|
|
const knownIds = new Set(discovered.map((mod) => mod.manifest.id));
|
|
const seen = new Set<string>();
|
|
const order: string[] = [];
|
|
for (const id of config.order) {
|
|
if (knownIds.has(id) && !seen.has(id)) {
|
|
seen.add(id);
|
|
order.push(id);
|
|
}
|
|
}
|
|
for (const mod of discovered) {
|
|
if (!seen.has(mod.manifest.id)) {
|
|
seen.add(mod.manifest.id);
|
|
order.push(mod.manifest.id);
|
|
}
|
|
}
|
|
const enabled: Record<string, boolean> = {};
|
|
for (const id of order) {
|
|
enabled[id] = config.enabled[id] === true;
|
|
}
|
|
return {
|
|
format: 1,
|
|
order,
|
|
enabled,
|
|
activePresetId: config.activePresetId,
|
|
presets: config.presets,
|
|
};
|
|
}
|
|
|
|
export function resolveModLoadOrder(
|
|
discovered: readonly DiscoveredMod[],
|
|
config: Pick<ClientModsConfig, 'order' | 'enabled'>,
|
|
gameVersion?: string | null,
|
|
): ResolvedModLoadOrder {
|
|
const byId = new Map(discovered.map((mod) => [mod.manifest.id, mod]));
|
|
const orderedIds: string[] = [];
|
|
const seen = new Set<string>();
|
|
for (const id of config.order) {
|
|
if (byId.has(id) && !seen.has(id)) {
|
|
seen.add(id);
|
|
orderedIds.push(id);
|
|
}
|
|
}
|
|
for (const mod of discovered) {
|
|
if (!seen.has(mod.manifest.id)) {
|
|
seen.add(mod.manifest.id);
|
|
orderedIds.push(mod.manifest.id);
|
|
}
|
|
}
|
|
|
|
const enabledMods = orderedIds
|
|
.filter((id) => config.enabled[id] === true)
|
|
.map((id) => byId.get(id)!);
|
|
const enabledIndex = new Map(enabledMods.map((mod, index) => [mod.manifest.id, index]));
|
|
const issues: ModIssue[] = [];
|
|
|
|
for (const mod of enabledMods) {
|
|
const id = mod.manifest.id;
|
|
const pos = enabledIndex.get(id)!;
|
|
|
|
if (mod.manifest.apiVersion !== MOD_API_VERSION) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'api-version-mismatch',
|
|
modId: id,
|
|
detail: `mod targets api_version "${mod.manifest.apiVersion}", current experimental API is "${MOD_API_VERSION}"`,
|
|
});
|
|
}
|
|
|
|
if (gameVersion && mod.manifest.gameVersions.length > 0 && !matchesAnyVersionPattern(gameVersion, mod.manifest.gameVersions)) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'game-version-mismatch',
|
|
modId: id,
|
|
detail: `mod lists game_versions [${mod.manifest.gameVersions.join(', ')}], client is ${gameVersion}`,
|
|
});
|
|
}
|
|
|
|
for (const reqId of mod.manifest.requires) {
|
|
if (!byId.has(reqId)) {
|
|
issues.push({
|
|
severity: 'error',
|
|
kind: 'missing-dependency',
|
|
modId: id,
|
|
otherModId: reqId,
|
|
detail: `requires missing mod "${reqId}"`,
|
|
});
|
|
} else if (!enabledIndex.has(reqId)) {
|
|
issues.push({
|
|
severity: 'error',
|
|
kind: 'dependency-disabled',
|
|
modId: id,
|
|
otherModId: reqId,
|
|
detail: `requires disabled mod "${reqId}"`,
|
|
});
|
|
} else if (enabledIndex.get(reqId)! > pos) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'dependency-order',
|
|
modId: id,
|
|
otherModId: reqId,
|
|
detail: `loaded before required dependency "${reqId}"`,
|
|
});
|
|
}
|
|
}
|
|
|
|
for (const conflictId of mod.manifest.conflicts) {
|
|
if (enabledIndex.has(conflictId) && id < conflictId) {
|
|
issues.push({
|
|
severity: 'error',
|
|
kind: 'declared-conflict',
|
|
modId: id,
|
|
otherModId: conflictId,
|
|
detail: `declares incompatibility with "${conflictId}"`,
|
|
});
|
|
}
|
|
}
|
|
|
|
for (const afterId of mod.manifest.loadAfter) {
|
|
const otherPos = enabledIndex.get(afterId);
|
|
if (otherPos !== undefined && otherPos > pos) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'load-order-hint',
|
|
modId: id,
|
|
otherModId: afterId,
|
|
detail: `recommends loading after "${afterId}"`,
|
|
});
|
|
}
|
|
}
|
|
|
|
for (const beforeId of mod.manifest.loadBefore) {
|
|
const otherPos = enabledIndex.get(beforeId);
|
|
if (otherPos !== undefined && otherPos < pos) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'load-order-hint',
|
|
modId: id,
|
|
otherModId: beforeId,
|
|
detail: `recommends loading before "${beforeId}"`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
detectTargetOverlaps(enabledMods, issues);
|
|
|
|
return {
|
|
enabledMods,
|
|
issues,
|
|
hasBlockingErrors: issues.some((issue) => issue.severity === 'error'),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Topologically sort mods using `requires`, `load_after`, and `load_before` constraints.
|
|
* Falls back gracefully to existing relative order when cycles exist.
|
|
*/
|
|
export function computeAutoSortOrder(
|
|
discovered: readonly DiscoveredMod[],
|
|
currentOrder: readonly string[],
|
|
): string[] {
|
|
const rank = new Map<string, number>();
|
|
currentOrder.forEach((id, index) => rank.set(id, index));
|
|
const ids = discovered.map((mod) => mod.manifest.id);
|
|
const idSet = new Set(ids);
|
|
const edges = new Map<string, Set<string>>(ids.map((id) => [id, new Set()]));
|
|
const inDegree = new Map<string, number>(ids.map((id) => [id, 0]));
|
|
|
|
const addEdge = (before: string, after: string) => {
|
|
if (!idSet.has(before) || !idSet.has(after) || before === after) return;
|
|
const outgoing = edges.get(before)!;
|
|
if (!outgoing.has(after)) {
|
|
outgoing.add(after);
|
|
inDegree.set(after, (inDegree.get(after) ?? 0) + 1);
|
|
}
|
|
};
|
|
|
|
for (const mod of discovered) {
|
|
const id = mod.manifest.id;
|
|
for (const req of mod.manifest.requires) addEdge(req, id);
|
|
for (const after of mod.manifest.loadAfter) addEdge(after, id);
|
|
for (const before of mod.manifest.loadBefore) addEdge(id, before);
|
|
}
|
|
|
|
const comparePriority = (a: string, b: string) => {
|
|
const ra = rank.get(a) ?? Number.MAX_SAFE_INTEGER;
|
|
const rb = rank.get(b) ?? Number.MAX_SAFE_INTEGER;
|
|
return ra !== rb ? ra - rb : a.localeCompare(b);
|
|
};
|
|
|
|
const ready = ids.filter((id) => (inDegree.get(id) ?? 0) === 0).sort(comparePriority);
|
|
const result: string[] = [];
|
|
|
|
while (ready.length > 0) {
|
|
const next = ready.shift()!;
|
|
result.push(next);
|
|
for (const target of edges.get(next)!) {
|
|
const deg = (inDegree.get(target) ?? 1) - 1;
|
|
inDegree.set(target, deg);
|
|
if (deg === 0) {
|
|
ready.push(target);
|
|
ready.sort(comparePriority);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (result.length < ids.length) {
|
|
const placed = new Set(result);
|
|
const remaining = ids.filter((id) => !placed.has(id)).sort(comparePriority);
|
|
result.push(...remaining);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function detectTargetOverlaps(enabledMods: readonly DiscoveredMod[], issues: ModIssue[]): void {
|
|
const packFiles = new Map<string, string>();
|
|
const packPatches = new Map<string, string>();
|
|
const companionFiles = new Map<string, string>();
|
|
const tuningFiles = new Map<string, string>();
|
|
|
|
for (const mod of enabledMods) {
|
|
const id = mod.manifest.id;
|
|
|
|
for (const op of mod.content.packOperations) {
|
|
const key = `${op.pack}:${op.targetPath.toLowerCase()}`;
|
|
if (op.action === 'file') {
|
|
const previous = packFiles.get(key) ?? packPatches.get(key);
|
|
if (previous && previous !== id) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'pack-file-override',
|
|
modId: id,
|
|
otherModId: previous,
|
|
detail: `replaces "${op.pack}/${op.targetPath}" already modified by "${previous}"`,
|
|
});
|
|
}
|
|
packFiles.set(key, id);
|
|
} else {
|
|
const previousFile = packFiles.get(key);
|
|
const previousPatch = packPatches.get(key);
|
|
if (previousFile && previousFile !== id) {
|
|
issues.push({
|
|
severity: 'info',
|
|
kind: 'pack-blk-shared-target',
|
|
modId: id,
|
|
otherModId: previousFile,
|
|
detail: `patches "${op.pack}/${op.targetPath}" after "${previousFile}"`,
|
|
});
|
|
} else if (previousPatch && previousPatch !== id) {
|
|
issues.push({
|
|
severity: 'info',
|
|
kind: 'pack-blk-shared-target',
|
|
modId: id,
|
|
otherModId: previousPatch,
|
|
detail: `merges into "${op.pack}/${op.targetPath}" after "${previousPatch}"`,
|
|
});
|
|
}
|
|
packPatches.set(key, id);
|
|
}
|
|
}
|
|
|
|
for (const file of mod.content.clientFiles) {
|
|
const key = file.toLowerCase();
|
|
const previous = companionFiles.get(key);
|
|
if (previous && previous !== id) {
|
|
issues.push({
|
|
severity: 'warning',
|
|
kind: 'client-file-conflict',
|
|
modId: id,
|
|
otherModId: previous,
|
|
detail: `companion file "${file}" overrides "${previous}"`,
|
|
});
|
|
}
|
|
companionFiles.set(key, id);
|
|
}
|
|
|
|
for (const tuning of mod.content.serverTuningFiles) {
|
|
const key = tuning.toLowerCase();
|
|
const previous = tuningFiles.get(key);
|
|
if (previous && previous !== id) {
|
|
issues.push({
|
|
severity: 'info',
|
|
kind: 'tuning-file-shared',
|
|
modId: id,
|
|
otherModId: previous,
|
|
detail: `merges server tuning "${tuning}.jsonc" after "${previous}"`,
|
|
});
|
|
}
|
|
tuningFiles.set(key, id);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function matchesVersionPattern(version: string, pattern: string): boolean {
|
|
if (pattern === '*') return true;
|
|
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*');
|
|
return new RegExp(`^${escaped}$`).test(version);
|
|
}
|
|
|
|
function matchesAnyVersionPattern(version: string, patterns: readonly string[]): boolean {
|
|
return patterns.some((pattern) => matchesVersionPattern(version, pattern));
|
|
}
|