Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy

Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:32:36 +02:00
parent b56b13880e
commit 249818a7aa
111 changed files with 17472 additions and 13 deletions

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /alliances. Found an alliance: needs Peering office >= 1 on one of the founder's POPs; the founder becomes
* leader. Size cap = 10 + 2 * best Peering office level at this moment (rules.allianceCap), stored. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
const NAME_RE = /^[\p{L}\p{N}][\p{L}\p{N} _.'-]*$/u;
module.exports = function allianceCreate(ctx, { userId, worldId, name, tag }) {
const { db, now } = ctx;
const S = A.S;
const op = A.operatorOf(db, userId, worldId);
if (A.membership(db, op.id)) throw new GameError('already_in_alliance', { allianceId: A.membership(db, op.id).alliance_id });
const lvl = A.peeringLevel(db, op.id);
if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel });
name = cleanText(name);
tag = cleanText(tag);
const errors = [];
const len = [...name].length;
if (len < S.nameLen[0] || len > S.nameLen[1] || !NAME_RE.test(name)) errors.push({ path: 'name', message: 'must be ' + S.nameLen[0] + '-' + S.nameLen[1] + ' letters, digits, spaces or _ . \' -' });
if (!/^[A-Za-z0-9]+$/.test(tag) || tag.length < S.tagLen[0] || tag.length > S.tagLen[1]) errors.push({ path: 'tag', message: 'must be ' + S.tagLen[0] + '-' + S.tagLen[1] + ' letters or digits' });
if (errors.length) throw new GameError('validation_failed', { errors });
if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND name = ?', op.world_id, name)) throw new GameError('alliance_name_taken');
if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND tag = ?', op.world_id, tag)) throw new GameError('alliance_tag_taken');
const cap = R.allianceCap(lvl);
const r = db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)', op.world_id, name, tag, cap, op.id, now);
const id = Number(r.lastInsertRowid);
A.addMember(db, id, op.id, 'leader', now);
return { allianceId: id, name, tag, sizeCap: cap, role: 'leader' };
};

View file

@ -0,0 +1,9 @@
'use strict';
/* POST /alliances/:id/disband. Leader only. Removes members, invites, notes, proposals and relations. */
const A = require('../alliances');
module.exports = function allianceDisband(ctx, { userId, allianceId }) {
const { alliance } = A.requireRole(ctx.db, userId, allianceId, 'disband');
A.dissolve(ctx, alliance.id, 'disbanded');
return { changed: true };
};

View file

