Add create-scenario command to clusteriohost

Creates a scenario directory with the Clusterio modules patched into it
so the modules can be used outside of Clusterio. The command reuses the
save patching by zipping the scenario, running patch() on it and
extracting the result. Defaults to the freeplay scenario from the
Factorio install in the host config and all plugins enabled there.

Module loading in Instance.prepareSave is moved to patch.loadModules so
the command and the instance share it, and findVersion is exported from
server.ts so the command can find the freeplay scenario.

Zipped scenarios were tried as an output form but Factorio does not
pick them up from the scenarios folder, so only directories are written.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Fable 5.1 committed 2026-09-10 00:16:29 +00:00
1 parent 7987a5d925
commit c419f3e9b2
10 files changed
+349 -41

No files matched your search

+2 -24
View File
@@ -10,7 +10,7 @@ const execAsync = util.promisify(exec);
import * as lib from "@clusterio/lib";
import { FactorioServer } from "./server";
import { SaveModule, patch } from "./patch";
import { loadModules, patch } from "./patch";
import { exportData } from "./export";
import type Host from "./Host";
import BaseInstancePlugin from "./BaseInstancePlugin";
@@ -951,29 +951,7 @@ end`.replace(/\r?\n/g, " ");
// Patch save with lua modules from plugins
this.logger.verbose("Patching save");
// Find plugin modules to patch in
let modules: Map<string, SaveModule> = new Map();
for (let plugin of this.plugins.values()) {
let module = await SaveModule.fromPlugin(plugin);
if (!module) {
continue;
}
modules.set(module.info.name, module);
}
// Find stand alone modules to load
// XXX for now only the included clusterio module is loaded
let modulesDirectory = path.join(__dirname, "..", "..", "..", "modules");
for (let entry of await fs.readdir(modulesDirectory, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (modules.has(entry.name)) {
throw new Error(`Module with name ${entry.name} already exists in a plugin`);
}
let module = await SaveModule.fromDirectory(path.join(modulesDirectory, entry.name));
modules.set(module.info.name, module);
}
}
let modules = await loadModules([...this.plugins.values()].map(plugin => plugin.info));
await patch(this.path("saves", saveName), [...modules.values()]);
return saveName;
}
+149
View File
@@ -0,0 +1,149 @@
// Implementation of the create-scenario command
import fs from "node:fs/promises";
import os from "node:os";
import JSZip from "jszip";
import path from "path";
import * as lib from "@clusterio/lib";
import { logger } from "@clusterio/lib";
import { loadModules, patch, SaveModule } from "./patch";
import { findVersion } from "./server";
/**
* Create a scenario patched with the given modules
*
* Runs the save patching on the scenario at scenarioPath and writes the
* result to the directory at outputPath. The scenario can be a directory,
* a zipped scenario or a save.
*
* @param scenarioPath - Path to the scenario to patch.
* @param outputPath - Directory to write the patched scenario to.
* @param modules - Description of the modules to patch.
*/
export async function createScenario(scenarioPath: string, outputPath: string, modules: SaveModule[]) {
if (await fs.access(outputPath).then(() => true, () => false)) {
throw new Error(`${outputPath} already exists`);
}
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-scenario-"));
try {
const tempPath = path.join(tempDir, "scenario.zip");
if ((await fs.stat(scenarioPath)).isDirectory()) {
await zipDirectory(scenarioPath, tempPath);
} else {
await fs.copyFile(scenarioPath, tempPath);
}
await patch(tempPath, modules);
await extractZip(tempPath, outputPath);
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
}
async function zipDirectory(dirPath: string, zipPath: string) {
const root = path.basename(path.resolve(dirPath));
const zip = new JSZip();
let dirs: [string, string][] = [[dirPath, root]];
while (dirs.length) {
let [dir, relativeDir] = dirs.pop()!;
for (let entry of await fs.readdir(dir, { withFileTypes: true })) {
let fsPath = path.join(dir, entry.name);
let relativePath = path.posix.join(relativeDir, entry.name);
if (entry.isFile()) {
zip.file(relativePath, await fs.readFile(fsPath));
} else if (entry.isDirectory()) {
dirs.push([fsPath, relativePath]);
}
}
}
await fs.writeFile(zipPath, await zip.generateAsync({ type: "nodebuffer" }));
}
async function extractZip(zipPath: string, dirPath: string) {
const zip = await JSZip.loadAsync(await fs.readFile(zipPath));
const root = lib.findRoot(zip);
for (let file of Object.values(zip.files)) {
if (file.dir || !file.name.startsWith(`${root}/`)) {
continue;
}
const fsPath = path.join(dirPath, file.name.slice(root.length + 1));
await fs.mkdir(path.dirname(fsPath), { recursive: true });
await fs.writeFile(fsPath, await file.async("nodebuffer"));
}
}
/**
* Yargs create-scenario command
*
* @param yargs - yargs command builder.
*/
export function createScenarioCommand(yargs: any) {
yargs
.positional("output", {
describe: "Directory to write the scenario to",
type: "string",
})
.option("scenario", {
nargs: 1,
describe: "Scenario directory, zipped scenario or save to patch, defaults to freeplay",
type: "string",
})
.option("factorio-version", {
nargs: 1,
describe: "Factorio version to take the freeplay scenario from",
default: "latest",
type: "string",
})
.option("plugins", {
describe: "Plugins to patch modules from, defaults to all plugins enabled in the host config",
type: "array",
})
;
}
/**
* Handle yargs create-scenario command
*
* @param args - yargs args object.
* @param hostConfig - Host config.
* @param pluginInfos - Plugins available to the host.
*/
export async function handleCreateScenarioCommand(
args: Record<string, unknown>,
hostConfig: lib.HostConfig,
pluginInfos: lib.PluginNodeEnvInfo[],
) {
let selected: lib.PluginNodeEnvInfo[];
if (args.plugins) {
selected = (args.plugins as string[]).map(name => {
const pluginInfo = pluginInfos.find(info => info.name === name);
if (!pluginInfo) {
throw new Error(`Plugin ${name} is not in the plugin list`);
}
return pluginInfo;
});
} else {
selected = pluginInfos.filter(
info => info.instanceEntrypoint && hostConfig.get(`${info.name}.load_plugin`)
);
}
let scenarioPath = args.scenario as string | undefined;
if (scenarioPath === undefined) {
const factorioDir = hostConfig.get("host.factorio_directory");
const version = args.factorioVersion as lib.TargetVersion;
if (!lib.isTargetVersion(version)) {
throw new Error(`Invalid Factorio version ${version}`);
}
const [dataDir] = await findVersion(factorioDir, version);
scenarioPath = path.join(dataDir, "base", "scenarios", "freeplay");
}
const modules = await loadModules(selected);
logger.info(`Patching ${scenarioPath} with modules ${[...modules.keys()].join(", ")}`);
await createScenario(scenarioPath, args.output as string, [...modules.values()]);
logger.info(`Created scenario ${args.output}`);
}
+43 -5
View File
@@ -91,7 +91,11 @@ export class SaveModule {
}
static async fromPlugin(plugin: BaseInstancePlugin) {
let pluginPackagePath = require.resolve(path.posix.join(plugin.info.requirePath, "package.json"));
return SaveModule.fromPluginInfo(plugin.info);
}
static async fromPluginInfo(info: lib.PluginNodeEnvInfo) {
let pluginPackagePath = require.resolve(path.posix.join(info.requirePath, "package.json"));
let moduleDirectory = path.join(path.dirname(pluginPackagePath), "module");
try {
await fs.access(moduleDirectory);
@@ -103,17 +107,17 @@ export class SaveModule {
let moduleJson;
try {
moduleJson = {
name: plugin.info.name,
version: plugin.info.version,
name: info.name,
version: info.version,
dependencies: { "clusterio": "*" },
...JSON.parse(await fs.readFile(moduleJsonPath, "utf8")),
};
} catch (err: any) {
throw new Error(`Loading module/module.json in plugin ${plugin.info.name} failed: ${err.message}`);
throw new Error(`Loading module/module.json in plugin ${info.name} failed: ${err.message}`);
}
if (!lib.ModuleInfo.validate(moduleJson)) {
throw new Error(
`module/module.json in plugin ${plugin.info.name} failed validation:\n` +
`module/module.json in plugin ${info.name} failed validation:\n` +
`${JSON.stringify(lib.ModuleInfo.validate.errors, null, "\t")}`
);
}
@@ -149,6 +153,40 @@ export class SaveModule {
}
}
/**
* Load the modules to patch into a save
*
* Collects the modules provided by the given plugins together with the
* modules bundled with the host package.
*
* @param pluginInfos - Plugins to load modules from.
* @returns Map of module name to module.
*/
export async function loadModules(pluginInfos: Iterable<lib.PluginNodeEnvInfo>) {
let modules: Map<string, SaveModule> = new Map();
for (let pluginInfo of pluginInfos) {
let module = await SaveModule.fromPluginInfo(pluginInfo);
if (!module) {
continue;
}
modules.set(module.info.name, module);
}
// Find stand alone modules to load
// XXX for now only the included clusterio module is loaded
let modulesDirectory = path.join(__dirname, "..", "..", "..", "modules");
for (let entry of await fs.readdir(modulesDirectory, { withFileTypes: true })) {
if (entry.isDirectory()) {
if (modules.has(entry.name)) {
throw new Error(`Module with name ${entry.name} already exists in a plugin`);
}
let module = await SaveModule.fromDirectory(path.join(modulesDirectory, entry.name));
modules.set(module.info.name, module);
}
}
return modules;
}
export class PatchInfo {
static currentVersion = 1;
+4 -3
View File
@@ -181,9 +181,11 @@ async function downloadAndExtractTar(url: string, targetDir: string) {
* Version to look for, supports the special value "latest" for the
* latest version available.
* @returns Array with path to data dir and version found.
* @internal
*/
async function findVersion(factorioDir: string, targetVersion: lib.TargetVersion): Promise<[string, lib.FullVersion]> {
export async function findVersion(
factorioDir: string,
targetVersion: lib.TargetVersion,
): Promise<[string, lib.FullVersion]> {
// Check if this is a direct installation dir
const directVersion = await getFactorioVersion(factorioDir);
if (directVersion !== null) {
@@ -1580,7 +1582,6 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
// For testing only
export const _getFactorioVersion = getFactorioVersion;
export const _versionOrder = versionOrder;
export const _findVersion = findVersion;
export const _listFactorioVersions = listFactorioVersions;
export const _downloadAndExtractZip = downloadAndExtractZip;
export const _downloadAndExtractTar = downloadAndExtractTar;