@virtbase/proxmox-api 2.0.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/model.js ADDED
@@ -0,0 +1,17 @@
1
+ // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
+ // Copyright (C) 2020-2024 Chemouni Uriel <uchemouni@gmail.com>
3
+ //
4
+ // This program is free software: you can redistribute it and/or modify
5
+ // it under the terms of the GNU General Public License as published by
6
+ // the Free Software Foundation, either version 3 of the License, or
7
+ // (at your option) any later version.
8
+ //
9
+ // This program is distributed in the hope that it will be useful,
10
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ // GNU General Public License for more details.
13
+ //
14
+ // You should have received a copy of the GNU General Public License
15
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ export {};
17
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,gEAAgE;AAChE,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,oEAAoE;AACpE,sCAAsC;AACtC,EAAE;AACF,kEAAkE;AAClE,iEAAiE;AACjE,gEAAgE;AAChE,+CAA+C;AAC/C,EAAE;AACF,oEAAoE;AACpE,wEAAwE"}
@@ -0,0 +1,112 @@
1
+ import type { ApiParamType, ApiRequestable } from "./proxy.js";
2
+ /**
3
+ * Common Proxmox authentification properties
4
+ */
5
+ export interface ProxmoxEngineOptionsCommon {
6
+ /**
7
+ * Proxmox address
8
+ * currently used as hostname, so it can not contains a port number.
9
+ */
10
+ host: string;
11
+ /**
12
+ * Proxmox connexion port, default is 8006
13
+ */
14
+ port?: number;
15
+ /**
16
+ * http protocol, can be http or https, default is https
17
+ */
18
+ schema?: "https" | "http";
19
+ /**
20
+ * separated timeout for authentification call, default is 5 second
21
+ */
22
+ authTimeout?: number;
23
+ /**
24
+ * timeout for proxmox request, default is 60 seconds
25
+ */
26
+ queryTimeout?: number;
27
+ /**
28
+ * print the request in curl or fetch format
29
+ */
30
+ debug?: "curl" | "fetch";
31
+ }
32
+ /**
33
+ * Proxmox authentification as user / password
34
+ */
35
+ export interface ProxmoxEngineOptionsPass extends ProxmoxEngineOptionsCommon {
36
+ /**
37
+ * Your username, if not specified will use root@pam
38
+ */
39
+ username?: string;
40
+ /**
41
+ * The password
42
+ */
43
+ password: string;
44
+ }
45
+ /**
46
+ * Proxmox authentification as tokenID / tokenSecret
47
+ */
48
+ export interface ProxmoxEngineOptionsToken extends ProxmoxEngineOptionsCommon {
49
+ tokenID: string;
50
+ tokenSecret: string;
51
+ }
52
+ /**
53
+ * Shape of a `fetch` implementation accepted by {@link ProxmoxEngine}.
54
+ *
55
+ * Structurally satisfied by the platform `fetch`, so any WHATWG-compatible
56
+ * replacement - a mock, an instrumented wrapper, an agent-bound fetch - can be
57
+ * passed straight through.
58
+ */
59
+ export type FetchInterface = (url: string | URL, options?: RequestInit) => Promise<Response>;
60
+ /**
61
+ * Type Union for proxmox Authentification options
62
+ */
63
+ export type ProxmoxEngineOptions = (ProxmoxEngineOptionsToken | ProxmoxEngineOptionsPass) & {
64
+ fetch?: FetchInterface;
65
+ };
66
+ /**
67
+ * Default Proxmox doRequest provider, this Class will be used if you provide Proxmox authentification options to the Proxy generator
68
+ */
69
+ export declare class ProxmoxEngine implements ApiRequestable {
70
+ CSRFPreventionToken?: string;
71
+ ticket?: string;
72
+ private readonly username;
73
+ private readonly password;
74
+ private hostname;
75
+ private port?;
76
+ private readonly schema;
77
+ private authTimeout;
78
+ private queryTimeout;
79
+ private debug?;
80
+ private fetch;
81
+ constructor(options: ProxmoxEngineOptions);
82
+ get host(): string;
83
+ /**
84
+ *
85
+ * @param method http method GET POST PUT of DELETE
86
+ * @param path http path
87
+ * @param pathTemplate http path without var replacements *
88
+ * @param params query params
89
+ * @param retries retries id
90
+ * @returns data from remote response
91
+ */
92
+ doRequest(method: string, path: string, pathTemplate: string, params?: ApiParamType, retries?: number): Promise<unknown>;
93
+ /**
94
+ * Decode a response into the PVE `{ data, errors }` envelope.
95
+ */
96
+ private readBody;
97
+ /**
98
+ * Echo the request that just failed, as a runnable `curl` line or as the
99
+ * `fetch` call that produced it. Only fires when `debug` is set.
100
+ */
101
+ private logRequest;
102
+ /**
103
+ * return the current ticket/token, or create new ones, is previous one had been discared, or missing.
104
+ * @returns Proxmox API ticket and CSRFPreventionToken
105
+ */
106
+ getTicket(): Promise<{
107
+ ticket: string;
108
+ CSRFPreventionToken: string;
109
+ }>;
110
+ }
111
+ export default ProxmoxEngine;
112
+ //# sourceMappingURL=proxmox-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxmox-engine.d.ts","sourceRoot":"","sources":["../src/proxmox-engine.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAS/D;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC1B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,wBAAyB,SAAQ,0BAA0B;IAC1E;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,yBAA0B,SAAQ,0BAA0B;IAC3E,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,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c,aAAa"}
@@ -0,0 +1,308 @@
1
+ // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
+ // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
+ //
4
+ // This program is free software: you can redistribute it and/or modify
5
+ // it under the terms of the GNU General Public License as published by
6
+ // the Free Software Foundation, either version 3 of the License, or
7
+ // (at your option) any later version.
8
+ //
9
+ // This program is distributed in the hope that it will be useful,
10
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ // GNU General Public License for more details.
13
+ //
14
+ // You should have received a copy of the GNU General Public License
15
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ const USER_AGENT = "proxmox-api (https://github.com/UrielCh/proxmox-api)";
17
+ const BASE_HEADERS = {
18
+ Accept: "*/*",
19
+ "User-Agent": USER_AGENT,
20
+ };
21
+ /**
22
+ * Own enumerable entries of `params`, minus the null and undefined ones.
23
+ *
24
+ * PVE rejects empty values, and callers routinely pass optional fields
25
+ * through as undefined, so they are dropped rather than serialised.
26
+ */
27
+ function definedEntries(params) {
28
+ if (!params)
29
+ return [];
30
+ return Object.entries(params).filter(([, value]) => value !== null && value !== undefined);
31
+ }
32
+ /**
33
+ * Encode one parameter the way the PVE API expects: booleans as 1/0, arrays as
34
+ * the key repeated once per element.
35
+ */
36
+ function appendParam(target, key, value) {
37
+ if (value === true) {
38
+ target.set(key, "1");
39
+ }
40
+ else if (value === false) {
41
+ target.set(key, "0");
42
+ }
43
+ else if (Array.isArray(value)) {
44
+ for (const element of value)
45
+ target.append(key, `${element}`);
46
+ }
47
+ else {
48
+ target.set(key, `${value}`);
49
+ }
50
+ }
51
+ /**
52
+ * Default Proxmox doRequest provider, this Class will be used if you provide Proxmox authentification options to the Proxy generator
53
+ */
54
+ export class ProxmoxEngine {
55
+ CSRFPreventionToken;
56
+ ticket;
57
+ username;
58
+ password;
59
+ hostname; // was named host
60
+ port;
61
+ schema;
62
+ authTimeout;
63
+ queryTimeout;
64
+ debug;
65
+ fetch;
66
+ constructor(options) {
67
+ // Bound to globalThis: some runtimes reject the platform `fetch` when it
68
+ // is invoked as a method of another object.
69
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
70
+ if ("tokenID" in options && options.tokenSecret) {
71
+ this.username = "";
72
+ this.password = "";
73
+ if (!options.tokenID.match(/.*@.+!.+/)) {
74
+ const msg = "invalid tokenID, format should look be like USER@REALM!TOKENID";
75
+ console.error(msg);
76
+ throw Error(msg);
77
+ }
78
+ if (!options.tokenSecret.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)) {
79
+ const msg = "invalid tokenSecret, format should be an lowercased UUID like 12345678-1234-1234-1234-1234567890ab";
80
+ console.error(msg);
81
+ throw Error(msg);
82
+ }
83
+ // USER@REALM!TOKENID
84
+ this.ticket = `PVEAPIToken=${options.tokenID}=${options.tokenSecret}`;
85
+ }
86
+ else {
87
+ const optPass = options;
88
+ this.username = optPass.username || "root@pam";
89
+ this.password = optPass.password;
90
+ if (!this.password) {
91
+ const msg = `password is missing for Proxmox connection`;
92
+ console.error(msg);
93
+ throw Error(msg);
94
+ }
95
+ }
96
+ this.hostname = options.host;
97
+ this.port = options.port;
98
+ this.schema = options.schema || "https";
99
+ this.authTimeout = options.authTimeout || 5000;
100
+ this.queryTimeout = options.queryTimeout || 60000;
101
+ this.debug = options.debug;
102
+ }
103
+ get host() {
104
+ if (!this.port)
105
+ return this.hostname;
106
+ return `${this.hostname}:${this.port}`;
107
+ }
108
+ /**
109
+ *
110
+ * @param method http method GET POST PUT of DELETE
111
+ * @param path http path
112
+ * @param pathTemplate http path without var replacements *
113
+ * @param params query params
114
+ * @param retries retries id
115
+ * @returns data from remote response
116
+ */
117
+ async doRequest(method, path, pathTemplate, params, retries = 0) {
118
+ const { CSRFPreventionToken, ticket } = await this.getTicket();
119
+ // ensure that method is uppercased
120
+ const httpMethod = method.toUpperCase();
121
+ const headers = { ...BASE_HEADERS };
122
+ // auth
123
+ if (!this.username) {
124
+ headers.Authorization = ticket; // PVEAPIToken=USER@REALM!TOKENID=UUID
125
+ }
126
+ else {
127
+ headers.cookie = `PVEAuthCookie=${ticket}`;
128
+ headers.CSRFPreventionToken = CSRFPreventionToken;
129
+ }
130
+ // proxmox base url
131
+ const requestUrl = new URL(`${this.schema}://${this.host}${path}`);
132
+ let body;
133
+ const entries = definedEntries(params);
134
+ if (entries.length > 0) {
135
+ const sendsBody = httpMethod === "PUT" || httpMethod === "POST";
136
+ const searchParams = sendsBody
137
+ ? new URLSearchParams()
138
+ : requestUrl.searchParams;
139
+ for (const [key, value] of entries)
140
+ appendParam(searchParams, key, value);
141
+ if (sendsBody) {
142
+ body = searchParams.toString();
143
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
144
+ // `Content-Length` is deliberately left to fetch, which derives it
145
+ // from the body. Upstream set it by hand from `body.length`; that
146
+ // happens to agree here - `URLSearchParams.toString()` percent-encodes
147
+ // to ASCII - but it is a second source of truth for the same fact, and
148
+ // one that silently disagrees the moment the body is transformed.
149
+ }
150
+ }
151
+ const fetchInit = {
152
+ method: httpMethod,
153
+ body,
154
+ headers,
155
+ // Self-clearing, unlike a setTimeout/clearTimeout pair - which leaked a
156
+ // pending timer on every request that threw.
157
+ signal: AbortSignal.timeout(this.queryTimeout),
158
+ };
159
+ let res;
160
+ try {
161
+ res = await this.fetch(requestUrl, fetchInit);
162
+ }
163
+ catch (e) {
164
+ this.logRequest(httpMethod, requestUrl, fetchInit, headers, {
165
+ ticket,
166
+ CSRFPreventionToken,
167
+ });
168
+ const attempt = retries + 1;
169
+ if (attempt < 2) {
170
+ return this.doRequest(httpMethod, path, pathTemplate, params, attempt);
171
+ }
172
+ // throw Error
173
+ let errMsg = `FaILED to call ${httpMethod} ${requestUrl}`;
174
+ const err = e;
175
+ if (err.cause?.message)
176
+ errMsg += ` cause by:${err.cause.message}`;
177
+ throw new Error(errMsg, { cause: e });
178
+ }
179
+ const data = await this.readBody(res, httpMethod, requestUrl);
180
+ switch (res.status) {
181
+ case 400:
182
+ throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
183
+ case 500:
184
+ throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
185
+ case 401:
186
+ if (res.statusText === "invalid PVE ticket" ||
187
+ res.statusText === "permission denied - invalid PVE ticket") {
188
+ this.ticket = undefined;
189
+ // A token is not renewable, so do not spend the retry on it.
190
+ let attempt = this.username ? retries : 10;
191
+ attempt++;
192
+ if (attempt < 2)
193
+ return this.doRequest(httpMethod, path, pathTemplate, params, attempt);
194
+ }
195
+ throw Error(`${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`);
196
+ case 200:
197
+ return data.data;
198
+ default:
199
+ throw Error(`${httpMethod} ${requestUrl} connection failed with ${res.status} ${res.statusText} return: ${JSON.stringify(data)}`);
200
+ }
201
+ }
202
+ /**
203
+ * Decode a response into the PVE `{ data, errors }` envelope.
204
+ */
205
+ async readBody(res, method, requestUrl) {
206
+ const contentType = res.headers.get("content-type");
207
+ const data = { data: null };
208
+ // PVE answers `application/json;charset=UTF-8`, but match on the media
209
+ // type alone so a proxy that respaces the parameter is still understood.
210
+ if (contentType?.startsWith("application/json")) {
211
+ try {
212
+ return (await res.json());
213
+ }
214
+ catch {
215
+ data.errors = "Failed to parse response json";
216
+ }
217
+ }
218
+ else if (contentType === "application/octet-stream") {
219
+ data.data = res.body;
220
+ }
221
+ else if (!contentType) {
222
+ data.errors = "";
223
+ try {
224
+ data.errors = await res.text();
225
+ }
226
+ catch {
227
+ // ignore reading error;
228
+ }
229
+ }
230
+ else {
231
+ // should never append
232
+ throw Error(`${method} ${requestUrl} unexpected contentType "${contentType}" status Line:${res.status} ${res.statusText}`);
233
+ }
234
+ return data;
235
+ }
236
+ /**
237
+ * Echo the request that just failed, as a runnable `curl` line or as the
238
+ * `fetch` call that produced it. Only fires when `debug` is set.
239
+ */
240
+ logRequest(method, requestUrl, fetchInit, headers, auth) {
241
+ if (!this.debug)
242
+ return;
243
+ if (this.debug === "fetch") {
244
+ console.log(`fetch("${requestUrl}", ${JSON.stringify(fetchInit)})`);
245
+ return;
246
+ }
247
+ const credentials = headers.cookie
248
+ ? `-H "CSRFPreventionToken: ${auth.CSRFPreventionToken}" --cookie ${JSON.stringify(headers.cookie)}`
249
+ : `-H "Authorization: ${auth.ticket}"`;
250
+ const data = fetchInit.body
251
+ ? `--data ${JSON.stringify(fetchInit.body)}`
252
+ : "";
253
+ if (method === "POST") {
254
+ console.log(`curl -v --insecure ${credentials} ${data} ${requestUrl}`);
255
+ }
256
+ else if (method === "GET") {
257
+ console.log(`curl -v --insecure ${credentials} ${requestUrl}`);
258
+ }
259
+ else {
260
+ console.log(`curl -v -X ${method} ${credentials} ${data} ${requestUrl}`);
261
+ }
262
+ }
263
+ /**
264
+ * return the current ticket/token, or create new ones, is previous one had been discared, or missing.
265
+ * @returns Proxmox API ticket and CSRFPreventionToken
266
+ */
267
+ async getTicket() {
268
+ if (this.ticket) {
269
+ if (!this.username)
270
+ return { ticket: this.ticket, CSRFPreventionToken: "" };
271
+ if (this.CSRFPreventionToken)
272
+ return {
273
+ ticket: this.ticket,
274
+ CSRFPreventionToken: this.CSRFPreventionToken,
275
+ };
276
+ }
277
+ // update ticket endpoint
278
+ const requestUrl = `${this.schema}://${this.host}/api2/json/access/ticket`;
279
+ try {
280
+ const { password, username } = this;
281
+ const body = new URLSearchParams({ username, password }).toString();
282
+ const headers = {
283
+ ...BASE_HEADERS,
284
+ "Content-Type": "application/x-www-form-urlencoded",
285
+ };
286
+ const r = await this.fetch(requestUrl, {
287
+ method: "POST",
288
+ headers,
289
+ signal: AbortSignal.timeout(this.authTimeout),
290
+ body,
291
+ });
292
+ const text = await r.text();
293
+ if (r.status !== 200) {
294
+ throw Error(`login failed with ${r.status}: ${r.statusText} ${text}`);
295
+ }
296
+ const respObj = JSON.parse(text);
297
+ const { CSRFPreventionToken, ticket } = respObj.data;
298
+ this.CSRFPreventionToken = CSRFPreventionToken;
299
+ this.ticket = ticket;
300
+ return { ticket, CSRFPreventionToken };
301
+ }
302
+ catch (e) {
303
+ throw new Error(`Auth ${requestUrl} Failed!`, { cause: e });
304
+ }
305
+ }
306
+ }
307
+ export default ProxmoxEngine;
308
+ //# sourceMappingURL=proxmox-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxmox-engine.js","sourceRoot":"","sources":["../src/proxmox-engine.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,gEAAgE;AAChE,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,oEAAoE;AACpE,sCAAsC;AACtC,EAAE;AACF,kEAAkE;AAClE,iEAAiE;AACjE,gEAAgE;AAChE,+CAA+C;AAC/C,EAAE;AACF,oEAAoE;AACpE,wEAAwE;AAIxE,MAAM,UAAU,GAAG,sDAAsD,CAAC;AAE1E,MAAM,YAAY,GAAqC;IACrD,MAAM,EAAE,KAAK;IACb,YAAY,EAAE,UAAU;CACzB,CAAC;AAuFF;;;;;GAKG;AACH,SAAS,cAAc,CAAC,MAAqB;IAC3C,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAClC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CACrD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,WAAW,CAClB,MAAuB,EACvB,GAAW,EACX,KAAc;IAEd,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACnB,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACvB,CAAC;SAAM,IAAI,KAAK,KAAK,KAAK,EAAE,CAA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@@ -0,0 +1,39 @@
1
+ /**
2
+ * Parameters for one API call.
3
+ *
4
+ * Values are whatever the endpoint declares in `model.ts`; the engine encodes
5
+ * them on the way out.
6
+ */
7
+ export type ApiParamType = Record<string, unknown>;
8
+ /**
9
+ * The transport the proxy calls into.
10
+ *
11
+ * Implement it to send requests somewhere other than a live cluster - a
12
+ * recorded fixture, a queue, a per-tenant router - and hand the result to
13
+ * {@link buildApiProxy} or `proxmoxApi()`.
14
+ */
15
+ export interface ApiRequestable {
16
+ /**
17
+ * Execute one request.
18
+ *
19
+ * @param httpMethod GET, POST, PUT or DELETE.
20
+ * @param path The concrete path, placeholders already substituted.
21
+ * @param pathTemplate The same path with `*` in place of each substituted
22
+ * value, which makes calls to one endpoint groupable for logging or
23
+ * metrics regardless of the ids involved.
24
+ * @param params Query or body parameters.
25
+ */
26
+ doRequest(httpMethod: string, path: string, pathTemplate: string, params?: ApiParamType): Promise<unknown>;
27
+ }
28
+ /**
29
+ * Build the proxy that turns property access into API paths.
30
+ *
31
+ * Nothing is requested while the path is walked - each step returns a new
32
+ * proxy. The call happens when a `$`-prefixed method is invoked.
33
+ *
34
+ * @param engine Transport to send requests through.
35
+ * @param path Prefix every path is built on, normally `/api2/json`.
36
+ * @typeParam T The generated API shape to present, e.g. `Proxmox.Api`.
37
+ */
38
+ export declare function buildApiProxy<T>(engine: ApiRequestable, path: string): T;
39
+ //# sourceMappingURL=proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAgBA;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;;;OASG;IACH,SAAS,CACP,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,YAAY,GACpB,OAAO,CAAC,OAAO,CAAC,CAAC;CACrB;AAsID;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,CAExE"}
package/dist/proxy.js ADDED
@@ -0,0 +1,135 @@
1
+ // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
+ // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
+ //
4
+ // This program is free software: you can redistribute it and/or modify
5
+ // it under the terms of the GNU General Public License as published by
6
+ // the Free Software Foundation, either version 3 of the License, or
7
+ // (at your option) any later version.
8
+ //
9
+ // This program is distributed in the hope that it will be useful,
10
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ // GNU General Public License for more details.
13
+ //
14
+ // You should have received a copy of the GNU General Public License
15
+ // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ /**
17
+ * Keys that resolve on the node instead of extending the path.
18
+ *
19
+ * Without these, `String(proxmox)` or a debugger inspecting the object would
20
+ * silently build `/toString` and hand back another proxy.
21
+ */
22
+ const OBJECT_KEYS = new Set([
23
+ "toString",
24
+ "valueOf",
25
+ "toLocaleString",
26
+ ]);
27
+ /**
28
+ * Reserved at the root only.
29
+ *
30
+ * A root proxy is the value most likely to be handed to code that sniffs for
31
+ * an EventEmitter - a logger, a test harness - and every one of those probes
32
+ * would otherwise mint a path segment. Deeper nodes are not exposed that way,
33
+ * so they keep these names usable as real segments.
34
+ */
35
+ const EVENT_EMITTER_KEYS = new Set([
36
+ "addListener",
37
+ "emit",
38
+ "eventNames",
39
+ "getMaxListeners",
40
+ "listenerCount",
41
+ "listeners",
42
+ "off",
43
+ "on",
44
+ "once",
45
+ "prependListener",
46
+ "prependOnceListener",
47
+ "rawListeners",
48
+ "removeAllListeners",
49
+ "removeListener",
50
+ "setMaxListeners",
51
+ ]);
52
+ const ROOT_KEYS = new Set([
53
+ ...OBJECT_KEYS,
54
+ ...EVENT_EMITTER_KEYS,
55
+ ]);
56
+ /**
57
+ * Characters that would change the shape of the URL rather than sit inside a
58
+ * path segment. A `/` would invent a path level; `?` and `#` would start a
59
+ * query or fragment and drop the rest of the path.
60
+ */
61
+ const UNSAFE_IN_SEGMENT = /[/?#]/g;
62
+ function escapeSegment(value) {
63
+ return String(value).replace(UNSAFE_IN_SEGMENT, (char) => encodeURIComponent(char));
64
+ }
65
+ /**
66
+ * One node of the path being built.
67
+ *
68
+ * Nodes are immutable: navigating produces a new node, so a partially walked
69
+ * path can be held onto and reused.
70
+ */
71
+ class ApiNode {
72
+ engine;
73
+ path;
74
+ model;
75
+ constructor(engine, path, model) {
76
+ this.engine = engine;
77
+ this.path = path;
78
+ this.model = model;
79
+ }
80
+ toString() {
81
+ return `ProxyApi{path:${this.path}}`;
82
+ }
83
+ }
84
+ /**
85
+ * Resolve one property access into either a request function or the next node.
86
+ */
87
+ function navigate(node, key) {
88
+ if (key === "$") {
89
+ return (id) => descend(node, escapeSegment(id), "*", childHandler);
90
+ }
91
+ if (key.startsWith("$")) {
92
+ const httpMethod = key.slice(1);
93
+ return (params) => node.engine.doRequest(httpMethod, node.path, node.model, params);
94
+ }
95
+ // A leading underscore is the escape hatch for segments that collide with a
96
+ // reserved name: `_on` requests `/on`.
97
+ const segment = key.startsWith("_") ? key.slice(1) : key;
98
+ return descend(node, segment, segment, childHandler);
99
+ }
100
+ function descend(node, pathSegment, modelSegment, handler) {
101
+ return new Proxy(new ApiNode(node.engine, `${node.path}/${pathSegment}`, `${node.model}/${modelSegment}`), handler);
102
+ }
103
+ function createHandler(reserved) {
104
+ return {
105
+ // `new proxmox.nodes()` yields the node rather than throwing, which keeps
106
+ // the proxy inert in code that probes values by constructing them.
107
+ construct: (target) => target,
108
+ get(target, property) {
109
+ if (typeof property === "symbol" || reserved.has(property)) {
110
+ const value = Reflect.get(target, property);
111
+ // Bound to the node, not the proxy. Called on the proxy, `toString`
112
+ // would read `this.path` back through this trap, get another proxy,
113
+ // stringify that, and recurse until the stack ran out.
114
+ return typeof value === "function" ? value.bind(target) : value;
115
+ }
116
+ return navigate(target, property);
117
+ },
118
+ };
119
+ }
120
+ const childHandler = createHandler(OBJECT_KEYS);
121
+ const rootHandler = createHandler(ROOT_KEYS);
122
+ /**
123
+ * Build the proxy that turns property access into API paths.
124
+ *
125
+ * Nothing is requested while the path is walked - each step returns a new
126
+ * proxy. The call happens when a `$`-prefixed method is invoked.
127
+ *
128
+ * @param engine Transport to send requests through.
129
+ * @param path Prefix every path is built on, normally `/api2/json`.
130
+ * @typeParam T The generated API shape to present, e.g. `Proxmox.Api`.
131
+ */
132
+ export function buildApiProxy(engine, path) {
133
+ return new Proxy(new ApiNode(engine, path, path), rootHandler);
134
+ }
135
+ //# sourceMappingURL=proxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,gEAAgE;AAChE,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,oEAAoE;AACpE,sCAAsC;AACtC,EAAE;AACF,kEAAkE;AAClE,iEAAiE;AACjE,gEAAgE;AAChE,+CAA+C;AAC/C,EAAE;AACF,oEAAoE;AACpE,wEAAwE;AAoCxE;;;;;GAKG;AACH,MAAM,WAAW,GAAwB,IAAI,GAAG,CAAC;IAC/C,UAAU;IACV,SAAS;IACT,gBAAgB;CACjB,CAAC,CAAC;AAEH;;;;;;;GAOG;AACH,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC;IACtD,aAAa;IACb,MAAM;IACN,YAAY;IACZ,iBAAiB;IACjB,eAAe;IACf,WAAW;IACX,KAAK;IACL,IAAI;IACJ,MAAM;IACN,iBAAiB;IACjB,qBAAqB;IACrB,cAAc;IACd,oBAAoB;IACpB,gBAAgB;IAChB,iBAAiB;CAClB,CAAC,CAAC;AAEH,MAAM,S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