-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.js
More file actions
424 lines (362 loc) · 18.1 KB
/
run.js
File metadata and controls
424 lines (362 loc) · 18.1 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
// SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath)
//
// run.js — Homoiconic, fault-tolerant, platform-independent run script
// for IDApTIK (asymmetric co-op stealth puzzle-platformer)
//
// Usage:
// deno run --allow-all run.js # auto-detect and launch
// deno run --allow-all run.js --help # show usage
// ─────────────────────────────────────────────────────────────────────────────
// REGISTRY — the script IS the data; reflect() reads this at runtime
// ─────────────────────────────────────────────────────────────────────────────
const REGISTRY = {
identity: {
name: "idaptik",
display: "IDApTIK",
version: "0.2.0",
license: "AGPL-3.0-or-later",
repo: "https://github.com/hyperpolymath/idaptik",
},
ports: {
vite: 1984, // Orwell — surveillance state, appropriate for a spy game
syncServer: 4030,
fallback: [1985, 1986, 1987],
},
tasks: {
gameOnly: ["task", "dev"], // deno task dev (Vite + ReScript watcher)
full: ["task", "dev:all"], // + Elixir sync server
build: ["task", "build"],
test: ["task", "test"],
},
git: {
remote: "origin",
branch: "main",
mirrors: [],
},
capabilities: [
"reflect", // reads own source (homoiconic)
"detectPlatform", // OS, arch, display server
"checkGitSync", // fetch + ahead/behind + dirty
"selfHeal", // check Deno, ReScript, Vite dependencies
"detectVersions", // git tags + dist/ artifacts
"findPort", // probe Vite port, fallback range
"launchGameOnly", // deno task dev (Vite + ReScript, no sync server)
"launchFull", // deno task dev:all (+ Elixir sync server)
"gitCycle", // add, commit, push to origin + mirrors
],
};
// ─────────────────────────────────────────────────────────────────────────────
// REFLECTION
// ─────────────────────────────────────────────────────────────────────────────
async function reflect() {
const path = new URL(import.meta.url).pathname;
const src = await Deno.readTextFile(path);
return { path, lines: src.split("\n").length, capabilities: REGISTRY.capabilities };
}
// ─────────────────────────────────────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────────────────────────────────────
async function run(cmd, args) {
try {
const p = new Deno.Command(cmd, { args, stdout: "piped", stderr: "piped" });
const { code, stdout, stderr } = await p.output();
return {
ok: code === 0,
out: new TextDecoder().decode(stdout).trim(),
err: new TextDecoder().decode(stderr).trim(),
};
} catch (e) {
return { ok: false, out: "", err: e.message };
}
}
const c = { reset:"\x1b[0m", bold:"\x1b[1m", green:"\x1b[32m", yellow:"\x1b[33m", cyan:"\x1b[36m" };
const log = (m) => console.log(`${c.green}▶${c.reset} ${m}`);
const warn = (m) => console.warn(`${c.yellow}⚠${c.reset} ${m}`);
const head = (m) => console.log(`\n${c.bold}${c.cyan}${m}${c.reset}`);
// ─────────────────────────────────────────────────────────────────────────────
// PLATFORM DETECTION
// ─────────────────────────────────────────────────────────────────────────────
async function detectPlatform() {
const os = Deno.build.os;
const arch = Deno.build.arch;
let display = "unknown";
if (os === "linux") {
if (Deno.env.get("WAYLAND_DISPLAY")) display = "wayland";
else if (Deno.env.get("DISPLAY")) display = "x11";
else display = "headless";
} else if (os === "darwin") display = "quartz";
else if (os === "windows") display = "win32";
const has = async (cmd) => {
try {
const p = new Deno.Command("which", { args: [cmd], stdout: "null", stderr: "null" });
return (await p.output()).success;
} catch { return false; }
};
const hasBrowser = await has("xdg-open") || await has("open") || await has("start");
const browserCmd = (await has("xdg-open")) ? "xdg-open"
: (await has("open")) ? "open"
: null;
return {
os, arch, display,
hasDeno: await has("deno"),
hasMix: await has("mix"), // Elixir sync server
hasBrowser, browserCmd,
};
}
// ─────────────────────────────────────────────────────────────────────────────
// GIT SYNC
// ─────────────────────────────────────────────────────────────────────────────
async function checkGitSync() {
const sync = { dirty: false, ahead: 0, behind: 0, branch: "main", fetchError: false };
const branch = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
if (branch.ok) sync.branch = branch.out;
const fetch = await run("git", ["fetch", "--quiet", REGISTRY.git.remote]);
if (!fetch.ok) { sync.fetchError = true; warn("git fetch failed — offline mode"); }
const rl = await run("git", ["rev-list", "--left-right", "--count",
`${REGISTRY.git.remote}/${sync.branch}...HEAD`]);
if (rl.ok) {
const [b, a] = rl.out.split(/\s+/);
sync.behind = parseInt(b, 10) || 0;
sync.ahead = parseInt(a, 10) || 0;
}
const diff = await run("git", ["status", "--porcelain"]);
if (diff.ok && diff.out) sync.dirty = true;
const remotes = await run("git", ["remote", "-v"]);
if (remotes.ok) {
REGISTRY.git.mirrors = [...new Set(
remotes.out.split("\n")
.filter(l => l.includes("(push)") && !l.startsWith(REGISTRY.git.remote + "\t"))
.map(l => l.split("\t")[0])
)];
}
return sync;
}
// ─────────────────────────────────────────────────────────────────────────────
// SELF-HEALING
// ─────────────────────────────────────────────────────────────────────────────
async function selfHeal(platform) {
const healed = [];
if (!platform.hasDeno) {
warn("Deno not found — install via: https://deno.land/#installation");
return healed;
}
// Ensure node_modules exist (Deno compat layer for Vite/ReScript)
try {
await Deno.stat("node_modules");
} catch {
log("node_modules missing — running: deno install --node-modules-dir=auto");
const install = await run("deno", ["install", "--node-modules-dir=auto", "--allow-scripts"]);
if (install.ok) healed.push("Installed node_modules via deno install");
else warn("deno install failed: " + install.err);
}
// Ensure ReScript has been compiled at least once
try {
await Deno.stat("lib/bs");
} catch {
log("ReScript lib/bs missing — running: deno task res:build");
const build = await run("deno", ["task", "res:build"]);
if (build.ok) healed.push("Built ReScript (lib/bs)");
else warn("ReScript build failed — check rescript.json");
}
return healed;
}
// ─────────────────────────────────────────────────────────────────────────────
// VERSION DETECTION
// ─────────────────────────────────────────────────────────────────────────────
async function detectVersions() {
const versions = [];
const tags = await run("git", ["tag", "--sort=-version:refname"]);
if (tags.ok && tags.out) {
tags.out.split("\n").slice(0, 3).forEach(t => {
if (t) versions.push({ type: "release", label: t });
});
}
const sha = await run("git", ["rev-parse", "--short", "HEAD"]);
if (sha.ok) versions.push({ type: "current", label: `HEAD (${sha.out})` });
try {
const dist = await Deno.stat("dist");
versions.push({ type: "dist", label: `dist/ built ${dist.mtime?.toISOString().slice(0,10) ?? "?"}` });
} catch { /* no dist yet */ }
return versions;
}
// ─────────────────────────────────────────────────────────────────────────────
// PORT PROBING
// ─────────────────────────────────────────────────────────────────────────────
async function findFreePort() {
const candidates = [REGISTRY.ports.vite, ...REGISTRY.ports.fallback];
for (const port of candidates) {
try {
const l = Deno.listen({ port });
l.close();
return port;
} catch { /* in use */ }
}
return REGISTRY.ports.vite; // Vite will find a free port itself
}
// ─────────────────────────────────────────────────────────────────────────────
// LAUNCH
// ─────────────────────────────────────────────────────────────────────────────
async function launchGameOnly(platform) {
if (!platform.hasDeno) {
warn("Deno required — install via https://deno.land/#installation");
return false;
}
const port = await findFreePort();
const url = `http://localhost:${port}/`;
log(`Launching IDApTIK game (single-player mode) on port ${port}...`);
log(`Note: Sync server NOT started — single-player only`);
const p = new Deno.Command("deno", {
args: REGISTRY.tasks.gameOnly,
stdin: "null", stdout: "inherit", stderr: "inherit",
env: { ...Deno.env.toObject(), VITE_PORT: String(port) },
});
const child = p.spawn();
// Give Vite a moment to start, then open browser
await new Promise(r => setTimeout(r, 1500));
if (platform.browserCmd) {
log(`Opening ${url}`);
await run(platform.browserCmd, [url]);
} else {
log(`Open in browser: ${url}`);
}
await child.status;
return true;
}
async function launchFull(platform) {
if (!platform.hasDeno) return false;
if (!platform.hasMix) {
warn("Elixir/Mix not found — falling back to game-only mode (no sync server)");
return await launchGameOnly(platform);
}
const port = await findFreePort();
log(`Launching IDApTIK with sync server (port ${REGISTRY.ports.syncServer})...`);
const p = new Deno.Command("deno", {
args: REGISTRY.tasks.full,
stdin: "null", stdout: "inherit", stderr: "inherit",
env: { ...Deno.env.toObject(), VITE_PORT: String(port) },
});
const child = p.spawn();
await new Promise(r => setTimeout(r, 2500));
const url = `http://localhost:${port}/`;
if (platform.browserCmd) {
log(`Opening ${url}`);
await run(platform.browserCmd, [url]);
} else {
log(`Open in browser: ${url}`);
}
await child.status;
return true;
}
// ─────────────────────────────────────────────────────────────────────────────
// GIT CYCLE
// ─────────────────────────────────────────────────────────────────────────────
async function gitCycle(sync) {
head("── Git cycle ──");
const add = await run("git", ["add", "-A"]);
if (!add.ok) { warn("git add failed: " + add.err); return; }
const staged = await run("git", ["diff", "--cached", "--stat"]);
if (staged.out) {
const commit = await run("git", ["commit", "-m",
"chore: run.js launch cycle — platform auto-detected, self-healed"]);
if (commit.ok) log("Committed outstanding changes");
else { warn("Commit failed: " + commit.err); return; }
} else {
log("Nothing to commit — working tree clean");
}
// Push current branch
const pushBranch = await run("git", ["push", REGISTRY.git.remote, sync.branch]);
if (pushBranch.ok) log(`Pushed ${sync.branch} → ${REGISTRY.git.remote}`);
else warn("Push failed: " + pushBranch.err);
// Merge to main if not already there
const mainBranch = "main";
if (sync.branch !== mainBranch) {
log(`Merging ${sync.branch} → ${mainBranch}...`);
const checkout = await run("git", ["checkout", mainBranch]);
if (!checkout.ok) { warn("Could not switch to main: " + checkout.err); return; }
const merge = await run("git", ["merge", "--ff-only", sync.branch]);
if (merge.ok) {
log(`Fast-forward merged ${sync.branch} → ${mainBranch}`);
} else {
const mergeRegular = await run("git", ["merge", sync.branch,
"-m", `chore: merge ${sync.branch} → main`]);
if (!mergeRegular.ok) { warn("Merge failed: " + mergeRegular.err); return; }
log(`Merged ${sync.branch} → ${mainBranch}`);
}
const pushMain = await run("git", ["push", REGISTRY.git.remote, mainBranch]);
if (pushMain.ok) log(`Pushed ${mainBranch} → ${REGISTRY.git.remote}`);
else warn("Main push failed: " + pushMain.err);
} else {
log("Already on main — no merge needed");
}
// Push to mirrors
for (const mirror of REGISTRY.git.mirrors) {
const mp = await run("git", ["push", mirror, mainBranch]);
if (mp.ok) log(`Pushed to mirror: ${mirror}`);
else warn(`Mirror push failed (${mirror}): ${mp.err}`);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// MAIN
// ─────────────────────────────────────────────────────────────────────────────
if (import.meta.main) {
const args = Deno.args;
if (args.includes("--help") || args.includes("-h")) {
console.log(`
${c.bold}${REGISTRY.identity.display} — run.js${c.reset}
${REGISTRY.identity.license} | ${REGISTRY.identity.repo}
Usage: deno run --allow-all run.js [OPTIONS]
Options:
--help, -h Show this help
--full Start with Elixir sync server (multiplayer)
--no-git Skip git sync check and post-launch git cycle
--no-launch Git cycle only (no game launch)
--reflect Print self-reflection data and exit
Default: game-only mode (Vite + ReScript, no sync server — single-player).
Use --full to enable the sync server for multiplayer/co-op mode.
`);
Deno.exit(0);
}
if (args.includes("--reflect")) {
const r = await reflect();
console.log(JSON.stringify({ registry: REGISTRY, reflection: r }, null, 2));
Deno.exit(0);
}
const skipGit = args.includes("--no-git");
const doLaunch = !args.includes("--no-launch");
const fullMode = args.includes("--full");
head(`${REGISTRY.identity.display} v${REGISTRY.identity.version}`);
const r = await reflect();
log(`Reflected: ${r.lines} lines, ${r.capabilities.length} capabilities`);
head("Platform");
const platform = await detectPlatform();
log(`OS: ${platform.os}/${platform.arch} / display: ${platform.display}`);
log(`Deno: ${platform.hasDeno ? "available" : "NOT FOUND"}`);
log(`Elixir/Mix: ${platform.hasMix ? "available" : "not found (single-player only)"}`);
log(`Browser: ${platform.browserCmd ?? "none"}`);
let sync = { dirty: false, ahead: 0, behind: 0, branch: "main", fetchError: false };
if (!skipGit) {
head("Git sync");
sync = await checkGitSync();
log(`Branch: ${sync.branch} | ahead: ${sync.ahead} | behind: ${sync.behind}`);
if (sync.dirty) warn("Working tree has uncommitted changes");
if (sync.behind > 0) warn(`${sync.behind} commit(s) behind remote`);
if (REGISTRY.git.mirrors.length > 0) log(`Mirrors: ${REGISTRY.git.mirrors.join(", ")}`);
}
head("Self-heal");
const healed = await selfHeal(platform);
if (healed.length > 0) healed.forEach(h => log(`Healed: ${h}`));
else log("No healing required");
head("Versions");
const versions = await detectVersions();
versions.forEach(v => log(`${v.type}: ${v.label}`));
if (doLaunch) {
head(`Launch (${fullMode ? "full — with sync server" : "game-only — single-player"})`);
const launched = fullMode
? await launchFull(platform)
: await launchGameOnly(platform);
if (!launched) warn("Could not launch — check Deno installation");
}
if (!skipGit) await gitCycle(sync);
head("Done");
}