@ -0,0 +1,32 @@
'use strict';
/* POST /alliances/:id/invite. Needs the `invite` permission. Target by operator id or name (same world). Idempotent:
* a second invite to the same operator returns the pending one. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInvite(ctx, { userId, allianceId, operatorId, name }) {
const { db, now } = ctx;
const S = A.S;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'invite');
const target = operatorId !== undefined
? db.get('SELECT * FROM operators WHERE id = ? AND world_id = ?', operatorId, alliance.world_id)
: db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', name, alliance.world_id);
if (!target) throw new GameError('not_found', { what: 'operator' });
if (target.id === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot invite yourself' }] });
const m = A.membership(db, target.id);
if (m) throw new GameError('already_in_alliance', { allianceId: m.alliance_id });
db.run("UPDATE alliance_invites SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now);
const open = db.get("SELECT id, expires_at FROM alliance_invites WHERE alliance_id = ? AND operator_id = ? AND status = 'pending'", alliance.id, target.id);
if (open) return { inviteId: open.id, operatorId: target.id, expiresAt: open.expires_at, changed: false };
if (A.memberCount(db, alliance.id) >= A.refreshCap(db, alliance)) throw new GameError('alliance_full', { cap: alliance.size_cap });
const pending = db.get("SELECT COUNT(*) AS n FROM alliance_invites WHERE alliance_id = ? AND status = 'pending'", alliance.id).n;
if (pending >= S.maxPendingInvites) throw new GameError('conflict', { what: 'too many pending invites', max: S.maxPendingInvites });
const expiresAt = now + Math.round(S.inviteTtlHours * A.HOUR);
const r = db.run('INSERT INTO alliance_invites (alliance_id, operator_id, invited_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?)', alliance.id, target.id, op.id, now, expiresAt);
const inviteId = Number(r.lastInsertRowid);
A.notifyOperator(ctx, target.id, 'alliance_invite', { inviteId, allianceId: alliance.id, tag: alliance.tag, name: alliance.name, by: op.name, expiresAt });
return { inviteId, operatorId: target.id, expiresAt, changed: true };
};

View file

@ -0,0 +1,41 @@
'use strict';
/* POST /alliance-invites/:id/accept | /decline. Only the invited operator's user. Accepting needs Peering office >= 1,
* no current alliance, and room (cap re-evaluated). Answering an already answered invite the same way is a no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInviteAnswer(ctx, { userId, inviteId, accept }) {
const { db, now } = ctx;
const S = A.S;
const inv = db.get(`SELECT i.*, o.user_id AS uid, o.name AS oname FROM alliance_invites i JOIN operators o ON o.id = i.operator_id WHERE i.id = ?`, inviteId);
if (!inv || inv.uid !== userId) throw new GameError('not_found', { what: 'invite' });
if (inv.status !== 'pending') {
if ((accept && inv.status === 'accepted') || (!accept && inv.status === 'declined')) return { changed: false, allianceId: inv.alliance_id };
throw new GameError(inv.status === 'expired' ? 'invite_expired' : 'conflict', { what: 'invite is ' + inv.status });
}
if (inv.expires_at <= now) {
// The refusal rolls this transaction back; the invite is simply treated as expired whenever it is looked at.
throw new GameError('invite_expired', { expiresAt: inv.expires_at });
}
const alliance = A.getAlliance(db, inv.alliance_id);
if (!alliance) throw new GameError('not_found', { what: 'alliance' });
if (!accept) {
db.run("UPDATE alliance_invites SET status = 'declined', answered_at = ? WHERE id = ?", now, inv.id);
A.notifyOperator(ctx, inv.invited_by, 'alliance_invite_declined', { inviteId: inv.id, allianceId: alliance.id, by: inv.oname });
return { changed: true, allianceId: alliance.id };
}
const cur = A.membership(db, inv.operator_id);
if (cur) throw new GameError('already_in_alliance', { allianceId: cur.alliance_id });
const lvl = A.peeringLevel(db, inv.operator_id);
if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel });
const cap = A.refreshCap(db, alliance);
if (A.memberCount(db, alliance.id) >= cap) throw new GameError('alliance_full', { cap });
A.addMember(db, alliance.id, inv.operator_id, 'member', now);
db.run("UPDATE alliance_invites SET status = 'accepted', answered_at = ? WHERE id = ?", now, inv.id);
A.notifyAlliance(ctx, alliance.id, 'alliance_member_joined', { allianceId: alliance.id, operatorId: inv.operator_id, name: inv.oname }, { except: inv.operator_id });
return { changed: true, allianceId: alliance.id, role: 'member' };
};

View file

@ -0,0 +1,15 @@
'use strict';
/* DELETE /alliances/:id/invites/:inviteId. Needs `cancelInvite`. Idempotent for an already cancelled invite. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceInviteCancel(ctx, { userId, allianceId, inviteId }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'cancelInvite');
const inv = db.get('SELECT id, status FROM alliance_invites WHERE id = ? AND alliance_id = ?', inviteId, alliance.id);
if (!inv) throw new GameError('not_found', { what: 'invite' });
if (inv.status === 'cancelled') return { changed: false };
if (inv.status !== 'pending') throw new GameError('conflict', { what: 'invite is ' + inv.status });
db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE id = ?", now, inv.id);
return { changed: true };
};

View file

@ -0,0 +1,19 @@
'use strict';
/* POST /alliances/:id/kick. Needs `kick` and the actor must outrank the target. Target not in the alliance: no-op. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceKick(ctx, { userId, allianceId, operatorId }) {
const { db } = ctx;
const { op, alliance, member } = A.requireRole(db, userId, allianceId, 'kick');
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'use leave to leave an alliance' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) return { changed: false };
if (!R.outranks(member.role, t.role)) throw new GameError('forbidden', { need: 'outrank', role: member.role, targetRole: t.role });
const target = db.get('SELECT id, name FROM operators WHERE id = ?', operatorId);
A.removeMember(db, operatorId);
A.notifyOperator(ctx, operatorId, 'alliance_kicked', { allianceId: alliance.id, tag: alliance.tag, name: alliance.name });
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId, name: target.name, kicked: true });
return { changed: true };
};

View file

@ -0,0 +1,23 @@
'use strict';
/* POST /alliances/:id/leave. The leader cannot leave while others remain (transfer first); a leader who is alone
* dissolves the alliance. Leaving an alliance you are not in is a no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceLeave(ctx, { userId, allianceId }) {
const { db } = ctx;
const alliance = A.getAlliance(db, allianceId);
if (!alliance) throw new GameError('not_found', { what: 'alliance' });
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, alliance.world_id);
if (!op) throw new GameError('not_found', { what: 'alliance' });
const m = A.membership(db, op.id);
if (!m || m.alliance_id !== alliance.id) return { changed: false };
if (m.role === 'leader') {
if (A.memberCount(db, alliance.id) > 1) throw new GameError('leader_must_transfer');
A.dissolve(ctx, alliance.id, 'last_member_left');
return { changed: true, disbanded: true };
}
A.removeMember(db, op.id);
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false });
return { changed: true, disbanded: false };
};

View file

@ -0,0 +1,41 @@
'use strict';
/* Pinned notes of an alliance. Three commands, one file: allianceNoteAdd / allianceNoteEdit / allianceNoteDelete
* (registered separately in commands/index.js). Needs `editNotes`. */
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
function text(raw) {
const t = cleanText(raw, { multiline: true });
if (!t || [...t].length > A.S.noteMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + A.S.noteMax + ' characters of plain text' }] });
return t;
}
const view = (n) => ({ id: n.id, authorId: n.author_id, text: n.text, createdAt: n.created_at, updatedAt: n.updated_at });
function allianceNoteAdd(ctx, { userId, allianceId, text: raw }) {
const { db, now } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const t = text(raw);
if (db.get('SELECT COUNT(*) AS n FROM alliance_notes WHERE alliance_id = ?', alliance.id).n >= A.S.maxNotes) throw new GameError('notes_full', { max: A.S.maxNotes });
const r = db.run('INSERT INTO alliance_notes (alliance_id, author_id, text, created_at, updated_at) VALUES (?, ?, ?, ?, ?)', alliance.id, op.id, t, now, now);
return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', Number(r.lastInsertRowid))) };
}
function allianceNoteEdit(ctx, { userId, allianceId, noteId, text: raw }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const t = text(raw);
const r = db.run('UPDATE alliance_notes SET text = ?, updated_at = ? WHERE id = ? AND alliance_id = ?', t, now, noteId, alliance.id);
if (!r.changes) throw new GameError('not_found', { what: 'note' });
return { note: view(db.get('SELECT * FROM alliance_notes WHERE id = ?', noteId)) };
}
function allianceNoteDelete(ctx, { userId, allianceId, noteId }) {
const { db } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'editNotes');
const r = db.run('DELETE FROM alliance_notes WHERE id = ? AND alliance_id = ?', noteId, alliance.id);
return { changed: r.changes > 0 };
}
module.exports = { allianceNoteAdd, allianceNoteEdit, allianceNoteDelete, noteView: view };

View file

