virtualizorjs 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -0
- package/dist/index.d.cts +502 -0
- package/dist/index.d.mts +49 -24
- package/dist/index.d.ts +49 -24
- package/dist/index.mjs +3 -10
- package/package.json +24 -26
- package/dist/index.js +0 -11
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";const h$1=require("node:http"),m=require("node:https");function _interopDefaultCompat(o){return o&&typeof o=="object"&&"default"in o?o.default:o}const h__default=_interopDefaultCompat(h$1),m__default=_interopDefaultCompat(m),DEFAULT_CONFIG={port:4085,https:!0,rejectUnauthorized:!1,timeout:3e4,debug:!1},DEFAULT_TASK_POLLING={pollIntervalMs:2e3,timeoutMs:12e4};class VirtualizorApiError extends Error{code;details;constructor(e,r,u){super(e),this.name="VirtualizorApiError",this.code=r,this.details=u}format(){return`[API Error ${this.code}] ${this.message}`}}function buildQueryString(o,e,r){const u={};for(const[d,p]of Object.entries(o))p!==void 0&&(u[d]=p);const l=new URLSearchParams;l.set("api","json"),l.set("adminapikey",e),l.set("adminapipass",r);for(const[d,p]of Object.entries(u))l.set(d,String(p));return`?${l.toString()}`}const f=5e3;class HttpClient{constructor(e){this.config=e;const r=e.https?m__default.Agent:h__default.Agent;this.agent=new r({keepAlive:!0,maxSockets:50,maxFreeSockets:10,scheduling:"lifo",...e.https?{rejectUnauthorized:e.rejectUnauthorized}:{}}),this.logger=e.logger}agent;logger;parseResponse(e){if(e.error&&e.error.length>0){const r=e.error[0];if(r)throw new VirtualizorApiError(r.msg,r.code)}return e}async request(e,r={},u={}){const l={act:e,...r},d=buildQueryString(l,this.config.apiKey,this.config.apiPass);if(this.config.debug){const g=d.replace(/adminapikey=[^&]*/,"adminapikey=[REDACTED]").replace(/adminapipass=[^&]*/,"adminapipass=[REDACTED]");this.logger.debug(`Request: act=${e} path=/index.php${g}`)}const p=`/index.php${d}`,y=Object.entries(u).filter(([,g])=>g!==void 0).map(([g,b])=>`${encodeURIComponent(g)}=${encodeURIComponent(String(b))}`).join("&");try{const g=await this.rawRequest(p,y||void 0);return this.parseResponse(g)}catch(g){throw this.config.debug&&(g instanceof VirtualizorApiError?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${g.code}] ${g.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${g.message}`)),g}}validateJsonDepth(e,r=0){if(r>100)throw new VirtualizorApiError("JSON depth limit exceeded",-32e3);if(typeof e=="object"&&e!==null)if(Array.isArray(e))for(const u of e)this.validateJsonDepth(u,r+1);else for(const u of Object.values(e))this.validateJsonDepth(u,r+1)}destroy(){this.agent.destroy()}rawRequest(e,r){const u=this.config.https?m__default:h__default,l={host:this.config.host,port:this.config.port,path:e,method:r?"POST":"GET",headers:{"Content-Type":"application/x-www-form-urlencoded",...r?{"Content-Length":Buffer.byteLength(r)}:{}},agent:this.agent};return new Promise((d,p)=>{const y=u.request(l,w=>{const $=[];w.on("data",q=>{$.push(q)}),w.on("end",()=>{const q=Buffer.concat($).toString("utf8");if(w.statusCode===302||w.statusCode===301){p(new VirtualizorApiError(`Redirect detected (status ${w.statusCode}). Authentication failed. Location: ${w.headers.location}`,w.statusCode));return}try{const v=JSON.parse(q);this.validateJsonDepth(v),d(v)}catch(v){this.config.debug&&(v instanceof VirtualizorApiError?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${v.code}] ${v.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${v.message}`)),p(new VirtualizorApiError(`Failed to parse response: ${v.message??"Invalid JSON"}`,-32700))}}),w.on("error",q=>{this.config.debug&&this.logger.error("[Virtualizor] \u25CF Error: Response stream error",q),p(new VirtualizorApiError(`Response stream error: ${q.message??"Unknown error"}`,-32e3))})}),g=setTimeout(()=>{y.destroy(new VirtualizorApiError(`Connection timeout after ${f}ms`,-32e3))},f),b=setTimeout(()=>{y.destroy(new VirtualizorApiError(`Request timed out after ${this.config.timeout}ms`,-32e3))},this.config.timeout);y.once("socket",w=>{w.connecting?w.once("connect",()=>clearTimeout(g)):clearTimeout(g)}),y.once("close",()=>{clearTimeout(g),clearTimeout(b)}),y.on("error",w=>{w instanceof VirtualizorApiError?p(w):p(new VirtualizorApiError(`Request error ${w}`,-32e3))}),r&&y.write(r),y.end()})}}const n$1=process.platform==="win32",t=process.env.NO_COLOR===void 0&&process.stdout.isTTY;function s(o,e){return t?`\x1B[${o}m${e}\x1B[0m`:e}const colors={red:o=>s(31,o),green:o=>s(32,o),yellow:o=>s(33,o),blue:o=>s(34,o),cyan:o=>s(36,o),dim:o=>s(2,o)},symbols={success:n$1?"\u221A":"\u2714",error:n$1?"\xD7":"\u2716",warning:n$1?"\u203C":"\u26A0",info:n$1?"i":"\u2139",bullet:"\u25CF",arrow:"\u2192",chevron:"\u203A",pointer:"\u276F",star:"\u2605"};class ConsoleLogger{constructor(e="Virtualizor"){this.prefix=e}timestamp(){const e=new Date().toISOString().split("T")[1];return colors.dim(e?e.slice(0,8):"00:00:00")}tag(){return colors.cyan(`[${this.prefix}]`)}debug(e,...r){console.log(this.timestamp(),this.tag(),colors.dim(symbols.bullet),colors.dim(e),...r)}info(e,...r){console.log(this.timestamp(),this.tag(),colors.blue(symbols.info),e,...r)}warn(e,...r){console.log(this.timestamp(),this.tag(),colors.yellow(symbols.warning),colors.yellow(e),...r)}error(e,r){console.error(this.timestamp(),this.tag(),colors.red(symbols.error),colors.red(e)),r?.stack&&console.error(colors.dim(r.stack.split(`
|
|
2
|
+
`).slice(1,4).join(`
|
|
3
|
+
`)))}success(e,...r){console.log(this.timestamp(),this.tag(),colors.green(symbols.success),colors.green(e),...r)}}const defaultLogger=new ConsoleLogger;function formatError(o,e=!1){if(o instanceof VirtualizorApiError){const r=o.details&&e?`
|
|
4
|
+
${colors.dim(JSON.stringify(o.details,null,2))}`:"";return`${symbols.error} ${colors.red(`[API Error ${o.code}]`)} ${o.message}${r}`}return`${symbols.error} ${colors.red(o.message)}`}class PlansResource{constructor(e){this.http=e}async list(){return(await this.http.request("plans",{},{})).plans}async create(e){return this.http.request("addplan",{},e)}async delete(e){return this.http.request("plans",{},{delete:e})}async get(e){const r=(await this.http.request("plans",{},{})).plans[e];if(!r)throw new VirtualizorApiError("Plan not found",404);return r}async update(e){return this.http.request("editplan",{},e)}}class TasksResource{constructor(e){this.http=e}async get(e){return(await this.http.request("tasks",{taskid:e},{})).tasks[e]}async wait(e,r={}){const{pollIntervalMs:u=DEFAULT_TASK_POLLING.pollIntervalMs,timeoutMs:l=DEFAULT_TASK_POLLING.timeoutMs}=r,d=Date.now()+l;for(;Date.now()<d;){const p=await this.get(e);if(!p)throw new VirtualizorApiError("Task not found",404);if(p.status==="1"||p.status==="done")return p;if(p.status==="error"||p.status==="-1")throw new VirtualizorApiError("Task failed",500);await new Promise(y=>setTimeout(y,u))}throw new VirtualizorApiError(`Task timed out after ${l}ms`,408)}}class UsersResource{constructor(e){this.http=e}async list(){return(await this.http.request("users",{},{})).users}async create(e){return this.http.request("adduser",{},e)}async delete(e){return this.http.request("users",{},{delete:e})}async suspend(e){return this.http.request("users",{},{suspend:e})}async unsuspend(e){return this.http.request("users",{},{unsuspend:e})}async get(e){const r=(await this.http.request("users",{},{uid:e})).user[e];if(!r)throw new VirtualizorApiError("User not found",404);return r}async update(e){return this.http.request("edituser",{},e)}}const VPS_CONSTANTS={REBUILD_REOS_FLAG:1,MIGRATE_FLAG:1,MIGRATE_BUT_FLAG:1};class VpsResource{constructor(e){this.http=e}async list(e={}){return(await this.http.request("vs",{},e)).vs??{}}async get(e){const r=await this.http.request("vs",{},e),u=Object.entries(r.vs??{});if(u.length===0)throw new VirtualizorApiError("VPS not found",404);const l=u[0];if(!l)throw new VirtualizorApiError("VPS not found",404);const[,d]=l;return d}async create(e){return this.http.request("addvs",{},e)}async delete(e){return this.http.request("vs",{delete:e},{})}async start(e){return this.http.request("vs",{vpsid:e,action:"start"},{})}async stop(e){return this.http.request("vs",{vpsid:e,action:"stop"},{})}async restart(e){return this.http.request("vs",{vpsid:e,action:"restart"},{})}async poweroff(e){return this.http.request("vs",{vpsid:e,action:"poweroff"},{})}async suspend(e){return this.http.request("vs",{suspend:e},{})}async unsuspend(e){return this.http.request("vs",{unsuspend:e},{})}async rebuild(e,r){return this.http.request("rebuild",{},{vpsid:e,reos:VPS_CONSTANTS.REBUILD_REOS_FLAG,...r})}async clone(e,r){return this.http.request("clone",{},{vpsid:e,...r})}async migrate(e,r){return this.http.request("migrate",{},{vpsid:e,migrate:VPS_CONSTANTS.MIGRATE_FLAG,migrate_but:VPS_CONSTANTS.MIGRATE_BUT_FLAG,...r})}async status(e){return this.http.request("vstatus",{vpsid:e},{})}async vnc(e){return this.http.request("vnc",{vpsid:e},{})}async stats(e){return this.http.request("vps_stats",{},{vpsid:e})}}const i="https://registry.npmjs.org/virtualizorjs/latest";async function a(o){const e=new AbortController,r=setTimeout(()=>e.abort(),o);try{const u=await fetch(i,{signal:e.signal});if(!u.ok)throw new Error(`HTTP ${u.status}`);return await u.json()}finally{clearTimeout(r)}}function c(o,e){const r=o.split(".").map(Number),u=e.split(".").map(Number);return(u[0]??0)>(r[0]??0)||(u[0]??0)===(r[0]??0)&&(u[1]??0)>(r[1]??0)||(u[0]??0)===(r[0]??0)&&(u[1]??0)===(r[1]??0)&&(u[2]??0)>(r[2]??0)}let n=!1;async function checkForUpdates(o,e,r){if(!n){n=!0;try{const u=(await a(r?.timeout??2e3)).version;if(!c(o,u))return;e.warn(`Update available: ${o} \u2192 ${u}`),e.warn('Run "npm install virtualizorjs@latest" to update')}catch{}}}const h=require("../package.json").version;class VirtualizorClient{vps;users;plans;tasks;logger;constructor(e){const r=e.logger??defaultLogger;this.logger=r;const u={host:e.host,apiKey:e.apiKey,apiPass:e.apiPass??"",port:e.port??DEFAULT_CONFIG.port,https:e.https??DEFAULT_CONFIG.https,rejectUnauthorized:e.rejectUnauthorized??DEFAULT_CONFIG.rejectUnauthorized,timeout:e.timeout??DEFAULT_CONFIG.timeout,debug:e.debug??DEFAULT_CONFIG.debug,logger:r,disableUpdateCheck:e.disableUpdateCheck??!1},l=new HttpClient(u);this.vps=new VpsResource(l),this.users=new UsersResource(l),this.plans=new PlansResource(l),this.tasks=new TasksResource(l),u.disableUpdateCheck||checkForUpdates(h,r).catch(()=>{})}}function createVirtualizorClient(o){return new VirtualizorClient(o)}function formatIps(o,e){const r=e?.as??"array",u=e?.separator??", ";if(!o)return r==="array"?[]:"";let l=[];if(Array.isArray(o))l=o.filter(Boolean);else if(typeof o=="string"){const d=o.trim();d===""?l=[]:d.includes(",")?l=d.split(",").map(p=>p.trim()).filter(Boolean):/\s+/.test(d)?l=d.split(/\s+/).map(p=>p.trim()).filter(Boolean):l=[d]}else typeof o=="object"&&(l=Object.values(o).filter(Boolean));return r==="array"?l:l.join(u)}exports.ConsoleLogger=ConsoleLogger;exports.VirtualizorApiError=VirtualizorApiError;exports.VirtualizorClient=VirtualizorClient;exports.colors=colors;exports.createVirtualizorClient=createVirtualizorClient;exports.defaultLogger=defaultLogger;exports.formatError=formatError;exports.formatIps=formatIps;exports.symbols=symbols;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
declare class VirtualizorApiError extends Error {
|
|
2
|
+
readonly code: number;
|
|
3
|
+
readonly details: Record<string, unknown> | undefined;
|
|
4
|
+
constructor(message: string, code: number, details?: Record<string, unknown>);
|
|
5
|
+
format(): string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface Logger {
|
|
9
|
+
debug(message: string, ...args: unknown[]): void;
|
|
10
|
+
info(message: string, ...args: unknown[]): void;
|
|
11
|
+
warn(message: string, ...args: unknown[]): void;
|
|
12
|
+
error(message: string, error?: Error): void;
|
|
13
|
+
success?(message: string, ...args: unknown[]): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
declare class ConsoleLogger implements Logger {
|
|
17
|
+
private readonly prefix;
|
|
18
|
+
constructor(prefix?: string);
|
|
19
|
+
private timestamp;
|
|
20
|
+
private tag;
|
|
21
|
+
debug(message: string, ...args: unknown[]): void;
|
|
22
|
+
info(message: string, ...args: unknown[]): void;
|
|
23
|
+
warn(message: string, ...args: unknown[]): void;
|
|
24
|
+
error(message: string, error?: Error): void;
|
|
25
|
+
success(message: string, ...args: unknown[]): void;
|
|
26
|
+
}
|
|
27
|
+
declare const defaultLogger: ConsoleLogger;
|
|
28
|
+
|
|
29
|
+
declare function formatError(error: Error, verbose?: boolean): string;
|
|
30
|
+
|
|
31
|
+
declare const colors: {
|
|
32
|
+
red: (str: string) => string;
|
|
33
|
+
green: (str: string) => string;
|
|
34
|
+
yellow: (str: string) => string;
|
|
35
|
+
blue: (str: string) => string;
|
|
36
|
+
cyan: (str: string) => string;
|
|
37
|
+
dim: (str: string) => string;
|
|
38
|
+
};
|
|
39
|
+
declare const symbols: {
|
|
40
|
+
success: string;
|
|
41
|
+
error: string;
|
|
42
|
+
warning: string;
|
|
43
|
+
info: string;
|
|
44
|
+
bullet: string;
|
|
45
|
+
arrow: string;
|
|
46
|
+
chevron: string;
|
|
47
|
+
pointer: string;
|
|
48
|
+
star: string;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
interface VirtualizorError {
|
|
52
|
+
code: number;
|
|
53
|
+
msg: string;
|
|
54
|
+
}
|
|
55
|
+
interface VirtualizorResponse {
|
|
56
|
+
title?: string;
|
|
57
|
+
timenow?: number;
|
|
58
|
+
time_taken?: string;
|
|
59
|
+
error?: VirtualizorError[];
|
|
60
|
+
}
|
|
61
|
+
interface AsyncTaskResult extends VirtualizorResponse {
|
|
62
|
+
done?: 1;
|
|
63
|
+
taskid?: string;
|
|
64
|
+
}
|
|
65
|
+
type VirtType = 'kvm' | 'xen' | 'openvz' | 'lxc' | 'proxmox' | 'virtuozzo' | 'xcp' | 'hyperv';
|
|
66
|
+
type ApiParams = Record<string, unknown>;
|
|
67
|
+
|
|
68
|
+
interface VirtualizorConfig {
|
|
69
|
+
host: string;
|
|
70
|
+
apiKey: string;
|
|
71
|
+
apiPass?: string;
|
|
72
|
+
port?: number;
|
|
73
|
+
https?: boolean;
|
|
74
|
+
rejectUnauthorized?: boolean;
|
|
75
|
+
timeout?: number;
|
|
76
|
+
debug?: boolean;
|
|
77
|
+
logger?: Logger;
|
|
78
|
+
disableUpdateCheck?: boolean;
|
|
79
|
+
}
|
|
80
|
+
interface ResolvedConfig {
|
|
81
|
+
host: string;
|
|
82
|
+
apiKey: string;
|
|
83
|
+
apiPass: string;
|
|
84
|
+
port: number;
|
|
85
|
+
https: boolean;
|
|
86
|
+
rejectUnauthorized: boolean;
|
|
87
|
+
timeout: number;
|
|
88
|
+
debug: boolean;
|
|
89
|
+
logger: Logger;
|
|
90
|
+
disableUpdateCheck: boolean;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
declare class HttpClient {
|
|
94
|
+
private readonly config;
|
|
95
|
+
private readonly agent;
|
|
96
|
+
private readonly logger;
|
|
97
|
+
constructor(config: ResolvedConfig);
|
|
98
|
+
parseResponse<T extends VirtualizorResponse>(data: T): T;
|
|
99
|
+
request<T extends VirtualizorResponse>(act: string, queryParams?: ApiParams, bodyParams?: ApiParams): Promise<T>;
|
|
100
|
+
private validateJsonDepth;
|
|
101
|
+
destroy(): void;
|
|
102
|
+
private rawRequest;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface Plan {
|
|
106
|
+
pid: string;
|
|
107
|
+
plan_name: string;
|
|
108
|
+
disk: string;
|
|
109
|
+
ram: string;
|
|
110
|
+
bandwidth: string;
|
|
111
|
+
cpu: string;
|
|
112
|
+
virt?: string;
|
|
113
|
+
}
|
|
114
|
+
interface CreatePlanParams {
|
|
115
|
+
plan_name: string;
|
|
116
|
+
disk: number;
|
|
117
|
+
ram: number;
|
|
118
|
+
bandwidth: number;
|
|
119
|
+
cpu: number;
|
|
120
|
+
virt?: string;
|
|
121
|
+
[key: string]: unknown;
|
|
122
|
+
}
|
|
123
|
+
interface UpdatePlanParams {
|
|
124
|
+
pid: string;
|
|
125
|
+
plan_name?: string;
|
|
126
|
+
disk?: number;
|
|
127
|
+
ram?: number;
|
|
128
|
+
bandwidth?: number;
|
|
129
|
+
cpu?: number;
|
|
130
|
+
virt?: string;
|
|
131
|
+
[key: string]: unknown;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
declare class PlansResource {
|
|
135
|
+
private readonly http;
|
|
136
|
+
constructor(http: HttpClient);
|
|
137
|
+
list(): Promise<Record<string, Plan>>;
|
|
138
|
+
create(params: CreatePlanParams): Promise<AsyncTaskResult>;
|
|
139
|
+
delete(planId: string): Promise<AsyncTaskResult>;
|
|
140
|
+
get(planId: string): Promise<Plan>;
|
|
141
|
+
update(params: UpdatePlanParams): Promise<AsyncTaskResult>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface Task {
|
|
145
|
+
id: string;
|
|
146
|
+
action: string;
|
|
147
|
+
status: string;
|
|
148
|
+
vpsid?: string;
|
|
149
|
+
data?: unknown;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
declare class TasksResource {
|
|
153
|
+
private readonly http;
|
|
154
|
+
constructor(http: HttpClient);
|
|
155
|
+
get(taskId: string): Promise<Task | undefined>;
|
|
156
|
+
wait(taskId: string, options?: {
|
|
157
|
+
pollIntervalMs?: number;
|
|
158
|
+
timeoutMs?: number;
|
|
159
|
+
}): Promise<Task>;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
interface User {
|
|
163
|
+
uid: string;
|
|
164
|
+
email: string;
|
|
165
|
+
fname?: string;
|
|
166
|
+
lname?: string;
|
|
167
|
+
status: string;
|
|
168
|
+
type: string;
|
|
169
|
+
}
|
|
170
|
+
interface CreateUserParams {
|
|
171
|
+
email: string;
|
|
172
|
+
password: string;
|
|
173
|
+
fname?: string;
|
|
174
|
+
lname?: string;
|
|
175
|
+
acttype?: number;
|
|
176
|
+
[key: string]: unknown;
|
|
177
|
+
}
|
|
178
|
+
interface UpdateUserParams {
|
|
179
|
+
uid: string;
|
|
180
|
+
email?: string;
|
|
181
|
+
password?: string;
|
|
182
|
+
fname?: string;
|
|
183
|
+
lname?: string;
|
|
184
|
+
status?: string;
|
|
185
|
+
acttype?: number;
|
|
186
|
+
[key: string]: unknown;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
declare class UsersResource {
|
|
190
|
+
private readonly http;
|
|
191
|
+
constructor(http: HttpClient);
|
|
192
|
+
list(): Promise<Record<string, User>>;
|
|
193
|
+
create(params: CreateUserParams): Promise<AsyncTaskResult>;
|
|
194
|
+
delete(uid: string): Promise<AsyncTaskResult>;
|
|
195
|
+
suspend(uid: string): Promise<AsyncTaskResult>;
|
|
196
|
+
unsuspend(uid: string): Promise<AsyncTaskResult>;
|
|
197
|
+
get(uid: string): Promise<User>;
|
|
198
|
+
update(params: UpdateUserParams): Promise<AsyncTaskResult>;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
interface VPSData {
|
|
202
|
+
os_type?: number | string;
|
|
203
|
+
rtc?: number | string;
|
|
204
|
+
unprivileged?: number | string;
|
|
205
|
+
vnc_auto_port?: number | string;
|
|
206
|
+
nested_virt?: number | string;
|
|
207
|
+
vga_vram?: number | string;
|
|
208
|
+
discard?: number | string;
|
|
209
|
+
vlan_tag?: number | string;
|
|
210
|
+
enable_guest_agent?: number | string;
|
|
211
|
+
ssd_emulation?: number | string;
|
|
212
|
+
machine_type?: number | string;
|
|
213
|
+
bios?: string;
|
|
214
|
+
enable_tpm?: number | string;
|
|
215
|
+
disable_password?: string;
|
|
216
|
+
ssh_options?: string;
|
|
217
|
+
added_keys?: unknown[];
|
|
218
|
+
io_uring?: number | string;
|
|
219
|
+
min_ram?: number | string;
|
|
220
|
+
vga?: number | string;
|
|
221
|
+
vga_memory?: number | string;
|
|
222
|
+
cpu_flags?: number | string;
|
|
223
|
+
scsi_controller?: number | string;
|
|
224
|
+
demo?: string | null;
|
|
225
|
+
enable_cpu_threshold?: number | string;
|
|
226
|
+
cpu_threshold?: number | string;
|
|
227
|
+
cpu_threshold_time?: number | string;
|
|
228
|
+
disable_guest_agent?: number | string;
|
|
229
|
+
disable_autostart?: number | string;
|
|
230
|
+
iothread?: number | string;
|
|
231
|
+
nesting?: number | string;
|
|
232
|
+
suspended_time?: number | string;
|
|
233
|
+
multiqueue?: number | string;
|
|
234
|
+
freeze_fs_on_backup?: number | string;
|
|
235
|
+
enable_ver_scaling?: number | string;
|
|
236
|
+
ver_max_ram?: string | number;
|
|
237
|
+
ver_ram_threshold?: string | number;
|
|
238
|
+
ver_ram_inc_by?: string | number;
|
|
239
|
+
ver_max_cpu?: string | number;
|
|
240
|
+
ver_cpu_threshold?: string | number;
|
|
241
|
+
ver_cpu_inc_by?: string | number;
|
|
242
|
+
random_ipv6?: number | string;
|
|
243
|
+
encrypted_pass?: number | string;
|
|
244
|
+
vm_admin_name?: string;
|
|
245
|
+
crypted_pass?: string | null;
|
|
246
|
+
crypted_salt?: string | null;
|
|
247
|
+
custom_ipv6_on_edit?: number | string;
|
|
248
|
+
docker_info?: unknown | null;
|
|
249
|
+
}
|
|
250
|
+
interface VPS {
|
|
251
|
+
vpsid: string;
|
|
252
|
+
vps_name?: string;
|
|
253
|
+
uuid?: string;
|
|
254
|
+
serid?: string | number;
|
|
255
|
+
time?: string | number;
|
|
256
|
+
edittime?: string | number;
|
|
257
|
+
virt?: VirtType | string;
|
|
258
|
+
uid?: string | number;
|
|
259
|
+
plid?: string | number;
|
|
260
|
+
hostname: string;
|
|
261
|
+
osid?: string | number;
|
|
262
|
+
os_name: string;
|
|
263
|
+
iso?: string;
|
|
264
|
+
sec_iso?: string;
|
|
265
|
+
boot?: string;
|
|
266
|
+
space?: string | number;
|
|
267
|
+
inodes?: string | number;
|
|
268
|
+
ram: string;
|
|
269
|
+
burst?: string | number;
|
|
270
|
+
swap?: string | number;
|
|
271
|
+
cpu?: string | number;
|
|
272
|
+
cores?: string | number;
|
|
273
|
+
cpupin?: string | number;
|
|
274
|
+
cpu_percent?: string | number;
|
|
275
|
+
bandwidth: string;
|
|
276
|
+
network_speed?: string | number;
|
|
277
|
+
upload_speed?: string | number;
|
|
278
|
+
io?: string | number;
|
|
279
|
+
ubc?: string;
|
|
280
|
+
acpi?: string | number;
|
|
281
|
+
apic?: string | number;
|
|
282
|
+
pae?: string | number;
|
|
283
|
+
shadow?: string | number;
|
|
284
|
+
vnc?: string | number;
|
|
285
|
+
vncport?: string | number;
|
|
286
|
+
vnc_passwd?: string;
|
|
287
|
+
hvm?: string | number;
|
|
288
|
+
suspended?: string | number;
|
|
289
|
+
suspend_reason?: string | null;
|
|
290
|
+
nw_suspended?: string | null;
|
|
291
|
+
rescue?: string | number;
|
|
292
|
+
band_suspend?: string | number;
|
|
293
|
+
tuntap?: string | number;
|
|
294
|
+
ppp?: string | number;
|
|
295
|
+
ploop?: string | number;
|
|
296
|
+
dns_nameserver?: string;
|
|
297
|
+
osreinstall_limit?: string | number;
|
|
298
|
+
preferences?: unknown | null;
|
|
299
|
+
nic_type?: string;
|
|
300
|
+
vif_type?: string;
|
|
301
|
+
virtio?: string | number;
|
|
302
|
+
pv_on_hvm?: string | number;
|
|
303
|
+
disks?: unknown | null;
|
|
304
|
+
kvm_cache?: string | number;
|
|
305
|
+
io_mode?: string | number;
|
|
306
|
+
cpu_mode?: string;
|
|
307
|
+
total_iops_sec?: string | number;
|
|
308
|
+
read_bytes_sec?: string | number;
|
|
309
|
+
write_bytes_sec?: string | number;
|
|
310
|
+
kvm_vga?: string | number;
|
|
311
|
+
acceleration?: string | number;
|
|
312
|
+
vnc_keymap?: string;
|
|
313
|
+
routing?: string | number;
|
|
314
|
+
mg?: string;
|
|
315
|
+
used_bandwidth?: string | number;
|
|
316
|
+
cached_disk?: unknown;
|
|
317
|
+
webuzo?: string | number;
|
|
318
|
+
disable_ebtables?: string | number;
|
|
319
|
+
install_xentools?: string | number;
|
|
320
|
+
admin_managed?: string | number;
|
|
321
|
+
rdp?: string | number;
|
|
322
|
+
topology_sockets?: string | number;
|
|
323
|
+
topology_cores?: string | number;
|
|
324
|
+
topology_threads?: string | number;
|
|
325
|
+
mac?: string;
|
|
326
|
+
notes?: string | null;
|
|
327
|
+
disable_nw_config?: string | number;
|
|
328
|
+
locked?: string;
|
|
329
|
+
openvz_features?: string;
|
|
330
|
+
speed_cap?: string;
|
|
331
|
+
numa?: string | number;
|
|
332
|
+
bpid?: string | number;
|
|
333
|
+
bserid?: string | number;
|
|
334
|
+
timezone?: string | null;
|
|
335
|
+
ha?: string | number;
|
|
336
|
+
load_balancer?: string | number;
|
|
337
|
+
data?: VPSData;
|
|
338
|
+
fwid?: string | number;
|
|
339
|
+
admin_fwid?: string | number;
|
|
340
|
+
current_resource?: unknown | null;
|
|
341
|
+
plan_expiry?: string | number;
|
|
342
|
+
machine_status?: string | number;
|
|
343
|
+
tags?: string | null;
|
|
344
|
+
server_name?: string;
|
|
345
|
+
email?: string;
|
|
346
|
+
pid?: string | number;
|
|
347
|
+
type?: string | number;
|
|
348
|
+
os_distro?: string;
|
|
349
|
+
stid?: number[];
|
|
350
|
+
ips?: Record<string, string>;
|
|
351
|
+
}
|
|
352
|
+
interface ListVPSParams {
|
|
353
|
+
user?: string | number;
|
|
354
|
+
vpsid?: string | number;
|
|
355
|
+
vpsname?: string;
|
|
356
|
+
vpsip?: string;
|
|
357
|
+
vpshostname?: string;
|
|
358
|
+
vsstatus?: string;
|
|
359
|
+
vstype?: VirtType;
|
|
360
|
+
serid?: number;
|
|
361
|
+
plid?: number;
|
|
362
|
+
bpid?: number;
|
|
363
|
+
[key: string]: unknown;
|
|
364
|
+
}
|
|
365
|
+
interface CreateVPSParams {
|
|
366
|
+
hostname: string;
|
|
367
|
+
rootpass: string;
|
|
368
|
+
osid: number;
|
|
369
|
+
plid?: number;
|
|
370
|
+
user_email?: string;
|
|
371
|
+
ips?: number;
|
|
372
|
+
ips_int?: number;
|
|
373
|
+
space?: number;
|
|
374
|
+
ram?: number;
|
|
375
|
+
burst?: number;
|
|
376
|
+
bandwidth?: number;
|
|
377
|
+
cpu?: number;
|
|
378
|
+
cpu_percent?: number;
|
|
379
|
+
virt?: VirtType;
|
|
380
|
+
serid?: number;
|
|
381
|
+
node_select?: 0 | 1;
|
|
382
|
+
recipe?: number;
|
|
383
|
+
sshkey?: string;
|
|
384
|
+
nopassword?: 0 | 1;
|
|
385
|
+
[key: string]: unknown;
|
|
386
|
+
}
|
|
387
|
+
interface RebuildVPSParams {
|
|
388
|
+
osid: number;
|
|
389
|
+
newpass: string;
|
|
390
|
+
/** Must be set to 1 to confirm the rebuild */
|
|
391
|
+
conf: 1;
|
|
392
|
+
/** Format primary disk (0 = no, 1 = yes); defaults to 0 */
|
|
393
|
+
format_primary?: 0 | 1;
|
|
394
|
+
/** Send rebuild notification email (0 = no, 1 = yes) */
|
|
395
|
+
eu_send_rebuild_email?: 0 | 1;
|
|
396
|
+
recipe?: number;
|
|
397
|
+
sshkey?: string;
|
|
398
|
+
}
|
|
399
|
+
interface CloneVPSParams {
|
|
400
|
+
hostname: string;
|
|
401
|
+
rootpass: string;
|
|
402
|
+
from_server: number;
|
|
403
|
+
to_server: number;
|
|
404
|
+
}
|
|
405
|
+
interface MigrateVPSParams {
|
|
406
|
+
/** Destination server ID */
|
|
407
|
+
serid: number;
|
|
408
|
+
/** Source server IP address */
|
|
409
|
+
from_ip: string;
|
|
410
|
+
/** Source server API/root password */
|
|
411
|
+
from_pass: string;
|
|
412
|
+
/** 0 = ignore VDF conflicts, 1 = error on conflict */
|
|
413
|
+
ignore_if_vdfconflict?: 0 | 1;
|
|
414
|
+
/** 0 = use gzip compression, 1 = disable gzip */
|
|
415
|
+
disable_gzip?: 0 | 1;
|
|
416
|
+
/** 0 = offline migration, 1 = live migration */
|
|
417
|
+
online?: 0 | 1;
|
|
418
|
+
}
|
|
419
|
+
interface VPSStatsResponse extends VirtualizorResponse {
|
|
420
|
+
vs_stats?: unknown;
|
|
421
|
+
vs_bandwidth?: unknown;
|
|
422
|
+
time_taken?: string;
|
|
423
|
+
}
|
|
424
|
+
interface VNCInfo extends VirtualizorResponse {
|
|
425
|
+
novnc?: string;
|
|
426
|
+
[key: string]: unknown;
|
|
427
|
+
}
|
|
428
|
+
interface VPSStatusInfo {
|
|
429
|
+
status: number;
|
|
430
|
+
used_cpu?: string;
|
|
431
|
+
used_ram?: number;
|
|
432
|
+
used_disk?: number;
|
|
433
|
+
net_in?: number;
|
|
434
|
+
net_out?: number;
|
|
435
|
+
used_inode?: string;
|
|
436
|
+
io_read?: number;
|
|
437
|
+
io_write?: number;
|
|
438
|
+
inode?: number;
|
|
439
|
+
ram?: string;
|
|
440
|
+
disk?: string;
|
|
441
|
+
used_bandwidth?: string;
|
|
442
|
+
bandwidth?: string;
|
|
443
|
+
virt?: string;
|
|
444
|
+
}
|
|
445
|
+
interface VPSStatusResponse extends VirtualizorResponse {
|
|
446
|
+
[key: string]: VPSStatusInfo | unknown;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
declare class VpsResource {
|
|
450
|
+
private readonly http;
|
|
451
|
+
constructor(http: HttpClient);
|
|
452
|
+
list(filters?: ListVPSParams): Promise<Record<string, VPS>>;
|
|
453
|
+
get(filters: ListVPSParams): Promise<VPS>;
|
|
454
|
+
create(params: CreateVPSParams): Promise<AsyncTaskResult>;
|
|
455
|
+
delete(vpsId: string): Promise<AsyncTaskResult>;
|
|
456
|
+
start(vpsId: string): Promise<AsyncTaskResult>;
|
|
457
|
+
stop(vpsId: string): Promise<AsyncTaskResult>;
|
|
458
|
+
restart(vpsId: string): Promise<AsyncTaskResult>;
|
|
459
|
+
poweroff(vpsId: string): Promise<AsyncTaskResult>;
|
|
460
|
+
suspend(vpsId: string): Promise<AsyncTaskResult>;
|
|
461
|
+
unsuspend(vpsId: string): Promise<AsyncTaskResult>;
|
|
462
|
+
rebuild(vpsId: string, params: RebuildVPSParams): Promise<AsyncTaskResult>;
|
|
463
|
+
clone(vpsId: string, params: CloneVPSParams): Promise<AsyncTaskResult>;
|
|
464
|
+
migrate(vpsId: string, params: MigrateVPSParams): Promise<AsyncTaskResult>;
|
|
465
|
+
status(vpsId: string): Promise<VPSStatusResponse>;
|
|
466
|
+
vnc(vpsId: string): Promise<VNCInfo>;
|
|
467
|
+
stats(vpsId: string): Promise<VPSStatsResponse>;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
declare class VirtualizorClient {
|
|
471
|
+
readonly vps: VpsResource;
|
|
472
|
+
readonly users: UsersResource;
|
|
473
|
+
readonly plans: PlansResource;
|
|
474
|
+
readonly tasks: TasksResource;
|
|
475
|
+
readonly logger: Logger;
|
|
476
|
+
constructor(config: VirtualizorConfig);
|
|
477
|
+
}
|
|
478
|
+
declare function createVirtualizorClient(config: VirtualizorConfig): VirtualizorClient;
|
|
479
|
+
|
|
480
|
+
type IpsInput = string[] | Record<string, string> | string | undefined | null;
|
|
481
|
+
type FormatIpsOptions = {
|
|
482
|
+
/**
|
|
483
|
+
* Choose the return type. Defaults to 'array'.
|
|
484
|
+
* - 'array' returns string[]
|
|
485
|
+
* - 'string' returns a joined string using `separator`
|
|
486
|
+
*/
|
|
487
|
+
as?: 'array' | 'string';
|
|
488
|
+
/** Separator used when returning a string. Defaults to ', '. */
|
|
489
|
+
separator?: string;
|
|
490
|
+
};
|
|
491
|
+
/**
|
|
492
|
+
* formatIps
|
|
493
|
+
* - Default behavior: return an array of IP strings (string[])
|
|
494
|
+
* - If options.as === 'string' it returns a joined string using options.separator
|
|
495
|
+
*/
|
|
496
|
+
declare function formatIps(ips: IpsInput): string[];
|
|
497
|
+
declare function formatIps(ips: IpsInput, options: FormatIpsOptions & {
|
|
498
|
+
as: 'string';
|
|
499
|
+
}): string;
|
|
500
|
+
|
|
501
|
+
export { ConsoleLogger, VirtualizorApiError, VirtualizorClient, colors, createVirtualizorClient, defaultLogger, formatError, formatIps, symbols };
|
|
502
|
+
export type { AsyncTaskResult, CloneVPSParams, CreatePlanParams, CreateUserParams, CreateVPSParams, IpsInput, ListVPSParams, Logger, MigrateVPSParams, Plan, RebuildVPSParams, Task, UpdatePlanParams, UpdateUserParams, User, VNCInfo, VPS, VPSStatsResponse, VPSStatusInfo, VPSStatusResponse, VirtType, VirtualizorConfig };
|
package/dist/index.d.mts
CHANGED
|
@@ -26,23 +26,15 @@ declare class ConsoleLogger implements Logger {
|
|
|
26
26
|
}
|
|
27
27
|
declare const defaultLogger: ConsoleLogger;
|
|
28
28
|
|
|
29
|
+
declare function formatError(error: Error, verbose?: boolean): string;
|
|
30
|
+
|
|
29
31
|
declare const colors: {
|
|
30
32
|
red: (str: string) => string;
|
|
31
33
|
green: (str: string) => string;
|
|
32
34
|
yellow: (str: string) => string;
|
|
33
35
|
blue: (str: string) => string;
|
|
34
|
-
magenta: (str: string) => string;
|
|
35
36
|
cyan: (str: string) => string;
|
|
36
|
-
white: (str: string) => string;
|
|
37
|
-
gray: (str: string) => string;
|
|
38
37
|
dim: (str: string) => string;
|
|
39
|
-
bold: (str: string) => string;
|
|
40
|
-
underline: (str: string) => string;
|
|
41
|
-
bgRed: (str: string) => string;
|
|
42
|
-
bgGreen: (str: string) => string;
|
|
43
|
-
bgYellow: (str: string) => string;
|
|
44
|
-
bgBlue: (str: string) => string;
|
|
45
|
-
bgCyan: (str: string) => string;
|
|
46
38
|
};
|
|
47
39
|
declare const symbols: {
|
|
48
40
|
success: string;
|
|
@@ -56,18 +48,6 @@ declare const symbols: {
|
|
|
56
48
|
star: string;
|
|
57
49
|
};
|
|
58
50
|
|
|
59
|
-
interface BoxOptions {
|
|
60
|
-
title?: string;
|
|
61
|
-
borderColor?: 'cyan' | 'yellow' | 'red' | 'green' | 'blue' | 'magenta';
|
|
62
|
-
padding?: number;
|
|
63
|
-
margin?: number;
|
|
64
|
-
}
|
|
65
|
-
declare function createBox(content: string, options?: BoxOptions): string;
|
|
66
|
-
declare function createUpdateBox(current: string, latest: string): string;
|
|
67
|
-
declare function createErrorBox(title: string, message: string, hint?: string): string;
|
|
68
|
-
|
|
69
|
-
declare function formatError(error: Error, verbose?: boolean): string;
|
|
70
|
-
|
|
71
51
|
interface VirtualizorError {
|
|
72
52
|
code: number;
|
|
73
53
|
msg: string;
|
|
@@ -140,6 +120,16 @@ interface CreatePlanParams {
|
|
|
140
120
|
virt?: string;
|
|
141
121
|
[key: string]: unknown;
|
|
142
122
|
}
|
|
123
|
+
interface UpdatePlanParams {
|
|
124
|
+
pid: string;
|
|
125
|
+
plan_name?: string;
|
|
126
|
+
disk?: number;
|
|
127
|
+
ram?: number;
|
|
128
|
+
bandwidth?: number;
|
|
129
|
+
cpu?: number;
|
|
130
|
+
virt?: string;
|
|
131
|
+
[key: string]: unknown;
|
|
132
|
+
}
|
|
143
133
|
|
|
144
134
|
declare class PlansResource {
|
|
145
135
|
private readonly http;
|
|
@@ -147,6 +137,8 @@ declare class PlansResource {
|
|
|
147
137
|
list(): Promise<Record<string, Plan>>;
|
|
148
138
|
create(params: CreatePlanParams): Promise<AsyncTaskResult>;
|
|
149
139
|
delete(planId: string): Promise<AsyncTaskResult>;
|
|
140
|
+
get(planId: string): Promise<Plan>;
|
|
141
|
+
update(params: UpdatePlanParams): Promise<AsyncTaskResult>;
|
|
150
142
|
}
|
|
151
143
|
|
|
152
144
|
interface Task {
|
|
@@ -183,6 +175,16 @@ interface CreateUserParams {
|
|
|
183
175
|
acttype?: number;
|
|
184
176
|
[key: string]: unknown;
|
|
185
177
|
}
|
|
178
|
+
interface UpdateUserParams {
|
|
179
|
+
uid: string;
|
|
180
|
+
email?: string;
|
|
181
|
+
password?: string;
|
|
182
|
+
fname?: string;
|
|
183
|
+
lname?: string;
|
|
184
|
+
status?: string;
|
|
185
|
+
acttype?: number;
|
|
186
|
+
[key: string]: unknown;
|
|
187
|
+
}
|
|
186
188
|
|
|
187
189
|
declare class UsersResource {
|
|
188
190
|
private readonly http;
|
|
@@ -192,6 +194,8 @@ declare class UsersResource {
|
|
|
192
194
|
delete(uid: string): Promise<AsyncTaskResult>;
|
|
193
195
|
suspend(uid: string): Promise<AsyncTaskResult>;
|
|
194
196
|
unsuspend(uid: string): Promise<AsyncTaskResult>;
|
|
197
|
+
get(uid: string): Promise<User>;
|
|
198
|
+
update(params: UpdateUserParams): Promise<AsyncTaskResult>;
|
|
195
199
|
}
|
|
196
200
|
|
|
197
201
|
interface VPSData {
|
|
@@ -421,6 +425,26 @@ interface VNCInfo extends VirtualizorResponse {
|
|
|
421
425
|
novnc?: string;
|
|
422
426
|
[key: string]: unknown;
|
|
423
427
|
}
|
|
428
|
+
interface VPSStatusInfo {
|
|
429
|
+
status: number;
|
|
430
|
+
used_cpu?: string;
|
|
431
|
+
used_ram?: number;
|
|
432
|
+
used_disk?: number;
|
|
433
|
+
net_in?: number;
|
|
434
|
+
net_out?: number;
|
|
435
|
+
used_inode?: string;
|
|
436
|
+
io_read?: number;
|
|
437
|
+
io_write?: number;
|
|
438
|
+
inode?: number;
|
|
439
|
+
ram?: string;
|
|
440
|
+
disk?: string;
|
|
441
|
+
used_bandwidth?: string;
|
|
442
|
+
bandwidth?: string;
|
|
443
|
+
virt?: string;
|
|
444
|
+
}
|
|
445
|
+
interface VPSStatusResponse extends VirtualizorResponse {
|
|
446
|
+
[key: string]: VPSStatusInfo | unknown;
|
|
447
|
+
}
|
|
424
448
|
|
|
425
449
|
declare class VpsResource {
|
|
426
450
|
private readonly http;
|
|
@@ -438,7 +462,7 @@ declare class VpsResource {
|
|
|
438
462
|
rebuild(vpsId: string, params: RebuildVPSParams): Promise<AsyncTaskResult>;
|
|
439
463
|
clone(vpsId: string, params: CloneVPSParams): Promise<AsyncTaskResult>;
|
|
440
464
|
migrate(vpsId: string, params: MigrateVPSParams): Promise<AsyncTaskResult>;
|
|
441
|
-
status(vpsId: string): Promise<
|
|
465
|
+
status(vpsId: string): Promise<VPSStatusResponse>;
|
|
442
466
|
vnc(vpsId: string): Promise<VNCInfo>;
|
|
443
467
|
stats(vpsId: string): Promise<VPSStatsResponse>;
|
|
444
468
|
}
|
|
@@ -474,4 +498,5 @@ declare function formatIps(ips: IpsInput, options: FormatIpsOptions & {
|
|
|
474
498
|
as: 'string';
|
|
475
499
|
}): string;
|
|
476
500
|
|
|
477
|
-
export {
|
|
501
|
+
export { ConsoleLogger, VirtualizorApiError, VirtualizorClient, colors, createVirtualizorClient, defaultLogger, formatError, formatIps, symbols };
|
|
502
|
+
export type { AsyncTaskResult, CloneVPSParams, CreatePlanParams, CreateUserParams, CreateVPSParams, IpsInput, ListVPSParams, Logger, MigrateVPSParams, Plan, RebuildVPSParams, Task, UpdatePlanParams, UpdateUserParams, User, VNCInfo, VPS, VPSStatsResponse, VPSStatusInfo, VPSStatusResponse, VirtType, VirtualizorConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -26,23 +26,15 @@ declare class ConsoleLogger implements Logger {
|
|
|
26
26
|
}
|
|
27
27
|
declare const defaultLogger: ConsoleLogger;
|
|
28
28
|
|
|
29
|
+
declare function formatError(error: Error, verbose?: boolean): string;
|
|
30
|
+
|
|
29
31
|
declare const colors: {
|
|
30
32
|
red: (str: string) => string;
|
|
31
33
|
green: (str: string) => string;
|
|
32
34
|
yellow: (str: string) => string;
|
|
33
35
|
blue: (str: string) => string;
|
|
34
|
-
magenta: (str: string) => string;
|
|
35
36
|
cyan: (str: string) => string;
|
|
36
|
-
white: (str: string) => string;
|
|
37
|
-
gray: (str: string) => string;
|
|
38
37
|
dim: (str: string) => string;
|
|
39
|
-
bold: (str: string) => string;
|
|
40
|
-
underline: (str: string) => string;
|
|
41
|
-
bgRed: (str: string) => string;
|
|
42
|
-
bgGreen: (str: string) => string;
|
|
43
|
-
bgYellow: (str: string) => string;
|
|
44
|
-
bgBlue: (str: string) => string;
|
|
45
|
-
bgCyan: (str: string) => string;
|
|
46
38
|
};
|
|
47
39
|
declare const symbols: {
|
|
48
40
|
success: string;
|
|
@@ -56,18 +48,6 @@ declare const symbols: {
|
|
|
56
48
|
star: string;
|
|
57
49
|
};
|
|
58
50
|
|
|
59
|
-
interface BoxOptions {
|
|
60
|
-
title?: string;
|
|
61
|
-
borderColor?: 'cyan' | 'yellow' | 'red' | 'green' | 'blue' | 'magenta';
|
|
62
|
-
padding?: number;
|
|
63
|
-
margin?: number;
|
|
64
|
-
}
|
|
65
|
-
declare function createBox(content: string, options?: BoxOptions): string;
|
|
66
|
-
declare function createUpdateBox(current: string, latest: string): string;
|
|
67
|
-
declare function createErrorBox(title: string, message: string, hint?: string): string;
|
|
68
|
-
|
|
69
|
-
declare function formatError(error: Error, verbose?: boolean): string;
|
|
70
|
-
|
|
71
51
|
interface VirtualizorError {
|
|
72
52
|
code: number;
|
|
73
53
|
msg: string;
|
|
@@ -140,6 +120,16 @@ interface CreatePlanParams {
|
|
|
140
120
|
virt?: string;
|
|
141
121
|
[key: string]: unknown;
|
|
142
122
|
}
|
|
123
|
+
interface UpdatePlanParams {
|
|
124
|
+
pid: string;
|
|
125
|
+
plan_name?: string;
|
|
126
|
+
disk?: number;
|
|
127
|
+
ram?: number;
|
|
128
|
+
bandwidth?: number;
|
|
129
|
+
cpu?: number;
|
|
130
|
+
virt?: string;
|
|
131
|
+
[key: string]: unknown;
|
|
132
|
+
}
|
|
143
133
|
|
|
144
134
|
declare class PlansResource {
|
|
145
135
|
private readonly http;
|
|
@@ -147,6 +137,8 @@ declare class PlansResource {
|
|
|
147
137
|
list(): Promise<Record<string, Plan>>;
|
|
148
138
|
create(params: CreatePlanParams): Promise<AsyncTaskResult>;
|
|
149
139
|
delete(planId: string): Promise<AsyncTaskResult>;
|
|
140
|
+
get(planId: string): Promise<Plan>;
|
|
141
|
+
update(params: UpdatePlanParams): Promise<AsyncTaskResult>;
|
|
150
142
|
}
|
|
151
143
|
|
|
152
144
|
interface Task {
|
|
@@ -183,6 +175,16 @@ interface CreateUserParams {
|
|
|
183
175
|
acttype?: number;
|
|
184
176
|
[key: string]: unknown;
|
|
185
177
|
}
|
|
178
|
+
interface UpdateUserParams {
|
|
179
|
+
uid: string;
|
|
180
|
+
email?: string;
|
|
181
|
+
password?: string;
|
|
182
|
+
fname?: string;
|
|
183
|
+
lname?: string;
|
|
184
|
+
status?: string;
|
|
185
|
+
acttype?: number;
|
|
186
|
+
[key: string]: unknown;
|
|
187
|
+
}
|
|
186
188
|
|
|
187
189
|
declare class UsersResource {
|
|
188
190
|
private readonly http;
|
|
@@ -192,6 +194,8 @@ declare class UsersResource {
|
|
|
192
194
|
delete(uid: string): Promise<AsyncTaskResult>;
|
|
193
195
|
suspend(uid: string): Promise<AsyncTaskResult>;
|
|
194
196
|
unsuspend(uid: string): Promise<AsyncTaskResult>;
|
|
197
|
+
get(uid: string): Promise<User>;
|
|
198
|
+
update(params: UpdateUserParams): Promise<AsyncTaskResult>;
|
|
195
199
|
}
|
|
196
200
|
|
|
197
201
|
interface VPSData {
|
|
@@ -421,6 +425,26 @@ interface VNCInfo extends VirtualizorResponse {
|
|
|
421
425
|
novnc?: string;
|
|
422
426
|
[key: string]: unknown;
|
|
423
427
|
}
|
|
428
|
+
interface VPSStatusInfo {
|
|
429
|
+
status: number;
|
|
430
|
+
used_cpu?: string;
|
|
431
|
+
used_ram?: number;
|
|
432
|
+
used_disk?: number;
|
|
433
|
+
net_in?: number;
|
|
434
|
+
net_out?: number;
|
|
435
|
+
used_inode?: string;
|
|
436
|
+
io_read?: number;
|
|
437
|
+
io_write?: number;
|
|
438
|
+
inode?: number;
|
|
439
|
+
ram?: string;
|
|
440
|
+
disk?: string;
|
|
441
|
+
used_bandwidth?: string;
|
|
442
|
+
bandwidth?: string;
|
|
443
|
+
virt?: string;
|
|
444
|
+
}
|
|
445
|
+
interface VPSStatusResponse extends VirtualizorResponse {
|
|
446
|
+
[key: string]: VPSStatusInfo | unknown;
|
|
447
|
+
}
|
|
424
448
|
|
|
425
449
|
declare class VpsResource {
|
|
426
450
|
private readonly http;
|
|
@@ -438,7 +462,7 @@ declare class VpsResource {
|
|
|
438
462
|
rebuild(vpsId: string, params: RebuildVPSParams): Promise<AsyncTaskResult>;
|
|
439
463
|
clone(vpsId: string, params: CloneVPSParams): Promise<AsyncTaskResult>;
|
|
440
464
|
migrate(vpsId: string, params: MigrateVPSParams): Promise<AsyncTaskResult>;
|
|
441
|
-
status(vpsId: string): Promise<
|
|
465
|
+
status(vpsId: string): Promise<VPSStatusResponse>;
|
|
442
466
|
vnc(vpsId: string): Promise<VNCInfo>;
|
|
443
467
|
stats(vpsId: string): Promise<VPSStatsResponse>;
|
|
444
468
|
}
|
|
@@ -474,4 +498,5 @@ declare function formatIps(ips: IpsInput, options: FormatIpsOptions & {
|
|
|
474
498
|
as: 'string';
|
|
475
499
|
}): string;
|
|
476
500
|
|
|
477
|
-
export {
|
|
501
|
+
export { ConsoleLogger, VirtualizorApiError, VirtualizorClient, colors, createVirtualizorClient, defaultLogger, formatError, formatIps, symbols };
|
|
502
|
+
export type { AsyncTaskResult, CloneVPSParams, CreatePlanParams, CreateUserParams, CreateVPSParams, IpsInput, ListVPSParams, Logger, MigrateVPSParams, Plan, RebuildVPSParams, Task, UpdatePlanParams, UpdateUserParams, User, VNCInfo, VPS, VPSStatsResponse, VPSStatusInfo, VPSStatusResponse, VirtType, VirtualizorConfig };
|
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import q from"node:http";import b from"node:https";const m={port:4085,https:!0,rejectUnauthorized:!1,timeout:3e4,debug:!1},A={pollIntervalMs:2e3,timeoutMs:12e4};class i extends Error{code;details;constructor(t,e,r){super(t),this.name="VirtualizorApiError",this.code=e,this.details=r}format(){return`[API Error ${this.code}] ${this.message}`}}function j(s,t,e){const r={};for(const[a,o]of Object.entries(s))o!==void 0&&(r[a]=o);const n=new URLSearchParams;n.set("api","json"),n.set("adminapikey",t),n.set("adminapipass",e);for(const[a,o]of Object.entries(r))n.set(a,String(o));return`?${n.toString()}`}const T=5e3;class S{constructor(t){this.config=t;const e=t.https?b.Agent:q.Agent;this.agent=new e({keepAlive:!0,maxSockets:50,maxFreeSockets:10,scheduling:"lifo",...t.https?{rejectUnauthorized:t.rejectUnauthorized}:{}}),this.logger=t.logger}agent;logger;parseResponse(t){if(t.error&&t.error.length>0){const e=t.error[0];if(e)throw new i(e.msg,e.code)}return t}async request(t,e={},r={}){const n={act:t,...e},a=j(n,this.config.apiKey,this.config.apiPass);if(this.config.debug){const u=a.replace(/adminapikey=[^&]*/,"adminapikey=[REDACTED]").replace(/adminapipass=[^&]*/,"adminapipass=[REDACTED]");this.logger.debug(`Request: act=${t} path=/index.php${u}`)}const o=`/index.php${a}`,p=Object.entries(r).filter(([,u])=>u!==void 0).map(([u,y])=>`${encodeURIComponent(u)}=${encodeURIComponent(String(y))}`).join("&");try{const u=await this.rawRequest(o,p||void 0);return this.parseResponse(u)}catch(u){throw this.config.debug&&(u instanceof i?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${u.code}] ${u.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${u.message}`)),u}}validateJsonDepth(t,e=0){if(e>100)throw new i("JSON depth limit exceeded",-32e3);if(typeof t=="object"&&t!==null)if(Array.isArray(t))for(const r of t)this.validateJsonDepth(r,e+1);else for(const r of Object.values(t))this.validateJsonDepth(r,e+1)}destroy(){this.agent.destroy()}rawRequest(t,e){const r=this.config.https?b:q,n={host:this.config.host,port:this.config.port,path:t,method:e?"POST":"GET",headers:{"Content-Type":"application/x-www-form-urlencoded",...e?{"Content-Length":Buffer.byteLength(e)}:{}},agent:this.agent};return new Promise((a,o)=>{const p=r.request(n,h=>{const $=[];h.on("data",g=>{$.push(g)}),h.on("end",()=>{const g=Buffer.concat($).toString("utf8");if(h.statusCode===302||h.statusCode===301){o(new i(`Redirect detected (status ${h.statusCode}). Authentication failed. Location: ${h.headers.location}`,h.statusCode));return}try{const l=JSON.parse(g);this.validateJsonDepth(l),a(l)}catch(l){this.config.debug&&(l instanceof i?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${l.code}] ${l.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${l.message}`)),o(new i(`Failed to parse response: ${l.message??"Invalid JSON"}`,-32700))}}),h.on("error",g=>{this.config.debug&&this.logger.error("[Virtualizor] \u25CF Error: Response stream error",g),o(new i(`Response stream error: ${g.message??"Unknown error"}`,-32e3))})}),u=setTimeout(()=>{p.destroy(new i(`Connection timeout after ${T}ms`,-32e3))},T),y=setTimeout(()=>{p.destroy(new i(`Request timed out after ${this.config.timeout}ms`,-32e3))},this.config.timeout);p.once("socket",h=>{h.connecting?h.once("connect",()=>clearTimeout(u)):clearTimeout(u)}),p.once("close",()=>{clearTimeout(u),clearTimeout(y)}),p.on("error",h=>{h instanceof i?o(h):o(new i(`Request error ${h}`,-32e3))}),e&&p.write(e),p.end()})}}const w=process.platform==="win32",U=process.env.NO_COLOR===void 0&&process.stdout.isTTY;function f(s,t){return U?`\x1B[${s}m${t}\x1B[0m`:t}const c={red:s=>f(31,s),green:s=>f(32,s),yellow:s=>f(33,s),blue:s=>f(34,s),cyan:s=>f(36,s),dim:s=>f(2,s)},d={success:w?"\u221A":"\u2714",error:w?"\xD7":"\u2716",warning:w?"\u203C":"\u26A0",info:w?"i":"\u2139",bullet:"\u25CF",arrow:"\u2192",chevron:"\u203A",pointer:"\u276F",star:"\u2605"};class E{constructor(t="Virtualizor"){this.prefix=t}timestamp(){const t=new Date().toISOString().split("T")[1];return c.dim(t?t.slice(0,8):"00:00:00")}tag(){return c.cyan(`[${this.prefix}]`)}debug(t,...e){console.log(this.timestamp(),this.tag(),c.dim(d.bullet),c.dim(t),...e)}info(t,...e){console.log(this.timestamp(),this.tag(),c.blue(d.info),t,...e)}warn(t,...e){console.log(this.timestamp(),this.tag(),c.yellow(d.warning),c.yellow(t),...e)}error(t,e){console.error(this.timestamp(),this.tag(),c.red(d.error),c.red(t)),e?.stack&&console.error(c.dim(e.stack.split(`
|
|
2
2
|
`).slice(1,4).join(`
|
|
3
|
-
`)))
|
|
4
|
-
`)
|
|
5
|
-
`);if(o>0){let y=" ".repeat(o);return d.split(`
|
|
6
|
-
`).map(z=>y+z).join(`
|
|
7
|
-
`)}return d}function b(s,t){let e=["\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","\u2551 \u{1F680} UPDATE AVAILABLE \u{1F680} \u2551","\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563","\u2551 \u2551",`\u2551 Current version: ${s.padEnd(18)} \u2551`,`\u2551 Latest version: ${t.padEnd(17)} \u2551`,"\u2551 \u2551","\u2551 To update, run: \u2551","\u2551 npm install virtualizorjs@latest \u2551","\u2551 \u2551","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"].join(`
|
|
8
|
-
`);return a.yellow(e)}function N(s,t,e){let o=["\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","\u2551 \u274C ERROR OCCURRED \u274C \u2551","\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563","\u2551 \u2551",`\u2551 ${s.padEnd(34)}\u2551`,"\u2551 \u2551",`\u2551 ${t.padEnd(34)}\u2551`,"\u2551 \u2551",e?`\u2551 \u{1F4A1} ${e.padEnd(29)}\u2551`:"",e?"\u2551 \u2551":"","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"].filter(r=>r!==void 0).join(`
|
|
9
|
-
`);return a.red(o)}function B(s,t=false){if(s instanceof n){let e=s.details&&t?`
|
|
10
|
-
${a.dim(JSON.stringify(s.details,null,2))}`:"";return `${g.error} ${a.red(`[API Error ${s.code}]`)} ${s.message}${e}`}return `${g.error} ${a.red(s.message)}`}var x=class{constructor(t){this.http=t;}async list(){return (await this.http.request("plans",{},{})).plans}async create(t){return this.http.request("addplan",{},t)}async delete(t){return this.http.request("plans",{},{delete:t})}};var V=class{constructor(t){this.http=t;}async get(t){return (await this.http.request("tasks",{taskid:t},{})).tasks[t]}async wait(t,e={}){let{pollIntervalMs:o=I.pollIntervalMs,timeoutMs:r=I.timeoutMs}=e,p=Date.now()+r;for(;Date.now()<p;){let i=await this.get(t);if(!i)throw new n("Task not found",404);if(i.status==="1"||i.status==="done")return i;if(i.status==="error"||i.status==="-1")throw new n("Task failed",500);await new Promise(m=>setTimeout(m,o));}throw new n(`Task timed out after ${r}ms`,408)}};var C=class{constructor(t){this.http=t;}async list(){return (await this.http.request("users",{},{})).users}async create(t){return this.http.request("adduser",{},t)}async delete(t){return this.http.request("users",{},{delete:t})}async suspend(t){return this.http.request("users",{},{suspend:t})}async unsuspend(t){return this.http.request("users",{},{unsuspend:t})}};var E={REBUILD_REOS_FLAG:1,MIGRATE_FLAG:1,MIGRATE_BUT_FLAG:1};var S=class{constructor(t){this.http=t;}async list(t={}){return (await this.http.request("vs",{},t)).vs??{}}async get(t){let e=await this.http.request("vs",{},t),o=Object.entries(e.vs??{});if(o.length===0)throw new n("VPS not found",404);let r=o[0];if(!r)throw new n("VPS not found",404);let[,p]=r;return p}async create(t){return this.http.request("addvs",{},t)}async delete(t){return this.http.request("vs",{delete:t},{})}async start(t){return this.http.request("vs",{vpsid:t,action:"start"},{})}async stop(t){return this.http.request("vs",{vpsid:t,action:"stop"},{})}async restart(t){return this.http.request("vs",{vpsid:t,action:"restart"},{})}async poweroff(t){return this.http.request("vs",{vpsid:t,action:"poweroff"},{})}async suspend(t){return this.http.request("vs",{suspend:t},{})}async unsuspend(t){return this.http.request("vs",{unsuspend:t},{})}async rebuild(t,e){return this.http.request("rebuild",{},{vpsid:t,reos:E.REBUILD_REOS_FLAG,...e})}async clone(t,e){return this.http.request("clone",{},{vpsid:t,...e})}async migrate(t,e){return this.http.request("migrate",{},{vpsid:t,migrate:E.MIGRATE_FLAG,migrate_but:E.MIGRATE_BUT_FLAG,...e})}async status(t){return this.http.request("vstatus",{vpsid:t},{})}async vnc(t){return this.http.request("vnc",{vpsid:t},{})}async stats(t){return this.http.request("vps_stats",{},{vpsid:t})}};var H="https://registry.npmjs.org/virtualizorjs/latest";async function J(s){let t=new AbortController,e=setTimeout(()=>t.abort(),s);try{let o=await fetch(H,{signal:t.signal});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}finally{clearTimeout(e);}}function K(s,t){let e=s.split(".").map(Number),o=t.split(".").map(Number);return (o[0]??0)>(e[0]??0)||(o[0]??0)===(e[0]??0)&&(o[1]??0)>(e[1]??0)||(o[0]??0)===(e[0]??0)&&(o[1]??0)===(e[1]??0)&&(o[2]??0)>(e[2]??0)}var _=false;async function D(s,t,e){if(!(_&&true)){_=true;try{let r=(await J(e?.timeout??2e3)).version;if(!K(s,r))return;t.warn(`Update available: ${s} \u2192 ${r}`),console.log(),console.log(b(s,r)),console.log();}catch{}}}var W=M().version,L=class{vps;users;plans;tasks;logger;constructor(t){let e=t.logger??w;this.logger=e;let o={host:t.host,apiKey:t.apiKey,apiPass:t.apiPass??"",port:t.port??P.port,https:t.https??P.https,rejectUnauthorized:t.rejectUnauthorized??P.rejectUnauthorized,timeout:t.timeout??P.timeout,debug:t.debug??P.debug,logger:e,disableUpdateCheck:t.disableUpdateCheck??false},r=new v(o);this.vps=new S(r),this.users=new C(r),this.plans=new x(r),this.tasks=new V(r),o.disableUpdateCheck||D(W,e).catch(()=>{});}};function Y(s){return new L(s)}function X(s,t){let e=t?.as??"array",o=t?.separator??", ";if(!s)return e==="array"?[]:"";let r=[];if(Array.isArray(s))r=s.filter(Boolean);else if(typeof s=="string"){let p=s.trim();p===""?r=[]:p.includes(",")?r=p.split(",").map(i=>i.trim()).filter(Boolean):/\s+/.test(p)?r=p.split(/\s+/).map(i=>i.trim()).filter(Boolean):r=[p];}else typeof s=="object"&&(r=Object.values(s).filter(Boolean));return e==="array"?r:r.join(o)}
|
|
11
|
-
export{k as ConsoleLogger,n as VirtualizorApiError,L as VirtualizorClient,a as colors,O as createBox,N as createErrorBox,b as createUpdateBox,Y as createVirtualizorClient,w as defaultLogger,B as formatError,X as formatIps,g as symbols};
|
|
3
|
+
`)))}success(t,...e){console.log(this.timestamp(),this.tag(),c.green(d.success),c.green(t),...e)}}const R=new E;function I(s,t=!1){if(s instanceof i){const e=s.details&&t?`
|
|
4
|
+
${c.dim(JSON.stringify(s.details,null,2))}`:"";return`${d.error} ${c.red(`[API Error ${s.code}]`)} ${s.message}${e}`}return`${d.error} ${c.red(s.message)}`}class O{constructor(t){this.http=t}async list(){return(await this.http.request("plans",{},{})).plans}async create(t){return this.http.request("addplan",{},t)}async delete(t){return this.http.request("plans",{},{delete:t})}async get(t){const e=(await this.http.request("plans",{},{})).plans[t];if(!e)throw new i("Plan not found",404);return e}async update(t){return this.http.request("editplan",{},t)}}class F{constructor(t){this.http=t}async get(t){return(await this.http.request("tasks",{taskid:t},{})).tasks[t]}async wait(t,e={}){const{pollIntervalMs:r=A.pollIntervalMs,timeoutMs:n=A.timeoutMs}=e,a=Date.now()+n;for(;Date.now()<a;){const o=await this.get(t);if(!o)throw new i("Task not found",404);if(o.status==="1"||o.status==="done")return o;if(o.status==="error"||o.status==="-1")throw new i("Task failed",500);await new Promise(p=>setTimeout(p,r))}throw new i(`Task timed out after ${n}ms`,408)}}class L{constructor(t){this.http=t}async list(){return(await this.http.request("users",{},{})).users}async create(t){return this.http.request("adduser",{},t)}async delete(t){return this.http.request("users",{},{delete:t})}async suspend(t){return this.http.request("users",{},{suspend:t})}async unsuspend(t){return this.http.request("users",{},{unsuspend:t})}async get(t){const e=(await this.http.request("users",{},{uid:t})).user[t];if(!e)throw new i("User not found",404);return e}async update(t){return this.http.request("edituser",{},t)}}const v={REBUILD_REOS_FLAG:1,MIGRATE_FLAG:1,MIGRATE_BUT_FLAG:1};class z{constructor(t){this.http=t}async list(t={}){return(await this.http.request("vs",{},t)).vs??{}}async get(t){const e=await this.http.request("vs",{},t),r=Object.entries(e.vs??{});if(r.length===0)throw new i("VPS not found",404);const n=r[0];if(!n)throw new i("VPS not found",404);const[,a]=n;return a}async create(t){return this.http.request("addvs",{},t)}async delete(t){return this.http.request("vs",{delete:t},{})}async start(t){return this.http.request("vs",{vpsid:t,action:"start"},{})}async stop(t){return this.http.request("vs",{vpsid:t,action:"stop"},{})}async restart(t){return this.http.request("vs",{vpsid:t,action:"restart"},{})}async poweroff(t){return this.http.request("vs",{vpsid:t,action:"poweroff"},{})}async suspend(t){return this.http.request("vs",{suspend:t},{})}async unsuspend(t){return this.http.request("vs",{unsuspend:t},{})}async rebuild(t,e){return this.http.request("rebuild",{},{vpsid:t,reos:v.REBUILD_REOS_FLAG,...e})}async clone(t,e){return this.http.request("clone",{},{vpsid:t,...e})}async migrate(t,e){return this.http.request("migrate",{},{vpsid:t,migrate:v.MIGRATE_FLAG,migrate_but:v.MIGRATE_BUT_FLAG,...e})}async status(t){return this.http.request("vstatus",{vpsid:t},{})}async vnc(t){return this.http.request("vnc",{vpsid:t},{})}async stats(t){return this.http.request("vps_stats",{},{vpsid:t})}}const P="https://registry.npmjs.org/virtualizorjs/latest";async function _(s){const t=new AbortController,e=setTimeout(()=>t.abort(),s);try{const r=await fetch(P,{signal:t.signal});if(!r.ok)throw new Error(`HTTP ${r.status}`);return await r.json()}finally{clearTimeout(e)}}function D(s,t){const e=s.split(".").map(Number),r=t.split(".").map(Number);return(r[0]??0)>(e[0]??0)||(r[0]??0)===(e[0]??0)&&(r[1]??0)>(e[1]??0)||(r[0]??0)===(e[0]??0)&&(r[1]??0)===(e[1]??0)&&(r[2]??0)>(e[2]??0)}let C=!1;async function V(s,t,e){if(!C){C=!0;try{const r=(await _(e?.timeout??2e3)).version;if(!D(s,r))return;t.warn(`Update available: ${s} \u2192 ${r}`),t.warn('Run "npm install virtualizorjs@latest" to update')}catch{}}}const x=require("../package.json").version;class k{vps;users;plans;tasks;logger;constructor(t){const e=t.logger??R;this.logger=e;const r={host:t.host,apiKey:t.apiKey,apiPass:t.apiPass??"",port:t.port??m.port,https:t.https??m.https,rejectUnauthorized:t.rejectUnauthorized??m.rejectUnauthorized,timeout:t.timeout??m.timeout,debug:t.debug??m.debug,logger:e,disableUpdateCheck:t.disableUpdateCheck??!1},n=new S(r);this.vps=new z(n),this.users=new L(n),this.plans=new O(n),this.tasks=new F(n),r.disableUpdateCheck||V(x,e).catch(()=>{})}}function G(s){return new k(s)}function B(s,t){const e=t?.as??"array",r=t?.separator??", ";if(!s)return e==="array"?[]:"";let n=[];if(Array.isArray(s))n=s.filter(Boolean);else if(typeof s=="string"){const a=s.trim();a===""?n=[]:a.includes(",")?n=a.split(",").map(o=>o.trim()).filter(Boolean):/\s+/.test(a)?n=a.split(/\s+/).map(o=>o.trim()).filter(Boolean):n=[a]}else typeof s=="object"&&(n=Object.values(s).filter(Boolean));return e==="array"?n:n.join(r)}export{E as ConsoleLogger,i as VirtualizorApiError,k as VirtualizorClient,c as colors,G as createVirtualizorClient,R as defaultLogger,I as formatError,B as formatIps,d as symbols};
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "virtualizorjs",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "TypeScript SDK for the Virtualizor server management API. Create, start, stop, restart, rebuild, and manage VPS instances with a type-safe, developer-friendly client.",
|
|
5
|
-
"main": "./dist/index.
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
@@ -12,14 +12,14 @@
|
|
|
12
12
|
"default": "./dist/index.mjs"
|
|
13
13
|
},
|
|
14
14
|
"require": {
|
|
15
|
-
"types": "./dist/index.d.
|
|
16
|
-
"default": "./dist/index.
|
|
15
|
+
"types": "./dist/index.d.cts",
|
|
16
|
+
"default": "./dist/index.cjs"
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
21
|
-
"build": "
|
|
22
|
-
"dev": "
|
|
21
|
+
"build": "unbuild",
|
|
22
|
+
"dev": "unbuild --watch",
|
|
23
23
|
"test": "bun test",
|
|
24
24
|
"test:watch": "bun test --watch",
|
|
25
25
|
"coverage": "bun test --coverage",
|
|
@@ -41,24 +41,22 @@
|
|
|
41
41
|
"url": "git+https://github.com/kkMihai/virtualizorjs.git"
|
|
42
42
|
},
|
|
43
43
|
"bugs": {
|
|
44
|
-
|
|
45
|
-
},
|
|
46
|
-
"homepage": "https://github.com/kkMihai/virtualizorjs#readme",
|
|
47
|
-
"engines": {
|
|
48
|
-
"bun": ">=1.3.
|
|
49
|
-
},
|
|
50
|
-
"devDependencies": {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
},
|
|
61
|
-
"trustedDependencies": [
|
|
62
|
-
"@biomejs/biome"
|
|
63
|
-
]
|
|
44
|
+
"url": "https://github.com/kkMihai/virtualizorjs/issues"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/kkMihai/virtualizorjs#readme",
|
|
47
|
+
"engines": {
|
|
48
|
+
"bun": ">=1.3.10"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@arethetypeswrong/cli": "^0.18.2",
|
|
52
|
+
"@biomejs/biome": "^2.4.7",
|
|
53
|
+
"@commitlint/cli": "^20.5.0",
|
|
54
|
+
"@commitlint/config-conventional": "^20.5.0",
|
|
55
|
+
"@types/bun": "latest",
|
|
56
|
+
"bumpp": "^11.0.1",
|
|
57
|
+
"husky": "^9.1.7",
|
|
58
|
+
"unbuild": "^3.6.1",
|
|
59
|
+
"typescript": "^5.9.3"
|
|
60
|
+
},
|
|
61
|
+
"trustedDependencies": ["@biomejs/biome"]
|
|
64
62
|
}
|
package/dist/index.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
'use strict';var j=require('http'),U=require('https');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var j__default=/*#__PURE__*/_interopDefault(j);var U__default=/*#__PURE__*/_interopDefault(U);var F=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var M=F(($t,Q)=>{Q.exports={name:"virtualizorjs",version:"2.2.1",description:"TypeScript SDK for the Virtualizor server management API. Create, start, stop, restart, rebuild, and manage VPS instances with a type-safe, developer-friendly client.",main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{import:{types:"./dist/index.d.mts",default:"./dist/index.mjs"},require:{types:"./dist/index.d.ts",default:"./dist/index.js"}}},scripts:{build:"tsup",dev:"tsup --watch",test:"bun test","test:watch":"bun test --watch",coverage:"bun test --coverage",typecheck:"tsc --noEmit",lint:"biome check src tests","lint:fix":"biome check --write src tests",format:"biome format --write src tests",release:"bun run build && bumpp",prepublishOnly:"bun run build && bun run typecheck","check-exports":"attw --pack .",prepare:"husky"},files:["dist","README.md","LICENSE"],keywords:["virtualizor","vps","sdk","api","typescript","nodejs","bun"],author:"kkMihai",license:"MIT",repository:{type:"git",url:"git+https://github.com/kkMihai/virtualizorjs.git"},bugs:{url:"https://github.com/kkMihai/virtualizorjs/issues"},homepage:"https://github.com/kkMihai/virtualizorjs#readme",engines:{bun:">=1.3.0"},devDependencies:{"@arethetypeswrong/cli":"^0.17.0","@biomejs/biome":"^1.9.0","@commitlint/cli":"^19.0.0","@commitlint/config-conventional":"^19.0.0","@types/bun":"latest",bumpp:"^9.0.0",husky:"^9.0.0",tsup:"^8.0.0",typescript:"^5.5.0"},trustedDependencies:["@biomejs/biome"]};});var P={port:4085,https:true,rejectUnauthorized:false,timeout:3e4,debug:false},I={pollIntervalMs:2e3,timeoutMs:12e4};var n=class extends Error{code;details;constructor(t,e,o){super(t),this.name="VirtualizorApiError",this.code=e,this.details=o;}format(){return `[API Error ${this.code}] ${this.message}`}};function $(s,t,e){let o={};for(let[p,i]of Object.entries(s))i!==void 0&&(o[p]=i);let r=new URLSearchParams;r.set("api","json"),r.set("adminapikey",t),r.set("adminapipass",e);for(let[p,i]of Object.entries(o))r.set(p,String(i));return `?${r.toString()}`}var q=5e3,v=class{constructor(t){this.config=t;let e=t.https?U__default.default.Agent:j__default.default.Agent;this.agent=new e({keepAlive:true,maxSockets:50,maxFreeSockets:10,scheduling:"lifo",...t.https?{rejectUnauthorized:t.rejectUnauthorized}:{}}),this.logger=t.logger;}agent;logger;parseResponse(t){if(t.error&&t.error.length>0){let e=t.error[0];if(e)throw new n(e.msg,e.code)}return t}async request(t,e={},o={}){let r={act:t,...e},p=$(r,this.config.apiKey,this.config.apiPass);if(this.config.debug){let c=p.replace(/adminapikey=[^&]*/,"adminapikey=[REDACTED]").replace(/adminapipass=[^&]*/,"adminapipass=[REDACTED]");this.logger.debug(`Request: act=${t} path=/index.php${c}`);}let i=`/index.php${p}`,m=Object.entries(o).filter(([,c])=>c!==void 0).map(([c,R])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(R))}`).join("&");try{let c=await this.rawRequest(i,m||void 0);return this.parseResponse(c)}catch(c){throw this.config.debug&&(c instanceof n?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${c.code}] ${c.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${c.message}`)),c}}validateJsonDepth(t,e=0){if(e>100)throw new n("JSON depth limit exceeded",-32e3);if(typeof t=="object"&&t!==null)if(Array.isArray(t))for(let r of t)this.validateJsonDepth(r,e+1);else for(let r of Object.values(t))this.validateJsonDepth(r,e+1);}destroy(){this.agent.destroy();}rawRequest(t,e){let o=this.config.https?U__default.default:j__default.default,r={host:this.config.host,port:this.config.port,path:t,method:e?"POST":"GET",headers:{"Content-Type":"application/x-www-form-urlencoded",...e?{"Content-Length":Buffer.byteLength(e)}:{}},agent:this.agent};return new Promise((p,i)=>{let m=o.request(r,u=>{let T=[];u.on("data",f=>{T.push(f);}),u.on("end",()=>{let f=Buffer.concat(T).toString("utf8");if(u.statusCode===302||u.statusCode===301){i(new n(`Redirect detected (status ${u.statusCode}). Authentication failed. Location: ${u.headers.location}`,u.statusCode));return}try{let d=JSON.parse(f);this.validateJsonDepth(d),p(d);}catch(d){this.config.debug&&(d instanceof n?this.logger.error(`[Virtualizor] \u25CF Error: [API Error ${d.code}] ${d.message}`):this.logger.error(`[Virtualizor] \u25CF Error: ${d.message}`)),i(new n(`Failed to parse response: ${d.message??"Invalid JSON"}`,-32700));}}),u.on("error",f=>{this.config.debug&&this.logger.error("[Virtualizor] \u25CF Error: Response stream error",f),i(new n(`Response stream error: ${f.message??"Unknown error"}`,-32e3));});}),c=setTimeout(()=>{m.destroy(new n(`Connection timeout after ${q}ms`,-32e3));},q),R=setTimeout(()=>{m.destroy(new n(`Request timed out after ${this.config.timeout}ms`,-32e3));},this.config.timeout);m.once("socket",u=>{u.connecting?u.once("connect",()=>clearTimeout(c)):clearTimeout(c);}),m.once("close",()=>{clearTimeout(c),clearTimeout(R);}),m.on("error",u=>{u instanceof n?i(u):i(new n(`Request error ${u}`,-32e3));}),e&&m.write(e),m.end();})}};var A=process.platform==="win32",G=process.env.NO_COLOR===void 0&&process.stdout.isTTY;function l(s,t){return G?`\x1B[${s}m${t}\x1B[0m`:t}var a={red:s=>l(31,s),green:s=>l(32,s),yellow:s=>l(33,s),blue:s=>l(34,s),magenta:s=>l(35,s),cyan:s=>l(36,s),white:s=>l(37,s),gray:s=>l(90,s),dim:s=>l(2,s),bold:s=>l(1,s),underline:s=>l(4,s),bgRed:s=>l(41,s),bgGreen:s=>l(42,s),bgYellow:s=>l(43,s),bgBlue:s=>l(44,s),bgCyan:s=>l(46,s)},g={success:A?"\u221A":"\u2714",error:A?"\xD7":"\u2716",warning:A?"\u203C":"\u26A0",info:A?"i":"\u2139",bullet:"\u25CF",arrow:"\u2192",chevron:"\u203A",pointer:"\u276F",star:"\u2605"},h={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"};var k=class{constructor(t="Virtualizor"){this.prefix=t;}timestamp(){let e=new Date().toISOString().split("T")[1];return a.dim(e?e.slice(0,8):"00:00:00")}tag(){return a.cyan(`[${this.prefix}]`)}debug(t,...e){console.log(this.timestamp(),this.tag(),a.dim(g.bullet),a.dim(t),...e);}info(t,...e){console.log(this.timestamp(),this.tag(),a.blue(g.info),t,...e);}warn(t,...e){console.log(this.timestamp(),this.tag(),a.yellow(g.warning),a.yellow(t),...e);}error(t,e){console.error(this.timestamp(),this.tag(),a.red(g.error),a.red(t)),e?.stack&&console.error(a.dim(e.stack.split(`
|
|
2
|
-
`).slice(1,4).join(`
|
|
3
|
-
`)));}success(t,...e){console.log(this.timestamp(),this.tag(),a.green(g.success),a.green(t),...e);}},w=new k;function O(s,t={}){let{padding:e=1,margin:o=0,borderColor:r="cyan"}=t,p=s.split(`
|
|
4
|
-
`),m=Math.max(...p.map(y=>y.length))+e*2,c=a[r]??a.cyan,R=h.horizontal.repeat(m),u=`${h.topLeft}${R}${h.topRight}`,T=`${h.bottomLeft}${R}${h.bottomRight}`,f=p.map(y=>{let z=" ".repeat(e)+y+" ".repeat(e);return `${h.vertical}${z.padEnd(m)}${h.vertical}`}),d=[c(u),...f.map(y=>c(y)),c(T)].join(`
|
|
5
|
-
`);if(o>0){let y=" ".repeat(o);return d.split(`
|
|
6
|
-
`).map(z=>y+z).join(`
|
|
7
|
-
`)}return d}function b(s,t){let e=["\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","\u2551 \u{1F680} UPDATE AVAILABLE \u{1F680} \u2551","\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563","\u2551 \u2551",`\u2551 Current version: ${s.padEnd(18)} \u2551`,`\u2551 Latest version: ${t.padEnd(17)} \u2551`,"\u2551 \u2551","\u2551 To update, run: \u2551","\u2551 npm install virtualizorjs@latest \u2551","\u2551 \u2551","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"].join(`
|
|
8
|
-
`);return a.yellow(e)}function N(s,t,e){let o=["\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557","\u2551 \u274C ERROR OCCURRED \u274C \u2551","\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563","\u2551 \u2551",`\u2551 ${s.padEnd(34)}\u2551`,"\u2551 \u2551",`\u2551 ${t.padEnd(34)}\u2551`,"\u2551 \u2551",e?`\u2551 \u{1F4A1} ${e.padEnd(29)}\u2551`:"",e?"\u2551 \u2551":"","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"].filter(r=>r!==void 0).join(`
|
|
9
|
-
`);return a.red(o)}function B(s,t=false){if(s instanceof n){let e=s.details&&t?`
|
|
10
|
-
${a.dim(JSON.stringify(s.details,null,2))}`:"";return `${g.error} ${a.red(`[API Error ${s.code}]`)} ${s.message}${e}`}return `${g.error} ${a.red(s.message)}`}var x=class{constructor(t){this.http=t;}async list(){return (await this.http.request("plans",{},{})).plans}async create(t){return this.http.request("addplan",{},t)}async delete(t){return this.http.request("plans",{},{delete:t})}};var V=class{constructor(t){this.http=t;}async get(t){return (await this.http.request("tasks",{taskid:t},{})).tasks[t]}async wait(t,e={}){let{pollIntervalMs:o=I.pollIntervalMs,timeoutMs:r=I.timeoutMs}=e,p=Date.now()+r;for(;Date.now()<p;){let i=await this.get(t);if(!i)throw new n("Task not found",404);if(i.status==="1"||i.status==="done")return i;if(i.status==="error"||i.status==="-1")throw new n("Task failed",500);await new Promise(m=>setTimeout(m,o));}throw new n(`Task timed out after ${r}ms`,408)}};var C=class{constructor(t){this.http=t;}async list(){return (await this.http.request("users",{},{})).users}async create(t){return this.http.request("adduser",{},t)}async delete(t){return this.http.request("users",{},{delete:t})}async suspend(t){return this.http.request("users",{},{suspend:t})}async unsuspend(t){return this.http.request("users",{},{unsuspend:t})}};var E={REBUILD_REOS_FLAG:1,MIGRATE_FLAG:1,MIGRATE_BUT_FLAG:1};var S=class{constructor(t){this.http=t;}async list(t={}){return (await this.http.request("vs",{},t)).vs??{}}async get(t){let e=await this.http.request("vs",{},t),o=Object.entries(e.vs??{});if(o.length===0)throw new n("VPS not found",404);let r=o[0];if(!r)throw new n("VPS not found",404);let[,p]=r;return p}async create(t){return this.http.request("addvs",{},t)}async delete(t){return this.http.request("vs",{delete:t},{})}async start(t){return this.http.request("vs",{vpsid:t,action:"start"},{})}async stop(t){return this.http.request("vs",{vpsid:t,action:"stop"},{})}async restart(t){return this.http.request("vs",{vpsid:t,action:"restart"},{})}async poweroff(t){return this.http.request("vs",{vpsid:t,action:"poweroff"},{})}async suspend(t){return this.http.request("vs",{suspend:t},{})}async unsuspend(t){return this.http.request("vs",{unsuspend:t},{})}async rebuild(t,e){return this.http.request("rebuild",{},{vpsid:t,reos:E.REBUILD_REOS_FLAG,...e})}async clone(t,e){return this.http.request("clone",{},{vpsid:t,...e})}async migrate(t,e){return this.http.request("migrate",{},{vpsid:t,migrate:E.MIGRATE_FLAG,migrate_but:E.MIGRATE_BUT_FLAG,...e})}async status(t){return this.http.request("vstatus",{vpsid:t},{})}async vnc(t){return this.http.request("vnc",{vpsid:t},{})}async stats(t){return this.http.request("vps_stats",{},{vpsid:t})}};var H="https://registry.npmjs.org/virtualizorjs/latest";async function J(s){let t=new AbortController,e=setTimeout(()=>t.abort(),s);try{let o=await fetch(H,{signal:t.signal});if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.json()}finally{clearTimeout(e);}}function K(s,t){let e=s.split(".").map(Number),o=t.split(".").map(Number);return (o[0]??0)>(e[0]??0)||(o[0]??0)===(e[0]??0)&&(o[1]??0)>(e[1]??0)||(o[0]??0)===(e[0]??0)&&(o[1]??0)===(e[1]??0)&&(o[2]??0)>(e[2]??0)}var _=false;async function D(s,t,e){if(!(_&&true)){_=true;try{let r=(await J(e?.timeout??2e3)).version;if(!K(s,r))return;t.warn(`Update available: ${s} \u2192 ${r}`),console.log(),console.log(b(s,r)),console.log();}catch{}}}var W=M().version,L=class{vps;users;plans;tasks;logger;constructor(t){let e=t.logger??w;this.logger=e;let o={host:t.host,apiKey:t.apiKey,apiPass:t.apiPass??"",port:t.port??P.port,https:t.https??P.https,rejectUnauthorized:t.rejectUnauthorized??P.rejectUnauthorized,timeout:t.timeout??P.timeout,debug:t.debug??P.debug,logger:e,disableUpdateCheck:t.disableUpdateCheck??false},r=new v(o);this.vps=new S(r),this.users=new C(r),this.plans=new x(r),this.tasks=new V(r),o.disableUpdateCheck||D(W,e).catch(()=>{});}};function Y(s){return new L(s)}function X(s,t){let e=t?.as??"array",o=t?.separator??", ";if(!s)return e==="array"?[]:"";let r=[];if(Array.isArray(s))r=s.filter(Boolean);else if(typeof s=="string"){let p=s.trim();p===""?r=[]:p.includes(",")?r=p.split(",").map(i=>i.trim()).filter(Boolean):/\s+/.test(p)?r=p.split(/\s+/).map(i=>i.trim()).filter(Boolean):r=[p];}else typeof s=="object"&&(r=Object.values(s).filter(Boolean));return e==="array"?r:r.join(o)}
|
|
11
|
-
exports.ConsoleLogger=k;exports.VirtualizorApiError=n;exports.VirtualizorClient=L;exports.colors=a;exports.createBox=O;exports.createErrorBox=N;exports.createUpdateBox=b;exports.createVirtualizorClient=Y;exports.defaultLogger=w;exports.formatError=B;exports.formatIps=X;exports.symbols=g;
|