forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.js
More file actions
581 lines (498 loc) · 15.7 KB
/
Copy pathdev.js
File metadata and controls
581 lines (498 loc) · 15.7 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#!/usr/bin/env node
/**
* Acode Dev Orchestrator
*
* Starts:
* 1. HTTP static file server (serves www/) + WebSocket reload relay (same port)
* 2. rspack --watch with DEV_MODE enabled
* 3. cordova run android (after first successful compilation)
* 4. File watcher on src/plugins/ for auto plugin reinstall
*
* The app loads boot.js from the APK assets; boot.js detects DEV_MODE and
* fetches the latest main.js / main.css from the dev server over HTTP.
* A WebSocket connection from the app receives "reload" messages on recompile.
*/
const { spawn, execSync } = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");
const https = require("node:https");
const net = require("node:net");
const { WebSocketServer } = require("ws");
const os = require("node:os");
// ─── helpers ────────────────────────────────────────────────────────────────
const ROOT = path.resolve(__dirname, "../..");
const WWW = path.join(ROOT, "www");
const PLUGINS = path.join(ROOT, "src", "plugins");
const PLATFORM_WWW = path.join(ROOT, "platforms", "android", "platform_www");
const CORDOVA_BIN = path.join(
ROOT,
"node_modules",
"cordova",
"bin",
"cordova",
);
const MIME = {
".html": "text/html",
".js": "application/javascript",
".mjs": "application/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".map": "application/json",
};
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const iface of Object.values(interfaces)) {
if (!iface) continue;
for (const addr of iface) {
if (addr.family === "IPv4" && !addr.internal) {
// Prefer 192.168.x.x or 10.x.x.x over other private ranges
if (
addr.address.startsWith("192.168.") ||
addr.address.startsWith("10.")
) {
return addr.address;
}
}
}
}
// Fallback: any non-internal IPv4
for (const iface of Object.values(interfaces)) {
if (!iface) continue;
for (const addr of iface) {
if (addr.family === "IPv4" && !addr.internal) {
return addr.address;
}
}
}
return "127.0.0.1";
}
function getFreePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.listen(0, () => {
const port = server.address().port;
server.close(() => resolve(port));
});
server.on("error", reject);
});
}
function log(label, msg) {
const reset = "\x1b[0m";
const green = "\x1b[92m";
const yellow = "\x1b[93m";
const blue = "\x1b[94m";
const colors = { info: blue, ok: green, warn: yellow };
const c = colors[label] || reset;
console.log(` ${c}[${label}]${reset} ${msg}`);
}
function resolveSpawnCommand(command) {
if (process.platform !== "win32") return command;
const lower = command.toLowerCase();
if (lower.endsWith(".cmd") || lower.endsWith(".exe")) return command;
if (lower === "cordova" || lower === "npx" || lower === "npm") {
return `${command}.cmd`;
}
return command;
}
function buildSpawnEnv(extra = {}) {
const merged = { ...process.env, ...extra };
const sanitized = {};
for (const [key, value] of Object.entries(merged)) {
if (!key || key.startsWith("=") || value === undefined) continue;
sanitized[key] = String(value);
}
return sanitized;
}
function getAppVariant(args) {
return args.some((arg) => arg.toLowerCase() === "free") ? "free" : "paid";
}
function spawnAsync(command, args, options) {
return new Promise((resolve, reject) => {
const mergedOptions = {
stdio: "inherit",
...options,
env: options?.env ? buildSpawnEnv(options.env) : options?.env,
};
const useLocalCordova = command === "cordova" && fs.existsSync(CORDOVA_BIN);
const proc = useLocalCordova
? spawn(process.execPath, [CORDOVA_BIN, ...args], mergedOptions)
: spawn(resolveSpawnCommand(command), args, mergedOptions);
proc.on("close", (code) => {
if (code === 0) resolve();
else reject(new Error(`${command} exited with code ${code}`));
});
proc.on("error", reject);
});
}
// ─── self-signed certificate ─────────────────────────────────────────────────
let _cachedCert = null;
function getDevCert() {
if (_cachedCert) return _cachedCert;
const certPath = path.join(ROOT, ".dev-cert.pem");
const keyPath = path.join(ROOT, ".dev-key.pem");
// Reuse existing cert if available
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
_cachedCert = {
cert: fs.readFileSync(certPath),
key: fs.readFileSync(keyPath),
};
return _cachedCert;
}
// Generate via openssl (available on macOS, Linux, and Git Bash on Windows)
try {
execSync(
`openssl req -x509 -newkey rsa:2048 -keyout "${keyPath}" -out "${certPath}" -days 365 -nodes -subj "/CN=acode-dev"`,
{ stdio: "pipe" },
);
_cachedCert = {
cert: fs.readFileSync(certPath),
key: fs.readFileSync(keyPath),
};
log("ok", "Generated self-signed dev certificate");
return _cachedCert;
} catch (_e) {
// openssl not available
}
log("warn", "openssl not found — falling back to HTTP");
return null;
}
// ─── HTTPS + WebSocket server ─────────────────────────────────────────────────
async function createServer(port) {
const tls = getDevCert();
let server;
if (tls) {
server = https.createServer(tls, handleRequest);
} else {
log("warn", "No TLS certificate — falling back to HTTP");
log("warn", "Install openssl to enable HTTPS for your dev server");
const http = require("node:http");
server = http.createServer(handleRequest);
}
const wss = new WebSocketServer({ server });
wss.on("connection", (ws) => {
log("info", "App connected via WebSocket");
ws.on("error", () => {});
});
return {
server,
wss,
broadcast: (msg) => broadcast(wss, msg),
isHttps: !!tls,
protocol: tls ? "https" : "http",
};
}
function handleRequest(req, res) {
let urlPath = req.url.split("?")[0];
if (urlPath === "/") urlPath = "/index.html";
const relative = path.normalize(urlPath).replace(/^\/+/, "");
const filePath = path.join(WWW, relative);
if (!filePath.startsWith(WWW + path.sep) && filePath !== WWW) {
res.writeHead(403);
res.end("Forbidden");
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME[ext] || "application/octet-stream";
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end("Not found");
return;
}
res.writeHead(200, {
"Content-Type": contentType,
"Access-Control-Allow-Origin": "*",
"Cache-Control": "no-cache, no-store, must-revalidate",
});
res.end(data);
});
}
function broadcast(wss, message) {
if (typeof message !== "string") {
message = JSON.stringify(message);
}
for (const client of wss.clients) {
if (client.readyState === 1) {
client.send(message);
}
}
}
// ─── cordova helpers ─────────────────────────────────────────────────────────
function ensureCordovaFiles() {
// Copy cordova.js and any other platform_www files into www/
// so the dev server can serve them when the app redirects to it.
if (!fs.existsSync(PLATFORM_WWW)) {
log("warn", "platform_www not found — skipping cordova file copy");
return;
}
const files = fs.readdirSync(PLATFORM_WWW);
for (const file of files) {
const src = path.join(PLATFORM_WWW, file);
const dest = path.join(WWW, file);
if (fs.statSync(src).isFile()) {
// Don't overwrite index.html
if (file === "index.html") continue;
fs.copyFileSync(src, dest);
}
}
log("ok", "Copied cordova platform files to www/");
}
async function launchApp(target, platform, emulator) {
if (target) {
log("info", `Launching app on ${target}...`);
} else {
log("info", "Launching app...");
}
return new Promise((resolve, reject) => {
const args = ["run", platform];
if (emulator) args.push("--emulator");
if (target) args.push("--target", target);
const useLocalCordova = fs.existsSync(CORDOVA_BIN);
const proc = useLocalCordova
? spawn(process.execPath, [CORDOVA_BIN, ...args], {
cwd: ROOT,
stdio: "inherit",
})
: spawn(resolveSpawnCommand("cordova"), args, {
cwd: ROOT,
stdio: "inherit",
});
proc.on("close", (code) => {
if (code === 0) resolve();
else
reject(new Error(`cordova run ${platform} exited with code ${code}`));
});
proc.on("error", reject);
});
}
// ─── rspack watcher ──────────────────────────────────────────────────────────
function startRspackWatch(host, port, proto, onCompiled) {
log("info", "Starting rspack --watch...");
const env = buildSpawnEnv({
DEV_MODE: "true",
DEV_HOST: host,
DEV_PORT: String(port),
DEV_PROTO: proto,
});
const rspackBin = path.join(
ROOT,
"node_modules",
"@rspack",
"cli",
"bin",
"rspack.js",
);
const useLocalRspack = fs.existsSync(rspackBin);
if (!useLocalRspack) {
log("warn", "Local rspack CLI not found, falling back to npx rspack");
}
const proc = useLocalRspack
? spawn(process.execPath, [rspackBin, "--watch", "--mode", "development"], {
cwd: ROOT,
env,
stdio: "pipe",
})
: spawn(
resolveSpawnCommand("npx"),
["rspack", "--watch", "--mode", "development"],
{
cwd: ROOT,
env,
stdio: "pipe",
},
);
let firstCompile = true;
proc.stdout.on("data", (chunk) => {
const text = chunk.toString();
process.stdout.write(text);
if (text.includes("compiled successfully") || text.includes("compiled")) {
if (firstCompile) {
firstCompile = false;
}
onCompiled();
}
});
proc.stderr.on("data", (chunk) => {
process.stderr.write(chunk);
});
proc.on("error", (err) => {
log("warn", `rspack error: ${err.message}`);
log("warn", "rspack watcher failed to start; exiting dev mode");
process.exit(1);
});
proc.on("close", (code) => {
if (code !== 0 && code !== null) {
log("warn", `rspack exited with code ${code}`);
}
});
return proc;
}
// ─── plugin watcher ──────────────────────────────────────────────────────────
let pluginUpdateTimer = null;
const pluginUpdates = new Set();
let pluginPlatform = "android";
function startPluginWatcher(platform) {
pluginPlatform = platform;
let chokidar;
try {
chokidar = require("chokidar");
} catch (_e) {
log("warn", "chokidar not installed — plugin auto-update disabled");
return;
}
if (!fs.existsSync(PLUGINS)) {
log("warn", "src/plugins/ not found — plugin watcher skipped");
return;
}
const watcher = chokidar.watch(path.join(PLUGINS, "**", "*"), {
ignored: /(^|[\/\\])\../, // dotfiles
persistent: true,
ignoreInitial: true,
awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 },
});
watcher.on("change", (filePath) => schedulePluginUpdate(filePath));
watcher.on("add", (filePath) => schedulePluginUpdate(filePath));
watcher.on("unlink", (filePath) => schedulePluginUpdate(filePath));
log("info", "Watching src/plugins/ for changes...");
}
function schedulePluginUpdate(filePath) {
// Extract top-level plugin dir name from path
const relative = path.relative(PLUGINS, filePath);
const pluginDir = relative.split(path.sep)[0];
if (!pluginDir || pluginDir === "tsconfig.tsbuildinfo") return;
pluginUpdates.add(pluginDir);
if (pluginUpdateTimer) clearTimeout(pluginUpdateTimer);
pluginUpdateTimer = setTimeout(applyPluginUpdates, 2000);
}
async function applyPluginUpdates() {
if (pluginUpdates.size === 0) return;
for (const dir of pluginUpdates) {
const pluginPath = path.join(PLUGINS, dir);
const pluginXml = path.join(pluginPath, "plugin.xml");
if (!fs.existsSync(pluginXml)) {
log("warn", `No plugin.xml in ${dir} — skipping`);
continue;
}
const xml = fs.readFileSync(pluginXml, "utf8");
const idMatch = /<plugin[^>]*?\sid=["']([^"']+)["']/.exec(xml);
const pluginId = idMatch?.[1];
if (!pluginId) {
log("warn", `Could not find plugin id in ${dir}/plugin.xml`);
continue;
}
log("info", `Updating plugin: ${pluginId}`);
try {
await spawnAsync("cordova", ["plugin", "remove", pluginId], {
cwd: ROOT,
});
} catch (_e) {
// Plugin might not be installed yet — that's OK
}
try {
await spawnAsync("cordova", ["plugin", "add", `./src/plugins/${dir}`], {
cwd: ROOT,
});
log("ok", `Plugin ${pluginId} reinstalled`);
} catch (err) {
log("warn", `Failed to reinstall plugin ${pluginId}: ${err.message}`);
continue;
}
}
pluginUpdates.clear();
// Restart the app after plugin changes (native changes need full restart)
try {
const configXml = fs.readFileSync(path.join(ROOT, "config.xml"), "utf8");
const pkgMatch = /id="([^"]+)"/.exec(configXml);
const pkg = pkgMatch?.[1];
if (pkg) {
log("info", "Restarting app after plugin update...");
// Need to rebuild APK since native plugin code changed
await spawnAsync("cordova", ["build", pluginPlatform], {
cwd: ROOT,
});
if (pluginPlatform === "android") {
await spawnAsync("adb", ["uninstall", pkg], { stdio: "ignore" });
}
await spawnAsync("cordova", ["run", pluginPlatform], {
cwd: ROOT,
});
}
} catch (err) {
log("warn", `Could not rebuild after plugin update: ${err.message}`);
}
}
// ─── main ────────────────────────────────────────────────────────────────────
async function main() {
const args = process.argv.slice(2);
const platform =
args.find((a) => /^(android|ios|browser)$/i.test(a)) || "android";
const appVariant = getAppVariant(args);
const target =
args.find((a) => a.startsWith("--target="))?.split("=")[1] || null;
const emulator = args.includes("--emulator") || args.includes("-e");
console.log("\n ⚡ Acode Dev Mode\n");
if (appVariant) {
log("info", `Configuring ${appVariant} app variant...`);
await spawnAsync(
process.execPath,
[path.join(ROOT, "utils", "config.js"), "d", appVariant],
{ cwd: ROOT },
);
}
const host = getLocalIP();
const port = await getFreePort();
log("info", `Local IP: ${host}`);
log("info", `Port: ${port}`);
// 1. Ensure cordova files are in www/ for the dev server
ensureCordovaFiles();
// 2. Start HTTPS (or HTTP fallback) + WebSocket server
const { server, broadcast, protocol } = await createServer(port);
const origin = `${protocol}://${host}:${port}`;
log("info", `Dev Origin: ${origin}`);
server.listen(port, () => {
log("ok", "Dev server started");
});
// 3. Start rspack --watch
let appLaunched = false;
startRspackWatch(host, port, protocol, () => {
broadcast("reload");
if (!appLaunched) {
appLaunched = true;
setTimeout(async () => {
try {
await launchApp(target, platform, emulator);
} catch (err) {
log("warn", `Launch failed: ${err.message}`);
}
}, 3000); // give APK install time
}
});
// 4. Start plugin file watcher
startPluginWatcher(platform);
// Graceful shutdown
process.on("SIGINT", () => {
log("info", "Shutting down...");
server.close();
process.exit(0);
});
process.on("SIGTERM", () => {
server.close();
process.exit(0);
});
}
if (require.main === module) {
main().catch((err) => {
console.error(err);
process.exit(1);
});
}
module.exports = { getAppVariant };