@ -0,0 +1,17 @@
'use strict';
/* POST /alliances/:id/role. Needs `setRole` (leader). Roles diplomat | officer | member; use transfer for leadership. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceRole(ctx, { userId, allianceId, operatorId, role }) {
const { db } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'setRole');
if (A.S.roles.indexOf(role) < 0 || role === 'leader') throw new GameError('validation_failed', { errors: [{ path: 'role', message: 'must be diplomat, officer or member' }] });
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'the leader cannot change their own role; transfer leadership' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' });
if (t.role === role) return { changed: false, role };
db.run('UPDATE alliance_members SET role = ? WHERE operator_id = ?', role, operatorId);
A.notifyOperator(ctx, operatorId, 'alliance_role', { allianceId: alliance.id, tag: alliance.tag, from: t.role, role });
return { changed: true, role };
};

View file

@ -0,0 +1,18 @@
'use strict';
/* POST /alliances/:id/transfer. The leader hands leadership to another member and becomes an officer. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function allianceTransfer(ctx, { userId, allianceId, operatorId }) {
const { db } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'transfer');
if (operatorId === op.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you are already the leader' }] });
const t = A.membership(db, operatorId);
if (!t || t.alliance_id !== alliance.id) throw new GameError('not_found', { what: 'member' });
db.run("UPDATE alliance_members SET role = 'officer' WHERE operator_id = ?", op.id); // before promoting: one leader at a time
db.run("UPDATE alliance_members SET role = 'leader' WHERE operator_id = ?", operatorId);
A.refreshCap(db, alliance);
const target = db.get('SELECT name FROM operators WHERE id = ?', operatorId);
A.notifyAlliance(ctx, alliance.id, 'alliance_leader', { allianceId: alliance.id, operatorId, name: target.name, from: op.name });
return { changed: true, leaderId: operatorId };
};

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /diplomacy/proposals/:proposalId/accept | /decline. Needs `diplomacy` in the receiving alliance. The move is
* validated again against the CURRENT relation (it may have changed since the proposal was made). */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploAnswer(ctx, { userId, proposalId, accept }) {
const { db, now } = ctx;
const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId);
if (!p) throw new GameError('not_found', { what: 'proposal' });
const { op, alliance } = A.requireRole(db, userId, p.to_id, 'diplomacy'); // forbidden/not_found for outsiders
if (p.status !== 'pending') {
if ((accept && p.status === 'accepted') || (!accept && p.status === 'declined')) return { changed: false };
throw new GameError(p.status === 'expired' ? 'proposal_expired' : 'conflict', { what: 'proposal is ' + p.status });
}
if (p.expires_at <= now) throw new GameError('proposal_expired', { expiresAt: p.expires_at });
const proposer = A.getAlliance(db, p.from_id);
if (!proposer) throw new GameError('not_found', { what: 'alliance' });
if (!accept) {
db.run("UPDATE alliance_proposals SET status = 'declined', answered_at = ? WHERE id = ?", now, p.id);
A.notifyAlliance(ctx, proposer.id, 'diplomacy_declined', { proposalId: p.id, by: Dip.brief(alliance), state: p.state }, { roles: ['leader', 'diplomat'] });
return { changed: true };
}
const rel = A.getRelation(db, alliance.id, proposer.id);
const from = rel ? rel.state : 'neutral';
if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at });
if (R.diplomacyMove(from, p.state) !== 'proposal') throw new GameError('diplomacy_invalid', { from, to: p.state });
db.run("UPDATE alliance_proposals SET status = 'accepted', answered_at = ? WHERE id = ?", now, p.id);
Dip.applyChange(ctx, alliance, proposer, p.state, { by: op.name, proposalId: p.id });
return { changed: true, from, state: p.state };
};

View file

