Repository navigation
Expand file tree
/
Copy pathindex.mjs
More file actions
343 lines (273 loc) · 12.4 KB
/
Copy pathindex.mjs
File metadata and controls
343 lines (273 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import Logger from "@hackthedev/terminal-logger";
import FrontendLibs from "@hackthedev/frontend-libs";
import ExpressStarter from "@hackthedev/express-starter"
import crypto from "crypto"
import path from "path"
import { exec } from "child_process";
import { fileURLToPath } from "url";
import fs from "node:fs";
export const __filename = fileURLToPath(import.meta.url);
export const __dirname = path.dirname(__filename);
export default class SetupWizard {
constructor({
onCompleted = null,
debug = false,
title = "Setup Wizard",
subtitle = "Easy Web Installer",
redirectUrl = null
} = {}){
this.webEndpointId = crypto.randomUUID();
this.starter = new ExpressStarter()
this.starter.registerErrorHandlers(); // avoid crashing and enable error logging
this.starter.registerTemplateMiddleware({
publicWebDir: path.join(__dirname, "public"),
urlPrefix: `/wizard/${this.webEndpointId}`,
getPlaceholders: async (req) => {
return [
["setup.title", () => title],
["setup.subtitle", () => subtitle]
]
}
}); // cool template engine
this.debug = debug;
this.app = this.starter.app;
this.express = this.starter.express;
this.redirectUrl = redirectUrl
Logger.logDebug = debug;
// current step
this.index = 0;
this.steps = new Map();
this.prerequisites = {};
this.values = {}
// callbacks
this.onCompleted = onCompleted
this.installLibs();
this.starter.startHttpServer(5000, () => {
this.registerWebEndpoint();
Logger.success("Setup Page is available at:")
Logger.success(`http://localhost:${this.starter.server.address().port}/wizard/${this.webEndpointId}/`)
Logger.warn("Copy the url to continue the setup process.")
})
this.customJsDir = path.join(__dirname, "public", "js", "custom");
if(!fs.existsSync(this.customJsDir)) fs.mkdirSync(this.customJsDir);
}
async exitSetup() {
try {
if (this.starter?.server) {
await new Promise((resolve, reject) => {
this.starter.server.close((error) => {
if (error) return reject(error);
resolve();
});
});
Logger.success("Setup server stopped.");
}
} catch (error) {
Logger.error("Failed to stop setup server:");
Logger.error(error);
}
}
async installLibs(){
try{
let libDir = path.join(__dirname, "public", "js", "libs");
const results = await FrontendLibs.installMultiple([
{ package: '@hackthedev/icons@latest', path: libDir },
{ package: '@hackthedev/element-loader@latest', path: libDir },
{ package: '@hackthedev/chat-tools@latest', path: libDir },
]);
results.forEach((r) => {
if(r?.success || r?.skipped){
Logger.debug(r?.message)
}
else{
Logger.error(r?.message)
}
});
}
catch(exc){
Logger.error(exc);
}
}
addPrerequisites(prerequisites = {}){
this.prerequisites = prerequisites
}
addStep(step = {}){
if(!step?.id) throw new Error("Missing step identifier (id)");
if(!step?.title) throw new Error("Missing Step title");
if(!step?.description) Logger.debug(`Step ${step?.id} is missing a description. Its recommended!`)
// avoid duplicates
if(this.steps.has(step.id)){
return Logger.debug(`Step ${step.id} already exists! Skipped...`)
}
this.steps.set(step.id, step)
}
getPrerequisite(prerequisitieIndex) {
const prerequisite =
this.prerequisites?.[this.getOSName()]?.[Number(prerequisitieIndex)];
if (!prerequisite) return null;
return {
title: prerequisite?.title ?? null,
check: prerequisite?.check ?? null,
install: prerequisite?.install ?? null,
execute: prerequisite?.execute ?? null,
};
}
registerWebEndpoint(){
this.app.post(`/wizard/${this.webEndpointId}/prerequisites/:prerequisitieIndex/execute`, this.express.json(), async(req, res, next) => {
let prerequisitieIndex = req?.params?.prerequisitieIndex ?? null;
let data = req.body ?? null;
if(!prerequisitieIndex) return res.status(404).json({ error: "Prerequisite id not found"})
// get the actions like check, install, execute
let prerequisite = this.getPrerequisite(prerequisitieIndex);
if(!prerequisite) return res.status(404).json({ error: `Prerequisites execute steps not found for ${this.getOSName()}`})
let executeCommands = prerequisite?.execute;
if(executeCommands?.length === 0) return res.status(200).json({ error: null})
// check system test commands
let testResults = {}
for(let i = 0; i < executeCommands.length; i++){
let command = executeCommands[i];
let {success, stdout, stderr, code} = await this.runCommand(command);
if(stderr?.trim() === "") stderr = null;
const isWorking = success === true && code === 0;
testResults = {
success: !!isWorking,
stdout,
stderr: stderr ?? null,
code
}
// some debug help
if(isWorking === false){
Logger.debug(`Prerequisite execute was not successful for (${prerequisitieIndex})`)
Logger.debug(testResults)
}
}
res.status(200).json({ error: null, results: testResults});
})
this.app.post(`/wizard/${this.webEndpointId}/prerequisites/:prerequisitieIndex/install`, this.express.json(), async(req, res, next) => {
let prerequisitieIndex = req?.params?.prerequisitieIndex ?? null;
let data = req.body ?? null;
if(!prerequisitieIndex && prerequisitieIndex !== 0) return res.status(404).json({ error: "Prerequisite id not found"})
// get the actions like check, install, execute
let prerequisite = this.getPrerequisite(prerequisitieIndex);
if(!prerequisite) return res.status(404).json({ error: `Prerequisites install steps not found for${this.getOSName()}`})
let installCommands = prerequisite?.install;
if(installCommands?.length === 0) return res.status(404).json({ error: `Prerequisites install step not found for ${this.getOSName()}`})
// check system test commands
let testResults = {}
for(let i = 0; i < installCommands.length; i++){
let command = installCommands[i];
let {success, stdout, stderr, code} = await this.runCommand(command);
if(stderr?.trim() === "") stderr = null;
const isWorking = success === true && code === 0;
testResults = {
success: !!isWorking,
stdout,
stderr: stderr ?? null,
code
}
// some debug help
if(isWorking === false){
Logger.debug(`Prerequisite install was not successful for (${prerequisitieIndex})`)
Logger.debug(testResults)
}
}
res.status(200).json({ error: null, results: testResults});
})
this.app.post(`/wizard/${this.webEndpointId}/prerequisites/:prerequisitieIndex/check`, this.express.json(), async(req, res, next) => {
let prerequisitieIndex = req?.params?.prerequisitieIndex ?? null;
let data = req.body ?? null;
if(!prerequisitieIndex) return res.status(404).json({ error: "Prerequisite id not found"})
let prerequisite = this.getPrerequisite(prerequisitieIndex);
if(!prerequisite) return res.status(404).json({ error: `Prerequisites check steps not found for ${this.getOSName()}`})
let checkCommands = prerequisite?.check;
if(checkCommands?.length === 0) return res.status(404).json({ error: `Prerequisites check step not found for ${this.getOSName()}`})
// check system test commands
let testResults = {}
for(let i = 0; i < checkCommands.length; i++){
let command = checkCommands[i];
let cmd = command[0];
let expect = command[1] ?? null;
let {success, stdout, stderr, code} = await this.runCommand(cmd);
if(stderr?.trim() === "") stderr = null;
const isWorking = stdout.includes(expect) || stderr?.includes(expect);
testResults = {
success: !!isWorking,
stdout,
stderr: isWorking ? null : stderr,
code
}
}
res.status(200).json({ error: null, results: testResults});
})
this.app.post(`/wizard/${this.webEndpointId}/step/:stepId/test`, this.express.json(), async(req, res, next) => {
let stepId = req?.params?.stepId ?? null;
let data = req.body ?? null;
if(!stepId) return res.status(404).json({ error: "Step not found"})
if(!this.steps.has(stepId)) return res.status(404).json({ error: "Step not found"})
let step = this.steps.get(stepId);
if(step?.test && typeof step?.test === "function"){
let stepTestError = await step.test(data)
if(stepTestError?.error) {
return res.status(200).json({ error: stepTestError.error });
}
}
res.status(200).json({ error: null});
})
this.app.get(`/wizard/${this.webEndpointId}/steps`, this.express.json(), async(req, res, next) => {
res.status(200).json({steps: Object.fromEntries(this.steps)})
})
this.app.get(`/wizard/${this.webEndpointId}/prerequisites`, this.express.json(), async(req, res, next) => {
res.status(200).json({prerequisites: this.prerequisites?.[this.getOSName()]})
})
this.app.get(`/wizard/${this.webEndpointId}/finish`, this.express.json(), async(req, res, next) => {
if(this.onCompleted && typeof this.onCompleted === "function") await this.onCompleted();
res.status(200).json({ error: null, redirectUrl: this.redirectUrl})
await this.exitSetup();
})
this.app.get(`/wizard/${this.webEndpointId}/js/custom`, async (req, res) => {
try {
const files = await fs.promises.readdir(this.customJsDir);
const jsFiles = files
.filter(file => file.endsWith(".js"))
.map(file => `/wizard/${this.webEndpointId}/js/custom/${file}`);
res.status(200).json({
files: jsFiles
});
}
catch (exc) {
Logger.error(exc);
res.status(500).json({
error: "Failed to load custom JS files"
});
}
});
this.app.use(
`/wizard/${this.webEndpointId}`,
this.express.static(
path.join(__dirname, "public")
)
);
}
runCommand(command) {
return new Promise((resolve) => {
exec(command, (error, stdout, stderr) => {
resolve({
success: !error,
code: error?.code ?? 0,
stdout: stdout.trim(),
stderr: stderr.trim()
});
});
});
}
getOSName() {
switch (process.platform) {
case "win32":
return "windows";
case "linux":
return "linux";
default:
throw new Error(`Unsupported OS: ${process.platform}`);
}
}
}