@devnote-dev/pterojs
Version:
A verbose API library for Pterodactyl
1,562 lines (1,548 loc) • 122 kB
TypeScript
import { EventEmitter } from 'events';
import { Axios } from 'axios';
/** Applies an external option to the request. */
declare type External<T> = {
external?: boolean;
} & T;
/** Applies a filter option to the request. */
declare type Filter<T> = {
filter?: string;
} & T;
/** An internal form of the filter arguments. */
declare type FilterArray<T> = {
filter?: string[];
} & T;
/** Applies an include option on the request. */
declare type Include<T> = {
include?: string[];
} & T;
/** Applies a sort option on the request. */
declare type Sort<T> = {
sort?: string;
} & T;
/** The types object `T` can be resolved from, including itself. */
declare type Resolvable<T> = string | number | Record<string, any> | T;
/** Represents the daemon information on a node. */
interface DaemonData {
listening: number;
sftp: number;
base: string;
}
/** Represents the feature limits of a server. */
interface FeatureLimits {
/** The total number of allocations for the server. */
allocations: number;
/** The total number of backups allowed on the server. */
backups: number;
/** The total number of databases on the server. */
databases: number;
}
/** General fetch options for requests. */
interface FetchOptions {
/**
* Whether to skip cache checks and go straight to the request.
* This does not apply to all managers that use FetchOptions,
* check the specific method docs for more information.
* @default false
*/
force?: boolean;
/**
* The page number to get results from.
* @default 1
*/
page?: number;
/**
* The number of results to return per-page.
* @default 50
*/
perPage?: number;
}
/** Represents the configuration for the pterojs.json file. */
interface FileConfig {
application?: Record<string, OptionSpec>;
client?: Record<string, OptionSpec>;
}
/** Represents the limits of a server. */
interface Limits {
/** The amount of memory allocated to the server. */
memory: number;
/** The amount of swap space allocated to the server. */
swap: number;
/** The amount of disk allocated to the server. */
disk: number;
/** The amount of block IO bandwidth allowed for the server. */
io: number;
/**
* The number of threads (or specific threads) the server can use.
* `null` means unlimited.
*/
threads: string | null;
/** The amount of CPU allocated to the server. */
cpu: number;
}
/** Represents a location object. */
interface NodeLocation {
id: number;
long: string;
short: string;
createdAt: Date;
updatedAt: Date | null;
}
/**
* Option specification attributes for the {@link FileConfig}.
* PteroJS currently supports the following config options:
* * users
* * nodes
* * nests
* * servers
* * locations
* * subUsers
*/
interface OptionSpec {
/**
* Whether to call the option manager's `fetch()` method
* (used by the main class' `connect()` method).
*/
fetch?: boolean;
/** Whether to cache the option manager's values. */
cache?: boolean;
/**
* The maximum amount of entries to allow for the option manager's cache.
* @experimental
*/
max?: number;
}
/**
* Represents the metadata received from endpoints with
* paginated responses.
*/
interface PaginationMeta {
current: number;
total: number;
count: number;
perPage: number;
totalPages: number;
links?: string[];
}
interface RequestEvents {
debug: [message: string];
preRequest: [data: any];
postRequest: [data: any];
}
interface DictConstructor {
new (): Dict<any, any>;
new <K, V>(entries?: readonly [K, V][]): Dict<K, V>;
new <K, V>(iterable?: Iterable<readonly [K, V]>): Dict<K, V>;
readonly [Symbol.iterator]: DictConstructor;
readonly [Symbol.species]: DictConstructor;
}
/**
* Dict (or Dictionary) is an extended Map with additional helper methods
* used for manager caches in the PteroJS library.
*/
declare class Dict<K, V> extends Map<K, V> {
['constructor']: DictConstructor;
private _limit;
get limit(): number;
/**
* Sets a limit for the number of entries the dict can have.
* **Note:** this cannot be changed once set. Attempting to will throw an error.
* @param amount The number of entries allowed for the dict.
*/
setLimit(amount: number): void;
/** @returns Whether the dict has a set limit. */
isLimited(): boolean;
set(key: K, value: V): this;
/**
* Checks if at least one of the entries in the dict pass the function.
* @param fn The function to apply to the dict.
*/
some(fn: (value: V, key: K, dict: this) => boolean): boolean;
/**
* Checks if all the entries in the dict pass the function.
* @param fn The function to apply to the dict.
*/
every(fn: (value: V, key: K, dict: this) => boolean): boolean;
/**
* Checks that any of the specified keys exist in the dict.
* @param keys The keys to check for.
*/
hasAny(...keys: K[]): boolean;
/**
* Checks that all of the specified keys exist in the dict.
* @param keys The keys to check for.
*/
hasAll(...keys: K[]): boolean;
/**
* Returns the first entry (or entries if otherwise specified) in the dict.
* @param [amount] The number of entries to return from the start of the dict.
*/
first<T extends number | undefined>(amount?: T): T extends undefined ? V : V[];
/**
* Returns the first key (or keys if otherwise specified) in the dict.
* @param [amount] The number of keys to return from the start of the dict.
*/
firstKey<T extends number | undefined>(amount?: T): T extends undefined ? K : K[];
/**
* Returns the last entry (or entries if otherwise specified) in the dict.
* @param [amount] The number of entries to return from the end of the dict.
*/
last<T extends number | undefined>(amount?: T): T extends undefined ? V : V[];
/**
* Returns the last key (or keys if otherwise specified) in the dict.
* @param [amount] The number of keys to return from the end of the dict.
*/
lastKey<T extends number | undefined>(amount?: T): T extends undefined ? K : K[];
/**
* Returns a random entry (or entries if otherwise specified) in the dict.
* @param [amount] The number of entries to return from the dict.
*/
random<T extends number | undefined>(amount?: T): T extends undefined ? V : V[];
/**
* Returns a random key (or keys if otherwise specified) in the dict.
* @param [amount] The number of keys to return from the dict.
*/
randomKey<T extends number | undefined>(amount?: T): T extends undefined ? K : K[];
/**
* Applies the function to each entry in the dict and returns an array of
* the results.
* @param fn The function to apply to the dict.
* @returns The mapped results.
*/
map<T>(fn: (value: V, key: K, dict: this) => T): T[];
/**
* Applies the function to each entry in the dict and returns a dict of the
* results that passed.
* @param fn The function to apply to the dict.
* @returns The filtered dict.
*/
filter(fn: (value: V, key: K, dict: this) => boolean): Dict<K, V>;
/**
* Applies a function to each entry in the dict and returns the first one
* that passes.
* @param fn The function to apply to the dict.
*/
find(fn: (value: V, key: K, dict: this) => boolean): V | undefined;
/**
* Applies a function to each entry in the dict and returns the number of
* items removed.
* @param fn The function to apply to the dict.
* @returns The number of sweeped entries.
*/
sweep(fn: (value: V, key: K, dict: this) => boolean): number;
/**
* Applies a function to each entry in the dict and returns 2 dicts, the first
* containing entries that passed the function and the second containing
* the failed entries.
* @param fn The function to apply to the dict.
* @returns The passed and failed dicts.
*/
part(fn: (value: V, key: K, dict: this) => boolean): Dict<K, V>[];
/**
* Reduces each entry in the dict to a single value.
* @param fn The function to apply to the dict.
* @returns The reduced value.
*/
reduce<T>(fn: (value: V, key: K, dict: this) => T, acc: T): T;
/**
* Joins one or more dicts with the current one and returns the value.
* @param dict The dicts to join.
* @returns The joined dicts.
*/
join(...dict: Dict<K, V>[]): Dict<K, V>;
/**
* @param dict The dict to compare differences to.
* @returns A dict containing the different entries between both dicts.
*/
difference(dict: Dict<K, V>): Dict<K, V>;
/**
* Updates the values of the current dict with the specified dict, settings the
* values in place.
* @param dict The dict to update with.
*/
update(dict: Dict<K, V>): void;
/** @returns A clone of the dict. */
clone(): Dict<K, V>;
}
declare abstract class BaseManager {
meta: PaginationMeta;
abstract get FILTERS(): readonly string[];
abstract get SORTS(): readonly string[];
abstract get INCLUDES(): readonly string[];
abstract fetch(...args: unknown[]): Promise<unknown>;
/**
* Gets the allowed query options from the inherited manager.
* @returns The query options.
* @internal
*/
getQueryOptions(): {
filters: readonly string[];
sorts: readonly string[];
includes: readonly string[];
};
/**
* Fetches rach page and joins the results.
* @returns Dictionary of the specified types
* @internal
*/
protected getFetchAll<T, K>(...options: unknown[]): Promise<Dict<T, K>>;
}
/** Represents an allocation object. */
interface Allocation {
id: number;
ip: string;
alias: string | undefined;
port: number;
notes: string | undefined;
assigned: boolean;
}
interface ApplicationDatabase {
id: number;
serverId: number;
hostId: number;
database: unknown;
username: string;
remote: string;
maxConnections: number;
createdAt: Date;
updatedAt: Date | undefined;
}
/** Options for creating a node. */
interface CreateNodeOptions {
name: string;
description: string | undefined;
/** @deprecated Broken, use `locationId`. */
location: string;
locationId: number;
public: boolean;
fqdn: string;
scheme: string;
behindProxy: boolean;
memory: number;
memoryOverallocate?: number;
disk: number;
diskOverallocate?: number;
/** @deprecated Use `daemonPort` and `daemonListen` instead. */
sftp: {
port: number;
listener: number;
};
daemonBase: string;
daemonSftp: number;
daemonListen: number;
maintenanceMode: boolean;
uploadSize?: number;
}
/** Options for creating a user account. */
interface CreateUserOptions {
externalId?: string;
email: string;
username: string;
firstname: string;
lastname: string;
password?: string;
isAdmin?: boolean;
}
/** Options for creating a server. */
interface CreateServerOptions {
/** The external identifier of the server. */
externalId?: string;
/** The name of the server. */
name: string;
/**
* A description of the server.
* @default undefined
*/
description?: string;
/** The ID of the user that will own the server. */
user: number;
/** The egg to use for the server. */
egg: number;
/** The default docker image for the server. */
dockerImage: string;
/** The server startup command. */
startup: string;
/** An environment variables object. */
environment: Record<string, string | number | boolean>;
/**
* Whether to skip the egg installation script.
* @default false
*/
skipScripts?: boolean;
/** Doesn't work, don't use this. */
oomDisabled?: boolean;
/** The server limits. */
limits?: Partial<Limits>;
/** The server's feature limits. */
featureLimits?: Partial<FeatureLimits>;
/** The server allocation details. */
allocation: {
/** The default server allocation. */
default: number;
/** Additional allocations for the server. */
additional?: number[];
};
/**
* Node deployment options. This is for more control over where the
* server is deployed within the location and port ranges specified.
*/
deploy?: {
locations: number[];
dedicatedIp: boolean;
portRange: string[];
};
/**
* Whether to start the server after the installation process is complete.
* @default false
*/
startOnCompletion?: boolean;
}
/** Represents a nest egg object. */
interface Egg {
id: number;
uuid: string;
nest: number;
name: string;
description: string;
author: string;
/**
* @deprecated Will be removed in Pterodactyl v2 in favour of
* {@link dockerImages}.
*/
dockerImage: string;
dockerImages: string[];
config: {
files: Record<string, any>;
startup: Record<string, any>;
stop: string;
logs: string[];
fileDenylist: string[];
extends: string | null;
};
startup: string;
script: {
privileged: boolean;
install: string;
entry: string;
container: string;
extends: string | null;
};
createdAt: Date;
updatedAt: Date | undefined;
}
/** Represents a nest object. */
interface Nest {
id: number;
uuid: string;
author: string;
name: string;
description: string;
createdAt: Date;
updatedAt: Date | undefined;
}
/** Represents a node configuration object (from Wings). */
interface NodeConfiguration {
uuid: string;
tokenId: string;
token: string;
debug: boolean;
api: {
host: string;
port: number;
ssl: {
enabled: boolean;
cert: string;
key: string;
};
uploadLimit: number;
};
system: {
data: string;
sftp: {
bindPort: number;
};
};
allowedMounts: string[];
remote: string;
}
/** Query options for fetching deployable nodes. */
interface NodeDeploymentOptions {
memory: number;
disk: number;
locationIds?: number[];
}
/** Represents a server status. If the server has no status, `NONE` is used. */
declare enum ServerStatus {
INSTALLING = "installing",
INSTALL_FAILED = "install_failed",
SUSPENDED = "suspended",
RESTORING = "restoring_backup",
NONE = ""
}
interface UpdateBuildOptions {
limits?: Partial<Limits>;
featureLimits?: Partial<FeatureLimits>;
allocation?: number;
oomDisabled?: boolean;
addAllocations?: number[];
removeAllocations?: number[];
}
interface UpdateDetailsOptions {
name?: string;
owner?: number;
externalId?: string;
description?: string;
}
interface UpdateStartupOptions {
startup?: string;
environment?: Record<string, string | number | boolean>;
egg?: number;
image?: string;
skipScripts?: boolean;
}
interface UpdateUserOptions extends Omit<CreateUserOptions, 'externalId'> {
externalId?: string | null;
}
declare class Node {
readonly client: PteroApp;
/** The internal ID of the node (separate from UUID). */
readonly id: number;
/** The UUID of the node. */
readonly uuid: string;
/** The date the node was created. */
readonly createdAt: Date;
/** Whether the node is public. */
public: boolean;
/** The name of the node. */
name: string;
/** The description of the server (if set). */
description: string | undefined;
/** The ID of the location the node is on. */
locationId: number;
/**
* The location object the node is on. This is not fetched by default
* and must be retrieved by including 'location' in `NodeManager#fetch`.
*/
location: NodeLocation | undefined;
/** A dict of servers on the node. */
servers: Dict<number, ApplicationServer>;
/** The FQDN of the node. */
fqdn: string;
/** The HTTP scheme of the node. */
scheme: string;
/** Whether the node is behind a proxy. */
behindProxy: boolean;
/** Whether the node is in maintenance mode. */
maintenance: boolean;
/** The amount of memory the node has. */
memory: number;
/** The amount of memory the node has overallocated. */
overallocatedMemory: number;
/** The amount of disk the node has. */
disk: number;
/** The amount of disk the node has overallocated. */
overallocatedDisk: number;
/** The maximum upload size for the node. */
uploadSize: number;
/** The Wings daemon information. */
daemon: DaemonData;
constructor(client: PteroApp, data: any);
_patch(data: any): void;
/**
* Returns a formatted URL to the node in the admin panel.
* @returns The formatted URL.
*/
get adminURL(): string;
/**
* Fetches the configuration of the node.
* @returns The node configuration.
*/
getConfig(): Promise<NodeConfiguration>;
/**
* Updates the node with the specified options.
* @param options Update node options.
* @see {@link CreateNodeOptions UpdateNodeOptions}.
* @returns The updated instance.
*/
update(options: Partial<CreateNodeOptions>): Promise<this>;
/**
* Converts the node into a JSON object, relative to the API
* response object.
* @returns The JSON object.
*/
toJSON(): object;
/** @returns The string representation of the node. */
toString(): string;
}
interface Activity {
id: string;
batch: unknown;
event: string;
isApi: boolean;
ip: string | null;
description: string | null;
properties: Record<string, any>;
hasAdditionalMetadata: boolean;
timestamp: Date;
}
/** Represents a client API key. */
interface APIKey {
identifier: string;
description: string;
allowedIps: string[];
createdAt: Date;
lastUsedAt: Date | undefined;
token?: string;
}
/** Represents a server backup object. */
interface Backup {
uuid: string;
name: string;
ignoredFiles: string[];
hash: string | undefined;
bytes: number;
checksum: string | undefined;
successful: boolean;
locked: boolean;
createdAt: Date;
completedAt: Date | undefined;
}
/** Represents the client metedata from a client servers request. */
interface ClientMeta {
isServerOwner?: boolean;
userPermissions?: Record<string, string>;
}
/** Represents the currently used resources of a server. */
interface ClientResources {
currentState: string;
isSuspended: boolean;
resources: {
memoryBytes: number;
cpuAbsolute: number;
diskBytes: number;
networkRxBytes: number;
networkTxBytes: number;
uptime: number;
};
}
/** Options for creating a server backup. */
interface CreateBackupOptions {
name?: string;
isLocked?: boolean;
ignored?: string;
}
/** Options for creating a server schedule. */
interface CreateScheduleOptions {
name: string;
active: boolean;
dayOfWeek?: string;
dayOfMonth?: string;
month: string;
hour: string;
minute: string;
onlyWhenOnline?: boolean;
}
/** Represents a schedule cronjob object. */
interface Cron {
dayOfWeek: string;
dayOfMonth: string;
month: string;
hour: string;
minute: string;
}
/** Represents a server database object. */
interface ClientDatabase {
id: number;
name: string;
username: string;
host: {
address: string;
port: number;
};
connectionsFrom: string;
maxConnections: string;
password?: string;
}
/** Represents an egg variable. */
interface EggVariable {
name: string;
description: string;
envVariable: string;
defaultValue: string | number;
serverValue: string | number;
isEditable: boolean;
rules: string;
}
/** Represents a file or file-like object on the server. */
interface File {
name: string;
mode: string;
modeBits: bigint;
size: number;
isFile: boolean;
isSymlink: boolean;
mimetype: string;
createdAt: Date;
modifiedAt: Date | undefined;
}
/** Options for changing file permissions. */
interface FileChmodData {
file: string;
mode: number;
}
/** Represents a network allocation object for a server. */
interface NetworkAllocation {
id: number;
ip: string;
ipAlias: string;
port: number;
notes: string | null;
isDefault: boolean;
}
/**
* Represents a permission descriptor for grouped permissions.
* Available permission groups:
* * websocket
* * control
* * user
* * file
* * backup
* * allocation
* * startup
* * database
* * schedule
* * settings
*/
interface PermissionDescriptor {
description: string;
keys: Record<string, string>;
}
/** Represents a task for a schedule. */
interface ScheduleTask {
id: number;
sequenceId: number;
action: string;
payload: string;
offset: number;
queued: boolean;
createdAt: Date;
updatedAt: Date | undefined;
}
declare type ScheduleTaskAction = 'backup' | 'command' | 'power';
declare enum ShardStatus {
CLOSED = 0,
CONNECTING = 1,
CONNECTED = 2
}
interface SSHKey {
name: string;
fingerprint: string;
publicKey: string;
createdAt: Date;
}
interface StartupData {
variables: EggVariable[];
startupCommand: string;
dockerImages?: string[];
rawStartupCommand: string;
}
interface WebSocketAuth {
data: {
socket: string;
token: string;
};
}
interface WebSocketEvents {
debug: [message: string];
error: [message: string];
rawPayload: [data: any];
authSuccess: [];
serverConnect: [id: string];
serverOutput: [output: string];
daemonMessage: [output: string];
serverDisconnect: [];
statsUpdate: [stats: ClientResources];
statusUpdate: [status: string];
transferUpdate: [data: any];
installStart: [];
installOutput: [output: string];
installComplete: [];
backupComplete: [backup: Partial<Backup>];
}
interface WebSocketPayload {
event: string;
args?: string[];
}
declare class Shard extends EventEmitter {
client: PteroClient;
id: string;
origin: boolean;
private socket;
private status;
readyAt: number;
ping: number;
lastPing: number;
constructor(client: PteroClient, id: string, origin: boolean);
emit<E extends keyof WebSocketEvents>(event: E, ...args: WebSocketEvents[E]): boolean;
on<E extends keyof WebSocketEvents>(event: E, listener: (...args: WebSocketEvents[E]) => void): this;
once<E extends keyof WebSocketEvents>(event: E, listener: (...args: WebSocketEvents[E]) => void): this;
off<E extends keyof WebSocketEvents>(event: E, listener: (...args: WebSocketEvents[E]) => void): this;
private debug;
/** Initializes the connection to the server websocket after authentication. */
connect(): Promise<void>;
private refresh;
/**
* Sends a websocket event to the server (with optional payload args).
* @param event The event to send to the server.
* @param args Additional arguements to pass with to the event.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => shard.send('send logs'));
* shard.connect();
* ```
*/
send(event: string, args?: string[]): void;
/**
* Sends an event to the server and waits for a response.
* @param event The event to send.
* @param [args] The arguments to send with the event.
* @returns The event's response, if any.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => {
* shard.request('sendCommand', '/say hello world').then(console.log)
* );
* shard.connect();
* ```
*/
request(event: string, args?: string): Promise<any>;
/**
* Sends an event to the server and waits for a response.
* @param event The event to send.
* @param command The command to send.
* @returns The event's response, if any.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => {
* shard.request('sendCommand', '/say hello world').then(console.log)
* );
* shard.connect();
* ```
*/
request(event: 'sendCommand', command: string): Promise<void>;
/**
* Sends an event to the server and waits for a response.
* @param event The event to send.
* @returns The event's response, if any.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => {
* shard.request('sendLogs').then(console.log)
* );
* shard.connect();
* ```
*/
request(event: 'sendLogs'): Promise<void>;
/**
* Sends an event to the server and waits for a response.
* @param event The event to send.
* @returns The event's response, if any.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => {
* shard.request('sendStats').then(console.log)
* );
* shard.connect();
* ```
*/
request(event: 'sendStats'): Promise<void>;
/**
* Sends an event to the server and waits for a response.
* @param event The event to send.
* @param state The power state to send.
* @returns The event's response, if any.
* @example
* ```
* const shard = client.addSocketServer('411d2eb9');
* shard.on('authSuccess', () => {
* shard.request('setState', 'restart').then(console.log)
* );
* shard.connect();
* ```
*/
request(event: 'setState', state: string): Promise<void>;
/** Disconnects the websocket from the API. */
disconnect(): void;
private onOpen;
private onMessage;
private onError;
private onClose;
}
declare class BackupManager extends BaseManager {
client: PteroClient;
cache: Dict<string, Backup>;
serverId: string;
/** Allowed filter arguments for backups (none). */
get FILTERS(): readonly never[];
/** Allowed include arguments for backups (none). */
get INCLUDES(): readonly never[];
/** Allowed sort arguments for backups (none). */
get SORTS(): readonly never[];
constructor(client: PteroClient, serverId: string);
/**
* Transforms the raw backup object(s) into typed objects.
* @param data The resolvable backup object(s).
* @returns The resolved backup object(s).
*/
_patch(data: any): any;
/**
* Fetches a backup from the API by its identifier. This will check the cache first unless the
* force option is specified.
*
* @param id The identifier of the backup.
* @param [options] Additional fetch options.
* @returns The fetched backup.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.fetch({ perPage: 10 })
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(id: string, options?: Include<FetchOptions>): Promise<Backup>;
/**
* Fetches a list of backups from the API with the given options (default is undefined).
*
* @param [options] Additional fetch options.
* @returns The fetched backups.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.fetch({ perPage: 10 })
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(options?: Include<FetchOptions>): Promise<Dict<number, Backup>>;
/**
* Creates a new backup on the server.
* @see {@link CreateBackupOptions}.
*
* @param options Create backup options.
* @returns The new backup.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.create({ name: 'bungee-archive' })
* .then(console.log)
* .catch(console.error);
* ```
*/
create(options?: CreateBackupOptions): Promise<Backup>;
/**
* Toggles the locked status of a backup.
* @param id The UUID of the backup.
* @returns The updated backup.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.toggleLock('904df120')
* .then(console.log)
* .catch(console.error);
* ```
*/
toggleLock(id: string): Promise<Backup>;
/**
* Fetches the download URL for a specified backup.
* @param id The UUID of the backup.
* @returns The download URL.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.getDownloadURL('904df120')
* .then(console.log)
* .catch(console.error);
* ```
*/
getDownloadURL(id: string): Promise<string>;
/**
* Fetches and saves a backup to a specified path on the system.
* @param id The UUID of the backup.
* @param dest The file path to save the backup to.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.download('904df120', './bungee-archive.tar.gz')
* .catch(console.error);
* ```
*/
download(id: string, dest: string): Promise<void>;
/**
* Restores a specified backup to the server.
* @param id The UUID of the backup.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.restore('904df120').catch(console.error);
* ```
*/
restore(id: string): Promise<void>;
/**
* Deletes a specified backup.
* @param id The UUID of the backup.
* @example
* ```
* const server = await client.servers.fetch('34740510');
* await server.backups.delete('c4b9c4c7').catch(console.error);
* ```
*/
delete(id: string): Promise<void>;
}
declare class ClientDatabaseManager extends BaseManager {
client: PteroClient;
cache: Dict<number, ClientDatabase>;
serverId: string;
/** Allowed filter arguments for databases (none). */
get FILTERS(): readonly never[];
/**
* Allowed include arguments for databases:
* * password
*/
get INCLUDES(): readonly string[];
/** Allowed sort arguments for databases (none). */
get SORTS(): readonly never[];
constructor(client: PteroClient, serverId: string);
/**
* Transforms the raw database object(s) into typed objects.
* @param data The resolvable database object(s).
* @returns The resolved database object(s).
*/
_patch(data: any): any;
/**
* Fetches a list of databases from the API with the given options (default is undefined).
*
* @param [options] Additional fetch options.
* @returns The fetched databases.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.databases.fetch({ page: 2 })
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(options?: Include<FetchOptions>): Promise<Dict<number, ClientDatabase>>;
/**
* Creates a database on the server.
* @param database The name of the database.
* @param remote The connections allowed to the database.
* @returns The new database.
*/
create(database: string, remote: string): Promise<ClientDatabase>;
/**
* Rotates the password of a specified database.
* @param id The ID of the database.
* @returns The updated database.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.databases.rotate(1)
* .then(console.log)
* .catch(console.error);
* ```
*/
rotate(id: number): Promise<ClientDatabase>;
/**
* Deletes a database from the server.
* @param id The ID of the database.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.databases.delete(2).catch(console.error);
* ```
*/
delete(id: number): Promise<void>;
}
declare class FileManager {
client: PteroClient;
cache: Dict<string, Dict<string, File>>;
serverId: string;
constructor(client: PteroClient, serverId: string);
/**
* Transforms the raw file object(s) into typed objects.
* @param data The resolvable file object(s).
* @returns The resolved file object(s).
*/
_patch(dir: string, data: any): Dict<string, File>;
/**
* Returns a URI-encoded UNIX version of the specified path for requests.
* @param path The path to clean.
* @returns The cleaned path.
*/
private clean;
/**
* Fetches the files/directories in a specified direcory (defaults to root).
* @param [dir] The directory to fetch from.
* @returns The fetched files.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.fetch().then(console.log).catch(console.error);
* ```
*/
fetch(dir?: string): Promise<Dict<string, File>>;
/**
* Fetches the contents of a specified file. The content is always returned as a
* string by default, regardless of file type.
* @param path The file path.
* @returns The file contents.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.getContents('./install.log')
* .then(console.log)
* .catch(console.error);
* ```
*/
getContents(path: string): Promise<string>;
/**
* Fetches the download URL for a specified file.
* @param path The file path.
* @returns The download URL.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.getDownloadURL('./config.yml')
* .then(console.log)
* .catch(console.error);
* ```
*/
getDownloadURL(path: string): Promise<string>;
/**
* Fetches and saves a file to a specified path on the system.
* @param path The file path.
* @param dest The file path to save the file to.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.download('./config.yml', '/mc/config.yml')
* .catch(console.error);
* ```
*/
download(path: string, dest: string): Promise<void>;
/**
* Fetches the upload URL for a specified directory (defaults to root).
* @param [dir] The directory the files should be uploaded to.
* @returns The upload URL.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.getUploadURL('./plugins')
* .then(console.log)
* .catch(console.error);
* ```
*/
getUploadURL(dir?: string): Promise<string>;
/**
* Uploads a file from the system to a specified directory on the server.
* @param dir The directory the files should be uploaded to.
* @param file The path to the file on the system.
* @todo
*/
private upload;
/**
* Writes the content to a specified file.
* @param path The file path.
* @param content The content to write.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.write(
* './config.yml',
* 'listeners:\n- host: 0.0.0.0:6203\n query_port: 6203'
* )
* .catch(console.error);
* ```
*/
write(path: string, content: any): Promise<void>;
/**
* Creates a folder in a specified root folder.
* @param path The root path to create the directory in.
* @param name The name of the directory.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.createFolder('./', 'ext').catch(console.error);
* ```
*/
createFolder(path: string, name: string): Promise<void>;
/**
* Renames one or more files in a specified directory.
* @param path The root path of the files.
* @param files The file rename descriptors.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.rename(
* './',
* [
* { from: 'install.log', to: 'old-install.log' },
* { from: '_config.yml', to: 'new-config.yml' }
* ]
* )
* .catch(console.error);
* ```
*/
rename(path: string, files: {
from: string;
to: string;
}[]): Promise<void>;
/**
* Changes the permissions on one or more files in a specified directory.
* @param dir The root path of the files.
* @param files The file mode descriptors.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.chmod(
* './',
* [{ file: 'server.jar', mode: 0o755 }]
* )
* .catch(console.error);
* ```
*/
chmod(dir: string, files: FileChmodData[]): Promise<void>;
/**
* Copies the specified file in its directory.
* @param path The path of the file to copy.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.copy('server.properties').catch(console.error);
* ```
*/
copy(path: string): Promise<void>;
/**
* Compresses the specified files into a zip file.
* @param dir The root directory of the files.
* @param files The files to be compressed.
* @returns The compressed files.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.compress(
* './'
* ['server.properties', 'server.jar', 'config.yml']
* )
* .then(console.log)
* .catch(console.error);
* ```
*/
compress(dir: string, files: string[]): Promise<File>;
/**
* Decompresses the specified file in its directory.
* @param dir The root directory of the file.
* @param file The file to decompress.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.decompress('./ext', 'archive-2022-08-25T034234Z.tar.gz')
* .catch(console.error);
* ```
*/
decompress(dir: string, file: string): Promise<void>;
/**
* Deletes one or more files in the specified directory.
* @param dir The root directory of the files.
* @param files The files to delete.
* @example
* ```
* const server = await client.servers.fetch('aea005b6');
* await server.files.delete('./', ['old-install.log'])
* .catch(console.error);
* ```
*/
delete(dir: string, files: string[]): Promise<void>;
}
declare class NetworkManager {
client: PteroClient;
cache: Dict<number, NetworkAllocation>;
serverId: string;
constructor(client: PteroClient, serverId: string);
/**
* Transforms the raw allocation object(s) into typed objects.
* @param data The resolvable allocation object(s).
* @returns The resolved allocation object(s).
*/
_patch(data: any): any;
/**
* Fetches the network allocations on the server.
* @returns The fetched network allocations.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.network.fetch()
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(): Promise<Dict<number, NetworkAllocation>>;
/**
* Sets the notes of a specified network allocation.
* @param id The ID of the network allocation.
* @param notes The notes to set.
* @returns The updated network allocation.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.network.setNote(14, 'bungee')
* .then(console.log)
* .catch(console.error);
* ```
*/
setNote(id: number, notes: string): Promise<NetworkAllocation>;
/**
* Sets the primary allocation of the server.
* @param id The ID of the network allocation.
* @returns The updated network allocation.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.network.setPrimary(14)
* .then(console.log)
* .catch(console.error);
* ```
*/
setPrimary(id: number): Promise<NetworkAllocation>;
/**
* Unassigns the specified network allocation form the server.
* @param id The ID of the network allocation.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.network.unassign(12).catch(console.error);
* ```
*/
unassign(id: number): Promise<void>;
}
declare class SubUserManager {
client: PteroClient;
serverId: string;
cache: Dict<string, SubUser>;
constructor(client: PteroClient, serverId: string);
/**
* Transforms the raw subuser object(s) into class objects.
* @param data The resolvable subuser object(s).
* @returns The resolved subuser object(s).
*/
_patch(data: any): any;
/**
* Resolves a subuser from an object. This can be:
* * a string
* * a number
* * an object
*
* @param obj The object to resolve from.
* @returns The resolved user or undefined if not found.
*/
resolve(obj: Resolvable<SubUser>): SubUser | undefined;
/**
* Returns a formatted URL to the subuser.
* @returns The formatted URL.
*/
get panelURL(): string;
/**
* Fetches a subuser from the API by its UUID. This will check the cache first unless the
* force option is specified.
*
* @param uuid The UUID of the subuser.
* @param [options] Additional fetch options.
* @returns The fetched subuser.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.users.fetch('36de5ed4-8c37-4bde-a1da-4203115a3e9d')
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(uuid: string, options?: FetchOptions): Promise<SubUser>;
/**
* Fetches a list of subusers from the API with the given options (default is undefined).
*
* @param [options] Additional fetch options.
* @returns The fetched subusers.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.users.fetch({ perPage: 10 })
* .then(console.log)
* .catch(console.error);
* ```
*/
fetch(options?: FetchOptions): Promise<Dict<number, SubUser>>;
/**
* Adds a user as a subuser to the server.
* @param email The email of the account to add.
* @param permissions Permissions for the account.
* @returns The new subuser.
* @example
* ```
* const perms = new Permissions(...Permissions.CONTROL, ...Permissions.FILES);
* const server = await client.servers.fetch('1c639a86');
* await server.users.add('user@example.com', perms.value)
* .then(console.log)
* .catch(console.error);
* ```
*/
add(email: string, permissions: string[]): Promise<SubUser>;
/**
* Updates the permissions of a specified subuser.
* @param id The UUID of the subuser.
* @param permissions The permissions to set.
* @returns The updated subuser account.
* @example
* ```
* const perms = new Permissions(...Permissions.FILES, ...Permissions.BACKUPS);
* const server = await client.servers.fetch('1c639a86');
* await server.users.setPermissions(
* '36de5ed4-8c37-4bde-a1da-4203115a3e9d',
* perms.value
* )
* .then(console.log)
* .catch(console.error);
* ```
*/
setPermissions(id: string, permissions: string[]): Promise<SubUser>;
/**
* Removes a subuser's access to the server.
* @param id The UUID of the subuser.
* @example
* ```
* const server = await client.servers.fetch('1c639a86');
* await server.users.remove('9d7b1d20-6e34-4a3a-abcd-c26ae79dc2bd')
* .catch(console.error);
* ```
*/
remove(id: string): Promise<void>;
}
declare class ClientServer {
client: PteroClient;
/** The UUID of the server. */
readonly uuid: string;
/** A substring of the server's UUID. */
readonly identifier: string;
/** The internal ID of the server. */
readonly internalId: number;
/** The name of the server. */
name: string;
/** The description of the server (if set). */
description: string | undefined;
/** Whether the client user is the server owner. */
isOwner: boolean;
/** The name of the node the server is on. */
node: string;
/** An object containing the SFTP details. */
sftpDetails: {
ip: string;
port: number;
};
/** An object containing the server limits. */
limits: Limits;
/** An object containing the server feature limits. */
featureLimits: FeatureLimits;
/** A list of egg features the server uses. */
eggFeatures: string[] | undefined;
/** The invocation (or startup command) for the server. */
invocation: string | null;
/** The docker image the server uses. */
dockerImage: string;
/** The current status of the server. */
status: string | undefined;
/** Whether the server is suspended. */
suspended: boolean;
/** Whether the server is installing. */
installing: boolean;
/** Whether the server is transferring. */
transferring: boolean;
backups: BackupManager;
databases: ClientDatabaseManager;
files: FileManager;
network: NetworkManager;
users: SubUserManager;
constructor(client: PteroClient, data: any);
_patch(data: any): void;
/**
* Returns a formatted URL to the server.
* @returns The formatted URL.
*/
get panelURL(): string;
/**
* Fetches the server resources data.
* @returns The server resources.
*/
fetchResources(): Promise<ClientResources>;
/**
* Fetches the server startup and egg variables data.
* @returns The startup and egg variable data.
* @see {@link StartupData}.
*/
fetchStartup(): Promise<StartupData>;
/**
* Sends a command to the server console.
* @param command The command to send.
*/
sendCommand(command: string): Promise<void>;
/**
* Sets the power state of the server.
* @param state The power state.
*/
setPowerState(state: 'start' | 'stop' | 'restart' | 'kill'): Promise<void>;
/**
* Updates the server's docker image.
* @param image The docker image.
*/
setDockerImage(image: string): Promise<void>;
/**
* Updates a specified environment variable on the server. The key must be
* the environment variable name in capital letters, not the normal
* variable name.
* @param key The environment variable key.
* @param value The value of the environment variable.
* @returns The updated egg variable.
*/
setVariable(key: string, value: string): Promise<EggVariable>;
/**
* Updates the server's name.
* @param name The new server name.
*/
rename(name: string): Promise<void>;
/** Triggers the reinstall process for the server. */
reinstall(): Promise<void>;
/**
* Converts the server into a JSON object, relative to the API
* response object.
* @returns The JSON object.
*/
toJSON(): object;
/** @returns The string representation of the server. */
toString(): string;
}
declare class ClientServerManager extends BaseManager {
client: PteroClient;
cache: Dict<string, ClientServer>;
/** Allowed filter arguments for servers (none). */
get FILTERS(): readonly never[];
/**
* Allowed include arguments for servers:
* * egg
* * subusers
*/
get INCLUDES(): readonly string[];
/** Allowed sort arguments for servers