@ -0,0 +1,54 @@
'use strict';
/* POST /alliances/:id/diplomacy { targetId, state }. Needs `diplomacy`. What happens depends on the move
* (rules.diplomacyMove): 'immediate' applies at once (declaring war from neutral), 'delayed' schedules a cancel that
* takes 24 h / world speed (a `diploChange` event), 'proposal' asks the other alliance to accept. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { loadWorld } = require('../state');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploPropose(ctx, { userId, allianceId, targetId, state }) {
const { db, now, scheduler } = ctx;
const { op, alliance } = A.requireRole(db, userId, allianceId, 'diplomacy');
if (targetId === alliance.id) throw new GameError('validation_failed', { errors: [{ path: 'targetId', message: 'cannot be your own alliance' }] });
const other = A.getAlliance(db, targetId);
if (!other || other.world_id !== alliance.world_id) throw new GameError('not_found', { what: 'alliance' });
const rel = A.getRelation(db, alliance.id, other.id);
const from = rel ? rel.state : 'neutral';
if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at, startedBy: rel.pending_by });
const move = R.diplomacyMove(from, state);
if (!move) throw new GameError('diplomacy_invalid', { from, to: state });
if (move === 'immediate') {
Dip.applyChange(ctx, alliance, other, state, { by: op.name });
return { result: 'applied', from, state };
}
if (move === 'delayed') {
const world = loadWorld(db, alliance.world_id);
const dueAt = now + R.pactCancelMs(world.speed);
A.withdrawProposals(db, alliance.id, other.id, now);
const eventId = scheduler.enqueue({ worldId: alliance.world_id, dueAt, type: 'diploChange', payload: { a: alliance.id, b: other.id, to: state, by: alliance.id } });
const [x, y] = A.pairOf(alliance.id, other.id);
db.run('UPDATE alliance_relations SET pending_to = ?, pending_at = ?, pending_by = ?, pending_event = ? WHERE a_id = ? AND b_id = ?', state, dueAt, alliance.id, eventId, x, y);
for (const [me, o2] of [[alliance, other], [other, alliance]]) {
A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_pending', { allianceId: me.id, other: Dip.brief(o2), from, to: state, effectiveAt: dueAt, startedBy: alliance.id });
}
return { result: 'scheduled', from, state, effectiveAt: dueAt, eventId };
}
// proposal
const reverse = db.get("SELECT id, state AS st, expires_at FROM alliance_proposals WHERE from_id = ? AND to_id = ? AND status = 'pending'", other.id, alliance.id);
if (reverse && reverse.expires_at > now && reverse.st === state) throw new GameError('proposal_exists', { proposalId: reverse.id });
db.run("UPDATE alliance_proposals SET status = 'expired', answered_at = ? WHERE status = 'pending' AND expires_at <= ?", now, now);
// a new proposal from the same side replaces the old one
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE from_id = ? AND to_id = ? AND status = 'pending'", now, alliance.id, other.id);
const expiresAt = now + Math.round(A.S.proposalTtlHours * A.HOUR);
const r = db.run('INSERT INTO alliance_proposals (world_id, from_id, to_id, state, proposed_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
alliance.world_id, alliance.id, other.id, state, op.id, now, expiresAt);
const proposalId = Number(r.lastInsertRowid);
A.notifyAlliance(ctx, other.id, 'diplomacy_proposal', { proposalId, from: Dip.brief(alliance), state, expiresAt }, { roles: ['leader', 'diplomat'] });
return { result: 'proposed', from, state, proposalId, expiresAt };
};

View file

@ -0,0 +1,22 @@
'use strict';
/* DELETE /alliances/:id/diplomacy/:otherId/pending. The alliance that started a delayed change (cancelling a pact,
* declaring war out of a pact) may take it back before it takes effect. Nothing pending: no-op. */
const { GameError } = require('../errors');
const A = require('../alliances');
const Dip = require('../diplomacy');
module.exports = function diploRevoke(ctx, { userId, allianceId, otherId }) {
const { db, now } = ctx;
const { alliance } = A.requireRole(db, userId, allianceId, 'diplomacy');
const other = A.getAlliance(db, otherId);
if (!other) throw new GameError('not_found', { what: 'alliance' });
const rel = A.getRelation(db, alliance.id, other.id);
if (!rel || !rel.pending_to) return { changed: false };
if (rel.pending_by !== alliance.id) throw new GameError('forbidden', { need: 'pending change started by your alliance' });
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, rel.pending_event);
db.run('UPDATE alliance_relations SET pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL WHERE a_id = ? AND b_id = ?', rel.a_id, rel.b_id);
for (const [me, o2] of [[alliance, other], [other, alliance]]) {
A.notifyAlliance(ctx, me.id, 'diplomacy_cancel_revoked', { allianceId: me.id, other: Dip.brief(o2), state: rel.state });
}
return { changed: true, state: rel.state };
};

View file

@ -0,0 +1,15 @@
'use strict';
/* DELETE /diplomacy/proposals/:proposalId. The proposing alliance withdraws it. Needs `diplomacy`. */
const { GameError } = require('../errors');
const A = require('../alliances');
module.exports = function diploWithdraw(ctx, { userId, proposalId }) {
const { db, now } = ctx;
const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId);
if (!p) throw new GameError('not_found', { what: 'proposal' });
A.requireRole(db, userId, p.from_id, 'diplomacy');
if (p.status === 'withdrawn') return { changed: false };
if (p.status !== 'pending') throw new GameError('conflict', { what: 'proposal is ' + p.status });
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE id = ?", now, p.id);
return { changed: true };
};

View file

@ -5,11 +5,41 @@
* scheduler timer because the command may have enqueued events.
*/
const handlers = {
// stage 3/4: military and expansion
train: require('./train'),
research: require('./research'),
sendMovement: require('./sendMovement'),
sendTransport: require('./sendTransport'),
recallMovement: require('./recallMovement'),
withdrawStationed: require('./withdrawStationed'),
markReportRead: require('./markReportRead'),
signup: require('./signup'),
joinWorld: require('./joinWorld'),
build: require('./build'),
cancelBuild: require('./cancelBuild'),
renameTown: require('./renameTown'),
// stage 5: alliances, diplomacy, messages
allianceCreate: require('./allianceCreate'),
allianceInvite: require('./allianceInvite'),
allianceInviteCancel: require('./allianceInviteCancel'),
allianceInviteAnswer: require('./allianceInviteAnswer'),
allianceLeave: require('./allianceLeave'),
allianceKick: require('./allianceKick'),
allianceRole: require('./allianceRole'),
allianceTransfer: require('./allianceTransfer'),
allianceDisband: require('./allianceDisband'),
allianceNoteAdd: require('./allianceNote').allianceNoteAdd,
allianceNoteEdit: require('./allianceNote').allianceNoteEdit,
allianceNoteDelete: require('./allianceNote').allianceNoteDelete,
diploPropose: require('./diploPropose'),
diploAnswer: require('./diploAnswer'),
diploWithdraw: require('./diploWithdraw'),
diploRevoke: require('./diploRevoke'),
messageSend: require('./messageSend'),
messageRead: require('./messageRead'),
messageDelete: require('./messageDelete'),
messageBlock: require('./messageBlock').messageBlock,
messageUnblock: require('./messageBlock').messageUnblock,
};
function createCommands({ db, clock, scheduler }) {

View file

@ -0,0 +1,14 @@
'use strict';
/* POST /reports/:id/read (and /reports/read-all). Per-user read flag; the report itself is shared. */
const { GameError } = require('../errors');
module.exports = function markReportRead(ctx, { userId, reportId, all }) {
const { db, now } = ctx;
if (all) {
const r = db.run('UPDATE report_recipients SET read_at = ? WHERE user_id = ? AND read_at IS NULL', now, userId);
return { marked: Number(r.changes) };
}
const r = db.run('UPDATE report_recipients SET read_at = COALESCE(read_at, ?) WHERE report_id = ? AND user_id = ?', now, reportId, userId);
if (!r.changes) throw new GameError('not_found', { what: 'report' });
return { marked: 1 };
};

View file

@ -0,0 +1,31 @@
'use strict';
/* POST /messages/blocks { operatorId } and DELETE /messages/blocks/:operatorId. Blocked senders' messages are not
* delivered (the sender is not told). Both idempotent. Registered as messageBlock and messageUnblock. */
const { GameError } = require('../errors');
const A = require('../alliances');
function resolve(db, userId, operatorId) {
const target = db.get('SELECT * FROM operators WHERE id = ?', operatorId);
if (!target) throw new GameError('not_found', { what: 'operator' });
const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id);
if (!me) throw new GameError('not_found', { what: 'operator' });
if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'you cannot block yourself' }] });
return { me, target };
}
function messageBlock(ctx, { userId, operatorId }) {
const { db, now } = ctx;
const { me, target } = resolve(db, userId, operatorId);
if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id)) return { changed: false };
if (db.get('SELECT COUNT(*) AS n FROM message_blocks WHERE operator_id = ?', me.id).n >= A.S.maxBlocks) throw new GameError('conflict', { what: 'block list full', max: A.S.maxBlocks });
db.run('INSERT INTO message_blocks (operator_id, blocked_id, created_at) VALUES (?, ?, ?)', me.id, target.id, now);
return { changed: true };
}
function messageUnblock(ctx, { userId, operatorId }) {
const { db } = ctx;
const { me, target } = resolve(db, userId, operatorId);
return { changed: db.run('DELETE FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', me.id, target.id).changes > 0 };
}
module.exports = { messageBlock, messageUnblock };

