nestjs-web-console 1.0.1 → 1.0.3

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.
Files changed (47) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +66 -66
  3. package/dist/console.types.d.ts +75 -75
  4. package/dist/console.types.js +15 -15
  5. package/dist/controllers/web.console.controller.d.ts +1 -1
  6. package/dist/controllers/web.console.controller.js +690 -675
  7. package/dist/filters/http-exception.filter.d.ts +4 -4
  8. package/dist/filters/http-exception.filter.js +50 -50
  9. package/dist/index.d.ts +8 -8
  10. package/dist/index.js +24 -24
  11. package/dist/services/all.commands.d.ts +3 -3
  12. package/dist/services/all.commands.js +13 -13
  13. package/dist/services/processors/base/console.command.d.ts +8 -8
  14. package/dist/services/processors/base/console.command.js +27 -27
  15. package/dist/services/processors/base/invalid.command.d.ts +5 -5
  16. package/dist/services/processors/base/invalid.command.js +14 -14
  17. package/dist/services/processors/base/not-logged.command.d.ts +5 -5
  18. package/dist/services/processors/base/not-logged.command.js +10 -10
  19. package/dist/services/processors/bash.command.d.ts +7 -7
  20. package/dist/services/processors/bash.command.js +102 -102
  21. package/dist/services/processors/clear-screen.command.d.ts +6 -6
  22. package/dist/services/processors/clear-screen.command.js +30 -30
  23. package/dist/services/processors/cmd.command.d.ts +7 -7
  24. package/dist/services/processors/cmd.command.js +99 -99
  25. package/dist/services/processors/help.command.d.ts +7 -7
  26. package/dist/services/processors/help.command.js +41 -41
  27. package/dist/services/processors/index.d.ts +8 -8
  28. package/dist/services/processors/index.js +24 -24
  29. package/dist/services/processors/invite.command.d.ts +9 -9
  30. package/dist/services/processors/invite.command.js +76 -76
  31. package/dist/services/processors/join.command.d.ts +8 -8
  32. package/dist/services/processors/join.command.js +108 -108
  33. package/dist/services/processors/login.command.d.ts +14 -14
  34. package/dist/services/processors/login.command.js +69 -69
  35. package/dist/services/processors/logout.command.d.ts +6 -6
  36. package/dist/services/processors/logout.command.js +30 -30
  37. package/dist/services/remote.console.service.d.ts +30 -30
  38. package/dist/services/remote.console.service.js +107 -107
  39. package/dist/services/temp.file.service.d.ts +25 -23
  40. package/dist/services/temp.file.service.js +102 -90
  41. package/dist/services/web.console.service.d.ts +57 -57
  42. package/dist/services/web.console.service.js +437 -437
  43. package/dist/web.console.module.d.ts +6 -6
  44. package/dist/web.console.module.js +87 -87
  45. package/dist.zip +0 -0
  46. package/package.json +5 -5
  47. package/tsconfig.json +18 -18
