earthgames 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Avatar Genie LLC (DBA Earth Games)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,163 @@
1
- # Temporary Holding Version
1
+ # Earth Games kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Make your own multiplayer game on [Earth Games](https://playearth.games): a 1:1 3D world built from real maps that runs in the browser. You write the rules in JavaScript. The world, the vehicles, the characters, combat, the HUD and the leaderboards are already there.
4
+
5
+ This package has the command-line tool, the types for your editor, the docs and example games.
6
+
7
+ | Read | For |
8
+ |---|---|
9
+ | This page | The five-minute start |
10
+ | [docs/guide.md](docs/guide.md) | How to do the common things, with working code: playing anywhere, zones and pickups, characters, combat, HUD and menus, rounds and teams, saves, races, testing, publishing, what makers earn |
11
+ | [docs/api.md](docs/api.md) | Every call and event, with its signature |
12
+ | [docs/reference.md](docs/reference.md) | `game.json` field by field, the ids of weapons, characters, sounds and marker styles, and every limit with its number |
13
+
14
+ No code? The **Make a game** app on the in-game phone makes the same kind of game by picking, placing and adding rule cards.
15
+
16
+ ## Start
17
+
18
+ You need [Node.js](https://nodejs.org) 20 or newer and a free Earth Games account.
19
+
20
+ 1. On the site, open your account, go to the **Developer** tab, accept the maker rules and make a developer token.
21
+ 2. Make a game and sign the kit in:
22
+
23
+ ```sh
24
+ npx earthgames new my-game
25
+ cd my-game
26
+ npx earthgames login --token egdev_…
27
+ ```
28
+
29
+ 3. Run it on the live world:
30
+
31
+ ```sh
32
+ npx earthgames dev
33
+ ```
34
+
35
+ This checks the game, uploads it as a private draft and prints a link. Open the link and enter the world: you are in your game. Edit `server.js` and save, and the running game restarts with the new code in about a second. Whatever your script prints with `console.log` shows in the terminal and in the game (the `` ` `` key).
36
+
37
+ Friends can join your draft with its invite code.
38
+
39
+ ## A game is two files
40
+
41
+ `game.json` says what the game is:
42
+
43
+ ```json
44
+ {
45
+ "id": "my-game",
46
+ "title": "My Game",
47
+ "summary": "Say in a sentence or two what players do.",
48
+ "version": "0.1.0",
49
+ "api": 1,
50
+ "instance": { "kind": "match", "maxPlayers": 8 },
51
+ "area": { "anywhere": true },
52
+ "content": { "violence": "none" }
53
+ }
54
+ ```
55
+
56
+ `server.js` holds the rules. It runs on Earth Games' servers, one copy per running game, reacts to events and calls `eg`:
57
+
58
+ ```js
59
+ export default {
60
+ onPlayerJoin(player) {
61
+ eg.ui.toast(player, 'Find the flag.');
62
+ const at = eg.world.offset(player, 0, -60); // 60 m north of them
63
+ eg.entities.add({ id: 'flag-' + player.id, kind: 'zone', at, radius: 6, label: 'Flag', visibleTo: player, trigger: {} });
64
+ eg.ui.waypoint(player, at);
65
+ },
66
+ onZone(player, entityId, what) {
67
+ if (what === 'enter') eg.ui.toast(player, 'Got it.', 'good');
68
+ },
69
+ };
70
+ ```
71
+
72
+ Nothing in that game is a fixed coordinate, so it plays in any town on Earth. Keep it that way where you can: place things relative to players (`eg.world.offset`), at real places near them (`eg.world.placesNear`), or by rule (`eg.spawners.add({ where: { minFromPlayersM: 50 } })`).
73
+
74
+ ## Keeping things
75
+
76
+ - A little data per player, in any game: `eg.saves.setPlayer(player, 'best', 41.5)` and `await eg.saves.getPlayer(player, 'best')`. It follows the player into every match of your game.
77
+ - A world that keeps going: set `"instance": { "kind": "persistent" }`. Save with `eg.saves.set('day', 3)`, and read everything back when the world opens again:
78
+
79
+ ```js
80
+ let day = 1;
81
+ export default {
82
+ onLoad(saved, info) { day = saved.day || 1; }, // before onStart; info.fresh is true for a new world
83
+ onStart() { eg.timers.every(60, () => eg.saves.set('day', ++day)); },
84
+ };
85
+ ```
86
+
87
+ Each saved world has an invite code that never changes, so friends can come back to it later.
88
+ - A new round in the same game: `eg.instance.restart()`. Saves are kept; everything else starts over.
89
+
90
+ ## Teams and races
91
+
92
+ - Teams: `eg.teams.define([{ id: 'red' }, { id: 'blue' }])`, then `eg.teams.auto()` puts everyone on the smaller side. `eg.teams.addScore('red', 1)` keeps score, and a HUD piece shows it: `eg.ui.hud(null, [{ type: 'teams' }])`. Teammates cannot hurt each other.
93
+ - A race: the platform times it and draws the gates, the start lights and the clock. You say where, and what a finish is worth.
94
+
95
+ ```js
96
+ export default {
97
+ async onPlayerJoin(player) {
98
+ const [track] = await eg.race.tracksNear(player); // real streets near them
99
+ if (track) await eg.race.offer(player, track.id); // a ring on the start line; stop in it for the lights
100
+ },
101
+ onRace(player, race) {
102
+ if (race.ev === 'finish') eg.ui.toast(null, player.name + ' finished in ' + (race.ms / 1000).toFixed(2) + ' s');
103
+ },
104
+ };
105
+ ```
106
+
107
+ For a course of your own, give `eg.race.course` a list of points and offer the id it returns. Players who line up together start together.
108
+
109
+ ## Commands
110
+
111
+ | Command | What it does |
112
+ |---|---|
113
+ | `earthgames new <folder> [--template blank\|pursuit\|horde]` | Start a game from a template |
114
+ | `earthgames check [folder]` | Check `game.json` and `server.js`, and say what is wrong in plain words |
115
+ | `earthgames login --token <token>` | Save your developer token on this computer |
116
+ | `earthgames dev [folder]` | Push the game as a draft, then push again on every save and show its console |
117
+ | `earthgames pack [folder]` | Write one file holding the whole package |
118
+ | `earthgames submit [folder]` | Send this version to the Earth Games team for review |
119
+ | `earthgames status` | Where each of your games stands: waiting, live, or not approved and why |
120
+
121
+ Your token is saved in `~/.earthgames.json`. You can set `EARTHGAMES_TOKEN` in the environment instead.
122
+
123
+ ## What is in the box
124
+
125
+ - `docs/guide.md`: how-to guides with working code.
126
+ - `docs/api.md`: every call, event and HUD piece, with its signature and what it does.
127
+ - `docs/reference.md`: `game.json`, the library ids and the limits.
128
+ - `types/earthgames.d.ts`: the same as types. `earthgames new` copies it next to your game, so your editor completes `eg.` and checks your handlers.
129
+ - `examples/pursuit`: a pack that chases the players. Characters and spawners.
130
+ - `examples/horde`: waves of attackers. Combat, weapons, an item of the game's own, effects.
131
+ - `examples/responder`: First Responder. Calls made from real hospitals and streets, a signal to follow, a moving target, the siren.
132
+ - `examples/racing`: Racing. Race tools, best-time boards per track and class, medals, points.
133
+ - `examples/deliveries`: Delivery Jobs, an official game layered on the shared world. A longer read: menus, HUD cards, scoring, leaderboards.
134
+ - `templates/blank`: the flag game above.
135
+
136
+ ## What a script can and cannot do
137
+
138
+ The aim is as much freedom as can safely be given. Limits are budgets, not bans.
139
+
140
+ - It can change anything inside its own running game, and nothing outside it.
141
+ - It never learns who a player is: only a display name and an id that is the same each time that person plays your game.
142
+ - It has no network access and cannot put HTML on a player's page.
143
+ - It uses the characters, vehicles and sounds in the Earth Games library.
144
+ - It has a time budget per turn and limits on entities, characters and messages. The game's console shows what it is using, and every number is in [docs/reference.md](docs/reference.md#limits).
145
+
146
+ Blood is only shown when your manifest says the game has it (`"content": { "blood": true }`), and only to signed-in players who turned it on in their own settings.
147
+
148
+ ## Publishing
149
+
150
+ When the game is ready, `earthgames submit` sends this version to the Earth Games team. Every game is reviewed before it goes live; `earthgames status` (or the Developer tab of your account) shows where it stands and, if it was not approved, why.
151
+
152
+ - A live game gets its own page at `/games/<id>` and is listed on the Games page. You get a maker page listing your live games.
153
+ - To update, raise `"version"` in `game.json` and submit again. Players keep getting the approved version until the new one is approved.
154
+ - Your game's `"id"` is yours once you have submitted it.
155
+ - The team can switch a game off if it breaks the maker rules. You are told why.
156
+
157
+ ## What makers earn
158
+
159
+ Turning on maker mode gives you the Developer role on the Earth Games Discord. Games that players keep coming back to earn their makers free Earth Pass time and higher developer roles, worked out each month. Makers can also ask for a town to be built for their game, a few times a month. Rewards are a thank-you, not payment: there is no revenue share. The numbers are in [docs/guide.md](docs/guide.md#rewards) and in the Developer tab of your account.
160
+
161
+ ## License
162
+
163
+ The kit, the types and the examples are MIT licensed. The Earth Games engine and service are not part of this package.
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ // The Earth Games kit: make a game, check it, and run it on the live world while you write it.
3
+ //
4
+ // earthgames new <folder> [--template blank|pursuit|horde] start a game from a template
5
+ // earthgames check [folder] check game.json and server.js
6
+ // earthgames login [--token <token>] [--server <url>] save your developer token
7
+ // earthgames dev [folder] push the game as a draft, watch the folder,
8
+ // push again on every save, show its console
9
+ // earthgames pack [folder] write one file holding the whole package
10
+ // earthgames submit [folder] send this version to the Earth Games team for review
11
+ // earthgames status where each of your games stands (waiting, live, rejected and why)
12
+ //
13
+ // A game is a folder: game.json (the manifest) and server.js (the rules script). The script runs
14
+ // on Earth Games' servers, never on your computer: `dev` uploads it as a private draft that only
15
+ // you can start, at a link this prints. Your token is in your account on the site (Developer tab).
16
+ // No dependencies; Node 20 or newer.
17
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync, watch, copyFileSync } from 'node:fs';
18
+ import { join, resolve, basename, dirname } from 'node:path';
19
+ import { homedir } from 'node:os';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { checkPackage, GAME_ID_RE } from '../lib/manifest.js';
22
+
23
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
24
+ const DEFAULT_SERVER = 'https://playearth.games';
25
+ const CONFIG = process.env.EARTHGAMES_CONFIG || join(homedir(), '.earthgames.json');
26
+ export const LIMITS = { scriptBytes: 256 * 1024 };
27
+ const color = (c, s) => (process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${c}m${s}\x1b[0m` : s);
28
+ const red = s => color(31, s), green = s => color(32, s), yellow = s => color(33, s), dim = s => color(2, s), bold = s => color(1, s);
29
+
30
+ /** argv after the command → { _: [positional], flag: value | true }. */
31
+ export function parseArgs(argv) {
32
+ const out = { _: [] };
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const a = argv[i];
35
+ if (!a.startsWith('--')) { out._.push(a); continue; }
36
+ const eq = a.indexOf('='), key = a.slice(2, eq < 0 ? undefined : eq);
37
+ out[key] = eq >= 0 ? a.slice(eq + 1) : argv[i + 1] != null && !argv[i + 1].startsWith('--') ? argv[++i] : true;
38
+ }
39
+ return out;
40
+ }
41
+ /** Read a game folder. → { ok, errors, warnings, manifest (as written), pkg: { manifest (checked), server } | null } */
42
+ export function readGame(dir) {
43
+ const file = join(dir, 'game.json');
44
+ if (!existsSync(file)) return { ok: false, errors: [`There is no game.json in ${dir}. Run "earthgames new <folder>" to start a game.`], warnings: [], manifest: null, pkg: null };
45
+ let manifest;
46
+ try { manifest = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { return { ok: false, errors: [`game.json is not valid JSON: ${e.message}`], warnings: [], manifest: null, pkg: null }; }
47
+ const sfile = join(dir, 'server.js'), server = existsSync(sfile) ? readFileSync(sfile, 'utf8') : null;
48
+ const r = checkPackage({ manifest, server }, {});
49
+ const errors = [...r.errors], warnings = [...r.warnings];
50
+ if (server == null) warnings.push('There is no server.js: the game has no rules yet.');
51
+ else if (Buffer.byteLength(server) > LIMITS.scriptBytes) errors.push(`server.js is larger than ${LIMITS.scriptBytes / 1024} KB.`);
52
+ return { ok: !errors.length, errors, warnings, manifest, pkg: errors.length ? null : { manifest: r.manifest, server } };
53
+ }
54
+ export function readConfig() { try { return JSON.parse(readFileSync(CONFIG, 'utf8')); } catch { return {}; } }
55
+ const settings = flags => { const c = readConfig(); return { server: String(flags.server || process.env.EARTHGAMES_SERVER || c.server || DEFAULT_SERVER).replace(/\/+$/, ''), token: String(flags.token || process.env.EARTHGAMES_TOKEN || c.token || '') }; };
56
+
57
+ function report(r, log) {
58
+ for (const e of r.errors) log(`${red('error')} ${e}`);
59
+ for (const w of r.warnings) log(`${yellow('note')} ${w}`);
60
+ }
61
+ /** The templates that ship with the kit: { name: folder }. */
62
+ export function templates() {
63
+ const out = {};
64
+ for (const base of [join(ROOT, 'templates'), join(ROOT, 'examples')]) if (existsSync(base)) for (const d of readdirSync(base, { withFileTypes: true })) if (d.isDirectory() && existsSync(join(base, d.name, 'game.json')) && !(d.name in out)) out[d.name] = join(base, d.name);
65
+ return out;
66
+ }
67
+ const titleOf = id => id.split('-').filter(Boolean).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
68
+
69
+ export const commands = {
70
+ async new(flags, log) {
71
+ const target = flags._[0]; if (!target) { log('Which folder? For example: earthgames new my-game'); return 1; }
72
+ const dir = resolve(target), id = basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
73
+ if (!GAME_ID_RE.test(id)) { log(red(`"${basename(dir)}" cannot be a game id. Use 3 to 40 lowercase letters, digits or dashes.`)); return 1; }
74
+ if (existsSync(dir) && readdirSync(dir).length) { log(red(`${dir} already has files in it.`)); return 1; }
75
+ const all = templates(), name = String(flags.template || 'blank'), from = all[name];
76
+ if (!from) { log(red(`There is no template "${name}". Templates: ${Object.keys(all).filter(k => k !== 'deliveries').join(', ')}.`)); return 1; }
77
+ mkdirSync(dir, { recursive: true });
78
+ const manifest = JSON.parse(readFileSync(join(from, 'game.json'), 'utf8'));
79
+ Object.assign(manifest, { id, title: titleOf(id), version: '0.1.0' });
80
+ if (name !== 'blank') manifest.summary = `My own game, started from the ${name} example.`;
81
+ writeFileSync(join(dir, 'game.json'), JSON.stringify(manifest, null, 2) + '\n');
82
+ if (existsSync(join(from, 'server.js'))) copyFileSync(join(from, 'server.js'), join(dir, 'server.js'));
83
+ // Editor help: types for `eg` and the handlers, without installing anything.
84
+ writeFileSync(join(dir, 'jsconfig.json'), JSON.stringify({ compilerOptions: { checkJs: true, target: 'es2022', module: 'es2022', types: [] }, include: ['server.js', 'earthgames.d.ts'] }, null, 2) + '\n');
85
+ if (existsSync(join(ROOT, 'types', 'earthgames.d.ts'))) copyFileSync(join(ROOT, 'types', 'earthgames.d.ts'), join(dir, 'earthgames.d.ts'));
86
+ log(`${green('Created')} ${dir}`);
87
+ log(` game.json what the game is (title, players, content)\n server.js its rules\n\nNext:\n cd ${target}\n earthgames dev ${dim('# runs it on the live world, reloading as you save')}`);
88
+ return 0;
89
+ },
90
+ async check(flags, log) {
91
+ const dir = resolve(flags._[0] || '.'), r = readGame(dir);
92
+ report(r, log);
93
+ if (r.ok) log(`${green('OK')} ${r.pkg.manifest.title} (${r.pkg.manifest.id}) ${r.pkg.manifest.version}: ${r.pkg.manifest.instance.kind}, up to ${r.pkg.manifest.instance.maxPlayers} players${r.pkg.manifest.content.blood ? ', has blood' : ''}`);
94
+ return r.ok ? 0 : 1;
95
+ },
96
+ async login(flags, log) {
97
+ const token = String(flags.token || process.env.EARTHGAMES_TOKEN || '').trim();
98
+ if (!/^egdev_[A-Za-z0-9_-]{20,}$/.test(token)) { log('Pass your developer token: earthgames login --token egdev_…\nIt is on the Developer tab of your account on the site. Keep it to yourself: anyone who has it can push games as you.'); return 1; }
99
+ const c = { ...readConfig(), token, ...(flags.server ? { server: String(flags.server).replace(/\/+$/, '') } : {}) };
100
+ const { server } = settings({ ...flags, token });
101
+ const res = await call(server, token, 'GET', '/api/play/dev/me');
102
+ if (!res.ok) { log(red(res.error || 'The server did not accept that token.')); return 1; }
103
+ writeFileSync(CONFIG, JSON.stringify(c, null, 2) + '\n', { mode: 0o600 });
104
+ log(`${green('Signed in')} as ${res.data.name}. Token saved in ${CONFIG}.`);
105
+ return 0;
106
+ },
107
+ async dev(flags, log, { once = !!flags.once, signal = null } = {}) {
108
+ const dir = resolve(flags._[0] || '.'), { server, token } = settings(flags);
109
+ if (!token) { log('Sign in first: earthgames login --token egdev_… (your token is on the Developer tab of your account)'); return 1; }
110
+ let seq = 0, last = '', id = null, timer = null, busy = false, again = false;
111
+ async function push(why) {
112
+ if (busy) { again = true; return; }
113
+ busy = true;
114
+ try {
115
+ const r = readGame(dir);
116
+ if (!r.ok) { report(r, log); log(dim('Not pushed. Fix the above and save again.')); return false; }
117
+ const body = JSON.stringify({ manifest: r.manifest, server: r.pkg.server });
118
+ if (body === last && why !== 'start') return true;
119
+ const res = await call(server, token, 'POST', '/api/play/dev/push', body);
120
+ if (!res.ok) { log(red(res.error || 'The push failed.')); for (const e of res.data?.errors || []) log(`${red('error')} ${e}`); return false; }
121
+ last = body; id = res.data.id;
122
+ for (const w of res.data.warnings || []) log(`${yellow('note')} ${w}`);
123
+ log(`${green(why === 'start' ? 'Pushed' : 'Reloaded')} ${bold(r.pkg.manifest.title)} ${dim(new Date().toLocaleTimeString())}${res.data.reloaded ? dim(` (${res.data.reloaded} running ${res.data.reloaded === 1 ? 'game' : 'games'} restarted)`) : ''}`);
124
+ if (why === 'start') log(`Play it: ${bold(res.data.play)}\n${dim('Watching for changes. Ctrl+C stops.')}`);
125
+ return true;
126
+ } finally { busy = false; if (again) { again = false; void push('change'); } }
127
+ }
128
+ if (!(await push('start')) && once) return 1;
129
+ if (once) return 0;
130
+ const onChange = (_, file) => { if (file && !/^(game\.json|server\.js)$/.test(String(file))) return; clearTimeout(timer); timer = setTimeout(() => void push('change'), 150); };
131
+ const watcher = watch(dir, onChange);
132
+ // The game's console: what the script logged and what the platform told it, from every running copy.
133
+ const poll = setInterval(async () => {
134
+ if (!id) return;
135
+ const res = await call(server, token, 'GET', `/api/play/dev/logs?game=${encodeURIComponent(id)}&after=${seq}`).catch(() => null);
136
+ for (const l of res?.data?.logs || []) { seq = Math.max(seq, l.seq); log(`${l.level === 'error' ? red('error') : l.level === 'warn' ? yellow('warn ') : dim('log ')} ${l.text}`); }
137
+ }, 1500);
138
+ await new Promise(done => { const stop = () => { watcher.close(); clearInterval(poll); clearTimeout(timer); done(); }; process.once('SIGINT', stop); signal?.addEventListener('abort', stop); });
139
+ return 0;
140
+ },
141
+ async pack(flags, log) {
142
+ const dir = resolve(flags._[0] || '.'), r = readGame(dir);
143
+ report(r, log); if (!r.ok) return 1;
144
+ const out = resolve(String(flags.out || join(dir, `${r.pkg.manifest.id}-${r.pkg.manifest.version}.egpkg.json`)));
145
+ writeFileSync(out, JSON.stringify({ format: 'earthgames-package', api: r.pkg.manifest.api, manifest: r.manifest, server: r.pkg.server }) + '\n');
146
+ log(`${green('Packed')} ${out} (${Math.ceil(statSync(out).size / 1024)} KB)`);
147
+ return 0;
148
+ },
149
+ async submit(flags, log) {
150
+ const dir = resolve(flags._[0] || '.'), r = readGame(dir), { server, token } = settings(flags);
151
+ report(r, log); if (!r.ok) return 1;
152
+ if (!token) { log('Sign in first: earthgames login --token egdev_… (your token is on the Developer tab of your account)'); return 1; }
153
+ const res = await call(server, token, 'POST', '/api/play/dev/submit', JSON.stringify({ manifest: r.manifest, server: r.pkg.server }));
154
+ if (!res.ok) { log(red(res.error || 'The game could not be sent.')); for (const e of res.data?.errors || []) log(`${red('error')} ${e}`); return 1; }
155
+ for (const w of res.data.warnings || []) log(`${yellow('note')} ${w}`);
156
+ log(`${green('Sent for review')} ${bold(r.pkg.manifest.title)} ${res.data.version}`);
157
+ log(res.data.live ? `Players keep getting version ${res.data.live} until the team approves this one.` : 'The Earth Games team reviews every game before it goes live.');
158
+ log(`See where it stands: ${bold('earthgames status')} (or the Developer tab of your account). Once live, its page is ${res.data.page}`);
159
+ return 0;
160
+ },
161
+ async status(flags, log) {
162
+ const { server, token } = settings(flags);
163
+ if (!token) { log('Sign in first: earthgames login --token egdev_…'); return 1; }
164
+ const res = await call(server, token, 'GET', '/api/play/dev/games');
165
+ if (!res.ok) { log(red(res.error || 'Could not ask the server.')); return 1; }
166
+ if (!res.data.games.length) { log('You have not sent a game for review yet. In a game\'s folder: earthgames submit'); return 0; }
167
+ const word = { live: green('live'), review: yellow('waiting for review'), rejected: red('not approved'), killed: red('switched off by the team'), none: dim('not live') };
168
+ for (const g of res.data.games) {
169
+ log(`${bold(g.id)} ${word[g.status] || g.status}${g.live ? dim(` (players get ${g.live})`) : ''}${g.reports ? yellow(` ${g.reports} open ${g.reports === 1 ? 'report' : 'reports'}`) : ''}`);
170
+ if (g.killed) log(` ${red('switched off')}: ${g.killed.reason}`);
171
+ for (const v of g.versions.slice(0, 3)) log(` ${v.v} ${v.state}${v.note ? `: ${v.note}` : ''}`);
172
+ }
173
+ return 0;
174
+ },
175
+ };
176
+
177
+ /** One request to the site. → { ok, status, data, error } (never throws for an HTTP error). */
178
+ export async function call(server, token, method, path, body = null) {
179
+ let res;
180
+ try { res = await fetch(server + path, { method, headers: { authorization: `Bearer ${token}`, ...(body ? { 'content-type': 'application/json' } : {}) }, body }); }
181
+ catch (e) { return { ok: false, status: 0, data: null, error: `Could not reach ${server} (${e.cause?.code || e.message}).` }; }
182
+ let data = null; try { data = await res.json(); } catch {}
183
+ return { ok: res.ok && data?.ok !== false, status: res.status, data, error: data?.error || (res.ok ? null : res.status === 401 ? 'That developer token is not valid. Make a new one on the Developer tab of your account, then: earthgames login --token …' : `The server said ${res.status}.`) };
184
+ }
185
+
186
+ const HELP = `Earth Games kit
187
+
188
+ earthgames new <folder> [--template blank|pursuit|horde]
189
+ earthgames check [folder]
190
+ earthgames login --token <token>
191
+ earthgames dev [folder]
192
+ earthgames pack [folder]
193
+ earthgames submit [folder]
194
+ earthgames status
195
+
196
+ Docs: ${DEFAULT_SERVER}/developers`;
197
+
198
+ export async function main(argv, log = console.log) {
199
+ const [cmd, ...rest] = argv;
200
+ if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') { log(HELP); return 0; }
201
+ if (cmd === '--version' || cmd === '-v') { log(JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version); return 0; }
202
+ if (!Object.hasOwn(commands, cmd)) { log(`There is no "${cmd}" command.\n\n${HELP}`); return 1; }
203
+ return commands[cmd](parseArgs(rest), log);
204
+ }
205
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(process.argv.slice(2)).then(code => { process.exitCode = code; }, e => { console.error(red(e?.message || String(e))); process.exitCode = 1; });