Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
339 lines
20 KiB
JavaScript
339 lines
20 KiB
JavaScript
'use strict';
|
||
/*
|
||
* The send dialog: App.openSend({ x, y, fromTownId, type }). Opened from a map tile, the POP screen, the units screen and the
|
||
* movements screen. It looks the target up (GET /map/tile), offers the movement types that can work, lets you pick units
|
||
* (or cargo, or the wild slots of a new POP), previews latency and arrival from rules.js and sends POST /movements. The
|
||
* server re-validates everything; this dialog only avoids obviously doomed sends and explains the greyed-out ones.
|
||
* An Idempotency intent is generated per opened dialog (and again after a successful send), so a retried tap cannot send twice.
|
||
*/
|
||
(function () {
|
||
const { h, clear, icon, toast, openSheet } = UI;
|
||
const R = UpstreamRules;
|
||
const D = UpstreamData;
|
||
const Mil = UpstreamMil;
|
||
const mil = () => App.mil;
|
||
const num = (n) => App.fmt.num(n);
|
||
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
||
|
||
App.openSend = function openSend(opts) {
|
||
opts = opts || {};
|
||
const st = {
|
||
x: Number.isInteger(opts.x) ? opts.x : null, y: Number.isInteger(opts.y) ? opts.y : null,
|
||
tile: null, tileErr: null, fromId: null, from: null, type: null, units: {}, cargo: {}, target: '',
|
||
wild: D.START.wild.slice(), endProtection: false, busy: false, nonce: nonce(), loadSeq: 0, tileSeq: 0, options: [],
|
||
};
|
||
const own = App.state.towns;
|
||
st.fromId = own.some((t) => t.id === opts.fromTownId) ? opts.fromTownId : (App.state.townId || (own[0] && own[0].id));
|
||
if (!st.fromId) { toast(App.t('pop.noTown'), 'error'); return; }
|
||
|
||
const body = h('div', { class: 'detail send' });
|
||
let offTick = null;
|
||
const ctl = openSheet({ title: App.t('send.title'), icon: 'target', closeLabel: App.t('common.close'), body, onClose: () => { if (offTick) offTick(); } });
|
||
|
||
const secTarget = h('div', { class: 'send-sec' });
|
||
const secFrom = h('div', { class: 'send-sec' });
|
||
const secType = h('div', { class: 'send-sec' });
|
||
const secUnits = h('div', { class: 'send-sec' });
|
||
const secPreview = h('div', { class: 'send-sec' });
|
||
const secWarn = h('div', { class: 'send-sec' });
|
||
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go() }, icon('target'), h('span', { text: App.t('send.go') }));
|
||
body.appendChild(secTarget); body.appendChild(secFrom); body.appendChild(secType); body.appendChild(secUnits); body.appendChild(secPreview); body.appendChild(secWarn);
|
||
body.appendChild(h('div', { class: 'send-foot' }, errEl, submit));
|
||
|
||
const fromTown = () => own.find((t) => t.id === st.fromId);
|
||
const home = () => (st.from ? st.from.td.military.units.home : {});
|
||
const op = () => App.state.operator;
|
||
|
||
// ------------------------------------------------------------------ data
|
||
async function loadFrom() {
|
||
const seq = ++st.loadSeq;
|
||
let r;
|
||
try {
|
||
if (st.fromId === App.state.townId && App.state.townData && App.state.townData.military) r = { td: App.state.townData, rt: App.rulesTown(), at: App.fetchedServerTime };
|
||
else { const x = await mil().loadTown(st.fromId); r = { td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime), at: x.serverTime }; }
|
||
} catch (e) { if (seq === st.loadSeq) showErr(App.errMsg(e)); return; }
|
||
if (seq !== st.loadSeq) return;
|
||
st.from = r;
|
||
afterData();
|
||
}
|
||
|
||
async function loadTile() {
|
||
if (st.x === null || st.y === null) { st.tile = null; return; }
|
||
const seq = ++st.tileSeq;
|
||
st.tile = null; st.tileErr = null;
|
||
drawTarget();
|
||
try {
|
||
const t = await App.api.get('/map/tile', { x: st.x, y: st.y });
|
||
if (seq !== st.tileSeq) return;
|
||
st.tile = t;
|
||
} catch (e) {
|
||
if (seq !== st.tileSeq) return;
|
||
st.tileErr = e.code === 'not_found' ? App.t('tile.void') : App.errMsg(e);
|
||
}
|
||
afterData();
|
||
}
|
||
|
||
function afterData() {
|
||
drawTarget();
|
||
drawFrom();
|
||
if (!st.tile || !st.from) { drawTypes(); return; }
|
||
computeOptions();
|
||
drawTypes();
|
||
}
|
||
|
||
function computeOptions() {
|
||
const m = st.from.td.military;
|
||
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0 });
|
||
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
|
||
const first = st.options.find((o) => o.ok);
|
||
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
|
||
}
|
||
|
||
function setType(type, keep) {
|
||
if (!keep && type === st.type) return;
|
||
st.type = type;
|
||
st.units = type ? Mil.defaultUnits(type, home()) : {};
|
||
st.cargo = {}; st.target = ''; st.endProtection = false;
|
||
showErr('');
|
||
drawTypes(); drawUnits(); refresh();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ sections
|
||
function drawTarget() {
|
||
clear(secTarget);
|
||
const t = st.tile;
|
||
const xin = h('input', { type: 'number', inputmode: 'numeric', value: st.x === null ? '' : String(st.x), class: 'mil-num', 'aria-label': 'x', placeholder: 'x' });
|
||
const yin = h('input', { type: 'number', inputmode: 'numeric', value: st.y === null ? '' : String(st.y), class: 'mil-num', 'aria-label': 'y', placeholder: 'y' });
|
||
const lookup = () => {
|
||
const x = Math.round(Number(xin.value)), y = Math.round(Number(yin.value));
|
||
if (xin.value === '' || yin.value === '' || !Number.isFinite(x) || !Number.isFinite(y)) return;
|
||
st.x = x; st.y = y; st.type = null; loadTile();
|
||
};
|
||
secTarget.appendChild(h('h3', { class: 'sub', text: App.t('send.target') }));
|
||
secTarget.appendChild(h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin,
|
||
h('button', { class: 'btn small', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))));
|
||
if (!t) {
|
||
secTarget.appendChild(h('div', { class: 'chips' }, own.map((o) => h('button', { class: 'chip-btn', type: 'button', onclick: () => { st.x = o.x; st.y = o.y; st.type = null; loadTile(); } }, o.name))));
|
||
}
|
||
if (st.tileErr) { secTarget.appendChild(h('p', { class: 'reason', text: st.tileErr })); return; }
|
||
if (st.x !== null && !t) { secTarget.appendChild(h('p', { class: 'dimmer', text: App.t('common.loading') })); return; }
|
||
if (!t) return;
|
||
const pills = [h('span', { class: 'pill', text: App.t('tile.' + t.type) })];
|
||
if (t.town) {
|
||
if (t.town.mine) pills.push(h('span', { class: 'pill accent', text: App.t('map.info.yours') }));
|
||
if (t.town.isCapital) pills.push(h('span', { class: 'pill', text: App.t('map.info.capital') }));
|
||
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
|
||
}
|
||
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
|
||
secTarget.appendChild(h('div', { class: 'send-target' },
|
||
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : App.t('tile.' + t.type) }), mil().coordLink(t.x, t.y)),
|
||
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
|
||
h('div', { class: 'pill-row' }, pills)));
|
||
}
|
||
|
||
function drawFrom() {
|
||
clear(secFrom);
|
||
if (own.length < 2) return;
|
||
secFrom.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
|
||
h('select', { onchange: (e) => { st.fromId = Number(e.target.value); st.from = null; st.type = null; st.units = {}; drawUnits(); drawTypes(); loadFrom(); } },
|
||
own.map((o) => h('option', { value: o.id, selected: o.id === st.fromId, text: o.name })))));
|
||
}
|
||
|
||
function reasonText(o) {
|
||
const r = o.reason || '';
|
||
if (r.indexOf('settle:') === 0) {
|
||
const code = r.slice(7), s = st.tile && st.tile.settle ? st.tile.settle : {};
|
||
if (code === 'footprint_too_low') return App.t('send.reason.footprint', { have: num(s.footprint), need: num(s.footprintNeeded) });
|
||
if (code === 'out_of_range') return App.t('send.reason.range', { n: s.maxDistance || D.EXPANSION.maxDistance });
|
||
return App.t('send.reason.cannotSettle');
|
||
}
|
||
return App.t('send.reason.' + r);
|
||
}
|
||
|
||
function drawTypes() {
|
||
clear(secType);
|
||
if (!st.tile || !st.from) return;
|
||
if (!st.options.length) { secType.appendChild(h('p', { class: 'empty', text: App.t('send.nothing') })); return; }
|
||
secType.appendChild(h('h3', { class: 'sub', text: App.t('send.what') }));
|
||
secType.appendChild(h('div', { class: 'seg wrap-seg', role: 'group', 'aria-label': App.t('send.what') }, st.options.map((o) =>
|
||
h('button', { class: 'seg-btn', type: 'button', disabled: !o.ok, 'aria-pressed': String(o.type === st.type), onclick: () => setType(o.type) }, icon(Mil.TYPE_ICON[o.type]), h('span', { text: mil().typeLabel(o.type) })))));
|
||
const off = st.options.filter((o) => !o.ok);
|
||
if (off.length) secType.appendChild(h('ul', { class: 'send-why' }, off.map((o) => h('li', { class: 'row-sub wrap', text: mil().typeLabel(o.type) + ': ' + reasonText(o) }))));
|
||
}
|
||
|
||
function pickRow(label, have, cur, onChange, sub) {
|
||
const range = h('input', { type: 'range', min: '0', max: String(have), step: '1', value: String(cur), 'aria-label': label });
|
||
const numIn = h('input', { type: 'number', inputmode: 'numeric', min: '0', max: String(have), value: String(cur), class: 'mil-num', 'aria-label': label });
|
||
const set = (v) => { v = Math.max(0, Math.min(have, Math.floor(Number(v)) || 0)); range.value = String(v); numIn.value = String(v); onChange(v); };
|
||
range.addEventListener('input', () => set(range.value));
|
||
numIn.addEventListener('input', () => set(numIn.value));
|
||
return h('div', { class: 'mil-pick' },
|
||
h('div', { class: 'row' }, h('span', null, h('b', { text: label }), h('span', { class: 'dimmer', text: ' / ' + num(have) })), sub || null),
|
||
h('div', { class: 'pick-ctl' },
|
||
h('button', { class: 'btn small', type: 'button', 'aria-label': '-1', onclick: () => set(Number(numIn.value) - 1) }, '−'),
|
||
range,
|
||
h('button', { class: 'btn small', type: 'button', 'aria-label': '+1', onclick: () => set(Number(numIn.value) + 1) }, '+'),
|
||
numIn,
|
||
h('button', { class: 'btn small', type: 'button', onclick: () => set(have) }, App.t('send.all'))));
|
||
}
|
||
|
||
function drawUnits() {
|
||
clear(secUnits);
|
||
const type = st.type;
|
||
if (!type || !st.from) return;
|
||
const opt = st.options.find((o) => o.type === type);
|
||
if (!opt || !opt.ok) return; // greyed out: the reason is shown with the type picker
|
||
const h0 = home();
|
||
if (type === 'settle') {
|
||
const s = st.tile.settle || {};
|
||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.settle.title') }));
|
||
secUnits.appendChild(h('p', { class: 'preview', text: App.t('send.settle.crews', { n: D.EXPANSION.crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) }));
|
||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.settle.footprint', { have: num(s.footprint), need: num(s.footprintNeeded), n: s.maxDistance || D.EXPANSION.maxDistance }) }));
|
||
for (let i = 0; i < D.WILD_SLOTS; i++) {
|
||
secUnits.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.settle.wild', { n: i + 1 }) }),
|
||
h('select', { onchange: (e) => { st.wild[i] = e.target.value; } },
|
||
D.FIELD_TYPES.map((ft) => h('option', { value: ft, selected: st.wild[i] === ft, text: App.buildingName(ft) + ' (' + App.resName(D.FIELD_PRODUCES[ft]) + ')' })))));
|
||
}
|
||
return;
|
||
}
|
||
if (type === 'transport') {
|
||
const m = st.from.td.military;
|
||
const cur = R.resourcesAt(st.from.rt, App.now()).amounts;
|
||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.cargo') }));
|
||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.cargo.cap', { n: num(m.transport.capacityPerLink), free: Math.max(0, m.transport.links - m.transport.active), links: m.transport.links }) }));
|
||
for (const r of D.RESOURCES) {
|
||
const have = Math.floor(cur[r] || 0);
|
||
secUnits.appendChild(pickRow(App.resName(r), have, st.cargo[r] || 0, (v) => { if (v > 0) st.cargo[r] = v; else delete st.cargo[r]; refresh(); }));
|
||
}
|
||
return;
|
||
}
|
||
const rows = Mil.unitsForType(type, h0);
|
||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.units') }));
|
||
if (!rows.length) { secUnits.appendChild(h('p', { class: 'empty', text: App.t('send.reason.no_units') })); return; }
|
||
for (const r of rows) {
|
||
const def = D.UNITS[r.unit];
|
||
secUnits.appendChild(pickRow(mil().unitName(r.unit), r.have, st.units[r.unit] || 0, (v) => { if (v > 0) st.units[r.unit] = v; else delete st.units[r.unit]; refresh(); },
|
||
h('span', { class: 'row-sub', text: def.speed + ' ' + App.t('send.tilesPerHour') })));
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ preview, warnings, button state
|
||
function ready() {
|
||
if (!st.tile || !st.from || !st.type) return { ok: false, why: '' };
|
||
const o = st.options.find((x) => x.type === st.type);
|
||
if (!o || !o.ok) return { ok: false, why: '' };
|
||
const m = st.from.td.military;
|
||
if (!m.units.online) return { ok: false, why: App.t('err.units_offline') };
|
||
if (st.type === 'transport') {
|
||
const total = Object.keys(st.cargo).reduce((s, k) => s + st.cargo[k], 0);
|
||
if (total < 1) return { ok: false, why: '' };
|
||
if (total > m.transport.capacityPerLink) return { ok: false, why: App.t('err.capacity_exceeded') };
|
||
} else {
|
||
const sel = Mil.cleanSelection(st.units, home());
|
||
if (Mil.sumUnits(sel) < 1) return { ok: false, why: '' };
|
||
if (st.type === 'takeover' && !(sel[D.EXPANSION.conquestUnit] > 0)) return { ok: false, why: App.t('send.reason.needs_ma_team') };
|
||
const chk = R.checkUnitsForType(st.type, sel);
|
||
if (chk) return { ok: false, why: '' };
|
||
}
|
||
if (needsProtectionConfirm() && !st.endProtection) return { ok: false, why: App.t('send.protection.need') };
|
||
return { ok: true, why: '' };
|
||
}
|
||
|
||
const needsProtectionConfirm = () => Mil.isHostile(st.type) && op() && op().protectionUntil > App.now();
|
||
|
||
function refresh() {
|
||
drawPreview();
|
||
drawWarn();
|
||
const r = ready();
|
||
submit.disabled = !r.ok || st.busy;
|
||
}
|
||
|
||
function drawPreview() {
|
||
clear(secPreview);
|
||
if (!st.tile || !st.from || !st.type) return;
|
||
const from = fromTown();
|
||
if (!from) return;
|
||
const units = st.type === 'transport' ? {} : Mil.cleanSelection(st.units, home());
|
||
const hasSel = st.type === 'transport' ? Object.keys(st.cargo).length > 0 : Mil.sumUnits(units) > 0;
|
||
if (!hasSel) { secPreview.appendChild(h('p', { class: 'dimmer', text: App.t('send.pickSome') })); return; }
|
||
const p = Mil.preview(st.type, from, { x: st.tile.x, y: st.tile.y }, units, st.cargo, App.state.world.speed);
|
||
secPreview.appendChild(h('div', { class: 'send-preview' },
|
||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.distance') }), h('span', { class: 'v mono', text: App.fmt.dec(p.dist) + ' ' + App.t('common.tiles') })),
|
||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.latency') }), h('span', { class: 'v mono', text: App.fmt.dur(p.ms) })),
|
||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.arrives') }), h('span', { class: 'v mono', text: mil().clockTime(App.now() + p.ms) })),
|
||
p.slowest ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.slowest') }), h('span', { class: 'v mono', text: p.slowest + ' ' + App.t('send.tilesPerHour') })) : null,
|
||
(st.type === 'raid' || st.type === 'attack' || st.type === 'takeover') && p.carry > 0 ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.carry') }), h('span', { class: 'v mono', text: num(p.carry) })) : null));
|
||
}
|
||
|
||
function drawWarn() {
|
||
clear(secWarn);
|
||
if (!st.tile || !st.from || !st.type) return;
|
||
const type = st.type;
|
||
const items = [];
|
||
if (needsProtectionConfirm()) {
|
||
const cb = h('input', { type: 'checkbox', checked: st.endProtection, onchange: (e) => { st.endProtection = e.target.checked; refresh(); } });
|
||
items.push(h('label', { class: 'warn-check' }, cb, h('span', null, h('b', { text: App.t('send.protection.title') }), ' ', App.t('send.protection.body', { t: mil().dayTime(op().protectionUntil) }))));
|
||
}
|
||
if ((type === 'attack' || type === 'takeover') && (st.units.exploit_kit || 0) > 0) {
|
||
items.push(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.siege') }),
|
||
h('select', { onchange: (e) => { st.target = e.target.value; } },
|
||
h('option', { value: '', text: App.t('send.siege.none') }),
|
||
Mil.siegeTargets().map((k) => h('option', { value: k, selected: st.target === k, text: App.buildingName(k) }))),
|
||
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
|
||
}
|
||
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
|
||
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
|
||
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
|
||
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
|
||
if (Mil.isHostile(type) && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.hostile.hint') }));
|
||
const r = ready();
|
||
if (r.why) items.push(h('p', { class: 'reason', text: r.why }));
|
||
secWarn.appendChild(h('div', { class: 'send-warn' }, items));
|
||
}
|
||
|
||
function showErr(msg) { errEl.textContent = msg || ''; errEl.hidden = !msg; }
|
||
|
||
// ------------------------------------------------------------------ send
|
||
async function go() {
|
||
const r = ready();
|
||
if (!r.ok || st.busy) return;
|
||
st.busy = true; submit.disabled = true; showErr('');
|
||
const body = { fromTownId: st.fromId, type: st.type };
|
||
if (st.tile.town) body.toTownId = st.tile.town.id; else { body.x = st.tile.x; body.y = st.tile.y; }
|
||
if (st.type === 'transport') body.cargo = Object.assign({}, st.cargo);
|
||
else body.units = Mil.cleanSelection(st.units, home());
|
||
if (st.type === 'settle') body.wild = st.wild.slice(0, D.WILD_SLOTS);
|
||
if ((st.type === 'attack' || st.type === 'takeover') && st.target && (body.units.exploit_kit || 0) > 0) body.target = st.target;
|
||
if (needsProtectionConfirm() && st.endProtection) body.confirmEndProtection = true;
|
||
try {
|
||
const res = await App.api.post('/movements', body, { intent: 'send:' + st.fromId + ':' + st.nonce });
|
||
st.nonce = nonce();
|
||
toast(App.t('send.sent', { type: mil().typeLabel(res.type), t: App.fmt.dur(res.arriveAt - res.departAt) }), 'ok');
|
||
ctl.close();
|
||
App.refreshMovements().catch(() => {});
|
||
App.refreshTown().catch(() => {});
|
||
if (App.state.operator && res.protectionEnded) App.state.operator.protectionUntil = 0;
|
||
} catch (e) {
|
||
st.busy = false;
|
||
let msg = App.errMsg(e);
|
||
const reason = e.details && e.details.reason;
|
||
if (e.code === 'invalid_target' && reason && UpstreamI18n.strings.en['send.invalid.' + reason]) msg += ' ' + App.t('send.invalid.' + reason);
|
||
showErr(msg);
|
||
if (e.code === 'not_enough_units' || e.code === 'units_offline' || e.code === 'conflict') { st.from = null; loadFrom(); }
|
||
refresh();
|
||
}
|
||
}
|
||
|
||
// keep the arrival clock and affordability honest while the dialog stays open
|
||
let lastSlot = 0;
|
||
offTick = App.onTick((now) => {
|
||
const slot = Math.floor(now / 15000);
|
||
if (slot !== lastSlot && !st.busy && st.from && st.tile && st.type) { lastSlot = slot; drawPreview(); }
|
||
});
|
||
drawTarget(); drawFrom();
|
||
loadFrom();
|
||
if (st.x !== null) loadTile();
|
||
refresh();
|
||
};
|
||
}());
|