Add requiredMods to plugin declarations (#1229)

* Add requiredMods to plugin declarations

Plugins can list the Factorio mods they need under requiredMods. When an
instance starts, the host warns in the instance log about each loaded
plugin whose required mods are missing or disabled in the mod pack.
Subspace Storage declares the subspace_storage mod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Refuse to start without required mods and download them

requiredMods entries are now Factorio dependency strings, and a mod
listed twice gives a version range. The plugin loader validates them.

The host refuses to start an instance whose mod pack is missing a
required mod of a loaded plugin, has it disabled or has it outside the
version range.

On start the controller resolves the required mods of its plugins and
their dependencies for the default mod pack's Factorio version and
downloads the ones missing from the mod store. The resolver and portal
download move from the ControlConnection handlers into Controller
methods so both paths share them.

Subspace Storage requires subspace_storage >= 1.99.0, and the
integration tests build a stub of that mod for the test mod pack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add a Factorio 1.1 variant to the subspace_storage test stub

The 1.1 test jobs failed because the test mod pack asked for
subspace_storage 2.3.11, which the stub did not build. The real mod
publishes 2.3.11 for 1.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cooldude2606andClaude Opus 5.5 authored and GitHub committed 2026-11-19 20:07:40 +00:00
commit dd20054151
12 files changed
+479 -206

No files matched your search

+23
View File
@@ -151,6 +151,10 @@ The following properties are recognized:
Array of features the plugin needs from the instances it is loaded on, any of `"SavePatching"`, `"ScriptCommands"` and `"LuaUdp"`.
See [Handling Invalid Configuration](#handling-invalid-configuration)
**requiredMods**:
Array of Factorio mods the plugin needs in the mod pack of the instances it is loaded on, written as Factorio dependency strings.
See [Handling Invalid Configuration](#handling-invalid-configuration)
**messages**:
Array of request and event classes for this plugin.
See guide for [defining link messages](#defining-link-messages) below.
@@ -321,6 +325,25 @@ export const plugin = {
Enabling the plugin on an instance that has the feature turned off then fails config validation, so the mistake is caught when the config is edited instead of when the instance starts.
Instances that have the feature turned off get the plugin disabled by default when it is added.
If the plugin talks to a Factorio mod, list the mod under `requiredMods` using the same format as `dependencies` in a mod's info.json, without a prefix.
List a mod twice to give a version range:
```js
export const plugin = {
name: "foo_frobber",
// ...
requiredMods: ["frobber >= 1.2.0", "frobber < 2.0.0"],
};
```
An instance with the plugin loaded refuses to start if its mod pack is missing one of the mods, has it disabled, or has a version outside the range.
Leave out the dependencies of the required mods. Factorio checks those itself.
When the controller starts it downloads required mods it does not have, and their dependencies, from the mod portal for the Factorio version of the default mod pack.
This needs `controller.factorio_username` and `controller.factorio_token` to be set.
The mods still have to be added to the mod packs by hand.
Forks of a required mod are not supported.
Other constraints on config fields are expressed with a `validator` on the field definition, which throws when the value is not acceptable.
Use `dependsOn` when the check involves other fields so that the validator runs when those change too.
See [Configuration System](config-system.md) for details.
+3 -206
View File
@@ -662,36 +662,7 @@ export default class ControlConnection extends BaseConnection {
* @param request - Request object with mod name, version, and factorioVersion.
*/
async handleModPortalDownloadRequest(request: lib.ModPortalDownloadRequest) {
const factorioVersion = request.factorioVersion;
const toDownload = this._controller.modStore.filterInstalled(request.mods, false);
if (toDownload.length > 0) {
// Get Factorio credentials from config
const username = this._controller.config.get("controller.factorio_username");
const token = this._controller.config.get("controller.factorio_token");
if (!username || username === "" || !token || token === "") {
throw new lib.ConflictError("Factorio credentials (username, token) not configured on the controller.");
}
try {
logger.info(`Downloading ${toDownload.length} mods for Factorio ${factorioVersion} from portal.`);
await this._controller.modStore.downloadMods(toDownload, username, token, factorioVersion);
} catch (error: any) {
logger.error(`Error downloading mods from portal: ${error.message}`);
const errorMessage = "Mod portal download failed";
if (error.message.includes("401") || error.message.includes("Unauthorized")) {
throw new lib.ConflictError(
`${errorMessage}: Authentication failed. Check Factorio username/token in controller config.`
);
}
if (error.message.includes("404") || error.message.includes("Not Found")) {
throw new lib.NotFoundError(`${errorMessage}: Mod version not found on the portal.`);
}
throw new lib.InternalServerError(`${errorMessage}: ${error.message}`);
}
}
await this._controller.downloadModsFromPortal(request.mods, request.factorioVersion);
// Verify all mods are present
const modInfos = [];
@@ -707,183 +678,9 @@ export default class ControlConnection extends BaseConnection {
return modInfos;
}
// eslint-disable-next-line complexity
async handleModDependencyResolveRequest(request: lib.ModDependencyResolveRequest) {
const {factorioVersion, checkForUpdates} = request;
const searchQueue = [...request.mods];
const localInfos = [...this._controller.modStore.mods()];
const builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion);
const skipSearch = new Set(builtInModNames);
type ModPortalModType = InstanceType<typeof lib.ModPortalGetAllRequest.Response>["mods"][number];
type ModPortalReleaseType = NonNullable<ModPortalModType["releases"]>[number];
const dependencyRequirements = new Map<string, lib.ModVersionRange>();
const recommendedRequirements = new Map<string, lib.ModVersionRange>();
const optionalRequirements = new Map<string, lib.ModVersionRange>();
const candidateReleases = new Map<string, lib.ModInfo>();
const errors = new Map<string, lib.ModDependencyResolveErrors>();
const _modPortalReleases = new Map<string, ModPortalModType | null>();
async function fetchModReleases(modName: string) {
let releases = _modPortalReleases.get(modName);
if (releases === undefined) {
try {
releases = await lib.ModStore.fetchModReleases(modName);
} catch (error: any) {
if (!error.message.includes("404") && !error.message.includes("Not Found")) {
logger.error(`Error fetching mod from portal: ${error.message}`);
throw new lib.InternalServerError(`Dependency resolution failed: ${error.message}`);
} else {
releases = null;
}
}
}
_modPortalReleases.set(modName, releases);
return releases;
}
function selectModRelease(releases: ModPortalModType | null, versionRange: lib.ModVersionRange) {
if (!releases || !releases.releases) {
return null;
}
// Select the latest matching version for the mod pack's Factorio version
const release = releases.releases
.filter(info => (
versionRange.testVersion(info.version)
&& lib.normaliseMajorMinorVersion(
lib.normaliseSourceVersion(info.info_json.factorio_version)
) === factorioVersion
))
.reduce<ModPortalReleaseType | undefined>((max, cur) => (
max && lib.integerSourceVersion(max.version) > lib.integerSourceVersion(cur.version) ? max : cur
), undefined);
if (!release) {
return null;
}
// Create the mod info class from the selected
try {
return lib.ModInfo.fromJSON({
...release.info_json, // includes dependencies
sha1: release.sha1,
version: release.version,
name: releases.name,
author: releases.owner,
title: releases.title,
});
} catch {
// Can error if there are invalid dependencies
errors.set(releases.name, "invalidDependency");
return null;
}
}
while (searchQueue.length > 0) {
// Dequeue the next mod, skip if incompatible
const mod = searchQueue.shift()!;
if (mod.incompatible) {
errors.set(mod.name, "incompatible");
continue;
}
// Get the current version range (dependencies can be promoted to a stricter requirement)
const versionRange =
dependencyRequirements.get(mod.name)
?? recommendedRequirements.get(mod.name)
?? optionalRequirements.get(mod.name)
?? new lib.ModVersionRange();
if (mod.required) {
// Add to required, remove from recommended and optional
dependencyRequirements.set(mod.name, versionRange);
recommendedRequirements.delete(mod.name);
optionalRequirements.delete(mod.name);
} else if (mod.recommended) {
// If not required, add to recommended and remove from optional
if (!dependencyRequirements.has(mod.name)) {
recommendedRequirements.set(mod.name, versionRange);
optionalRequirements.delete(mod.name);
}
} else if (
!dependencyRequirements.has(mod.name)
&& !recommendedRequirements.has(mod.name)
) {
// If not required or recommended, add to optional
optionalRequirements.set(mod.name, versionRange);
}
// Update the version range if needed
if (mod.version) {
versionRange.combineVersion(mod.version);
if (!versionRange.valid) {
candidateReleases.delete(mod.name);
errors.set(mod.name, "unsatisfiable");
continue;
}
}
// Do not add dependencies for errors, skips, optionals, or valid candidates
const existingCandidate = candidateReleases.get(mod.name);
if (errors.has(mod.name) || skipSearch.has(mod.name) || optionalRequirements.has(mod.name) || (
existingCandidate && versionRange.testVersion(existingCandidate.version)
)) {
continue;
}
// Check if a local version fits the requirements
let candidate = localInfos
.filter(info => (
info.name === mod.name
&& info.factorioVersion === factorioVersion
&& versionRange.testVersion(info.version)
))
.reduce<lib.ModInfo | undefined>((max, cur) => (
max && max.integerVersion > cur.integerVersion ? max : cur
), undefined);
// Check if a mod poral version fits the requirements
if (!candidate || checkForUpdates) {
const releases = await fetchModReleases(mod.name);
const release = selectModRelease(releases, versionRange);
// We only select the mod portal release if it is more recent than the local candidate
if (release && (!candidate || release.integerVersion > candidate.integerVersion)) {
candidate = release;
}
}
// Queue the dependencies of the new candidate
if (candidate) {
candidateReleases.set(mod.name, candidate);
for (const dep of candidate.dependencies) {
searchQueue.push(dep);
}
} else {
candidateReleases.delete(mod.name);
skipSearch.add(mod.name);
}
}
// Add the not found dependencies as errors
for (const modName of dependencyRequirements.keys()) {
if (!candidateReleases.has(modName) && !errors.has(modName)) {
errors.set(modName, "notFound");
}
}
// Remove incompatible and unsatisfiable dependencies if they aren't required by others
for (const [modName, error] of errors) {
if (!dependencyRequirements.has(modName) && (error === "incompatible" || error === "unsatisfiable")) {
errors.delete(modName);
}
}
return new lib.ModDependencyResolveRequest.Response(
[...candidateReleases.values()], errors,
return await this._controller.resolveModDependencies(
request.mods, request.factorioVersion, request.checkForUpdates,
);
}
+262
View File
@@ -512,6 +512,9 @@ export default class Controller {
logger.info("Started controller");
this.startedAtMs = Date.now();
this.downloadRequiredMods().catch(
err => logger.warn(`Unable to download mods required by plugins: ${err.message}`)
);
this.onAutosaveIntervalChanged();
this.onSystemMetricsIntervalChanged();
this._state = "running";
@@ -1169,6 +1172,265 @@ export default class Controller {
}
/**
* Download mods from the Factorio mod portal to the mod store
*
* Mods already in the mod store are skipped.
*
* @throws {lib.ConflictError} if the Factorio credentials are not configured.
*/
async downloadModsFromPortal(mods: lib.ModNameVersionPair[], factorioVersion: lib.MajorMinorVersion) {
const toDownload = this.modStore.filterInstalled(mods, false);
if (toDownload.length > 0) {
// Get Factorio credentials from config
const username = this.config.get("controller.factorio_username");
const token = this.config.get("controller.factorio_token");
if (!username || username === "" || !token || token === "") {
throw new lib.ConflictError("Factorio credentials (username, token) not configured on the controller.");
}
try {
logger.info(`Downloading ${toDownload.length} mods for Factorio ${factorioVersion} from portal.`);
await this.modStore.downloadMods(toDownload, username, token, factorioVersion);
} catch (error: any) {
logger.error(`Error downloading mods from portal: ${error.message}`);
const errorMessage = "Mod portal download failed";
if (error.message.includes("401") || error.message.includes("Unauthorized")) {
throw new lib.ConflictError(
`${errorMessage}: Authentication failed. Check Factorio username/token in controller config.`
);
}
if (error.message.includes("404") || error.message.includes("Not Found")) {
throw new lib.NotFoundError(`${errorMessage}: Mod version not found on the portal.`);
}
throw new lib.InternalServerError(`${errorMessage}: ${error.message}`);
}
}
}
/**
* Resolve mods and their dependencies against the mod store and the Factorio mod portal
*/
// eslint-disable-next-line complexity
async resolveModDependencies(
mods: lib.ModDependency[],
factorioVersion: lib.MajorMinorVersion,
checkForUpdates = false,
) {
const searchQueue = [...mods];
const localInfos = [...this.modStore.mods()];
const builtInModNames = lib.ModPack.getBuiltinModNames(factorioVersion);
const skipSearch = new Set(builtInModNames);
type ModPortalModType = InstanceType<typeof lib.ModPortalGetAllRequest.Response>["mods"][number];
type ModPortalReleaseType = NonNullable<ModPortalModType["releases"]>[number];
const dependencyRequirements = new Map<string, lib.ModVersionRange>();
const recommendedRequirements = new Map<string, lib.ModVersionRange>();
const optionalRequirements = new Map<string, lib.ModVersionRange>();
const candidateReleases = new Map<string, lib.ModInfo>();
const errors = new Map<string, lib.ModDependencyResolveErrors>();
const _modPortalReleases = new Map<string, ModPortalModType | null>();
async function fetchModReleases(modName: string) {
let releases = _modPortalReleases.get(modName);
if (releases === undefined) {
try {
releases = await lib.ModStore.fetchModReleases(modName);
} catch (error: any) {
if (!error.message.includes("404") && !error.message.includes("Not Found")) {
logger.error(`Error fetching mod from portal: ${error.message}`);
throw new lib.InternalServerError(`Dependency resolution failed: ${error.message}`);
} else {
releases = null;
}
}
}
_modPortalReleases.set(modName, releases);
return releases;
}
function selectModRelease(releases: ModPortalModType | null, versionRange: lib.ModVersionRange) {
if (!releases || !releases.releases) {
return null;
}
// Select the latest matching version for the mod pack's Factorio version
const release = releases.releases
.filter(info => (
versionRange.testVersion(info.version)
&& lib.normaliseMajorMinorVersion(
lib.normaliseSourceVersion(info.info_json.factorio_version)
) === factorioVersion
))
.reduce<ModPortalReleaseType | undefined>((max, cur) => (
max && lib.integerSourceVersion(max.version) > lib.integerSourceVersion(cur.version) ? max : cur
), undefined);
if (!release) {
return null;
}
// Create the mod info class from the selected
try {
return lib.ModInfo.fromJSON({
...release.info_json, // includes dependencies
sha1: release.sha1,
version: release.version,
name: releases.name,
author: releases.owner,
title: releases.title,
});
} catch {
// Can error if there are invalid dependencies
errors.set(releases.name, "invalidDependency");
return null;
}
}
while (searchQueue.length > 0) {
// Dequeue the next mod, skip if incompatible
const mod = searchQueue.shift()!;
if (mod.incompatible) {
errors.set(mod.name, "incompatible");
continue;
}
// Get the current version range (dependencies can be promoted to a stricter requirement)
const versionRange =
dependencyRequirements.get(mod.name)
?? recommendedRequirements.get(mod.name)
?? optionalRequirements.get(mod.name)
?? new lib.ModVersionRange();
if (mod.required) {
// Add to required, remove from recommended and optional
dependencyRequirements.set(mod.name, versionRange);
recommendedRequirements.delete(mod.name);
optionalRequirements.delete(mod.name);
} else if (mod.recommended) {
// If not required, add to recommended and remove from optional
if (!dependencyRequirements.has(mod.name)) {
recommendedRequirements.set(mod.name, versionRange);
optionalRequirements.delete(mod.name);
}
} else if (
!dependencyRequirements.has(mod.name)
&& !recommendedRequirements.has(mod.name)
) {
// If not required or recommended, add to optional
optionalRequirements.set(mod.name, versionRange);
}
// Update the version range if needed
if (mod.version) {
versionRange.combineVersion(mod.version);
if (!versionRange.valid) {
candidateReleases.delete(mod.name);
errors.set(mod.name, "unsatisfiable");
continue;
}
}
// Do not add dependencies for errors, skips, optionals, or valid candidates
const existingCandidate = candidateReleases.get(mod.name);
if (errors.has(mod.name) || skipSearch.has(mod.name) || optionalRequirements.has(mod.name) || (
existingCandidate && versionRange.testVersion(existingCandidate.version)
)) {
continue;
}
// Check if a local version fits the requirements
let candidate = localInfos
.filter(info => (
info.name === mod.name
&& info.factorioVersion === factorioVersion
&& versionRange.testVersion(info.version)
))
.reduce<lib.ModInfo | undefined>((max, cur) => (
max && max.integerVersion > cur.integerVersion ? max : cur
), undefined);
// Check if a mod poral version fits the requirements
if (!candidate || checkForUpdates) {
const releases = await fetchModReleases(mod.name);
const release = selectModRelease(releases, versionRange);
// We only select the mod portal release if it is more recent than the local candidate
if (release && (!candidate || release.integerVersion > candidate.integerVersion)) {
candidate = release;
}
}
// Queue the dependencies of the new candidate
if (candidate) {
candidateReleases.set(mod.name, candidate);
for (const dep of candidate.dependencies) {
searchQueue.push(dep);
}
} else {
candidateReleases.delete(mod.name);
skipSearch.add(mod.name);
}
}
// Add the not found dependencies as errors
for (const modName of dependencyRequirements.keys()) {
if (!candidateReleases.has(modName) && !errors.has(modName)) {
errors.set(modName, "notFound");
}
}
// Remove incompatible and unsatisfiable dependencies if they aren't required by others
for (const [modName, error] of errors) {
if (!dependencyRequirements.has(modName) && (error === "incompatible" || error === "unsatisfiable")) {
errors.delete(modName);
}
}
return new lib.ModDependencyResolveRequest.Response(
[...candidateReleases.values()], errors,
);
}
/**
* Download the mods required by plugins that are missing from the mod store
*
* Resolves for the Factorio version of the default mod pack. Dependencies
* of the required mods are downloaded too.
*/
async downloadRequiredMods() {
const required = this.pluginInfos.flatMap(pluginInfo => lib.pluginRequiredMods(pluginInfo));
const modPackId = this.config.get("controller.default_mod_pack_id");
const modPack = modPackId !== null ? this.modPacks.get(modPackId) : undefined;
if (!required.length || !modPack) {
return;
}
const factorioVersion = lib.normaliseMajorMinorVersion(modPack.factorioVersion);
const { dependencies, errors } = await this.resolveModDependencies(required, factorioVersion);
const builtInMods = new Set(lib.ModPack.getBuiltinModNames(factorioVersion));
for (const [name, error] of errors) {
if (!builtInMods.has(name)) {
logger.warn(`Unable to resolve mod ${name} required by plugins: ${error}`);
}
}
const toDownload = this.modStore.filterInstalled(dependencies.map(
info => ({ name: info.name, version: new lib.ModVersionEquality("=", info.normalisedVersion) })
), false);
if (!toDownload.length) {
return;
}
const names = toDownload.map(mod => `${mod.name} ${mod.version.version}`).join(", ");
logger.info(`Downloading mods required by plugins: ${names}`);
await this.downloadModsFromPortal(toDownload, factorioVersion);
}
modPacksUpdated(modPacks: lib.ModPack[]) {
this.subscriptions.broadcast(new lib.ModPackUpdatesEvent(modPacks));
this.hooks.modPacksUpdated.invoke(modPacks);
+33
View File
@@ -1032,6 +1032,39 @@ end`.replace(/\r?\n/g, " ");
}
await this.syncMods();
this.checkRequiredMods(this.activeModPack);
}
/**
* Check that the mod pack has the mods required by the loaded plugins
*
* @throws {lib.ConflictError} if a required mod is missing, disabled or the wrong version.
*/
checkRequiredMods(modPack: lib.ModPack) {
const problems = [];
for (const pluginInfo of this.loadedPlugins) {
const unmet = [];
for (const dependency of lib.pluginRequiredMods(pluginInfo)) {
const mod = modPack.mods.get(dependency.name);
if (!mod) {
unmet.push(`${dependency.spec} (missing)`);
} else if (!mod.enabled) {
unmet.push(`${dependency.spec} (disabled)`);
} else if (dependency.version && !dependency.version.testVersion(mod.version)) {
unmet.push(`${dependency.spec} (found ${mod.version})`);
}
}
if (unmet.length) {
problems.push(`Plugin ${pluginInfo.name} requires ${unmet.join(", ")}.`);
}
}
if (problems.length) {
throw new lib.ConflictError(
`Mod pack ${modPack.name} does not have the mods required by the loaded plugins. ` +
`${problems.join(" ")} ` +
"Add the mods to the mod pack or set <plugin>.load_plugin to false for this instance."
);
}
}
/**
+23
View File
@@ -9,6 +9,7 @@ import type { PermissionDefinition } from "./permissions.js";
import type { PlayerStats, Role } from "./data/index.js";
import type { SyncHook } from "./SyncHook.js";
import type { ErrorClass } from "./link/index.js";
import { ModDependency } from "./data/ModInfo.js";
export const PluginFeatureFlags = [
/** The plugin requires module code to be patched into the save */
@@ -41,6 +42,11 @@ export type PluginDeclaration = {
migrationEntrypoint?: string;
features?: (typeof PluginFeatureFlags)[number][];
/**
* Factorio mods the plugin needs in the instance's mod pack, as Factorio
* dependency strings like `"subspace_storage >= 2.3.0"`.
*/
requiredMods?: string[];
messages?: any[];
errors?: ErrorClass[];
@@ -65,6 +71,23 @@ export function pluginNeedsWebBuild(info: PluginDeclaration) {
);
}
/**
* Parse the requiredMods of a plugin
*
* A mod listed more than once must satisfy every entry, which gives a range.
*
* @throws Error if an entry is invalid or has a dependency prefix.
*/
export function pluginRequiredMods(pluginInfo: PluginDeclaration) {
return (pluginInfo.requiredMods ?? []).map(spec => {
const dependency = new ModDependency(spec);
if (dependency.type !== "required") {
throw new Error(`requiredMods entry "${spec}" can not have a dependency prefix`);
}
return dependency;
});
}
export type PluginNodeEnvInfo = PluginDeclaration & {
/**
* Path to the folder with the static files that should be hosted on the web
+6
View File
@@ -84,6 +84,12 @@ export async function loadPluginInfos(pluginList: Map<string, string>, skippedNp
);
}
try {
libPlugin.pluginRequiredMods(pluginInfo);
} catch (err: any) {
throw new libErrors.PluginError(pluginName, err);
}
// migrate: ignore incompatible old plugins
if (pluginInfo.messages && !(pluginInfo.messages instanceof Array)) {
logger.warn(`Ignoring incompatible pre alpha.14 plugin ${pluginName}`);
+4
View File
@@ -12,6 +12,10 @@ Run the following commands in the folder Clusterio is installed to:
Substitute clusteriocontroller with clusteriohost or clusterioctl if this a dedicate host or ctl installation respectively.
The plugin needs the [Subspace Storage mod](https://mods.factorio.com/mod/subspace_storage) in the mod pack of every instance it is loaded on.
The controller downloads it from the mod portal on start if the Factorio credentials are configured, but you have to add it to the mod packs yourself.
Instances with the plugin loaded refuse to start without it. Set `subspace_storage.load_plugin` to false on instances that should not use it.
## Controller Configuration
+1
View File
@@ -19,6 +19,7 @@ export const plugin: lib.PluginDeclaration = {
title: "Subspace Storage",
description: "Provides shared storage across instances for the Subspace Storage mod",
instanceEntrypoint: "dist/node/instance.js",
requiredMods: ["subspace_storage >= 1.99.0"],
instanceConfigFields: {
"subspace_storage.log_item_transfers": {
title: "Log Item Transfers",
+44
View File
@@ -305,6 +305,50 @@ describe("controller/src/Controller", function() {
await assert.rejects(Controller.loadJsonObject(path.join(dir, "invalid.json")), SyntaxError);
});
});
describe(".downloadRequiredMods()", function() {
let ctrl, resolveCalls, downloadCalls, resolved;
function modInfo(name, version) {
return lib.ModInfo.fromJSON({ name, version, factorio_version: "2.0" });
}
beforeEach(function() {
const config = new ControllerConfig("controller", { "controller.version": controllerVersion });
ctrl = new Controller({}, [
{ name: "foo", title: "Foo", requiredMods: ["foo_mod >= 1.0.0"] },
{ name: "bar", title: "Bar" },
], config);
const modPack = ModPack.fromJSON({ id: 7, name: "default", factorio_version: "2.0.10" });
ctrl.modPacks.set(modPack);
config.set("controller.default_mod_pack_id", 7);
resolveCalls = [];
downloadCalls = [];
resolved = [modInfo("foo_mod", "1.2.0"), modInfo("dep_mod", "0.1.0")];
ctrl.resolveModDependencies = async (mods, factorioVersion) => {
resolveCalls.push([mods.map(mod => mod.spec), factorioVersion]);
return new lib.ModDependencyResolveRequest.Response(resolved, new Map());
};
ctrl.downloadModsFromPortal = async (mods, factorioVersion) => {
downloadCalls.push([mods.map(mod => `${mod.name} ${mod.version}`), factorioVersion]);
};
});
it("should download required mods and their dependencies for the default mod pack", async function() {
await ctrl.downloadRequiredMods();
assert.deepEqual(resolveCalls, [[["foo_mod >= 1.0.0"], "2.0"]]);
assert.deepEqual(downloadCalls, [[["foo_mod = 1.2.0", "dep_mod = 0.1.0"], "2.0"]]);
});
it("should skip mods already in the mod store", async function() {
ctrl.modStore = new lib.ModStore("mods", new Map(resolved.map(info => [info.filename, info])));
await ctrl.downloadRequiredMods();
assert.deepEqual(downloadCalls, []);
});
it("should do nothing when no plugin requires mods", async function() {
ctrl.pluginInfos = [{ name: "bar", title: "Bar" }];
await ctrl.downloadRequiredMods();
assert.deepEqual(resolveCalls, []);
});
});
describe(".loggableHeaders()", function() {
it("should redact credentials and keep other headers", function() {
const headers = {
+43
View File
@@ -336,6 +336,49 @@ describe("class Instance", function() {
});
});
describe(".checkRequiredMods()", function() {
beforeEach(function() {
instance.loadedPlugins = new Set([
{ name: "foo", requiredMods: ["foo_mod", "bar_mod >= 1.1.0", "bar_mod < 2.0.0"] },
{ name: "bar" },
]);
});
function modPack(mods) {
return lib.ModPack.fromJSON({ name: "pack", mods });
}
it("should accept a mod pack with the required mods", function() {
instance.checkRequiredMods(modPack([
{ name: "foo_mod", enabled: true, version: "1.0.0" },
{ name: "bar_mod", enabled: true, version: "1.1.0" },
]));
});
it("should reject missing, disabled and out of range mods", function() {
const expected = (unmet) => new lib.ConflictError(
"Mod pack pack does not have the mods required by the loaded plugins. " +
`Plugin foo requires ${unmet}. ` +
"Add the mods to the mod pack or set <plugin>.load_plugin to false for this instance."
);
assert.throws(
() => instance.checkRequiredMods(modPack([{ name: "bar_mod", enabled: true, version: "1.0.0" }])),
expected("foo_mod (missing), bar_mod >= 1.1.0 (found 1.0.0)"),
);
assert.throws(
() => instance.checkRequiredMods(modPack([
{ name: "foo_mod", enabled: false, version: "1.0.0" },
{ name: "bar_mod", enabled: true, version: "2.0.0" },
])),
expected("foo_mod (disabled), bar_mod < 2.0.0 (found 2.0.0)"),
);
});
it("should ignore plugins that are not loaded", function() {
instance.loadedPlugins = new Set([{ name: "bar" }]);
instance.checkRequiredMods(modPack([]));
});
});
describe("save name checks", function() {
it("should reject a start save outside the saves directory", async function() {
await assert.rejects(
+19
View File
@@ -353,6 +353,22 @@ before(async function() {
sourceDir: "packages/host/lua/clusterio_lib",
outputDir: modsDir,
});
// Stand-in for the mod required by the subspace_storage plugin
const subspaceStorageDir = path.join("temp", "test", "subspace_storage");
await fs.rm(subspaceStorageDir, { force: true, recursive: true });
await fs.mkdir(subspaceStorageDir, { recursive: true });
await fs.writeFile(path.join(subspaceStorageDir, "info.json"), JSON.stringify({
name: "subspace_storage",
variants: [
{ version: "2.3.11", factorio_version: "1.1" },
{ version: "2.3.20", factorio_version: "2.0" },
{ version: "2.3.21", factorio_version: "2.1" },
],
title: "Subspace Storage test stub",
author: "Clusterio Team",
dependencies: ["base", "clusterio_lib"],
}));
await lib.build({ build: true, pack: true, sourceDir: subspaceStorageDir, outputDir: modsDir });
console.log("Setting Controller Config");
await execController("config create");
@@ -410,6 +426,9 @@ before(async function() {
const [major, minor] = lib.normaliseMajorMinorVersion(latestFactorioVersion).split(".");
testPack.mods.set("clusterio_lib", { name: "clusterio_lib", enabled: true, version: `2.1.${major}${minor}` });
testPack.mods.set(
"subspace_storage", { name: "subspace_storage", enabled: true, version: `2.3.${major}${minor}` }
);
await control.sendTo("controller", new lib.ModPackCreateRequest(testPack));
await control.sendTo(
+18
View File
@@ -24,4 +24,22 @@ describe("lib/plugin", function() {
}
});
});
describe("pluginRequiredMods()", function() {
it("should parse dependency strings", function() {
const mods = lib.pluginRequiredMods({
name: "foo", title: "Foo", requiredMods: ["bar", "baz >= 1.2.0", "baz < 2.0.0"],
});
assert.deepEqual(mods.map(mod => [mod.name, mod.version?.toString()]), [
["bar", undefined], ["baz", ">= 1.2.0"], ["baz", "< 2.0.0"],
]);
});
it("should return an empty list without requiredMods", function() {
assert.deepEqual(lib.pluginRequiredMods({ name: "foo", title: "Foo" }), []);
});
it("should reject dependency prefixes and invalid versions", function() {
for (const spec of ["? bar", "! bar", "~ bar", "bar >= 1..2"]) {
assert.throws(() => lib.pluginRequiredMods({ name: "foo", title: "Foo", requiredMods: [spec] }));
}
});
});
});