View file

@ -0,0 +1,24 @@
'use strict';
/* DELETE /messages/:id. Removes the caller's own copy only (sender copy or recipient copy). When nobody has a copy
* left the row is purged. Deleting an already deleted copy is a no-op; a message you never saw is not_found. */
const { GameError } = require('../errors');
module.exports = function messageDelete(ctx, { userId, messageId }) {
const { db, now } = ctx;
const m = db.get('SELECT m.id, m.sender_id, m.sender_deleted_at, o.user_id AS suid FROM messages m JOIN operators o ON o.id = m.sender_id WHERE m.id = ?', messageId);
if (!m) throw new GameError('not_found', { what: 'message' });
let changed = false;
if (m.suid === userId) {
changed = !m.sender_deleted_at;
if (changed) db.run('UPDATE messages SET sender_deleted_at = ? WHERE id = ?', now, m.id);
} else {
const r = db.get(`SELECT r.operator_id, r.deleted_at FROM message_recipients r JOIN operators o ON o.id = r.operator_id WHERE r.message_id = ? AND o.user_id = ?`, m.id, userId);
if (!r) throw new GameError('not_found', { what: 'message' });
changed = !r.deleted_at;
if (changed) db.run('UPDATE message_recipients SET deleted_at = ? WHERE message_id = ? AND operator_id = ?', now, m.id, r.operator_id);
}
const left = db.get(`SELECT (SELECT sender_deleted_at IS NULL FROM messages WHERE id = ?) AS s,
(SELECT COUNT(*) FROM message_recipients WHERE message_id = ? AND deleted_at IS NULL) AS r`, m.id, m.id);
if (!left.s && !left.r) { db.run('DELETE FROM message_recipients WHERE message_id = ?', m.id); db.run('DELETE FROM messages WHERE id = ?', m.id); }
return { changed };
};

View file

@ -0,0 +1,12 @@
'use strict';
/* POST /messages/read { ids } or { all: true }: mark received messages read. Already-read ones are left alone. */
module.exports = function messageRead(ctx, { userId, ids, all, worldId }) {
const { db, now } = ctx;
const ops = db.all(worldId !== undefined ? 'SELECT id FROM operators WHERE user_id = ? AND world_id = ?' : 'SELECT id FROM operators WHERE user_id = ?', userId, ...(worldId !== undefined ? [worldId] : []));
let changed = 0;
for (const o of ops) {
if (all) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id).changes;
else for (const id of ids || []) changed += db.run('UPDATE message_recipients SET read_at = ? WHERE operator_id = ? AND message_id = ? AND read_at IS NULL AND deleted_at IS NULL', now, o.id, id).changes;
}
return { changed: Number(changed) };
};

View file

