-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathorchestrator.js
More file actions
335 lines (299 loc) · 10 KB
/
Copy pathorchestrator.js
File metadata and controls
335 lines (299 loc) · 10 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
#!/usr/bin/env node
const { spawn } = require('child_process')
const readline = require('readline')
const http = require('http')
const os = require('os')
const path = require('path')
const axios = require('axios')
const mode = process.argv[2] || 'prod'
const isWin = os.platform() === 'win32'
const npmCmd = isWin ? 'npm.cmd' : 'npm'
const colors = {
reset: '\x1b[0m',
server: '\x1b[36m',
client: '\x1b[32m',
system: '\x1b[33m',
}
if (mode === '--version' || mode === '-v') {
const pkg = require('./package.json')
console.log(`dango version ${pkg.version}`)
process.exit(0)
}
async function checkForUpdates() {
if (process.argv.includes('--no-update') || mode === 'dev') return
try {
const npmGlobalPrefix = require('child_process')
.execSync('npm config get prefix', { encoding: 'utf8' })
.trim()
const scriptPath = path.resolve(__dirname)
const isGlobalInstall = scriptPath.includes(npmGlobalPrefix)
const pkg = require('./package.json')
const current = pkg.version
if (isGlobalInstall) {
const { data } = await axios.get('https://registry.npmjs.org/@serifpersia/dango/latest', {
timeout: 3000,
headers: { 'User-Agent': 'dango-cli' },
})
const latest = data.version
if (current !== latest) {
console.log(
`\n${colors.system}[Update]${colors.reset} ` +
`New version ${colors.client}${latest}${colors.reset} available (current: ${current})`
)
if (process.stdin.isTTY) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
const answer = await new Promise((resolve) => {
rl.question(
`${colors.system}[Update]${colors.reset} Would you like to perform a clean install now? (y/N) `,
(ans) => {
rl.close()
resolve(ans.toLowerCase())
}
)
})
if (answer === 'y' || answer === 'yes') {
console.log(`${colors.system}[Update]${colors.reset} Updating dango...`)
try {
require('child_process').execSync(`${npmCmd} install -g @serifpersia/dango@latest`, {
stdio: 'inherit',
})
console.log(
`\n${colors.system}[Update]${colors.reset} Update successful! Please restart dango to apply changes.`
)
process.exit(0)
} catch (err) {
console.error(
`\n${colors.system}[Update]${colors.reset} Update failed: ${err.message}`
)
if (!isWin) {
console.log(
`${colors.system}[Update]${colors.reset} Hint: You might need to run with sudo:`
)
console.log(
`${colors.system}[Update]${colors.reset} ${colors.client}sudo dango${colors.reset}\n`
)
}
console.log(
`${colors.system}[Update]${colors.reset} Continuing with current version...\n`
)
}
} else {
console.log(
`${colors.system}[Update]${colors.reset} Continuing with version ${current}...\n`
)
}
if (process.stdin.isTTY) process.stdin.resume()
} else {
console.log(
`${colors.system}[Update]${colors.reset} Run: npm install -g @serifpersia/dango to update.\n`
)
}
}
} else {
const { data } = await axios.get(
'https://api.github.com/repos/serifpersia/dango/releases/latest',
{ timeout: 3000 }
)
const latestDate = new Date(data.published_at)
const pkgDate = new Date(pkg.versionDate || 0)
if (latestDate > pkgDate) {
console.log(`\n${colors.system}====================================================`)
console.log(`${colors.system}[Update Available]${colors.reset} New version found!`)
console.log(
`Please download the latest release: ${colors.client}${data.html_url}${colors.reset}`
)
console.log(`Replace your current files with the new ones from the zip.`)
console.log(
`${colors.system}====================================================\n${colors.reset}`
)
}
}
} catch (error) {
// Silently ignore network/registry errors
}
}
const SERVER_DIR = path.join(__dirname, 'server')
const CLIENT_DIR = path.join(__dirname, 'client')
let syncSpinner = null
let syncMessage = ''
let syncDots = 0
const startSpinner = (msg) => {
syncMessage = msg
syncDots = 0
process.stdout.write(`${colors.system}[System]${colors.reset} ${msg}`)
syncSpinner = setInterval(() => {
syncDots = (syncDots + 1) % 4
process.stdout.write(
`\r${colors.system}[System]${colors.reset} ${msg}${'.'.repeat(syncDots)}${' '.repeat(3 - syncDots)}`
)
}, 400)
}
const stopSpinner = () => {
if (syncSpinner) {
clearInterval(syncSpinner)
syncSpinner = null
process.stdout.write('\n')
}
}
const log = (prefix, color, data) => {
const str = data.toString()
if (str.includes('[SYNC_START]')) {
const parts = str.split('[SYNC_START]')
if (parts[1]) startSpinner(parts[1].split('\n')[0].trim())
return
}
if (str.includes('[SYNC_END]')) {
stopSpinner()
return
}
if (str.includes('[SERVER_EXIT]')) {
stopSpinner()
console.log(
`${colors.system}[System]${colors.reset} Server sync complete. Shutting down cleanly.`
)
if (isWin) {
if (serverProcess) spawn('taskkill', ['/pid', serverProcess.pid, '/f', '/t'], { shell: true })
if (clientProcess) spawn('taskkill', ['/pid', clientProcess.pid, '/f', '/t'], { shell: true })
} else {
if (serverProcess) {
try {
process.kill(-serverProcess.pid, 'SIGTERM')
} catch {}
}
if (clientProcess) {
try {
process.kill(-clientProcess.pid, 'SIGTERM')
} catch {}
}
}
setTimeout(() => process.exit(0), 2000)
return
}
const lines = str.split('\n').filter((line) => line.trim() !== '')
if (lines.length === 0) return
if (syncSpinner) {
process.stdout.write('\r\x1b[K')
for (const line of lines) {
console.log(`${color}[${prefix}]${colors.reset} ${line}`)
}
process.stdout.write(
`${colors.system}[System]${colors.reset} ${syncMessage}${'.'.repeat(syncDots)}${' '.repeat(3 - syncDots)}`
)
} else {
for (const line of lines) {
console.log(`${color}[${prefix}]${colors.reset} ${line}`)
}
}
}
const spawnOpts = (cwd) => ({
stdio: 'pipe',
shell: isWin,
cwd,
detached: !isWin,
windowsHide: true,
})
let serverProcess, clientProcess
let isShuttingDown = false
async function main() {
console.log(
`${colors.system}[System]${colors.reset} Starting dango in ${mode.toUpperCase()} mode...`
)
console.log(
`${colors.system}[System]${colors.reset} Press 'q' or 'Ctrl+C' to cleanly exit and sync data.\n`
)
if (mode === 'dev') {
serverProcess = spawn(npmCmd, ['run', 'dev'], spawnOpts(SERVER_DIR))
clientProcess = spawn(npmCmd, ['run', 'dev'], spawnOpts(CLIENT_DIR))
} else {
const serverPath = path.join(SERVER_DIR, 'dist', 'server.js')
serverProcess = spawn('node', ['--max-old-space-size=256', serverPath], spawnOpts(SERVER_DIR))
}
if (serverProcess) {
serverProcess.stdout.on('data', (data) => log('Server', colors.server, data))
serverProcess.stderr.on('data', (data) => log('Server', colors.server, data))
serverProcess.on('exit', (code) => {
if (!isShuttingDown) {
log('System', colors.system, `Server crashed or exited prematurely.`)
process.exit(code || 0)
}
})
}
if (clientProcess) {
clientProcess.stdout.on('data', (data) => log('Client', colors.client, data))
clientProcess.stderr.on('data', (data) => log('Client', colors.client, data))
}
if (process.stdin.isTTY) {
process.stdin.resume()
readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)
}
process.stdin.on('keypress', (str, key) => {
if (key && (key.name === 'q' || (key.ctrl && key.name === 'c'))) {
shutdown()
}
})
}
const shutdown = () => {
if (isShuttingDown) return
isShuttingDown = true
console.log(`\n${colors.system}[System]${colors.reset} Initiating clean shutdown...`)
if (clientProcess) {
if (isWin) spawn('taskkill', ['/pid', clientProcess.pid, '/f', '/t'], { shell: true })
else {
clientProcess.kill('SIGTERM')
setTimeout(() => {
if (clientProcess.connected || !clientProcess.killed) clientProcess.kill('SIGKILL')
}, 5000)
}
}
const req = http.request({
hostname: '127.0.0.1',
port: 3000,
path: '/api/internal/shutdown',
method: 'POST',
})
req.on('error', () => {
console.log(`${colors.system}[System]${colors.reset} Server unreachable, forcing exit.`)
if (isWin && serverProcess)
spawn('taskkill', ['/pid', serverProcess.pid, '/f', '/t'], { shell: true })
else if (serverProcess) {
try {
process.kill(-serverProcess.pid, 'SIGKILL')
} catch {}
}
if (clientProcess) {
if (isWin) spawn('taskkill', ['/pid', clientProcess.pid, '/f', '/t'], { shell: true })
else
try {
process.kill(-clientProcess.pid, 'SIGKILL')
} catch {}
}
setTimeout(() => process.exit(0), 1000)
})
req.end()
setTimeout(() => {
console.log(`${colors.system}[System]${colors.reset} Force exiting after timeout.`)
if (isWin && serverProcess)
spawn('taskkill', ['/pid', serverProcess.pid, '/f', '/t'], { shell: true })
else if (serverProcess) {
try {
process.kill(-serverProcess.pid, 'SIGKILL')
} catch {}
}
if (clientProcess) {
if (isWin) spawn('taskkill', ['/pid', clientProcess.pid, '/f', '/t'], { shell: true })
else
try {
process.kill(-clientProcess.pid, 'SIGKILL')
} catch {}
}
setTimeout(() => process.exit(1), 1000)
}, 15000)
}
process.on('SIGINT', () => {
shutdown()
})
;(async () => {
await checkForUpdates()
main()
})()