@@ -1,437 +1,437 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
- return c > 3 && r && Object.defineProperty(target, key, r), r;
23
- };
24
- var __importStar = (this && this.__importStar) || function (mod) {
25
- if (mod && mod.__esModule) return mod;
26
- var result = {};
27
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
- __setModuleDefault(result, mod);
29
- return result;
30
- };
31
- var __metadata = (this && this.__metadata) || function (k, v) {
32
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.WebConsoleService = void 0;
39
- const common_1 = require("@nestjs/common");
40
- const core_1 = require("@nestjs/core");
41
- const moment_1 = __importDefault(require("moment"));
42
- const moment_duration_format_1 = __importDefault(require("moment-duration-format"));
43
- const node_eta_1 = __importDefault(require("node-eta"));
44
- const invalid_command_1 = require("./processors/base/invalid.command");
45
- const not_logged_command_1 = require("./processors/base/not-logged.command");
46
- (0, moment_duration_format_1.default)(moment_1.default);
47
- let WebConsoleService = class WebConsoleService {
48
- constructor(moduleRef) {
49
- Object.defineProperty(this, "moduleRef", {
50
- enumerable: true,
51
- configurable: true,
52
- writable: true,
53
- value: moduleRef
54
- });
55
- Object.defineProperty(this, "allCommands", {
56
- enumerable: true,
57
- configurable: true,
58
- writable: true,
59
- value: []
60
- });
61
- Object.defineProperty(this, "session", {
62
- enumerable: true,
63
- configurable: true,
64
- writable: true,
65
- value: {}
66
- });
67
- Object.defineProperty(this, "consoleOptions", {
68
- enumerable: true,
69
- configurable: true,
70
- writable: true,
71
- value: void 0
72
- });
73
- Object.defineProperty(this, "longWorkFactory", {
74
- enumerable: true,
75
- configurable: true,
76
- writable: true,
77
- value: (session) => async (process) => {
78
- let pgCurrent, pgMax, changed = false, lastPercent = -1;
79
- let eta;
80
- let progress = (current, max) => {
81
- if (pgMax != max) {
82
- eta = new node_eta_1.default(max);
83
- eta.start();
84
- }
85
- eta.iterate();
86
- if (pgCurrent != current || pgMax != max) {
87
- pgCurrent = current;
88
- pgMax = max;
89
- changed = true;
90
- }
91
- };
92
- let timer = setInterval(() => {
93
- if (changed) {
94
- changed = false;
95
- const percent = !pgMax ? 0 : Math.round(pgCurrent / pgMax * 100);
96
- if (lastPercent == -1 || percent - lastPercent >= 10) {
97
- //get estimates
98
- if (pgCurrent < pgMax) {
99
- this.log(session, `${percent}% (${pgCurrent}/${pgMax}) ${lastPercent == -1 ? '' : 'ETA: ' + moment_1.default.duration(+eta.format('{{eta}}'), 'seconds').format('hh:mm:ss', { trim: false })}`);
100
- lastPercent = percent;
101
- while (lastPercent % 10)
102
- lastPercent--;
103
- }
104
- }
105
- }
106
- }, 2000);
107
- await process(progress)
108
- .then(() => {
109
- this.log(session, `${!pgMax ? 0 : Math.round(pgCurrent / pgMax * 100)}% (${pgCurrent}/${pgMax}) ✔️`);
110
- })
111
- .finally(() => {
112
- clearInterval(timer);
113
- });
114
- }
115
- });
116
- Object.defineProperty(this, "loopFactory", {
117
- enumerable: true,
118
- configurable: true,
119
- writable: true,
120
- value: (session) => async (items, process) => {
121
- const wrappedProcess = async (progress) => {
122
- for (let i = 0; i < items.length; i++) {
123
- if (session.cancel)
124
- return;
125
- progress(i + 1, items.length);
126
- await process(items[i], i);
127
- }
128
- };
129
- return await this.longWorkFactory(session)(wrappedProcess);
130
- }
131
- });
132
- Object.defineProperty(this, "makeId", {
133
- enumerable: true,
134
- configurable: true,
135
- writable: true,
136
- value: length => {
137
- let text = "";
138
- const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
139
- for (let i = 0; i < length; i++) {
140
- text += possible.charAt(Math.floor(Math.random() * possible.length));
141
- }
142
- return text;
143
- }
144
- });
145
- Object.defineProperty(this, "getAppCookies", {
146
- enumerable: true,
147
- configurable: true,
148
- writable: true,
149
- value: (req) => {
150
- var _a;
151
- // We extract the raw cookies from the request headers
152
- const rawCookies = ((_a = req.headers.cookie) === null || _a === void 0 ? void 0 : _a.split('; ')) || [];
153
- const parsedCookies = {};
154
- rawCookies.forEach(rawCookie => {
155
- const parsedCookie = rawCookie.split('=');
156
- parsedCookies[parsedCookie[0]] = parsedCookie[1];
157
- });
158
- return parsedCookies;
159
- }
160
- });
161
- (async () => {
162
- const { ALL_COMMANDS } = await Promise.resolve().then(() => __importStar(require('./all.commands')));
163
- for (let i = 0; i < ALL_COMMANDS.length; i++) {
164
- let COMMAND = ALL_COMMANDS[i];
165
- this.allCommands.push(await moduleRef.create(COMMAND));
166
- }
167
- })().catch(console.warn);
168
- }
169
- parse(commandLine, session) {
170
- const index = commandLine.indexOf(' ');
171
- let command = '', arg = '';
172
- session.logs += `web:/> ${commandLine}<br/>`;
173
- try {
174
- if (index == -1) {
175
- command = commandLine;
176
- }
177
- else {
178
- command = commandLine.substring(0, index);
179
- arg = commandLine.substring(index + 1);
180
- }
181
- }
182
- catch (e) {
183
- }
184
- if (!command)
185
- return this.createInvalidCommand(commandLine, '');
186
- const commandObj = this.allCommands.find(x => x.command.toLowerCase() == command);
187
- if (!commandObj)
188
- return this.createInvalidCommand(commandLine, command);
189
- if (commandObj.requiresAuth && !session.isLogged)
190
- return this.createNotLoggedCommand(commandLine, '');
191
- return {
192
- cmd: commandObj,
193
- arg
194
- };
195
- }
196
- createInvalidCommand(rawCommand, command) {
197
- const cmd = new invalid_command_1.InvalidCommand();
198
- return { cmd, arg: command };
199
- }
200
- createNotLoggedCommand(rawCommand, command) {
201
- const cmd = new not_logged_command_1.NotLoggedCommand();
202
- return { cmd, arg: command };
203
- }
204
- log(session, text) {
205
- if (session.cancel)
206
- return;
207
- session.logs += '<div>' + text + '</div>';
208
- }
209
- toTable(entities, noColumns) {
210
- var _a;
211
- if (!entities)
212
- return 'Empty object';
213
- const isArray = Array.isArray(entities);
214
- if (!isArray && typeof entities != 'object')
215
- entities = { Result: entities };
216
- if (!isArray && (!entities || !Object.keys(entities).length))
217
- return 'Empty object';
218
- else if (isArray && !entities.length)
219
- return 'No records';
220
- const columns = noColumns ? [0] : Object.keys(isArray ? entities[0] : entities);
221
- let html = "<table border='1'>";
222
- //add header row
223
- if (!noColumns) {
224
- html += "<thead><tr>";
225
- for (let i = 0; i < columns.length; i++)
226
- html += "<th>" + columns[i] + "</th>";
227
- html += "</tr></thead>";
228
- }
229
- //add rows
230
- for (let i = 0; i < (isArray ? entities.length : 1); i++) {
231
- html += "<tr>";
232
- for (let j = 0; j < columns.length; j++)
233
- html += "<td>" + ((_a = (noColumns ? (isArray ? entities[i] : entities) : (isArray ? entities[i][columns[j]] : entities[columns[j]]))) === null || _a === void 0 ? void 0 : _a.toString()) + "</td>";
234
- html += "</tr>";
235
- }
236
- html += "</table>";
237
- return html;
238
- }
239
- readLine(session, title, opts) {
240
- return new Promise((res, rej) => {
241
- if (session.cancel)
242
- return rej('Operation canceled');
243
- session.logs += '<div class="row">' + title + '&nbsp;';
244
- session.readLineOpts = opts || {};
245
- session.readLineOpts['title'] = title + ' ';
246
- if (session.readLineOpts.boolean) {
247
- session.readLineOpts.select = [
248
- ['1', (typeof session.readLineOpts.boolean == 'boolean' || !session.readLineOpts.boolean.positive) ? 'Yes' : session.readLineOpts.boolean.positive],
249
- ['', (typeof session.readLineOpts.boolean == 'boolean' || !session.readLineOpts.boolean.negative) ? 'No' : session.readLineOpts.boolean.negative]
250
- ];
251
- if (typeof session.readLineOpts.boolean == 'object' && session.readLineOpts.boolean.reverse) {
252
- session.readLineOpts.select.reverse();
253
- }
254
- }
255
- session.readLineCallback = (input) => {
256
- if (session.cancel)
257
- return rej('Operation canceled');
258
- let displayInput;
259
- if (session.readLineOpts.secure)
260
- displayInput = '*'.repeat(input.length);
261
- else if (session.readLineOpts.select && Array.isArray(session.readLineOpts.select[0]))
262
- displayInput = session.readLineOpts.select.find(x => x[0] == input)[1];
263
- else
264
- displayInput = input;
265
- session.logs += displayInput + '</div>';
266
- res(input);
267
- };
268
- });
269
- }
270
- parseArgs(arg) {
271
- let parsedArgs = [];
272
- if (arg) {
273
- let w = '', wqs = false;
274
- for (let i = 0; i < arg.length; i++) {
275
- if (arg[i] == '"' && (i == 0 || arg[i - 1] != '\\')) {
276
- if (wqs) {
277
- if (w)
278
- parsedArgs.push(w);
279
- w = '';
280
- wqs = false;
281
- }
282
- else
283
- wqs = true;
284
- }
285
- else if (arg[i] == ' ' && !wqs) {
286
- if (w)
287
- parsedArgs.push(w);
288
- w = '';
289
- }
290
- else if (arg[i] == '\\' && (i == 0 || arg[i - 1] != '\\')) {
291
- continue;
292
- }
293
- else
294
- w += arg[i];
295
- }
296
- if (w)
297
- parsedArgs.push(w);
298
- }
299
- return parsedArgs;
300
- }
301
- async readArgs(session, arg, mapList, parameters) {
302
- const { result, flatResult } = await this._readArgs(session, mapList, this.parseArgs(arg));
303
- if (parameters) {
304
- if (parameters.confirm) {
305
- this.log(session, parameters.confirm['title'] || 'Executing command with parameters:');
306
- if (!parameters.confirm['skipTable']) {
307
- this.log(session, this.toTable(flatResult.reduce((o, v, i) => {
308
- o[v.label.endsWith(':') ? v.label.slice(-1) : v.label] = v.text;
309
- return o;
310
- }, {})));
311
- }
312
- if ((await this.readLine(session, 'Confirm? [Y/N]')).toLowerCase() != 'y') {
313
- throw new Error('Operation canceled');
314
- }
315
- }
316
- }
317
- return result;
318
- }
319
- getSession(req, res) {
320
- this.clearExpired();
321
- let sessionId = this.getAppCookies(req)['console-session'];
322
- if (!sessionId || !(sessionId in this.session)) {
323
- sessionId = this.makeId(16);
324
- res.cookie('console-session', sessionId);
325
- }
326
- let session = this.session[sessionId];
327
- if (!session)
328
- session = this.session[sessionId] = {
329
- logs: '',
330
- expires: Date.now() + this.consoleOptions.session.timeout,
331
- isLogged: false,
332
- running: false,
333
- readLineCallback: null,
334
- cancel: false,
335
- onCancel: null
336
- };
337
- else
338
- session.expires = Date.now() + this.consoleOptions.session.timeout;
339
- return session;
340
- }
341
- escapeHtml(unsafe) {
342
- return unsafe
343
- .replace(/&/g, "&amp;")
344
- .replace(/</g, "&lt;")
345
- .replace(/>/g, "&gt;")
346
- .replace(/"/g, "&quot;")
347
- .replace(/'/g, "&#039;");
348
- }
349
- async _readArgs(session, mapList, parsedArgs) {
350
- var _a, _b, _c, _d;
351
- let result = [], flatResult = [];
352
- for (let i = 0; i < mapList.length; i++) {
353
- let map = mapList[i];
354
- let label = map.title, text, input;
355
- if (parsedArgs.length) {
356
- const desiredInput = parsedArgs.shift();
357
- if ((_a = map.opts) === null || _a === void 0 ? void 0 : _a.boolean) {
358
- map.opts.select = [
359
- ['1', (typeof map.opts.boolean == 'boolean' || !map.opts.boolean.positive) ? 'Yes' : map.opts.boolean.positive],
360
- ['', (typeof map.opts.boolean == 'boolean' || !map.opts.boolean.negative) ? 'No' : map.opts.boolean.negative]
361
- ];
362
- if (typeof map.opts.boolean == 'object' && map.opts.boolean.reverse) {
363
- map.opts.select.reverse();
364
- }
365
- }
366
- if ((_b = map.opts) === null || _b === void 0 ? void 0 : _b.select) {
367
- const isArray = Array.isArray(map.opts.select[0]);
368
- if (isArray) {
369
- const pair = map.opts.select.find(x => x[1] == desiredInput);
370
- if (pair)
371
- input = pair[0];
372
- else
373
- session.logs += '<div>' + (`Invalid parameter "${desiredInput}". ${map.expectDesc || ''}`) + '</div>';
374
- }
375
- else if (map.opts.select.includes(desiredInput))
376
- input = desiredInput;
377
- else
378
- session.logs += '<div>' + (`Invalid parameter "${desiredInput}". ${map.expectDesc || ''}`) + '</div>';
379
- }
380
- else
381
- input = desiredInput;
382
- }
383
- while (true) {
384
- if (input == null)
385
- input = await this.readLine(session, map.title + (map.default ? ` [${map.default}]` : '') + ':', map.opts);
386
- if (!input && map.default)
387
- input = map.default;
388
- if (!map.expect || (typeof map.expect == 'string' ? expectRegex[map.expect] : map.expect).test(input)) {
389
- if (((_d = (_c = map.opts) === null || _c === void 0 ? void 0 : _c.select) === null || _d === void 0 ? void 0 : _d.length) && Array.isArray(map.opts.select[0]))
390
- text = map.opts.select.find(x => x[0] == input)[1];
391
- else
392
- text = input;
393
- break;
394
- }
395
- session.logs += '<div>' + (`Invalid parameter "${input}". ${map.expectDesc || ''}`) + '</div>';
396
- input = null;
397
- }
398
- flatResult.push({ input, label, text });
399
- result.push(input);
400
- if (map.then) {
401
- const innerResult = await this._readArgs(session, await map.then(input), parsedArgs);
402
- result.push(innerResult.result);
403
- flatResult.push(...innerResult.flatResult);
404
- }
405
- }
406
- return { result, flatResult };
407
- }
408
- clearExpired() {
409
- const keys = Object.keys(this.session);
410
- keys.forEach(key => {
411
- var _a;
412
- if (this.session[key].expires < Date.now()) {
413
- const session = this.session[key];
414
- session.cancel = true;
415
- (_a = session.onCancel) === null || _a === void 0 ? void 0 : _a.call(this);
416
- if (session.readLineCallback) {
417
- session.readLineCallback(null);
418
- session.readLineCallback = null;
419
- }
420
- session.running = false;
421
- delete this.session[key];
422
- }
423
- });
424
- }
425
- };
426
- __decorate([
427
- (0, common_1.Inject)('CONFIG_ROOT_OPTIONS'),
428
- __metadata("design:type", Object)
429
- ], WebConsoleService.prototype, "consoleOptions", void 0);
430
- WebConsoleService = __decorate([
431
- (0, common_1.Injectable)(),
432
- __metadata("design:paramtypes", [core_1.ModuleRef])
433
- ], WebConsoleService);
434
- exports.WebConsoleService = WebConsoleService;
435
- const expectRegex = {
436
- email: /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/
437
- };
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || function (mod) {
25
+ if (mod && mod.__esModule) return mod;
26
+ var result = {};
27
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
+ __setModuleDefault(result, mod);
29
+ return result;
30
+ };
31
+ var __metadata = (this && this.__metadata) || function (k, v) {
32
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.WebConsoleService = void 0;
39
+ const common_1 = require("@nestjs/common");
40
+ const core_1 = require("@nestjs/core");
41
+ const moment_1 = __importDefault(require("moment"));
42
+ const moment_duration_format_1 = __importDefault(require("moment-duration-format"));
43
+ const node_eta_1 = __importDefault(require("node-eta"));
44
+ const invalid_command_1 = require("./processors/base/invalid.command");
45
+ const not_logged_command_1 = require("./processors/base/not-logged.command");
46
+ (0, moment_duration_format_1.default)(moment_1.default);
47
+ let WebConsoleService = class WebConsoleService {
48
+ constructor(moduleRef) {
49
+ Object.defineProperty(this, "moduleRef", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: moduleRef
54
+ });
55
+ Object.defineProperty(this, "allCommands", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: []
60
+ });
61
+ Object.defineProperty(this, "session", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: {}
66
+ });
67
+ Object.defineProperty(this, "consoleOptions", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ Object.defineProperty(this, "longWorkFactory", {
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true,
77
+ value: (session) => async (process) => {
78
+ let pgCurrent, pgMax, changed = false, lastPercent = -1;
79
+ let eta;
80
+ let progress = (current, max) => {
81
+ if (pgMax != max) {
82
+ eta = new node_eta_1.default(max);
83
+ eta.start();
84
+ }
85
+ eta.iterate();
86
+ if (pgCurrent != current || pgMax != max) {
87
+ pgCurrent = current;
88
+ pgMax = max;
89
+ changed = true;
90
+ }
91
+ };
92
+ let timer = setInterval(() => {
93
+ if (changed) {
94
+ changed = false;
95
+ const percent = !pgMax ? 0 : Math.round(pgCurrent / pgMax * 100);
96
+ if (lastPercent == -1 || percent - lastPercent >= 10) {
97
+ //get estimates
98
+ if (pgCurrent < pgMax) {
99
+ this.log(session, `${percent}% (${pgCurrent}/${pgMax}) ${lastPercent == -1 ? '' : 'ETA: ' + moment_1.default.duration(+eta.format('{{eta}}'), 'seconds').format('hh:mm:ss', { trim: false })}`);
100
+ lastPercent = percent;
101
+ while (lastPercent % 10)
102
+ lastPercent--;
103
+ }
104
+ }
105
+ }
106
+ }, 2000);
107
+ await process(progress)
108
+ .then(() => {
109
+ this.log(session, `${!pgMax ? 0 : Math.round(pgCurrent / pgMax * 100)}% (${pgCurrent}/${pgMax}) ✔️`);
110
+ })
111
+ .finally(() => {
112
+ clearInterval(timer);
113
+ });
114
+ }
115
+ });
116
+ Object.defineProperty(this, "loopFactory", {
117
+ enumerable: true,
118
+ configurable: true,
119
+ writable: true,
120
+ value: (session) => async (items, process) => {
121
+ const wrappedProcess = async (progress) => {
122
+ for (let i = 0; i < items.length; i++) {
123
+ if (session.cancel)
124
+ return;
125
+ progress(i + 1, items.length);
126
+ await process(items[i], i);
127
+ }
128
+ };
129
+ return await this.longWorkFactory(session)(wrappedProcess);
130
+ }
131
+ });
132
+ Object.defineProperty(this, "makeId", {
133
+ enumerable: true,
134
+ configurable: true,
135
+ writable: true,
136
+ value: length => {
137
+ let text = "";
138
+ const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
139
+ for (let i = 0; i < length; i++) {
140
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
141
+ }
142
+ return text;
143
+ }
144
+ });
145
+ Object.defineProperty(this, "getAppCookies", {
146
+ enumerable: true,
147
+ configurable: true,
148
+ writable: true,
149
+ value: (req) => {
150
+ var _a;
151
+ // We extract the raw cookies from the request headers
152
+ const rawCookies = ((_a = req.headers.cookie) === null || _a === void 0 ? void 0 : _a.split('; ')) || [];
153
+ const parsedCookies = {};
154
+ rawCookies.forEach(rawCookie => {
155
+ const parsedCookie = rawCookie.split('=');
156
+ parsedCookies[parsedCookie[0]] = parsedCookie[1];
157
+ });
158
+ return parsedCookies;
159
+ }
160
+ });
161
+ (async () => {
162
+ const { ALL_COMMANDS } = await Promise.resolve().then(() => __importStar(require('./all.commands')));
163
+ for (let i = 0; i < ALL_COMMANDS.length; i++) {
164
+ let COMMAND = ALL_COMMANDS[i];
165
+ this.allCommands.push(await moduleRef.create(COMMAND));
166
+ }
167
+ })().catch(console.warn);
168
+ }
169
+ parse(commandLine, session) {
170
+ const index = commandLine.indexOf(' ');
171
+ let command = '', arg = '';
172
+ session.logs += `web:/> ${commandLine}<br/>`;
173
+ try {
174
+ if (index == -1) {
175
+ command = commandLine;
176
+ }
177
+ else {
178
+ command = commandLine.substring(0, index);
179
+ arg = commandLine.substring(index + 1);
180
+ }
181
+ }
182
+ catch (e) {
183
+ }
184
+ if (!command)
185
+ return this.createInvalidCommand(commandLine, '');
186
+ const commandObj = this.allCommands.find(x => x.command.toLowerCase() == command);
187
+ if (!commandObj)
188
+ return this.createInvalidCommand(commandLine, command);
189
+ if (commandObj.requiresAuth && !session.isLogged)
190
+ return this.createNotLoggedCommand(commandLine, '');
191
+ return {
192
+ cmd: commandObj,
193
+ arg
194
+ };
195
+ }
196
+ createInvalidCommand(rawCommand, command) {
197
+ const cmd = new invalid_command_1.InvalidCommand();
198
+ return { cmd, arg: command };
199
+ }
200
+ createNotLoggedCommand(rawCommand, command) {
201
+ const cmd = new not_logged_command_1.NotLoggedCommand();
202
+ return { cmd, arg: command };
203
+ }
204
+ log(session, text) {
205
+ if (session.cancel)
206
+ return;
207
+ session.logs += '<div>' + text + '</div>';
208
+ }
209
+ toTable(entities, noColumns) {
210
+ var _a;
211
+ if (!entities)
212
+ return 'Empty object';
213
+ const isArray = Array.isArray(entities);
214
+ if (!isArray && typeof entities != 'object')
215
+ entities = { Result: entities };
216
+ if (!isArray && (!entities || !Object.keys(entities).length))
217
+ return 'Empty object';
218
+ else if (isArray && !entities.length)
219
+ return 'No records';
220
+ const columns = noColumns ? [0] : Object.keys(isArray ? entities[0] : entities);
221
+ let html = "<div style='overflow-x: auto'><table border='1'>";
222
+ //add header row
223
+ if (!noColumns) {
224
+ html += "<thead><tr>";
225
+ for (let i = 0; i < columns.length; i++)
226
+ html += "<th>" + columns[i] + "</th>";
227
+ html += "</tr></thead>";
228
+ }
229
+ //add rows
230
+ for (let i = 0; i < (isArray ? entities.length : 1); i++) {
231
+ html += "<tr>";
232
+ for (let j = 0; j < columns.length; j++)
233
+ html += "<td>" + ((_a = (noColumns ? (isArray ? entities[i] : entities) : (isArray ? entities[i][columns[j]] : entities[columns[j]]))) === null || _a === void 0 ? void 0 : _a.toString()) + "</td>";
234
+ html += "</tr>";
235
+ }
236
+ html += "</table></div>";
237
+ return html;
238
+ }
239
+ readLine(session, title, opts) {
240
+ return new Promise((res, rej) => {
241
+ if (session.cancel)
242
+ return rej('Operation canceled');
243
+ session.logs += '<div class="row">' + title + '&nbsp;';
244
+ session.readLineOpts = opts || {};
245
+ session.readLineOpts['title'] = title + ' ';
246
+ if (session.readLineOpts.boolean) {
247
+ session.readLineOpts.select = [
248
+ ['1', (typeof session.readLineOpts.boolean == 'boolean' || !session.readLineOpts.boolean.positive) ? 'Yes' : session.readLineOpts.boolean.positive],
249
+ ['', (typeof session.readLineOpts.boolean == 'boolean' || !session.readLineOpts.boolean.negative) ? 'No' : session.readLineOpts.boolean.negative]
250
+ ];
251
+ if (typeof session.readLineOpts.boolean == 'object' && session.readLineOpts.boolean.reverse) {
252
+ session.readLineOpts.select.reverse();
253
+ }
254
+ }
255
+ session.readLineCallback = (input) => {
256
+ if (session.cancel)
257
+ return rej('Operation canceled');
258
+ let displayInput;
259
+ if (session.readLineOpts.secure)
260
+ displayInput = '*'.repeat(input.length);
261
+ else if (session.readLineOpts.select && Array.isArray(session.readLineOpts.select[0]))
262
+ displayInput = session.readLineOpts.select.find(x => x[0] == input)[1];
263
+ else
264
+ displayInput = input;
265
+ session.logs += displayInput + '</div>';
266
+ res(input);
267
+ };
268
+ });
269
+ }
270
+ parseArgs(arg) {
271
+ let parsedArgs = [];
272
+ if (arg) {
273
+ let w = '', wqs = false;
274
+ for (let i = 0; i < arg.length; i++) {
275
+ if (arg[i] == '"' && (i == 0 || arg[i - 1] != '\\')) {
276
+ if (wqs) {
277
+ if (w)
278
+ parsedArgs.push(w);
279
+ w = '';
280
+ wqs = false;
281
+ }
282
+ else
283
+ wqs = true;
284
+ }
285
+ else if (arg[i] == ' ' && !wqs) {
286
+ if (w)
287
+ parsedArgs.push(w);
288
+ w = '';
289
+ }
290
+ else if (arg[i] == '\\' && (i == 0 || arg[i - 1] != '\\')) {
291
+ continue;
292
+ }
293
+ else
294
+ w += arg[i];
295
+ }
296
+ if (w)
297
+ parsedArgs.push(w);
298
+ }
299
+ return parsedArgs;
300
+ }
301
+ async readArgs(session, arg, mapList, parameters) {
302
+ const { result, flatResult } = await this._readArgs(session, mapList, this.parseArgs(arg));
303
+ if (parameters) {
304
+ if (parameters.confirm) {
305
+ this.log(session, parameters.confirm['title'] || 'Executing command with parameters:');
306
+ if (!parameters.confirm['skipTable']) {
307
+ this.log(session, this.toTable(flatResult.reduce((o, v, i) => {
308
+ o[v.label.endsWith(':') ? v.label.slice(-1) : v.label] = v.text;
309
+ return o;
310
+ }, {})));
311
+ }
312
+ if ((await this.readLine(session, 'Confirm? [Y/N]')).toLowerCase() != 'y') {
313
+ throw new Error('Operation canceled');
314
+ }
315
+ }
316
+ }
317
+ return result;
318
+ }
319
+ getSession(req, res) {
320
+ this.clearExpired();
321
+ let sessionId = this.getAppCookies(req)['console-session'];
322
+ if (!sessionId || !(sessionId in this.session)) {
323
+ sessionId = this.makeId(16);
324
+ res.cookie('console-session', sessionId);
325
+ }
326
+ let session = this.session[sessionId];
327
+ if (!session)
328
+ session = this.session[sessionId] = {
329
+ logs: '',
330
+ expires: Date.now() + this.consoleOptions.session.timeout,
331
+ isLogged: false,
332
+ running: false,
333
+ readLineCallback: null,
334
+ cancel: false,
335
+ onCancel: null
336
+ };
337
+ else
338
+ session.expires = Date.now() + this.consoleOptions.session.timeout;
339
+ return session;
340
+ }
341
+ escapeHtml(unsafe) {
342
+ return unsafe
343
+ .replace(/&/g, "&amp;")
344
+ .replace(/</g, "&lt;")
345
+ .replace(/>/g, "&gt;")
346
+ .replace(/"/g, "&quot;")
347
+ .replace(/'/g, "&#039;");
348
+ }
349
+ async _readArgs(session, mapList, parsedArgs) {
350
+ var _a, _b, _c, _d;
351
+ let result = [], flatResult = [];
352
+ for (let i = 0; i < mapList.length; i++) {
353
+ let map = mapList[i];
354
+ let label = map.title, text, input;
355
+ if (parsedArgs.length) {
356
+ const desiredInput = parsedArgs.shift();
357
+ if ((_a = map.opts) === null || _a === void 0 ? void 0 : _a.boolean) {
358
+ map.opts.select = [
359
+ ['1', (typeof map.opts.boolean == 'boolean' || !map.opts.boolean.positive) ? 'Yes' : map.opts.boolean.positive],
360
+ ['', (typeof map.opts.boolean == 'boolean' || !map.opts.boolean.negative) ? 'No' : map.opts.boolean.negative]
361
+ ];
362
+ if (typeof map.opts.boolean == 'object' && map.opts.boolean.reverse) {
363
+ map.opts.select.reverse();
364
+ }
365
+ }
366
+ if ((_b = map.opts) === null || _b === void 0 ? void 0 : _b.select) {
367
+ const isArray = Array.isArray(map.opts.select[0]);
368
+ if (isArray) {
369
+ const pair = map.opts.select.find(x => x[1] == desiredInput);
370
+ if (pair)
371
+ input = pair[0];
372
+ else
373
+ session.logs += '<div>' + (`Invalid parameter "${desiredInput}". ${map.expectDesc || ''}`) + '</div>';
374
+ }
375
+ else if (map.opts.select.includes(desiredInput))
376
+ input = desiredInput;
377
+ else
378
+ session.logs += '<div>' + (`Invalid parameter "${desiredInput}". ${map.expectDesc || ''}`) + '</div>';
379
+ }
380
+ else
381
+ input = desiredInput;
382
+ }
383
+ while (true) {
384
+ if (input == null)
385
+ input = await this.readLine(session, map.title + (map.default ? ` [${map.default}]` : '') + ':', map.opts);
386
+ if (!input && map.default)
387
+ input = map.default;
388
+ if (!map.expect || (typeof map.expect == 'string' ? expectRegex[map.expect] : map.expect).test(input)) {
389
+ if (((_d = (_c = map.opts) === null || _c === void 0 ? void 0 : _c.select) === null || _d === void 0 ? void 0 : _d.length) && Array.isArray(map.opts.select[0]))
390
+ text = map.opts.select.find(x => x[0] == input)[1];
391
+ else
392
+ text = input;
393
+ break;
394
+ }
395
+ session.logs += '<div>' + (`Invalid parameter "${input}". ${map.expectDesc || ''}`) + '</div>';
396
+ input = null;
397
+ }
398
+ flatResult.push({ input, label, text });
399
+ result.push(input);
400
+ if (map.then) {
401
+ const innerResult = await this._readArgs(session, await map.then(input), parsedArgs);
402
+ result.push(innerResult.result);
403
+ flatResult.push(...innerResult.flatResult);
404
+ }
405
+ }
406
+ return { result, flatResult };
407
+ }
408
+ clearExpired() {
409
+ const keys = Object.keys(this.session);
410
+ keys.forEach(key => {
411
+ var _a;
412
+ if (this.session[key].expires < Date.now()) {
413
+ const session = this.session[key];
414
+ session.cancel = true;
415
+ (_a = session.onCancel) === null || _a === void 0 ? void 0 : _a.call(this);
416
+ if (session.readLineCallback) {
417
+ session.readLineCallback(null);
418
+ session.readLineCallback = null;
419
+ }
420
+ session.running = false;
421
+ delete this.session[key];
422
+ }
423
+ });
424
+ }
425
+ };
426
+ __decorate([
427
+ (0, common_1.Inject)('CONFIG_ROOT_OPTIONS'),
428
+ __metadata("design:type", Object)
429
+ ], WebConsoleService.prototype, "consoleOptions", void 0);
430
+ WebConsoleService = __decorate([
431
+ (0, common_1.Injectable)(),
432
+ __metadata("design:paramtypes", [core_1.ModuleRef])
433
+ ], WebConsoleService);
434
+ exports.WebConsoleService = WebConsoleService;
435
+ const expectRegex = {
436
+ email: /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/
437
+ };