@ -0,0 +1,72 @@
'use strict';
/* POST /messages. Player-to-player (toOperatorId | toName) or broadcast to the sender's alliance (toAlliance: true).
* Plain text, control/bidi characters stripped, at most SOCIAL.messageMax characters, rate-limited per sender by
* counting their recent rows in `messages` (DB-backed: survives restarts, follows the injected clock).
* A recipient who blocked the sender gets no row at all; the sender is not told. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { cleanText } = require('../text');
const A = require('../alliances');
const MIN = 60 * 1000;
function limit(db, senderId, kind, now) {
const L = A.S.messageLimits;
const windows = kind === 'dm' ? [[10 * MIN, L.dm10min], [60 * MIN, L.dmHour]] : [[60 * MIN, L.broadcastHour]];
for (const [ms, max] of windows) {
const r = db.get('SELECT COUNT(*) AS n, MIN(created_at) AS first FROM messages WHERE sender_id = ? AND kind = ? AND created_at > ?', senderId, kind, now - ms);
if (r.n >= max) throw new GameError('rate_limited', { retryAfter: Math.max(1, Math.ceil((r.first + ms - now) / 1000)), limit: max, windowMs: ms, scope: 'messages' });
}
}
module.exports = function messageSend(ctx, { userId, worldId, toOperatorId, toName, toAlliance, text }) {
const { db, now } = ctx;
const S = A.S;
const body = cleanText(text, { multiline: true });
if (!body || [...body].length > S.messageMax) throw new GameError('validation_failed', { errors: [{ path: 'text', message: 'must be 1-' + S.messageMax + ' characters of plain text' }] });
const targets = [toOperatorId !== undefined, toName !== undefined, !!toAlliance].filter(Boolean).length;
if (targets !== 1) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'give exactly one of toOperatorId, toName, toAlliance' }] });
if (toAlliance) {
const me = A.operatorOf(db, userId, worldId);
const m = A.membership(db, me.id);
if (!m) throw new GameError('not_in_alliance');
if (!R.allianceCan(m.role, 'broadcast')) throw new GameError('forbidden', { need: 'broadcast', role: m.role });
limit(db, me.id, 'alliance', now);
const alliance = A.getAlliance(db, m.alliance_id);
const r = db.run('INSERT INTO messages (world_id, sender_id, kind, alliance_id, alliance_tag, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
me.world_id, me.id, 'alliance', alliance.id, alliance.tag, 'alliance:' + alliance.id, body, now);
const id = Number(r.lastInsertRowid);
const members = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND operator_id <> ?', alliance.id, me.id);
let delivered = 0;
for (const mm of members) {
if (db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', mm.operator_id, me.id)) continue;
db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, mm.operator_id);
delivered++;
A.notifyOperator(ctx, mm.operator_id, 'alliance_message', { messageId: id, allianceId: alliance.id, tag: alliance.tag, from: me.name });
}
return { messageId: id, kind: 'alliance', recipients: delivered, createdAt: now };
}
let target;
if (toOperatorId !== undefined) target = db.get('SELECT * FROM operators WHERE id = ?', toOperatorId);
else {
const mine = A.operatorOf(db, userId, worldId); // the world the name is looked up in
target = db.get('SELECT * FROM operators WHERE name = ? COLLATE NOCASE AND world_id = ?', toName, mine.world_id);
}
if (!target) throw new GameError('not_found', { what: 'operator' });
const me = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, target.world_id);
if (!me) throw new GameError('not_found', { what: 'operator' });
if (me.id === target.id) throw new GameError('validation_failed', { errors: [{ path: 'toOperatorId', message: 'you cannot message yourself' }] });
limit(db, me.id, 'dm', now);
const lo = Math.min(me.id, target.id), hi = Math.max(me.id, target.id);
const r = db.run('INSERT INTO messages (world_id, sender_id, kind, to_id, thread, body, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
me.world_id, me.id, 'dm', target.id, 'dm:' + lo + ':' + hi, body, now);
const id = Number(r.lastInsertRowid);
const blocked = !!db.get('SELECT 1 AS x FROM message_blocks WHERE operator_id = ? AND blocked_id = ?', target.id, me.id);
if (!blocked) {
db.run('INSERT INTO message_recipients (message_id, operator_id) VALUES (?, ?)', id, target.id);
A.notifyOperator(ctx, target.id, 'message', { messageId: id, from: { operatorId: me.id, name: me.name } });
}
return { messageId: id, kind: 'dm', recipients: blocked ? 0 : 1, createdAt: now };
};

View file

@ -0,0 +1,30 @@
'use strict';
/* POST /movements/:id/recall. Within the first 90 s (MILITARY.recallWindowMs) an outbound movement can turn around:
* its arrive event is cancelled and a return leg takes the same units and cargo home in as long as they were out. */
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
module.exports = function recallMovement(ctx0, { userId, movementId }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const mv = M.getMovement(db, movementId);
const op = mv && db.get('SELECT id FROM operators WHERE id = ? AND user_id = ?', mv.ownerId, userId);
if (!mv || !op) throw new GameError('not_found', { what: 'movement' });
if (mv.status !== 'out' || mv.type === 'return') throw new GameError('conflict', { what: 'movement cannot be recalled', status: mv.status, type: mv.type });
if (now - mv.departAt > D.MILITARY.recallWindowMs) throw new GameError('recall_expired', { departAt: mv.departAt, windowMs: D.MILITARY.recallWindowMs });
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
const dest = U.homeTownFor(db, mv.ownerId, origin && origin.owner_id === mv.ownerId ? origin.id : null);
if (!dest) throw new GameError('conflict', { what: 'no POP to return to' });
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, mv.eventId);
db.run("UPDATE movements SET status = 'recalled' WHERE id = ?", mv.id);
const elapsed = Math.max(1000, now - mv.departAt);
const f = Math.min(1, (now - mv.departAt) / Math.max(1, mv.arriveAt - mv.departAt));
const at = { x: Math.round(mv.from.x + (mv.to.x - mv.from.x) * f), y: Math.round(mv.from.y + (mv.to.y - mv.from.y) * f) };
const extra = Object.assign({}, mv.extra, { recalled: true });
if (mv.type === 'transport') extra.link = 1;
const ret = M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at, to: dest, units: mv.units, cargo: mv.cargo, arriveAt: now + elapsed, parentId: mv.id, extra });
return { recalled: mv.id, returnMovementId: ret.id, arriveAt: ret.arriveAt };
};

View file

@ -0,0 +1,26 @@
'use strict';
/* POST /towns/:id/research. One research at a time per POP (a `researchDone` event). +5% attack or defence per level
* of one unit type; level n needs a Research lab of level n + RESEARCH.labOffset. Incumbent sites speed it up. */
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { settle, spend } = require('../state');
const { ownedTown } = require('./build');
const U = require('../military/units');
module.exports = function research(ctx, { userId, townId, unit, stat }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
if (!R.unitDef(unit)) throw new GameError('unknown_unit', { unit });
settle(db, town, now);
const busy = !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", town.id);
const current = U.researchLevels(db, town.id)[R.researchKey(unit, stat)] || 0;
const plan = R.researchPlan(town, unit, stat, current, busy, now, U.researchBonusOf(db, town.ownerId));
if (!plan.ok) throw new GameError(plan.code, { unit, stat, toLevel: plan.toLevel, cost: plan.cost, missing: plan.missing });
spend(db, town, plan.cost);
const dueAt = now + plan.durationMs;
const eventId = scheduler.enqueue({
worldId: town.worldId, townId: town.id, type: 'researchDone', dueAt,
payload: { unit, stat, toLevel: plan.toLevel, startedAt: now, cost: plan.cost, userId },
});
return { eventId, unit, stat, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost };
};

