Reorganise packages/lib

Move the majority of the script files into a src directory to be
consistent with the organisation of the other packages.
This commit is contained in:
Hornwitser committed 2023-07-28 16:03:29 +02:00
1 parent bfe119eaa3
commit bc574ee1cb
48 files changed
+41 -41

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
"use strict";
/**
* Export manifest for a mod pack
*
* Tracks files stored on disk for data that extracted from Factorio using a
* given mod pack.
* @alias module:lib.ExportManifest
*/
class ExportManifest {
/**
* Mapping between known assets and their file names.
*
* Currently exported assets are
* - settings: JSON of mod settings prototypes.
* - prototypes: JSON of all game prototypes except settings.
* - item-spritesheet: PNG containing icons from the game.
* - item-metadata: JSON of Map entries describing icons in item-spritesheet
* - locale: JSON of flattened Map entries of en locale strings from the game.
* @type {Object<string, string>}
*/
assets = {};
constructor(assets) {
if (assets) { this.assets = assets; }
}
static jsonSchema = {
type: "object",
additionalProperties: false,
required: ["assets"],
properties: {
"assets": {
type: "object",
additionalProperties: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.assets);
}
}
module.exports = ExportManifest;
+235
View File
@@ -0,0 +1,235 @@
"use strict";
const fs = require("fs-extra");
const JSZip = require("jszip");
const path = require("path");
const libHash = require("../hash");
const libSchema = require("../schema");
const { findRoot } = require("../zip_ops");
const { integerModVersion, integerFactorioVersion, modVersionRegExp } = require("./version");
/**
* Info about a mod available on the controller.
*
* See https://wiki.factorio.com/Tutorial:Mod_structure#info.json for
* details of the invidiual fields sourced from info.json.
* @alias module:lib.ModInfo
*/
class ModInfo {
/**
* Internal name of this mod.
* This is the name of the zip file as well as the name that appears in
* info.json.
* @type {string}
*/
name = "";
/**
* Version of the mod.
* Sourced from info.json.
* @type {string}
*/
version = "";
/**
* Integer representation of the version
* @type {number}
*/
get integerVersion() {
return integerModVersion(this.version);
}
/**
* Display name of the mod.
* Sourced from info.json.
* @type {string}
*/
title = "";
/**
* Author of the mod.
* Sourced from info.json.
* @type {string}
*/
author = "";
/**
* Contact field for mod.
* Sourced from info.json.
* @type {string}
*/
contact = "";
/**
* Homepage of the mod.
* Sourced from info.json.
* @type {string}
*/
homepage = "";
/**
* Description of the mod.
* Sourced from info.json.
* @type {string}
*/
description = "";
/**
* Major version of Factorio this mod supports.
* Sourced from info.json.
* @type {string}
*/
factorioVersion = "0.12";
/**
* Integer representation of the factorioVersion
* @type {number}
*/
get integerFactorioVersion() {
return integerFactorioVersion(this.factorioVersion);
}
/**
* Dependiences for this mod.
* Sourced from info.json.
* @type {Array<string>}
*/
dependencies = ["base"];
/**
* Expected name of zip file containing this mod.
* @type {number}
*/
get filename() {
return `${this.name}_${this.version}.zip`;
}
/**
* Size of the mod in bytes
* @type {number}
*/
size = 0;
/**
* SHA1 hash of this mod
* @type {string=}
*/
sha1;
/**
* True if this mod has been deleted
* @type {boolean}
*/
isDeleted = false;
// Content of info.json found in mod files
static infoJsonSchema = {
type: "object",
required: ["name", "version", "title", "author"],
properties: {
"name": { type: "string" },
"version": { type: "string" },
"title": { type: "string" },
"author": { type: "string" },
"contact": { type: "string" },
"homepage": { type: "string" },
"description": { type: "string" },
"factorio_version": { type: "string" },
"dependencies": { type: "array", items: { type: "string" } },
},
};
static validateInfo = libSchema.compile(this.infoJsonSchema);
static jsonSchema = {
type: "object",
properties: {
...this.infoJsonSchema.properties,
"size": { type: "integer" },
"sha1": { type: "string" },
"is_deleted": { type: "boolean" },
},
};
static validate = libSchema.compile(this.jsonSchema);
static fromJSON(json) {
const modInfo = new this();
// info.json fields
if (json.name) { modInfo.name = json.name; }
if (json.version) { modInfo.version = json.version; }
if (json.title) { modInfo.title = json.title; }
if (json.author) { modInfo.author = json.author; }
if (json.contact) { modInfo.contact = json.contact; }
if (json.homepage) { modInfo.homepage = json.homepage; }
if (json.description) { modInfo.description = json.description; }
if (json.factorio_version) { modInfo.factorioVersion = json.factorio_version; }
if (json.dependencies) { modInfo.dependencies = json.dependencies; }
// Additional data
if (json.size) { modInfo.size = json.size; }
if (json.sha1) { modInfo.sha1 = json.sha1; }
if (json.is_deleted) { modInfo.isDeleted = json.is_deleted; }
return modInfo;
}
toJSON() {
let json = {
name: this.name,
version: this.version,
title: this.title,
author: this.author,
};
if (this.contact) { json.contact = this.contact; }
if (this.homepage) { json.homepage = this.homepage; }
if (this.description) { json.description = this.description; }
if (this.factorio_version !== "0.12") { json.factorio_version = this.factorioVersion; }
if (this.dependencies.length !== 1 || this.dependencies[0] !== "base") {
json.dependencies = this.dependencies;
}
if (this.size) { json.size = this.size; }
if (this.sha1) { json.sha1 = this.sha1; }
if (this.isDeleted) { json.is_deleted = this.isDeleted; }
return json;
}
static async fromModFile(modPath) {
let modInfo;
{
// XXX: JSZip needs the whole archive loaded in memory to work.
// This is clearly untenable and will be replaced later.
let zip = await JSZip.loadAsync(await fs.readFile(modPath));
let root = zip.folder(findRoot(zip));
let infoFile = root.file("info.json");
if (!infoFile) {
throw new Error("Mod contains no info.json file");
}
modInfo = JSON.parse(await infoFile.async("string"));
}
let valid = this.validateInfo(modInfo);
if (!valid) {
throw new Error("Mod's info.json is not valid");
}
if (!modVersionRegExp.test(modInfo.version)) {
throw new Error(`Mod's version (${modInfo.version}) is invalid`);
}
return this.fromJSON({
...modInfo,
size: (await fs.stat(modPath)).size,
sha1: await libHash.hashFile(modPath),
is_deleted: false,
});
}
}
module.exports = ModInfo;
+372
View File
@@ -0,0 +1,372 @@
"use strict";
const zlib = require("zlib");
const libSchema = require("../schema");
const ExportManifest = require("./ExportManifest");
const { integerFactorioVersion } = require("./version");
/**
* A setting for a mod.
* @typedef {object} module:lib.ModPack~ModSetting
* @property {boolean|number|string} value - Value of the given mod setting.
*/
const ModSettingJsonSchema = {
type: "object",
additionalProperties: false,
required: ["value"],
properties: {
"value": { type: ["boolean", "number", "string"] },
},
};
const ModSettingsJsonSchema = {
type: "object",
additionalProperties: ModSettingJsonSchema,
};
/**
* A mod in a mod pack
* @typedef {object} module:lib.ModPack~ModRecord
* @property {string} name - name of the mod.
* @property {boolean} enabled - if mod is to be loaded.
* @property {string} version - version of the mod.
* @property {string=} sha1 - SHA1 hash of the zip file.
*/
const ModRecordJsonSchema = {
type: "object",
required: ["name", "enabled", "version"],
properties: {
"name": { type: "string" },
"enabled": { type: "boolean" },
"version": { type: "string" },
"sha1": { type: "string" },
},
};
/**
* Factorio Mod Pack
*
* Tracks mods and settings for a collection of Factorio mods.
* @alias module:lib.ModPack
*/
class ModPack {
/**
* Id of this mod pack
* @type {number}
*/
id;
/**
* Name of this mod pack.
* @type {string}
*/
name = "";
/**
* Description for this modpcak.
* @type {string}
*/
description = "";
/**
* Version of Factorio this mod pack is for
* @type {string}
*/
factorioVersion = "1.1.0";
/**
* Integer representation of the factorioVersion
* @type {number}
*/
get integerFactorioVersion() {
return integerFactorioVersion(this.factorioVersion);
}
/**
* Mods included in this mod pack
* @type {Map<string, module:lib.ModPack~ModRecord>}
*/
mods = new Map();
/**
* Mod settings for this mod pack
* @type {Object<string, Map<string, module:lib.ModPack~ModSetting>>=}
*/
settings = {
"startup": new Map(),
"runtime-global": new Map(),
"runtime-per-user": new Map(),
};
/**
* Mapping to files containing exported data for this modpack
* @type {module:lib.ExportManifest|undefined}
*/
exportManifest;
/**
* True if this mod pack has been deleted from the list of mod packs.
* @type {boolean}
*/
isDeleted = false;
shallowClone() {
const clone = new this.constructor();
clone.id = this.id;
clone.name = this.name;
clone.description = this.description;
clone.factorioVersion = this.factorioVersion;
clone.mods = this.mods;
clone.settings = this.settings;
clone.exportManifest = this.exportManifest;
clone.isDeleted = this.isDeleted;
return clone;
}
static jsonSchema = {
type: "object",
additionalProperties: false,
required: ["name", "description", "factorio_version", "mods", "settings"],
properties: {
"id": { type: "integer" },
"name": { type: "string" },
"description": { type: "string" },
"factorio_version": { type: "string" },
"mods": {
type: "array",
items: ModRecordJsonSchema,
},
"settings": {
type: "object",
additionalProperties: false,
required: ["startup", "runtime-global", "runtime-per-user"],
properties: {
"startup": ModSettingsJsonSchema,
"runtime-global": ModSettingsJsonSchema,
"runtime-per-user": ModSettingsJsonSchema,
},
},
"export_manifest": ExportManifest.jsonSchema,
"is_deleted": { type: "boolean" },
},
};
static validate = libSchema.compile(this.jsonSchema);
static fromJSON(json) {
const modPack = new this();
if (json.id) {
modPack.id = json.id;
} else {
modPack.id = Math.random() * 2**31 | 0;
}
if (json.name) { modPack.name = json.name; }
if (json.description) { modPack.description = json.description; }
if (json.factorio_version) { modPack.factorioVersion = json.factorio_version; }
if (json.mods) { modPack.mods = new Map(json.mods.map(m => [m.name, m])); }
if (json.settings) {
modPack.settings = {
"startup": new Map(Object.entries(json.settings["startup"])),
"runtime-global": new Map(Object.entries(json.settings["runtime-global"])),
"runtime-per-user": new Map(Object.entries(json.settings["runtime-per-user"])),
};
}
if (json.export_manifest) { modPack.exportManifest = ExportManifest.fromJSON(json.export_manifest); }
if (json.is_deleted) { modPack.isDeleted = json.is_deleted; }
if (!modPack.mods.has("base")) {
modPack.mods.set("base", { name: "base", enabled: true, version: modPack.factorioVersion });
}
return modPack;
}
toJSON() {
let json = {
id: this.id,
name: this.name,
description: this.description,
factorio_version: this.factorioVersion,
mods: [...this.mods.values()],
settings: {
"startup": Object.fromEntries(this.settings["startup"]),
"runtime-global": Object.fromEntries(this.settings["runtime-global"]),
"runtime-per-user": Object.fromEntries(this.settings["runtime-per-user"]),
},
};
if (this.exportManifest) { json.export_manifest = this.exportManifest; }
if (this.isDeleted) { json.is_deleted = this.isDeleted; }
return json;
}
toModPackString() {
const json = this.toJSON();
delete json.id;
delete json.export_manifest;
// eslint-disable-next-line node/no-sync
let buf = zlib.deflateSync(JSON.stringify(json));
return buf.toString("base64");
}
static fromModPackString(modPackString) {
let buf = Buffer.from(modPackString, "base64");
try {
// eslint-disable-next-line node/no-sync
buf = zlib.inflateSync(buf);
} catch (err) {
if (err.code.startsWith("Z_")) {
throw new Error("Malformed mod pack string: zlib inflate failed");
}
}
let json;
try {
json = JSON.parse(buf);
} catch (err) {
throw new Error(`Malformed mod pack string: ${err.message}`);
}
if (!this.validate(json)) {
throw new Error("Malformed mod pack string: Schema validation failed");
}
return this.fromJSON(json);
}
toModSettingsDat() {
function uint8Byte(int) {
return Buffer.from(Uint8Array.from([int]).buffer);
}
function int16Bytes(int) {
return Buffer.from(Int16Array.from([int]).buffer);
}
function uint32Bytes(int) {
return Buffer.from(Uint32Array.from([int]).buffer);
}
function uint32SpaceOptimizedBytes(int) {
if (0 <= int && int < 0xff) {
return uint8Byte(int);
}
return Buffer.concat([
uint8Byte(0xff),
uint32Bytes(int),
]);
}
function doubleBytes(double) {
return Buffer.from(Float64Array.from([double]).buffer);
}
function stringBytes(str) {
const buf = Buffer.from(str, "utf8");
return Buffer.concat([
uint32SpaceOptimizedBytes(buf.length),
buf,
]);
}
function immutableStringBytes(str) {
if (str === undefined) {
return uint8Byte(1); // empty
}
return Buffer.concat([
uint8Byte(0), // empty
stringBytes(str),
]);
}
function versionBytes(version) {
const [main, major, minor] = version.split(".").map(n => Number.parseInt(n, 10));
return Buffer.concat([
int16Bytes(main),
int16Bytes(major),
int16Bytes(minor),
Buffer.alloc(2), // developer
Buffer.alloc(1), // reserved byte
]);
}
function propertyTreeListBytes(entries) {
const sizeBytes = uint32Bytes(entries.length);
const itemBytes = entries.flatMap(([key, item]) => [
immutableStringBytes(key),
// eslint-disable-next-line no-use-before-define
propertyTreeBytes(item),
]);
return Buffer.concat([
sizeBytes,
...itemBytes,
]);
}
function propertyTreeBytes(element) {
let type;
let dataBytes;
if (typeof element === null) {
type = 1;
dataBytes = Buffer.alloc(0);
} else if (typeof element === "boolean") {
type = 1;
dataBytes = uint8Byte(element);
} else if (typeof element === "number") {
type = 2;
dataBytes = doubleBytes(element);
} else if (typeof element === "string") {
type = 3;
dataBytes = immutableStringBytes(element);
} else if (element instanceof Array) {
type = 4;
dataBytes = propertyTreeListBytes(element.map(item => [undefined, item]));
} else if (typeof element === "object") {
type = 5;
dataBytes = propertyTreeListBytes(Object.entries(element));
} else {
throw new Error("Bad element passed to propertyTreeBytes");
}
return Buffer.concat([
uint8Byte(type),
Buffer.alloc(1), // anyTypeFlag
dataBytes,
]);
}
return Buffer.concat([
versionBytes(this.factorioVersion),
propertyTreeBytes(this.toJSON().settings),
]);
}
/**
* Fill in missing settings with their default values
*
* Uses the provided setting prototypes to add any missing mod settings
* in the mod pack with the default value from the prototype.
*
* @param {Object<string, object>} settingPrototypes -
* Setting prototypes exported from the game.
* @param {Logger} logger - Logger used to report warnings on.
*/
fillDefaultSettings(settingPrototypes, logger) {
const knownTypes = ["bool-setting", "int-setting", "double-setting", "string-setting"];
let prototypes = Object.entries(settingPrototypes)
.filter(([type, _]) => knownTypes.includes(type))
.flatMap(([_, settings]) => Object.values(settings))
;
for (let prototype of prototypes) {
if (!["startup", "runtime-global", "runtime-per-user"].includes(prototype.setting_type)) {
logger.warn(`Ignoring ${prototype.name} with unknown setting_type ${prototype.setting_type}`);
continue;
}
if (prototype.default_value === undefined) {
logger.warn(`Ignoring ${prototype.name} with missing default_value`);
continue;
}
if (this.settings[prototype.setting_type].get(prototype.name)) {
continue;
}
this.settings[prototype.setting_type].set(prototype.name, { value: prototype.default_value });
}
}
}
module.exports = ModPack;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
function jsonArray(ItemClass) {
return {
jsonSchema: {
type: "array",
items: ItemClass.jsonSchema,
},
fromJSON(json) {
return json.map(i => ItemClass.fromJSON(i));
},
};
}
function jsonPrimitive(type) {
return {
jsonSchema: { type },
fromJSON(json) {
return json;
},
};
}
module.exports = {
JsonBoolean: jsonPrimitive("boolean"),
JsonNumber: jsonPrimitive("number"),
JsonString: jsonPrimitive("string"),
jsonArray,
jsonPrimitive,
};
+31
View File
@@ -0,0 +1,31 @@
/**
* Shared data types used in Clusterio
* @module lib/data
* @author Hornwitser
*/
"use strict";
const ExportManifest = require("./ExportManifest");
const ModInfo = require("./ModInfo");
const ModPack = require("./ModPack");
const composites = require("./composites");
const messagesCore = require("./messages_core");
const messagesController = require("./messages_controller");
const messagesHost = require("./messages_host");
const messagesInstance = require("./messages_instance");
const messagesMod = require("./messages_mod");
const messagesUser = require("./messages_user");
const version = require("./version");
module.exports = {
ExportManifest,
ModInfo,
ModPack,
...composites,
...messagesCore,
...messagesController,
...messagesHost,
...messagesInstance,
...messagesMod,
...messagesUser,
...version,
};
@@ -0,0 +1,384 @@
"use strict";
const { JsonString } = require("./composites");
// TODO: remove after config refactor
/** @memberof module:lib */
class RawConfig {
/** @type {object} */
serializedConfig;
constructor(serializedConfig) {
this.serializedConfig = serializedConfig;
}
static jsonSchema = {
type: "object",
required: ["serializedConfig"],
properties: {
"serializedConfig": { type: "object" },
},
};
static fromJSON(json) {
return new this(json.serializedConfig);
}
}
/* @memberof module:lib */
class ControllerConfigGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.get_config";
static Response = RawConfig;
}
/** @memberof module:lib */
class ControllerConfigSetFieldRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.update_config";
/** @type {string} */
field;
/** @type {string} */
value;
constructor(field, value) {
this.field = field;
this.value = value;
}
static jsonSchema = {
type: "object",
required: ["field", "value"],
properties: {
"field": { type: "string" },
"value": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.field, json.value);
}
}
/* @memberof module:lib */
class ControllerConfigSetPropRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.controller.update_config";
/** @type {string} */
field;
/** @type {string} */
prop;
/** @type {undefined} */
value;
constructor(field, prop, value) {
this.field = field;
this.prop = prop;
if (value) { this.value = value; }
}
static jsonSchema = {
type: "object",
required: ["field", "prop"],
properties: {
field: { type: "string" },
prop: { type: "string" },
value: {},
},
};
static fromJSON(json) {
return new this(json.field, json.prop, json.value);
}
}
/* @memberof module:lib */
class HostGenerateTokenRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.generate_token";
/** @type {?number} */
hostId;
constructor(hostId) {
this.hostId = hostId;
}
static jsonSchema = {
type: "object",
required: ["hostId"],
properties: {
hostId: { type: ["integer", "null"] },
},
};
static fromJSON(json) {
return new this(json.hostId);
}
static Response = JsonString;
}
/** @memberof module:lib */
class HostConfigCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.create_config";
/** @type {?number} */
id;
/** @type {?string} */
name;
/** @type {boolean} */
generateToken;
constructor(id, name, generateToken) {
this.id = id;
this.name = name;
this.generateToken = generateToken;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "generateToken"],
properties: {
"id": { type: ["integer", "null"] },
"name": { type: ["string", "null"] },
"generateToken": { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.generateToken);
}
static Response = RawConfig;
}
/* @memberof module:lib */
class LogSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.log.follow";
/** @type {boolean} */
all;
/** @type {boolean} */
controller;
/** @type {array} */
hostIds;
/** @type {array} */
instanceIds;
/** @type {?string} */
maxLevel;
constructor(all, controller, hostIds, instanceIds, maxLevel) {
this.all = all;
this.controller = controller;
this.hostIds = hostIds;
this.instanceIds = instanceIds;
this.maxLevel = maxLevel;
}
static jsonSchema = {
type: "object",
required: ["all", "controller", "hostIds", "instanceIds", "maxLevel"],
properties: {
all: { type: "boolean" },
controller: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
instanceIds: {
type: "array",
items: { type: "integer" },
},
maxLevel: { type: ["string", "null"] },
},
};
static fromJSON(json) {
return new this(json.all, json.controller, json.hostIds, json.instanceIds, json.maxLevel);
}
}
/* @memberof module:lib */
class LogQueryRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.log.query";
/** @type {boolean} */
all;
/** @type {boolean} */
controller;
/** @type {Array<number>} */
hostIds;
/** @type {Array<number>} */
instanceIds;
/** @type {?string} */
maxLevel;
/** @type {integer} */
limit;
/** @type {undefined} */
order;
constructor(all, controller, hostIds, instanceIds, maxLevel, limit, order) {
this.all = all;
this.controller = controller;
this.hostIds = hostIds;
this.instanceIds = instanceIds;
this.maxLevel = maxLevel;
this.limit = limit;
this.order = order;
}
static jsonSchema = {
type: "object",
required: ["all", "controller", "hostIds", "instanceIds", "maxLevel", "limit", "order"],
properties: {
all: { type: "boolean" },
controller: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
instanceIds: {
type: "array",
items: { type: "integer" },
},
maxLevel: { type: ["string", "null"] },
limit: { type: "integer" },
order: {
enum: ["asc", "desc"],
},
},
};
static fromJSON(json) {
return new this(
json.all, json.controller, json.hostIds, json.instanceIds, json.maxLevel, json.limit, json.order
);
}
}
LogQueryRequest.Response = class Response {
/** @type {Array<object>} */
log;
constructor(log) {
this.log = log;
}
static jsonSchema = {
type: "object",
required: ["log"],
properties: {
log: {
type: "array",
items: { type: "object" },
},
},
};
static fromJSON(json) {
return new this(json.log);
}
};
/** @memberof module:lib */
class LogMessageEvent {
static type = "event";
static src = ["host", "controller"];
static dst = ["controller", "control"];
/** @type {object} */
info;
constructor(info) {
this.info = info;
}
static jsonSchema = {
type: "object",
required: ["info"],
properties: {
"info": {
type: "object",
required: ["level", "message"],
properties: {
"level": { type: "string" },
"message": { type: "string" },
},
},
},
};
static fromJSON(json) {
return new this(json.info);
}
}
/* @memberof module:lib */
class DebugDumpWsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.debug.dump_ws";
}
/* @memberof module:lib */
class DebugWsMessageEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {string} */
direction;
/** @type {string} */
content;
constructor(direction, content) {
this.direction = direction;
this.content = content;
}
static jsonSchema = {
type: "object",
required: ["direction", "content"],
properties: {
direction: { type: "string" },
content: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.direction, json.content);
}
}
module.exports = {
RawConfig,
ControllerConfigGetRequest,
ControllerConfigSetFieldRequest,
ControllerConfigSetPropRequest,
HostGenerateTokenRequest,
HostConfigCreateRequest,
LogSetSubscriptionsRequest,
LogQueryRequest,
LogMessageEvent,
DebugDumpWsRequest,
DebugWsMessageEvent,
};
+889
View File
@@ -0,0 +1,889 @@
"use strict";
const libSchema = require("../schema");
/** @memberof module:lib */
class Address {
/** Controller address */
static controller = 0;
/** Instance address */
static instance = 1;
/** Host address */
static host = 2;
/** Control address */
static control = 3;
/** Broadcast */
static broadcast = 4;
/** @type {number} */
type;
/** @type {string} */
id;
/** @type {string|undefined} */
requestId;
constructor(type, id, requestId) {
if (typeof type !== "number") {
throw Error(`Invalid type ${type}`);
}
this.type = type;
this.id = id;
this.requestId = requestId;
}
/**
* Convert from convenient shorthand notation to address.
*
* Supported notations and their corresponding address:
* - `"controller"`: new Address(Address.controller, 0)
* - `{ hostId: id }`: new Address(Address.host, id)
* - `{ instanceId: id }`: new Address(Address.instance, id)
* - `{ controlId: id }`: new Address(Address.control, id)
* `"allHosts"`: new Address(Address.broadcast, Address.host)
* `"allInstances"`: new Address(Address.broadcast, Address.instance)
* `"allControls"`: new Address(Address.broadcast, Address.control)
* @param {module:lib.Address|string|object} shorthand -
* Shorthand to translate with.
* @returns {module:lib.Address} Translated address.
*/
static fromShorthand(shorthand) {
if (shorthand instanceof Address) { return shorthand; }
if (shorthand === "controller") { return new Address(Address.controller, 0); }
if (shorthand === "allHosts") { return new Address(Address.broadcast, Address.host); }
if (shorthand === "allInstances") { return new Address(Address.broadcast, Address.instance); }
if (shorthand === "allControls") { return new Address(Address.broadcast, Address.control); }
let entries = Object.entries(shorthand);
if (entries.length === 1) {
let [name, value] = entries[0];
if (name === "hostId") { return new Address(Address.host, value); }
if (name === "instanceId") { return new Address(Address.instance, value); }
if (name === "controlId") { return new Address(Address.control, value); }
}
throw Error("Unrecognized shorthand");
}
static jsonSchema = {
type: "array",
minItems: 2,
items: [
{ type: "integer", minimum: 0, maximum: 4 },
{ type: "integer" },
{ type: "integer" },
],
};
static fromJSON(json) {
return new this(json[0], json[1], json[2]);
}
toJSON() {
if (this.requestId !== undefined) {
return [this.type, this.id, this.requestId];
}
return [this.type, this.id];
}
toString() {
const typeMap = ["controller", "instance", "host", "control"];
const type = typeMap[this.type] || this.type;
if (this.type === Address.broadcast) {
return `[Address ${type}:${typeMap[this.id] || this.id}]`;
}
if (this.requestId === undefined) {
return `[Address ${type}:${this.id}]`;
}
return `[Address ${type}:${this.id}:${this.requestId}]`;
}
/**
* Returns a string suitable for indexing the address in a Map
* @returns {string} unique string for this address
*/
index() {
return `${this.type}:${this.id}:${this.requestId}`;
}
/**
* Returns true if this address targets the given destination
* @param {module:lib.Address} dst - Destination to check
* @returns {boolean} true if this address is addressed to the given destination
*/
addressedTo(dst) {
if (this.type !== Address.broadcast) {
return (
this.type === dst.type
&& this.id === dst.id
);
}
return dst.type !== Address.broadcast && this.id === dst.type;
}
equals(other) {
return (
this.type === other.type
&& this.id === other.id
&& this.requestId === other.requestId
);
}
}
/** @memberof module:lib */
class Message {
/** @type {string} */
type;
constructor(type) {
this.type = type;
}
static jsonSchema;
static validate;
static fromJSON(json) {
/* eslint-disable no-use-before-define */
if (json.type === "hello") { return MessageHello.fromJSON(json); }
if (json.type === "registerHost") { return MessageRegisterHost.fromJSON(json); }
if (json.type === "registerControl") { return MessageRegisterControl.fromJSON(json); }
if (json.type === "ready") { return MessageReady.fromJSON(json); }
if (json.type === "resume") { return MessageResume.fromJSON(json); }
if (json.type === "continue") { return MessageContinue.fromJSON(json); }
if (json.type === "invalidate") { return MessageInvalidate.fromJSON(json); }
if (json.type === "heartbeat") { return MessageHeartbeat.fromJSON(json); }
if (json.type === "request") { return MessageRequest.fromJSON(json); }
if (json.type === "response") { return MessageResponse.fromJSON(json); }
if (json.type === "responseError") { return MessageResponseError.fromJSON(json); }
if (json.type === "event") { return MessageEvent.fromJSON(json); }
if (json.type === "disconnect") { return MessageDisconnect.fromJSON(json); }
/* eslint-enable no-use-before-define */
throw new Error(`Unrecognized message type ${json.type}`);
}
}
/** @memberof module:lib */
class HelloData {
/** @type {string} */
version;
/** @type {object} */
plugins;
constructor(version, plugins) {
this.version = version;
this.plugins = plugins;
}
static jsonSchema = {
type: "object",
required: ["version", "plugins"],
properties: {
"version": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.version, json.plugins);
}
}
/** @memberof module:lib */
class MessageHello extends Message {
/** @type {module:lib.HelloData} */
data;
constructor(data) {
super("hello");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "data"],
properties: {
"type": { const: "hello" },
"data": HelloData.jsonSchema,
},
};
static fromJSON(json) {
return new this(HelloData.fromJSON(json.data));
}
};
/** @memberof module:lib */
class RegisterHostData {
/** @type {string} */
token;
/** @type {string} */
agent;
/** @type {string} */
version;
/** @type {string} */
name;
/** @type {string} */
id;
/** @type {string|undefined} */
publicAddress;
/** @type {Object<string, string>} */
plugins;
constructor(token, agent, version, name, id, publicAddress, plugins) {
this.token = token;
this.agent = agent;
this.version = version;
this.name = name;
this.id = id;
this.publicAddress = publicAddress;
this.plugins = plugins;
}
static jsonSchema = {
type: "object",
required: ["token", "agent", "version", "name", "id", "plugins"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
"name": { type: "string" },
"id": { type: "integer" },
"publicAddress": { type: "string" },
"plugins": {
type: "object",
additionalProperties: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.token, json.agent, json.version, json.name, json.id, json.publicAddress, json.plugins);
}
}
/** @memberof module:lib */
class MessageRegisterHost extends Message {
/** @type {module:lib.RegisterHostData} */
data;
constructor(data) {
super("registerHost");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "data"],
properties: {
"type": { const: "registerHost" },
"data": RegisterHostData.jsonSchema,
},
};
static fromJSON(json) {
return new this(RegisterHostData.fromJSON(json.data));
}
};
/** @memberof module:lib */
class RegisterControlData {
/** @type {string} */
token;
/** @type {string} */
agent;
/** @type {string} */
version;
constructor(token, agent, version) {
this.token = token;
this.agent = agent;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["token", "agent", "version"],
properties: {
"token": { type: "string" },
"agent": { type: "string" },
"version": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.token, json.agent, json.version);
}
}
/** @memberof module:lib */
class MessageRegisterControl extends Message {
/** @type {module:lib.RegisterControlData} */
data;
constructor(data) {
super("registerControl");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "registerControl" },
"data": RegisterControlData.jsonSchema,
},
};
static fromJSON(json) {
return new this(RegisterControlData.fromJSON(json.data));
}
};
/** @memberof module:lib */
class AccountDetails {
/** @type {string} */
name;
/** @type {Array} */
roles;
constructor(name, roles) {
this.name = name;
this.roles = roles;
}
static jsonSchema = {
type: "object",
required: ["name", "roles"],
properties: {
"name": { type: "string" },
"roles": {
type: "array",
items: {
type: "object",
required: ["name", "id", "permissions"],
properties: {
"name": { type: "string" },
"id": { type: "integer" },
"permissions": {
type: "array",
items: { type: "string" },
},
},
},
},
},
};
static fromJSON(json) {
return new this(json.name, json.roles);
}
}
/** @memberof module:lib */
class ReadyData {
/** @type {module:lib.Address} */
src;
/** @type {string} */
sessionToken;
/** @type {number} */
sessionTimeout;
/** @type {number} */
heartbeatInterval;
/** @type {AccountDetails|undefined} */
account;
constructor(src, sessionToken, sessionTimeout, heartbeatInterval, account) {
this.src = src;
this.sessionToken = sessionToken;
this.sessionTimeout = sessionTimeout;
this.heartbeatInterval = heartbeatInterval;
if (account) { this.account = account; }
}
static jsonSchema = {
type: "object",
required: ["src", "sessionToken", "sessionTimeout", "heartbeatInterval"],
properties: {
"src": Address.jsonSchema,
"sessionToken": { type: "string" },
"sessionTimeout": { type: "number" },
"heartbeatInterval": { type: "number" },
"account": AccountDetails.jsonSchema,
},
};
static fromJSON(json) {
let account;
if (json.account) { account = AccountDetails.fromJSON(json.account); }
return new this(
Address.fromJSON(json.src),
json.sessionToken,
json.sessionTimeout,
json.heartbeatInterval,
account
);
}
}
/** @memberof module:lib */
class MessageReady extends Message {
/** @type {module:lib.ReadyData} */
data;
constructor(data) {
super("ready");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "ready" },
"data": ReadyData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ReadyData.fromJSON(json.data));
}
}
/** @memberof module:lib */
class ResumeData {
/** @type {string} */
sessionToken;
/** @type {integer|undefined} */
lastSeq;
constructor(sessionToken, lastSeq) {
this.sessionToken = sessionToken;
if (lastSeq !== undefined) { this.lastSeq = lastSeq; }
}
static jsonSchema = {
type: "object",
required: ["sessionToken"],
properties: {
"sessionToken": { type: "string" },
"lastSeq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.sessionToken, json.lastSeq);
}
}
/** @memberof module:lib */
class MessageResume extends Message {
/** @type {module:lib.ResumeData} */
data;
constructor(data) {
super("resume");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "resume" },
"data": ResumeData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ResumeData.fromJSON(json.data));
}
}
/** @memberof module:lib */
class ContinueData {
/** @type {number} */
sessionTimeout;
/** @type {number} */
heartbeatInterval;
/** @type {integer|undefined} */
lastSeq;
constructor(sessionTimeout, heartbeatInterval, lastSeq) {
this.sessionTimeout = sessionTimeout;
this.heartbeatInterval = heartbeatInterval;
if (lastSeq !== undefined) { this.lastSeq = lastSeq; }
}
static jsonSchema = {
type: "object",
required: ["sessionTimeout", "heartbeatInterval"],
properties: {
"sessionTimeout": { type: "number" },
"heartbeatInterval": { type: "number" },
"lastSeq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.sessionTimeout, json.heartbeatInterval, json.lastSeq);
}
}
/** @memberof module:lib */
class MessageContinue extends Message {
/** @type {module:lib.ContinueData} */
data;
constructor(data) {
super("continue");
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["data"],
properties: {
"type": { const: "continue" },
"data": ContinueData.jsonSchema,
},
};
static fromJSON(json) {
return new this(ContinueData.fromJSON(json.data));
}
}
/** @memberof module:lib */
class MessageInvalidate extends Message {
constructor() {
super("invalidate");
}
static jsonSchema = {
type: "object",
properties: {
"type": { const: "invalidate" },
},
};
static fromJSON(json) {
return new this();
}
}
/** @memberof module:lib */
class MessageHeartbeat extends Message {
/** @type {integer|undefined} */
seq;
constructor(seq) {
super("heartbeat");
this.seq = seq;
}
static jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { const: "heartbeat" },
"seq": { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.seq);
}
}
/** @memberof module:lib */
class MessageRequest extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {string} */
name;
/** @type {*} */
data;
constructor(seq, src, dst, name, data) {
super("request");
this.seq = seq;
this.src = src;
this.dst = dst;
this.name = name;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "name"],
properties: {
"type": { const: "request" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"name": { type: "string" },
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.name,
json.data,
);
}
};
/** @memberof module:lib */
class MessageResponse extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {*} */
data;
constructor(seq, src, dst, data) {
super("response");
this.seq = seq;
this.src = src;
this.dst = dst;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst"],
properties: {
"type": { const: "response" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.data,
);
}
};
/** @memberof module:lib */
class ResponseError {
/** @type {string} */
message;
/** @type {string|undefined} */
code;
/** @type {string|undefined} */
stack;
constructor(message, code, stack) {
this.message = message;
if (code) { this.code = code; }
if (stack) { this.stack = stack; }
}
static jsonSchema = {
type: "object",
required: ["message"],
properties: {
"message": { type: "string" },
"code": { type: "string" },
"stack": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.message, json.code, json.stack);
}
}
/** @memberof module:lib */
class MessageResponseError extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {module:lib.ResponseError} */
data;
constructor(seq, src, dst, data) {
super("responseError");
this.seq = seq;
this.src = src;
this.dst = dst;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "data"],
properties: {
"type": { const: "responseError" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"data": ResponseError.jsonSchema,
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
ResponseError.fromJSON(json.data),
);
}
};
/** @memberof module:lib */
class MessageEvent extends Message {
/** @type {number} */
seq;
/** @type {Address} */
src;
/** @type {Address} */
dst;
/** @type {string} */
name;
/** @type {*} */
data;
constructor(seq, src, dst, name, data) {
super("event");
this.seq = seq;
this.src = src;
this.dst = dst;
this.name = name;
this.data = data;
}
static jsonSchema = {
type: "object",
required: ["type", "seq", "src", "dst", "name"],
properties: {
"type": { const: "event" },
"seq": { type: "integer" },
"src": Address.jsonSchema,
"dst": Address.jsonSchema,
"name": { type: "string" },
"data": {},
},
};
static fromJSON(json) {
return new this(
json.seq,
Address.fromJSON(json.src),
Address.fromJSON(json.dst),
json.name,
json.data,
);
}
};
/** @memberof module:lib */
class MessageDisconnect extends Message {
/** @type {string} */
data;
constructor(stage) {
super("disconnect");
this.data = stage;
}
static jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { const: "disconnect" },
"data": { enum: ["prepare", "ready"] },
},
};
static fromJSON(json) {
return new this(json.data);
}
};
Message.jsonSchema = {
type: "object",
required: ["type"],
properties: {
"type": { enum: [
"hello", "registerHost", "registerControl", "ready", "resume", "continue", "invalidate",
"heartbeat", "request", "response", "responseError", "event", "disconnect",
] },
},
oneOf: [
MessageHello.jsonSchema,
MessageRegisterHost.jsonSchema,
MessageRegisterControl.jsonSchema,
MessageReady.jsonSchema,
MessageResume.jsonSchema,
MessageContinue.jsonSchema,
MessageInvalidate.jsonSchema,
MessageHeartbeat.jsonSchema,
MessageRequest.jsonSchema,
MessageResponse.jsonSchema,
MessageResponseError.jsonSchema,
MessageEvent.jsonSchema,
MessageDisconnect.jsonSchema,
],
};
Message.validate = libSchema.compile(Message.jsonSchema);
/** @memberof module:lib */
class PingRequest {
static type = "request";
static src = ["controller", "host", "control"];
static dst = ["controller", "host", "control"];
static permission = null;
}
module.exports = {
Message,
HelloData,
MessageHello,
RegisterHostData,
MessageRegisterHost,
RegisterControlData,
MessageRegisterControl,
AccountDetails,
ReadyData,
MessageReady,
ResumeData,
MessageResume,
ContinueData,
MessageContinue,
MessageInvalidate,
MessageHeartbeat,
Address,
MessageRequest,
MessageResponse,
ResponseError,
MessageResponseError,
MessageEvent,
MessageDisconnect,
PingRequest,
};
+243
View File
@@ -0,0 +1,243 @@
"use strict";
const { jsonArray } = require("./composites");
/** @memberof module:lib */
class HostDetails {
/** @type {string} */
agent;
/** @type {string} */
version;
/** @type {string} */
name;
/** @type {number} */
id;
/** @type {boolean} */
connected;
/** @type {string|undefined} */
publicAddress;
constructor(agent, version, name, id, connected, publicAddress) {
this.agent = agent;
this.version = version;
this.name = name;
this.id = id;
this.connected = connected;
if (publicAddress !== undefined) { this.publicAddress = publicAddress; }
}
static jsonSchema = {
type: "object",
required: ["agent", "version", "name", "id", "connected"],
properties: {
"agent": { type: "string" },
"version": { type: "string" },
"name": { type: "string" },
"id": { type: "integer" },
"connected": { type: "boolean" },
"publicAddress": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.agent, json.version, json.name, json.id, json.connected, json.publicAddress);
}
}
/** @memberof module:lib */
class HostListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.list";
static Response = jsonArray(HostDetails);
}
/* @memberof module:lib */
class HostSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.host.subscribe";
/** @type {boolean} */
all;
/** @type {Array<number>} */
hostIds;
constructor(all, hostIds) {
this.all = all;
this.hostIds = hostIds;
}
static jsonSchema = {
type: "object",
required: ["all", "hostIds"],
properties: {
all: { type: "boolean" },
hostIds: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.hostIds);
}
}
/* @memberof module:lib */
class HostUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib.HostDetails} */
update;
constructor(update) {
this.update = update;
}
static jsonSchema = {
type: "object",
required: ["update"],
properties: {
update: HostDetails.jsonSchema,
},
};
static fromJSON(json) {
return new this(HostDetails.fromJSON(json.update));
}
}
/** @memberof module:lib */
class HostMetricsRequest {
static type = "request";
static src = "controller";
static dst = "host";
}
HostMetricsRequest.Response = class Response { // TODO: Use JSON class pattern in Prometheus
/** @type {array} */
results;
constructor(results) {
this.results = results;
}
static jsonSchema = {
type: "object",
required: ["results"],
properties: {
"results": {
type: "array",
},
},
};
static fromJSON(json) {
return new this(json.results);
}
};
/** @memberof module:lib */
class ControllerConnectionEvent {
static type = "event";
static src = "host";
static dst = "instance";
/** @type {string} */
event;
constructor(event) {
this.event = event;
}
static jsonSchema = {
type: "object",
required: ["event"],
properties: {
"event": { type: "string" },
},
};
static fromJSON(json) {
return new this(json.event);
}
}
/* @memberof module:lib */
class PrepareControllerDisconnectRequest {
static type = "request";
static src = "host";
static dst = "instance";
}
/** @memberof module:lib */
class SyncUserListsEvent {
static type = "event";
static src = "controller";
static dst = "host";
/** @type {Set<string>} */
adminlist;
/** @type {Map<string, string>} */
banlist;
/** @type {Set<string>} */
whitelist;
constructor(adminlist, banlist, whitelist) {
this.adminlist = adminlist;
this.banlist = banlist;
this.whitelist = whitelist;
}
static jsonSchema = {
type: "object",
required: ["adminlist", "banlist", "whitelist"],
properties: {
"adminlist": {
type: "array",
items: { type: "string" },
},
"banlist": {
type: "array",
items: {
type: "array",
minItems: 2,
items: [{ type: "string" }, { type: "string" }],
},
},
"whitelist": {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(new Set(json.adminlist), new Set(json.banlist), new Set(json.whitelist));
}
static toJSON() {
return {
adminlist: [...this.adminlist],
banlist: [...this.banlist],
whitelist: [...this.whitelist],
};
}
}
module.exports = {
HostDetails,
HostListRequest,
HostSetSubscriptionsRequest,
HostUpdateEvent,
HostMetricsRequest,
ControllerConnectionEvent,
PrepareControllerDisconnectRequest,
SyncUserListsEvent,
};
File diff suppressed because it is too large. Load diff
+474
View File
@@ -0,0 +1,474 @@
"use strict";
const ModPack = require("./ModPack");
const ModInfo = require("./ModInfo");
const { jsonArray, JsonString } = require("./composites");
/* @memberof module:lib */
class ModPackGetRequest {
static type = "request";
static src = ["instance", "control"];
static dst = "controller";
static permission = "core.mod_pack.get";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
static Response = ModPack;
}
/* @memberof module:lib */
class ModPackGetDefaultRequest {
static type = "request";
static src = ["instance", "control"];
static dst = "controller";
static permission = "core.mod_pack.get";
static Response = ModPack;
}
/* @memberof module:lib */
class ModPackListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.list";
static Response = jsonArray(ModPack);
}
/** @memberof module:lib */
class ModPackCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.create";
/** @type {module:lib.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
"modPack": ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib */
class ModPackUpdateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.update";
/** @type {module:lib.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
"modPack": ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib */
class ModPackDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.delete";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib */
class ModPackSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod_pack.subscribe";
/** @type {boolean} */
all;
/** @type {Array<number>} */
modPackIds;
constructor(all, modPackIds) {
this.all = all;
this.modPackIds = modPackIds;
}
static jsonSchema = {
type: "object",
required: ["all", "modPackIds"],
properties: {
all: { type: "boolean" },
modPackIds: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.modPackIds);
}
}
/* @memberof module:lib */
class ModGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.get";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
static Response = ModInfo;
}
/* @memberof module:lib */
class ModListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.list";
static Response = jsonArray(ModInfo);
}
/* @memberof module:lib */
class ModSearchRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.search";
/** @type {string} */
query;
/** @type {string} */
factorioVersion;
/** @type {number} */
page;
/** @type {number|undefined} */
pageSize;
/** @type {string|undefined} */
sort;
/** @type {string|undefined} */
sortOrder;
constructor(query, factorioVersion, page, pageSize, sort, sortOrder) {
this.query = query;
this.factorioVersion = factorioVersion;
this.page = page;
if (pageSize) { this.pageSize = pageSize; }
if (sort) { this.sort = sort; }
if (sortOrder) { this.sortOrder = sortOrder; }
}
static jsonSchema = {
type: "object",
required: ["query", "factorioVersion", "page"],
properties: {
query: { type: "string" },
factorioVersion: { type: "string" },
pageSize: { type: "integer" },
page: { type: "integer" },
sort: { type: "string" },
sortOrder: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.query, json.factorioVersion, json.page, json.pageSize, json.sort, json.sortOrder);
}
}
ModSearchRequest.Response = class Response {
/** @type {Array<string>} */
queryIssues;
/** @type {number} */
pageCount;
/** @type {number} */
resultCount;
/** @type {Array<object>} */
results;
constructor(queryIssues, pageCount, resultCount, results) {
this.queryIssues = queryIssues;
this.pageCount = pageCount;
this.resultCount = resultCount;
this.results = results;
}
static jsonSchema = {
type: "object",
required: ["queryIssues", "pageCount", "resultCount", "results"],
properties: {
queryIssues: {
type: "array",
items: { type: "string" },
},
pageCount: { type: "integer" },
resultCount: { type: "integer" },
results: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
versions: {
type: "array",
items: ModInfo.jsonSchema,
},
},
},
},
},
};
static fromJSON(json) {
let results = json.results.map(
({ name, versions }) => ({ name, versions: versions.map(mod => ModInfo.fromJSON(mod)) })
);
return new this(json.queryIssues, json.pageCount, json.resultCount, results);
}
};
/* @memberof module:lib */
class ModSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.subscribe";
/** @type {boolean} */
all;
/** @type {Array<string>} */
modNames;
constructor(all, modNames) {
this.all = all;
this.modNames = modNames;
}
static jsonSchema = {
type: "object",
required: ["all", "modNames"],
properties: {
all: { type: "boolean" },
modNames: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.modNames);
}
}
/* @memberof module:lib */
class ModDownloadRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.download";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
static Response = JsonString;
}
/* @memberof module:lib */
class ModDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.mod.delete";
/** @type {string} */
name;
/** @type {string} */
version;
constructor(name, version) {
this.name = name;
this.version = version;
}
static jsonSchema = {
type: "object",
required: ["name", "version"],
properties: {
name: { type: "string" },
version: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.version);
}
}
/* @memberof module:lib */
class ModPackUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib.ModPack} */
modPack;
constructor(modPack) {
this.modPack = modPack;
}
static jsonSchema = {
type: "object",
required: ["modPack"],
properties: {
modPack: ModPack.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModPack.fromJSON(json.modPack));
}
}
/* @memberof module:lib */
class ModUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib.ModInfo} */
mod;
constructor(mod) {
this.mod = mod;
}
static jsonSchema = {
type: "object",
required: ["mod"],
properties: {
mod: ModInfo.jsonSchema,
},
};
static fromJSON(json) {
return new this(ModInfo.fromJSON(json.mod));
}
}
module.exports = {
ModPackGetRequest,
ModPackGetDefaultRequest,
ModPackListRequest,
ModPackCreateRequest,
ModPackUpdateRequest,
ModPackDeleteRequest,
ModPackSetSubscriptionsRequest,
ModGetRequest,
ModListRequest,
ModSearchRequest,
ModSetSubscriptionsRequest,
ModDownloadRequest,
ModDeleteRequest,
ModPackUpdateEvent,
ModUpdateEvent,
};
+708
View File
@@ -0,0 +1,708 @@
"use strict";
const PlayerStats = require("../PlayerStats");
const { jsonArray, JsonNumber } = require("./composites");
/* @memberof module:lib */
class RawPermission { // TODO refactor into lib/user.Permission
/** @type {string} */
name;
/** @type {string} */
title;
/** @type {string} */
description;
constructor(name, title, description) {
this.name = name;
this.title = title;
this.description = description;
}
static jsonSchema = {
type: "object",
required: ["name", "title", "description"],
properties: {
name: { type: "string" },
title: { type: "string" },
description: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.title, json.description);
}
}
/* @memberof module:lib */
class PermissionListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.permission.list";
static Response = jsonArray(RawPermission);
}
class RawRole { // TODO refactor into lib/user.Role
/** @type {number} */
id;
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(id, name, description, permissions) {
this.id = id;
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "description", "permissions"],
properties: {
id: { type: "integer" },
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.description, json.permissions);
}
}
/* @memberof module:lib */
class RoleListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.list";
static Response = jsonArray(RawRole);
}
/* @memberof module:lib */
class RoleCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.create";
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(name, description, permissions) {
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["name", "description", "permissions"],
properties: {
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.name, json.description, json.permissions);
}
static Response = JsonNumber;
}
/* @memberof module:lib */
class RoleUpdateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.update";
/** @type {number} */
id;
/** @type {string} */
name;
/** @type {string} */
description;
/** @type {Array<string>} */
permissions;
constructor(id, name, description, permissions) {
this.id = id;
this.name = name;
this.description = description;
this.permissions = permissions;
}
static jsonSchema = {
type: "object",
required: ["id", "name", "description", "permissions"],
properties: {
id: { type: "integer" },
name: { type: "string" },
description: { type: "string" },
permissions: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.id, json.name, json.description, json.permissions);
}
}
/* @memberof module:lib */
class RoleGrantDefaultPermissionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.update";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib */
class RoleDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.role.delete";
/** @type {number} */
id;
constructor(id) {
this.id = id;
}
static jsonSchema = {
type: "object",
required: ["id"],
properties: {
id: { type: "integer" },
},
};
static fromJSON(json) {
return new this(json.id);
}
}
/* @memberof module:lib */
class RawUser { // TODO refactor into lib/user.User
/** @type {string} */
name;
/** @type {Array<number>} */
roles;
/** @type {Array<number>} */
instances;
/** @type {boolean|undefined} */
isAdmin;
/** @type {boolean|undefined} */
isBanned;
/** @type {boolean|undefined} */
isWhitelisted;
/** @type {string|undefined} */
banReason;
/** @type {boolean|undefined} */
isDeleted;
/** @type {module:lib.PlayerStats} */
playerStats;
/** @type {Map<number, module:lib.PlayerStats>|undefined} */
instanceStats;
constructor(
name, roles, instances, isAdmin, isBanned, isWhitelisted, banReason,
isDeleted, playerStats, instanceStats
) {
this.name = name;
this.roles = roles;
this.instances = instances;
if (isAdmin !== undefined) { this.isAdmin = isAdmin; }
if (isBanned !== undefined) { this.isBanned = isBanned; }
if (isWhitelisted !== undefined) { this.isWhitelisted = isWhitelisted; }
if (banReason !== undefined) { this.banReason = banReason; }
if (isDeleted !== undefined) { this.isDeleted = isDeleted; }
if (playerStats !== undefined) { this.playerStats = playerStats; }
if (instanceStats !== undefined) { this.instanceStats = instanceStats; }
}
static jsonSchema = {
type: "object",
required: ["name", "roles", "instances"],
properties: {
name: { type: "string" },
roles: { type: "array", items: { type: "integer" } },
instances: { type: "array", items: { type: "integer" } },
isAdmin: { type: "boolean" },
isBanned: { type: "boolean" },
isWhitelisted: { type: "boolean" },
banReason: { type: "string" },
isDeleted: { type: "boolean" },
playerStats: PlayerStats.jsonSchema,
instanceStats: {
type: "array",
items: {
type: "array",
minItems: 2,
items: [{ type: "integer" }, PlayerStats.jsonSchema],
},
},
},
};
static fromJSON(json) {
let playerStats;
if (json.playerStats) {
playerStats = PlayerStats.fromJSON(json.playerStats);
}
let instanceStats;
if (json.instanceStats) {
instanceStats = new Map(
json.instanceStats.map(([id, stats]) => [id, PlayerStats.fromJSON(stats)])
);
}
return new this(
json.name, json.roles, json.instances, json.isAdmin, json.isBanned, json.isWhitelisted, json.banReason,
json.isDeleted, playerStats, instanceStats
);
}
toJSON() {
const json = {
name: this.name,
roles: this.roles,
instances: this.instances,
isAdmin: this.isAdmin,
isBanned: this.isBanned,
isWhitelisted: this.isWhitelisted,
banReason: this.banReason,
isDeleted: this.isDeleted,
playerStats: this.playerStats,
};
if (this.instanceStats) {
json.instanceStats = [...this.instanceStats];
}
return json;
}
}
/* @memberof module:lib */
class UserGetRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.get";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
static Response = RawUser;
}
/* @memberof module:lib */
class UserListRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.list";
static Response = jsonArray(RawUser);
}
/* @memberof module:lib */
class UserSetSubscriptionsRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.subscribe";
/** @type {boolean} */
all;
/** @type {Array<string>} */
names;
constructor(all, names) {
this.all = all;
this.names = names;
}
static jsonSchema = {
type: "object",
required: ["all", "names"],
properties: {
all: { type: "boolean" },
names: {
type: "array",
items: { type: "string" },
},
},
};
static fromJSON(json) {
return new this(json.all, json.names);
}
}
/* @memberof module:lib */
class UserCreateRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.create";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib */
class UserRevokeTokenRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.revoke_token";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib */
class UserUpdateRolesRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.update_roles";
/** @type {string} */
name;
/** @type {Array<number>} */
roles;
constructor(name, roles) {
this.name = name;
this.roles = roles;
}
static jsonSchema = {
type: "object",
required: ["name", "roles"],
properties: {
name: { type: "string" },
roles: {
type: "array",
items: { type: "integer" },
},
},
};
static fromJSON(json) {
return new this(json.name, json.roles);
}
}
/* @memberof module:lib */
class UserSetAdminRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_admin";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
admin;
constructor(name, create, admin) {
this.name = name;
this.create = create;
this.admin = admin;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "admin"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
admin: { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.admin);
}
}
/* @memberof module:lib */
class UserSetWhitelistedRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_whitelisted";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
whitelisted;
constructor(name, create, whitelisted) {
this.name = name;
this.create = create;
this.whitelisted = whitelisted;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "whitelisted"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
whitelisted: { type: "boolean" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.whitelisted);
}
}
/* @memberof module:lib */
class UserSetBannedRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.set_banned";
/** @type {string} */
name;
/** @type {boolean} */
create;
/** @type {boolean} */
banned;
/** @type {string} */
reason;
constructor(name, create, banned, reason) {
this.name = name;
this.create = create;
this.banned = banned;
this.reason = reason;
}
static jsonSchema = {
type: "object",
required: ["name", "create", "banned", "reason"],
properties: {
name: { type: "string" },
create: { type: "boolean" },
banned: { type: "boolean" },
reason: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name, json.create, json.banned, json.reason);
}
}
/* @memberof module:lib */
class UserDeleteRequest {
static type = "request";
static src = "control";
static dst = "controller";
static permission = "core.user.delete";
/** @type {string} */
name;
constructor(name) {
this.name = name;
}
static jsonSchema = {
type: "object",
required: ["name"],
properties: {
name: { type: "string" },
},
};
static fromJSON(json) {
return new this(json.name);
}
}
/* @memberof module:lib */
class AccountUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {Array<object>|undefined} */
roles;
constructor(roles) {
if (roles) { this.roles = roles; }
}
static jsonSchema = {
type: "object",
properties: {
roles: {
type: "array",
items: {
type: "object",
required: ["name", "id", "permissions"],
properties: {
name: { type: "string" },
id: { type: "integer" },
permissions: {
type: "array",
items: { type: "string" },
},
},
},
},
},
};
static fromJSON(json) {
return new this(json.roles);
}
}
/* @memberof module:lib */
class UserUpdateEvent {
static type = "event";
static src = "controller";
static dst = "control";
/** @type {module:lib.RawUser} */
user;
constructor(user) {
this.user = user;
}
static jsonSchema = {
type: "object",
required: ["user"],
properties: {
user: RawUser.jsonSchema,
},
};
static fromJSON(json) {
return new this(RawUser.fromJSON(json.user));
}
}
module.exports = {
RawPermission,
PermissionListRequest,
RawRole,
RoleListRequest,
RoleCreateRequest,
RoleUpdateRequest,
RoleGrantDefaultPermissionsRequest,
RoleDeleteRequest,
RawUser,
UserGetRequest,
UserListRequest,
UserSetSubscriptionsRequest,
UserCreateRequest,
UserRevokeTokenRequest,
UserUpdateRolesRequest,
UserSetAdminRequest,
UserSetWhitelistedRequest,
UserSetBannedRequest,
UserDeleteRequest,
AccountUpdateEvent,
UserUpdateEvent,
};
+44
View File
@@ -0,0 +1,44 @@
// Helper functions for dealing with factorio version numbers
"use strict";
/**
* Integer representation of a mod version
*
* Suitable for sorting and comparing version numbers which may have different
* number of leading zeros in them.
* @param {string} version - string representation of version.
* @returns {number} numeric representation.
* @alias module:lib.integerModVersion
*/
function integerModVersion(version) {
const [major, minor, sub] = version.split(".").map(n => Number.parseInt(n, 10));
return major * 0x100000000 + minor * 0x10000 + sub; // Can't use bitwise here because this is 48-bits.
}
/**
* Integer representation of a factorio version
*
* Suitable for sorting and comparing version numbers which may have different
* number of leading zeros in them.
* @param {string} version - string representation of version.
* @returns {number} numeric representation.
* @alias module:lib.integerFactorioVersion
*/
function integerFactorioVersion(version) {
const [main, major, minor] = version.split(".").map(n => Number.parseInt(n, 10));
return main * 0x100000000 + major * 0x10000 + (minor || 0); // Can't use bitwise here because this is 48-bits.
}
/**
* Matches valid mod versions.
* @type {RegExp}
* @alias module:lib.modVersionRegExp
*/
const modVersionRegExp = /^\d+\.\d+\.\d+$/;
module.exports = {
integerModVersion,
integerFactorioVersion,
modVersionRegExp,
};