View file

@ -0,0 +1,120 @@
'use strict';
/*
* POST /movements. Send units from one of your POPs: scan, raid, attack, takeover, reinforce, settle. (Resources go
* through sendTransport.) Validates everything against the rules, takes the units out of the POP and enqueues the
* `arrive` event. Nothing resolves now: combat happens at arrival, in the event queue, in order.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { ownedTown } = require('./build');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
const P = require('../military/power');
const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle'];
const HOSTILE = ['raid', 'attack', 'takeover'];
// The target of a movement: a POP (by id or by tile) or a bare tile. -> { town: row|null, x, y, tile }
function resolveTarget(db, world, args) {
let town = null, x, y;
if (args.toTownId !== undefined && args.toTownId !== null) {
town = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', args.toTownId, world.id);
if (!town) throw new GameError('not_found', { what: 'town' });
x = town.x; y = town.y;
} else if (Number.isInteger(args.x) && Number.isInteger(args.y)) {
x = args.x; y = args.y;
town = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y) || null;
} else {
throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'give toTownId or x and y' }] });
}
const tile = R.tileAt(world.seed, world.map_radius, x, y);
if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' });
return { town, x, y, tile };
}
module.exports = function sendMovement(ctx0, args) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const { userId, fromTownId, type } = args;
if (TYPES.indexOf(type) < 0) throw new GameError('validation_failed', { errors: [{ path: 'type', message: 'must be one of ' + TYPES.join(', ') }] });
const from = ownedTown(db, userId, fromTownId);
const world = loadWorld(db, from.worldId);
const op = U.getOperator(db, from.ownerId);
const units = U.cleanUnits(args.units || {});
const chk = R.checkUnitsForType(type, units);
if (chk) throw new GameError(chk.code, { reason: chk.reason });
settle(db, from, now);
const home = U.homeUnits(db, from.id);
for (const k of Object.keys(units)) if ((home[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: home[k] || 0, want: units[k] });
if (!P.online(from, now)) throw new GameError('units_offline', { townId: from.id });
const tgt = resolveTarget(db, world, args);
if (tgt.town && tgt.town.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
const dist = R.distance(from.x, from.y, tgt.x, tgt.y);
const arriveAt = now + R.movementMs(dist, units, world.speed);
const extra = { research: U.researchSnapshot(db, from.id, units) };
let defOp = null;
let endProtection = false;
if (type === 'scan' || HOSTILE.indexOf(type) >= 0) {
if (tgt.town) {
defOp = U.getOperator(db, tgt.town.owner_id);
if (defOp.id === op.id) throw new GameError('invalid_target', { reason: 'own_town' });
if (type !== 'scan') {
if (U.pactBlocks(db, op.id, defOp.id)) throw new GameError('invalid_target', { reason: 'pact' });
if (R.isProtected(defOp.protection_until, arriveAt)) throw new GameError('target_protected', { until: defOp.protection_until });
if (R.isProtected(op.protection_until, now)) {
if (!args.confirmEndProtection) throw new GameError('protection_active', { until: op.protection_until });
endProtection = true;
}
}
if (type === 'takeover') {
const count = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
const block = R.takeoverBlock(!!tgt.town.is_capital, count);
if (block === 'last_pop') throw new GameError('cannot_takeover', { reason: block });
const gate = R.footprintGate(U.operatorTowns(db, op.id).length, U.operatorFootprint(db, op.id, now));
if (!gate.ok) throw new GameError('footprint_too_low', { need: gate.need, have: gate.have });
}
} else if (tgt.tile.type === 'incumbent') {
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' });
} else {
throw new GameError('invalid_target', { reason: 'nothing_there' });
}
if ((type === 'attack' || type === 'takeover') && units.exploit_kit && args.target !== undefined && args.target !== null) {
const t = String(args.target);
const bdef = R.isFieldKey(t) ? { special: false } : R.buildingDef(t);
if (!bdef || bdef.special) throw new GameError('validation_failed', { errors: [{ path: 'target', message: 'not a building' }] });
extra.target = t;
}
} else if (type === 'reinforce') {
if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' });
if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' });
defOp = U.getOperator(db, tgt.town.owner_id);
} else if (type === 'settle') {
const own = U.operatorTowns(db, op.id);
let nearest = Infinity;
for (const t of own) nearest = Math.min(nearest, R.distance(t.x, t.y, tgt.x, tgt.y));
const chk2 = R.settleCheck({ tileType: tgt.tile.type, occupied: !!tgt.town, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
if (!chk2.ok) throw new GameError(chk2.code, chk2);
extra.wild = R.cleanWild(args.wild);
}
// ---- all checks passed: apply
if (endProtection) db.run('UPDATE operators SET protection_until = ? WHERE id = ?', now, op.id);
U.removeHome(db, from.id, units);
P.reschedule(ctx, from.id, now);
const mv = M.insertMovement(ctx, {
worldId: from.worldId, ownerId: op.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null,
from: { x: from.x, y: from.y }, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, extra,
});
if (tgt.town && defOp && defOp.id !== op.id) {
const uid = U.userOfOperator(db, defOp.id);
if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: tgt.town.id, fromTownId: from.id, arriveAt }); // type hidden
}
return { movementId: mv.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, protectionEnded: endProtection };
};
module.exports.resolveTarget = resolveTarget;

View file

@ -0,0 +1,52 @@
'use strict';
/*
* POST /movements with type 'transport': carry resources from one of your POPs to any POP. Capacity and the number
* of concurrent transports come from the Internet exchange (D.TRANSPORT): `links` = its level, each link carries
* `capacityPerLink`. The cargo leaves the POP now and is added to the target on arrival (anything above the target's
* Rack hall cap is lost). The trade stage calls `launchTransport` directly for the two legs of an accepted offer.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { ownedTown } = require('./build');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
// Validate + dispatch from an already settled, owned POP `from`. `toRow` is the target POP row. `extra` is stored on
// the movement (and its return leg) for later stages, e.g. { tradeId }. Returns the movement.
function launchTransport(ctx, from, toRow, cargo, extra) {
const { db, now } = ctx;
const plan = R.transportPlan(from, cargo, M.activeLinks(db, from.id), now);
if (!plan.ok) throw new GameError(plan.code, plan);
const world = loadWorld(db, from.worldId);
const dist = R.distance(from.x, from.y, toRow.x, toRow.y);
const clean = {};
for (const r of D.RESOURCES) if (cargo[r] > 0) clean[r] = cargo[r];
for (const r of D.RESOURCES) from.res[r] -= clean[r] || 0;
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', from.res.fiber, from.res.hardware, from.res.capital, from.id);
return M.insertMovement(ctx, {
worldId: from.worldId, ownerId: from.ownerId, type: 'transport', fromTownId: from.id, toTownId: toRow.id,
from: { x: from.x, y: from.y }, to: { x: toRow.x, y: toRow.y }, units: {}, cargo: clean,
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: Object.assign({}, extra || {}),
});
}
module.exports = function sendTransport(ctx0, { userId, fromTownId, toTownId, cargo }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const from = ownedTown(db, userId, fromTownId);
const to = db.get('SELECT * FROM towns WHERE id = ? AND world_id = ?', toTownId, from.worldId);
if (!to) throw new GameError('not_found', { what: 'town' });
if (to.id === from.id) throw new GameError('invalid_target', { reason: 'same_town' });
settle(db, from, now);
const mv = launchTransport(ctx, from, to, cargo || {});
const toOp = U.getOperator(db, to.owner_id);
if (toOp.id !== from.ownerId) {
const uid = U.userOfOperator(db, toOp.id);
if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: to.id, fromTownId: from.id, arriveAt: mv.arriveAt });
}
return { movementId: mv.id, type: 'transport', fromTownId: from.id, toTownId: to.id, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt };
};
module.exports.launchTransport = launchTransport;

37
server/commands/train.js Normal file
View file

@ -0,0 +1,37 @@
'use strict';
/*
* POST /towns/:id/train. Queue a batch of one unit type. Batches of the same training building run one after another
* (each is a `trainDone` event); different buildings train in parallel. Units appear when the batch finishes.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { settle, spend } = require('../state');
const { ownedTown } = require('./build');
// Pending batches of a training building, in due order: [{ id, dueAt, ...payload }].
function pendingBatches(db, townId, building) {
return db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", townId)
.map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload)))
.filter((b) => !building || b.building === building);
}
module.exports = function train(ctx, { userId, townId, unit, count }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
const def = R.unitDef(unit);
if (!def) throw new GameError('unknown_unit', { unit });
settle(db, town, now);
const queue = pendingBatches(db, town.id, def.building);
if (queue.length >= D.MILITARY.maxTrainQueue) throw new GameError('queue_full', { building: def.building, max: D.MILITARY.maxTrainQueue });
const tail = queue.length ? queue[queue.length - 1].dueAt : 0;
const plan = R.trainPlan(town, unit, count, now, tail);
if (!plan.ok) throw new GameError(plan.code, { unit, count, cost: plan.cost, missing: plan.missing });
spend(db, town, plan.cost);
const eventId = scheduler.enqueue({
worldId: town.worldId, townId: town.id, type: 'trainDone', dueAt: plan.dueAt,
payload: { unit, count, building: def.building, startAt: plan.startAt, cost: plan.cost, userId },
});
return { eventId, unit, count, building: def.building, startAt: plan.startAt, dueAt: plan.dueAt, cost: plan.cost };
};
module.exports.pendingBatches = pendingBatches;

View file

@ -0,0 +1,35 @@
'use strict';
/* POST /towns/:id/withdraw. Reinforcements standing in host POP :id go home. Either side may do it: the host owner
* sends them away, the units' owner calls them back. `units` defaults to the whole group. They travel home as a
* return movement and stop drawing the host's power right away. */
const { GameError } = require('../errors');
const { settle } = require('../state');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const M = require('../military/movements');
const P = require('../military/power');
module.exports = function withdrawStationed(ctx0, { userId, hostTownId, ownerTownId, units }) {
const ctx = ctxOf(ctx0);
const { db, now } = ctx;
const host = db.get('SELECT * FROM towns WHERE id = ?', hostTownId);
const owner = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId);
if (!host || !owner) throw new GameError('not_found', { what: 'town' });
const mine = (t) => !!db.get('SELECT 1 AS x FROM operators WHERE id = ? AND user_id = ?', t.owner_id, userId);
if (!mine(host) && !mine(owner)) throw new GameError('not_found', { what: 'town' });
const have = U.stationedOf(db, host.id, owner.id);
let take = units && Object.keys(units).length ? U.cleanUnits(units) : have;
take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0));
if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' });
for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] });
const hostTown = require('../state').loadTown(db, host.id);
settle(db, hostTown, now); // the host's draw changes
U.removeStationed(db, host.id, owner.id, take);
P.reschedule(ctx, host.id, now);
const mv = M.launchReturn(ctx, { worldId: host.world_id, ownerId: owner.owner_id, fromTownId: host.id, at: { x: host.x, y: host.y }, to: owner, units: take, cargo: {}, extra: { withdrawn: true } });
if (!mine(owner)) {
const uid = U.userOfOperator(db, owner.owner_id);
if (uid) ctx.notify(uid, host.world_id, 'reinforcements_sent_home', { hostTownId: host.id, ownerTownId: owner.id, units: take });
}
return { movementId: mv.id, units: take, arriveAt: mv.arriveAt };
};