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:
parent
b56b13880e
commit
249818a7aa
111 changed files with 17472 additions and 13 deletions
21
deploy/upstream-admin
Executable file
21
deploy/upstream-admin
Executable file
|
|
@ -0,0 +1,21 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# Run tools/admin.js as the service user, against the service's database. Install:
|
||||||
|
# install -m 0755 /opt/upstream/deploy/upstream-admin /usr/local/bin/upstream-admin
|
||||||
|
# upstream-admin help
|
||||||
|
# Running admin.js as root would create the database's -wal/-shm files owned by root and the game could no longer open
|
||||||
|
# the database, hence the runuser. DB_PATH comes from the environment, else /etc/upstream/upstream.env, else the default.
|
||||||
|
set -eu
|
||||||
|
APP_DIR=${UPSTREAM_DIR:-/opt/upstream}
|
||||||
|
ENV_FILE=${UPSTREAM_ENV_FILE:-/etc/upstream/upstream.env}
|
||||||
|
if [ -z "${DB_PATH:-}" ] && [ -r "$ENV_FILE" ]; then
|
||||||
|
DB_PATH=$(sed -n 's/^[[:space:]]*DB_PATH=//p' "$ENV_FILE" | tail -n 1 | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/")
|
||||||
|
fi
|
||||||
|
DB_PATH=${DB_PATH:-/var/lib/upstream/game.db}
|
||||||
|
if [ "$(id -u)" = 0 ]; then
|
||||||
|
exec runuser -u upstream -- env DB_PATH="$DB_PATH" node "$APP_DIR/tools/admin.js" "$@"
|
||||||
|
elif [ "$(id -un)" = upstream ]; then
|
||||||
|
exec env DB_PATH="$DB_PATH" node "$APP_DIR/tools/admin.js" "$@"
|
||||||
|
else
|
||||||
|
echo "upstream-admin: run as root (it switches to the upstream user) or as the upstream user" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
40
deploy/upstream-backup.service
Normal file
40
deploy/upstream-backup.service
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# One database snapshot (VACUUM INTO, verified, dated file name, old ones pruned). Started by upstream-backup.timer,
|
||||||
|
# or by hand: systemctl start upstream-backup. Safe while the game server is running (SQLite WAL: readers do not block
|
||||||
|
# the writer). See docs/DEPLOY.md, "Backups".
|
||||||
|
#
|
||||||
|
# install -m 0644 deploy/upstream-backup.service deploy/upstream-backup.timer /etc/systemd/system/
|
||||||
|
# systemctl daemon-reload && systemctl enable --now upstream-backup.timer
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Upstream - database snapshot
|
||||||
|
Documentation=file:///opt/upstream/docs/DEPLOY.md
|
||||||
|
# Not started from the main unit's dependency graph: a backup must also work while the game is stopped.
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=upstream
|
||||||
|
Group=upstream
|
||||||
|
WorkingDirectory=/opt/upstream
|
||||||
|
# Same state directory as upstream.service; snapshots go to /var/lib/upstream/backups (mode 0700).
|
||||||
|
StateDirectory=upstream
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
# Same override file, so DB_PATH follows the main service if you changed it there.
|
||||||
|
EnvironmentFile=-/etc/upstream/upstream.env
|
||||||
|
Environment=DB_PATH=/var/lib/upstream/game.db
|
||||||
|
# Keep the newest 14 snapshots (daily timer = two weeks). Edit here, or `systemctl edit upstream-backup`.
|
||||||
|
# --keep-days D works too; with both, a snapshot survives if either rule keeps it.
|
||||||
|
ExecStart=/usr/bin/env node /opt/upstream/tools/admin.js backup /var/lib/upstream/backups --keep 14
|
||||||
|
# A failed snapshot (verification failed, disk full) must be visible: the unit fails and journalctl shows why.
|
||||||
|
TimeoutStartSec=15min
|
||||||
|
Nice=10
|
||||||
|
IOSchedulingClass=idle
|
||||||
|
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
RestrictAddressFamilies=AF_UNIX
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
UMask=0077
|
||||||
14
deploy/upstream-backup.timer
Normal file
14
deploy/upstream-backup.timer
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
# Daily snapshot at 04:15 (+ up to 10 min jitter). Persistent: a run missed while the container was off happens at
|
||||||
|
# the next boot. Every 6 hours instead: OnCalendar=*-*-* 00/6:15:00 and raise --keep in upstream-backup.service.
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Upstream - daily database snapshot
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* 04:15:00
|
||||||
|
RandomizedDelaySec=10min
|
||||||
|
Persistent=true
|
||||||
|
Unit=upstream-backup.service
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
94
deploy/upstream.service
Normal file
94
deploy/upstream.service
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
# Upstream systemd unit (Debian 13 LXC; see docs/DEPLOY.md).
|
||||||
|
#
|
||||||
|
# install -m 0644 deploy/upstream.service /etc/systemd/system/upstream.service
|
||||||
|
# systemctl daemon-reload && systemctl enable --now upstream
|
||||||
|
# journalctl -u upstream -f
|
||||||
|
#
|
||||||
|
# Expects the app in /opt/upstream (server/, public/, node_modules/) and a Node >= 22.13 on the PATH (the Debian 13
|
||||||
|
# package is Node 20 and is too old for node:sqlite: see docs/DEPLOY.md section 1). The database lives in
|
||||||
|
# /var/lib/upstream (systemd creates it, owned by the service user, from StateDirectory=).
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=Upstream - persistent network-operator strategy game (Node server, SQLite)
|
||||||
|
Documentation=file:///opt/upstream/docs/DEPLOY.md
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=upstream
|
||||||
|
Group=upstream
|
||||||
|
WorkingDirectory=/opt/upstream
|
||||||
|
# /usr/bin/env finds node on systemd's default PATH: /usr/local/bin (official tarball) before /usr/bin (NodeSource).
|
||||||
|
ExecStart=/usr/bin/env node /opt/upstream/server/index.js
|
||||||
|
|
||||||
|
# ---- state --------------------------------------------------------------------------------------------------
|
||||||
|
# Creates /var/lib/upstream owned by the service user (mode 0700) before start. This is the ONLY place the game
|
||||||
|
# writes. Do not put the database in /opt/upstream.
|
||||||
|
StateDirectory=upstream
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
# Optional file for settings and secrets (SIGNUP_CODE). Values in it override the Environment= lines below.
|
||||||
|
# Keep it root:upstream 0640. The leading "-" means: fine if it does not exist.
|
||||||
|
EnvironmentFile=-/etc/upstream/upstream.env
|
||||||
|
|
||||||
|
# ---- configuration (see docs/DEPLOY.md, "Configuration") ----------------------------------------------------
|
||||||
|
Environment=NODE_ENV=production
|
||||||
|
Environment=PORT=8080
|
||||||
|
# "::" = one dual-stack socket for IPv4 + IPv6 (falls back to 0.0.0.0 if the kernel has no IPv6).
|
||||||
|
Environment=HOST=::
|
||||||
|
Environment=DB_PATH=/var/lib/upstream/game.db
|
||||||
|
# auto: believe X-Forwarded-For / X-Forwarded-Host only from loopback / private-range peers (your proxy).
|
||||||
|
Environment=TRUST_PROXY=auto
|
||||||
|
# Only when the proxy reaches this server from a NON-private address (global IPv6, Tailscale / CGNAT 100.64.0.0/10):
|
||||||
|
#Environment=TRUSTED_PROXIES=100.64.0.0/10,2001:db8::6
|
||||||
|
# Only when the proxy rewrites the Host header or you serve several public names (include the port if not 80/443):
|
||||||
|
#Environment=ALLOWED_ORIGINS=https://upstream.example.com
|
||||||
|
#Environment=MAX_CONN_PER_IP=40
|
||||||
|
# World settings: only read when the database has NO world yet (first boot). Change them later with
|
||||||
|
# `upstream-admin create-world` / `reset-world`, not here.
|
||||||
|
#Environment=WORLD_SPEED=1
|
||||||
|
#Environment=WORLD_RADIUS=50
|
||||||
|
#Environment=WORLD_NAME=World 1
|
||||||
|
# Invite code for signup. Empty/unset = open signup. Put the real value in /etc/upstream/upstream.env, not here.
|
||||||
|
#Environment=SIGNUP_CODE=
|
||||||
|
|
||||||
|
# ---- lifecycle ----------------------------------------------------------------------------------------------
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=2
|
||||||
|
# SIGTERM closes the listener and the database and exits 0 within about a second; SIGKILL after 15 s as a backstop.
|
||||||
|
# (A SIGKILL is still safe for SQLite: the WAL is replayed on the next start and overdue events are caught up.)
|
||||||
|
TimeoutStopSec=15
|
||||||
|
|
||||||
|
# ---- hardening that works in any container (no mount namespaces needed) ------------------------------------
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
# AF_NETLINK: Node's os.networkInterfaces() (start-up banner) and glibc's resolver use it.
|
||||||
|
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
# New files (the database, its -wal/-shm, snapshots) are readable by the service user only: they hold password hashes.
|
||||||
|
UMask=0077
|
||||||
|
# Do NOT add MemoryDenyWriteExecute=yes: V8's JIT needs writable+executable memory and Node would crash.
|
||||||
|
|
||||||
|
# ---- optional extra hardening: needs mount namespaces ------------------------------------------------------
|
||||||
|
# In an unprivileged Proxmox LXC these fail with "status=226/NAMESPACE" unless the container has the
|
||||||
|
# "Nesting" feature enabled (Proxmox: container > Options > Features > Nesting; then restart the CT).
|
||||||
|
# Unlike Netwall this app writes to disk, so ProtectSystem=strict needs the ReadWritePaths line next to it.
|
||||||
|
# (StateDirectory= already makes /var/lib/upstream writable under strict; ReadWritePaths is the explicit belt.)
|
||||||
|
#ProtectSystem=strict
|
||||||
|
#ReadWritePaths=/var/lib/upstream
|
||||||
|
#ProtectHome=yes
|
||||||
|
#PrivateTmp=yes
|
||||||
|
#PrivateDevices=yes
|
||||||
|
#ProtectKernelTunables=yes
|
||||||
|
#ProtectKernelModules=yes
|
||||||
|
#ProtectKernelLogs=yes
|
||||||
|
#ProtectControlGroups=yes
|
||||||
|
#ProtectClock=yes
|
||||||
|
#ProtectHostname=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
90
docs/API.md
90
docs/API.md
|
|
@ -27,4 +27,94 @@ REST JSON under `/api/v1/`. The machine-readable contract is `docs/openapi.json`
|
||||||
| `GET /map?x&y&r` | rural areas, incumbent sites, POPs in the viewport |
|
| `GET /map?x&y&r` | rural areas, incumbent sites, POPs in the viewport |
|
||||||
| `GET /notifications?after&limit` | durable notification feed (build done, ...) |
|
| `GET /notifications?after&limit` | durable notification feed (build done, ...) |
|
||||||
|
|
||||||
|
## Social (stage 5, no marketplace/transport yet)
|
||||||
|
|
||||||
|
`worldId` is optional everywhere a caller's operator is needed (default: their oldest operator). Most commands are
|
||||||
|
idempotent where that makes sense and answer `{ changed: false }` when there was nothing to do (leaving twice, kicking someone
|
||||||
|
already gone, accepting an invite twice). `forbidden` carries `details.need` (the missing permission).
|
||||||
|
|
||||||
|
**Alliances.** Roles `leader`, `diplomat`, `officer`, `member`; the permission table is `SOCIAL.permissions` in `data.js`
|
||||||
|
(`GET /alliances/mine` returns the caller's permissions). Founding and joining need a Peering office level >= 1 on one of the
|
||||||
|
operator's POPs (`peering_office_required`). Size cap: `10 + 2 * level` of the founder's best Peering office when founding, stored;
|
||||||
|
it is raised (never lowered) whenever a command runs that depends on it (invite, accept, transfer) if the current leader's best
|
||||||
|
office would give more; reads show the effective cap. One alliance per operator.
|
||||||
|
|
||||||
|
| Route | Purpose |
|
||||||
|
| ----- | ------- |
|
||||||
|
| `POST /alliances {name, tag}` | found (201); name 3-30 chars, tag 2-5 letters/digits, both unique per world, case-insensitive |
|
||||||
|
| `GET /alliances?q&after&limit`, `GET /alliances/mine`, `GET /alliances/:id` | directory (cursor: id), your alliance + role + permissions, public profile (size, leader, summed footprint, your relation) |
|
||||||
|
| `GET /alliances/:id/members` | members only: role, POP count, footprint, `lastOnline` (newest token use of the user, updated at most once a minute); bounded by the cap, so not paginated (`next` is always null) |
|
||||||
|
| `POST /alliances/:id/invite {operatorId \| name}`, `GET /alliances/:id/invites`, `DELETE /alliances/:id/invites/:inviteId` | invite (201; repeating returns the pending invite with 200), list sent, cancel. Invites expire after 7 days (real time) |
|
||||||
|
| `GET /alliance-invites`, `POST /alliance-invites/:id/accept`, `POST /alliance-invites/:id/decline` | the invitee's side |
|
||||||
|
| `POST /alliances/:id/leave`, `/kick {operatorId}`, `/role {operatorId, role}`, `/transfer {operatorId}`, `/disband` | leaving (the leader must transfer first, or is alone and disbands), kick (only members the actor outranks), set role (leader only), hand over leadership, disband |
|
||||||
|
| `GET/POST /alliances/:id/notes`, `POST/DELETE /alliances/:id/notes/:noteId` | pinned notes (max 10, 1000 chars, plain text) |
|
||||||
|
|
||||||
|
**Diplomacy.** States `war`, `neutral`, `nap`, `confed`. `POST /alliances/:id/diplomacy {targetId, state}` answers with
|
||||||
|
`result`: `applied` (declaring war from neutral takes effect at once), `proposed` (pacts, and peace out of war: the other alliance
|
||||||
|
must accept within 72 h, real time) or `scheduled` (cancelling a pact, or going to war out of one, takes 24 h / world speed:
|
||||||
|
`effectiveAt`, applied by the `diploChange` event). While a change is scheduled the old state holds and further changes between the
|
||||||
|
pair are `diplomacy_pending`; the alliance that started it can take it back. The move table is `SOCIAL.diplomacyMoves`.
|
||||||
|
|
||||||
|
| Route | Purpose |
|
||||||
|
| ----- | ------- |
|
||||||
|
| `GET /alliances/:id/diplomacy` | members only: relations (with scheduled change), incoming and outgoing open proposals |
|
||||||
|
| `POST /diplomacy/proposals/:proposalId/accept` / `.../decline`, `DELETE /diplomacy/proposals/:proposalId` | answer (receiving alliance) / withdraw (proposing alliance); all need `diplomacy` |
|
||||||
|
| `DELETE /alliances/:id/diplomacy/:otherId/pending` | revoke a scheduled cancel you started |
|
||||||
|
|
||||||
|
Notification types written: `alliance_invite`, `alliance_invite_declined`, `alliance_member_joined`, `alliance_member_left`,
|
||||||
|
`alliance_kicked`, `alliance_role`, `alliance_leader`, `alliance_disbanded`, `diplomacy_proposal`, `diplomacy_declined`,
|
||||||
|
`diplomacy_changed`, `diplomacy_cancel_pending`, `diplomacy_cancel_revoked`, `message`, `alliance_message`.
|
||||||
|
|
||||||
|
**Messages.** Plain text, 1-2000 characters; control characters, bidi overrides and invisible characters are stripped
|
||||||
|
(`server/text.js`) before anything is stored. Lists are newest first and the cursor is the last id of the previous page
|
||||||
|
(`?after=<next>` gives the next, older page). Sending is limited per sender by counting their recent messages (15 DMs / 10 min,
|
||||||
|
60 DMs / h, 20 alliance broadcasts / h, `SOCIAL.messageLimits`): `429 rate_limited` with `details.retryAfter`. Deleting removes only
|
||||||
|
your own copy. A recipient who blocked the sender gets nothing; the sender is not told (`recipients: 0`).
|
||||||
|
|
||||||
|
| Route | Purpose |
|
||||||
|
| ----- | ------- |
|
||||||
|
| `POST /messages {toOperatorId \| toName \| toAlliance, text}` | send (201) |
|
||||||
|
| `GET /messages/inbox?unread`, `/messages/outbox`, `/messages/thread/:operatorId`, `/messages/alliance` | lists; the inbox also returns `unread` |
|
||||||
|
| `GET /messages/:id`, `DELETE /messages/:id`, `POST /messages/read {ids \| all}` | one message, delete own copy, mark read |
|
||||||
|
| `GET/POST /messages/blocks`, `DELETE /messages/blocks/:operatorId` | block list (max 100) |
|
||||||
|
|
||||||
|
**Rankings.** `GET /rankings/operators` (footprint, `rules.footprintAt` over the operator's POPs), `/rankings/alliances` (sum over
|
||||||
|
members), `/rankings/battles?by=attack|defense|total` (from `operator_stats`, `available: false` and empty when that table does not
|
||||||
|
exist). The cursor is a rank offset (`next` = ranks already seen). Each response has `total` and `you` (the caller's own entry).
|
||||||
|
|
||||||
|
`GET /me` operators and `GET /map` town owners now carry `alliance: { id, tag, name } | null` next to `allianceId`.
|
||||||
|
|
||||||
|
## Military and expansion (stages 3-4)
|
||||||
|
|
||||||
|
Units are plain `{ unitId: count }` objects with the generic ids of `data.UNITS` (`port_scanner`, `soc_analyst`, `blue_team`,
|
||||||
|
`honeypot`, `script_crew`, `botnet`, `ddos_rig`, `exploit_kit`, `rollout_crew`, `ma_team`); names live in `i18n.js`. `GET /towns/:id`
|
||||||
|
now carries `town.military`: units at home (`online` flag, `offlineSince`), reinforcements standing here and away, the training queue,
|
||||||
|
what can be trained (cost, time, missing requirements), research levels and queue, transport links, and this POP's outgoing/incoming
|
||||||
|
movements. Nothing resolves when you send it: combat, loot and arrival happen in the event queue at the arrival time, and reports and
|
||||||
|
notifications (`incoming`, `report`, `train_done`, `research_done`, `movement_returned`, `transport_arrived`, `units_offline`,
|
||||||
|
`units_decommissioned`, `town_lost`, `town_gained`) tell you afterwards.
|
||||||
|
|
||||||
|
| Route | Purpose |
|
||||||
|
| ----- | ------- |
|
||||||
|
| `POST /towns/:id/train {unit, count}` | queue a batch (201). Batches of one training building (NOC / Ops lab / Rollout depot) run in order, buildings in parallel; queue limit 8 per building (`queue_full`) |
|
||||||
|
| `POST /towns/:id/research {unit, stat}` | +5% `attack` or `defence` per level for one unit type, one research at a time per POP, level n needs a Research lab of level n + 2 |
|
||||||
|
| `POST /movements {fromTownId, type, toTownId \| x,y, units, ...}` | send `scan`, `raid`, `attack`, `takeover`, `reinforce`, `settle` (201). `type: transport` carries `cargo: {fiber, hardware, capital}` (Internet exchange: level = concurrent transports, 500 each). Extra fields: `target` (building for exploit kits), `wild` (two field types for a new POP), `confirmEndProtection` |
|
||||||
|
| `GET /movements` | your active movements (full detail, `recallableUntil`) and incoming ones from others: origin and ETA only, `type: "unknown"` |
|
||||||
|
| `POST /movements/:id/recall` | turn an outbound movement around within the first 90 s (`recall_expired` after) |
|
||||||
|
| `POST /towns/:id/withdraw {ownerTownId, units?}` | reinforcements in this POP go home (host kicks them out, or their owner calls them back) |
|
||||||
|
| `GET /reports?after&limit&unread`, `GET /reports/:id`, `POST /reports/:id/read`, `POST /reports/read-all` | reports, **newest first**: `after` = id of the last report you have, the next page holds older ones. One shared row per battle, per-user read flag; kept 14 days |
|
||||||
|
| `GET /map/tile?x&y` | public facts about one tile for the send dialog: what is there, owner/protection, distance from each of your POPs, whether you could settle it (`settle.possible/code`) |
|
||||||
|
|
||||||
|
Rules the server enforces on `POST /movements` (error codes in `x-error-codes`): `not_enough_units`, `units_offline` (battery empty),
|
||||||
|
`invalid_target` (`details.reason`: own town, nothing there, pact partner, not allied, occupied tile ...), `target_protected` (beginner
|
||||||
|
protection still running at the arrival time; scans are allowed), `protection_active` (attacking from protected status needs
|
||||||
|
`confirmEndProtection: true` and ends your protection), `cannot_takeover` (last POP), `footprint_too_low` / `out_of_range` (settle and
|
||||||
|
takeover), `capacity_exceeded` / `no_transport_link` (transport). Pact partners (same alliance, NAP, confederation) cannot raid, attack
|
||||||
|
or take over each other; only the same alliance or a confederation may reinforce. The server re-checks target, protection and pact when
|
||||||
|
the movement arrives and bounces it (units come home, a `movement_failed` report says why) if something changed.
|
||||||
|
|
||||||
|
Report types: `raid`, `attack`, `takeover` (the same combat report: outcome, both sides' units and losses, attack/defence values,
|
||||||
|
firewall, loot, siege, takeover/loyalty), `scan` (attacker; intel when it succeeded), `scan_detected` (defender; attacker identity only
|
||||||
|
if the defender's scanners won), `incumbent`, `settle`, `reinforce`, `movement_failed`.
|
||||||
|
|
||||||
Later stages append their routes here and to the route table.
|
Later stages append their routes here and to the route table.
|
||||||
|
|
|
||||||
|
|
@ -33,3 +33,98 @@ committed file is stale, which satisfies "updated in the same commit as any rout
|
||||||
## D8 — Resource fields are slot-keyed
|
## D8 — Resource fields are slot-keyed
|
||||||
Buildings table key: `f1..f18` for resource fields (type fixed at founding, 4 per type + 2 wild), the building type for infrastructure.
|
Buildings table key: `f1..f18` for resource fields (type fixed at founding, 4 per type + 2 wild), the building type for infrastructure.
|
||||||
Build "slots": 1 concurrent build, 2 from Core router 10 (queue = pending `buildDone` events).
|
Build "slots": 1 concurrent build, 2 from Core router 10 (queue = pending `buildDone` events).
|
||||||
|
|
||||||
|
## S5-1 — Alliance size cap is stored, only ever raised
|
||||||
|
DESIGN says the Peering office level sets the size you can found. The cap is stored at founding (`10 + 2 * best level`). A lost or
|
||||||
|
downgraded building must never kick anyone, so the cap is monotonic: commands that depend on it (invite, accept, transfer) raise it if
|
||||||
|
the CURRENT leader's best office would give more; reads show `max(stored, formula)` without writing. The floor is therefore 10 even
|
||||||
|
for a leader without an office after a transfer. The office requirement (>= 1) is checked when founding and when accepting an invite,
|
||||||
|
not afterwards.
|
||||||
|
|
||||||
|
## S5-2 — Diplomacy move table is data, three kinds of change
|
||||||
|
`SOCIAL.diplomacyMoves` (data.js) says for each (from, to) whether it is `immediate`, a `proposal` or `delayed`. War from neutral is
|
||||||
|
immediate (no consent needed). Anything that leaves a pact (nap/confed -> neutral/war, confed -> nap) is `delayed`: 24 h / world speed
|
||||||
|
via a `diploChange` event, so you cannot betray a partner without warning. Pacts and peace need acceptance. While a delayed change is
|
||||||
|
pending the pair is locked (`diplomacy_pending`); only the starter can revoke. A pair at `neutral` with nothing pending has no row in
|
||||||
|
`alliance_relations`. Acceptance re-validates against the current state, because the relation may have moved since the proposal.
|
||||||
|
`war -> confed` is not allowed (go through a pact first).
|
||||||
|
|
||||||
|
## S5-3 — Membership lives in two tables, one writer
|
||||||
|
`operators.alliance_id` (from 001, cheap joins in /map, /me) and `alliance_members` (role, joined_at, one leader per alliance by a partial
|
||||||
|
unique index). `alliances.js` addMember/removeMember are the only writers. Alliance rows are hard-deleted on disband; messages keep a
|
||||||
|
`alliance_tag` snapshot and carry no foreign key to alliances so broadcasts survive.
|
||||||
|
|
||||||
|
## S5-4 — Last online comes from tokens
|
||||||
|
No new column: `lastOnline` = newest `tokens.last_used_at` of the member's user, which auth.js refreshes at most once a minute. So it
|
||||||
|
is accurate to about a minute and includes revoked tokens (a logout still counts as having been online).
|
||||||
|
|
||||||
|
## S5-5 — Message rate limit is DB-backed, not the in-memory Limiter
|
||||||
|
`server/http.js` Limiter keys on monotonic real time and forgets on restart; message limits are a product rule that should follow the
|
||||||
|
(fake) clock and survive restarts, so the sender's recent rows in `messages` are counted (`SOCIAL.messageLimits`, indexed by
|
||||||
|
`messages_sender`). The per-token/IP limiters still apply on top.
|
||||||
|
|
||||||
|
## S5-6 — Messages: per-recipient rows, sanitising on write
|
||||||
|
One `messages` row plus one `message_recipients` row per recipient (broadcast fan-out at send time: members who join later do not see
|
||||||
|
old broadcasts; members who leave keep what they received). Read/delete state is per recipient; the sender's copy is hidden with
|
||||||
|
`sender_deleted_at`; the row is purged when nobody has a copy. A blocked sender is silently not delivered to (no row), so blocking does
|
||||||
|
not leak. Text is sanitised once on write (`server/text.js`): C0/C1 controls, bidi overrides and isolates, zero-width and invisible
|
||||||
|
tag characters are stripped, NFC, `\r\n` -> `\n`; ZWJ/ZWNJ are kept for emoji. Clients render with `textContent` only.
|
||||||
|
|
||||||
|
## S5-7 — Rankings are computed per request, no cache
|
||||||
|
Footprint for a whole world comes from two queries (towns, buildings) and `rules.footprintAt`; fine for the expected 50-300 operators.
|
||||||
|
If it ever shows up in a profile, cache per (world, minute). Cursor is a rank offset because rankings are a computed snapshot, not rows.
|
||||||
|
|
||||||
|
## S5-8 — Route params and list order
|
||||||
|
`inviteId`, `noteId`, `proposalId`, `otherId`, `operatorId` were added to `INT_PARAMS` in http.js. Lists that are newest-first (messages)
|
||||||
|
use the last id as the `after` cursor and return older items; this is the one place `after` does not mean "newer than".
|
||||||
|
|
||||||
|
## S3-1 — Online/offline is computed lazily; `powerCheck` only does the side effects
|
||||||
|
Units are offline while the battery is empty and net power is negative. That is derived from the lazy battery value (`power.online`) at
|
||||||
|
the moment it matters (sending, combat, the town view), never from an event having run. The `powerCheck` event (one pending per POP,
|
||||||
|
re-armed by `power.reschedule` after anything that changes unit draw or building levels, including `buildDone`) only writes the
|
||||||
|
"units offline" notification and does the decommission after 24 h / world speed. Offline is all-or-nothing per POP (the contract of
|
||||||
|
`rules.unitsOnline`); the decommission then removes the most expensive units (home first, then reinforcements) until the draw fits the
|
||||||
|
output, not everything. Offline units are neither counted in defence nor hurt by a raid, but a full attack lost by the defender still
|
||||||
|
wipes them. Reinforcements draw from the host (`state.unitDraw` reads `stationed`); units in transit draw from nobody.
|
||||||
|
|
||||||
|
## S3-2 — Research is per POP, speed bonus per operator
|
||||||
|
`town_research(town_id, unit, stat, level)`; level n needs a Research lab of level n + 2, one research at a time per POP. An attack uses a
|
||||||
|
snapshot of the origin POP's research taken at departure (`movements.extra.research`); defenders use the research of the POP each group
|
||||||
|
belongs to. Incumbent sites: +10% research speed per distinct site taken (cap +50%), and a one-time +2500 Hardware per site and operator.
|
||||||
|
Taking a site does not remove it: it stays a static fortress for everybody else.
|
||||||
|
|
||||||
|
## S3-3 — One report row, many recipients; cleanup armed at the earliest expiry
|
||||||
|
A battle is one `reports` row shared through `report_recipients(report_id, user_id, role, read_at)`, so both sides see the same data (a
|
||||||
|
scan is two separate rows: intel for the scanner, "a scan happened" for the target, with the scanner's identity only if the target's
|
||||||
|
scanners won). `reportCleanup` is armed at the earliest `expires_at` (14 days, real time, not divided by world speed) and re-arms itself
|
||||||
|
only while reports remain: at most one pending cleanup per world, none on a quiet world.
|
||||||
|
|
||||||
|
## S3-4 — Arrival re-validates everything and bounces
|
||||||
|
A movement is validated when it is sent and again when it arrives (the target may have changed owner, got protection, joined a pact, the
|
||||||
|
tile may have been taken). If it no longer holds, the units turn around with the loot they carry and the sender gets a `movement_failed`
|
||||||
|
report. Return legs whose origin POP changed hands go to the operator's capital (or oldest POP).
|
||||||
|
|
||||||
|
## S3-5 — Takeover details
|
||||||
|
Only `takeover` movements (with an M&A team) can lower loyalty; one team per attack counts and is used up when it does. `takeoverBlock`:
|
||||||
|
a player's last POP wins over "capital" (refused at send); a capital with siblings is only dragged to loyalty 0. Loot is taken in the same
|
||||||
|
arrival, before the POP changes hands. On transfer the old owner's pending training/research is cancelled, pending builds are re-keyed to
|
||||||
|
the new owner's user, and that POP's units standing elsewhere are re-homed to the old owner's capital. A captured POP keeps its footprint.
|
||||||
|
|
||||||
|
## S3-6 — Transport links
|
||||||
|
`links` = Internet exchange level, each carries 500 (`D.TRANSPORT`). A link is busy while the transport is out and while its empty carriers
|
||||||
|
drive back (a `return` movement with `extra.link`). Cargo above the receiver's Rack hall cap is lost (the notification says how much).
|
||||||
|
`transport` movements keep arbitrary `extra` and `movements.hooks.transportArrived` is called on delivery, so the trade stage needs no
|
||||||
|
change in the movement code.
|
||||||
|
|
||||||
|
## S3-7 — Protection
|
||||||
|
Beginner protection blocks raid/attack/takeover in both directions. Sending one from a protected operator needs `confirmEndProtection`
|
||||||
|
and ends it at once; attacking an incumbent site does not end it; scans never do. The target's protection is compared with the ARRIVAL
|
||||||
|
time at send, and re-checked at arrival.
|
||||||
|
|
||||||
|
## S3-8 — Footprint gate counts the operator's total
|
||||||
|
`footprintNeeded(n)` with n = POPs owned now (second POP: n = 1). Founding and takeover both need `sum(footprint of own POPs) >= need`,
|
||||||
|
nothing is spent. New POPs start with every field at level 0, no infrastructure, 250 of each resource and loyalty 100.
|
||||||
|
|
||||||
|
## S3-9 — Moving units between your own POPs
|
||||||
|
`reinforce` to an own POP puts the units into `town_units` of the target (they live there now). Only units of OTHER operators are
|
||||||
|
`stationed` rows.
|
||||||
|
|
|
||||||
397
docs/DEPLOY.md
Normal file
397
docs/DEPLOY.md
Normal file
|
|
@ -0,0 +1,397 @@
|
||||||
|
# Deploying UPSTREAM
|
||||||
|
|
||||||
|
UPSTREAM is one Node process: it serves the static client from `public/`, the REST API under `/api/v1/` and (stage 6)
|
||||||
|
a WebSocket at `/ws`. Unlike NETWALL it **keeps state**: one SQLite file, owned by that process. A restart loses
|
||||||
|
nothing: overdue events are caught up in order before the server accepts traffic.
|
||||||
|
|
||||||
|
```
|
||||||
|
phone / laptop --https--> nginx Proxy Manager (TLS, :443) --http (+ WebSocket)--> Debian 13 LXC: node :8080
|
||||||
|
/opt/upstream (code, read-only)
|
||||||
|
/var/lib/upstream (game.db, backups/)
|
||||||
|
```
|
||||||
|
|
||||||
|
Same shape as NETWALL (`docs/DEPLOY.md` there): same proxy, same hardening notes, same env vars for the network
|
||||||
|
layer. The differences are the Node version (`node:sqlite` needs 22.13+), a state directory and backups.
|
||||||
|
|
||||||
|
**What was and was not run while writing this** (so you know what to check on the real box):
|
||||||
|
|
||||||
|
* **Run:** `systemd-analyze verify` on the three unit files (syntax and directives only), the CLI `tools/admin.js`
|
||||||
|
and its tests on a dev machine (Node 24.21), a backup, verify and prune cycle, `sh -n` on `deploy/upstream-admin`.
|
||||||
|
* **Taken from NETWALL's docs, not re-run for UPSTREAM:** everything about nginx Proxy Manager (labels, header
|
||||||
|
behaviour, "Client addresses"). NETWALL's guide records what was observed against NPM v2.16.0.
|
||||||
|
* **Never run:** a Proxmox LXC, a started unit under systemd, the timer firing on its own, a Node install from the
|
||||||
|
tarball or NodeSource on Debian 13, `rrsync`, Let's Encrypt, a restore on the real box. Treat those steps as a
|
||||||
|
checklist to confirm, and fix this file when reality differs.
|
||||||
|
|
||||||
|
## 1. Requirements
|
||||||
|
|
||||||
|
* Debian 13 (trixie) LXC with its own IPv4 (optionally IPv6) address the proxy can reach. 1 core, 512 MB RAM and 4 GB
|
||||||
|
disk are plenty for a small world; the database grows with the event and notification history (measure it with
|
||||||
|
`upstream-admin status`), and snapshots multiply it by the retention count.
|
||||||
|
* **Node 22.13 or newer.** Debian 13 ships `nodejs` **20.19.2** (checked on tracker.debian.org: stable has 20.19.2,
|
||||||
|
testing and unstable have 24.21). Node 20 has no `node:sqlite`, so `apt install nodejs` is **not enough**. `package.json`
|
||||||
|
says `"engines": {"node": ">=22.13"}`; 22.5 to 22.12 only have `node:sqlite` behind `--experimental-sqlite`, which
|
||||||
|
the unit does not pass. Development is on Node 24.21.
|
||||||
|
* A DNS name for the game (for example `upstream.example.com`) pointing at the proxy.
|
||||||
|
|
||||||
|
### Getting a suitable Node (pick one)
|
||||||
|
|
||||||
|
**A. Official tarball (no third-party apt repo, nothing piped into a shell).** Pick a current 24.x (Active LTS) or
|
||||||
|
22.x from https://nodejs.org/en/download and put its version in `V`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt update && apt install -y curl xz-utils ca-certificates
|
||||||
|
V=24.21.0 # example: use the current 24.x (or >= 22.13) you picked
|
||||||
|
ARCH=linux-x64 # linux-arm64 on ARM hosts (uname -m: aarch64)
|
||||||
|
cd /tmp
|
||||||
|
curl -fsSLO https://nodejs.org/dist/v$V/node-v$V-$ARCH.tar.xz
|
||||||
|
curl -fsSLO https://nodejs.org/dist/v$V/SHASUMS256.txt
|
||||||
|
grep " node-v$V-$ARCH.tar.xz\$" SHASUMS256.txt | sha256sum -c - # must print: ... OK
|
||||||
|
tar -C /opt -xJf node-v$V-$ARCH.tar.xz
|
||||||
|
ln -sfn /opt/node-v$V-$ARCH /opt/node
|
||||||
|
ln -sf /opt/node/bin/node /usr/local/bin/node
|
||||||
|
ln -sf /opt/node/bin/npm /usr/local/bin/npm
|
||||||
|
ln -sf /opt/node/bin/npx /usr/local/bin/npx
|
||||||
|
```
|
||||||
|
|
||||||
|
(For extra assurance also verify the signature of `SHASUMS256.txt` as described on nodejs.org.) An upgrade later is
|
||||||
|
a new tarball and `ln -sfn` to it, then `systemctl restart upstream`. `upstream.service` starts `/usr/bin/env node`, and
|
||||||
|
systemd's default PATH lists `/usr/local/bin` before `/usr/bin`, so the tarball wins over any distro Node.
|
||||||
|
|
||||||
|
**B. NodeSource apt repository** (follows their documentation; not run here). It puts Node in `/usr/bin/node`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt install -y ca-certificates curl gnupg
|
||||||
|
install -d -m 0755 /etc/apt/keyrings
|
||||||
|
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
|
||||||
|
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_24.x nodistro main" > /etc/apt/sources.list.d/nodesource.list
|
||||||
|
apt update && apt install -y nodejs # includes npm; do not also install Debian's npm package
|
||||||
|
```
|
||||||
|
|
||||||
|
**Verify either way** (all three must succeed):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node --version # v22.13.0 or newer
|
||||||
|
node -e "require('node:sqlite'); console.log('node:sqlite ok')"
|
||||||
|
which -a node # the first one is the one the unit will use
|
||||||
|
```
|
||||||
|
|
||||||
|
On 22.x/24.x Node may print `ExperimentalWarning: SQLite is an experimental feature` to stderr; that is harmless (it
|
||||||
|
shows up in the journal once per start). `No such built-in module: node:sqlite` means Node is too old (or it is the
|
||||||
|
distro's 20.x earlier on the PATH). If `node:sqlite` ever misbehaves, `DECISIONS.md` D1 describes the one-file swap
|
||||||
|
to `better-sqlite3` in `server/db.js`; that would add a native dependency and a build toolchain to the LXC.
|
||||||
|
|
||||||
|
## 2. Create the LXC (Proxmox)
|
||||||
|
|
||||||
|
Container creation, the Proxmox UI way (CLI `pct create` works too):
|
||||||
|
|
||||||
|
* Template `debian-13-standard`, **unprivileged**, hostname `upstream`, 1 core, 512 MB RAM (+256 MB swap), 4-8 GB disk.
|
||||||
|
* Network: a static address (or a DHCP reservation) on a bridge the NPM host can reach. The proxy forwards to that
|
||||||
|
address, so it must not change.
|
||||||
|
* Features: **Nesting** is optional; tick it only if you want the namespace-based hardening block in the unit
|
||||||
|
(section 3). Everything else works without it.
|
||||||
|
* Start on boot: yes. Timezone does not matter: the game uses UTC ms, the backup timer uses the container's clock.
|
||||||
|
* Proxmox's own CT backups (`vzdump`) are not a substitute for the snapshots in section 7: a running-container copy of
|
||||||
|
a SQLite file is crash-consistent at best. Use them for the OS and let the verified snapshots be the data backup.
|
||||||
|
|
||||||
|
## 3. Install in the LXC
|
||||||
|
|
||||||
|
Run as root inside the container (Node from section 1 is already in place).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
apt install -y rsync # for the copy below (or use git)
|
||||||
|
|
||||||
|
# a dedicated, login-less user that only runs the game
|
||||||
|
useradd --system --home-dir /var/lib/upstream --shell /usr/sbin/nologin upstream
|
||||||
|
|
||||||
|
# code: read-only for the service user, owned by root
|
||||||
|
mkdir -p /opt/upstream
|
||||||
|
# from your workstation:
|
||||||
|
# rsync -a --delete --exclude node_modules --exclude .git --exclude data --exclude e2e ./ root@<lxc>:/opt/upstream/
|
||||||
|
# (needs server/, public/, tools/, deploy/, docs/, package.json, package-lock.json; `test/` is optional)
|
||||||
|
cd /opt/upstream
|
||||||
|
npm ci --omit=dev # only "ws"; follows the lockfile exactly
|
||||||
|
chown -R root:root /opt/upstream
|
||||||
|
|
||||||
|
# the admin helper on the PATH
|
||||||
|
install -m 0755 /opt/upstream/deploy/upstream-admin /usr/local/bin/upstream-admin
|
||||||
|
|
||||||
|
# optional settings / secrets file (read by the unit and by upstream-admin)
|
||||||
|
install -d -m 0750 -o root -g upstream /etc/upstream
|
||||||
|
install -m 0640 -o root -g upstream /dev/null /etc/upstream/upstream.env
|
||||||
|
# edit it: SIGNUP_CODE=choose-a-long-random-string
|
||||||
|
# ALLOWED_ORIGINS=https://upstream.example.com
|
||||||
|
|
||||||
|
# the units
|
||||||
|
install -m 0644 /opt/upstream/deploy/upstream.service /opt/upstream/deploy/upstream-backup.service /opt/upstream/deploy/upstream-backup.timer /etc/systemd/system/
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable --now upstream upstream-backup.timer
|
||||||
|
systemctl status upstream
|
||||||
|
journalctl -u upstream -f
|
||||||
|
```
|
||||||
|
|
||||||
|
The first start prints `applied migrations: 001_init.sql, ...`, `created world 1` and the listen banner with
|
||||||
|
`database: /var/lib/upstream/game.db`. Quick manual run as the service user instead of systemd (Ctrl-C to stop):
|
||||||
|
`runuser -u upstream -- env PORT=8080 DB_PATH=/var/lib/upstream/game.db node /opt/upstream/server/index.js`.
|
||||||
|
|
||||||
|
### What the units do
|
||||||
|
|
||||||
|
* `deploy/upstream.service`: user `upstream`, `WorkingDirectory=/opt/upstream`, `StateDirectory=upstream` (systemd creates
|
||||||
|
`/var/lib/upstream` owned by that user, mode 0700, so the game can write nowhere else), `Restart=on-failure`,
|
||||||
|
`EnvironmentFile=-/etc/upstream/upstream.env` (overrides the `Environment=` lines), `UMask=0077` (database and
|
||||||
|
snapshots hold password hashes: owner-only).
|
||||||
|
* Hardening that works in any container: `NoNewPrivileges`, empty capability set (port 8080 needs none),
|
||||||
|
`RestrictAddressFamilies`, `RestrictRealtime`, `RestrictSUIDSGID`, `LockPersonality`, `SystemCallArchitectures`.
|
||||||
|
No `MemoryDenyWriteExecute` (V8 would crash).
|
||||||
|
* The namespace block (`ProtectSystem=strict`, `ReadWritePaths=/var/lib/upstream`, `PrivateTmp`, ...) is commented out.
|
||||||
|
In an unprivileged LXC it fails with `status=226/NAMESPACE` unless **Options > Features > Nesting** is on. Because the
|
||||||
|
app writes to disk, `ProtectSystem=strict` needs the `ReadWritePaths=` line that is already next to it in the unit;
|
||||||
|
without it the database cannot be opened.
|
||||||
|
* Shutdown: SIGTERM stops the scheduler timer, closes the listener and the database and exits 0 in about a second.
|
||||||
|
Even a SIGKILL or power cut is survivable (WAL replay on the next open, then overdue events are caught up).
|
||||||
|
* `deploy/upstream-backup.service` (oneshot) and `.timer`: see section 7.
|
||||||
|
|
||||||
|
## 4. Configuration
|
||||||
|
|
||||||
|
Environment variables read by `node server/index.js`. Put changes in `/etc/upstream/upstream.env` (`KEY=value`, one per
|
||||||
|
line, no `export`) or in a `systemctl edit upstream` override, then `systemctl restart upstream`.
|
||||||
|
|
||||||
|
| Variable | Default (unit) | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `PORT` | `8080` | TCP port. Unprivileged, so no capabilities needed. `0` picks a free one (banner prints it). |
|
||||||
|
| `HOST` | `::` | Bind address. `::` = one dual-stack socket for IPv4 and IPv6 (falls back to `0.0.0.0` if the kernel has no IPv6). `127.0.0.1` = this container only. |
|
||||||
|
| `DB_PATH` | `/var/lib/upstream/game.db` | SQLite file. The code default is `./data/game.db`; the unit overrides it. Its directory is created if missing, it must be writable by the service user. `-wal` and `-shm` files appear next to it: always copy via a snapshot (section 7), never with `cp` while running. |
|
||||||
|
| `TRUST_PROXY` | `auto` | `auto`: believe `X-Forwarded-For` / `X-Forwarded-Host` only from loopback / private-range peers. `1`: always (then firewall the port). `0`: never. Used for the per-IP rate limits and the log. |
|
||||||
|
| `TRUSTED_PROXIES` | empty | Extra IPs / CIDRs `auto` believes: needed when the proxy reaches the LXC from a global IPv6, Tailscale / CGNAT `100.64.0.0/10` or another routable address. |
|
||||||
|
| `ALLOWED_ORIGINS` | empty | Extra origins for the WebSocket origin check (stage 6), comma separated, with the port when it is not 80/443. The REST API uses bearer tokens (no cookies) and does not check origins. |
|
||||||
|
| `MAX_CONN_PER_IP` | `40` | Open connections per client address (WebSocket cap, stage 6). `0` disables. |
|
||||||
|
| `WORLD_SPEED` | unset (1) | World speed multiplier, **first boot only**, when the database has no world yet. |
|
||||||
|
| `WORLD_RADIUS` | unset (50) | Map radius in tiles (coordinates `-R..R`, so 50 = 101 x 101), **first boot only**. |
|
||||||
|
| `WORLD_NAME` | unset (`World 1`) | Name of the first world, **first boot only**. |
|
||||||
|
| `SIGNUP_CODE` | empty | If set, `POST /auth/signup` needs `"invite": "<this>"` in the body or answers `signup_closed` (403). Empty = open signup. Keep it in `/etc/upstream/upstream.env`, not in the unit file. |
|
||||||
|
| `UPSTREAM_DIR`, `UPSTREAM_ENV_FILE` | `/opt/upstream`, `/etc/upstream/upstream.env` | Only for the `upstream-admin` wrapper. |
|
||||||
|
|
||||||
|
Fixed in code (options of `createServer()`): per-IP and per-token rate limits (login and signup are stricter: about one
|
||||||
|
per 10 s sustained, burst 8, per client address), 32 KB request bodies, idempotency keys pruned hourly.
|
||||||
|
|
||||||
|
### First boot
|
||||||
|
|
||||||
|
An empty or missing database is created, all migrations are applied, and **one world is created** from `WORLD_SPEED`,
|
||||||
|
`WORLD_RADIUS`, `WORLD_NAME` (seed random). After that those variables are ignored: changing them does not touch the
|
||||||
|
existing world. More worlds, a different seed, ending or resetting a world are admin tasks (section 6). The first
|
||||||
|
player to sign up becomes an ordinary operator; there is no special admin account, admin work is the CLI on the box.
|
||||||
|
|
||||||
|
## 5. nginx Proxy Manager
|
||||||
|
|
||||||
|
In NPM: **Hosts > Proxy Hosts > Add Proxy Host**.
|
||||||
|
|
||||||
|
| Tab / field | Value |
|
||||||
|
|---|---|
|
||||||
|
| Details: Domain Names | `upstream.example.com` |
|
||||||
|
| Details: Scheme | `http` |
|
||||||
|
| Details: Forward Hostname / IP | the LXC's address (for example `192.168.1.51`), not `127.0.0.1` when NPM runs elsewhere or in its own container |
|
||||||
|
| Details: Forward Port | `8080` |
|
||||||
|
| Details: Cache Assets | **off** (static files are `no-cache` and revalidated by ETag; the game must see new versions) |
|
||||||
|
| Details: Block Common Exploits | optional |
|
||||||
|
| Details: **Websockets Support** | **on.** The REST game works without it, but stage 6 adds `/ws` and it fails with HTTP 426 when this is off. Switch it on now so you do not forget. |
|
||||||
|
| Custom Locations | none needed |
|
||||||
|
| SSL | Request a new Let's Encrypt certificate, **Force SSL**, **HTTP/2** (HSTS optional) |
|
||||||
|
| Advanced (gear) | nothing required; optional gzip below |
|
||||||
|
|
||||||
|
Optional, Advanced box, to compress JS/JSON for phones (the Node server does not compress; NPM's own `gzip on` only
|
||||||
|
covers HTML):
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
gzip on;
|
||||||
|
gzip_types text/css text/javascript application/javascript application/json application/manifest+json image/svg+xml;
|
||||||
|
```
|
||||||
|
|
||||||
|
Notes carried over from NETWALL's setup (observed there against NPM v2.16.0, not re-run for UPSTREAM):
|
||||||
|
|
||||||
|
* NPM sends `Host` **without the public port** and no `X-Forwarded-Host`. On a public port other than 443 the browser
|
||||||
|
`Origin` then differs from `Host`; list the origin with its port in `ALLOWED_ORIGINS` (matters for `/ws`).
|
||||||
|
* A proxy on a non-private address (global IPv6, Tailscale) is not believed by `TRUST_PROXY=auto`: every player then
|
||||||
|
shares one rate-limit budget and the log shows the proxy's address. Fix: `TRUSTED_PROXIES=<its address or CIDR>`.
|
||||||
|
* Clients on your own LAN can pick their address through NPM's `real_ip` handling, so the per-IP limits protect against
|
||||||
|
public abuse, not against LAN users.
|
||||||
|
* **Heads-up for stage 6:** NPM's default `proxy_read_timeout` is 90 s. NETWALL never idles because it streams 20
|
||||||
|
snapshots a second; UPSTREAM's socket will be quiet for long stretches. The WebSocket server must send a ping
|
||||||
|
well under 90 s (NETWALL's pings every 25 s), or the proxy drops idle players.
|
||||||
|
|
||||||
|
Firewall and dual stack: identical to NETWALL (`docs/DEPLOY.md` there, section 6): only the proxy needs to reach port
|
||||||
|
8080. `curl -i http://127.0.0.1:8080/healthz` and `curl -gi 'http://[::1]:8080/healthz'` check both families.
|
||||||
|
|
||||||
|
## 6. Operating: `upstream-admin`
|
||||||
|
|
||||||
|
`tools/admin.js` is the operator CLI (Node core only, uses the game's own `db.js`, `state.js`, `rules.js`).
|
||||||
|
`deploy/upstream-admin` runs it as the service user against the service's database (it reads `DB_PATH` from
|
||||||
|
`/etc/upstream/upstream.env`). **Do not run `node tools/admin.js` as root**: SQLite would create `game.db-wal` and
|
||||||
|
`-shm` owned by root and the game could no longer open its database (symptom in section 10).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
upstream-admin help
|
||||||
|
upstream-admin status # file, size, migrations, overdue events
|
||||||
|
upstream-admin worlds
|
||||||
|
upstream-admin create-world --name "Summer" --speed 2 --radius 60 --seed 1234 --end-in 90d
|
||||||
|
upstream-admin end-world 1 --yes
|
||||||
|
upstream-admin users [--banned] # no hashes or tokens are ever printed
|
||||||
|
upstream-admin operators [--world 1]
|
||||||
|
upstream-admin ban mallory # sets banned, revokes all tokens: old tokens give 401, login 403
|
||||||
|
upstream-admin unban mallory
|
||||||
|
upstream-admin revoke-tokens ada # log out everywhere
|
||||||
|
upstream-admin inspect-operator ada # (--world N when the name exists in several worlds, --id N by operator id)
|
||||||
|
upstream-admin inspect-town 12 # resources now (rules.resourcesAt), buildings, queue, units if the table exists
|
||||||
|
upstream-admin events --pending [--type buildDone --town 12 --limit 100]
|
||||||
|
upstream-admin replay-events --until +6h # dry run: what the scheduler would process, in order
|
||||||
|
upstream-admin replay-events --until +6h --simulate # + run the real handlers on a scratch copy, report outcome and follow-ups
|
||||||
|
upstream-admin backup /var/lib/upstream/backups --keep 14
|
||||||
|
upstream-admin verify-backup /var/lib/upstream/backups/upstream-20261011T041500Z.db
|
||||||
|
upstream-admin grant 12 --fiber 5000 --capital 2000 --yes # testing only
|
||||||
|
upstream-admin reset-world 1 --yes-destroy --backup /var/lib/upstream/backups --new-seed
|
||||||
|
upstream-admin migrate # apply pending migrations without starting the server
|
||||||
|
```
|
||||||
|
|
||||||
|
All commands take `--json` (machine output) and `--db FILE` (otherwise `$DB_PATH`, otherwise `./data/game.db`).
|
||||||
|
Exit codes: `0` ok, `1` failed, `2` usage error **or a destructive command missing its flag**, `3` not found.
|
||||||
|
|
||||||
|
Safety rules the CLI follows:
|
||||||
|
|
||||||
|
* Destructive or test-only commands refuse without a flag: `end-world` and `grant` need `--yes`; `reset-world`
|
||||||
|
needs `--yes-destroy` (without it, it prints what it would delete and exits 2). `ban`, `unban`, `revoke-tokens` are
|
||||||
|
reversible and need none.
|
||||||
|
* `reset-world` deletes the world's game rows (everything with a `world_id`, plus tables pointing at them: towns,
|
||||||
|
buildings, events, operators, alliances, messages, ... discovered from the schema, so tables added by later stages
|
||||||
|
are covered) and **keeps accounts and tokens**; players must join the world again. It resets `start_at`, clears
|
||||||
|
`end_at` and sets the world running. It rolls back if it would leave dangling references. Stop the game first
|
||||||
|
(`systemctl stop upstream`): the server does not know the world was swept while it is running. Use `--backup DIR`.
|
||||||
|
* Everything runs on a running server's database: writes are single short `BEGIN IMMEDIATE` transactions, the
|
||||||
|
connection is always closed, and SQLite's 5 s busy timeout covers collisions with the game (`database is locked`
|
||||||
|
from the CLI just means: try again).
|
||||||
|
* `grant` adds to the town's stored amounts (valid at its `res_at`); the lazy model carries them forward. Amounts above
|
||||||
|
the Rack hall cap are kept but stop growing, like a lowered cap.
|
||||||
|
* `inspect-town` shows values as of now **ignoring** overdue events; it says so when there are any (server stopped).
|
||||||
|
|
||||||
|
## 7. Backups and restore
|
||||||
|
|
||||||
|
`upstream-backup.timer` runs `upstream-backup.service` daily at 04:15 (10 min jitter, `Persistent=true`). It runs
|
||||||
|
`tools/admin.js backup /var/lib/upstream/backups --keep 14` as the service user. A snapshot is:
|
||||||
|
|
||||||
|
1. `VACUUM INTO` a temporary `.partial-*` file: a consistent copy as of one moment, safe while the game runs (WAL readers do
|
||||||
|
not block the writer; the game keeps its own 5 s busy timeout);
|
||||||
|
2. verified: opened read-only, `PRAGMA integrity_check` = `ok`, `worlds` and `schema_migrations` present;
|
||||||
|
3. published under a dated name `upstream-YYYYMMDDTHHMMSSZ.db` (UTC) with a hard link, so an existing file is never
|
||||||
|
replaced (a same-second collision becomes `...Z-1.db`), mode 0600;
|
||||||
|
4. only then older snapshots are pruned: `--keep N` keeps the newest N, `--keep-days D` keeps those younger than D days,
|
||||||
|
both = survive if either keeps it, neither = no pruning. The newest snapshot and any file not matching the naming
|
||||||
|
pattern are never deleted. A failed verification leaves nothing behind and prunes nothing, and the unit fails
|
||||||
|
(`systemctl status upstream-backup`, `journalctl -u upstream-backup`).
|
||||||
|
|
||||||
|
Snapshots are plain SQLite files (journal mode `delete`), not `-wal` dependent: copy a single file.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl list-timers upstream-backup.timer # next run
|
||||||
|
systemctl start upstream-backup # one right now
|
||||||
|
journalctl -u upstream-backup -n 20
|
||||||
|
ls -l /var/lib/upstream/backups
|
||||||
|
```
|
||||||
|
|
||||||
|
Change the schedule or retention with `systemctl edit upstream-backup.timer` / `upstream-backup.service` (for every
|
||||||
|
6 hours: `OnCalendar=*-*-* 00/6:15:00` and a larger `--keep`). Before an upgrade or a `reset-world`, take one by hand.
|
||||||
|
|
||||||
|
### Off-box copy
|
||||||
|
|
||||||
|
Snapshots on the same disk die with the container. Pull them from another machine (NAS, workstation, the Proxmox host),
|
||||||
|
for example from cron or a timer there:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rsync -a --ignore-existing root@<lxc>:/var/lib/upstream/backups/ /srv/backups/upstream/
|
||||||
|
```
|
||||||
|
|
||||||
|
`--ignore-existing` makes it append-only on your side (nothing already stored is overwritten, and snapshots pruned on
|
||||||
|
the LXC stay on the backup host until you decide otherwise). Better than a root key: a dedicated key restricted in
|
||||||
|
`authorized_keys` to `command="rrsync -ro /var/lib/upstream/backups",restrict ...` (`rrsync` comes with the `rsync`
|
||||||
|
package; not run here). The files are owner-only (`upstream`), so the reading user needs root or a group ACL.
|
||||||
|
|
||||||
|
### Restore
|
||||||
|
|
||||||
|
The restore is a file copy, and the time model makes it clean: the restored world simply fast-forwards. Every event that
|
||||||
|
fell due since the snapshot is processed in order at start-up, each at its own due time. What is lost is what players did after
|
||||||
|
the snapshot (builds started, signups, messages) and their tokens: players log in again.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl stop upstream-backup.timer upstream
|
||||||
|
upstream-admin verify-backup /var/lib/upstream/backups/upstream-20261011T041500Z.db # exit 0 or stop here
|
||||||
|
mkdir -p /var/lib/upstream/pre-restore
|
||||||
|
mv /var/lib/upstream/game.db* /var/lib/upstream/pre-restore/ 2>/dev/null # keep the old one, incl. -wal/-shm
|
||||||
|
install -o upstream -g upstream -m 0600 /var/lib/upstream/backups/upstream-20261011T041500Z.db /var/lib/upstream/game.db
|
||||||
|
systemctl start upstream upstream-backup.timer
|
||||||
|
journalctl -u upstream -n 20 # look for "caught up N overdue event(s)"
|
||||||
|
upstream-admin status
|
||||||
|
```
|
||||||
|
|
||||||
|
Restoring onto another machine works the same way (install code and Node, copy the file to `DB_PATH`). Migrations in
|
||||||
|
the snapshot are checksummed: if the code is newer than the snapshot, the missing migrations are applied at boot; run
|
||||||
|
code that is **older** than the snapshot's last migration (`upstream-admin status` shows it) only if you know the schema
|
||||||
|
still fits, the server does not check for that.
|
||||||
|
|
||||||
|
## 8. Upgrading
|
||||||
|
|
||||||
|
```sh
|
||||||
|
upstream-admin backup /var/lib/upstream/backups --keep 14 # 1. snapshot first
|
||||||
|
rsync -a --delete --exclude node_modules --exclude .git --exclude data ./ root@<lxc>:/opt/upstream/ # 2. new code (from your workstation)
|
||||||
|
cd /opt/upstream && npm ci --omit=dev && chown -R root:root /opt/upstream # 3. dependencies, ownership
|
||||||
|
systemctl restart upstream # 4. migrations apply at boot
|
||||||
|
journalctl -u upstream -n 30 # 5. "applied migrations: ..." then the listen banner
|
||||||
|
curl -i http://127.0.0.1:8080/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
* Migrations are `server/migrations/NNN_name.sql`, applied in order inside a transaction each, **recorded with a
|
||||||
|
checksum and never edited after they shipped**. If one that was applied has changed, the server refuses to start
|
||||||
|
(`migration 001_init.sql was edited after it was applied`): restore that file from git and ship a **new** numbered
|
||||||
|
migration instead. `upstream-admin status` lists applied and pending migrations; `upstream-admin migrate` applies
|
||||||
|
them without starting the game.
|
||||||
|
* Each migration runs in its own transaction: a failing one rolls back and the server exits, earlier ones of the same
|
||||||
|
boot stay applied. Going back to the old code after a migration committed means restoring the pre-upgrade snapshot
|
||||||
|
(section 7).
|
||||||
|
* Updated unit files: `install -m 0644 ...`, `systemctl daemon-reload`, `systemctl restart upstream`.
|
||||||
|
* Players reconnecting after the restart need no action; clients get `serverTime` in every response and refetch.
|
||||||
|
|
||||||
|
## 9. Health, logs, checks
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -i https://upstream.example.com/healthz # 200 ok (only says the process answers HTTP)
|
||||||
|
curl -I https://upstream.example.com/ # 200 + Content-Security-Policy
|
||||||
|
upstream-admin status # database, migrations, events pending / OVERDUE
|
||||||
|
journalctl -u upstream -f # live log; -p err for failures only
|
||||||
|
journalctl -u upstream --since "1 hour ago" | grep -E "failed|refused"
|
||||||
|
```
|
||||||
|
|
||||||
|
The log has: applied migrations, created world, caught-up events, `refused rate_limited(...) ip=...`, and
|
||||||
|
`event N (type) failed: ...` for a handler that threw (that event is marked `failed` and the queue moves on; list them
|
||||||
|
with `upstream-admin events --status failed`). Player IP addresses appear in the log; passwords and tokens never do.
|
||||||
|
A healthy server has **no overdue events** in `status`: the timer processes events within milliseconds of their due time.
|
||||||
|
|
||||||
|
## 10. Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Cause and fix |
|
||||||
|
|---|---|
|
||||||
|
| Service dies at start: `No such built-in module: node:sqlite` | Node is older than 22.13, or the distro's Node 20 is first on the PATH. `node --version`, `which -a node`, section 1. |
|
||||||
|
| `ExperimentalWarning: SQLite is an experimental feature` in the journal | Harmless. Printed once per start on some Node versions. |
|
||||||
|
| `SQLITE_CANTOPEN` / `unable to open database file` | `DB_PATH`'s directory is not writable by `upstream`: wrong path in `upstream.env`, `/var/lib/upstream` created by hand with other ownership (`chown -R upstream:upstream /var/lib/upstream`), or `ProtectSystem=strict` enabled without `ReadWritePaths=/var/lib/upstream`. |
|
||||||
|
| `attempt to write a readonly database` / `unable to open database file` right after using the CLI | `admin.js` was run as root and left root-owned `game.db-wal` / `-shm`. Stop the game, `chown upstream:upstream /var/lib/upstream/game.db*`, start. Use `upstream-admin`, which switches user. |
|
||||||
|
| `migration NNN_x.sql was edited after it was applied` | An applied migration changed on disk (checksum mismatch). Restore it from git; changes go in a new migration. |
|
||||||
|
| `UPSTREAM failed to start: ...` with `EADDRINUSE` | Another process on the port (`ss -ltnp \| grep 8080`) or two copies. Change `PORT` and the NPM forward port together. |
|
||||||
|
| `IPv6 is not available (...); falling back to 0.0.0.0` | The kernel has no IPv6. IPv4 keeps working; set `HOST=0.0.0.0` to silence it. |
|
||||||
|
| `status=226/NAMESPACE` | The optional namespace hardening is on in an LXC without Nesting: enable **Options > Features > Nesting** and restart the CT, or comment the block out. |
|
||||||
|
| `Cannot find module 'ws'` | `npm ci --omit=dev` was not run in `/opt/upstream`. |
|
||||||
|
| 502 Bad Gateway from NPM | Upstream unreachable: `systemctl status upstream`, `curl -i http://<lxc>:8080/healthz` from the NPM host, forward IP/port, firewall. |
|
||||||
|
| Page loads but a new deploy still shows the old client | NPM *Cache Assets* is on, or a service layer ignores `no-cache`. Switch it off, hard-reload. |
|
||||||
|
| Signup answers 403 `signup_closed` | `SIGNUP_CODE` is set. Send `{"invite": "<code>"}` in the signup body, or unset it and restart. |
|
||||||
|
| Login/signup answers 429 `rate_limited` for many players | They all arrive from one address: the proxy is not trusted so the per-IP budget is shared (log says `ip=<the proxy>`). Set `TRUSTED_PROXIES`. Login and signup allow about one request per 10 s per address, burst 8; a whole classroom behind one NAT can hit that. |
|
||||||
|
| Game seems frozen: builds never finish | `upstream-admin status`: `OVERDUE` events mean the scheduler is not running (server stopped or stuck) or handlers fail: `upstream-admin events --status failed`, journal `event N ... failed`. A restart catches up everything in order. |
|
||||||
|
| Banned user still plays | They cannot: `ban` revokes every token and blocks login. Check the username spelling (`upstream-admin users --banned`). |
|
||||||
|
| `database is locked` from the CLI | The game held a write lock longer than the 5 s busy timeout. Retry. |
|
||||||
|
| `upstream-backup.service` failed | `journalctl -u upstream-backup`. Typical: disk full, or the integrity check of the new snapshot failed (then nothing was kept and nothing pruned; check the disk and the `game.db` itself). |
|
||||||
|
| Backups not appearing | `systemctl list-timers upstream-backup.timer`; the timer must be **enabled** (`systemctl enable --now upstream-backup.timer`), not just installed. |
|
||||||
|
| World reset by mistake | Restore the snapshot taken before (section 7), or the one `reset-world --backup` wrote. |
|
||||||
|
| (stage 6) WebSocket upgrade answered 426 / 403 / 429 | 426: **Websockets Support** off in NPM. 403: origin check, see `ALLOWED_ORIGINS` and the notes in section 5. 429: more than `MAX_CONN_PER_IP` sockets from one address. |
|
||||||
|
|
@ -184,6 +184,27 @@ POP view (buildings + queue), Resource view (slots), Map (pan/zoom, tile info, s
|
||||||
station, movements list), Reports, Messages, Alliance, Exchange, Rankings, Profile/settings. Every countdown is
|
station, movements list), Reports, Messages, Alliance, Exchange, Rankings, Profile/settings. Every countdown is
|
||||||
computed from `serverTime`.
|
computed from `serverTime`.
|
||||||
|
|
||||||
|
## Stage 3/4 clarifications (what the server does, where DESIGN.md was silent)
|
||||||
|
|
||||||
|
- **Training/research:** training time = unit time x count / (1 + 0.03 x level of the training building) / world speed; batches of one
|
||||||
|
building queue one after another. Research cost = 8 x the unit's cost x 1.35^(level-1), time 30 min x 1.3^(level-1) / (1 + 0.03 x lab
|
||||||
|
level); research level n needs Research lab n + 2.
|
||||||
|
- **Roles per movement:** scan = port scanners only; raid = attackers and defenders (no siege); attack = + DDoS rigs and exploit kits;
|
||||||
|
takeover = + M&A teams (at least one); reinforce = anything that moves; settle = exactly three Rollout crews. Honeypots never move.
|
||||||
|
- **Combat:** formulas as above; ties go to the defender; a unit group loses `round(n x fraction)` per type. Raid: BOTH sides lose
|
||||||
|
`0.5 x (weaker/stronger)^1.5` whoever wins. Defenders are home crews plus each reinforcement group (own research each), counted only
|
||||||
|
while online. The cold-spare cache applies to raids only; a full attack takes loot from the whole stock. Loot is split evenly over Fiber,
|
||||||
|
Hardware, Capital, leftovers going to the others, capped by the survivors' carry. Exploit kits count by survivors.
|
||||||
|
- **Scan:** `sa` vs `sd` = scanners x (1 + 5% per defence-research level of port_scanner). Success needs `sa > sd`; `detail` is `basic`
|
||||||
|
(units, resources) and `full` at 2:1 (+ buildings, loyalty, the target's outgoing movements with their types). A failed scan loses all
|
||||||
|
scanners and reveals the scanner to the target; a successful one loses `0.5 x (sd/sa)^1.5`.
|
||||||
|
- **Incumbent site defence:** `600 x (1 +- 25% per site, seeded) x (1 + 4% x world days)`, world days = real days x speed; sites are scanned
|
||||||
|
or attacked, never raided or taken over, and never fight back.
|
||||||
|
- **Power:** when the battery is empty and net power is negative, all units in that POP are offline; after 24 h / speed the most
|
||||||
|
expensive are decommissioned until the draw fits.
|
||||||
|
- **Transport:** 12 tiles/h, 500 per link, links = Internet exchange level; a link is busy until the empty carriers are back.
|
||||||
|
- **Protection and recall:** see S3-4 and S3-7 in DECISIONS.md; the recall window is 90 s of real time (not divided by world speed).
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
||||||
- One or two defence stats per unit?
|
- One or two defence stats per unit?
|
||||||
|
|
|
||||||
59
docs/NEXT.md
59
docs/NEXT.md
|
|
@ -7,5 +7,64 @@ Honest status, updated at the end of every stage.
|
||||||
- Stage 1 economy (server): lazy resources, buildings, build queue, storage caps, power battery.
|
- Stage 1 economy (server): lazy resources, buildings, build queue, storage caps, power battery.
|
||||||
- Stage 2 world (server): seeded tiles, spawn ring, map viewport query.
|
- Stage 2 world (server): seeded tiles, spawn ring, map viewport query.
|
||||||
|
|
||||||
|
## Stage 5 (partial): social, server only
|
||||||
|
Built (migration `003_social.sql`): alliances (found, invite/accept/decline/cancel, leave, kick, roles, leader transfer, disband,
|
||||||
|
pinned notes, member list with POP count and last online), diplomacy between alliances (war, neutral, NAP, confederation;
|
||||||
|
proposals; 24 h / speed pact cancel through the `diploChange` event; revoke), messages (DM, alliance broadcast, inbox/outbox/thread/
|
||||||
|
alliance feed, read, delete own copy, block list, DB-backed rate limit, text sanitising), rankings (operators, alliances, battles),
|
||||||
|
`alliance` in `/me` and `/map`, lookup helpers in `server/alliances.js` (`operatorRelation`, `atWar`, `confederated`, `pactPartners`).
|
||||||
|
Tests: `test/social-*.test.js` (pure rules, alliances, diplomacy with the fake clock and event queue, messages, rankings), every
|
||||||
|
response in them is checked against its declared schema (`createTestServer({ contract: true })` in `test/helpers.js`).
|
||||||
|
|
||||||
|
Not done:
|
||||||
|
- Marketplace / Internet exchange and resource transport (waits for the movement system of stage 3).
|
||||||
|
- Shared report folder of the alliance (needs reports from stage 3), confederation effects (reinforce, see incoming) and the pact
|
||||||
|
effect "no attacks inside a NAP/confederation": the military stage must call `alliances.pactPartners` / `confederated`; nothing
|
||||||
|
enforces it yet.
|
||||||
|
- No web client, no WebSocket push (notifications rows are written; stage 6 pushes them).
|
||||||
|
- Message retention/cleanup of old rows, alliance rename/description, mass-mail abuse reporting, sitter accounts.
|
||||||
|
- Rankings are not cached; battle rankings stay empty until the military stage writes `operator_stats`.
|
||||||
|
- Not run: Playwright, load, or any bot balance run; the social numbers in `SOCIAL` (limits, TTLs, role table) are first guesses.
|
||||||
|
|
||||||
|
## Stage 3/4: military and expansion (server only)
|
||||||
|
Built (migration `002_military.sql`: `town_units`, `stationed`, `town_research`, `town_power`, `movements`, `reports`, `report_recipients`,
|
||||||
|
`operator_stats`, `incumbent_takes`): 10 unit types and research in `data.js`/`rules.js`; training queue (`trainDone` per batch,
|
||||||
|
sequential per building); research (`researchDone`); movements scan/raid/attack/takeover/reinforce/settle/transport with latency, ETA,
|
||||||
|
recall (90 s), return legs with loot; combat resolved at arrival in the event queue (full attack, raid, firewall vs DDoS rigs, exploit
|
||||||
|
kits on a chosen building, loot with Rack hall cache, losses, reinforcements, research, battle points in `operator_stats`);
|
||||||
|
scans with intel and detection; takeover with loyalty, capital and last-POP protection, footprint gate; founding POPs with wild-slot
|
||||||
|
choice; incumbent sites (static defence growing with world age, one-time Hardware bonus, +10% research speed per site); beginner
|
||||||
|
protection (both directions, re-checked at arrival); power: offline units when the battery is empty, decommission after 24 h
|
||||||
|
(`powerCheck`); incoming warnings with hidden type; reports (shared row, per-user read flag, 14 day cleanup event); transport movement
|
||||||
|
and arrival hook (`movements.hooks.transportArrived`) for the trade stage. Routes: see docs/API.md, all in `docs/openapi.json`.
|
||||||
|
Tests: `test/military-*.test.js` (rules as pure functions, train queue order, raid end to end, event order and determinism, takeover and
|
||||||
|
its protections, offline units and decommission, restart catch-up from a reopened DB file, protection, settle, incumbent, transport,
|
||||||
|
recall, research, reports/cursor/retention, API smoke over HTTP). Fake clock, in-memory DB, port 0; no Playwright.
|
||||||
|
Not done / not claimed:
|
||||||
|
- **Nothing is balanced.** All unit stats, costs, research curves, incumbent defence and the 50-unit-scale combat numbers are first guesses;
|
||||||
|
there was no bot run (`tools/bot.js` does not exist yet). Do not cite any of them as tuned.
|
||||||
|
- Training cannot be cancelled; reports cannot be shared to the alliance yet (the shared report folder needs a table in the social stage);
|
||||||
|
confederates do not see each other's incoming movements (only reinforce is wired); no sitter, no night protection.
|
||||||
|
- A building damaged by exploit kits that has an upgrade in flight jumps to the queued level when that finishes (`buildDone` sets absolute levels).
|
||||||
|
- Units in transit draw no power from anyone; an operator cannot choose a new capital POP (no command); a captured POP keeps its footprint.
|
||||||
|
- Backbone landing sites and the Backbone node (end game) are not part of this stage.
|
||||||
|
|
||||||
|
## Client (stages 1-2 web client)
|
||||||
|
Built: `public/` vanilla JS, no build step, strict-CSP friendly (no inline scripts or handlers, no external requests).
|
||||||
|
- Shell (`js/main.js`): session, `App.registerScreen({id, titleKey, navKey, icon, hud, render, onShow, onHide, onLang})`, bottom nav
|
||||||
|
(left rail in landscape and on wide screens), live resource bar ticked with `rules.resourcesAt` from the server clock, hash routing.
|
||||||
|
- Screens (`js/screens/`): login/signup (invite field appears after `signup_closed`), POP (resource fields by type, infrastructure,
|
||||||
|
build queue with countdowns and cancel, power panel, detail sheet with the server's `next` plan, live affordability, rename),
|
||||||
|
map (`js/render.js` canvas: pan, pinch, wheel, keyboard, culling; chunked `GET /map` cache; tile info sheet), alerts
|
||||||
|
(`GET /notifications`), settings (language, device tokens + revoke, logout).
|
||||||
|
- `js/api.js`: bearer token, serverTime offset, retry/backoff (network, 429 + Retry-After, 502-504), `Idempotency-Key` per intent,
|
||||||
|
`ApiError.code`, event emitter with a reserved `push` event (no WebSocket client yet).
|
||||||
|
- `js/i18n.js`: en + nb, all player-facing names; `PWA`: manifest + icons (no service worker, so no offline mode).
|
||||||
|
- Tests: `test/client-i18n.test.js` (key parity, names, error codes, formatting), `test/client-api.test.js` (retry, idempotency, offset).
|
||||||
|
- Looked at with headless Chromium screenshots (phone portrait, phone landscape, desktop) and one scripted signup/build/cancel/map-tap
|
||||||
|
flow on a phone profile. Not run: real devices, Safari/iOS, Playwright suite.
|
||||||
|
Gaps: the unread badge is stored in localStorage (no "mark read" route); `/me` exposes the world seed which the client ignores;
|
||||||
|
no push, no service worker, canvas has no inertia/fling, no light theme.
|
||||||
|
|
||||||
## Not done
|
## Not done
|
||||||
- Everything else. See CLAUDE.md "Working in stages".
|
- Everything else. See CLAUDE.md "Working in stages".
|
||||||
|
|
|
||||||
6600
docs/openapi.json
6600
docs/openapi.json
File diff suppressed because it is too large
Load diff
|
|
@ -6,7 +6,7 @@
|
||||||
"main": "server/index.js",
|
"main": "server/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server/index.js",
|
"start": "node server/index.js",
|
||||||
"test": "node --test test/",
|
"test": "node --test test/*.test.js",
|
||||||
"openapi": "node tools/gen-openapi.js",
|
"openapi": "node tools/gen-openapi.js",
|
||||||
"e2e": "node e2e/run.js"
|
"e2e": "node e2e/run.js"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
324
public/css/style.css
Normal file
324
public/css/style.css
Normal file
|
|
@ -0,0 +1,324 @@
|
||||||
|
/* UPSTREAM client styles. Dark "network ops console", phone-first.
|
||||||
|
*
|
||||||
|
* Layout modes (the shell is a grid on #app):
|
||||||
|
* portrait / narrow top bar, resource bar, scrolling view, bottom nav (thumb reach)
|
||||||
|
* rail (landscape and short) OR (width >= 900): nav becomes a left rail, so landscape phones keep their height
|
||||||
|
* Safe-area insets are applied once, on #app. Every interactive target is at least 44px tall. No hover-only affordances.
|
||||||
|
*/
|
||||||
|
:root {
|
||||||
|
--bg: #070b16;
|
||||||
|
--panel: #0c1322;
|
||||||
|
--panel2: #111b30;
|
||||||
|
--panel3: #16233d;
|
||||||
|
--line: #1d2c4c;
|
||||||
|
--line2: #2a3f6b;
|
||||||
|
--text: #d3e6ff;
|
||||||
|
--dim: #9bb2d6;
|
||||||
|
--dimmer: #7790b8;
|
||||||
|
--cyan: #4de3ff;
|
||||||
|
--amber: #ffd24d;
|
||||||
|
--red: #ff6b87;
|
||||||
|
--green: #35e0a1;
|
||||||
|
--violet: #b06cff;
|
||||||
|
--fiber: #4de3ff;
|
||||||
|
--hardware: #ff9f5a;
|
||||||
|
--capital: #5be08f;
|
||||||
|
--power: #ffd24d;
|
||||||
|
--safe-t: env(safe-area-inset-top, 0px);
|
||||||
|
--safe-r: env(safe-area-inset-right, 0px);
|
||||||
|
--safe-b: env(safe-area-inset-bottom, 0px);
|
||||||
|
--safe-l: env(safe-area-inset-left, 0px);
|
||||||
|
--nav-h: 58px;
|
||||||
|
--rail-w: 76px;
|
||||||
|
--radius: 14px;
|
||||||
|
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||||
|
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.4 var(--font); overflow: hidden; overscroll-behavior: none; -webkit-text-size-adjust: 100%; }
|
||||||
|
button, input, select { font: inherit; color: inherit; }
|
||||||
|
button { cursor: pointer; touch-action: manipulation; }
|
||||||
|
h1, h2, h3, p, ul { margin: 0; padding: 0; }
|
||||||
|
ul { list-style: none; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
b { font-weight: 650; }
|
||||||
|
.mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
|
||||||
|
.dimmer { color: var(--dimmer); }
|
||||||
|
.small { font-size: 13px; }
|
||||||
|
svg.ic { width: 1.3em; height: 1.3em; flex: none; display: inline-block; vertical-align: middle; }
|
||||||
|
|
||||||
|
:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; border-radius: 6px; }
|
||||||
|
button:focus:not(:focus-visible), [tabindex="-1"]:focus { outline: none; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- shell */
|
||||||
|
#app {
|
||||||
|
position: fixed; inset: 0; height: 100dvh;
|
||||||
|
display: grid; grid-template-columns: minmax(0, 1fr);
|
||||||
|
grid-template-rows: auto auto minmax(0, 1fr) auto;
|
||||||
|
grid-template-areas: "top" "hud" "view" "nav";
|
||||||
|
padding: var(--safe-t) var(--safe-r) 0 var(--safe-l);
|
||||||
|
background: radial-gradient(1000px 520px at 15% -10%, #0e1d3a 0%, transparent 60%), radial-gradient(800px 460px at 100% 110%, #1a0f33 0%, transparent 55%), var(--bg);
|
||||||
|
}
|
||||||
|
#topbar { grid-area: top; display: flex; align-items: center; gap: 10px; padding: 8px 16px 6px; min-height: 44px; }
|
||||||
|
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: .08em; font-size: 15px; }
|
||||||
|
.brand-mark { width: 18px; height: 18px; background: linear-gradient(135deg, var(--cyan), #3b82f6); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); flex: none; }
|
||||||
|
.brand-mark.big { width: 40px; height: 40px; }
|
||||||
|
.netstate { margin-left: auto; font-size: 12px; padding: 4px 10px; border-radius: 999px; background: #3a1620; color: #ffb3c2; border: 1px solid #6b2236; }
|
||||||
|
.netstate.ok { background: #0f3a2c; color: #9af0cd; border-color: #1a6a4f; }
|
||||||
|
#hud { grid-area: hud; width: 100%; max-width: 1124px; justify-self: center; }
|
||||||
|
#view { grid-area: view; min-height: 0; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; }
|
||||||
|
#app[data-screen="map"] #view { overflow: hidden; }
|
||||||
|
#app[data-screen="auth"] #topbar, #app[data-state="out"] #topbar { display: none; }
|
||||||
|
.screen { min-height: 100%; }
|
||||||
|
.screen-map { height: 100%; min-height: 0; position: relative; }
|
||||||
|
|
||||||
|
#nav {
|
||||||
|
grid-area: nav; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr;
|
||||||
|
background: rgba(9, 15, 29, .96); border-top: 1px solid var(--line);
|
||||||
|
padding-bottom: var(--safe-b);
|
||||||
|
}
|
||||||
|
.nav-btn { background: none; border: 0; min-height: var(--nav-h); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; color: var(--dim); font-size: 12px; position: relative; padding: 4px 2px; }
|
||||||
|
.nav-btn[aria-current="page"] { color: var(--cyan); }
|
||||||
|
.nav-btn[aria-current="page"]::before { content: ""; position: absolute; top: 0; left: 28%; right: 28%; height: 3px; border-radius: 0 0 3px 3px; background: var(--cyan); }
|
||||||
|
.nav-ic { position: relative; display: inline-flex; }
|
||||||
|
.nav-ic svg.ic { width: 24px; height: 24px; }
|
||||||
|
.nav-badge { position: absolute; top: -5px; right: -9px; min-width: 17px; height: 17px; padding: 0 4px; border-radius: 9px; background: var(--red); color: #1a0710; font-size: 11px; font-weight: 700; display: grid; place-items: center; }
|
||||||
|
.nav-lbl { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
|
||||||
|
@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) {
|
||||||
|
#app {
|
||||||
|
grid-template-columns: var(--rail-w) minmax(0, 1fr);
|
||||||
|
grid-template-rows: auto auto minmax(0, 1fr);
|
||||||
|
grid-template-areas: "nav top" "nav hud" "nav view";
|
||||||
|
padding-bottom: var(--safe-b);
|
||||||
|
}
|
||||||
|
#app[data-state="out"] { grid-template-columns: minmax(0, 1fr); grid-template-areas: "view" "view" "view"; }
|
||||||
|
#nav { grid-auto-flow: row; grid-auto-columns: auto; grid-auto-rows: min-content; align-content: start; border-top: 0; border-right: 1px solid var(--line); padding: 6px 0; padding-bottom: 6px; overflow-y: auto; }
|
||||||
|
.nav-btn { min-height: 62px; }
|
||||||
|
.nav-btn[aria-current="page"]::before { top: 22%; bottom: 22%; left: 0; right: auto; width: 3px; height: auto; border-radius: 0 3px 3px 0; }
|
||||||
|
#topbar { padding-top: 4px; min-height: 36px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.boot { display: grid; place-items: center; gap: 14px; padding: 48px 16px; color: var(--dim); text-align: center; }
|
||||||
|
.spinner { width: 28px; height: 28px; border: 3px solid var(--line2); border-top-color: var(--cyan); border-radius: 50%; animation: spin .9s linear infinite; }
|
||||||
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 3s; } * { scroll-behavior: auto !important; } }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- resource bar */
|
||||||
|
.hud { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; padding: 4px 12px 8px; }
|
||||||
|
.hud-chip { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 12px; padding: 6px 8px 7px; min-width: 0; --c: var(--dim); }
|
||||||
|
.hud-chip.fiber { --c: var(--fiber); } .hud-chip.hardware { --c: var(--hardware); } .hud-chip.capital { --c: var(--capital); } .hud-chip.power { --c: var(--power); }
|
||||||
|
.hud-top { display: flex; align-items: center; gap: 4px; color: var(--c); white-space: nowrap; }
|
||||||
|
.hud-top svg.ic { width: 16px; height: 16px; }
|
||||||
|
.hud-top .val { color: var(--text); font-family: var(--mono); font-size: 15px; letter-spacing: -.02em; }
|
||||||
|
.hud-top .cap { color: var(--dimmer); font-size: 11px; font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.hud-sub { font-size: 11px; color: var(--dim); font-family: var(--mono); margin: 1px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.hud-chip.full { border-color: #6b5a1f; }
|
||||||
|
.hud-chip.full .rate { color: var(--amber); font-weight: 700; letter-spacing: .06em; }
|
||||||
|
.hud-chip.bad { border-color: #6b2236; }
|
||||||
|
.hud-chip.bad .val, .hud-chip.empty .rate { color: var(--red); }
|
||||||
|
.hud-chip.bad .bar i, .hud-chip.empty .bar i { background: var(--red); }
|
||||||
|
.bar { height: 4px; border-radius: 2px; background: #0a1020; overflow: hidden; }
|
||||||
|
.bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--c, var(--cyan)); border-radius: 2px; transition: width .4s linear; }
|
||||||
|
.hud-chip.full .bar i { background: var(--amber); }
|
||||||
|
@media (max-width: 400px) { .hud { gap: 4px; padding: 4px 8px 6px; } .hud-top .cap { display: none; } .hud-top .val { font-size: 14px; } }
|
||||||
|
@media (orientation: landscape) and (max-height: 520px) { .hud { padding-bottom: 4px; } .hud-chip { padding: 4px 8px 5px; } .hud-sub { margin-bottom: 2px; } }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- generic parts */
|
||||||
|
.page { padding: 8px 12px 24px; display: grid; gap: 12px; max-width: 720px; margin: 0 auto; }
|
||||||
|
.pad { padding: 28px 16px; }
|
||||||
|
.card { background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; }
|
||||||
|
.card-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; margin-bottom: 10px; }
|
||||||
|
.card-head h1, .card-head h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .1em; color: var(--dim); font-weight: 650; display: flex; align-items: center; gap: 6px; }
|
||||||
|
.card-head h1 { font-size: 15px; color: var(--text); }
|
||||||
|
.page-head { margin-bottom: 0; }
|
||||||
|
.empty { color: var(--dimmer); font-size: 14px; text-align: center; padding: 10px 6px; }
|
||||||
|
.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||||
|
.kv { display: flex; justify-content: space-between; gap: 12px; padding: 7px 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.kv:last-of-type { border-bottom: 0; }
|
||||||
|
.kv .k { color: var(--dimmer); } .kv .v { text-align: right; overflow-wrap: anywhere; }
|
||||||
|
|
||||||
|
.pill { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; border-radius: 999px; background: var(--panel3); border: 1px solid var(--line2); font-size: 12px; color: var(--dim); max-width: 100%; }
|
||||||
|
.pill svg.ic { width: 13px; height: 13px; }
|
||||||
|
.pill.accent { color: #06222b; background: var(--cyan); border-color: var(--cyan); font-weight: 650; }
|
||||||
|
.pill.green { color: #04241a; background: var(--green); border-color: var(--green); font-weight: 650; }
|
||||||
|
.pill.amber { color: #2b2204; background: var(--amber); border-color: var(--amber); font-weight: 600; }
|
||||||
|
.pill.dim { color: var(--dimmer); background: transparent; }
|
||||||
|
.pill.res-fiber { color: var(--fiber); } .pill.res-hardware { color: var(--hardware); } .pill.res-capital { color: var(--capital); } .pill.res-power { color: var(--power); }
|
||||||
|
.pill-row { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; }
|
||||||
|
|
||||||
|
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 46px; padding: 0 18px; border-radius: 12px; border: 1px solid var(--line2); background: var(--panel3); color: var(--text); font-weight: 600; }
|
||||||
|
.btn:disabled { opacity: .45; cursor: not-allowed; }
|
||||||
|
.btn.primary { background: linear-gradient(180deg, #2fc4e6, #1b97c0); border-color: #55d6f2; color: #03202a; }
|
||||||
|
.btn.primary:disabled { background: var(--panel3); border-color: var(--line2); color: var(--dim); }
|
||||||
|
.btn.danger { background: #3a1620; border-color: #7a2a3f; color: #ffc4d0; }
|
||||||
|
.btn.wide { width: 100%; }
|
||||||
|
.btn.small { min-height: 36px; padding: 0 12px; font-size: 13px; }
|
||||||
|
.btn-row { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 10px; margin-top: 12px; }
|
||||||
|
.icon-btn { width: 44px; height: 44px; flex: none; display: inline-grid; place-items: center; border-radius: 12px; background: transparent; border: 1px solid transparent; color: var(--dim); }
|
||||||
|
.icon-btn:hover { background: var(--panel3); }
|
||||||
|
.linklike { background: none; border: 0; color: var(--cyan); min-height: 44px; text-decoration: underline; text-underline-offset: 3px; width: 100%; }
|
||||||
|
.chip-btn { min-width: 52px; min-height: 40px; border-radius: 999px; background: transparent; border: 1px solid var(--line2); color: var(--dim); padding: 0 14px; }
|
||||||
|
.chip-btn[aria-pressed="true"], .seg-btn[aria-pressed="true"] { background: var(--cyan); border-color: var(--cyan); color: #04222b; font-weight: 700; }
|
||||||
|
.seg { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 6px; }
|
||||||
|
.seg-btn { min-height: 46px; border-radius: 12px; background: var(--panel3); border: 1px solid var(--line2); color: var(--dim); }
|
||||||
|
|
||||||
|
.field { display: grid; gap: 5px; margin-bottom: 12px; }
|
||||||
|
.field-lbl { font-size: 13px; color: var(--dim); }
|
||||||
|
.field-hint { font-size: 12px; color: var(--dimmer); }
|
||||||
|
input[type="text"], input[type="password"], select { width: 100%; min-height: 48px; padding: 0 14px; border-radius: 12px; background: #080e1c; border: 1px solid var(--line2); color: var(--text); font-size: 16px; }
|
||||||
|
input:focus-visible, select:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; border-color: var(--cyan); }
|
||||||
|
.form-error { color: #ffc4d0; background: #3a1620; border: 1px solid #7a2a3f; border-radius: 10px; padding: 9px 12px; font-size: 14px; margin-bottom: 12px; }
|
||||||
|
.notice { color: var(--amber); font-size: 14px; margin-bottom: 12px; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- auth */
|
||||||
|
.screen-auth { display: grid; place-items: center; padding: calc(16px + var(--safe-t)) 16px calc(16px + var(--safe-b)); min-height: 100%; }
|
||||||
|
.auth-card { width: min(100%, 400px); display: grid; gap: 14px; }
|
||||||
|
.auth-logo { display: flex; align-items: center; gap: 14px; justify-content: center; }
|
||||||
|
.auth-name { font-size: 28px; font-weight: 750; letter-spacing: .12em; }
|
||||||
|
.auth-tag { text-align: center; color: var(--dim); }
|
||||||
|
.auth-form { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 18px; padding: 18px 16px 8px; }
|
||||||
|
.auth-h { font-size: 20px; margin-bottom: 14px; }
|
||||||
|
.lang-switch { display: flex; justify-content: center; gap: 8px; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- POP */
|
||||||
|
.cols { display: grid; gap: 12px; padding: 4px 12px 24px; max-width: 1100px; margin: 0 auto; align-items: start; }
|
||||||
|
.col { display: grid; gap: 12px; min-width: 0; }
|
||||||
|
@media (min-width: 760px) { .cols { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); } }
|
||||||
|
.pop-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: -4px 0 4px; }
|
||||||
|
.town-name { font-size: 22px; font-weight: 700; overflow-wrap: anywhere; }
|
||||||
|
.town-select { font-size: 18px; font-weight: 650; }
|
||||||
|
.pop-meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; color: var(--dim); font-size: 13px; }
|
||||||
|
|
||||||
|
.queue { display: grid; gap: 8px; }
|
||||||
|
.q-item { display: flex; align-items: center; gap: 4px; background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding-right: 2px; }
|
||||||
|
.q-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; background: none; border: 0; padding: 8px 6px 8px 10px; text-align: left; min-height: 56px; }
|
||||||
|
.q-main .bar { margin-top: 6px; --c: var(--amber); }
|
||||||
|
.q-main > b { font-size: 15px; color: var(--amber); }
|
||||||
|
.row-ic { width: 38px; height: 38px; flex: none; display: grid; place-items: center; border-radius: 10px; background: var(--panel3); color: var(--cyan); }
|
||||||
|
.row-ic svg.ic { width: 22px; height: 22px; }
|
||||||
|
.row-main { flex: 1; min-width: 0; display: grid; gap: 2px; }
|
||||||
|
.row-title { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.row-title .lv { color: var(--dim); font-size: 13px; }
|
||||||
|
.row-sub { color: var(--dimmer); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
|
||||||
|
.stat-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 10px; }
|
||||||
|
.stat { background: var(--panel2); border-radius: 10px; padding: 7px 10px; display: grid; }
|
||||||
|
.stat small { color: var(--dimmer); font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
|
||||||
|
.stat b { font-family: var(--mono); font-size: 17px; }
|
||||||
|
.good { color: var(--green); } .bad { color: var(--red); }
|
||||||
|
.power-card .bar { height: 8px; --c: var(--power); margin: 6px 0 8px; }
|
||||||
|
.power-status { font-size: 13px; color: var(--dim); }
|
||||||
|
.power-status.warn { color: var(--amber); } .power-status.bad { color: var(--red); }
|
||||||
|
|
||||||
|
.groups { display: grid; gap: 12px; }
|
||||||
|
.group { --c: var(--cyan); }
|
||||||
|
.group.res-fiber { --c: var(--fiber); } .group.res-hardware { --c: var(--hardware); } .group.res-capital { --c: var(--capital); } .group.res-power { --c: var(--power); }
|
||||||
|
.group-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; color: var(--c); }
|
||||||
|
.group-head b { color: var(--text); }
|
||||||
|
.group-rate { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--c); }
|
||||||
|
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(56px, 1fr)); gap: 8px; }
|
||||||
|
.tile { position: relative; aspect-ratio: 1; min-height: 56px; border-radius: 14px; background: var(--panel2); border: 1px solid color-mix(in srgb, var(--c) 35%, var(--line)); color: var(--c); padding: 6px; display: block; text-align: left; overflow: hidden; }
|
||||||
|
.tile.res-fiber { --c: var(--fiber); } .tile.res-hardware { --c: var(--hardware); } .tile.res-capital { --c: var(--capital); } .tile.res-power { --c: var(--power); }
|
||||||
|
.tile-ic { width: 26px; height: 26px; opacity: .95; }
|
||||||
|
.tile-lvl { position: absolute; right: 8px; bottom: 6px; font-family: var(--mono); font-size: 22px; color: var(--text); line-height: 1; }
|
||||||
|
.tile-badge { position: absolute; right: 5px; top: 5px; display: grid; place-items: center; }
|
||||||
|
.tile-badge svg.ic { width: 15px; height: 15px; }
|
||||||
|
.tile-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background: transparent; }
|
||||||
|
.tile-bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--amber); }
|
||||||
|
.tile[data-st="ready"] { border-color: var(--green); box-shadow: 0 0 0 1px rgba(53, 224, 161, .35), 0 0 14px rgba(53, 224, 161, .18); }
|
||||||
|
.tile[data-st="ready"] .tile-badge { color: var(--green); }
|
||||||
|
.tile[data-st="queued"] { border-color: var(--amber); } .tile[data-st="queued"] .tile-badge { color: var(--amber); }
|
||||||
|
.tile[data-st="locked"] { opacity: .65; } .tile[data-st="locked"] .tile-badge { color: var(--dimmer); }
|
||||||
|
.tile[data-st="max"] { border-color: #8a7a2a; }
|
||||||
|
|
||||||
|
.rows { display: grid; gap: 8px; }
|
||||||
|
.row-btn { position: relative; width: 100%; display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; overflow: hidden; }
|
||||||
|
.row-btn[data-st="ready"] { border-color: color-mix(in srgb, var(--green) 70%, var(--line)); }
|
||||||
|
.row-btn[data-st="queued"] { border-color: var(--amber); }
|
||||||
|
.row-btn[data-st="locked"] .row-ic { color: var(--dimmer); }
|
||||||
|
.row-btn .pill { flex: none; max-width: 42%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- sheet */
|
||||||
|
.sheet-wrap { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; justify-content: center; pointer-events: none; }
|
||||||
|
.backdrop { position: absolute; inset: 0; background: rgba(2, 5, 12, .62); opacity: 0; transition: opacity .18s; pointer-events: auto; }
|
||||||
|
.sheet { position: relative; width: min(100%, 520px); max-height: min(86dvh, 720px); overflow-y: auto; background: var(--panel); border: 1px solid var(--line2); border-bottom: 0; border-radius: 20px 20px 0 0; padding: 6px 16px calc(16px + var(--safe-b)); transform: translateY(24px); opacity: 0; transition: transform .2s ease-out, opacity .2s; pointer-events: auto; box-shadow: 0 -10px 40px rgba(0, 0, 0, .5); margin: 0 var(--safe-r) 0 var(--safe-l); }
|
||||||
|
.sheet-wrap.open .backdrop { opacity: 1; }
|
||||||
|
.sheet-wrap.open .sheet { transform: none; opacity: 1; }
|
||||||
|
.sheet-grab { width: 40px; height: 4px; border-radius: 2px; background: var(--line2); margin: 4px auto 6px; }
|
||||||
|
.sheet-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
|
||||||
|
.sheet-title { flex: 1; font-size: 19px; min-width: 0; overflow-wrap: anywhere; }
|
||||||
|
.sheet-icon { width: 40px; height: 40px; border-radius: 12px; background: var(--panel3); display: grid; place-items: center; color: var(--cyan); flex: none; }
|
||||||
|
.sheet-icon.res-fiber { color: var(--fiber); } .sheet-icon.res-hardware { color: var(--hardware); } .sheet-icon.res-capital { color: var(--capital); } .sheet-icon.res-power { color: var(--power); }
|
||||||
|
.sheet-icon svg.ic { width: 24px; height: 24px; }
|
||||||
|
.detail { display: grid; gap: 10px; }
|
||||||
|
.detail-desc { color: var(--dim); }
|
||||||
|
.detail-level { display: flex; justify-content: space-between; align-items: center; gap: 10px; }
|
||||||
|
.lvl-now { font-weight: 700; font-size: 17px; }
|
||||||
|
.lvl-next { display: inline-flex; align-items: center; gap: 4px; color: var(--green); font-size: 14px; }
|
||||||
|
.preview { color: var(--text); background: var(--panel2); border-radius: 10px; padding: 8px 12px; font-size: 14px; }
|
||||||
|
.sub { font-size: 12px; text-transform: uppercase; letter-spacing: .1em; color: var(--dimmer); margin-top: 2px; }
|
||||||
|
.costs { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.cost { display: inline-flex; align-items: center; gap: 6px; background: var(--panel2); border: 1px solid var(--line2); border-radius: 10px; padding: 6px 10px; --c: var(--dim); }
|
||||||
|
.cost.fiber { --c: var(--fiber); } .cost.hardware { --c: var(--hardware); } .cost.capital { --c: var(--capital); }
|
||||||
|
.cost svg.ic { color: var(--c); width: 18px; height: 18px; }
|
||||||
|
.cost b { font-family: var(--mono); }
|
||||||
|
.cost small { color: var(--dimmer); font-size: 11px; }
|
||||||
|
.cost.short { border-color: #7a2a3f; } .cost.short b { color: var(--red); }
|
||||||
|
.meta { justify-content: flex-start; color: var(--dim); }
|
||||||
|
.reqs { display: grid; gap: 6px; }
|
||||||
|
.reqs li { display: flex; align-items: center; gap: 8px; font-size: 14px; }
|
||||||
|
.reqs li.ok { color: var(--green); } .reqs li.miss { color: var(--red); }
|
||||||
|
.reqs small { margin-left: auto; color: var(--dimmer); }
|
||||||
|
.reason { color: var(--amber); font-size: 14px; min-height: 1.4em; }
|
||||||
|
.detail-queue { background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding: 12px; display: grid; gap: 8px; }
|
||||||
|
.detail-queue .bar { --c: var(--amber); height: 6px; }
|
||||||
|
.detail-queue b { color: var(--amber); font-size: 18px; }
|
||||||
|
|
||||||
|
@media (min-width: 700px) and (min-height: 560px) {
|
||||||
|
.sheet-wrap { align-items: center; }
|
||||||
|
.sheet { border-bottom: 1px solid var(--line2); border-radius: 20px; max-height: 86dvh; padding-bottom: 16px; }
|
||||||
|
}
|
||||||
|
@media (orientation: landscape) and (max-height: 520px) {
|
||||||
|
.sheet { max-height: 94dvh; width: min(100%, 560px); }
|
||||||
|
.sheet-grab { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- toasts */
|
||||||
|
#toasts { position: fixed; left: 0; right: 0; bottom: calc(var(--nav-h) + var(--safe-b) + 12px); display: grid; justify-items: center; gap: 8px; z-index: 80; pointer-events: none; padding: 0 16px; }
|
||||||
|
.toast { background: #12203b; border: 1px solid var(--line2); color: var(--text); padding: 10px 16px; border-radius: 12px; font-size: 14px; max-width: 480px; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); transition: opacity .25s, transform .25s; }
|
||||||
|
.toast.ok { border-color: #1a6a4f; background: #0e2b23; }
|
||||||
|
.toast.error { border-color: #7a2a3f; background: #2d1019; color: #ffd0da; }
|
||||||
|
.toast.out { opacity: 0; transform: translateY(8px); }
|
||||||
|
@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) { #toasts { bottom: 14px; left: var(--rail-w); } }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- map */
|
||||||
|
.map-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; cursor: grab; outline: none; user-select: none; -webkit-user-select: none; }
|
||||||
|
.map-canvas.grabbing { cursor: grabbing; }
|
||||||
|
.map-canvas:focus-visible { outline: 2px solid var(--cyan); outline-offset: -2px; }
|
||||||
|
.map-controls { position: absolute; right: 12px; bottom: 14px; display: grid; gap: 8px; z-index: 3; }
|
||||||
|
.map-btn { width: 48px; height: 48px; border-radius: 14px; background: rgba(12, 19, 34, .92); border: 1px solid var(--line2); color: var(--text); display: grid; place-items: center; box-shadow: 0 4px 14px rgba(0, 0, 0, .45); }
|
||||||
|
.map-btn svg.ic { width: 24px; height: 24px; }
|
||||||
|
.map-coords { position: absolute; left: 12px; bottom: 14px; z-index: 3; padding: 4px 10px; border-radius: 999px; background: rgba(12, 19, 34, .85); border: 1px solid var(--line); color: var(--dim); font-size: 12px; pointer-events: none; }
|
||||||
|
.map-legend { position: absolute; left: 10px; top: 8px; z-index: 3; display: flex; flex-wrap: wrap; gap: 4px 12px; padding: 5px 10px; border-radius: 10px; background: rgba(12, 19, 34, .8); border: 1px solid var(--line); font-size: 11px; color: var(--dim); pointer-events: none; max-width: calc(100% - 20px); }
|
||||||
|
.map-legend li { display: flex; align-items: center; gap: 5px; }
|
||||||
|
.lg { width: 10px; height: 10px; display: inline-block; }
|
||||||
|
.lg.you { background: var(--cyan); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); }
|
||||||
|
.lg.rival { background: #e08a4a; clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); }
|
||||||
|
.lg.rural { border: 2px solid var(--capital); border-radius: 50%; }
|
||||||
|
.lg.incumbent { background: #241338; border: 2px solid var(--violet); }
|
||||||
|
@media (max-height: 420px) { .map-legend { display: none; } }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- alerts + settings */
|
||||||
|
.alert-list { display: grid; gap: 8px; }
|
||||||
|
.alert { width: 100%; display: flex; align-items: center; gap: 10px; background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; }
|
||||||
|
.alert.new { border-color: var(--cyan); background: #0c1f33; }
|
||||||
|
.when { font-size: 12px; color: var(--dimmer); flex: none; }
|
||||||
|
.device-list { display: grid; gap: 8px; margin-top: 10px; }
|
||||||
|
.device { display: flex; align-items: center; gap: 10px; background: var(--panel2); border-radius: 12px; padding: 8px 10px; min-height: 56px; }
|
||||||
|
.device .row-sub { white-space: normal; }
|
||||||
|
.card .btn.wide { margin-top: 10px; }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) { .sheet, .backdrop, .toast, .bar i { transition: none; } }
|
||||||
BIN
public/icons/icon-192.png
Normal file
BIN
public/icons/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
BIN
public/icons/icon-512.png
Normal file
BIN
public/icons/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
BIN
public/icons/icon-maskable-512.png
Normal file
BIN
public/icons/icon-maskable-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 90 KiB |
17
public/icons/icon.svg
Normal file
17
public/icons/icon.svg
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||||
|
<defs>
|
||||||
|
<radialGradient id="g" cx="30%" cy="18%" r="95%"><stop offset="0" stop-color="#16315c"/><stop offset="1" stop-color="#070b16"/></radialGradient>
|
||||||
|
</defs>
|
||||||
|
<rect width="512" height="512" rx="112" fill="url(#g)"/>
|
||||||
|
<rect x="20" y="20" width="472" height="472" rx="94" fill="none" stroke="#4de3ff" stroke-opacity=".35" stroke-width="6"/>
|
||||||
|
<!-- region links to the core POP -->
|
||||||
|
<path d="M120 410L256 290M392 410L256 290M150 170L256 290M362 170L256 290" fill="none" stroke="#4de3ff" stroke-width="10" stroke-linecap="round" stroke-opacity=".7"/>
|
||||||
|
<g fill="#0d2038" stroke="#5aa9ff" stroke-width="9">
|
||||||
|
<circle cx="120" cy="410" r="26"/><circle cx="392" cy="410" r="26"/><circle cx="150" cy="170" r="26"/><circle cx="362" cy="170" r="26"/>
|
||||||
|
</g>
|
||||||
|
<!-- the core POP: a hexagon -->
|
||||||
|
<path d="M256 220l54 31v62l-54 31-54-31v-62z" fill="#0d2a44" stroke="#4de3ff" stroke-width="12" stroke-linejoin="round"/>
|
||||||
|
<circle cx="256" cy="282" r="17" fill="#35e0a1"/>
|
||||||
|
<!-- upstream arrow -->
|
||||||
|
<path d="M256 140V70M226 98l30-30 30 30" fill="none" stroke="#ffd24d" stroke-width="13" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
49
public/icons/sprite.svg
Normal file
49
public/icons/sprite.svg
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
|
||||||
|
<!-- UPSTREAM icon sprite. 24x24, stroke/fill currentColor. Referenced as <use href="icons/sprite.svg#i-name">. -->
|
||||||
|
<defs>
|
||||||
|
|
||||||
|
<!-- navigation / ui -->
|
||||||
|
<symbol id="i-pop" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5l7.5 4.3v8.4L12 20.5l-7.5-4.3V7.8z"/><circle fill="currentColor" cx="12" cy="12" r="2.6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5v6M12 14.5v6M4.5 7.8l5.2 3M14.3 13.2l5.2 3M19.5 7.8l-5.2 3M9.7 13.2l-5.2 3" opacity=".55"/></symbol>
|
||||||
|
<symbol id="i-map" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 6l5.5-2 6 2 5.5-2v14l-5.5 2-6-2-5.5 2z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9 4v14M15 6v14"/></symbol>
|
||||||
|
<symbol id="i-bell" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6 17V11a6 6 0 0112 0v6l1.6 1.8H4.4z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10 20.5a2.2 2.2 0 004 0"/></symbol>
|
||||||
|
<symbol id="i-gear" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.2l1.6 2.3 2.7-.7.9 2.7 2.7.9-.7 2.7 2.3 1.6-2.3 1.6.7 2.7-2.7.9-.9 2.7-2.7-.7L12 20.8l-1.6-2.3-2.7.7-.9-2.7-2.7-.9.7-2.7L2.5 12l2.3-1.6-.7-2.7 2.7-.9.9-2.7 2.7.7z"/></symbol>
|
||||||
|
<symbol id="i-x" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M6 6l12 12M18 6L6 18" stroke-width="2.4"/></symbol>
|
||||||
|
<symbol id="i-check" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5 12.5l4.5 4.5L19 7.5" stroke-width="2.6"/></symbol>
|
||||||
|
<symbol id="i-plus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12 5v14M5 12h14" stroke-width="2.4"/></symbol>
|
||||||
|
<symbol id="i-minus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5 12h14" stroke-width="2.4"/></symbol>
|
||||||
|
<symbol id="i-locate" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="6.5"/><circle fill="currentColor" cx="12" cy="12" r="2.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 2.5v3.5M12 18v3.5M2.5 12H6M18 12h3.5"/></symbol>
|
||||||
|
<symbol id="i-logout" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10 4.5H5.5v15H10M14 8l4 4-4 4M18 12H9.5"/></symbol>
|
||||||
|
<symbol id="i-shield" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3l7 3v5.5c0 4.6-3 7.6-7 9.5-4-1.9-7-4.9-7-9.5V6z"/></symbol>
|
||||||
|
<symbol id="i-clock" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 7v5.2l3.4 2"/></symbol>
|
||||||
|
<symbol id="i-pencil" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4.5 19.5l1-4.2L16 4.8a1.8 1.8 0 012.6 0l.6.6a1.8 1.8 0 010 2.6L8.7 18.5z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14.5 6.5l3 3"/></symbol>
|
||||||
|
<symbol id="i-alert" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 4l9 16H3z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 10v4.5M12 17.4v.1"/></symbol>
|
||||||
|
<symbol id="i-lock" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="5.5" y="11" width="13" height="9" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M8.5 11V8a3.5 3.5 0 017 0v3"/></symbol>
|
||||||
|
<symbol id="i-up" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12 19V6M6 11.5l6-6 6 6" stroke-width="2.4"/></symbol>
|
||||||
|
<symbol id="i-refresh" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M19 12a7 7 0 11-2.2-5.1M19 4.5v4.3h-4.3"/></symbol>
|
||||||
|
<symbol id="i-device" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="7" y="3.5" width="10" height="17" rx="2.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10.5 17.5h3"/></symbol>
|
||||||
|
|
||||||
|
<!-- resources -->
|
||||||
|
<symbol id="i-fiber" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5c-3 3.4-3 13.6 0 17M5 6.8c4 1 10 1 14 0" opacity=".6"/></symbol>
|
||||||
|
<symbol id="i-hardware" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="6.5" y="6.5" width="11" height="11" rx="1.8"/><rect fill="currentColor" x="10" y="10" width="4" height="4" rx=".6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9.5 3.5v3M14.5 3.5v3M9.5 17.5v3M14.5 17.5v3M3.5 9.5h3M3.5 14.5h3M17.5 9.5h3M17.5 14.5h3"/></symbol>
|
||||||
|
<symbol id="i-capital" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14.6 9.4c-.5-1-1.4-1.5-2.6-1.5-1.5 0-2.6.8-2.6 2 0 2.7 5.2 1.4 5.2 4.2 0 1.2-1.1 2-2.6 2-1.2 0-2.2-.6-2.7-1.6M12 6.2v1.7M12 16.1v1.7"/></symbol>
|
||||||
|
<symbol id="i-power" viewBox="0 0 24 24"><path fill="currentColor" d="M13.4 2.8L5.5 13.4h5.2l-1 7.8 8.8-11.4h-5.4z"/></symbol>
|
||||||
|
<symbol id="i-battery" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3.5" y="7.5" width="15" height="9" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M21 10.5v3"/><path fill="currentColor" d="M6 10h3v4H6z"/></symbol>
|
||||||
|
|
||||||
|
<!-- buildings: i-b-<type> -->
|
||||||
|
<symbol id="i-b-cable_yard" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M5.5 8.5c3.5 1.6 9.5 1.6 13 0M5.5 15.5c3.5-1.6 9.5-1.6 13 0" opacity=".65"/></symbol>
|
||||||
|
<symbol id="i-b-supply_depot" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 8.2L12 4l8.5 4.2v8.6L12 21l-8.5-4.2z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 8.2L12 12.5l8.5-4.3M12 12.5V21"/></symbol>
|
||||||
|
<symbol id="i-b-sales_office" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 20.5V8.5l6-4v16M10 8.5l10 3.5v8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6.5 11h1.5M6.5 14.5h1.5M13.5 15h3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3 20.5h18"/></symbol>
|
||||||
|
<symbol id="i-b-substation" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3v18M7.5 21l4.5-13 4.5 13M5 8.5h14M7 13.5h10"/><path fill="currentColor" d="M12 3l1.5 2.5h-3z"/></symbol>
|
||||||
|
<symbol id="i-b-core_router" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3.4"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5v5.1M12 15.4v5.1M3.5 12h5.1M15.4 12h5.1M6 6l3.6 3.6M14.4 14.4L18 18M18 6l-3.6 3.6M9.6 14.4L6 18"/><circle fill="currentColor" cx="12" cy="3.5" r="1.4"/><circle fill="currentColor" cx="12" cy="20.5" r="1.4"/><circle fill="currentColor" cx="3.5" cy="12" r="1.4"/><circle fill="currentColor" cx="20.5" cy="12" r="1.4"/></symbol>
|
||||||
|
<symbol id="i-b-rack_hall" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="5" y="3.5" width="14" height="17" rx="1.8"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M5 9.2h14M5 14.8h14M8 6.4h.1M8 12h.1M8 17.7h.1M12 6.4h4.5M12 12h4.5M12 17.7h4.5"/></symbol>
|
||||||
|
<symbol id="i-b-battery_bank" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="6.5" width="16" height="11" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M21.5 10v4"/><path fill="currentColor" d="M5.5 9h2.6v6H5.5zM9.6 9h2.6v6H9.6z"/></symbol>
|
||||||
|
<symbol id="i-b-firewall" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3.5" y="4.5" width="17" height="15" rx="1.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 9.5h17M3.5 14.5h17M9 4.5v5M15 4.5v5M6.5 9.5v5M12 9.5v5M17.5 9.5v5M9 14.5v5M15 14.5v5"/></symbol>
|
||||||
|
<symbol id="i-b-noc" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="4" width="18" height="12.5" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M8 20.5h8M12 16.5v4M5.8 11h3l1.6-3.5 2.4 6 1.6-2.5h3.2"/></symbol>
|
||||||
|
<symbol id="i-b-research_lab" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9.5 3.5h5M10.5 3.5v6L5 19a1.5 1.5 0 001.3 2.2h11.4A1.5 1.5 0 0019 19l-5.5-9.5v-6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7.8 15h8.4"/><circle fill="currentColor" cx="10.5" cy="17.7" r=".9"/><circle fill="currentColor" cx="14" cy="16.7" r=".7"/></symbol>
|
||||||
|
<symbol id="i-b-ops_lab" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="4.5" width="18" height="15" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7 9.5l3.2 2.5L7 14.5M12.5 15h4.5"/></symbol>
|
||||||
|
<symbol id="i-b-internet_exchange" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 8h13M13.5 4.5L17 8l-3.5 3.5M20 16H7M10.5 12.5L7 16l3.5 3.5"/></symbol>
|
||||||
|
<symbol id="i-b-peering_office" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="8.5" cy="12" r="5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="15.5" cy="12" r="5"/></symbol>
|
||||||
|
<symbol id="i-b-rollout_depot" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M2.5 16.5V8h10v8.5M12.5 11h4.2l3 3.2v2.3h-7.2"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="7" cy="17.5" r="2"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="16.5" cy="17.5" r="2"/></symbol>
|
||||||
|
<symbol id="i-b-backbone_node" viewBox="0 0 24 24"><circle fill="currentColor" cx="4.5" cy="12" r="2.1"/><circle fill="currentColor" cx="12" cy="12" r="2.1"/><circle fill="currentColor" cx="19.5" cy="12" r="2.1"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6.6 12h3.3M14.1 12h3.3M12 4.5v5.4M12 14.1v5.4"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="4.5" r="1.4"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="19.5" r="1.4"/></symbol>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 13 KiB |
46
public/index.html
Normal file
46
public/index.html
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="theme-color" content="#070b16">
|
||||||
|
<meta name="color-scheme" content="dark">
|
||||||
|
<meta name="mobile-web-app-capable" content="yes">
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||||
|
<meta name="apple-mobile-web-app-title" content="UPSTREAM">
|
||||||
|
<meta name="description" content="UPSTREAM: build POPs, connect the region and outlast rival network operators.">
|
||||||
|
<title>UPSTREAM</title>
|
||||||
|
<link rel="manifest" href="manifest.webmanifest">
|
||||||
|
<link rel="icon" href="icons/icon.svg" type="image/svg+xml">
|
||||||
|
<link rel="apple-touch-icon" href="icons/icon-192.png">
|
||||||
|
<link rel="stylesheet" href="css/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app" data-state="boot">
|
||||||
|
<header id="topbar">
|
||||||
|
<div class="brand"><span class="brand-mark" aria-hidden="true"></span><span id="title">UPSTREAM</span></div>
|
||||||
|
<span id="netstate" class="netstate" role="status" aria-live="polite" hidden></span>
|
||||||
|
</header>
|
||||||
|
<section id="hud" class="hud" aria-label="Resources" hidden></section>
|
||||||
|
<main id="view"></main>
|
||||||
|
<nav id="nav" aria-label="Main navigation" hidden></nav>
|
||||||
|
</div>
|
||||||
|
<div id="sheet-root"></div>
|
||||||
|
<div id="toasts" role="status" aria-live="polite"></div>
|
||||||
|
<noscript><p style="padding:24px;color:#d3e6ff;font-family:sans-serif">UPSTREAM needs JavaScript.</p></noscript>
|
||||||
|
|
||||||
|
<script src="js/data.js" defer></script>
|
||||||
|
<script src="js/rules.js" defer></script>
|
||||||
|
<script src="js/i18n.js" defer></script>
|
||||||
|
<script src="js/api.js" defer></script>
|
||||||
|
<script src="js/ui.js" defer></script>
|
||||||
|
<script src="js/render.js" defer></script>
|
||||||
|
<script src="js/main.js" defer></script>
|
||||||
|
<script src="js/screens/auth.js" defer></script>
|
||||||
|
<script src="js/screens/pop.js" defer></script>
|
||||||
|
<script src="js/screens/map.js" defer></script>
|
||||||
|
<script src="js/screens/alerts.js" defer></script>
|
||||||
|
<script src="js/screens/settings.js" defer></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
203
public/js/api.js
Normal file
203
public/js/api.js
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* REST client for /api/v1. No DOM; fetch, storage, clock and sleep are injected so Node tests can drive it
|
||||||
|
* (test/client-api.test.js). Loads as a browser script (window.UpstreamApi) and as a Node module.
|
||||||
|
*
|
||||||
|
* const api = UpstreamApi.createApi({ fetch, storage: localStorage });
|
||||||
|
* const me = await api.get('/me');
|
||||||
|
* await api.post('/towns/3/build', { key: 'f1' }, { intent: 'build:3:f1' });
|
||||||
|
* api.serverNow(); // server clock estimate in ms: use this for every countdown
|
||||||
|
* api.on('unauthorized', fn); // token rejected: the shell drops to the login screen
|
||||||
|
* api.on('push', fn); // reserved: the WebSocket client (stage 6) calls api.emit('push', msg)
|
||||||
|
*
|
||||||
|
* Rules it follows (docs/API.md):
|
||||||
|
* - every response carries serverTime; the offset is kept from the lowest-latency sample (replayed idempotent
|
||||||
|
* responses carry the ORIGINAL serverTime and are ignored for this)
|
||||||
|
* - errors are { error: { code, message, details } } and become ApiError with .code; callers switch on code
|
||||||
|
* - mutating POSTs of a logged-in user carry an Idempotency-Key. An "intent" (a stable string like
|
||||||
|
* 'build:3:f1') keeps the same key across calls until the server has given a definite answer, so a tap that
|
||||||
|
* died on a flaky network and is tapped again cannot build twice. Without an intent, one key per call, reused
|
||||||
|
* by that call's retries.
|
||||||
|
* - retries with backoff: network errors, 429 (Retry-After honoured, seconds), 502/503/504 and request_in_progress.
|
||||||
|
* Network errors and 5xx are only retried when repeating is safe (GET, a keyed POST). 429 is always safe.
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) module.exports = factory();
|
||||||
|
else root.UpstreamApi = factory();
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function () {
|
||||||
|
class ApiError extends Error {
|
||||||
|
constructor(code, message, status, details, retryAfter) {
|
||||||
|
super(message || code);
|
||||||
|
this.name = 'ApiError';
|
||||||
|
this.code = code;
|
||||||
|
this.status = status || 0;
|
||||||
|
this.details = details || {};
|
||||||
|
this.retryAfter = retryAfter || 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEY_RE = /^[A-Za-z0-9_.:-]{8,64}$/;
|
||||||
|
|
||||||
|
function defaultHex() {
|
||||||
|
const c = typeof globalThis !== 'undefined' && globalThis.crypto;
|
||||||
|
if (c && c.getRandomValues) {
|
||||||
|
const a = new Uint8Array(12);
|
||||||
|
c.getRandomValues(a);
|
||||||
|
return Array.prototype.map.call(a, (b) => (b < 16 ? '0' : '') + b.toString(16)).join('');
|
||||||
|
}
|
||||||
|
let s = '';
|
||||||
|
for (let i = 0; i < 24; i++) s += Math.floor(Math.random() * 16).toString(16);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createApi(opts) {
|
||||||
|
opts = opts || {};
|
||||||
|
const doFetch = opts.fetch;
|
||||||
|
const now = opts.now || Date.now;
|
||||||
|
const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
||||||
|
const base = (opts.base || 'api/v1').replace(/\/$/, '');
|
||||||
|
const tokenKey = opts.tokenKey || 'upstream.token';
|
||||||
|
const maxRetries = opts.maxRetries === undefined ? 4 : opts.maxRetries;
|
||||||
|
const maxWaitMs = opts.maxWaitMs || 15000; // a Retry-After longer than this is given to the caller instead
|
||||||
|
const hex = opts.randomHex || defaultHex;
|
||||||
|
const jitter = opts.jitter || (() => Math.random());
|
||||||
|
|
||||||
|
// ---- token (storage can throw or be empty in private windows: stay usable from memory)
|
||||||
|
let memToken = null;
|
||||||
|
const store = opts.storage;
|
||||||
|
function getToken() {
|
||||||
|
if (memToken) return memToken;
|
||||||
|
try { return (store && store.getItem(tokenKey)) || null; } catch (e) { return null; }
|
||||||
|
}
|
||||||
|
function setToken(t) {
|
||||||
|
memToken = t || null;
|
||||||
|
try { if (store) { if (t) store.setItem(tokenKey, t); else store.removeItem(tokenKey); } } catch (e) { /* memory only */ }
|
||||||
|
}
|
||||||
|
const clearToken = () => setToken(null);
|
||||||
|
|
||||||
|
// ---- events
|
||||||
|
const handlers = {};
|
||||||
|
function on(evt, fn) {
|
||||||
|
(handlers[evt] = handlers[evt] || new Set()).add(fn);
|
||||||
|
return () => off(evt, fn);
|
||||||
|
}
|
||||||
|
function off(evt, fn) { if (handlers[evt]) handlers[evt].delete(fn); }
|
||||||
|
function emit(evt, data) {
|
||||||
|
if (!handlers[evt]) return;
|
||||||
|
for (const fn of Array.from(handlers[evt])) { try { fn(data); } catch (e) { /* a listener must not break the client */ } }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- server clock
|
||||||
|
let offset = 0, bestRtt = null, bestAt = 0, haveOffset = false;
|
||||||
|
function observeServerTime(serverTime, t0, t1) {
|
||||||
|
if (!Number.isFinite(serverTime)) return;
|
||||||
|
const rtt = Math.max(0, t1 - t0);
|
||||||
|
if (bestRtt === null || rtt <= bestRtt || t1 - bestAt > 5 * 60 * 1000) {
|
||||||
|
offset = serverTime - (t0 + t1) / 2;
|
||||||
|
bestRtt = rtt; bestAt = t1; haveOffset = true;
|
||||||
|
emit('offset', offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const serverNow = () => now() + offset;
|
||||||
|
|
||||||
|
// ---- idempotency keys
|
||||||
|
const intents = new Map();
|
||||||
|
const newKey = () => 'u' + hex();
|
||||||
|
function keyFor(intent) {
|
||||||
|
if (!intent) return newKey();
|
||||||
|
let k = intents.get(intent);
|
||||||
|
if (!k) { k = newKey(); intents.set(intent, k); }
|
||||||
|
return k;
|
||||||
|
}
|
||||||
|
|
||||||
|
function backoff(attempt) { return Math.round(400 * Math.pow(2, attempt) * (0.75 + jitter() * 0.5)); }
|
||||||
|
|
||||||
|
let offline = false;
|
||||||
|
function setOffline(v) { if (v !== offline) { offline = v; emit(v ? 'offline' : 'online'); } }
|
||||||
|
|
||||||
|
function buildUrl(path, query) {
|
||||||
|
let u = base + (path[0] === '/' ? path : '/' + path);
|
||||||
|
if (query) {
|
||||||
|
const p = [];
|
||||||
|
for (const k of Object.keys(query)) if (query[k] !== undefined && query[k] !== null) p.push(encodeURIComponent(k) + '=' + encodeURIComponent(query[k]));
|
||||||
|
if (p.length) u += '?' + p.join('&');
|
||||||
|
}
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(method, path, o) {
|
||||||
|
o = o || {};
|
||||||
|
const authed = o.auth !== false;
|
||||||
|
const token = authed ? getToken() : null;
|
||||||
|
const hasBody = o.body !== undefined && method !== 'GET';
|
||||||
|
const keyed = method === 'POST' && !!token;
|
||||||
|
const key = keyed ? keyFor(o.intent) : null;
|
||||||
|
const safeToRepeat = method === 'GET' || keyed;
|
||||||
|
const headers = { Accept: 'application/json' };
|
||||||
|
if (token) headers.Authorization = 'Bearer ' + token;
|
||||||
|
if (hasBody) headers['Content-Type'] = 'application/json';
|
||||||
|
if (key) headers['Idempotency-Key'] = key;
|
||||||
|
const init = { method, headers, cache: 'no-store' };
|
||||||
|
if (hasBody) init.body = JSON.stringify(o.body);
|
||||||
|
const url = buildUrl(path, o.query);
|
||||||
|
const retries = o.retries === undefined ? maxRetries : o.retries;
|
||||||
|
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
const t0 = now();
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await doFetch(url, init);
|
||||||
|
} catch (e) {
|
||||||
|
setOffline(true);
|
||||||
|
if (attempt < retries && (safeToRepeat || method === 'DELETE')) { await sleep(backoff(attempt)); continue; }
|
||||||
|
throw new ApiError('network_error', String(e && e.message || e), 0); // intent key is kept: same tap, same key
|
||||||
|
}
|
||||||
|
const t1 = now();
|
||||||
|
let body = null;
|
||||||
|
try { body = await res.json(); } catch (e) { body = null; }
|
||||||
|
const replay = res.headers && res.headers.get && res.headers.get('Idempotent-Replay');
|
||||||
|
if (body && !replay) observeServerTime(body.serverTime, t0, t1);
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
setOffline(false);
|
||||||
|
if (o.intent) intents.delete(o.intent);
|
||||||
|
return body || {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const err = body && body.error ? body.error : {};
|
||||||
|
const code = err.code || (res.status === 429 ? 'rate_limited' : 'http_' + res.status);
|
||||||
|
let retryAfter = 0;
|
||||||
|
const ra = res.headers && res.headers.get ? Number(res.headers.get('Retry-After')) : NaN;
|
||||||
|
if (Number.isFinite(ra) && ra > 0) retryAfter = ra;
|
||||||
|
else if (err.details && Number(err.details.retryAfter) > 0) retryAfter = Number(err.details.retryAfter);
|
||||||
|
|
||||||
|
// 429 was refused before doing anything, so it is always safe to repeat.
|
||||||
|
if (res.status === 429 && attempt < retries) {
|
||||||
|
const wait = retryAfter ? retryAfter * 1000 : backoff(attempt);
|
||||||
|
if (wait <= maxWaitMs) { await sleep(wait); continue; }
|
||||||
|
}
|
||||||
|
if ([502, 503, 504].includes(res.status) && attempt < retries && safeToRepeat) { await sleep(backoff(attempt)); continue; }
|
||||||
|
if (code === 'request_in_progress' && attempt < retries) { await sleep(500 + backoff(attempt)); continue; }
|
||||||
|
|
||||||
|
setOffline(false); // the server answered: the network is fine
|
||||||
|
if (o.intent && res.status !== 429 && res.status < 500) intents.delete(o.intent); // a definite answer ends the intent
|
||||||
|
if (res.status === 401 && token && code === 'unauthorized') { clearToken(); emit('unauthorized', {}); }
|
||||||
|
throw new ApiError(code, err.message, res.status, err.details, retryAfter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
request,
|
||||||
|
get: (path, query, o) => request('GET', path, Object.assign({ query }, o)),
|
||||||
|
post: (path, body, o) => request('POST', path, Object.assign({ body: body === undefined ? {} : body }, o)),
|
||||||
|
del: (path, o) => request('DELETE', path, o),
|
||||||
|
getToken, setToken, clearToken, hasToken: () => !!getToken(),
|
||||||
|
on, off, emit,
|
||||||
|
serverNow, hasServerTime: () => haveOffset, serverOffset: () => offset,
|
||||||
|
pendingIntents: () => Array.from(intents.keys()),
|
||||||
|
isValidKey: (k) => KEY_RE.test(k),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { createApi, ApiError };
|
||||||
|
}));
|
||||||
|
|
@ -94,6 +94,47 @@
|
||||||
// AS numbers come from the 32-bit private range (RFC 6996). Display name only.
|
// AS numbers come from the 32-bit private range (RFC 6996). Display name only.
|
||||||
const AS_RANGE = { min: 4200000000, max: 4294967294 };
|
const AS_RANGE = { min: 4200000000, max: 4294967294 };
|
||||||
|
|
||||||
|
// Alliances, diplomacy, messages (stage 5). Roles are listed most senior first. `permissions` maps an action to the
|
||||||
|
// roles allowed to do it; rules.allianceCan reads it. Times in hours are at world speed 1x unless noted "real".
|
||||||
|
const SOCIAL = {
|
||||||
|
roles: ['leader', 'diplomat', 'officer', 'member'],
|
||||||
|
permissions: {
|
||||||
|
invite: ['leader', 'officer'],
|
||||||
|
cancelInvite: ['leader', 'officer'],
|
||||||
|
viewInvites: ['leader', 'officer'],
|
||||||
|
kick: ['leader', 'officer'], // and only members the actor outranks
|
||||||
|
setRole: ['leader'],
|
||||||
|
transfer: ['leader'],
|
||||||
|
diplomacy: ['leader', 'diplomat'],
|
||||||
|
editNotes: ['leader', 'diplomat', 'officer'],
|
||||||
|
broadcast: ['leader', 'diplomat', 'officer', 'member'],
|
||||||
|
disband: ['leader'],
|
||||||
|
},
|
||||||
|
allianceBaseSize: 10, // size cap = base + perLevel * Peering office level (best POP of the leader)
|
||||||
|
allianceSizePerLevel: 2,
|
||||||
|
minPeeringLevel: 1, // needed to found or join
|
||||||
|
nameLen: [3, 30], tagLen: [2, 5],
|
||||||
|
inviteTtlHours: 168, // real time, not divided by world speed
|
||||||
|
proposalTtlHours: 72, // real time
|
||||||
|
maxPendingInvites: 25,
|
||||||
|
maxNotes: 10, noteMax: 1000,
|
||||||
|
// Diplomacy. from -> to -> how the change happens: 'immediate' (one side decides), 'proposal' (the other side
|
||||||
|
// must accept) or 'delayed' (one side cancels, takes pactCancelHours / world speed). Missing = not allowed.
|
||||||
|
diplomacyStates: ['war', 'neutral', 'nap', 'confed'],
|
||||||
|
diplomacyMoves: {
|
||||||
|
neutral: { war: 'immediate', nap: 'proposal', confed: 'proposal' },
|
||||||
|
nap: { neutral: 'delayed', war: 'delayed', confed: 'proposal' },
|
||||||
|
confed: { neutral: 'delayed', nap: 'delayed', war: 'delayed' },
|
||||||
|
war: { neutral: 'proposal', nap: 'proposal' },
|
||||||
|
},
|
||||||
|
pactCancelHours: 24,
|
||||||
|
// Messages: plain text, DB-backed send limits per sender (counted over the window, real time).
|
||||||
|
messageMax: 2000,
|
||||||
|
messageLimits: { dm10min: 15, dmHour: 60, broadcastHour: 20 },
|
||||||
|
maxBlocks: 100,
|
||||||
|
rankingsPageMax: 100,
|
||||||
|
};
|
||||||
|
|
||||||
const WORLD_DEFAULTS = {
|
const WORLD_DEFAULTS = {
|
||||||
name: 'World 1',
|
name: 'World 1',
|
||||||
speed: 1,
|
speed: 1,
|
||||||
|
|
@ -101,6 +142,99 @@
|
||||||
preset: 'standard',
|
preset: 'standard',
|
||||||
};
|
};
|
||||||
|
|
||||||
return { HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
|
// ------------------------------------------------------------------ military (stages 3 and 4)
|
||||||
BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS };
|
// Units. Stats: attack, defence, speed (tiles/hour at 1x), carry (loot per unit), draw (power points/hour while
|
||||||
|
// stationed), cost (per unit), time (seconds per unit at 1x, before building level), building (where it is trained),
|
||||||
|
// requires (all must hold; the training building is always required at level 1). `fixed: true` = never moves.
|
||||||
|
// role: scout | defender | attacker | siege | settler | conquest. Ids are generic; i18n.js holds the names.
|
||||||
|
const UNITS = {
|
||||||
|
port_scanner: { role: 'scout', building: 'noc', attack: 0, defence: 1, speed: 20, carry: 0, draw: 1, cost: { fiber: 30, hardware: 30, capital: 20 }, time: 90, requires: [{ type: 'noc', level: 1 }] },
|
||||||
|
soc_analyst: { role: 'defender', building: 'noc', attack: 5, defence: 25, speed: 7, carry: 0, draw: 1, cost: { fiber: 60, hardware: 20, capital: 10 }, time: 120, requires: [{ type: 'noc', level: 1 }] },
|
||||||
|
blue_team: { role: 'defender', building: 'noc', attack: 10, defence: 80, speed: 5, carry: 0, draw: 2, cost: { fiber: 100, hardware: 90, capital: 50 }, time: 300, requires: [{ type: 'noc', level: 5 }, { type: 'research_lab', level: 2 }] },
|
||||||
|
honeypot: { role: 'defender', building: 'noc', attack: 0, defence: 100, speed: 0, carry: 0, draw: 1, cost: { fiber: 120, hardware: 80, capital: 40 }, time: 280, requires: [{ type: 'noc', level: 3 }, { type: 'research_lab', level: 1 }], fixed: true },
|
||||||
|
script_crew: { role: 'attacker', building: 'ops_lab', attack: 40, defence: 10, speed: 8, carry: 50, draw: 1, cost: { fiber: 80, hardware: 40, capital: 30 }, time: 180, requires: [{ type: 'ops_lab', level: 1 }] },
|
||||||
|
botnet: { role: 'attacker', building: 'ops_lab', attack: 90, defence: 25, speed: 14, carry: 150, draw: 3, cost: { fiber: 200, hardware: 160, capital: 120 }, time: 420, requires: [{ type: 'ops_lab', level: 5 }, { type: 'research_lab', level: 5 }] },
|
||||||
|
ddos_rig: { role: 'siege', building: 'ops_lab', attack: 60, defence: 20, speed: 5, carry: 0, draw: 3, cost: { fiber: 300, hardware: 250, capital: 100 }, time: 600, requires: [{ type: 'ops_lab', level: 8 }, { type: 'research_lab', level: 6 }] },
|
||||||
|
exploit_kit: { role: 'siege', building: 'ops_lab', attack: 40, defence: 10, speed: 5, carry: 0, draw: 3, cost: { fiber: 280, hardware: 300, capital: 150 }, time: 720, requires: [{ type: 'ops_lab', level: 10 }, { type: 'research_lab', level: 8 }] },
|
||||||
|
rollout_crew: { role: 'settler', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 400, hardware: 300, capital: 300 }, time: 900, requires: [{ type: 'rollout_depot', level: 1 }] },
|
||||||
|
ma_team: { role: 'conquest', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 700, hardware: 600, capital: 800 }, time: 1200, requires: [{ type: 'rollout_depot', level: 5 }] },
|
||||||
|
};
|
||||||
|
// Display / UI order.
|
||||||
|
const UNIT_ORDER = ['port_scanner', 'soc_analyst', 'blue_team', 'honeypot', 'script_crew', 'botnet', 'ddos_rig', 'exploit_kit', 'rollout_crew', 'ma_team'];
|
||||||
|
|
||||||
|
const MILITARY = {
|
||||||
|
researchPerLevel: 0.05, // +5% attack or defence per research level of one unit type
|
||||||
|
trainSpeedPerLevel: 0.03, // training time / (1 + 0.03 * level of the training building)
|
||||||
|
maxTrainQueue: 8, // batches waiting per training building
|
||||||
|
maxBatch: 5000,
|
||||||
|
defenceBase: 10, // flat defence of any POP, before the firewall multiplier
|
||||||
|
rigFirewallDivisor: 10, // every 10 DDoS rigs lower the effective firewall by one level
|
||||||
|
lossExponent: 1.5,
|
||||||
|
raidLossFactor: 0.5, // raid: both sides lose 0.5 * (weak/strong)^1.5
|
||||||
|
cachePerLevel: 0.10, // Rack hall hides 10% of the stock per level from raids ...
|
||||||
|
cacheMax: 0.5, // ... up to 50%
|
||||||
|
kitsMin: 5, // exploit kits (survivors) needed to damage a building at all
|
||||||
|
kitsPerLevel: 20, // levels destroyed = max(1, floor(kits / 20))
|
||||||
|
loyaltyDrop: [15, 30], // inclusive range, rolled from the world seed
|
||||||
|
scanBuildingsRatio: 2, // attacking scanners needed per defending scanner to see buildings
|
||||||
|
scanLossExponent: 1.5,
|
||||||
|
recallWindowMs: 90 * 1000,
|
||||||
|
reportRetentionMs: 14 * 24 * HOUR_MS, // real time
|
||||||
|
pointsPerCost: 0.01, // battle points per resource point of killed units (operator_stats)
|
||||||
|
decommissionHours: 24, // offline this long (divided by world speed) and units are decommissioned
|
||||||
|
batteryEpsilon: 1e-6,
|
||||||
|
maxLists: 200,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Research: +5% (MILITARY.researchPerLevel) attack or defence for ONE unit type per level, per POP, in the Research lab.
|
||||||
|
// Level n needs a Research lab of level n + labOffset. One research at a time per POP.
|
||||||
|
const RESEARCH = {
|
||||||
|
stats: ['attack', 'defence'],
|
||||||
|
maxLevel: 10,
|
||||||
|
labOffset: 2,
|
||||||
|
costFactor: 8, // times the unit's own cost, per level, growing with costGrowth
|
||||||
|
costGrowth: 1.35,
|
||||||
|
timeBase: 1800, // seconds at level 1
|
||||||
|
timeGrowth: 1.3,
|
||||||
|
labSpeedPerLevel: 0.03,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Founding and conquering POPs (stage 4).
|
||||||
|
const EXPANSION = {
|
||||||
|
settleUnit: 'rollout_crew',
|
||||||
|
crews: 3, // exactly this many found a POP; consumed
|
||||||
|
maxDistance: 15, // from any own POP
|
||||||
|
startResources: { fiber: 250, hardware: 250, capital: 250 }, // "1 h of resources" for a POP that produces nothing yet
|
||||||
|
foundedLoyalty: 100,
|
||||||
|
conqueredLoyalty: 25,
|
||||||
|
conquestUnit: 'ma_team', // one per takeover counts and is used up when it lowers loyalty
|
||||||
|
};
|
||||||
|
|
||||||
|
// Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level.
|
||||||
|
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 500 };
|
||||||
|
|
||||||
|
// Which unit roles may go on which movement type.
|
||||||
|
const MOVE_ROLES = {
|
||||||
|
scan: ['scout'],
|
||||||
|
raid: ['attacker', 'defender'],
|
||||||
|
attack: ['attacker', 'defender', 'siege'],
|
||||||
|
takeover: ['attacker', 'defender', 'siege', 'conquest'],
|
||||||
|
reinforce: ['scout', 'defender', 'attacker', 'siege', 'settler', 'conquest'],
|
||||||
|
settle: ['settler'],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Incumbent (NPC) sites: static defence that grows with world age. Taking one (first time per operator) gives a
|
||||||
|
// one-time Hardware bonus; each distinct site taken adds +10% research speed, up to researchSpeedMax.
|
||||||
|
const INCUMBENT = {
|
||||||
|
baseDefence: 600,
|
||||||
|
variance: 0.25, // per-site factor 1 +- variance, from the world seed
|
||||||
|
perDayGrowth: 0.04, // +4% of base per world day (world days = real days * speed)
|
||||||
|
scanStrength: 12, // counts as this many scanners when scanned
|
||||||
|
hardwareBonus: 2500,
|
||||||
|
researchSpeedBonus: 0.10,
|
||||||
|
researchSpeedMax: 0.5,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
|
||||||
|
SOCIAL, BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS };
|
||||||
}));
|
}));
|
||||||
|
|
|
||||||
376
public/js/i18n.js
Normal file
376
public/js/i18n.js
Normal file
|
|
@ -0,0 +1,376 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* UPSTREAM strings (en + nb) and number/time formatting. Pure: no DOM, no storage, no Date.now(). Loads as a browser
|
||||||
|
* script (window.UpstreamI18n) and as a Node module (the key-parity test lives in test/client-i18n.test.js).
|
||||||
|
*
|
||||||
|
* Player-facing names of buildings, resources and tile types live ONLY here (and as ids in data.js); game logic uses
|
||||||
|
* the generic ids. Keys are flat dotted strings. `{name}` placeholders are filled by t(). Both languages must have
|
||||||
|
* identical key sets and identical placeholders: the test enforces it.
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) module.exports = factory();
|
||||||
|
else root.UpstreamI18n = factory();
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function () {
|
||||||
|
const LANGS = ['en', 'nb'];
|
||||||
|
|
||||||
|
const en = {
|
||||||
|
'app.name': 'UPSTREAM',
|
||||||
|
'app.tagline': 'Build your POP. Connect the region. Outlast the competition.',
|
||||||
|
|
||||||
|
'nav.pop': 'POP', 'nav.map': 'Map', 'nav.alerts': 'Alerts', 'nav.settings': 'Settings', 'nav.label': 'Main navigation',
|
||||||
|
'screen.pop': 'Your POP', 'screen.map': 'Region map', 'screen.alerts': 'Alerts', 'screen.settings': 'Settings',
|
||||||
|
|
||||||
|
'common.cancel': 'Cancel', 'common.close': 'Close', 'common.back': 'Back', 'common.save': 'Save', 'common.confirm': 'Confirm',
|
||||||
|
'common.loading': 'Loading…', 'common.retry': 'Retry', 'common.none': 'None', 'common.yes': 'Yes', 'common.no': 'No',
|
||||||
|
'common.offline': 'Connection lost. Retrying…', 'common.online': 'Back online.',
|
||||||
|
'common.perHour': '/h', 'common.tiles': 'tiles',
|
||||||
|
|
||||||
|
'res.fiber': 'Fiber', 'res.hardware': 'Hardware', 'res.capital': 'Capital', 'res.power': 'Power', 'res.battery': 'Battery',
|
||||||
|
|
||||||
|
'tile.land': 'Open land', 'tile.rural': 'Unconnected rural area', 'tile.incumbent': 'Legacy incumbent site', 'tile.pop': 'POP', 'tile.void': 'Off the map',
|
||||||
|
|
||||||
|
'building.cable_yard.name': 'Cable yard',
|
||||||
|
'building.cable_yard.desc': 'Spools, reels and a suspicious amount of duct tape. Produces Fiber.',
|
||||||
|
'building.supply_depot.name': 'Supply depot',
|
||||||
|
'building.supply_depot.desc': 'Racks of spare parts nobody dares to count. Produces Hardware.',
|
||||||
|
'building.sales_office.name': 'Sales office',
|
||||||
|
'building.sales_office.desc': 'Convinces customers that 99.9% is a lot of nines. Produces Capital.',
|
||||||
|
'building.substation.name': 'Substation',
|
||||||
|
'building.substation.desc': 'Turns mains hum into power points. Everything you build draws from it.',
|
||||||
|
'building.core_router.name': 'Core router',
|
||||||
|
'building.core_router.desc': 'The thing everything else routes through. Shortens all build times.',
|
||||||
|
'building.rack_hall.name': 'Rack hall',
|
||||||
|
'building.rack_hall.desc': 'Floor space with good airflow. Sets how much Fiber, Hardware and Capital you can store.',
|
||||||
|
'building.battery_bank.name': 'Battery bank',
|
||||||
|
'building.battery_bank.desc': 'Buys you time when power is short. Sets the power buffer.',
|
||||||
|
'building.firewall.name': 'Firewall',
|
||||||
|
'building.firewall.desc': 'Default deny, mostly. Boosts the defence of the whole POP.',
|
||||||
|
'building.noc.name': 'NOC',
|
||||||
|
'building.noc.desc': 'Screens full of green dots and one red one. Trains defensive crews.',
|
||||||
|
'building.research_lab.name': 'Research lab',
|
||||||
|
'building.research_lab.desc': 'Where the clever ideas get a budget. Unlocks units and upgrades.',
|
||||||
|
'building.ops_lab.name': 'Ops lab',
|
||||||
|
'building.ops_lab.desc': 'Tools for the operations people do not talk about. Trains offensive units.',
|
||||||
|
'building.internet_exchange.name': 'Internet exchange',
|
||||||
|
'building.internet_exchange.desc': 'Where everyone meets and pretends not to compete. Trade between POPs.',
|
||||||
|
'building.peering_office.name': 'Peering office',
|
||||||
|
'building.peering_office.desc': 'Handshakes and mutual benefit. Found or join an alliance.',
|
||||||
|
'building.rollout_depot.name': 'Rollout depot',
|
||||||
|
'building.rollout_depot.desc': 'Trucks, trenchers and optimism. Trains the crews that found new POPs.',
|
||||||
|
'building.backbone_node.name': 'Backbone node',
|
||||||
|
'building.backbone_node.desc': 'The end-game building. Level 100 wins the world.',
|
||||||
|
|
||||||
|
'pop.capital': 'Capital POP',
|
||||||
|
'pop.rename': 'Rename POP', 'pop.rename.label': 'POP name', 'pop.rename.done': 'POP renamed.',
|
||||||
|
'pop.coords': 'x {x} · y {y}',
|
||||||
|
'pop.loyalty': 'Customer loyalty', 'pop.footprint': 'Footprint', 'pop.footprintPerDay': '+{n}/day',
|
||||||
|
'pop.queue.title': 'Build queue', 'pop.queue.slots': '{used}/{total} slots',
|
||||||
|
'pop.queue.empty': 'Nothing under construction. An idle network is not the same as a healthy one.',
|
||||||
|
'pop.queue.to': 'to level {n}', 'pop.queue.cancel': 'Cancel build',
|
||||||
|
'pop.fields.title': 'Resource fields', 'pop.fields.group': '{name} · {n} fields',
|
||||||
|
'pop.infra.title': 'Infrastructure',
|
||||||
|
'pop.level': 'Lv {n}', 'pop.notBuilt': 'Not built', 'pop.max': 'Max', 'pop.inQueue': 'Building',
|
||||||
|
'pop.upgradeReady': 'Can upgrade', 'pop.locked': 'Requirements missing',
|
||||||
|
'pop.load.error': 'Could not load this POP.',
|
||||||
|
'pop.noTown': 'No POP on this account yet.',
|
||||||
|
'pop.bonus': 'Rural bonus', 'pop.bonus.none': 'No rural areas in reach',
|
||||||
|
|
||||||
|
'power.title': 'Power', 'power.out': 'Output', 'power.draw': 'Draw', 'power.net': 'Net', 'power.buffer': 'Buffer',
|
||||||
|
'power.ok': 'Stable', 'power.draining': 'Draining: empty in {t}', 'power.charging': 'Charging: full in {t}', 'power.full': 'Buffer full',
|
||||||
|
'power.empty': 'Buffer empty: units offline', 'power.unit': 'pts',
|
||||||
|
|
||||||
|
'sheet.level': 'Level {n}', 'sheet.nextLevel': 'Next: level {n}',
|
||||||
|
'sheet.cost': 'Cost', 'sheet.time': 'Build time', 'sheet.requires': 'Requires', 'sheet.have': 'have {n}',
|
||||||
|
'sheet.build': 'Build level {n}', 'sheet.upgrade': 'Upgrade to level {n}', 'sheet.building': 'Building…',
|
||||||
|
'sheet.maxed': 'Fully upgraded', 'sheet.underway': 'Under construction', 'sheet.done': 'Done in {t}',
|
||||||
|
'sheet.affordableIn': 'Affordable in {t}', 'sheet.capTooLow': 'Needs a bigger Rack hall (it holds {cap})',
|
||||||
|
'sheet.cancel': 'Cancel this build', 'sheet.cancel.confirm': 'Cancel {name} to level {n}?',
|
||||||
|
'sheet.cancel.refund': '80% of the cost comes back to the POP.', 'sheet.cancel.keep': 'Keep building',
|
||||||
|
'sheet.built': 'Queued {name} to level {n}.', 'sheet.cancelled': 'Build cancelled. Refund added.',
|
||||||
|
'sheet.preview.output': 'Output {a} → {b} per hour', 'sheet.preview.storage': 'Storage {a} → {b}',
|
||||||
|
'sheet.preview.battery': 'Power buffer {a} → {b}', 'sheet.preview.core': 'Build time ×{a} → ×{b}',
|
||||||
|
'sheet.preview.core2': 'Level {n} opens a second build slot.', 'sheet.preview.draw': 'Power draw +{n}',
|
||||||
|
'sheet.preview.firewall': 'Defence ×{a} → ×{b}', 'sheet.preview.output.now': 'Output now: {a} per hour',
|
||||||
|
|
||||||
|
'map.centre': 'Centre on my POP', 'map.zoomIn': 'Zoom in', 'map.zoomOut': 'Zoom out',
|
||||||
|
'map.label': 'Region map. Drag to pan, pinch or scroll to zoom, tap a tile for details.',
|
||||||
|
'map.noWorld': 'This account has not joined a world yet.', 'map.error': 'Could not load part of the map.',
|
||||||
|
'map.scanning': 'Scanning…', 'map.legend.rural': 'Rural', 'map.legend.incumbent': 'Incumbent', 'map.legend.you': 'You', 'map.legend.rival': 'Rival',
|
||||||
|
'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} tiles from your capital',
|
||||||
|
'map.info.land': 'Nothing here yet. Not a single strand of fibre.',
|
||||||
|
'map.info.rural': 'POPs within {n} tiles get +{p}% {res} output while they stay connected.',
|
||||||
|
'map.info.incumbent': 'A legacy telco stronghold. It never attacks. It does not need to.',
|
||||||
|
'map.info.operator': 'Operator', 'map.info.as': 'AS number', 'map.info.yours': 'Your POP', 'map.info.rival': 'Rival operator',
|
||||||
|
'map.info.protected': 'Beginner protection, no attacks in or out.', 'map.info.open': 'Open POP', 'map.info.capital': 'Capital',
|
||||||
|
|
||||||
|
'alerts.empty': 'All quiet on the wire.', 'alerts.error': 'Could not load alerts.', 'alerts.new': 'new',
|
||||||
|
'alerts.build_done': '{name} reached level {level}', 'alerts.build_done.in': 'in {town}',
|
||||||
|
'alerts.unknown': 'Event: {type}', 'alerts.more': 'Older alerts hidden', 'alerts.count': '{n} unread',
|
||||||
|
|
||||||
|
'settings.language': 'Language', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)',
|
||||||
|
'settings.account': 'Account', 'settings.username': 'Username', 'settings.operator': 'Operator', 'settings.as': 'AS number', 'settings.world': 'World',
|
||||||
|
'settings.worldInfo': '{name} · {speed}× speed · radius {r}',
|
||||||
|
'settings.devices': 'Devices', 'settings.devices.hint': 'Each device holds its own token. Revoke one and that device is logged out.',
|
||||||
|
'settings.device.current': 'This device', 'settings.device.unnamed': 'Unnamed device', 'settings.device.revoke': 'Revoke',
|
||||||
|
'settings.device.revoked': 'Device revoked.', 'settings.device.lastUsed': 'Last used {t}', 'settings.device.created': 'Added {t}',
|
||||||
|
'settings.logout': 'Log out', 'settings.logout.confirm': 'Log out on this device?',
|
||||||
|
'settings.about': 'About', 'settings.about.text': 'UPSTREAM is a hobby project. Fictional operators only; any resemblance to real networks is a routing leak.',
|
||||||
|
|
||||||
|
'auth.login': 'Log in', 'auth.signup': 'Sign up', 'auth.username': 'Username', 'auth.password': 'Password',
|
||||||
|
'auth.invite': 'Invite code', 'auth.invite.hint': 'This server needs an invite code to sign up.',
|
||||||
|
'auth.toSignup': 'New operator? Create an account', 'auth.toLogin': 'Already peering? Log in',
|
||||||
|
'auth.username.hint': '3-20 letters, digits, _ or -', 'auth.password.hint': 'At least 8 characters',
|
||||||
|
'auth.working': 'Working…', 'auth.expired': 'Your session ended. Log in again.',
|
||||||
|
'auth.welcome': 'Welcome, operator.',
|
||||||
|
|
||||||
|
'time.d': 'd', 'time.h': 'h', 'time.m': 'm', 'time.s': 's',
|
||||||
|
'time.now': 'just now', 'time.ago': '{t} ago', 'time.in': 'in {t}',
|
||||||
|
|
||||||
|
'err.bad_request': 'The request was malformed.',
|
||||||
|
'err.validation_failed': 'Some field is missing or looks wrong.',
|
||||||
|
'err.unauthorized': 'You are not logged in.',
|
||||||
|
'err.invalid_credentials': 'Wrong username or password.',
|
||||||
|
'err.forbidden': 'You may not do that.',
|
||||||
|
'err.not_found': 'That no longer exists.',
|
||||||
|
'err.method_not_allowed': 'That is not allowed here.',
|
||||||
|
'err.conflict': 'That clashes with the current state. Refresh and try again.',
|
||||||
|
'err.request_in_progress': 'Still working on your last request.',
|
||||||
|
'err.idempotency_key_reuse': 'That request clashed with an earlier one. Try again.',
|
||||||
|
'err.payload_too_large': 'That is too much data.',
|
||||||
|
'err.rate_limited': 'Too many requests. Slow down a little.',
|
||||||
|
'err.internal_error': 'Something broke on the server side.',
|
||||||
|
'err.signup_closed': 'Signup needs a valid invite code.',
|
||||||
|
'err.username_taken': 'That username is taken.',
|
||||||
|
'err.world_full': 'No room left on the map.',
|
||||||
|
'err.unknown_building': 'No such building or slot.',
|
||||||
|
'err.not_buildable': 'That cannot be built here.',
|
||||||
|
'err.max_level': 'Already at the maximum level.',
|
||||||
|
'err.requirements_not_met': 'A required building is missing.',
|
||||||
|
'err.already_queued': 'That is already under construction.',
|
||||||
|
'err.queue_full': 'All build slots are busy.',
|
||||||
|
'err.not_enough_resources': 'Not enough resources yet.',
|
||||||
|
'err.network_error': 'Cannot reach the server.',
|
||||||
|
'err.unknown': 'Something went wrong.',
|
||||||
|
};
|
||||||
|
|
||||||
|
const nb = {
|
||||||
|
'app.name': 'UPSTREAM',
|
||||||
|
'app.tagline': 'Bygg din POP. Koble sammen regionen. Overlev konkurrentene.',
|
||||||
|
|
||||||
|
'nav.pop': 'POP', 'nav.map': 'Kart', 'nav.alerts': 'Varsler', 'nav.settings': 'Innstillinger', 'nav.label': 'Hovednavigasjon',
|
||||||
|
'screen.pop': 'Din POP', 'screen.map': 'Regionkart', 'screen.alerts': 'Varsler', 'screen.settings': 'Innstillinger',
|
||||||
|
|
||||||
|
'common.cancel': 'Avbryt', 'common.close': 'Lukk', 'common.back': 'Tilbake', 'common.save': 'Lagre', 'common.confirm': 'Bekreft',
|
||||||
|
'common.loading': 'Laster…', 'common.retry': 'Prøv igjen', 'common.none': 'Ingen', 'common.yes': 'Ja', 'common.no': 'Nei',
|
||||||
|
'common.offline': 'Mistet forbindelsen. Prøver igjen…', 'common.online': 'Tilbake på nett.',
|
||||||
|
'common.perHour': '/t', 'common.tiles': 'ruter',
|
||||||
|
|
||||||
|
'res.fiber': 'Fiber', 'res.hardware': 'Maskinvare', 'res.capital': 'Kapital', 'res.power': 'Strøm', 'res.battery': 'Batteri',
|
||||||
|
|
||||||
|
'tile.land': 'Åpent land', 'tile.rural': 'Utkoblet landsbygd', 'tile.incumbent': 'Gammelt monopolsted', 'tile.pop': 'POP', 'tile.void': 'Utenfor kartet',
|
||||||
|
|
||||||
|
'building.cable_yard.name': 'Kabelgård',
|
||||||
|
'building.cable_yard.desc': 'Trommer, kveiler og mistenkelig mye teip. Produserer Fiber.',
|
||||||
|
'building.supply_depot.name': 'Utstyrslager',
|
||||||
|
'building.supply_depot.desc': 'Hyller med reservedeler ingen tør telle. Produserer Maskinvare.',
|
||||||
|
'building.sales_office.name': 'Salgskontor',
|
||||||
|
'building.sales_office.desc': 'Overbeviser kunder om at 99,9 % er mange nitall. Produserer Kapital.',
|
||||||
|
'building.substation.name': 'Transformatorstasjon',
|
||||||
|
'building.substation.desc': 'Gjør nettbrumming om til strømpoeng. Alt du bygger trekker herfra.',
|
||||||
|
'building.core_router.name': 'Kjerneruter',
|
||||||
|
'building.core_router.desc': 'Alt annet ruter gjennom denne. Gjør alle byggetider kortere.',
|
||||||
|
'building.rack_hall.name': 'Racksal',
|
||||||
|
'building.rack_hall.desc': 'Gulvplass med god luftstrøm. Bestemmer hvor mye Fiber, Maskinvare og Kapital du kan lagre.',
|
||||||
|
'building.battery_bank.name': 'Batteribank',
|
||||||
|
'building.battery_bank.desc': 'Kjøper deg tid når strømmen er knapp. Bestemmer strømbufferen.',
|
||||||
|
'building.firewall.name': 'Brannmur',
|
||||||
|
'building.firewall.desc': 'Stort sett «deny all». Styrker forsvaret i hele POP-en.',
|
||||||
|
'building.noc.name': 'NOC',
|
||||||
|
'building.noc.desc': 'Skjermer full av grønne prikker og én rød. Trener forsvarsmannskap.',
|
||||||
|
'building.research_lab.name': 'Forskningslab',
|
||||||
|
'building.research_lab.desc': 'Der kloke ideer får budsjett. Låser opp enheter og oppgraderinger.',
|
||||||
|
'building.ops_lab.name': 'Ops-lab',
|
||||||
|
'building.ops_lab.desc': 'Verktøy for operasjoner ingen snakker høyt om. Trener angrepsenheter.',
|
||||||
|
'building.internet_exchange.name': 'Internettknutepunkt',
|
||||||
|
'building.internet_exchange.desc': 'Der alle møtes og later som de ikke konkurrerer. Handel mellom POP-er.',
|
||||||
|
'building.peering_office.name': 'Peeringkontor',
|
||||||
|
'building.peering_office.desc': 'Håndtrykk og gjensidig nytte. Stift eller bli med i en allianse.',
|
||||||
|
'building.rollout_depot.name': 'Utrullingsdepot',
|
||||||
|
'building.rollout_depot.desc': 'Lastebiler, grøftefresere og optimisme. Trener mannskapene som stifter nye POP-er.',
|
||||||
|
'building.backbone_node.name': 'Ryggradsnode',
|
||||||
|
'building.backbone_node.desc': 'Sluttspillbygget. Nivå 100 vinner verdenen.',
|
||||||
|
|
||||||
|
'pop.capital': 'Hoved-POP',
|
||||||
|
'pop.rename': 'Gi POP-en nytt navn', 'pop.rename.label': 'POP-navn', 'pop.rename.done': 'POP-en har fått nytt navn.',
|
||||||
|
'pop.coords': 'x {x} · y {y}',
|
||||||
|
'pop.loyalty': 'Kundelojalitet', 'pop.footprint': 'Fotavtrykk', 'pop.footprintPerDay': '+{n}/døgn',
|
||||||
|
'pop.queue.title': 'Byggekø', 'pop.queue.slots': '{used}/{total} plasser',
|
||||||
|
'pop.queue.empty': 'Ingenting under bygging. Et stille nett er ikke det samme som et friskt nett.',
|
||||||
|
'pop.queue.to': 'til nivå {n}', 'pop.queue.cancel': 'Avbryt bygging',
|
||||||
|
'pop.fields.title': 'Ressursfelt', 'pop.fields.group': '{name} · {n} felt',
|
||||||
|
'pop.infra.title': 'Infrastruktur',
|
||||||
|
'pop.level': 'Nv {n}', 'pop.notBuilt': 'Ikke bygget', 'pop.max': 'Maks', 'pop.inQueue': 'Under bygging',
|
||||||
|
'pop.upgradeReady': 'Kan oppgraderes', 'pop.locked': 'Mangler krav',
|
||||||
|
'pop.load.error': 'Kunne ikke laste denne POP-en.',
|
||||||
|
'pop.noTown': 'Ingen POP på denne kontoen ennå.',
|
||||||
|
'pop.bonus': 'Landsbygdbonus', 'pop.bonus.none': 'Ingen landsbygd innen rekkevidde',
|
||||||
|
|
||||||
|
'power.title': 'Strøm', 'power.out': 'Produksjon', 'power.draw': 'Forbruk', 'power.net': 'Netto', 'power.buffer': 'Buffer',
|
||||||
|
'power.ok': 'Stabil', 'power.draining': 'Tapper: tom om {t}', 'power.charging': 'Lader: full om {t}', 'power.full': 'Bufferen er full',
|
||||||
|
'power.empty': 'Bufferen er tom: enheter er frakoblet', 'power.unit': 'p',
|
||||||
|
|
||||||
|
'sheet.level': 'Nivå {n}', 'sheet.nextLevel': 'Neste: nivå {n}',
|
||||||
|
'sheet.cost': 'Kostnad', 'sheet.time': 'Byggetid', 'sheet.requires': 'Krever', 'sheet.have': 'har {n}',
|
||||||
|
'sheet.build': 'Bygg nivå {n}', 'sheet.upgrade': 'Oppgrader til nivå {n}', 'sheet.building': 'Bygger…',
|
||||||
|
'sheet.maxed': 'Fullt oppgradert', 'sheet.underway': 'Under bygging', 'sheet.done': 'Ferdig om {t}',
|
||||||
|
'sheet.affordableIn': 'Råd om {t}', 'sheet.capTooLow': 'Trenger større Racksal (rommer {cap})',
|
||||||
|
'sheet.cancel': 'Avbryt denne byggingen', 'sheet.cancel.confirm': 'Avbryte {name} til nivå {n}?',
|
||||||
|
'sheet.cancel.refund': '80 % av kostnaden går tilbake til POP-en.', 'sheet.cancel.keep': 'Fortsett byggingen',
|
||||||
|
'sheet.built': '{name} til nivå {n} er satt i kø.', 'sheet.cancelled': 'Bygging avbrutt. Refusjon lagt til.',
|
||||||
|
'sheet.preview.output': 'Produksjon {a} → {b} per time', 'sheet.preview.storage': 'Lager {a} → {b}',
|
||||||
|
'sheet.preview.battery': 'Strømbuffer {a} → {b}', 'sheet.preview.core': 'Byggetid ×{a} → ×{b}',
|
||||||
|
'sheet.preview.core2': 'Nivå {n} åpner en ekstra byggeplass.', 'sheet.preview.draw': 'Strømforbruk +{n}',
|
||||||
|
'sheet.preview.firewall': 'Forsvar ×{a} → ×{b}', 'sheet.preview.output.now': 'Produksjon nå: {a} per time',
|
||||||
|
|
||||||
|
'map.centre': 'Sentrer på min POP', 'map.zoomIn': 'Zoom inn', 'map.zoomOut': 'Zoom ut',
|
||||||
|
'map.label': 'Regionkart. Dra for å flytte, knip eller scroll for å zoome, trykk på en rute for detaljer.',
|
||||||
|
'map.noWorld': 'Denne kontoen er ikke med i noen verden ennå.', 'map.error': 'Kunne ikke laste deler av kartet.',
|
||||||
|
'map.scanning': 'Skanner…', 'map.legend.rural': 'Landsbygd', 'map.legend.incumbent': 'Monopolist', 'map.legend.you': 'Deg', 'map.legend.rival': 'Rival',
|
||||||
|
'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} ruter fra hovedstaden din',
|
||||||
|
'map.info.land': 'Ingenting her ennå. Ikke en eneste fiberstreng.',
|
||||||
|
'map.info.rural': 'POP-er innen {n} ruter får +{p} % {res}-produksjon så lenge de er tilkoblet.',
|
||||||
|
'map.info.incumbent': 'Et gammelt telekomfestning. Det angriper aldri. Det trenger ikke.',
|
||||||
|
'map.info.operator': 'Operatør', 'map.info.as': 'AS-nummer', 'map.info.yours': 'Din POP', 'map.info.rival': 'Rivaliserende operatør',
|
||||||
|
'map.info.protected': 'Nybegynnerbeskyttelse, ingen angrep inn eller ut.', 'map.info.open': 'Åpne POP', 'map.info.capital': 'Hovedstad',
|
||||||
|
|
||||||
|
'alerts.empty': 'Stille på linja.', 'alerts.error': 'Kunne ikke laste varsler.', 'alerts.new': 'ny',
|
||||||
|
'alerts.build_done': '{name} nådde nivå {level}', 'alerts.build_done.in': 'i {town}',
|
||||||
|
'alerts.unknown': 'Hendelse: {type}', 'alerts.more': 'Eldre varsler er skjult', 'alerts.count': '{n} uleste',
|
||||||
|
|
||||||
|
'settings.language': 'Språk', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)',
|
||||||
|
'settings.account': 'Konto', 'settings.username': 'Brukernavn', 'settings.operator': 'Operatør', 'settings.as': 'AS-nummer', 'settings.world': 'Verden',
|
||||||
|
'settings.worldInfo': '{name} · {speed}× fart · radius {r}',
|
||||||
|
'settings.devices': 'Enheter', 'settings.devices.hint': 'Hver enhet har sin egen token. Tilbakekall én, så logges den enheten ut.',
|
||||||
|
'settings.device.current': 'Denne enheten', 'settings.device.unnamed': 'Enhet uten navn', 'settings.device.revoke': 'Tilbakekall',
|
||||||
|
'settings.device.revoked': 'Enheten er tilbakekalt.', 'settings.device.lastUsed': 'Sist brukt {t}', 'settings.device.created': 'Lagt til {t}',
|
||||||
|
'settings.logout': 'Logg ut', 'settings.logout.confirm': 'Logge ut på denne enheten?',
|
||||||
|
'settings.about': 'Om', 'settings.about.text': 'UPSTREAM er et hobbyprosjekt. Kun fiktive operatører; likhet med ekte nett er en rutelekkasje.',
|
||||||
|
|
||||||
|
'auth.login': 'Logg inn', 'auth.signup': 'Registrer deg', 'auth.username': 'Brukernavn', 'auth.password': 'Passord',
|
||||||
|
'auth.invite': 'Invitasjonskode', 'auth.invite.hint': 'Denne serveren krever invitasjonskode for å registrere deg.',
|
||||||
|
'auth.toSignup': 'Ny operatør? Opprett konto', 'auth.toLogin': 'Allerede peeret? Logg inn',
|
||||||
|
'auth.username.hint': '3-20 bokstaver, tall, _ eller -', 'auth.password.hint': 'Minst 8 tegn',
|
||||||
|
'auth.working': 'Jobber…', 'auth.expired': 'Økten er over. Logg inn igjen.',
|
||||||
|
'auth.welcome': 'Velkommen, operatør.',
|
||||||
|
|
||||||
|
'time.d': 'd', 'time.h': 't', 'time.m': 'm', 'time.s': 's',
|
||||||
|
'time.now': 'akkurat nå', 'time.ago': '{t} siden', 'time.in': 'om {t}',
|
||||||
|
|
||||||
|
'err.bad_request': 'Forespørselen var ugyldig.',
|
||||||
|
'err.validation_failed': 'Et felt mangler eller ser feil ut.',
|
||||||
|
'err.unauthorized': 'Du er ikke logget inn.',
|
||||||
|
'err.invalid_credentials': 'Feil brukernavn eller passord.',
|
||||||
|
'err.forbidden': 'Det har du ikke lov til.',
|
||||||
|
'err.not_found': 'Det finnes ikke lenger.',
|
||||||
|
'err.method_not_allowed': 'Det er ikke tillatt her.',
|
||||||
|
'err.conflict': 'Det kolliderer med dagens tilstand. Oppdater og prøv igjen.',
|
||||||
|
'err.request_in_progress': 'Jobber fortsatt med forrige forespørsel.',
|
||||||
|
'err.idempotency_key_reuse': 'Forespørselen kolliderte med en tidligere. Prøv igjen.',
|
||||||
|
'err.payload_too_large': 'Det er for mye data.',
|
||||||
|
'err.rate_limited': 'For mange forespørsler. Ta det litt roligere.',
|
||||||
|
'err.internal_error': 'Noe gikk i stykker hos serveren.',
|
||||||
|
'err.signup_closed': 'Registrering krever gyldig invitasjonskode.',
|
||||||
|
'err.username_taken': 'Brukernavnet er opptatt.',
|
||||||
|
'err.world_full': 'Ikke plass igjen på kartet.',
|
||||||
|
'err.unknown_building': 'Ingen slik bygning eller plass.',
|
||||||
|
'err.not_buildable': 'Det kan ikke bygges her.',
|
||||||
|
'err.max_level': 'Allerede på høyeste nivå.',
|
||||||
|
'err.requirements_not_met': 'En påkrevd bygning mangler.',
|
||||||
|
'err.already_queued': 'Det er allerede under bygging.',
|
||||||
|
'err.queue_full': 'Alle byggeplasser er opptatt.',
|
||||||
|
'err.not_enough_resources': 'Ikke nok ressurser ennå.',
|
||||||
|
'err.network_error': 'Får ikke kontakt med serveren.',
|
||||||
|
'err.unknown': 'Noe gikk galt.',
|
||||||
|
};
|
||||||
|
|
||||||
|
const strings = { en, nb };
|
||||||
|
|
||||||
|
function detectLang(navLang) {
|
||||||
|
const l = String(navLang || '').toLowerCase();
|
||||||
|
return /^(nb|nn|no)(\b|-|_)/.test(l) || l === 'no' ? 'nb' : 'en';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill {placeholders}. Missing vars stay visible as {name}, so a bug shows up on screen instead of as "undefined".
|
||||||
|
function fill(s, vars) {
|
||||||
|
if (!vars) return s;
|
||||||
|
return s.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m));
|
||||||
|
}
|
||||||
|
|
||||||
|
function t(lang, key, vars) {
|
||||||
|
const table = strings[lang] || en;
|
||||||
|
const s = Object.prototype.hasOwnProperty.call(table, key) ? table[key] : (Object.prototype.hasOwnProperty.call(en, key) ? en[key] : key);
|
||||||
|
return fill(s, vars);
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = (lang) => (lang === 'nb' ? 'nb-NO' : 'en-GB');
|
||||||
|
const nfCache = {};
|
||||||
|
function nf(lang, digits) {
|
||||||
|
const k = lang + digits;
|
||||||
|
if (!nfCache[k]) nfCache[k] = new Intl.NumberFormat(locale(lang), { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
||||||
|
return nfCache[k];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whole numbers for amounts. Compact (12.3k, 4.5M) from 100 000 up so nothing overflows a phone-width chip.
|
||||||
|
function fmtNum(lang, n) {
|
||||||
|
n = Number(n) || 0;
|
||||||
|
const a = Math.abs(n);
|
||||||
|
if (a >= 1e6) return nf(lang, 1).format(Math.floor(n / 1e5) / 10) + 'M';
|
||||||
|
if (a >= 1e5) return nf(lang, 0).format(Math.floor(n / 1e3)) + 'k';
|
||||||
|
return nf(lang, 0).format(Math.floor(n + 1e-9));
|
||||||
|
}
|
||||||
|
|
||||||
|
// One decimal below 100, whole numbers above; always signed when `signed` (rates: +12.4, -3).
|
||||||
|
function fmtDec(lang, n, signed) {
|
||||||
|
n = Number(n) || 0;
|
||||||
|
const a = Math.abs(n);
|
||||||
|
const s = a >= 100 ? nf(lang, 0).format(Math.round(a)) : nf(lang, 1).format(a);
|
||||||
|
const sign = n < 0 ? '−' : (signed && n > 0 ? '+' : '');
|
||||||
|
return sign + s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "2d 3h", "2h 5m", "4m 10s", "12s". At most `parts` units (default 2), rounding the last one up never; floors.
|
||||||
|
function fmtDuration(lang, ms, parts) {
|
||||||
|
parts = parts || 2;
|
||||||
|
let s = Math.max(0, Math.floor(ms / 1000));
|
||||||
|
if (s < 1) return '0' + t(lang, 'time.s');
|
||||||
|
const units = [['time.d', 86400], ['time.h', 3600], ['time.m', 60], ['time.s', 1]];
|
||||||
|
const out = [];
|
||||||
|
for (const [k, size] of units) {
|
||||||
|
const v = Math.floor(s / size);
|
||||||
|
s -= v * size;
|
||||||
|
if (v > 0 || out.length) out.push(v + t(lang, k));
|
||||||
|
if (out.length >= parts) break;
|
||||||
|
}
|
||||||
|
while (out.length > 1 && /^0\D/.test(out[out.length - 1])) out.pop(); // "1h 0m" -> "1h"
|
||||||
|
return out.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Countdown clock "h:mm:ss" (or "m:ss" under an hour). Ceil so it never shows 0:00 while time is left.
|
||||||
|
function fmtClock(ms) {
|
||||||
|
const total = Math.max(0, Math.ceil(ms / 1000));
|
||||||
|
const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
|
||||||
|
const p = (v) => (v < 10 ? '0' : '') + v;
|
||||||
|
return h > 0 ? h + ':' + p(m) + ':' + p(s) : m + ':' + p(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// "5m ago", "just now". `diff` = now - then in ms.
|
||||||
|
function fmtAgo(lang, diff) {
|
||||||
|
if (diff < 45000) return t(lang, 'time.now');
|
||||||
|
return t(lang, 'time.ago', { t: fmtDuration(lang, diff, 1) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fictional AS numbers come from the private 32-bit range; shown as "AS4200000123".
|
||||||
|
const fmtAs = (n) => 'AS' + n;
|
||||||
|
|
||||||
|
return { LANGS, strings, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs };
|
||||||
|
}));
|
||||||
404
public/js/main.js
Normal file
404
public/js/main.js
Normal file
|
|
@ -0,0 +1,404 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* The shell: session, screen registry, bottom nav, resource bar (HUD), ticker, language. Screens live in
|
||||||
|
* js/screens/*.js and register themselves:
|
||||||
|
*
|
||||||
|
* App.registerScreen({
|
||||||
|
* id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav
|
||||||
|
* hud: true, // show the resource bar above it
|
||||||
|
* render(container) {}, // once, when the screen is first shown: build the persistent DOM
|
||||||
|
* onShow(params) {}, // every time it becomes visible
|
||||||
|
* onHide() {},
|
||||||
|
* onLang() {}, // optional: language changed while visible (default: onShow again)
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag.
|
||||||
|
* Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon, toast, safeStore } = UI;
|
||||||
|
const I = UpstreamI18n;
|
||||||
|
const R = UpstreamRules;
|
||||||
|
const D = UpstreamData;
|
||||||
|
|
||||||
|
const api = UpstreamApi.createApi({
|
||||||
|
fetch: window.fetch.bind(window),
|
||||||
|
storage: (function () { try { return window.localStorage; } catch (e) { return null; } }()),
|
||||||
|
});
|
||||||
|
|
||||||
|
const LANG_KEY = 'upstream.lang';
|
||||||
|
const TOWN_KEY = 'upstream.town';
|
||||||
|
const SEEN_KEY = 'upstream.alerts.seen.';
|
||||||
|
|
||||||
|
const App = {
|
||||||
|
api,
|
||||||
|
state: { user: null, operators: [], operator: null, world: null, towns: [], townId: null, townData: null, townFetchedAt: 0, lang: 'en', unread: 0 },
|
||||||
|
screens: new Map(),
|
||||||
|
current: null,
|
||||||
|
params: null,
|
||||||
|
};
|
||||||
|
window.App = App;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tiny event bus (town, session, lang)
|
||||||
|
const bus = {};
|
||||||
|
App.on = (evt, fn) => { (bus[evt] = bus[evt] || new Set()).add(fn); return () => bus[evt].delete(fn); };
|
||||||
|
App.emit = (evt, data) => { if (bus[evt]) for (const fn of Array.from(bus[evt])) { try { fn(data); } catch (e) { console.error(e); } } };
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ i18n helpers
|
||||||
|
App.t = (key, vars) => I.t(App.state.lang, key, vars);
|
||||||
|
App.fmt = {
|
||||||
|
num: (n) => I.fmtNum(App.state.lang, n),
|
||||||
|
dec: (n, signed) => I.fmtDec(App.state.lang, n, signed),
|
||||||
|
dur: (ms, parts) => I.fmtDuration(App.state.lang, ms, parts),
|
||||||
|
clock: (ms) => I.fmtClock(ms),
|
||||||
|
ago: (ms) => I.fmtAgo(App.state.lang, ms),
|
||||||
|
compact: (n) => (Math.abs(n) >= 1000 ? I.fmtDec(App.state.lang, n / 1000) + 'k' : I.fmtNum(App.state.lang, n)),
|
||||||
|
};
|
||||||
|
App.errMsg = (err) => {
|
||||||
|
const code = err && err.code;
|
||||||
|
if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code);
|
||||||
|
return (err && err.message) || App.t('err.unknown');
|
||||||
|
};
|
||||||
|
App.resName = (r) => App.t('res.' + r);
|
||||||
|
App.buildingName = (type) => (I.strings.en['building.' + type + '.name'] ? App.t('building.' + type + '.name') : type);
|
||||||
|
App.buildingDesc = (type) => (I.strings.en['building.' + type + '.desc'] ? App.t('building.' + type + '.desc') : '');
|
||||||
|
|
||||||
|
App.setLang = (lang) => {
|
||||||
|
if (!I.LANGS.includes(lang)) return;
|
||||||
|
App.state.lang = lang;
|
||||||
|
safeStore.set(LANG_KEY, lang);
|
||||||
|
document.documentElement.lang = lang;
|
||||||
|
buildNav();
|
||||||
|
renderHud(true);
|
||||||
|
if (App.current) {
|
||||||
|
setTitle(App.current);
|
||||||
|
if (App.current.onLang) App.current.onLang(); else if (App.current.onShow) App.current.onShow(App.params || {});
|
||||||
|
}
|
||||||
|
App.emit('lang', lang);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ server clock + ticker
|
||||||
|
App.now = () => api.serverNow();
|
||||||
|
const tickers = new Set();
|
||||||
|
App.onTick = (fn) => { tickers.add(fn); return () => tickers.delete(fn); };
|
||||||
|
setInterval(() => {
|
||||||
|
if (document.hidden) return;
|
||||||
|
const now = api.serverNow();
|
||||||
|
tickHud(now);
|
||||||
|
for (const fn of Array.from(tickers)) { try { fn(now); } catch (e) { console.error(e); } }
|
||||||
|
}, 250);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ screens + nav
|
||||||
|
const elView = () => document.getElementById('view');
|
||||||
|
const elNav = () => document.getElementById('nav');
|
||||||
|
const elApp = () => document.getElementById('app');
|
||||||
|
|
||||||
|
App.registerScreen = (def) => { App.screens.set(def.id, def); };
|
||||||
|
|
||||||
|
function buildNav() {
|
||||||
|
const nav = elNav();
|
||||||
|
clear(nav);
|
||||||
|
nav.setAttribute('aria-label', App.t('nav.label'));
|
||||||
|
for (const def of App.screens.values()) {
|
||||||
|
if (def.nav === false) continue;
|
||||||
|
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
|
||||||
|
const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) },
|
||||||
|
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
|
||||||
|
if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page');
|
||||||
|
nav.appendChild(btn);
|
||||||
|
}
|
||||||
|
updateBadge();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateBadge() {
|
||||||
|
const n = App.state.unread;
|
||||||
|
const b = elNav().querySelector('[data-screen="alerts"] .nav-badge');
|
||||||
|
if (!b) return;
|
||||||
|
b.hidden = !n;
|
||||||
|
b.textContent = n > 9 ? '9+' : String(n);
|
||||||
|
const btn = b.closest('button');
|
||||||
|
if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { n }) + ')' : ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTitle(def) { document.getElementById('title').textContent = def.id === 'auth' ? App.t('app.name') : App.t(def.titleKey); document.title = (def.id === 'auth' ? '' : App.t(def.titleKey) + ' · ') + 'UPSTREAM'; }
|
||||||
|
|
||||||
|
// Navigate. Sets the hash (so back/forward work); hashchange does the actual switch.
|
||||||
|
App.go = (id, params) => {
|
||||||
|
App.nextParams = params || null;
|
||||||
|
const want = '#/' + id;
|
||||||
|
if (location.hash === want) show(id, App.nextParams); else location.hash = want;
|
||||||
|
};
|
||||||
|
|
||||||
|
function show(id, params) {
|
||||||
|
if (!App.state.user && id !== 'auth') id = 'auth';
|
||||||
|
if (App.state.user && id === 'auth') id = 'pop';
|
||||||
|
const def = App.screens.get(id) || App.screens.get(App.state.user ? 'pop' : 'auth');
|
||||||
|
if (!def) return;
|
||||||
|
if (App.current && App.current !== def && App.current.onHide) App.current.onHide();
|
||||||
|
const view = elView();
|
||||||
|
for (const s of view.children) s.hidden = s.dataset.screen !== def.id;
|
||||||
|
let box = view.querySelector('[data-screen="' + def.id + '"]');
|
||||||
|
if (!box) {
|
||||||
|
box = h('section', { class: 'screen screen-' + def.id, dataset: { screen: def.id }, tabindex: '-1' });
|
||||||
|
view.appendChild(box);
|
||||||
|
if (def.render) def.render(box);
|
||||||
|
}
|
||||||
|
box.hidden = false;
|
||||||
|
App.current = def;
|
||||||
|
App.params = params || {};
|
||||||
|
const app = elApp();
|
||||||
|
app.dataset.screen = def.id;
|
||||||
|
app.dataset.state = App.state.user ? 'in' : 'out';
|
||||||
|
elNav().hidden = !App.state.user;
|
||||||
|
for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); }
|
||||||
|
setTitle(def);
|
||||||
|
renderHud(false);
|
||||||
|
if (def.onShow) def.onShow(App.params);
|
||||||
|
if (App.state.user && def.nav !== false) safeStore.set('upstream.screen', def.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('hashchange', () => {
|
||||||
|
const id = (location.hash.match(/^#\/(\w+)/) || [])[1] || 'pop';
|
||||||
|
const p = App.nextParams; App.nextParams = null;
|
||||||
|
show(id, p);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ session
|
||||||
|
// Accepts the operators array of /me or of an auth response.
|
||||||
|
App.setSession = (user, operators) => {
|
||||||
|
const st = App.state;
|
||||||
|
st.user = user;
|
||||||
|
st.operators = operators || [];
|
||||||
|
st.operator = st.operators[0] || null; // v1: one world per account
|
||||||
|
st.world = st.operator ? st.operator.world : null;
|
||||||
|
st.towns = st.operator ? st.operator.towns : [];
|
||||||
|
const saved = Number(safeStore.get(TOWN_KEY));
|
||||||
|
const pick = st.towns.find((t) => t.id === saved) || st.towns.find((t) => t.isCapital) || st.towns[0] || null;
|
||||||
|
st.townId = pick ? pick.id : null;
|
||||||
|
st.townData = null;
|
||||||
|
st.unread = 0;
|
||||||
|
App.emit('session', st);
|
||||||
|
};
|
||||||
|
|
||||||
|
App.clearSession = () => {
|
||||||
|
const st = App.state;
|
||||||
|
st.user = null; st.operators = []; st.operator = null; st.world = null; st.towns = []; st.townId = null; st.townData = null; st.unread = 0;
|
||||||
|
api.clearToken();
|
||||||
|
renderHud(true);
|
||||||
|
App.emit('session', st);
|
||||||
|
};
|
||||||
|
|
||||||
|
App.loadMe = async () => {
|
||||||
|
const me = await api.get('/me');
|
||||||
|
App.setSession(me.user, me.operators);
|
||||||
|
return me;
|
||||||
|
};
|
||||||
|
|
||||||
|
App.setTown = (id) => {
|
||||||
|
if (App.state.townId === id) return;
|
||||||
|
App.state.townId = id; App.state.townData = null;
|
||||||
|
safeStore.set(TOWN_KEY, String(id));
|
||||||
|
App.refreshTown().catch(() => {});
|
||||||
|
App.emit('townchange', id);
|
||||||
|
};
|
||||||
|
|
||||||
|
let townInflight = null;
|
||||||
|
App.refreshTown = () => {
|
||||||
|
const st = App.state;
|
||||||
|
if (!st.townId) return Promise.resolve(null);
|
||||||
|
if (townInflight) return townInflight;
|
||||||
|
const id = st.townId;
|
||||||
|
townInflight = api.get('/towns/' + id).then((r) => {
|
||||||
|
if (st.townId !== id) return null;
|
||||||
|
st.townData = r.town;
|
||||||
|
st.townFetchedAt = Date.now();
|
||||||
|
App.fetchedServerTime = r.serverTime; // the instant the amounts in r.town are exact for
|
||||||
|
rulesCache = null;
|
||||||
|
renderHud(true);
|
||||||
|
App.emit('town', r.town);
|
||||||
|
return r.town;
|
||||||
|
}).finally(() => { townInflight = null; });
|
||||||
|
return townInflight;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ rules.js view of the current POP (previews + ticking)
|
||||||
|
let rulesCache = null;
|
||||||
|
// The rules.js town shape from the API response: same function the server settles with, so the numbers agree.
|
||||||
|
App.rulesTown = () => {
|
||||||
|
const st = App.state, td = st.townData;
|
||||||
|
if (!td || !st.world) return null;
|
||||||
|
if (rulesCache && rulesCache.src === td) return rulesCache.town;
|
||||||
|
const buildings = {};
|
||||||
|
let bdraw = 0;
|
||||||
|
for (const b of td.buildings) {
|
||||||
|
if (b.level <= 0) continue;
|
||||||
|
buildings[b.key] = { type: b.type, level: b.level };
|
||||||
|
const def = D.BUILDINGS[b.type];
|
||||||
|
if (def && def.kind === 'infra') bdraw += def.draw * b.level;
|
||||||
|
}
|
||||||
|
const town = {
|
||||||
|
id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0,
|
||||||
|
res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer },
|
||||||
|
footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {},
|
||||||
|
};
|
||||||
|
rulesCache = { src: td, town };
|
||||||
|
return town;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Current amounts at server time `now`. Falls back to the fetched values if the rules cannot be applied.
|
||||||
|
App.resourcesNow = (now) => {
|
||||||
|
const td = App.state.townData;
|
||||||
|
if (!td) return null;
|
||||||
|
try {
|
||||||
|
const rt = App.rulesTown();
|
||||||
|
const cur = R.resourcesAt(rt, now === undefined ? api.serverNow() : now);
|
||||||
|
return { amounts: cur.amounts, caps: cur.caps, rates: cur.rates };
|
||||||
|
} catch (e) {
|
||||||
|
const amounts = { battery: td.power.buffer }, caps = { battery: td.power.bufferCap };
|
||||||
|
for (const r of D.RESOURCES) { amounts[r] = td.resources[r].amount; caps[r] = td.resources[r].cap; }
|
||||||
|
return { amounts, caps, rates: { fiber: td.resources.fiber.rate, hardware: td.resources.hardware.rate, capital: td.resources.capital.rate, powerOut: td.power.out, powerDraw: td.power.draw, powerNet: td.power.net } };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ resource bar
|
||||||
|
const hudRefs = {};
|
||||||
|
|
||||||
|
function renderHud(rebuild) {
|
||||||
|
const hud = document.getElementById('hud');
|
||||||
|
const def = App.current;
|
||||||
|
const td = App.state.townData;
|
||||||
|
const want = !!(def && def.hud && td && App.state.user);
|
||||||
|
hud.hidden = !want;
|
||||||
|
if (!want) return;
|
||||||
|
if (!rebuild && hud.firstChild) return;
|
||||||
|
clear(hud);
|
||||||
|
for (const r of D.RESOURCES.concat(['power'])) {
|
||||||
|
const refs = {
|
||||||
|
val: h('b', { class: 'val' }), cap: h('span', { class: 'cap' }), rate: h('span', { class: 'rate' }), fill: h('i'),
|
||||||
|
};
|
||||||
|
hudRefs[r] = refs;
|
||||||
|
hud.appendChild(h('div', { class: 'hud-chip ' + r, role: 'group', dataset: { res: r } },
|
||||||
|
h('div', { class: 'hud-top' }, icon(r), refs.val, refs.cap),
|
||||||
|
h('div', { class: 'hud-sub' }, refs.rate),
|
||||||
|
h('div', { class: 'bar', 'aria-hidden': 'true' }, refs.fill)));
|
||||||
|
}
|
||||||
|
tickHud(api.serverNow(), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastText = new WeakMap();
|
||||||
|
function setText(el, s) { if (lastText.get(el) !== s) { lastText.set(el, s); el.textContent = s; } }
|
||||||
|
|
||||||
|
function tickHud(now, force) {
|
||||||
|
const hud = document.getElementById('hud');
|
||||||
|
if (hud.hidden && !force) return;
|
||||||
|
const cur = App.resourcesNow(now);
|
||||||
|
if (!cur || !hudRefs.fiber) return;
|
||||||
|
const f = App.fmt;
|
||||||
|
for (const r of D.RESOURCES) {
|
||||||
|
const refs = hudRefs[r];
|
||||||
|
const amt = cur.amounts[r], cap = cur.caps[r], rate = cur.rates[r];
|
||||||
|
const full = amt >= cap - 0.01;
|
||||||
|
setText(refs.val, f.num(amt));
|
||||||
|
setText(refs.cap, '/' + f.compact(cap));
|
||||||
|
setText(refs.rate, full ? 'FULL' : f.dec(rate, true) + App.t('common.perHour'));
|
||||||
|
refs.fill.style.setProperty('--p', String(cap > 0 ? Math.min(1, amt / cap) : 0));
|
||||||
|
const chip = refs.val.closest('.hud-chip');
|
||||||
|
chip.classList.toggle('full', full);
|
||||||
|
if (force) chip.setAttribute('aria-label', App.resName(r) + ': ' + f.num(amt) + ' / ' + f.num(cap) + ', ' + f.dec(rate, true) + App.t('common.perHour'));
|
||||||
|
}
|
||||||
|
const p = hudRefs.power;
|
||||||
|
const net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
|
||||||
|
setText(p.val, f.dec(net, true));
|
||||||
|
setText(p.cap, App.t('power.unit'));
|
||||||
|
setText(p.rate, buf <= 0 && net < 0 ? App.t('power.empty').split(':')[0] : f.num(buf) + '/' + f.compact(bcap));
|
||||||
|
p.fill.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
|
||||||
|
const pc = p.val.closest('.hud-chip');
|
||||||
|
pc.classList.toggle('bad', net < 0);
|
||||||
|
pc.classList.toggle('empty', buf <= 0 && net < 0);
|
||||||
|
if (force) pc.setAttribute('aria-label', App.t('res.power') + ': ' + f.dec(net, true) + ', ' + App.t('res.battery') + ' ' + f.num(buf) + ' / ' + f.num(bcap));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ alerts badge (unread count from the notification feed)
|
||||||
|
const seenKey = () => SEEN_KEY + (App.state.user ? App.state.user.id : '0');
|
||||||
|
App.getSeen = () => Number(safeStore.get(seenKey())) || 0;
|
||||||
|
App.markSeen = (id) => {
|
||||||
|
if (id > App.getSeen()) safeStore.set(seenKey(), String(id));
|
||||||
|
App.state.unread = 0;
|
||||||
|
updateBadge();
|
||||||
|
};
|
||||||
|
App.checkAlerts = async () => {
|
||||||
|
if (!App.state.user) return;
|
||||||
|
try {
|
||||||
|
const after = App.getSeen();
|
||||||
|
const r = await api.get('/notifications', { after, limit: 50 });
|
||||||
|
if (App.current && App.current.id === 'alerts') { App.state.unread = 0; }
|
||||||
|
else App.state.unread = r.items.length;
|
||||||
|
updateBadge();
|
||||||
|
} catch (e) { /* badge is a convenience */ }
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ connection state
|
||||||
|
let backTimer = null;
|
||||||
|
api.on('offline', () => {
|
||||||
|
const el = document.getElementById('netstate');
|
||||||
|
el.textContent = App.t('common.offline'); el.hidden = false; el.classList.remove('ok');
|
||||||
|
clearTimeout(backTimer);
|
||||||
|
});
|
||||||
|
api.on('online', () => {
|
||||||
|
const el = document.getElementById('netstate');
|
||||||
|
if (el.hidden) return;
|
||||||
|
el.textContent = App.t('common.online'); el.classList.add('ok');
|
||||||
|
backTimer = setTimeout(() => { el.hidden = true; }, 1800);
|
||||||
|
if (App.state.user) App.refreshTown().catch(() => {});
|
||||||
|
});
|
||||||
|
api.on('unauthorized', () => {
|
||||||
|
App.clearSession();
|
||||||
|
App.authNotice = App.t('auth.expired');
|
||||||
|
App.go('auth');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (document.hidden || !App.state.user) return;
|
||||||
|
if (Date.now() - App.state.townFetchedAt > 20000) App.refreshTown().catch(() => {});
|
||||||
|
App.checkAlerts();
|
||||||
|
});
|
||||||
|
setInterval(() => { if (!document.hidden && App.state.user) App.checkAlerts(); }, 60000);
|
||||||
|
|
||||||
|
// After login or boot: load the POP and go to the screen the hash asks for.
|
||||||
|
App.enter = async (wantScreen) => {
|
||||||
|
buildNav();
|
||||||
|
const id = wantScreen || (location.hash.match(/^#\/(\w+)/) || [])[1] || safeStore.get('upstream.screen') || 'pop';
|
||||||
|
App.go(App.screens.has(id) && id !== 'auth' ? id : 'pop');
|
||||||
|
App.checkAlerts();
|
||||||
|
try { await App.refreshTown(); } catch (e) { toast(App.errMsg(e), 'error'); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ boot
|
||||||
|
async function boot() {
|
||||||
|
const saved = safeStore.get(LANG_KEY);
|
||||||
|
App.state.lang = I.LANGS.includes(saved) ? saved : I.detectLang(navigator.language);
|
||||||
|
document.documentElement.lang = App.state.lang;
|
||||||
|
buildNav();
|
||||||
|
if (!api.hasToken()) { App.go('auth'); return; }
|
||||||
|
const view = elView();
|
||||||
|
const status = h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }));
|
||||||
|
view.appendChild(status);
|
||||||
|
try {
|
||||||
|
await App.loadMe();
|
||||||
|
status.remove();
|
||||||
|
await App.enter();
|
||||||
|
} catch (e) {
|
||||||
|
status.remove();
|
||||||
|
if (e.code === 'network_error') {
|
||||||
|
const retry = h('button', { class: 'btn primary', type: 'button', onclick: () => { card.remove(); boot(); } }, icon('refresh'), App.t('common.retry'));
|
||||||
|
const card = h('div', { class: 'boot' }, h('p', { text: App.errMsg(e) }), retry);
|
||||||
|
view.appendChild(card);
|
||||||
|
} else if (e.code !== 'unauthorized') {
|
||||||
|
toast(App.errMsg(e), 'error');
|
||||||
|
App.go('auth');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', boot);
|
||||||
|
}());
|
||||||
398
public/js/render.js
Normal file
398
public/js/render.js
Normal file
|
|
@ -0,0 +1,398 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* The canvas map and nothing else (window.MapRender.MapView): camera, pan / pinch / wheel / keyboard, tile culling,
|
||||||
|
* drawing. It knows no API. The screen gives it a `source` with the loaded data and callbacks:
|
||||||
|
*
|
||||||
|
* source.forEachSpecial(x0, y0, x1, y1, fn(special)) rural + incumbent tiles in the rect
|
||||||
|
* source.townsInRect(x0, y0, x1, y1) -> [town] POPs in the rect
|
||||||
|
* source.isOwn(town) -> bool
|
||||||
|
* onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift)
|
||||||
|
* onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom }
|
||||||
|
*
|
||||||
|
* Coordinates are tile units, y grows downward; tile (x, y) is the square [x-.5, x+.5] x [y-.5, y+.5].
|
||||||
|
* Touch: one finger pans, two fingers pinch-zoom around their midpoint and never trigger a tap. A tap is only
|
||||||
|
* reported when no second finger was ever down and the finger moved less than a few pixels.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const COLORS = {
|
||||||
|
void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)',
|
||||||
|
fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338',
|
||||||
|
own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)',
|
||||||
|
};
|
||||||
|
|
||||||
|
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
|
||||||
|
|
||||||
|
// A stable colour per operator id so rivals are told apart but never confused with you (cyan) or incumbents (violet).
|
||||||
|
function rivalColors(id) {
|
||||||
|
const hues = [8, 28, 48, 86, 150, 330, 355, 120]; // warm and green hues, no cyan/blue/violet
|
||||||
|
const hue = hues[Math.abs(id | 0) % hues.length];
|
||||||
|
return { fill: 'hsl(' + hue + ',45%,24%)', stroke: 'hsl(' + hue + ',70%,62%)' };
|
||||||
|
}
|
||||||
|
|
||||||
|
class MapView {
|
||||||
|
constructor(canvas, source, opts) {
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.ctx = canvas.getContext('2d');
|
||||||
|
this.src = source;
|
||||||
|
this.opts = opts || {};
|
||||||
|
this.radius = 50;
|
||||||
|
this.cx = 0; this.cy = 0; this.zoom = 24;
|
||||||
|
this.w = 0; this.h = 0; this.dpr = 1;
|
||||||
|
this.selected = null;
|
||||||
|
this.pointers = new Map();
|
||||||
|
this.drag = null;
|
||||||
|
this.pinch = null;
|
||||||
|
this.raf = 0;
|
||||||
|
this.moveTimer = 0;
|
||||||
|
this.labelFn = null;
|
||||||
|
this.reachTiles = 2;
|
||||||
|
this._bind();
|
||||||
|
}
|
||||||
|
|
||||||
|
setWorld(radius) { this.radius = radius; this._limits(); this.invalidate(); }
|
||||||
|
setSelected(x, y) { this.selected = x === null ? null : { x, y }; this.invalidate(); }
|
||||||
|
|
||||||
|
resize() {
|
||||||
|
const r = this.canvas.getBoundingClientRect();
|
||||||
|
const dpr = Math.min(window.devicePixelRatio || 1, 3);
|
||||||
|
if (!r.width || !r.height) return false;
|
||||||
|
this.w = r.width; this.h = r.height; this.dpr = dpr;
|
||||||
|
this.canvas.width = Math.round(r.width * dpr);
|
||||||
|
this.canvas.height = Math.round(r.height * dpr);
|
||||||
|
this._limits();
|
||||||
|
this.zoom = clamp(this.zoom, this.minZoom, this.maxZoom);
|
||||||
|
this._clampCenter();
|
||||||
|
this.invalidate();
|
||||||
|
this._scheduleMoveEnd(0);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
_limits() {
|
||||||
|
const span = this.radius * 2 + 3;
|
||||||
|
this.minZoom = clamp(Math.min(this.w || 300, this.h || 300) / span, 2.5, 20);
|
||||||
|
this.maxZoom = 90;
|
||||||
|
}
|
||||||
|
|
||||||
|
_clampCenter() {
|
||||||
|
this.cx = clamp(this.cx, -this.radius, this.radius);
|
||||||
|
this.cy = clamp(this.cy, -this.radius, this.radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
setView(cx, cy, zoom) {
|
||||||
|
this.cx = cx; this.cy = cy;
|
||||||
|
if (zoom) this.zoom = clamp(zoom, this.minZoom, this.maxZoom);
|
||||||
|
this._clampCenter();
|
||||||
|
this.invalidate();
|
||||||
|
this._scheduleMoveEnd(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// screen px (relative to the canvas) <-> tile coordinates
|
||||||
|
toTile(px, py) { return { x: (px - this.w / 2) / this.zoom + this.cx, y: (py - this.h / 2) / this.zoom + this.cy }; }
|
||||||
|
toScreen(x, y) { return { x: (x - this.cx) * this.zoom + this.w / 2, y: (y - this.cy) * this.zoom + this.h / 2 }; }
|
||||||
|
|
||||||
|
// Visible tiles clamped to the world.
|
||||||
|
view() {
|
||||||
|
const a = this.toTile(0, 0), b = this.toTile(this.w, this.h), r = this.radius;
|
||||||
|
return {
|
||||||
|
x0: clamp(Math.floor(a.x), -r, r), y0: clamp(Math.floor(a.y), -r, r),
|
||||||
|
x1: clamp(Math.ceil(b.x), -r, r), y1: clamp(Math.ceil(b.y), -r, r),
|
||||||
|
cx: this.cx, cy: this.cy, zoom: this.zoom,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Zoom keeping the world point under screen (px, py) fixed.
|
||||||
|
zoomAt(px, py, factor) {
|
||||||
|
const before = this.toTile(px, py);
|
||||||
|
this.zoom = clamp(this.zoom * factor, this.minZoom, this.maxZoom);
|
||||||
|
this.cx = before.x - (px - this.w / 2) / this.zoom;
|
||||||
|
this.cy = before.y - (py - this.h / 2) / this.zoom;
|
||||||
|
this._clampCenter();
|
||||||
|
this.invalidate();
|
||||||
|
this._scheduleMoveEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
panBy(dxPx, dyPx) {
|
||||||
|
this.cx -= dxPx / this.zoom; this.cy -= dyPx / this.zoom;
|
||||||
|
this._clampCenter();
|
||||||
|
this.invalidate();
|
||||||
|
this._scheduleMoveEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
_scheduleMoveEnd(delay) {
|
||||||
|
clearTimeout(this.moveTimer);
|
||||||
|
this.moveTimer = setTimeout(() => { if (this.opts.onMoveEnd && this.w) this.opts.onMoveEnd(this.view()); }, delay === undefined ? 200 : delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
invalidate() {
|
||||||
|
if (this.raf) return;
|
||||||
|
this.raf = requestAnimationFrame(() => { this.raf = 0; this.draw(); });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ input
|
||||||
|
_bind() {
|
||||||
|
const c = this.canvas;
|
||||||
|
const rel = (e) => { const r = c.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; };
|
||||||
|
|
||||||
|
c.addEventListener('pointerdown', (e) => {
|
||||||
|
if (e.pointerType === 'mouse' && e.button !== 0) return;
|
||||||
|
try { c.setPointerCapture(e.pointerId); } catch (err) { /* synthetic */ }
|
||||||
|
const p = rel(e);
|
||||||
|
this.pointers.set(e.pointerId, { x: p.x, y: p.y });
|
||||||
|
if (this.pointers.size === 1) {
|
||||||
|
this.drag = { startX: p.x, startY: p.y, lastX: p.x, lastY: p.y, moved: false, pinched: false, t: e.timeStamp, touch: e.pointerType !== 'mouse' };
|
||||||
|
} else if (this.pointers.size === 2 && this.drag) {
|
||||||
|
this.drag.pinched = true;
|
||||||
|
this._startPinch();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
c.addEventListener('pointermove', (e) => {
|
||||||
|
const cur = this.pointers.get(e.pointerId);
|
||||||
|
if (!cur || !this.drag) return;
|
||||||
|
const p = rel(e);
|
||||||
|
cur.x = p.x; cur.y = p.y;
|
||||||
|
if (this.pointers.size >= 2 && this.pinch) { this._movePinch(); return; }
|
||||||
|
if (this.pointers.size === 1 && !this.drag.pinched) {
|
||||||
|
const slop = this.drag.touch ? 9 : 5;
|
||||||
|
if (!this.drag.moved && Math.hypot(p.x - this.drag.startX, p.y - this.drag.startY) > slop) this.drag.moved = true;
|
||||||
|
if (this.drag.moved) {
|
||||||
|
this.panBy(p.x - this.drag.lastX, p.y - this.drag.lastY);
|
||||||
|
c.classList.add('grabbing');
|
||||||
|
}
|
||||||
|
this.drag.lastX = p.x; this.drag.lastY = p.y;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const end = (e, cancelled) => {
|
||||||
|
if (!this.pointers.has(e.pointerId)) return;
|
||||||
|
const p = rel(e);
|
||||||
|
this.pointers.delete(e.pointerId);
|
||||||
|
try { c.releasePointerCapture(e.pointerId); } catch (err) { /* already released */ }
|
||||||
|
const d = this.drag;
|
||||||
|
if (this.pointers.size === 1 && d) {
|
||||||
|
// one finger left after a pinch: continue as a pan from where that finger is, never as a tap
|
||||||
|
const [rest] = this.pointers.values();
|
||||||
|
d.lastX = rest.x; d.lastY = rest.y; d.startX = rest.x; d.startY = rest.y; d.moved = true;
|
||||||
|
this.pinch = null;
|
||||||
|
}
|
||||||
|
if (this.pointers.size === 0 && d) {
|
||||||
|
const tap = !cancelled && !d.moved && !d.pinched && e.timeStamp - d.t < 700;
|
||||||
|
this.drag = null; this.pinch = null;
|
||||||
|
c.classList.remove('grabbing');
|
||||||
|
if (tap && this.opts.onTap) {
|
||||||
|
const t = this.toTile(p.x, p.y);
|
||||||
|
this.opts.onTap(Math.round(t.x), Math.round(t.y));
|
||||||
|
}
|
||||||
|
this._scheduleMoveEnd(60);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
c.addEventListener('pointerup', (e) => end(e, false));
|
||||||
|
c.addEventListener('pointercancel', (e) => end(e, true));
|
||||||
|
c.addEventListener('lostpointercapture', (e) => { if (this.pointers.has(e.pointerId)) end(e, true); });
|
||||||
|
|
||||||
|
c.addEventListener('wheel', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const p = rel(e);
|
||||||
|
const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
|
||||||
|
this.zoomAt(p.x, p.y, Math.exp(-dy * 0.0016));
|
||||||
|
}, { passive: false });
|
||||||
|
|
||||||
|
c.addEventListener('keydown', (e) => {
|
||||||
|
const step = Math.max(24, this.w * 0.2);
|
||||||
|
const k = e.key;
|
||||||
|
if (k === 'ArrowLeft') this.panBy(step, 0);
|
||||||
|
else if (k === 'ArrowRight') this.panBy(-step, 0);
|
||||||
|
else if (k === 'ArrowUp') this.panBy(0, step);
|
||||||
|
else if (k === 'ArrowDown') this.panBy(0, -step);
|
||||||
|
else if (k === '+' || k === '=') this.zoomAt(this.w / 2, this.h / 2, 1.3);
|
||||||
|
else if (k === '-' || k === '_') this.zoomAt(this.w / 2, this.h / 2, 1 / 1.3);
|
||||||
|
else if ((k === 'Enter' || k === ' ') && this.opts.onTap) this.opts.onTap(Math.round(this.cx), Math.round(this.cy));
|
||||||
|
else return;
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
_pair() { const a = Array.from(this.pointers.values()); return [a[0], a[1]]; }
|
||||||
|
|
||||||
|
_startPinch() {
|
||||||
|
const [a, b] = this._pair();
|
||||||
|
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||||
|
this.pinch = { dist: Math.max(10, Math.hypot(a.x - b.x, a.y - b.y)), zoom: this.zoom, world: this.toTile(mid.x, mid.y) };
|
||||||
|
}
|
||||||
|
|
||||||
|
_movePinch() {
|
||||||
|
const [a, b] = this._pair();
|
||||||
|
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
|
||||||
|
const k = Math.hypot(a.x - b.x, a.y - b.y) / this.pinch.dist;
|
||||||
|
this.zoom = clamp(this.pinch.zoom * k, this.minZoom, this.maxZoom);
|
||||||
|
// keep the world point that was under the fingers' midpoint under it (also pans with the midpoint)
|
||||||
|
this.cx = this.pinch.world.x - (mid.x - this.w / 2) / this.zoom;
|
||||||
|
this.cy = this.pinch.world.y - (mid.y - this.h / 2) / this.zoom;
|
||||||
|
this._clampCenter();
|
||||||
|
this.invalidate();
|
||||||
|
this._scheduleMoveEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ drawing
|
||||||
|
draw() {
|
||||||
|
const { ctx, dpr, w, h, zoom: z } = this;
|
||||||
|
if (!w || !h) return;
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
ctx.fillStyle = COLORS.void;
|
||||||
|
ctx.fillRect(0, 0, w, h);
|
||||||
|
|
||||||
|
const r = this.radius;
|
||||||
|
const tl = this.toScreen(-r - 0.5, -r - 0.5), br = this.toScreen(r + 0.5, r + 0.5);
|
||||||
|
ctx.fillStyle = COLORS.land;
|
||||||
|
ctx.fillRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
|
||||||
|
|
||||||
|
const v = this.view();
|
||||||
|
// land texture + grid
|
||||||
|
if (z >= 9) {
|
||||||
|
ctx.fillStyle = COLORS.land2;
|
||||||
|
for (let y = v.y0; y <= v.y1; y++) {
|
||||||
|
for (let x = v.x0 + (((v.x0 + y) & 1) ? 1 : 0); x <= v.x1; x += 2) {
|
||||||
|
const s = this.toScreen(x - 0.5, y - 0.5);
|
||||||
|
ctx.fillRect(s.x, s.y, z, z);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.lineWidth = 1;
|
||||||
|
if (z >= 14) {
|
||||||
|
ctx.strokeStyle = COLORS.grid;
|
||||||
|
ctx.beginPath();
|
||||||
|
for (let x = v.x0; x <= v.x1 + 1; x++) { const s = this.toScreen(x - 0.5, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); }
|
||||||
|
for (let y = v.y0; y <= v.y1 + 1; y++) { const s = this.toScreen(0, y - 0.5).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); }
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
// every 10 tiles, so a zoomed-out map still reads as a map
|
||||||
|
ctx.strokeStyle = COLORS.grid10;
|
||||||
|
ctx.beginPath();
|
||||||
|
for (let x = Math.ceil(v.x0 / 10) * 10; x <= v.x1; x += 10) { const s = this.toScreen(x, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); }
|
||||||
|
for (let y = Math.ceil(v.y0 / 10) * 10; y <= v.y1; y += 10) { const s = this.toScreen(0, y).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); }
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
// specials: rural areas and incumbent sites
|
||||||
|
this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => {
|
||||||
|
const s = this.toScreen(sp.x, sp.y);
|
||||||
|
if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus);
|
||||||
|
else this._incumbent(s.x, s.y);
|
||||||
|
});
|
||||||
|
|
||||||
|
const towns = this.src.townsInRect(v.x0 - 1, v.y0 - 1, v.x1 + 1, v.y1 + 1);
|
||||||
|
// faint rural reach rings around your own POPs
|
||||||
|
if (z >= 10) {
|
||||||
|
ctx.save();
|
||||||
|
ctx.setLineDash([4, 5]);
|
||||||
|
ctx.strokeStyle = COLORS.reach;
|
||||||
|
for (const t of towns) {
|
||||||
|
if (!this.src.isOwn(t)) continue;
|
||||||
|
const s = this.toScreen(t.x, t.y);
|
||||||
|
ctx.beginPath(); ctx.arc(s.x, s.y, this.reachTiles * z, 0, Math.PI * 2); ctx.stroke();
|
||||||
|
}
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
for (const t of towns) this._pop(t);
|
||||||
|
|
||||||
|
// world border
|
||||||
|
ctx.strokeStyle = COLORS.border;
|
||||||
|
ctx.lineWidth = 2;
|
||||||
|
ctx.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
|
||||||
|
|
||||||
|
// selection
|
||||||
|
if (this.selected) this._selection(this.selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
_rural(x, y, bonus) {
|
||||||
|
const { ctx, zoom: z } = this;
|
||||||
|
const col = COLORS[bonus] || COLORS.capital;
|
||||||
|
if (z < 6) { ctx.fillStyle = col; ctx.globalAlpha = 0.8; ctx.fillRect(x - Math.max(1, z / 2), y - Math.max(1, z / 2), Math.max(2, z), Math.max(2, z)); ctx.globalAlpha = 1; return; }
|
||||||
|
ctx.globalAlpha = 0.2; ctx.fillStyle = col;
|
||||||
|
ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.fill();
|
||||||
|
ctx.globalAlpha = 1; ctx.strokeStyle = col; ctx.lineWidth = Math.max(1, z * 0.06);
|
||||||
|
ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.stroke();
|
||||||
|
if (z >= 12) {
|
||||||
|
// "unconnected": a signal glyph with a cut line through it
|
||||||
|
ctx.lineWidth = Math.max(1, z * 0.07); ctx.lineCap = 'round';
|
||||||
|
for (let i = 1; i <= 2; i++) { ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.1 * i + z * 0.04, Math.PI * 1.2, Math.PI * 1.8); ctx.stroke(); }
|
||||||
|
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.05, 0, Math.PI * 2); ctx.fill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_incumbent(x, y) {
|
||||||
|
const { ctx, zoom: z } = this;
|
||||||
|
const s = z * 0.78;
|
||||||
|
ctx.fillStyle = COLORS.incumbentFill; ctx.strokeStyle = COLORS.incumbent; ctx.lineWidth = Math.max(1, z * 0.07);
|
||||||
|
ctx.fillRect(x - s / 2, y - s / 2, s, s);
|
||||||
|
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
|
||||||
|
if (z >= 14) {
|
||||||
|
ctx.fillStyle = COLORS.incumbent;
|
||||||
|
const n = 3, nw = s / 7;
|
||||||
|
for (let i = 0; i < n; i++) ctx.fillRect(x - s / 2 + s * 0.12 + i * (s * 0.3), y - s / 2 - nw * 0.0 + 1, nw * 1.3, nw * 1.3);
|
||||||
|
ctx.fillRect(x - s * 0.12, y + s * 0.02, s * 0.24, s * 0.28);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_hex(x, y, rad) {
|
||||||
|
const { ctx } = this;
|
||||||
|
ctx.beginPath();
|
||||||
|
for (let i = 0; i < 6; i++) {
|
||||||
|
const a = Math.PI / 6 + i * Math.PI / 3;
|
||||||
|
const px = x + Math.cos(a) * rad, py = y + Math.sin(a) * rad;
|
||||||
|
if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py);
|
||||||
|
}
|
||||||
|
ctx.closePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
_pop(t) {
|
||||||
|
const { ctx, zoom: z } = this;
|
||||||
|
const s = this.toScreen(t.x, t.y);
|
||||||
|
if (s.x < -40 || s.y < -40 || s.x > this.w + 40 || s.y > this.h + 40) return;
|
||||||
|
const own = this.src.isOwn(t);
|
||||||
|
const col = own ? { fill: COLORS.ownFill, stroke: COLORS.own } : rivalColors(t.owner.id);
|
||||||
|
const rad = Math.max(3, z * (own ? 0.5 : 0.42));
|
||||||
|
if (own) {
|
||||||
|
ctx.save();
|
||||||
|
ctx.shadowColor = COLORS.own; ctx.shadowBlur = Math.min(22, 6 + z * 0.35);
|
||||||
|
this._hex(s.x, s.y, rad); ctx.fillStyle = col.fill; ctx.fill();
|
||||||
|
ctx.restore();
|
||||||
|
}
|
||||||
|
this._hex(s.x, s.y, rad);
|
||||||
|
ctx.fillStyle = col.fill; ctx.fill();
|
||||||
|
ctx.strokeStyle = col.stroke; ctx.lineWidth = own ? Math.max(2, z * 0.1) : Math.max(1.2, z * 0.07); ctx.stroke();
|
||||||
|
if (z >= 10) {
|
||||||
|
ctx.fillStyle = col.stroke;
|
||||||
|
ctx.beginPath(); ctx.arc(s.x, s.y, Math.max(1.5, rad * (t.isCapital ? 0.38 : 0.22)), 0, Math.PI * 2); ctx.fill();
|
||||||
|
if (t.isCapital) { ctx.strokeStyle = col.stroke; ctx.lineWidth = 1; this._hex(s.x, s.y, rad * 0.68); ctx.stroke(); }
|
||||||
|
}
|
||||||
|
if (z >= 18 && t.owner.protected) {
|
||||||
|
ctx.strokeStyle = COLORS.select; ctx.lineWidth = Math.max(1, z * 0.05); ctx.setLineDash([3, 3]);
|
||||||
|
this._hex(s.x, s.y, rad + z * 0.12); ctx.stroke(); ctx.setLineDash([]);
|
||||||
|
}
|
||||||
|
if (z >= 24 || (own && z >= 12)) {
|
||||||
|
const label = this.labelFn ? this.labelFn(t, own) : t.name;
|
||||||
|
ctx.font = (own ? '700 ' : '600 ') + Math.round(clamp(z * 0.34, 10, 14)) + 'px system-ui, sans-serif';
|
||||||
|
ctx.textAlign = 'center'; ctx.textBaseline = 'top';
|
||||||
|
ctx.lineWidth = 3; ctx.lineJoin = 'round'; ctx.strokeStyle = COLORS.halo;
|
||||||
|
ctx.strokeText(label, s.x, s.y + rad + 3);
|
||||||
|
ctx.fillStyle = own ? COLORS.own : COLORS.text;
|
||||||
|
ctx.fillText(label, s.x, s.y + rad + 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_selection(sel) {
|
||||||
|
const { ctx, zoom: z } = this;
|
||||||
|
const s = this.toScreen(sel.x, sel.y);
|
||||||
|
const half = Math.max(5, z * 0.52), len = Math.max(3, half * 0.5);
|
||||||
|
ctx.strokeStyle = COLORS.select; ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
|
||||||
|
ctx.beginPath();
|
||||||
|
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
|
||||||
|
const px = s.x + sx * half, py = s.y + sy * half;
|
||||||
|
ctx.moveTo(px - sx * len, py); ctx.lineTo(px, py); ctx.lineTo(px, py - sy * len);
|
||||||
|
}
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.MapRender = { MapView, COLORS };
|
||||||
|
}());
|
||||||
|
|
@ -284,6 +284,37 @@
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ alliances and diplomacy
|
||||||
|
// Member cap of an alliance for a given Peering office level (best POP of the leader). The server stores the cap at
|
||||||
|
// founding and only ever raises it (server/alliances.js effectiveCap), so a lost building never kicks anyone.
|
||||||
|
function allianceCap(peeringLevel) {
|
||||||
|
return D.SOCIAL.allianceBaseSize + D.SOCIAL.allianceSizePerLevel * Math.max(0, Math.floor(peeringLevel || 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// May a member with `role` perform `action` (a key of SOCIAL.permissions)?
|
||||||
|
function allianceCan(role, action) {
|
||||||
|
const list = hasOwn(D.SOCIAL.permissions, action) ? D.SOCIAL.permissions[action] : null;
|
||||||
|
return !!list && list.indexOf(role) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seniority: leader 4 .. member 1, unknown roles -1.
|
||||||
|
function roleRank(role) {
|
||||||
|
const i = D.SOCIAL.roles.indexOf(role);
|
||||||
|
return i < 0 ? -1 : D.SOCIAL.roles.length - i;
|
||||||
|
}
|
||||||
|
const outranks = (a, b) => roleRank(a) > roleRank(b);
|
||||||
|
|
||||||
|
// How an alliance may move a relation from `from` to `to`: 'immediate' | 'proposal' | 'delayed' | null (not allowed).
|
||||||
|
function diplomacyMove(from, to) {
|
||||||
|
const row = hasOwn(D.SOCIAL.diplomacyMoves, from) ? D.SOCIAL.diplomacyMoves[from] : null;
|
||||||
|
return row && hasOwn(row, to) ? row[to] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Time a unilateral cancel of a pact takes (24 h at 1x, shorter on faster worlds).
|
||||||
|
function pactCancelMs(worldSpeed) {
|
||||||
|
return Math.max(1000, Math.round(D.SOCIAL.pactCancelHours * HOUR / (worldSpeed || 1)));
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ movement
|
// ------------------------------------------------------------------ movement
|
||||||
// Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min.
|
// Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min.
|
||||||
function latencyMs(dist, unitSpeed, worldSpeed) {
|
function latencyMs(dist, unitSpeed, worldSpeed) {
|
||||||
|
|
@ -291,10 +322,343 @@
|
||||||
return Math.max(10 * 60 * 1000, Math.round(hours * HOUR));
|
return Math.max(10 * 60 * 1000, Math.round(hours * HOUR));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ military: units, training, research (stages 3-4)
|
||||||
|
// Units are always plain objects { unitId: count }. `research` is { 'unitId:attack': level, 'unitId:defence': level }.
|
||||||
|
const MIL = D.MILITARY;
|
||||||
|
|
||||||
|
function unitDef(id) { return hasOwn(D.UNITS, id) ? D.UNITS[id] : null; }
|
||||||
|
const buildingLevel = (town, type) => (town.buildings[type] ? town.buildings[type].level : 0);
|
||||||
|
const unitCount = (units) => Object.keys(units || {}).reduce((s, k) => s + (units[k] || 0), 0);
|
||||||
|
const costValue = (cost) => D.RESOURCES.reduce((s, r) => s + ((cost && cost[r]) || 0), 0);
|
||||||
|
const unitValue = (id) => costValue(unitDef(id).cost);
|
||||||
|
const researchKey = (unit, stat) => unit + ':' + stat;
|
||||||
|
const researchLevel = (research, unit, stat) => (research && research[researchKey(unit, stat)]) || 0;
|
||||||
|
const researchMult = (level) => 1 + MIL.researchPerLevel * level;
|
||||||
|
// attack | defence of one unit of this type, with research
|
||||||
|
function unitStat(unit, stat, research) { return unitDef(unit)[stat] * researchMult(researchLevel(research, unit, stat)); }
|
||||||
|
|
||||||
|
function unitCost(unit, count) {
|
||||||
|
const def = unitDef(unit), out = {};
|
||||||
|
for (const r of D.RESOURCES) out[r] = def.cost[r] * count;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Training time in ms for a batch. The training building's level shortens it; world speed divides it.
|
||||||
|
function trainTimeMs(unit, count, buildingLvl, speed) {
|
||||||
|
const secs = unitDef(unit).time * count / (1 + MIL.trainSpeedPerLevel * buildingLvl) / (speed || 1);
|
||||||
|
return Math.max(1000, Math.round(secs * 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing requirements of a unit in a town: [{ type, level, have }]. The training building counts at level 1.
|
||||||
|
function unitMissing(town, unit) {
|
||||||
|
const def = unitDef(unit);
|
||||||
|
const need = [{ type: def.building, level: 1 }].concat(def.requires);
|
||||||
|
const best = {};
|
||||||
|
for (const r of need) best[r.type] = Math.max(best[r.type] || 0, r.level);
|
||||||
|
const missing = [];
|
||||||
|
for (const type of Object.keys(best)) {
|
||||||
|
const have = buildingLevel(town, type);
|
||||||
|
if (have < best[type]) missing.push({ type, level: best[type], have });
|
||||||
|
}
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Can `count` of `unit` be queued now? `tailAt` = due time of the last batch queued in the same building (batches of
|
||||||
|
// one building run one after another). Codes: unknown_unit, validation_failed, requirements_not_met, not_enough_resources.
|
||||||
|
function trainPlan(town, unit, count, now, tailAt) {
|
||||||
|
const def = unitDef(unit);
|
||||||
|
const base = { ok: false, unit, count };
|
||||||
|
if (!def) return Object.assign(base, { code: 'unknown_unit' });
|
||||||
|
if (!Number.isInteger(count) || count < 1 || count > MIL.maxBatch) return Object.assign(base, { code: 'validation_failed' });
|
||||||
|
const missing = unitMissing(town, unit);
|
||||||
|
base.building = def.building;
|
||||||
|
base.cost = unitCost(unit, count);
|
||||||
|
base.durationMs = trainTimeMs(unit, count, buildingLevel(town, def.building), town.speed);
|
||||||
|
base.startAt = Math.max(now, tailAt || 0);
|
||||||
|
base.dueAt = base.startAt + base.durationMs;
|
||||||
|
base.missing = missing;
|
||||||
|
if (missing.length) return Object.assign(base, { code: 'requirements_not_met' });
|
||||||
|
const have = resourcesAt(town, now).amounts;
|
||||||
|
for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
|
||||||
|
base.ok = true;
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- research
|
||||||
|
const RS = D.RESEARCH;
|
||||||
|
function researchCost(unit, toLevel) {
|
||||||
|
const def = unitDef(unit), out = {};
|
||||||
|
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * RS.costFactor * Math.pow(RS.costGrowth, toLevel - 1));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// speedBonus: the operator's permanent research speed bonus from incumbent sites (0.1 = +10%).
|
||||||
|
function researchTimeMs(unit, toLevel, labLevel, speed, speedBonus) {
|
||||||
|
const secs = RS.timeBase * Math.pow(RS.timeGrowth, toLevel - 1) / (1 + RS.labSpeedPerLevel * labLevel) / (speed || 1) / (1 + (speedBonus || 0));
|
||||||
|
return Math.max(1000, Math.round(secs * 1000));
|
||||||
|
}
|
||||||
|
function researchSpeedBonus(sitesTaken) { return Math.min(D.INCUMBENT.researchSpeedMax, D.INCUMBENT.researchSpeedBonus * sitesTaken); }
|
||||||
|
|
||||||
|
// Plan one research level. `current` = level now, `busy` = a research is already running in this POP.
|
||||||
|
// Codes: unknown_unit, not_researchable, max_level, requirements_not_met, queue_full, not_enough_resources.
|
||||||
|
function researchPlan(town, unit, stat, current, busy, now, speedBonus) {
|
||||||
|
const def = unitDef(unit);
|
||||||
|
const base = { ok: false, unit, stat, fromLevel: current, toLevel: current + 1 };
|
||||||
|
if (!def) return Object.assign(base, { code: 'unknown_unit' });
|
||||||
|
if (RS.stats.indexOf(stat) < 0 || !(def[stat] > 0)) return Object.assign(base, { code: 'not_researchable' });
|
||||||
|
if (current >= RS.maxLevel) return Object.assign(base, { code: 'max_level' });
|
||||||
|
const lab = buildingLevel(town, 'research_lab');
|
||||||
|
const missing = unitMissing(town, unit);
|
||||||
|
const needLab = base.toLevel + RS.labOffset;
|
||||||
|
if (lab < needLab) missing.push({ type: 'research_lab', level: needLab, have: lab });
|
||||||
|
base.missing = missing;
|
||||||
|
base.cost = researchCost(unit, base.toLevel);
|
||||||
|
base.durationMs = researchTimeMs(unit, base.toLevel, lab, town.speed, speedBonus);
|
||||||
|
if (missing.length) return Object.assign(base, { code: 'requirements_not_met' });
|
||||||
|
if (busy) return Object.assign(base, { code: 'queue_full' });
|
||||||
|
const have = resourcesAt(town, now).amounts;
|
||||||
|
for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
|
||||||
|
base.ok = true;
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ military: movements
|
||||||
|
// Slowest speed (tiles/hour at 1x) among the units actually in the group; Infinity when empty.
|
||||||
|
function slowestSpeed(units) {
|
||||||
|
let s = Infinity;
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s = Math.min(s, unitDef(k).speed);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
// Travel time of a unit group over `dist` tiles (min 10 min, see latencyMs). An empty group travels at transport speed.
|
||||||
|
function movementMs(dist, units, worldSpeed) {
|
||||||
|
const s = slowestSpeed(units);
|
||||||
|
return latencyMs(dist, isFinite(s) ? s : D.TRANSPORT.speed, worldSpeed);
|
||||||
|
}
|
||||||
|
function transportMs(dist, worldSpeed) { return latencyMs(dist, D.TRANSPORT.speed, worldSpeed); }
|
||||||
|
|
||||||
|
// Shape and role check of the units on a movement of `type`. null when fine, otherwise { code, reason }.
|
||||||
|
function checkUnitsForType(type, units) {
|
||||||
|
const roles = hasOwn(D.MOVE_ROLES, type) ? D.MOVE_ROLES[type] : null;
|
||||||
|
if (!roles) return { code: 'validation_failed', reason: 'type carries no units' };
|
||||||
|
let total = 0;
|
||||||
|
for (const k of Object.keys(units || {})) {
|
||||||
|
const n = units[k];
|
||||||
|
const def = unitDef(k);
|
||||||
|
if (!def) return { code: 'unknown_unit', reason: k };
|
||||||
|
if (!Number.isInteger(n) || n < 0) return { code: 'validation_failed', reason: 'bad count for ' + k };
|
||||||
|
if (n === 0) continue;
|
||||||
|
if (def.fixed) return { code: 'validation_failed', reason: k + ' cannot move' };
|
||||||
|
if (roles.indexOf(def.role) < 0) return { code: 'validation_failed', reason: k + ' cannot go on a ' + type };
|
||||||
|
total += n;
|
||||||
|
}
|
||||||
|
if (total < 1) return { code: 'validation_failed', reason: 'no units' };
|
||||||
|
if (type === 'settle') {
|
||||||
|
const only = Object.keys(units).filter((k) => units[k] > 0);
|
||||||
|
if (only.length !== 1 || only[0] !== D.EXPANSION.settleUnit || units[only[0]] !== D.EXPANSION.crews) {
|
||||||
|
return { code: 'validation_failed', reason: 'a settle needs exactly ' + D.EXPANSION.crews + ' ' + D.EXPANSION.settleUnit };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (type === 'takeover' && !(units[D.EXPANSION.conquestUnit] > 0)) return { code: 'validation_failed', reason: 'a takeover needs a ' + D.EXPANSION.conquestUnit };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Beginner protection: a protected operator cannot be attacked (raid, attack, takeover). Scans are fine.
|
||||||
|
const isProtected = (protectionUntil, at) => (protectionUntil || 0) > at;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ military: combat
|
||||||
|
const firewallMult = (level) => 1 + F.firewallPerLevel * level;
|
||||||
|
const effectiveFirewall = (level, rigs) => Math.max(0, level - (rigs || 0) / MIL.rigFirewallDivisor);
|
||||||
|
|
||||||
|
function powerOf(units, research, stat) {
|
||||||
|
let s = 0;
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s += units[k] * unitStat(k, stat, research);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
const attackPower = (units, research) => powerOf(units, research, 'attack');
|
||||||
|
const defencePower = (units, research) => powerOf(units, research, 'defence');
|
||||||
|
|
||||||
|
// Remove a fraction of every unit type (rounded to whole units). -> { survivors, lost }
|
||||||
|
function applyLoss(units, fraction) {
|
||||||
|
const survivors = {}, lost = {};
|
||||||
|
for (const k of Object.keys(units || {})) {
|
||||||
|
const n = units[k];
|
||||||
|
if (!(n > 0)) continue;
|
||||||
|
const l = fraction >= 1 ? n : Math.min(n, Math.round(n * fraction));
|
||||||
|
if (l > 0) lost[k] = l;
|
||||||
|
if (n - l > 0) survivors[k] = n - l;
|
||||||
|
}
|
||||||
|
return { survivors, lost };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The battle. Deterministic: inputs in, result out, no randomness.
|
||||||
|
// o.kind: 'attack' (full) | 'raid'
|
||||||
|
// o.attackers: { units, research }
|
||||||
|
// o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement)
|
||||||
|
// o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses)
|
||||||
|
// Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units.
|
||||||
|
// Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender.
|
||||||
|
function resolveBattle(o) {
|
||||||
|
const att = o.attackers.units || {};
|
||||||
|
const A = attackPower(att, o.attackers.research);
|
||||||
|
const rigs = att.ddos_rig || 0;
|
||||||
|
const effFw = effectiveFirewall(o.firewall || 0, rigs);
|
||||||
|
const groups = o.defenders || [];
|
||||||
|
const raw = groups.map((g) => defencePower(g.units, g.research));
|
||||||
|
const rawTotal = raw.reduce((s, v) => s + v, 0);
|
||||||
|
const isStatic = o.staticDefence !== undefined && o.staticDefence !== null;
|
||||||
|
const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw);
|
||||||
|
const attackerWins = A > Dv;
|
||||||
|
const hi = Math.max(A, Dv), lo = Math.min(A, Dv);
|
||||||
|
const ratio = hi > 0 ? lo / hi : 0;
|
||||||
|
let attF, defF;
|
||||||
|
if (o.kind === 'raid') {
|
||||||
|
attF = defF = MIL.raidLossFactor * Math.pow(ratio, MIL.lossExponent);
|
||||||
|
} else if (attackerWins) {
|
||||||
|
attF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); defF = 1;
|
||||||
|
} else {
|
||||||
|
attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent));
|
||||||
|
}
|
||||||
|
if (isStatic) defF = 0;
|
||||||
|
const a = applyLoss(att, attF);
|
||||||
|
const defenders = groups.map((g, i) => {
|
||||||
|
const r = applyLoss(g.units, defF);
|
||||||
|
return { id: g.id, sent: g.units, lost: r.lost, survivors: r.survivors, share: rawTotal > 0 ? raw[i] / rawTotal : 0 };
|
||||||
|
});
|
||||||
|
return { kind: o.kind, A, D: Dv, defenceRaw: rawTotal, effectiveFirewall: effFw, attackerWins, ratio, attackerLossFraction: attF, defenderLossFraction: defF,
|
||||||
|
attacker: { sent: att, lost: a.lost, survivors: a.survivors }, defenders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Battle points for destroying units (operator_stats.attack_points / defense_points).
|
||||||
|
function battlePoints(lostUnits) {
|
||||||
|
let v = 0;
|
||||||
|
for (const k of Object.keys(lostUnits || {})) if (unitDef(k)) v += unitValue(k) * lostUnits[k];
|
||||||
|
return v * MIL.pointsPerCost;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share of the stock the Rack hall hides from a raid ("cold spare").
|
||||||
|
const cacheFraction = (rackLevel) => Math.min(MIL.cacheMax, MIL.cachePerLevel * Math.max(0, rackLevel || 0));
|
||||||
|
|
||||||
|
// Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others.
|
||||||
|
// avail = what can be taken. -> whole-number { fiber, hardware, capital }.
|
||||||
|
function lootSplit(carry, avail) {
|
||||||
|
const take = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
let left = Math.max(0, carry);
|
||||||
|
for (let pass = 0; pass < 4 && left > 1e-9; pass++) {
|
||||||
|
const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9);
|
||||||
|
if (!open.length) break;
|
||||||
|
const share = left / open.length;
|
||||||
|
for (const r of open) {
|
||||||
|
const t = Math.min(share, avail[r] - take[r]);
|
||||||
|
take[r] += t; left -= t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const r of D.RESOURCES) take[r] = Math.floor(take[r] + 1e-9);
|
||||||
|
return take;
|
||||||
|
}
|
||||||
|
const carryOf = (units) => Object.keys(units || {}).reduce((s, k) => s + (unitDef(k) ? unitDef(k).carry * units[k] : 0), 0);
|
||||||
|
|
||||||
|
// Exploit kits (survivors) tear levels off one chosen building after a win.
|
||||||
|
const siegeLevels = (kits) => (kits >= MIL.kitsMin ? Math.max(1, Math.floor(kits / MIL.kitsPerLevel)) : 0);
|
||||||
|
|
||||||
|
// Customer loyalty lost to one M&A team, from a seeded roll r in [0, 1).
|
||||||
|
function loyaltyDrop(r) { const lo = MIL.loyaltyDrop[0], hi = MIL.loyaltyDrop[1]; return lo + Math.min(hi - lo, Math.floor(r * (hi - lo + 1))); }
|
||||||
|
|
||||||
|
// Why a POP cannot change owner: 'capital' | 'last_pop' | null. (A capital can still be dragged to zero loyalty.)
|
||||||
|
function takeoverBlock(isCapital, defenderTownCount) {
|
||||||
|
if (defenderTownCount <= 1) return 'last_pop'; // wins over 'capital': a lone capital is not even drained
|
||||||
|
if (isCapital) return 'capital';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footprint gate for founding or taking over: the operator owns `ownedCount` POPs now, `footprint` is their total.
|
||||||
|
function footprintGate(ownedCount, footprint) {
|
||||||
|
const need = footprintNeeded(ownedCount);
|
||||||
|
return { ok: footprint + 1e-6 >= need, need, have: footprint };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low.
|
||||||
|
function settleCheck(o) {
|
||||||
|
if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' };
|
||||||
|
if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist };
|
||||||
|
const g = footprintGate(o.ownedCount, o.footprint);
|
||||||
|
if (!g.ok) return { ok: false, code: 'footprint_too_low', need: g.need, have: g.have };
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wild slot choice at founding: two field types (any of FIELD_TYPES). Anything else falls back to the defaults.
|
||||||
|
function cleanWild(wild) {
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i < D.WILD_SLOTS; i++) out.push(wild && D.FIELD_TYPES.indexOf(wild[i]) >= 0 ? wild[i] : D.START.wild[i]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// A new POP: every field at level 0, no infrastructure at all.
|
||||||
|
function newTownBuildings(wild) {
|
||||||
|
const layout = fieldLayout(wild);
|
||||||
|
const out = {};
|
||||||
|
for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: 0 };
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- scanning
|
||||||
|
const scanStrength = (count, research) => count * researchMult(researchLevel(research, 'port_scanner', 'defence'));
|
||||||
|
// sa = attacking scanner strength, sd = defending. Success needs sa > sd; buildings (and more) at 2:1.
|
||||||
|
// A failed scan loses every scanner and reveals the scanner to the target; a successful one loses 0.5*(sd/sa)^1.5.
|
||||||
|
function resolveScan(sa, sd) {
|
||||||
|
const success = sa > sd;
|
||||||
|
return {
|
||||||
|
success,
|
||||||
|
detail: !success ? 'none' : (sa >= MIL.scanBuildingsRatio * sd ? 'full' : 'basic'),
|
||||||
|
identityRevealed: !success,
|
||||||
|
lossFraction: success ? MIL.raidLossFactor * Math.pow(sd / sa, MIL.scanLossExponent) : 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- incumbent (NPC) sites
|
||||||
|
// Static defence of the site at (x, y); ageDays = world age in world days (real days * speed).
|
||||||
|
function incumbentDefence(seed, x, y, ageDays) {
|
||||||
|
const f = 1 + D.INCUMBENT.variance * (2 * (hash(seed ^ 0x1ac0, x, y) / 4294967296) - 1);
|
||||||
|
return Math.round(D.INCUMBENT.baseDefence * f * (1 + D.INCUMBENT.perDayGrowth * Math.max(0, ageDays)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- power: when the battery is empty, units go offline and are decommissioned later
|
||||||
|
const decommissionMs = (speed) => Math.round(MIL.decommissionHours * HOUR / (speed || 1));
|
||||||
|
// units = { unit: count } of everything drawing power in one POP; allowedDraw = output minus building draw.
|
||||||
|
// Returns how many of each unit to decommission, most expensive first, until the draw fits.
|
||||||
|
function decommissionPlan(units, allowedDraw) {
|
||||||
|
let draw = 0;
|
||||||
|
for (const k of Object.keys(units)) draw += (units[k] || 0) * unitDef(k).draw;
|
||||||
|
const order = Object.keys(units).filter((k) => units[k] > 0).sort((a, b) => unitValue(b) - unitValue(a) || (a < b ? -1 : 1));
|
||||||
|
const remove = {};
|
||||||
|
for (const k of order) {
|
||||||
|
if (draw <= Math.max(0, allowedDraw) + 1e-9) break;
|
||||||
|
const d = unitDef(k).draw;
|
||||||
|
const n = d > 0 ? Math.min(units[k], Math.ceil((draw - Math.max(0, allowedDraw)) / d)) : 0;
|
||||||
|
if (n > 0) { remove[k] = n; draw -= n * d; }
|
||||||
|
}
|
||||||
|
return remove;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink
|
||||||
|
const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building);
|
||||||
|
// Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources.
|
||||||
|
function transportPlan(town, cargo, activeLinks, now) {
|
||||||
|
let total = 0;
|
||||||
|
for (const r of Object.keys(cargo || {})) {
|
||||||
|
if (D.RESOURCES.indexOf(r) < 0 || !Number.isInteger(cargo[r]) || cargo[r] < 0) return { ok: false, code: 'validation_failed' };
|
||||||
|
total += cargo[r];
|
||||||
|
}
|
||||||
|
if (total < 1) return { ok: false, code: 'validation_failed' };
|
||||||
|
if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks };
|
||||||
|
if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total };
|
||||||
|
const have = resourcesAt(town, now).amounts;
|
||||||
|
for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' };
|
||||||
|
return { ok: true, total };
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
|
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
|
||||||
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
|
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
|
||||||
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
|
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
|
||||||
|
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
|
||||||
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,
|
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,
|
||||||
};
|
};
|
||||||
}));
|
}));
|
||||||
|
|
|
||||||
84
public/js/screens/alerts.js
Normal file
84
public/js/screens/alerts.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
'use strict';
|
||||||
|
/* Alerts: the durable notification feed (GET /notifications). Newest first; what arrived since you last looked is marked. */
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon } = UI;
|
||||||
|
const PAGE = 100, MAX_PAGES = 5;
|
||||||
|
|
||||||
|
let box, listEl, statusEl, items = [], seenAtOpen = 0, loading = false, offTick = null;
|
||||||
|
|
||||||
|
function townName(id) {
|
||||||
|
const t = App.state.towns.find((x) => x.id === id);
|
||||||
|
return t ? t.name : '#' + id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One entry per notification type: icon + title + detail. Unknown types still show something readable.
|
||||||
|
function describe(n) {
|
||||||
|
const p = n.payload || {};
|
||||||
|
if (n.type === 'build_done') {
|
||||||
|
return { icon: 'b-' + p.type, title: App.t('alerts.build_done', { name: App.buildingName(p.type), level: p.level }), detail: App.t('alerts.build_done.in', { town: townName(p.townId) }), go: 'pop' };
|
||||||
|
}
|
||||||
|
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
clear(listEl);
|
||||||
|
if (!items.length) { listEl.appendChild(h('p', { class: 'empty pad', text: App.t('alerts.empty') })); return; }
|
||||||
|
const now = App.now();
|
||||||
|
for (const n of items.slice().reverse()) {
|
||||||
|
const d = describe(n);
|
||||||
|
const isNew = n.id > seenAtOpen;
|
||||||
|
listEl.appendChild(h('li', null,
|
||||||
|
h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go); } },
|
||||||
|
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||||
|
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: d.title }), isNew ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
|
||||||
|
d.detail ? h('span', { class: 'row-sub', text: d.detail }) : null),
|
||||||
|
h('span', { class: 'when mono', dataset: { at: n.createdAt }, text: App.fmt.ago(now - n.createdAt) }))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
if (loading) return;
|
||||||
|
loading = true;
|
||||||
|
statusEl.hidden = true;
|
||||||
|
try {
|
||||||
|
let after = items.length ? items[items.length - 1].id : 0;
|
||||||
|
for (let page = 0; page < MAX_PAGES; page++) {
|
||||||
|
const r = await App.api.get('/notifications', { after, limit: PAGE });
|
||||||
|
items = items.concat(r.items);
|
||||||
|
if (r.next === null || !r.items.length) break;
|
||||||
|
after = r.next;
|
||||||
|
}
|
||||||
|
draw();
|
||||||
|
if (items.length) App.markSeen(items[items.length - 1].id); else App.markSeen(0);
|
||||||
|
} catch (e) {
|
||||||
|
statusEl.textContent = App.t('alerts.error') + ' ' + App.errMsg(e);
|
||||||
|
statusEl.hidden = false;
|
||||||
|
} finally { loading = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
|
||||||
|
render(container) {
|
||||||
|
box = container;
|
||||||
|
listEl = h('ul', { class: 'alert-list' });
|
||||||
|
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
box.appendChild(h('div', { class: 'page' },
|
||||||
|
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.alerts') }),
|
||||||
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
|
||||||
|
statusEl, listEl));
|
||||||
|
App.on('session', () => { items = []; });
|
||||||
|
},
|
||||||
|
onShow() {
|
||||||
|
seenAtOpen = App.getSeen();
|
||||||
|
box.querySelector('h1').textContent = App.t('screen.alerts');
|
||||||
|
draw();
|
||||||
|
load();
|
||||||
|
if (offTick) offTick();
|
||||||
|
offTick = App.onTick(() => {
|
||||||
|
const now = App.now();
|
||||||
|
for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onHide() { if (offTick) offTick(); offTick = null; },
|
||||||
|
});
|
||||||
|
}());
|
||||||
100
public/js/screens/auth.js
Normal file
100
public/js/screens/auth.js
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
'use strict';
|
||||||
|
/* Login / signup. Not in the nav. The invite field appears when the server answers signup_closed. */
|
||||||
|
(function () {
|
||||||
|
const { h, icon, clear } = UI;
|
||||||
|
let box, mode = 'login', needInvite = false, busy = false;
|
||||||
|
let refs = {};
|
||||||
|
|
||||||
|
function deviceName() {
|
||||||
|
const ua = navigator.userAgent || '';
|
||||||
|
const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser';
|
||||||
|
const os = /Android/.test(ua) ? 'Android' : /iPhone|iPad|iPod/.test(ua) ? 'iOS' : /Windows/.test(ua) ? 'Windows' : /Mac OS/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : '';
|
||||||
|
return (browser + (os ? ' on ' + os : '')).slice(0, 40);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(msg) { refs.err.textContent = msg || ''; refs.err.hidden = !msg; }
|
||||||
|
|
||||||
|
function validationMessage(err) {
|
||||||
|
const list = err.details && err.details.errors;
|
||||||
|
const base = App.t('err.validation_failed');
|
||||||
|
if (Array.isArray(list) && list.length) {
|
||||||
|
const f = list[0];
|
||||||
|
const path = String(f.path || '').replace(/^\$?\.?/, '');
|
||||||
|
return base + (path ? ' (' + path + ')' : '');
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(ev) {
|
||||||
|
ev.preventDefault();
|
||||||
|
if (busy) return;
|
||||||
|
showError('');
|
||||||
|
const username = refs.user.value.trim(), password = refs.pass.value;
|
||||||
|
if (!username || !password) { showError(App.t('err.validation_failed')); return; }
|
||||||
|
busy = true; refs.go.disabled = true; refs.goText.textContent = App.t('auth.working');
|
||||||
|
try {
|
||||||
|
let r;
|
||||||
|
if (mode === 'signup') {
|
||||||
|
const body = { username, password, device: deviceName() };
|
||||||
|
if (needInvite && refs.invite.value.trim()) body.invite = refs.invite.value.trim();
|
||||||
|
r = await App.api.post('/auth/signup', body, { auth: false });
|
||||||
|
} else {
|
||||||
|
r = await App.api.post('/auth/login', { username, password, device: deviceName() }, { auth: false });
|
||||||
|
}
|
||||||
|
App.api.setToken(r.token);
|
||||||
|
App.setSession(r.user, r.operators);
|
||||||
|
refs.pass.value = '';
|
||||||
|
App.authNotice = null;
|
||||||
|
await App.enter('pop');
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code === 'signup_closed') { needInvite = true; draw(); refs.invite.focus(); showError(App.t('auth.invite.hint')); }
|
||||||
|
else if (e.code === 'validation_failed') showError(validationMessage(e));
|
||||||
|
else showError(App.errMsg(e));
|
||||||
|
} finally {
|
||||||
|
busy = false;
|
||||||
|
if (refs.go) { refs.go.disabled = false; refs.goText.textContent = App.t(mode === 'signup' ? 'auth.signup' : 'auth.login'); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function field(id, label, input, hint) {
|
||||||
|
return h('label', { class: 'field', for: id }, h('span', { class: 'field-lbl', text: label }), input, hint ? h('span', { class: 'field-hint', text: hint }) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
const keep = { u: refs.user ? refs.user.value : '', p: refs.pass ? refs.pass.value : '', i: refs.invite ? refs.invite.value : '', e: refs.err ? refs.err.textContent : '' };
|
||||||
|
clear(box);
|
||||||
|
const signup = mode === 'signup';
|
||||||
|
refs.user = h('input', { id: 'f-user', name: 'username', type: 'text', autocomplete: 'username', autocapitalize: 'none', autocorrect: 'off', spellcheck: 'false', required: true, minlength: signup ? '3' : null, maxlength: '20', pattern: signup ? '[A-Za-z0-9_\\-]{3,20}' : null, enterkeyhint: 'next' });
|
||||||
|
refs.pass = h('input', { id: 'f-pass', name: 'password', type: 'password', autocomplete: signup ? 'new-password' : 'current-password', required: true, minlength: signup ? '8' : null, maxlength: '128', enterkeyhint: needInvite && signup ? 'next' : 'go' });
|
||||||
|
refs.invite = h('input', { id: 'f-invite', name: 'invite', type: 'text', autocomplete: 'off', autocapitalize: 'none', spellcheck: 'false', maxlength: '64', enterkeyhint: 'go' });
|
||||||
|
refs.user.value = keep.u; refs.pass.value = keep.p; refs.invite.value = keep.i;
|
||||||
|
refs.err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
refs.goText = h('span', { text: App.t(signup ? 'auth.signup' : 'auth.login') });
|
||||||
|
refs.go = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), refs.goText);
|
||||||
|
const notice = App.authNotice ? h('p', { class: 'notice', text: App.authNotice }) : null;
|
||||||
|
|
||||||
|
const form = h('form', { class: 'auth-form', novalidate: false, onsubmit: submit },
|
||||||
|
h('h1', { class: 'auth-h', text: App.t(signup ? 'auth.signup' : 'auth.login') }),
|
||||||
|
notice,
|
||||||
|
field('f-user', App.t('auth.username'), refs.user, signup ? App.t('auth.username.hint') : null),
|
||||||
|
field('f-pass', App.t('auth.password'), refs.pass, signup ? App.t('auth.password.hint') : null),
|
||||||
|
signup && needInvite ? field('f-invite', App.t('auth.invite'), refs.invite) : null,
|
||||||
|
refs.err, refs.go,
|
||||||
|
h('button', { class: 'linklike', type: 'button', onclick: () => { mode = signup ? 'login' : 'signup'; draw(); } }, App.t(signup ? 'auth.toLogin' : 'auth.toSignup')));
|
||||||
|
|
||||||
|
box.appendChild(h('div', { class: 'auth-card' },
|
||||||
|
h('div', { class: 'auth-logo' }, h('span', { class: 'brand-mark big', 'aria-hidden': 'true' }), h('span', { class: 'auth-name', text: App.t('app.name') })),
|
||||||
|
h('p', { class: 'auth-tag', text: App.t('app.tagline') }),
|
||||||
|
form,
|
||||||
|
h('div', { class: 'lang-switch', role: 'group', 'aria-label': App.t('settings.language') },
|
||||||
|
...['en', 'nb'].map((l) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(App.state.lang === l), onclick: () => App.setLang(l) }, l === 'en' ? 'EN' : 'NB')))));
|
||||||
|
if (keep.e) showError(keep.e);
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'auth', titleKey: 'app.name', nav: false, hud: false,
|
||||||
|
render(container) { box = container; },
|
||||||
|
onShow() { draw(); if (window.matchMedia('(pointer: fine)').matches) setTimeout(() => { if (refs.user) refs.user.focus({ preventScroll: true }); }, 50); },
|
||||||
|
onLang() { draw(); },
|
||||||
|
});
|
||||||
|
}());
|
||||||
220
public/js/screens/map.js
Normal file
220
public/js/screens/map.js
Normal file
|
|
@ -0,0 +1,220 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the
|
||||||
|
* tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40
|
||||||
|
* chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are
|
||||||
|
* implied by the API (only rural areas, incumbent sites and POPs are listed).
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h, icon, openSheet, closeSheet, toast } = UI;
|
||||||
|
const R = UpstreamRules;
|
||||||
|
const F = UpstreamData.FORMULAS;
|
||||||
|
|
||||||
|
const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ chunk store
|
||||||
|
class Store {
|
||||||
|
constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; }
|
||||||
|
reset() { this.chunks.clear(); }
|
||||||
|
key(i, j) { return i + ',' + j; }
|
||||||
|
|
||||||
|
// Make sure every chunk touching the rect is loaded and fresh.
|
||||||
|
ensure(v, radius) {
|
||||||
|
const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK);
|
||||||
|
const want = [];
|
||||||
|
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
|
||||||
|
if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue;
|
||||||
|
const c = this.chunks.get(this.key(i, j));
|
||||||
|
const now = Date.now();
|
||||||
|
if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]);
|
||||||
|
}
|
||||||
|
// nearest to the view centre first
|
||||||
|
want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy));
|
||||||
|
for (const [i, j] of want) this.fetch(i, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetch(i, j) {
|
||||||
|
const k = this.key(i, j);
|
||||||
|
const prev = this.chunks.get(k);
|
||||||
|
if (prev && prev.state === 'loading') return;
|
||||||
|
if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; }
|
||||||
|
const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 };
|
||||||
|
rec.state = 'loading';
|
||||||
|
this.chunks.set(k, rec);
|
||||||
|
this.active++;
|
||||||
|
const x0 = i * CHUNK, y0 = j * CHUNK;
|
||||||
|
try {
|
||||||
|
const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 });
|
||||||
|
const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK;
|
||||||
|
rec.specials = r.specials.filter(inChunk);
|
||||||
|
rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s]));
|
||||||
|
rec.towns = r.towns.filter(inChunk);
|
||||||
|
rec.state = 'ok'; rec.at = Date.now();
|
||||||
|
} catch (e) {
|
||||||
|
rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails
|
||||||
|
if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); }
|
||||||
|
} finally {
|
||||||
|
this.active--;
|
||||||
|
if (this.onChange) this.onChange();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); }
|
||||||
|
special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; }
|
||||||
|
townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; }
|
||||||
|
loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; }
|
||||||
|
|
||||||
|
forEachSpecial(x0, y0, x1, y1, fn) {
|
||||||
|
for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s);
|
||||||
|
}
|
||||||
|
townsInRect(x0, y0, x1, y1) {
|
||||||
|
const out = [];
|
||||||
|
for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// After a rename the capital on the map must not show a stale name.
|
||||||
|
patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ screen
|
||||||
|
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
|
||||||
|
const store = new Store();
|
||||||
|
let infoSheet = null;
|
||||||
|
|
||||||
|
const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null);
|
||||||
|
const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null;
|
||||||
|
|
||||||
|
function updateCoords() {
|
||||||
|
if (!coordsEl || !view) return;
|
||||||
|
coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function centreOnOwn() {
|
||||||
|
const c = App.state.towns.find((t) => t.id === App.state.townId) || capital();
|
||||||
|
if (!c) return;
|
||||||
|
view.setView(c.x, c.y, 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
if (ready) return;
|
||||||
|
ready = true;
|
||||||
|
canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') });
|
||||||
|
coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' });
|
||||||
|
legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' });
|
||||||
|
const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name));
|
||||||
|
const controls = h('div', { class: 'map-controls' },
|
||||||
|
zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)),
|
||||||
|
zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)),
|
||||||
|
zoomBtn('locate', App.t('map.centre'), centreOnOwn));
|
||||||
|
controls.dataset.role = 'controls';
|
||||||
|
box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls);
|
||||||
|
|
||||||
|
const source = {
|
||||||
|
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
|
||||||
|
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
|
||||||
|
isOwn: (t) => t.owner.id === ownOperatorId(),
|
||||||
|
};
|
||||||
|
view = new MapRender.MapView(canvas, source, {
|
||||||
|
onTap: onTap,
|
||||||
|
onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); },
|
||||||
|
});
|
||||||
|
view.labelFn = (t, own) => (own ? t.name : t.owner.name);
|
||||||
|
view.reachTiles = F.ruralReach;
|
||||||
|
store.onChange = () => view.invalidate();
|
||||||
|
new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box);
|
||||||
|
// The camera moves are frequent; keep the coords chip in step cheaply.
|
||||||
|
canvas.addEventListener('pointermove', () => updateCoords());
|
||||||
|
canvas.addEventListener('wheel', () => updateCoords(), { passive: true });
|
||||||
|
drawLegend();
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawLegend() {
|
||||||
|
UI.clear(legendEl);
|
||||||
|
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
|
||||||
|
legendEl.appendChild(item('you', App.t('map.legend.you')));
|
||||||
|
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
||||||
|
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
||||||
|
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tile info
|
||||||
|
function onTap(x, y) {
|
||||||
|
const w = App.state.world;
|
||||||
|
if (!w) return;
|
||||||
|
if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return;
|
||||||
|
showTile(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showTile(x, y) {
|
||||||
|
view.setSelected(x, y);
|
||||||
|
const town = store.townAt(x, y);
|
||||||
|
const special = store.special(x, y);
|
||||||
|
const known = store.loaded(x, y);
|
||||||
|
const type = town ? 'pop' : special ? special.type : 'land';
|
||||||
|
const cap = capital();
|
||||||
|
const body = [];
|
||||||
|
const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value }));
|
||||||
|
|
||||||
|
if (town) {
|
||||||
|
const own = town.owner.id === ownOperatorId();
|
||||||
|
body.push(h('div', { class: 'pill-row' },
|
||||||
|
own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }),
|
||||||
|
town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null,
|
||||||
|
town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null));
|
||||||
|
body.push(row(App.t('map.info.operator'), town.owner.name));
|
||||||
|
body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber)));
|
||||||
|
} else if (special && special.type === 'rural') {
|
||||||
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) }));
|
||||||
|
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
|
||||||
|
} else if (special && special.type === 'incumbent') {
|
||||||
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
|
||||||
|
} else if (!known) {
|
||||||
|
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
|
||||||
|
} else {
|
||||||
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
||||||
|
}
|
||||||
|
body.push(row('', App.t('map.info.coords', { x, y })));
|
||||||
|
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
||||||
|
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
||||||
|
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
||||||
|
}
|
||||||
|
const title = town ? town.name : App.t('tile.' + type);
|
||||||
|
infoSheet = openSheet({
|
||||||
|
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
|
||||||
|
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
|
||||||
|
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ screen registration
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true,
|
||||||
|
render(container) {
|
||||||
|
box = container;
|
||||||
|
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
|
||||||
|
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
|
||||||
|
},
|
||||||
|
onShow(params) {
|
||||||
|
visible = true;
|
||||||
|
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
|
||||||
|
setup();
|
||||||
|
view.setWorld(App.state.world.mapRadius);
|
||||||
|
const apply = () => {
|
||||||
|
if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40);
|
||||||
|
else if (pendingFocus) { centreOnOwn(); pendingFocus = null; }
|
||||||
|
else view.setView(view.cx, view.cy);
|
||||||
|
updateCoords();
|
||||||
|
};
|
||||||
|
// the container was display:none until now: measure after layout
|
||||||
|
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
|
||||||
|
},
|
||||||
|
onHide() { visible = false; closeSheet(); },
|
||||||
|
onLang() {
|
||||||
|
if (!ready) return;
|
||||||
|
canvas.setAttribute('aria-label', App.t('map.label'));
|
||||||
|
drawLegend();
|
||||||
|
const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre'];
|
||||||
|
box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i])));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}());
|
||||||
495
public/js/screens/pop.js
Normal file
495
public/js/screens/pop.js
Normal file
|
|
@ -0,0 +1,495 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* POP screen: header, build queue, power, resource fields (grouped by type), infrastructure; tap a building for
|
||||||
|
* the detail sheet. All numbers come from GET /towns/:id (the server's "next" plan decides what is buildable); the
|
||||||
|
* client only ticks values forward with rules.js and re-checks affordability live, so a button wakes up the moment
|
||||||
|
* the resources are there. Countdowns come from the server clock (App.now()).
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
|
||||||
|
const R = UpstreamRules;
|
||||||
|
const D = UpstreamData;
|
||||||
|
const F = D.FORMULAS;
|
||||||
|
|
||||||
|
let box = null, dirty = true, visible = false;
|
||||||
|
let refs = { tiles: new Map(), rows: new Map(), queue: [] };
|
||||||
|
let offTick = null;
|
||||||
|
let prevQueue = null;
|
||||||
|
const refetchTries = new Map(); // queue event id -> refetch attempts after it came due
|
||||||
|
let sheetCtl = null;
|
||||||
|
|
||||||
|
const td = () => App.state.townData;
|
||||||
|
const find = (key) => (td() ? td().buildings.find((b) => b.key === key) : null);
|
||||||
|
const resOf = (type) => D.FIELD_PRODUCES[type] || null;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ building state (live)
|
||||||
|
// 'queued' | 'ready' | 'locked' | 'max' | 'wait'. `code` is the reason it cannot be built now (null = can).
|
||||||
|
function stateOf(b, cur) {
|
||||||
|
const t = td();
|
||||||
|
if (t.queue.some((q) => q.key === b.key)) return { st: 'queued', code: 'already_queued' };
|
||||||
|
if (b.level >= b.maxLevel) return { st: 'max', code: 'max_level' };
|
||||||
|
const n = b.next;
|
||||||
|
let code = n.code;
|
||||||
|
if (code === 'not_enough_resources' && cur && n.cost) {
|
||||||
|
let ok = true;
|
||||||
|
for (const r of D.RESOURCES) if (cur.amounts[r] + 1e-6 < n.cost[r]) ok = false;
|
||||||
|
if (ok) code = null;
|
||||||
|
}
|
||||||
|
if (code === null) return { st: 'ready', code: null };
|
||||||
|
if (code === 'requirements_not_met') return { st: 'locked', code };
|
||||||
|
return { st: 'wait', code };
|
||||||
|
}
|
||||||
|
|
||||||
|
// How long until the resources for `cost` are there (ms), or null if never (rate 0) / Infinity if above the storage cap.
|
||||||
|
function etaFor(cost, cur) {
|
||||||
|
let worst = 0;
|
||||||
|
for (const r of D.RESOURCES) {
|
||||||
|
const need = cost[r] - cur.amounts[r];
|
||||||
|
if (need <= 0) continue;
|
||||||
|
if (cost[r] > cur.caps[r]) return Infinity;
|
||||||
|
const rate = cur.rates[r];
|
||||||
|
if (rate <= 0) return null;
|
||||||
|
worst = Math.max(worst, need / rate * D.HOUR_MS);
|
||||||
|
}
|
||||||
|
return worst;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ pieces
|
||||||
|
function costChips(cost, cur, withHave) {
|
||||||
|
return h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
|
||||||
|
const short = cur && cur.amounts[r] + 1e-6 < cost[r];
|
||||||
|
return h('span', { class: 'cost ' + r + (short ? ' short' : ''), dataset: { res: r } }, icon(r),
|
||||||
|
h('b', { text: App.fmt.num(cost[r]) }),
|
||||||
|
withHave && cur ? h('small', { text: App.t('sheet.have', { n: App.fmt.num(cur.amounts[r]) }) }) : null);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmt2 = (x) => x.toFixed(2).replace('.', App.state.lang === 'nb' ? ',' : '.');
|
||||||
|
|
||||||
|
function levelPreview(b, toLevel) {
|
||||||
|
// [{ text }] lines describing what the next level changes, from rules.js.
|
||||||
|
const t = td(), rt = App.rulesTown(), world = App.state.world;
|
||||||
|
const lines = [];
|
||||||
|
const fmt = App.fmt;
|
||||||
|
const withLevel = (lvl) => {
|
||||||
|
const bb = Object.assign({}, rt.buildings);
|
||||||
|
bb[b.key] = { type: b.type, level: lvl };
|
||||||
|
return Object.assign({}, rt, { buildings: bb });
|
||||||
|
};
|
||||||
|
if (b.kind === 'field') {
|
||||||
|
const res = resOf(b.type);
|
||||||
|
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
|
||||||
|
const a = R.fieldOutputPerHour(b.level) * mult, c = R.fieldOutputPerHour(toLevel) * mult;
|
||||||
|
lines.push(App.t('sheet.preview.output', { a: fmt.dec(a), b: fmt.dec(c) }) + ' ' + App.resName(res));
|
||||||
|
} else if (b.type === 'rack_hall') {
|
||||||
|
lines.push(App.t('sheet.preview.storage', { a: fmt.num(R.storageCap(withLevel(b.level))), b: fmt.num(R.storageCap(withLevel(toLevel))) }));
|
||||||
|
} else if (b.type === 'battery_bank') {
|
||||||
|
lines.push(App.t('sheet.preview.battery', { a: fmt.num(R.batteryCap(withLevel(b.level))), b: fmt.num(R.batteryCap(withLevel(toLevel))) }));
|
||||||
|
} else if (b.type === 'core_router') {
|
||||||
|
const k = (l) => fmt2(1 / (1 + F.coreSpeedPerLevel * l));
|
||||||
|
lines.push(App.t('sheet.preview.core', { a: k(b.level), b: k(toLevel) }));
|
||||||
|
if (toLevel === F.secondQueueCoreLevel) lines.push(App.t('sheet.preview.core2', { n: toLevel }));
|
||||||
|
} else if (b.type === 'firewall') {
|
||||||
|
lines.push(App.t('sheet.preview.firewall', { a: fmt2(1 + F.firewallPerLevel * b.level), b: fmt2(1 + F.firewallPerLevel * toLevel) }));
|
||||||
|
}
|
||||||
|
const def = D.BUILDINGS[b.type];
|
||||||
|
if (def && def.draw > 0) lines.push(App.t('sheet.preview.draw', { n: def.draw }));
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requirementList(b) {
|
||||||
|
const def = D.BUILDINGS[b.type];
|
||||||
|
const levels = {};
|
||||||
|
for (const x of td().buildings) if (x.kind === 'infra') levels[x.type] = x.level;
|
||||||
|
return (def.requires || []).map((rq) => {
|
||||||
|
const have = levels[rq.type] || 0, ok = have >= rq.level;
|
||||||
|
return h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
|
||||||
|
h('span', { text: App.buildingName(rq.type) + ' ' + App.t('pop.level', { n: rq.level }) }),
|
||||||
|
h('small', { text: App.t('sheet.have', { n: have }) }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ detail sheet
|
||||||
|
function openBuilding(key, opts) {
|
||||||
|
const first = find(key);
|
||||||
|
if (!first) return;
|
||||||
|
const R_ = { cur: null };
|
||||||
|
const body = h('div', { class: 'detail' });
|
||||||
|
const ctl = openSheet({
|
||||||
|
title: App.buildingName(first.type), icon: 'b-' + first.type, iconClass: first.kind === 'field' ? 'res-' + resOf(first.type) : '',
|
||||||
|
closeLabel: App.t('common.close'), body,
|
||||||
|
onClose: () => { if (offSheetTick) offSheetTick(); offSheetTick = null; sheetCtl = null; },
|
||||||
|
});
|
||||||
|
sheetCtl = ctl;
|
||||||
|
let offSheetTick = null;
|
||||||
|
|
||||||
|
const els = {};
|
||||||
|
function build() {
|
||||||
|
for (const k of Object.keys(els)) delete els[k];
|
||||||
|
const b = find(key);
|
||||||
|
if (!b) { ctl.close(); return; }
|
||||||
|
const cur = App.resourcesNow();
|
||||||
|
clear(body);
|
||||||
|
body.appendChild(h('p', { class: 'detail-desc', text: App.buildingDesc(b.type) }));
|
||||||
|
body.appendChild(h('div', { class: 'detail-level' },
|
||||||
|
h('span', { class: 'lvl-now', text: b.level > 0 ? App.t('sheet.level', { n: b.level }) : App.t('pop.notBuilt') }),
|
||||||
|
b.level < b.maxLevel ? h('span', { class: 'lvl-next' }, icon('up'), App.t('sheet.nextLevel', { n: b.level + 1 })) : h('span', { class: 'lvl-next', text: App.t('sheet.maxed') })));
|
||||||
|
|
||||||
|
const queued = td().queue.find((q) => q.key === key);
|
||||||
|
if (queued) {
|
||||||
|
els.qbar = h('i');
|
||||||
|
els.qtime = h('b', { class: 'mono' });
|
||||||
|
body.appendChild(h('div', { class: 'detail-queue' },
|
||||||
|
h('div', { class: 'row' }, h('span', { text: App.t('sheet.underway') + ' · ' + App.t('pop.queue.to', { n: queued.toLevel }) }), els.qtime),
|
||||||
|
h('div', { class: 'bar' }, els.qbar)));
|
||||||
|
els.cancel = h('button', { class: 'btn danger wide', type: 'button', onclick: () => confirmCancel(queued) }, icon('x'), App.t('sheet.cancel'));
|
||||||
|
body.appendChild(els.cancel);
|
||||||
|
updateQueueEls(queued, App.now());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (b.level >= b.maxLevel) return;
|
||||||
|
|
||||||
|
const to = b.level + 1;
|
||||||
|
const next = b.next;
|
||||||
|
for (const text of levelPreview(b, to)) body.appendChild(h('p', { class: 'preview', text }));
|
||||||
|
els.costs = costChips(next.cost, cur, true);
|
||||||
|
body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') }));
|
||||||
|
body.appendChild(els.costs);
|
||||||
|
body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('sheet.time') + ': ' }), h('b', { text: App.fmt.dur(next.durationMs) })));
|
||||||
|
const reqs = requirementList(b);
|
||||||
|
if (reqs.length) { body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.requires') })); body.appendChild(h('ul', { class: 'reqs' }, reqs)); }
|
||||||
|
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
|
||||||
|
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => doBuild(b.key) }, icon('up'), h('span', { text: App.t(b.level > 0 ? 'sheet.upgrade' : 'sheet.build', { n: to }) }));
|
||||||
|
body.appendChild(els.reason);
|
||||||
|
body.appendChild(els.btn);
|
||||||
|
updateLive();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateQueueEls(q, now) {
|
||||||
|
const left = q.dueAt - now;
|
||||||
|
els.qtime.textContent = App.fmt.clock(left);
|
||||||
|
els.qbar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
|
||||||
|
}
|
||||||
|
|
||||||
|
let busy = false;
|
||||||
|
function updateLive() {
|
||||||
|
const b = find(key);
|
||||||
|
if (!b || !els.btn) return;
|
||||||
|
const cur = App.resourcesNow();
|
||||||
|
const s = stateOf(b, cur);
|
||||||
|
for (const chip of els.costs.children) chip.classList.toggle('short', cur.amounts[chip.dataset.res] + 1e-6 < b.next.cost[chip.dataset.res]);
|
||||||
|
const can = s.code === null && !busy;
|
||||||
|
els.btn.disabled = !can;
|
||||||
|
let reason = '';
|
||||||
|
if (s.code) {
|
||||||
|
reason = App.t('err.' + s.code);
|
||||||
|
if (s.code === 'not_enough_resources') {
|
||||||
|
const eta = etaFor(b.next.cost, cur);
|
||||||
|
if (eta === Infinity) reason = App.t('sheet.capTooLow', { cap: App.fmt.num(cur.caps.fiber) });
|
||||||
|
else if (eta !== null) reason = App.t('sheet.affordableIn', { t: App.fmt.dur(Math.max(1000, eta)) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
els.reason.textContent = reason;
|
||||||
|
els.reason.hidden = !reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doBuild(k) {
|
||||||
|
if (busy) return;
|
||||||
|
busy = true; els.btn.disabled = true;
|
||||||
|
els.btn.querySelector('span').textContent = App.t('sheet.building');
|
||||||
|
const t = td();
|
||||||
|
try {
|
||||||
|
const b = find(k);
|
||||||
|
await App.api.post('/towns/' + t.id + '/build', { key: k }, { intent: 'build:' + t.id + ':' + k });
|
||||||
|
toast(App.t('sheet.built', { name: App.buildingName(b.type), n: b.level + 1 }), 'ok');
|
||||||
|
ctl.close();
|
||||||
|
await App.refreshTown();
|
||||||
|
} catch (e) {
|
||||||
|
toast(App.errMsg(e), 'error');
|
||||||
|
busy = false;
|
||||||
|
try { await App.refreshTown(); } catch (e2) { /* shown by the offline chip */ }
|
||||||
|
if (sheetCtl === ctl) build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmCancel(q) {
|
||||||
|
clear(body);
|
||||||
|
const b = find(key);
|
||||||
|
body.appendChild(h('p', { class: 'detail-desc', text: App.t('sheet.cancel.confirm', { name: App.buildingName(b.type), n: q.toLevel }) }));
|
||||||
|
body.appendChild(h('p', { class: 'preview', text: App.t('sheet.cancel.refund') }));
|
||||||
|
body.appendChild(h('div', { class: 'btn-row' },
|
||||||
|
h('button', { class: 'btn', type: 'button', onclick: () => build() }, App.t('sheet.cancel.keep')),
|
||||||
|
h('button', { class: 'btn danger', type: 'button', onclick: async (ev) => {
|
||||||
|
ev.currentTarget.disabled = true;
|
||||||
|
try {
|
||||||
|
await App.api.del('/towns/' + td().id + '/queue/' + q.id);
|
||||||
|
toast(App.t('sheet.cancelled'), 'ok');
|
||||||
|
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||||
|
ctl.close();
|
||||||
|
App.refreshTown().catch(() => {});
|
||||||
|
} }, icon('x'), App.t('sheet.cancel'))));
|
||||||
|
}
|
||||||
|
|
||||||
|
offSheetTick = App.onTick((now) => {
|
||||||
|
const q = td() && td().queue.find((x) => x.key === key);
|
||||||
|
if (q && els.qtime) updateQueueEls(q, now); else if (els.btn) updateLive();
|
||||||
|
});
|
||||||
|
const offTown = App.on('town', () => { if (sheetCtl === ctl) build(); });
|
||||||
|
const prevClose = offSheetTick;
|
||||||
|
offSheetTick = () => { prevClose(); offTown(); };
|
||||||
|
build();
|
||||||
|
if (opts && opts.cancel) { const q = td().queue.find((x) => x.key === key); if (q) confirmCancel(q); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ main drawing
|
||||||
|
function tileLabel(b, s) {
|
||||||
|
const status = s.st === 'queued' ? App.t('pop.inQueue') : s.st === 'ready' ? App.t('pop.upgradeReady') : s.st === 'max' ? App.t('pop.max') : s.st === 'locked' ? App.t('pop.locked') : '';
|
||||||
|
return App.buildingName(b.type) + ', ' + (b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt')) + (status ? ', ' + status : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function fieldTile(b) {
|
||||||
|
const res = resOf(b.type);
|
||||||
|
const lvl = h('b', { class: 'tile-lvl', text: String(b.level) });
|
||||||
|
const badge = h('span', { class: 'tile-badge', 'aria-hidden': 'true' });
|
||||||
|
const bar = h('i');
|
||||||
|
const el = h('button', { class: 'tile res-' + res, type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
|
||||||
|
icon('b-' + b.type, 'tile-ic'), lvl, badge, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
|
||||||
|
refs.tiles.set(b.key, { el, badge, bar, b });
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function infraRow(b) {
|
||||||
|
const status = h('span', { class: 'pill' });
|
||||||
|
const sub = h('span', { class: 'row-sub' });
|
||||||
|
const bar = h('i');
|
||||||
|
const el = h('button', { class: 'row-btn', type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
|
||||||
|
h('span', { class: 'row-ic' }, icon('b-' + b.type)),
|
||||||
|
h('span', { class: 'row-main' },
|
||||||
|
h('span', { class: 'row-title' }, h('b', { text: App.buildingName(b.type) }), h('span', { class: 'lv', text: b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt') })),
|
||||||
|
sub),
|
||||||
|
status, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
|
||||||
|
refs.rows.set(b.key, { el, status, sub, bar, b });
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function header(t) {
|
||||||
|
const st = App.state;
|
||||||
|
const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r)));
|
||||||
|
const title = st.towns.length > 1
|
||||||
|
? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
|
||||||
|
st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name })))
|
||||||
|
: h('h1', { class: 'town-name', text: t.name });
|
||||||
|
return h('section', { class: 'card pop-head' },
|
||||||
|
h('div', { class: 'pop-title' }, title,
|
||||||
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))),
|
||||||
|
h('div', { class: 'pop-meta' },
|
||||||
|
h('span', { text: App.t('pop.coords', { x: t.x, y: t.y }) }),
|
||||||
|
t.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null,
|
||||||
|
h('span', { class: 'pill' }, icon('shield'), App.t('pop.loyalty') + ' ' + App.fmt.num(t.loyalty)),
|
||||||
|
h('span', { class: 'pill', text: App.t('pop.footprint') + ' ' + App.fmt.num(t.footprint) + ' (' + App.t('pop.footprintPerDay', { n: App.fmt.num(t.footprintPerDay) }) + ')' }),
|
||||||
|
bonus.length ? bonus : h('span', { class: 'pill dim', text: App.t('pop.bonus.none') })));
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRename() {
|
||||||
|
const t = td();
|
||||||
|
const input = h('input', { type: 'text', value: t.name, maxlength: '40', minlength: '2', 'aria-label': App.t('pop.rename.label'), autocomplete: 'off', enterkeyhint: 'done' });
|
||||||
|
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const save = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), App.t('common.save'));
|
||||||
|
const form = h('form', { class: 'detail', onsubmit: async (ev) => {
|
||||||
|
ev.preventDefault();
|
||||||
|
const name = input.value.trim();
|
||||||
|
if (name.length < 2) { err.textContent = App.t('err.validation_failed'); err.hidden = false; return; }
|
||||||
|
save.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await App.api.post('/towns/' + t.id + '/rename', { name });
|
||||||
|
const known = App.state.towns.find((x) => x.id === t.id);
|
||||||
|
if (known) known.name = r.name;
|
||||||
|
toast(App.t('pop.rename.done'), 'ok');
|
||||||
|
sheet.close();
|
||||||
|
await App.refreshTown();
|
||||||
|
} catch (e) { err.textContent = App.errMsg(e); err.hidden = false; save.disabled = false; }
|
||||||
|
} }, h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('pop.rename.label') }), input), err, save);
|
||||||
|
const sheet = openSheet({ title: App.t('pop.rename'), icon: 'pencil', closeLabel: App.t('common.close'), body: form });
|
||||||
|
setTimeout(() => { input.focus(); input.select(); }, 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
function queueCard(t) {
|
||||||
|
refs.queue = [];
|
||||||
|
const slots = h('span', { class: 'pill', text: App.t('pop.queue.slots', { used: t.queue.length, total: t.queueSlots }) });
|
||||||
|
const list = h('div', { class: 'queue' });
|
||||||
|
for (const q of t.queue) {
|
||||||
|
const time = h('b', { class: 'mono' }), bar = h('i');
|
||||||
|
const name = App.buildingName(q.type);
|
||||||
|
list.appendChild(h('div', { class: 'q-item' },
|
||||||
|
h('button', { class: 'q-main', type: 'button', onclick: () => openBuilding(q.key), 'aria-label': name + ' ' + App.t('pop.queue.to', { n: q.toLevel }) },
|
||||||
|
h('span', { class: 'row-ic' }, icon('b-' + q.type)),
|
||||||
|
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), h('span', { class: 'lv', text: App.t('pop.queue.to', { n: q.toLevel }) })),
|
||||||
|
h('span', { class: 'bar' }, bar)),
|
||||||
|
time),
|
||||||
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.queue.cancel') + ': ' + name, onclick: () => openBuilding(q.key, { cancel: true }) }, icon('x'))));
|
||||||
|
refs.queue.push({ q, time, bar });
|
||||||
|
}
|
||||||
|
if (!t.queue.length) list.appendChild(h('p', { class: 'empty', text: App.t('pop.queue.empty') }));
|
||||||
|
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.queue.title') }), slots), list);
|
||||||
|
}
|
||||||
|
|
||||||
|
function powerCard() {
|
||||||
|
refs.power = { out: h('b'), draw: h('b'), net: h('b'), buf: h('span', { class: 'mono' }), bar: h('i'), status: h('p', { class: 'power-status' }) };
|
||||||
|
const p = refs.power;
|
||||||
|
return h('section', { class: 'card power-card' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('power.title'))),
|
||||||
|
h('div', { class: 'stat-row' },
|
||||||
|
h('div', { class: 'stat' }, h('small', { text: App.t('power.out') }), p.out),
|
||||||
|
h('div', { class: 'stat' }, h('small', { text: App.t('power.draw') }), p.draw),
|
||||||
|
h('div', { class: 'stat' }, h('small', { text: App.t('power.net') }), p.net)),
|
||||||
|
h('div', { class: 'row' }, h('span', { class: 'dimmer', text: App.t('power.buffer') }), p.buf),
|
||||||
|
h('div', { class: 'bar power-bar', 'aria-hidden': 'true' }, p.bar), p.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fieldsCard(t) {
|
||||||
|
const fields = t.buildings.filter((b) => b.kind === 'field');
|
||||||
|
const world = App.state.world;
|
||||||
|
const groups = h('div', { class: 'groups' });
|
||||||
|
for (const type of D.FIELD_TYPES) {
|
||||||
|
const list = fields.filter((b) => b.type === type);
|
||||||
|
if (!list.length) continue;
|
||||||
|
const res = resOf(type);
|
||||||
|
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
|
||||||
|
const total = list.reduce((s, b) => s + R.fieldOutputPerHour(b.level) * mult, 0);
|
||||||
|
groups.appendChild(h('div', { class: 'group res-' + res },
|
||||||
|
h('div', { class: 'group-head' }, icon(res), h('b', { text: App.buildingName(type) }), h('span', { class: 'dimmer', text: '×' + list.length }),
|
||||||
|
h('span', { class: 'group-rate', text: App.fmt.dec(total, true) + ' ' + App.resName(res) + App.t('common.perHour') })),
|
||||||
|
h('div', { class: 'tiles' }, list.map(fieldTile))));
|
||||||
|
}
|
||||||
|
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.fields.title') })), groups);
|
||||||
|
}
|
||||||
|
|
||||||
|
function infraCard(t) {
|
||||||
|
const list = t.buildings.filter((b) => b.kind === 'infra');
|
||||||
|
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.infra.title') })), h('div', { class: 'rows' }, list.map(infraRow)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
dirty = false;
|
||||||
|
refs = { tiles: new Map(), rows: new Map(), queue: [] };
|
||||||
|
clear(box);
|
||||||
|
const t = td();
|
||||||
|
if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
|
||||||
|
if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
|
||||||
|
box.appendChild(h('div', { class: 'cols' },
|
||||||
|
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
|
||||||
|
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
|
||||||
|
tick(App.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ ticking
|
||||||
|
function tick(now) {
|
||||||
|
const t = td();
|
||||||
|
if (!t || !refs.power) return;
|
||||||
|
const cur = App.resourcesNow(now);
|
||||||
|
const f = App.fmt;
|
||||||
|
|
||||||
|
// queue countdowns + the refetch when something comes due
|
||||||
|
for (const e of refs.queue) {
|
||||||
|
const q = e.q, left = q.dueAt - now;
|
||||||
|
const time = f.clock(left);
|
||||||
|
if (e.time.textContent !== time) e.time.textContent = time;
|
||||||
|
e.bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
|
||||||
|
if (left <= -300) {
|
||||||
|
const tries = refetchTries.get(q.id) || { n: 0, at: 0 };
|
||||||
|
if (Date.now() >= tries.at) {
|
||||||
|
refetchTries.set(q.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) });
|
||||||
|
App.refreshTown().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tiles and rows
|
||||||
|
const queueByKey = new Map(t.queue.map((q) => [q.key, q]));
|
||||||
|
for (const [key, e] of refs.tiles) {
|
||||||
|
const s = stateOf(e.b, cur);
|
||||||
|
if (e.el.dataset.st !== s.st) {
|
||||||
|
e.el.dataset.st = s.st;
|
||||||
|
e.badge.textContent = '';
|
||||||
|
if (s.st === 'queued') e.badge.appendChild(icon('clock'));
|
||||||
|
else if (s.st === 'ready') e.badge.appendChild(icon('up'));
|
||||||
|
else if (s.st === 'locked') e.badge.appendChild(icon('lock'));
|
||||||
|
e.el.setAttribute('aria-label', tileLabel(e.b, s));
|
||||||
|
}
|
||||||
|
const q = queueByKey.get(key);
|
||||||
|
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
|
||||||
|
}
|
||||||
|
for (const [key, e] of refs.rows) {
|
||||||
|
const s = stateOf(e.b, cur);
|
||||||
|
const q = queueByKey.get(key);
|
||||||
|
let pill = '', pillCls = 'pill', sub = '';
|
||||||
|
if (s.st === 'queued') { pill = f.clock(q.dueAt - now); pillCls += ' amber mono'; sub = App.buildingDesc(e.b.type); }
|
||||||
|
else if (s.st === 'ready') { pill = App.t(e.b.level > 0 ? 'pop.upgradeReady' : 'sheet.build', { n: e.b.level + 1 }); pillCls += ' green'; sub = App.buildingDesc(e.b.type); }
|
||||||
|
else if (s.st === 'max') { pill = App.t('pop.max'); sub = App.buildingDesc(e.b.type); }
|
||||||
|
else if (s.st === 'locked') {
|
||||||
|
const m = (e.b.next.missing || [])[0];
|
||||||
|
pill = m ? App.buildingName(m.type) + ' ' + App.t('pop.level', { n: m.level }) : App.t('pop.locked'); pillCls += ' dim';
|
||||||
|
sub = App.buildingDesc(e.b.type);
|
||||||
|
} else sub = App.buildingDesc(e.b.type);
|
||||||
|
if (e.status.textContent !== pill) e.status.textContent = pill;
|
||||||
|
e.status.className = pillCls;
|
||||||
|
e.status.hidden = !pill;
|
||||||
|
if (e.sub.textContent !== sub) e.sub.textContent = sub;
|
||||||
|
e.el.dataset.st = s.st;
|
||||||
|
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
// power
|
||||||
|
const p = refs.power, net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
|
||||||
|
p.out.textContent = f.dec(cur.rates.powerOut);
|
||||||
|
p.draw.textContent = f.dec(cur.rates.powerDraw);
|
||||||
|
p.net.textContent = f.dec(net, true);
|
||||||
|
p.net.className = net < 0 ? 'bad' : 'good';
|
||||||
|
p.buf.textContent = f.num(buf) + ' / ' + f.num(bcap) + ' ' + App.t('power.unit');
|
||||||
|
p.bar.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
|
||||||
|
const speed = App.state.world.speed || 1;
|
||||||
|
let status, cls = '';
|
||||||
|
if (net < 0) {
|
||||||
|
if (buf <= 0) { status = App.t('power.empty'); cls = 'bad'; }
|
||||||
|
else { status = App.t('power.draining', { t: f.dur(buf / (-net * speed) * D.HOUR_MS) }); cls = 'warn'; }
|
||||||
|
} else if (net > 0 && buf < bcap - 0.01) status = App.t('power.charging', { t: f.dur((bcap - buf) / (net * speed) * D.HOUR_MS) });
|
||||||
|
else status = buf >= bcap - 0.01 && bcap > 0 ? App.t('power.full') : App.t('power.ok');
|
||||||
|
if (p.status.textContent !== status) p.status.textContent = status;
|
||||||
|
p.status.className = 'power-status ' + cls;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ town changed
|
||||||
|
function onTown(t) {
|
||||||
|
// toast for levels that finished since the last fetch
|
||||||
|
if (prevQueue && prevQueue.townId === t.id) {
|
||||||
|
const nowIds = new Set(t.queue.map((q) => q.id));
|
||||||
|
for (const q of prevQueue.items) {
|
||||||
|
if (nowIds.has(q.id)) continue;
|
||||||
|
const b = t.buildings.find((x) => x.key === q.key);
|
||||||
|
if (b && b.level >= q.toLevel) toast(App.t('alerts.build_done', { name: App.buildingName(q.type), level: b.level }), 'ok');
|
||||||
|
refetchTries.delete(q.id);
|
||||||
|
App.checkAlerts();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prevQueue = { townId: t.id, items: t.queue.slice() };
|
||||||
|
if (visible) draw(); else dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', hud: true,
|
||||||
|
render(container) {
|
||||||
|
box = container;
|
||||||
|
App.on('town', onTown);
|
||||||
|
App.on('session', () => { dirty = true; prevQueue = null; });
|
||||||
|
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||||
|
},
|
||||||
|
onShow() {
|
||||||
|
visible = true;
|
||||||
|
draw();
|
||||||
|
if (offTick) offTick();
|
||||||
|
offTick = App.onTick(tick);
|
||||||
|
if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {});
|
||||||
|
},
|
||||||
|
onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); },
|
||||||
|
});
|
||||||
|
}());
|
||||||
84
public/js/screens/settings.js
Normal file
84
public/js/screens/settings.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
'use strict';
|
||||||
|
/* Settings: language, account info, device tokens (list + revoke) and logout. */
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon, toast, openSheet } = UI;
|
||||||
|
const I = UpstreamI18n;
|
||||||
|
|
||||||
|
let box, devicesEl, tokens = null, tokenErr = null;
|
||||||
|
|
||||||
|
function kv(label, value) { return h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value })); }
|
||||||
|
|
||||||
|
async function loadTokens() {
|
||||||
|
try { tokens = (await App.api.get('/auth/tokens')).tokens; tokenErr = null; } catch (e) { tokenErr = App.errMsg(e); }
|
||||||
|
drawDevices();
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawDevices() {
|
||||||
|
if (!devicesEl) return;
|
||||||
|
clear(devicesEl);
|
||||||
|
if (tokenErr) { devicesEl.appendChild(h('p', { class: 'form-error', role: 'alert', text: tokenErr })); return; }
|
||||||
|
if (!tokens) { devicesEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
|
||||||
|
const now = App.now();
|
||||||
|
for (const t of tokens) {
|
||||||
|
devicesEl.appendChild(h('li', { class: 'device' },
|
||||||
|
h('span', { class: 'row-ic' }, icon('device')),
|
||||||
|
h('span', { class: 'row-main' },
|
||||||
|
h('span', { class: 'row-title' }, h('b', { text: t.device || App.t('settings.device.unnamed') }), t.current ? h('span', { class: 'pill accent', text: App.t('settings.device.current') }) : null),
|
||||||
|
h('span', { class: 'row-sub', text: App.t('settings.device.created', { t: App.fmt.ago(now - t.createdAt) }) + ' · ' + App.t('settings.device.lastUsed', { t: App.fmt.ago(now - t.lastUsedAt) }) })),
|
||||||
|
t.current ? null : h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => revoke(t, ev.currentTarget) }, App.t('settings.device.revoke'))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revoke(t, btn) {
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
await App.api.del('/auth/tokens/' + t.id);
|
||||||
|
toast(App.t('settings.device.revoked'), 'ok');
|
||||||
|
} catch (e) { if (e.code !== 'not_found') toast(App.errMsg(e), 'error'); }
|
||||||
|
loadTokens();
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmLogout() {
|
||||||
|
const sheet = openSheet({
|
||||||
|
title: App.t('settings.logout'), icon: 'logout', closeLabel: App.t('common.close'),
|
||||||
|
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: App.t('settings.logout.confirm') }),
|
||||||
|
h('div', { class: 'btn-row' },
|
||||||
|
h('button', { class: 'btn', type: 'button', onclick: () => sheet.close() }, App.t('common.cancel')),
|
||||||
|
h('button', { class: 'btn danger', type: 'button', onclick: async () => {
|
||||||
|
try { await App.api.post('/auth/logout', {}, { retries: 1 }); } catch (e) { /* the token may already be gone */ }
|
||||||
|
sheet.close();
|
||||||
|
App.clearSession();
|
||||||
|
App.authNotice = null;
|
||||||
|
App.go('auth');
|
||||||
|
} }, icon('logout'), App.t('settings.logout')))),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
clear(box);
|
||||||
|
const st = App.state;
|
||||||
|
const op = st.operator, w = st.world;
|
||||||
|
devicesEl = h('ul', { class: 'device-list' });
|
||||||
|
box.appendChild(h('div', { class: 'page' },
|
||||||
|
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.language') })),
|
||||||
|
h('div', { class: 'seg', role: 'group', 'aria-label': App.t('settings.language') },
|
||||||
|
I.LANGS.map((l) => h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(st.lang === l), onclick: () => App.setLang(l) }, App.t('settings.lang.' + l))))),
|
||||||
|
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.account') })),
|
||||||
|
st.user ? kv(App.t('settings.username'), st.user.username) : null,
|
||||||
|
op ? kv(App.t('settings.operator'), op.name) : null,
|
||||||
|
op ? kv(App.t('settings.as'), I.fmtAs(op.asNumber)) : null,
|
||||||
|
w ? kv(App.t('settings.world'), App.t('settings.worldInfo', { name: w.name, speed: w.speed, r: w.mapRadius })) : null,
|
||||||
|
h('button', { class: 'btn danger wide', type: 'button', onclick: confirmLogout }, icon('logout'), App.t('settings.logout'))),
|
||||||
|
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.devices') })),
|
||||||
|
h('p', { class: 'dimmer small', text: App.t('settings.devices.hint') }), devicesEl),
|
||||||
|
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.about') })),
|
||||||
|
h('p', { class: 'dimmer small', text: App.t('settings.about.text') }))));
|
||||||
|
drawDevices();
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
|
||||||
|
render(container) { box = container; App.on('session', () => { tokens = null; }); },
|
||||||
|
onShow() { draw(); loadTokens(); },
|
||||||
|
});
|
||||||
|
}());
|
||||||
132
public/js/ui.js
Normal file
132
public/js/ui.js
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Small DOM helpers shared by the shell and the screens (window.UI). Everything is built with createElement and
|
||||||
|
* textContent: player-controlled strings (POP names, usernames) never go through innerHTML. No inline handlers
|
||||||
|
* (CSP): events are attached with addEventListener.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||||
|
const XLINK = 'http://www.w3.org/1999/xlink';
|
||||||
|
|
||||||
|
// h('button', { class: 'btn', onclick: fn, 'aria-label': 'x', dataset: { k: 1 } }, 'text', childNode, [more])
|
||||||
|
function h(tag, props, ...kids) {
|
||||||
|
const el = document.createElement(tag);
|
||||||
|
if (props) {
|
||||||
|
for (const k of Object.keys(props)) {
|
||||||
|
const v = props[k];
|
||||||
|
if (v === undefined || v === null || v === false) continue;
|
||||||
|
if (k === 'class') el.className = v;
|
||||||
|
else if (k === 'text') el.textContent = v;
|
||||||
|
else if (k === 'dataset') Object.assign(el.dataset, v);
|
||||||
|
else if (k === 'style') { for (const s of Object.keys(v)) el.style.setProperty(s, v[s]); }
|
||||||
|
else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v);
|
||||||
|
else if (v === true) el.setAttribute(k, '');
|
||||||
|
else el.setAttribute(k, String(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
append(el, kids);
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function append(el, kids) {
|
||||||
|
for (const c of kids) {
|
||||||
|
if (c === null || c === undefined || c === false) continue;
|
||||||
|
if (Array.isArray(c)) append(el, c);
|
||||||
|
else el.appendChild(c instanceof Node ? c : document.createTextNode(String(c)));
|
||||||
|
}
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear(el) { while (el.firstChild) el.removeChild(el.firstChild); return el; }
|
||||||
|
|
||||||
|
// <svg class="ic"><use href="icons/sprite.svg#i-name"></use></svg>
|
||||||
|
function icon(name, cls) {
|
||||||
|
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||||
|
svg.setAttribute('class', 'ic' + (cls ? ' ' + cls : ''));
|
||||||
|
svg.setAttribute('aria-hidden', 'true');
|
||||||
|
svg.setAttribute('focusable', 'false');
|
||||||
|
const use = document.createElementNS(SVG_NS, 'use');
|
||||||
|
use.setAttribute('href', 'icons/sprite.svg#i-' + name);
|
||||||
|
use.setAttributeNS(XLINK, 'xlink:href', 'icons/sprite.svg#i-' + name);
|
||||||
|
svg.appendChild(use);
|
||||||
|
return svg;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ toasts
|
||||||
|
function toast(msg, kind) {
|
||||||
|
const root = document.getElementById('toasts');
|
||||||
|
if (!root) return;
|
||||||
|
const el = h('div', { class: 'toast ' + (kind || 'info'), text: msg });
|
||||||
|
root.appendChild(el);
|
||||||
|
while (root.children.length > 3) root.removeChild(root.firstChild);
|
||||||
|
setTimeout(() => { el.classList.add('out'); setTimeout(() => el.remove(), 250); }, kind === 'error' ? 4500 : 2600);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ sheet (bottom sheet on phones, dialog on desktop)
|
||||||
|
// openSheet({ title, icon, body: Node|Node[], onClose }) -> { el, body, close(), setTitle() }
|
||||||
|
let current = null;
|
||||||
|
|
||||||
|
function openSheet(opts) {
|
||||||
|
if (current) current.close(true);
|
||||||
|
const root = document.getElementById('sheet-root');
|
||||||
|
const prevFocus = document.activeElement;
|
||||||
|
const titleId = 'sheet-title';
|
||||||
|
const body = h('div', { class: 'sheet-body' });
|
||||||
|
const titleEl = h('h2', { id: titleId, class: 'sheet-title', text: opts.title || '' });
|
||||||
|
const closeBtn = h('button', { class: 'icon-btn', type: 'button', 'aria-label': opts.closeLabel || 'Close' }, icon('x'));
|
||||||
|
const panel = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId, tabindex: '-1' },
|
||||||
|
h('div', { class: 'sheet-grab', 'aria-hidden': 'true' }),
|
||||||
|
h('div', { class: 'sheet-head' }, opts.icon ? h('span', { class: 'sheet-icon ' + (opts.iconClass || '') }, icon(opts.icon)) : null, titleEl, closeBtn),
|
||||||
|
body);
|
||||||
|
const backdrop = h('div', { class: 'backdrop' });
|
||||||
|
const wrap = h('div', { class: 'sheet-wrap' }, backdrop, panel);
|
||||||
|
append(body, [].concat(opts.body || []));
|
||||||
|
root.appendChild(wrap);
|
||||||
|
requestAnimationFrame(() => wrap.classList.add('open'));
|
||||||
|
|
||||||
|
let closed = false;
|
||||||
|
const api = {
|
||||||
|
el: panel, body,
|
||||||
|
setTitle(s) { titleEl.textContent = s; },
|
||||||
|
close(silent) {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
if (current === api) current = null;
|
||||||
|
document.removeEventListener('keydown', onKey, true);
|
||||||
|
wrap.classList.remove('open');
|
||||||
|
setTimeout(() => wrap.remove(), 200);
|
||||||
|
if (!silent && prevFocus && prevFocus.focus && document.contains(prevFocus)) { try { prevFocus.focus({ preventScroll: true }); } catch (e) { /* gone */ } }
|
||||||
|
if (opts.onClose) opts.onClose();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
function onKey(e) {
|
||||||
|
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); api.close(); return; }
|
||||||
|
if (e.key !== 'Tab') return;
|
||||||
|
const f = panel.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');
|
||||||
|
if (!f.length) return;
|
||||||
|
const first = f[0], last = f[f.length - 1];
|
||||||
|
if (e.shiftKey && (document.activeElement === first || document.activeElement === panel)) { e.preventDefault(); last.focus(); }
|
||||||
|
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKey, true);
|
||||||
|
closeBtn.addEventListener('click', () => api.close());
|
||||||
|
// a sheet opened on finger lift (map tap) must not be closed by the compatibility click that follows the lift
|
||||||
|
const openedAt = Date.now();
|
||||||
|
backdrop.addEventListener('click', () => { if (Date.now() - openedAt > 400) api.close(); });
|
||||||
|
setTimeout(() => { try { panel.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0);
|
||||||
|
current = api;
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSheet() { if (current) current.close(); }
|
||||||
|
const sheetOpen = () => !!current;
|
||||||
|
|
||||||
|
// Cheap safe storage for per-viewer conveniences (language, last screen). Never for anything that must persist.
|
||||||
|
const safeStore = {
|
||||||
|
get(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } },
|
||||||
|
set(k, v) { try { window.localStorage.setItem(k, v); } catch (e) { /* private window */ } },
|
||||||
|
del(k) { try { window.localStorage.removeItem(k); } catch (e) { /* ignore */ } },
|
||||||
|
};
|
||||||
|
|
||||||
|
window.UI = { h, append, clear, icon, toast, openSheet, closeSheet, sheetOpen, safeStore };
|
||||||
|
}());
|
||||||
17
public/manifest.webmanifest
Normal file
17
public/manifest.webmanifest
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"name": "UPSTREAM",
|
||||||
|
"short_name": "UPSTREAM",
|
||||||
|
"description": "A persistent strategy game about rival regional network operators. Build POPs, connect the region, outlast the competition.",
|
||||||
|
"start_url": "./",
|
||||||
|
"scope": "./",
|
||||||
|
"display": "standalone",
|
||||||
|
"orientation": "any",
|
||||||
|
"background_color": "#070b16",
|
||||||
|
"theme_color": "#070b16",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
||||||
|
{ "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
||||||
|
{ "src": "icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
|
||||||
|
]
|
||||||
|
}
|
||||||
180
server/alliances.js
Normal file
180
server/alliances.js
Normal file
|
|
@ -0,0 +1,180 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Alliance data helpers shared by commands, events, queries and (later) the military stage.
|
||||||
|
*
|
||||||
|
* Other modules use the lookups at the bottom:
|
||||||
|
* relationBetween(db, allianceA, allianceB) -> 'war' | 'neutral' | 'nap' | 'confed'
|
||||||
|
* operatorRelation(db, opA, opB) -> 'self' | 'same_alliance' | 'war' | 'neutral' | 'nap' | 'confed'
|
||||||
|
* atWar(db, opA, opB), confederated(db, opA, opB), pactPartners(db, opA, opB)
|
||||||
|
*
|
||||||
|
* Membership is kept in alliance_members (role) and operators.alliance_id (quick lookup). addMember / removeMember
|
||||||
|
* are the only writers of both.
|
||||||
|
*/
|
||||||
|
const R = require('../public/js/rules.js');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
const { GameError } = require('./errors');
|
||||||
|
|
||||||
|
const S = D.SOCIAL;
|
||||||
|
const HOUR = D.HOUR_MS;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ operators and membership
|
||||||
|
|
||||||
|
// The caller's operator. With worldId: the one in that world; without: their oldest. not_found when there is none.
|
||||||
|
function operatorOf(db, userId, worldId) {
|
||||||
|
const row = worldId !== undefined && worldId !== null
|
||||||
|
? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId)
|
||||||
|
: db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
|
||||||
|
if (!row) throw new GameError('not_found', { what: 'operator' });
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best (highest) completed Peering office level over all POPs of an operator.
|
||||||
|
function peeringLevel(db, operatorId) {
|
||||||
|
const r = db.get(`SELECT MAX(b.level) AS lvl FROM buildings b JOIN towns t ON t.id = b.town_id
|
||||||
|
WHERE t.owner_id = ? AND b.type = 'peering_office'`, operatorId);
|
||||||
|
return r && r.lvl ? r.lvl : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = (db, operatorId) => db.get('SELECT operator_id, alliance_id, role, joined_at FROM alliance_members WHERE operator_id = ?', operatorId) || null;
|
||||||
|
const getAlliance = (db, id) => db.get('SELECT * FROM alliances WHERE id = ?', id) || null;
|
||||||
|
const memberCount = (db, allianceId) => db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE alliance_id = ?', allianceId).n;
|
||||||
|
const leaderOf = (db, allianceId) => db.get("SELECT operator_id FROM alliance_members WHERE alliance_id = ? AND role = 'leader'", allianceId);
|
||||||
|
|
||||||
|
// { id, tag, name } or null, for embedding in other views (/me, /map).
|
||||||
|
function allianceBrief(db, id) {
|
||||||
|
if (id === null || id === undefined) return null;
|
||||||
|
const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id);
|
||||||
|
return a || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The cap that applies now: the stored one, raised if the current leader's best Peering office would give more.
|
||||||
|
// Never lowered (a lost building must not kick anyone). Pure read; `refreshCap` persists a raise.
|
||||||
|
function effectiveCap(db, alliance) {
|
||||||
|
const lead = leaderOf(db, alliance.id);
|
||||||
|
const fromLeader = lead ? R.allianceCap(peeringLevel(db, lead.operator_id)) : 0;
|
||||||
|
return Math.max(alliance.size_cap, fromLeader);
|
||||||
|
}
|
||||||
|
function refreshCap(db, alliance) {
|
||||||
|
const cap = effectiveCap(db, alliance);
|
||||||
|
if (cap > alliance.size_cap) { db.run('UPDATE alliances SET size_cap = ? WHERE id = ?', cap, alliance.id); alliance.size_cap = cap; }
|
||||||
|
return cap;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addMember(db, allianceId, operatorId, role, now) {
|
||||||
|
db.run('INSERT INTO alliance_members (operator_id, alliance_id, role, joined_at) VALUES (?, ?, ?, ?)', operatorId, allianceId, role, now);
|
||||||
|
db.run('UPDATE operators SET alliance_id = ? WHERE id = ?', allianceId, operatorId);
|
||||||
|
// Any other open invites of this operator are moot now.
|
||||||
|
db.run("UPDATE alliance_invites SET status = 'cancelled', answered_at = ? WHERE operator_id = ? AND status = 'pending' AND alliance_id <> ?", now, operatorId, allianceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeMember(db, operatorId) {
|
||||||
|
db.run('DELETE FROM alliance_members WHERE operator_id = ?', operatorId);
|
||||||
|
db.run('UPDATE operators SET alliance_id = NULL WHERE id = ?', operatorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authorise an alliance action. Returns { op, alliance, member }. not_found: no such alliance (or the caller has no
|
||||||
|
// operator in its world); forbidden: not a member, or the role may not do `action`.
|
||||||
|
function requireRole(db, userId, allianceId, action) {
|
||||||
|
const alliance = 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 member = membership(db, op.id);
|
||||||
|
if (!member || member.alliance_id !== alliance.id) throw new GameError('forbidden', { need: 'member' });
|
||||||
|
if (action && !R.allianceCan(member.role, action)) throw new GameError('forbidden', { need: action, role: member.role });
|
||||||
|
return { op, alliance, member };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ notifications (rows in `notifications`)
|
||||||
|
|
||||||
|
const userOfOperator = (db, operatorId) => { const r = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return r ? r.user_id : null; };
|
||||||
|
|
||||||
|
function notifyOperator(ctx, operatorId, type, payload) {
|
||||||
|
const o = ctx.db.get('SELECT user_id, world_id FROM operators WHERE id = ?', operatorId);
|
||||||
|
if (o) ctx.scheduler.notify(o.user_id, o.world_id, type, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
// All members of an alliance, optionally only some roles, optionally skipping one operator.
|
||||||
|
function notifyAlliance(ctx, allianceId, type, payload, o) {
|
||||||
|
o = o || {};
|
||||||
|
const rows = ctx.db.all(`SELECT m.operator_id AS oid, m.role AS role, op.user_id AS uid, op.world_id AS wid
|
||||||
|
FROM alliance_members m JOIN operators op ON op.id = m.operator_id WHERE m.alliance_id = ?`, allianceId);
|
||||||
|
for (const r of rows) {
|
||||||
|
if (o.except && r.oid === o.except) continue;
|
||||||
|
if (o.roles && o.roles.indexOf(r.role) < 0) continue;
|
||||||
|
ctx.scheduler.notify(r.uid, r.wid, type, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ dissolving
|
||||||
|
|
||||||
|
// Remove an alliance and everything hanging off it. Counterparts of non-neutral relations are told it is neutral now.
|
||||||
|
function dissolve(ctx, allianceId, reason) {
|
||||||
|
const { db, now } = ctx;
|
||||||
|
const a = getAlliance(db, allianceId);
|
||||||
|
if (!a) return;
|
||||||
|
const brief = { allianceId: a.id, tag: a.tag, name: a.name };
|
||||||
|
notifyAlliance(ctx, a.id, 'alliance_disbanded', Object.assign({ reason }, brief));
|
||||||
|
const rels = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id);
|
||||||
|
for (const r of rels) {
|
||||||
|
const other = r.a_id === a.id ? r.b_id : r.a_id;
|
||||||
|
if (r.pending_event) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, r.pending_event);
|
||||||
|
if (r.state !== 'neutral') notifyAlliance(ctx, other, 'diplomacy_changed', { allianceId: other, otherId: a.id, otherTag: a.tag, from: r.state, to: 'neutral', reason: 'disbanded' });
|
||||||
|
}
|
||||||
|
db.run('DELETE FROM alliance_relations WHERE a_id = ? OR b_id = ?', a.id, a.id);
|
||||||
|
db.run('DELETE FROM alliance_proposals WHERE from_id = ? OR to_id = ?', a.id, a.id);
|
||||||
|
db.run('DELETE FROM alliance_invites WHERE alliance_id = ?', a.id);
|
||||||
|
db.run('DELETE FROM alliance_notes WHERE alliance_id = ?', a.id);
|
||||||
|
const ids = db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id);
|
||||||
|
for (const m of ids) removeMember(db, m.operator_id);
|
||||||
|
db.run('DELETE FROM alliances WHERE id = ?', a.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ relations
|
||||||
|
|
||||||
|
const pairOf = (x, y) => (x < y ? [x, y] : [y, x]);
|
||||||
|
const getRelation = (db, x, y) => { const [a, b] = pairOf(x, y); return db.get('SELECT * FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b) || null; };
|
||||||
|
|
||||||
|
// Set the current state of a pair, clearing any pending change. neutral with nothing pending = no row.
|
||||||
|
function setRelation(db, worldId, x, y, state, now) {
|
||||||
|
const [a, b] = pairOf(x, y);
|
||||||
|
if (state === 'neutral') { db.run('DELETE FROM alliance_relations WHERE a_id = ? AND b_id = ?', a, b); return; }
|
||||||
|
db.run(`INSERT INTO alliance_relations (a_id, b_id, world_id, state, since) VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (a_id, b_id) DO UPDATE SET state = excluded.state, since = excluded.since,
|
||||||
|
pending_to = NULL, pending_at = NULL, pending_by = NULL, pending_event = NULL`, a, b, worldId, state, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark every open proposal between two alliances (either direction) as withdrawn: the state moved on under them.
|
||||||
|
function withdrawProposals(db, x, y, now) {
|
||||||
|
db.run("UPDATE alliance_proposals SET status = 'withdrawn', answered_at = ? WHERE status = 'pending' AND ((from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?))", now, x, y, y, x);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ lookups for other modules
|
||||||
|
|
||||||
|
function relationBetween(db, allianceA, allianceB) {
|
||||||
|
if (!allianceA || !allianceB || allianceA === allianceB) return 'neutral';
|
||||||
|
const r = getRelation(db, allianceA, allianceB);
|
||||||
|
return r ? r.state : 'neutral';
|
||||||
|
}
|
||||||
|
|
||||||
|
function operatorRelation(db, opA, opB) {
|
||||||
|
if (opA === opB) return 'self';
|
||||||
|
const rows = db.all('SELECT id, alliance_id FROM operators WHERE id IN (?, ?)', opA, opB);
|
||||||
|
const a = rows.find((r) => r.id === opA), b = rows.find((r) => r.id === opB);
|
||||||
|
if (!a || !b || !a.alliance_id || !b.alliance_id) return 'neutral';
|
||||||
|
if (a.alliance_id === b.alliance_id) return 'same_alliance';
|
||||||
|
return relationBetween(db, a.alliance_id, b.alliance_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const atWar = (db, opA, opB) => operatorRelation(db, opA, opB) === 'war';
|
||||||
|
// Can reinforce each other and see each other's incoming: same alliance or confederation.
|
||||||
|
const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'confed' || r === 'same_alliance'; };
|
||||||
|
// May not attack each other: same alliance, NAP or confederation.
|
||||||
|
const pactPartners = (db, opA, opB) => { const r = operatorRelation(db, opA, opB); return r === 'nap' || r === 'confed' || r === 'same_alliance'; };
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
S, HOUR, operatorOf, peeringLevel, membership, getAlliance, memberCount, leaderOf, allianceBrief, effectiveCap, refreshCap,
|
||||||
|
addMember, removeMember, requireRole, userOfOperator, notifyOperator, notifyAlliance, dissolve,
|
||||||
|
pairOf, getRelation, setRelation, withdrawProposals,
|
||||||
|
relationBetween, operatorRelation, atWar, confederated, pactPartners,
|
||||||
|
};
|
||||||
35
server/commands/allianceCreate.js
Normal file
35
server/commands/allianceCreate.js
Normal 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' };
|
||||||
|
};
|
||||||
9
server/commands/allianceDisband.js
Normal file
9
server/commands/allianceDisband.js
Normal 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 };
|
||||||
|
};
|
||||||
32
server/commands/allianceInvite.js
Normal file
32
server/commands/allianceInvite.js
Normal 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 };
|
||||||
|
};
|
||||||
41
server/commands/allianceInviteAnswer.js
Normal file
41
server/commands/allianceInviteAnswer.js
Normal 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' };
|
||||||
|
};
|
||||||
15
server/commands/allianceInviteCancel.js
Normal file
15
server/commands/allianceInviteCancel.js
Normal 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 };
|
||||||
|
};
|
||||||
19
server/commands/allianceKick.js
Normal file
19
server/commands/allianceKick.js
Normal 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 };
|
||||||
|
};
|
||||||
23
server/commands/allianceLeave.js
Normal file
23
server/commands/allianceLeave.js
Normal 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 };
|
||||||
|
};
|
||||||
41
server/commands/allianceNote.js
Normal file
41
server/commands/allianceNote.js
Normal 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 };
|
||||||
17
server/commands/allianceRole.js
Normal file
17
server/commands/allianceRole.js
Normal 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 };
|
||||||
|
};
|
||||||
18
server/commands/allianceTransfer.js
Normal file
18
server/commands/allianceTransfer.js
Normal 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 };
|
||||||
|
};
|
||||||
35
server/commands/diploAnswer.js
Normal file
35
server/commands/diploAnswer.js
Normal 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 };
|
||||||
|
};
|
||||||
54
server/commands/diploPropose.js
Normal file
54
server/commands/diploPropose.js
Normal 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 };
|
||||||
|
};
|
||||||
22
server/commands/diploRevoke.js
Normal file
22
server/commands/diploRevoke.js
Normal 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 };
|
||||||
|
};
|
||||||
15
server/commands/diploWithdraw.js
Normal file
15
server/commands/diploWithdraw.js
Normal 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 };
|
||||||
|
};
|
||||||
|
|
@ -5,11 +5,41 @@
|
||||||
* scheduler timer because the command may have enqueued events.
|
* scheduler timer because the command may have enqueued events.
|
||||||
*/
|
*/
|
||||||
const handlers = {
|
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'),
|
signup: require('./signup'),
|
||||||
joinWorld: require('./joinWorld'),
|
joinWorld: require('./joinWorld'),
|
||||||
build: require('./build'),
|
build: require('./build'),
|
||||||
cancelBuild: require('./cancelBuild'),
|
cancelBuild: require('./cancelBuild'),
|
||||||
renameTown: require('./renameTown'),
|
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 }) {
|
function createCommands({ db, clock, scheduler }) {
|
||||||
|
|
|
||||||
14
server/commands/markReportRead.js
Normal file
14
server/commands/markReportRead.js
Normal 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 };
|
||||||
|
};
|
||||||
31
server/commands/messageBlock.js
Normal file
31
server/commands/messageBlock.js
Normal 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 };
|
||||||
24
server/commands/messageDelete.js
Normal file
24
server/commands/messageDelete.js
Normal 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 };
|
||||||
|
};
|
||||||
12
server/commands/messageRead.js
Normal file
12
server/commands/messageRead.js
Normal 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) };
|
||||||
|
};
|
||||||
72
server/commands/messageSend.js
Normal file
72
server/commands/messageSend.js
Normal 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 };
|
||||||
|
};
|
||||||
30
server/commands/recallMovement.js
Normal file
30
server/commands/recallMovement.js
Normal 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 };
|
||||||
|
};
|
||||||
26
server/commands/research.js
Normal file
26
server/commands/research.js
Normal 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 };
|
||||||
|
};
|
||||||
120
server/commands/sendMovement.js
Normal file
120
server/commands/sendMovement.js
Normal 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;
|
||||||
52
server/commands/sendTransport.js
Normal file
52
server/commands/sendTransport.js
Normal 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
37
server/commands/train.js
Normal 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;
|
||||||
35
server/commands/withdrawStationed.js
Normal file
35
server/commands/withdrawStationed.js
Normal 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 };
|
||||||
|
};
|
||||||
25
server/diplomacy.js
Normal file
25
server/diplomacy.js
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
'use strict';
|
||||||
|
/* Shared pieces of the diplomacy commands and the delayed `diploChange` event. */
|
||||||
|
const A = require('./alliances');
|
||||||
|
|
||||||
|
const brief = (a) => ({ id: a.id, tag: a.tag, name: a.name });
|
||||||
|
|
||||||
|
// Everybody in both alliances hears about a relation that changed.
|
||||||
|
function announceChange(ctx, x, y, from, to, extra) {
|
||||||
|
for (const [me, other] of [[x, y], [y, x]]) {
|
||||||
|
A.notifyAlliance(ctx, me.id, 'diplomacy_changed', Object.assign({ allianceId: me.id, other: brief(other), from, to }, extra || {}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make `to` the current relation of the pair right now, drop proposals that this overtakes, tell everyone.
|
||||||
|
function applyChange(ctx, x, y, to, extra) {
|
||||||
|
const { db, now } = ctx;
|
||||||
|
const cur = A.getRelation(db, x.id, y.id);
|
||||||
|
const from = cur ? cur.state : 'neutral';
|
||||||
|
A.setRelation(db, x.world_id, x.id, y.id, to, now);
|
||||||
|
A.withdrawProposals(db, x.id, y.id, now);
|
||||||
|
announceChange(ctx, x, y, from, to, extra);
|
||||||
|
return from;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { brief, announceChange, applyChange };
|
||||||
|
|
@ -28,6 +28,34 @@ const CODES = {
|
||||||
already_queued: [409, 'That building is already being built.'],
|
already_queued: [409, 'That building is already being built.'],
|
||||||
queue_full: [409, 'All build slots are busy.'],
|
queue_full: [409, 'All build slots are busy.'],
|
||||||
not_enough_resources: [409, 'Not enough resources.'],
|
not_enough_resources: [409, 'Not enough resources.'],
|
||||||
|
// social: alliances, diplomacy, messages
|
||||||
|
peering_office_required: [409, 'A Peering office (level 1 or higher) is needed to found or join an alliance.'],
|
||||||
|
already_in_alliance: [409, 'That operator is already in an alliance.'],
|
||||||
|
not_in_alliance: [409, 'You are not in that alliance.'],
|
||||||
|
alliance_name_taken: [409, 'That alliance name is taken.'],
|
||||||
|
alliance_tag_taken: [409, 'That alliance tag is taken.'],
|
||||||
|
alliance_full: [409, 'The alliance has no room for more members.'],
|
||||||
|
invite_expired: [409, 'The invite has expired.'],
|
||||||
|
leader_must_transfer: [409, 'The leader must hand over leadership before leaving.'],
|
||||||
|
notes_full: [409, 'The alliance has reached its pinned-note limit.'],
|
||||||
|
diplomacy_invalid: [409, 'That diplomatic move is not allowed from the current state.'],
|
||||||
|
diplomacy_pending: [409, 'A diplomatic change between these alliances is already scheduled.'],
|
||||||
|
proposal_exists: [409, 'The other alliance already proposed this; accept their proposal instead.'],
|
||||||
|
proposal_expired: [409, 'The proposal has expired.'],
|
||||||
|
// military and expansion
|
||||||
|
unknown_unit: [404, 'No such unit type.'],
|
||||||
|
not_researchable: [409, 'That unit stat cannot be researched.'],
|
||||||
|
not_enough_units: [409, 'Not enough units at home.'],
|
||||||
|
units_offline: [409, 'Those units are offline (the battery is empty).'],
|
||||||
|
invalid_target: [409, 'That target is not valid for this kind of movement.'],
|
||||||
|
target_protected: [409, 'The target is under beginner protection.'],
|
||||||
|
protection_active: [409, 'Attacking ends your beginner protection; confirm to go ahead.'],
|
||||||
|
out_of_range: [409, 'The target is too far from your POPs.'],
|
||||||
|
footprint_too_low: [409, 'Your footprint is too low for another POP.'],
|
||||||
|
cannot_takeover: [409, 'That POP cannot be taken over.'],
|
||||||
|
recall_expired: [409, 'The recall window (first 90 seconds) has passed.'],
|
||||||
|
capacity_exceeded: [409, 'More than one transport link can carry.'],
|
||||||
|
no_transport_link: [409, 'All transport links are busy (or there is no Internet exchange).'],
|
||||||
};
|
};
|
||||||
|
|
||||||
class GameError extends Error {
|
class GameError extends Error {
|
||||||
|
|
|
||||||
19
server/events/arrive.js
Normal file
19
server/events/arrive.js
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
'use strict';
|
||||||
|
/* A movement reached its destination. Payload { movementId }. Dispatches by movement type; everything runs at the
|
||||||
|
* event's own due time, inside the scheduler's transaction. Idempotent: only an `out` movement is processed. */
|
||||||
|
const M = require('../military/movements');
|
||||||
|
const A = require('../military/arrivals');
|
||||||
|
const combat = require('../military/combat');
|
||||||
|
|
||||||
|
module.exports = function arrive(ctx, ev) {
|
||||||
|
const mv = M.getMovement(ctx.db, ev.payload.movementId);
|
||||||
|
if (!mv || mv.status !== 'out') return;
|
||||||
|
ctx.db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id);
|
||||||
|
switch (mv.type) {
|
||||||
|
case 'scan': case 'raid': case 'attack': case 'takeover': return combat.arrive(ctx, mv, ev);
|
||||||
|
case 'reinforce': return A.arriveReinforce(ctx, mv, ev);
|
||||||
|
case 'transport': return A.arriveTransport(ctx, mv, ev);
|
||||||
|
case 'settle': return A.arriveSettle(ctx, mv, ev);
|
||||||
|
default: throw new Error('unknown movement type ' + mv.type);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -11,5 +11,6 @@ module.exports = function buildDone(ctx, ev) {
|
||||||
const cur = town.buildings[key];
|
const cur = town.buildings[key];
|
||||||
if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel);
|
if (!cur) db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, toLevel);
|
||||||
else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key);
|
else if (cur.level < toLevel) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', toLevel, town.id, key);
|
||||||
|
require('../military/power').reschedule(ctx, town.id, ev.dueAt); // building draw / battery cap changed: units' power check
|
||||||
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel });
|
if (userId) ctx.notify(userId, ev.worldId, 'build_done', { townId: town.id, key, type, level: toLevel });
|
||||||
};
|
};
|
||||||
|
|
|
||||||
15
server/events/diploChange.js
Normal file
15
server/events/diploChange.js
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
'use strict';
|
||||||
|
/* A unilateral cancel of a pact (or war declared out of a pact) came due. Payload { a, b, to, by }.
|
||||||
|
* Idempotent and safe against cancellation: it only acts when the relation row still points at THIS event. */
|
||||||
|
const A = require('../alliances');
|
||||||
|
const Dip = require('../diplomacy');
|
||||||
|
|
||||||
|
module.exports = function diploChange(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const { a, b, to } = ev.payload;
|
||||||
|
const rel = A.getRelation(db, a, b);
|
||||||
|
if (!rel || rel.pending_event !== ev.id) return; // revoked, replaced, or already applied
|
||||||
|
const x = A.getAlliance(db, a), y = A.getAlliance(db, b);
|
||||||
|
if (!x || !y) return;
|
||||||
|
Dip.applyChange(ctx, x, y, to, { delayed: true, startedBy: ev.payload.by });
|
||||||
|
};
|
||||||
|
|
@ -1,5 +1,13 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
/* Event type -> handler. One file per event type. */
|
/* Event type -> handler. One file per event type. */
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
// stage 3/4: military and expansion
|
||||||
|
trainDone: require('./trainDone'),
|
||||||
|
researchDone: require('./researchDone'),
|
||||||
|
arrive: require('./arrive'),
|
||||||
|
return: require('./return'),
|
||||||
|
powerCheck: require('./powerCheck'),
|
||||||
|
reportCleanup: require('./reportCleanup'),
|
||||||
buildDone: require('./buildDone'),
|
buildDone: require('./buildDone'),
|
||||||
|
diploChange: require('./diploChange'),
|
||||||
};
|
};
|
||||||
|
|
|
||||||
3
server/events/powerCheck.js
Normal file
3
server/events/powerCheck.js
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
'use strict';
|
||||||
|
/* Battery empty / offline for 24 h: see server/military/power.js. Payload { townId }. */
|
||||||
|
module.exports = require('../military/power').powerCheck;
|
||||||
9
server/events/reportCleanup.js
Normal file
9
server/events/reportCleanup.js
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
'use strict';
|
||||||
|
/* Delete expired reports (14 days, real time), then arm the next cleanup for the earliest remaining expiry. createReport
|
||||||
|
* arms it when none is pending, so there is at most one pending cleanup per world and none while no reports exist. */
|
||||||
|
module.exports = function reportCleanup(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
db.run('DELETE FROM reports WHERE world_id = ? AND expires_at <= ?', ev.worldId, ev.dueAt);
|
||||||
|
const left = db.get('SELECT MIN(expires_at) AS e FROM reports WHERE world_id = ?', ev.worldId);
|
||||||
|
if (left && left.e !== null) ctx.enqueue({ worldId: ev.worldId, dueAt: left.e, type: 'reportCleanup', payload: { worldId: ev.worldId } });
|
||||||
|
};
|
||||||
12
server/events/researchDone.js
Normal file
12
server/events/researchDone.js
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
'use strict';
|
||||||
|
/* A research level finished. Payload { unit, stat, toLevel, userId }. Idempotent: a level never goes down. */
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
|
||||||
|
module.exports = function researchDone(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const { unit, stat, toLevel, userId } = ev.payload;
|
||||||
|
if (!db.get('SELECT 1 AS x FROM towns WHERE id = ?', ev.townId)) return;
|
||||||
|
db.run(`INSERT INTO town_research (town_id, unit, stat, level) VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT (town_id, unit, stat) DO UPDATE SET level = MAX(level, excluded.level)`, ev.townId, unit, stat, toLevel);
|
||||||
|
if (userId) ctx.notify(userId, ev.worldId, 'research_done', { townId: ev.townId, unit, stat, level: toLevel, key: R.researchKey(unit, stat) });
|
||||||
|
};
|
||||||
28
server/events/return.js
Normal file
28
server/events/return.js
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* A return leg arrived: units and cargo go back home. If the origin POP changed hands meanwhile they go to the
|
||||||
|
* operator's capital (or oldest POP) instead; with no POP left they are lost. Cargo above the Rack hall cap is lost.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { loadTown, settle } = require('../state');
|
||||||
|
const M = require('../military/movements');
|
||||||
|
const U = require('../military/units');
|
||||||
|
const P = require('../military/power');
|
||||||
|
const { addCargo } = require('../military/arrivals');
|
||||||
|
|
||||||
|
module.exports = function ret(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const mv = M.getMovement(db, ev.payload.movementId);
|
||||||
|
if (!mv || mv.status !== 'out') return;
|
||||||
|
db.run("UPDATE movements SET status = 'done' WHERE id = ?", mv.id);
|
||||||
|
const dest = U.homeTownFor(db, mv.ownerId, mv.toTownId);
|
||||||
|
const uid = U.userOfOperator(db, mv.ownerId);
|
||||||
|
if (!dest) { if (uid) ctx.notify(uid, mv.worldId, 'movement_lost', { movementId: mv.id }); return; }
|
||||||
|
const town = loadTown(db, dest.id);
|
||||||
|
settle(db, town, ev.dueAt);
|
||||||
|
U.addHome(db, town.id, mv.units);
|
||||||
|
const lost = addCargo(db, town, mv.cargo);
|
||||||
|
P.reschedule(ctx, town.id, ev.dueAt);
|
||||||
|
if (uid && !mv.extra.link) ctx.notify(uid, mv.worldId, 'movement_returned', { movementId: mv.id, townId: town.id, units: mv.units, cargo: mv.cargo, cargoLost: lost });
|
||||||
|
};
|
||||||
17
server/events/trainDone.js
Normal file
17
server/events/trainDone.js
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
'use strict';
|
||||||
|
/* A training batch finished. Payload { unit, count, building, userId }. The POP is settled to the due time at the OLD
|
||||||
|
* power draw, then the units appear (and the draw rises). */
|
||||||
|
const { loadTown, settle } = require('../state');
|
||||||
|
const U = require('../military/units');
|
||||||
|
const P = require('../military/power');
|
||||||
|
|
||||||
|
module.exports = function trainDone(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const { unit, count, userId } = ev.payload;
|
||||||
|
const town = loadTown(db, ev.townId);
|
||||||
|
if (!town) return;
|
||||||
|
settle(db, town, ev.dueAt);
|
||||||
|
U.addHome(db, town.id, { [unit]: count });
|
||||||
|
P.reschedule(ctx, town.id, ev.dueAt);
|
||||||
|
if (userId) ctx.notify(userId, ev.worldId, 'train_done', { townId: town.id, unit, count });
|
||||||
|
};
|
||||||
|
|
@ -17,7 +17,7 @@ const { TokenBucket, clientIp } = require('./net');
|
||||||
const { applySecurityHeaders } = require('./static');
|
const { applySecurityHeaders } = require('./static');
|
||||||
|
|
||||||
const MAX_BODY = 32 * 1024;
|
const MAX_BODY = 32 * 1024;
|
||||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId']);
|
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId']);
|
||||||
|
|
||||||
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
|
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
|
||||||
class Limiter {
|
class Limiter {
|
||||||
|
|
|
||||||
102
server/migrations/002_military.sql
Normal file
102
server/migrations/002_military.sql
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
-- Stage 3/4 (military, expansion): units at home, reinforcements, research, movements, reports, battle points.
|
||||||
|
-- Units are { unit id: count } everywhere. Times are integer ms since the epoch (UTC).
|
||||||
|
|
||||||
|
-- Units at home, owned by the town's owner. Always settle() the town before changing these (power draw changes).
|
||||||
|
CREATE TABLE town_units (
|
||||||
|
town_id INTEGER NOT NULL REFERENCES towns(id),
|
||||||
|
unit TEXT NOT NULL,
|
||||||
|
count INTEGER NOT NULL CHECK (count > 0),
|
||||||
|
PRIMARY KEY (town_id, unit)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Reinforcements: units of owner_town_id's operator standing in host_town_id. They defend the host and draw its power.
|
||||||
|
CREATE TABLE stationed (
|
||||||
|
host_town_id INTEGER NOT NULL REFERENCES towns(id),
|
||||||
|
owner_town_id INTEGER NOT NULL REFERENCES towns(id),
|
||||||
|
unit TEXT NOT NULL,
|
||||||
|
count INTEGER NOT NULL CHECK (count > 0),
|
||||||
|
PRIMARY KEY (host_town_id, owner_town_id, unit)
|
||||||
|
);
|
||||||
|
CREATE INDEX stationed_owner ON stationed(owner_town_id);
|
||||||
|
|
||||||
|
-- Research levels per POP (attack or defence of one unit type).
|
||||||
|
CREATE TABLE town_research (
|
||||||
|
town_id INTEGER NOT NULL REFERENCES towns(id),
|
||||||
|
unit TEXT NOT NULL,
|
||||||
|
stat TEXT NOT NULL, -- attack | defence
|
||||||
|
level INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (town_id, unit, stat)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- When the units in a POP went offline (battery empty, net power negative). NULL / no row = online.
|
||||||
|
CREATE TABLE town_power (
|
||||||
|
town_id INTEGER PRIMARY KEY REFERENCES towns(id),
|
||||||
|
offline_since INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Everything that is travelling. type: scan | raid | attack | takeover | reinforce | settle | transport | return.
|
||||||
|
-- status: out (travelling, arrive/return event pending) | done | recalled (turned around, a return movement exists).
|
||||||
|
-- A target is a POP (to_town_id) or just a tile (settle, incumbent sites): to_x/to_y are always set.
|
||||||
|
CREATE TABLE movements (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||||
|
owner_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
from_town_id INTEGER REFERENCES towns(id),
|
||||||
|
to_town_id INTEGER REFERENCES towns(id),
|
||||||
|
from_x INTEGER NOT NULL,
|
||||||
|
from_y INTEGER NOT NULL,
|
||||||
|
to_x INTEGER NOT NULL,
|
||||||
|
to_y INTEGER NOT NULL,
|
||||||
|
units TEXT NOT NULL DEFAULT '{}',
|
||||||
|
cargo TEXT NOT NULL DEFAULT '{}',
|
||||||
|
depart_at INTEGER NOT NULL,
|
||||||
|
arrive_at INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'out',
|
||||||
|
event_id INTEGER,
|
||||||
|
parent_id INTEGER, -- the outbound movement a return belongs to
|
||||||
|
extra TEXT NOT NULL DEFAULT '{}', -- research snapshot, building target, wild slots, trade metadata, ...
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX movements_owner ON movements(owner_id, status);
|
||||||
|
CREATE INDEX movements_to ON movements(to_town_id, status);
|
||||||
|
CREATE INDEX movements_from ON movements(from_town_id, status);
|
||||||
|
|
||||||
|
-- A report is one row, shared by all participants (report_recipients). Kept 14 days (expires_at), cleaned by an event.
|
||||||
|
CREATE TABLE reports (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
summary TEXT NOT NULL DEFAULT '{}',
|
||||||
|
data TEXT NOT NULL DEFAULT '{}'
|
||||||
|
);
|
||||||
|
CREATE INDEX reports_expires ON reports(expires_at);
|
||||||
|
|
||||||
|
CREATE TABLE report_recipients (
|
||||||
|
report_id INTEGER NOT NULL REFERENCES reports(id) ON DELETE CASCADE,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
||||||
|
role TEXT NOT NULL, -- attacker | defender | reinforcer | sender | target
|
||||||
|
read_at INTEGER,
|
||||||
|
PRIMARY KEY (report_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX report_recipients_user ON report_recipients(user_id, report_id);
|
||||||
|
|
||||||
|
-- Battle points per operator, written by combat; rankings (social) read it.
|
||||||
|
CREATE TABLE operator_stats (
|
||||||
|
operator_id INTEGER PRIMARY KEY REFERENCES operators(id),
|
||||||
|
attack_points REAL NOT NULL DEFAULT 0,
|
||||||
|
defense_points REAL NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Incumbent sites an operator has taken (one-time Hardware bonus per site; the count drives the research speed bonus).
|
||||||
|
CREATE TABLE incumbent_takes (
|
||||||
|
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||||
|
x INTEGER NOT NULL,
|
||||||
|
y INTEGER NOT NULL,
|
||||||
|
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
taken_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (world_id, x, y, operator_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX incumbent_takes_operator ON incumbent_takes(operator_id);
|
||||||
113
server/migrations/003_social.sql
Normal file
113
server/migrations/003_social.sql
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
-- Stage 5 (social): alliances, diplomacy between alliances, pinned notes, messages.
|
||||||
|
-- operators.alliance_id (001) stays the quick lookup; alliance_members adds the role and is kept in step with it by
|
||||||
|
-- server/alliances.js (addMember / removeMember are the only writers).
|
||||||
|
|
||||||
|
CREATE TABLE alliances (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||||
|
name TEXT NOT NULL COLLATE NOCASE,
|
||||||
|
tag TEXT NOT NULL COLLATE NOCASE,
|
||||||
|
size_cap INTEGER NOT NULL, -- stored at founding, only ever raised (rules.allianceCap)
|
||||||
|
created_by INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
UNIQUE (world_id, name),
|
||||||
|
UNIQUE (world_id, tag)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE alliance_members (
|
||||||
|
operator_id INTEGER PRIMARY KEY REFERENCES operators(id),
|
||||||
|
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
role TEXT NOT NULL, -- leader | diplomat | officer | member
|
||||||
|
joined_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX alliance_members_alliance ON alliance_members(alliance_id);
|
||||||
|
CREATE UNIQUE INDEX alliance_one_leader ON alliance_members(alliance_id) WHERE role = 'leader';
|
||||||
|
|
||||||
|
CREATE TABLE alliance_invites (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
operator_id INTEGER NOT NULL REFERENCES operators(id), -- the invitee
|
||||||
|
invited_by INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | cancelled | expired
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
answered_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX alliance_invites_pending ON alliance_invites(alliance_id, operator_id) WHERE status = 'pending';
|
||||||
|
CREATE INDEX alliance_invites_operator ON alliance_invites(operator_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE alliance_notes (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
alliance_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
author_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX alliance_notes_alliance ON alliance_notes(alliance_id, id);
|
||||||
|
|
||||||
|
-- One row per alliance pair that is not plainly neutral (a_id < b_id). state = the CURRENT relation. A unilateral cancel
|
||||||
|
-- keeps `state` until the delayed `diploChange` event (pending_event) applies pending_to at pending_at.
|
||||||
|
CREATE TABLE alliance_relations (
|
||||||
|
a_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
b_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
world_id INTEGER NOT NULL,
|
||||||
|
state TEXT NOT NULL, -- war | neutral | nap | confed
|
||||||
|
since INTEGER NOT NULL,
|
||||||
|
pending_to TEXT,
|
||||||
|
pending_at INTEGER,
|
||||||
|
pending_by INTEGER, -- the alliance that started the change
|
||||||
|
pending_event INTEGER, -- events.id
|
||||||
|
PRIMARY KEY (a_id, b_id),
|
||||||
|
CHECK (a_id < b_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX alliance_relations_b ON alliance_relations(b_id);
|
||||||
|
|
||||||
|
CREATE TABLE alliance_proposals (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
world_id INTEGER NOT NULL,
|
||||||
|
from_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
to_id INTEGER NOT NULL REFERENCES alliances(id),
|
||||||
|
state TEXT NOT NULL, -- the proposed relation
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | withdrawn | expired
|
||||||
|
proposed_by INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
answered_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX alliance_proposals_pending ON alliance_proposals(from_id, to_id) WHERE status = 'pending';
|
||||||
|
CREATE INDEX alliance_proposals_to ON alliance_proposals(to_id, status);
|
||||||
|
|
||||||
|
-- Messages. No foreign key on alliance_id: broadcasts outlive a disbanded alliance (alliance_tag is a snapshot).
|
||||||
|
-- Each recipient has their own row (read / deleted); the sender's copy is hidden with sender_deleted_at.
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
world_id INTEGER NOT NULL,
|
||||||
|
sender_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
kind TEXT NOT NULL, -- dm | alliance
|
||||||
|
to_id INTEGER REFERENCES operators(id), -- dm only
|
||||||
|
alliance_id INTEGER, -- alliance broadcast only
|
||||||
|
alliance_tag TEXT,
|
||||||
|
thread TEXT NOT NULL, -- 'dm:<lowId>:<highId>' | 'alliance:<id>'
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
sender_deleted_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX messages_sender ON messages(sender_id, id);
|
||||||
|
CREATE INDEX messages_thread ON messages(thread, id);
|
||||||
|
|
||||||
|
CREATE TABLE message_recipients (
|
||||||
|
message_id INTEGER NOT NULL REFERENCES messages(id),
|
||||||
|
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
read_at INTEGER,
|
||||||
|
deleted_at INTEGER,
|
||||||
|
PRIMARY KEY (message_id, operator_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX message_recipients_operator ON message_recipients(operator_id, message_id);
|
||||||
|
|
||||||
|
CREATE TABLE message_blocks (
|
||||||
|
operator_id INTEGER NOT NULL REFERENCES operators(id), -- who blocks
|
||||||
|
blocked_id INTEGER NOT NULL REFERENCES operators(id),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (operator_id, blocked_id)
|
||||||
|
);
|
||||||
122
server/military/arrivals.js
Normal file
122
server/military/arrivals.js
Normal file
|
|
@ -0,0 +1,122 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Arrival handlers for the movements that are not fights: reinforce, transport, settle. Plus the shared pieces every
|
||||||
|
* arrival uses (cargo delivery, bouncing a movement back, brief descriptions for reports). Each handler runs inside the
|
||||||
|
* `arrive` event's transaction at the event's own due time.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { loadTown, settle, loadWorld } = require('../state');
|
||||||
|
const { createTown } = require('../commands/joinWorld');
|
||||||
|
const U = require('./units');
|
||||||
|
const M = require('./movements');
|
||||||
|
const P = require('./power');
|
||||||
|
const { createReport } = require('./reports');
|
||||||
|
|
||||||
|
const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null;
|
||||||
|
const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null;
|
||||||
|
|
||||||
|
// Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost
|
||||||
|
function addCargo(db, town, cargo) {
|
||||||
|
const cap = R.storageCap(town);
|
||||||
|
const lost = {};
|
||||||
|
for (const r of D.RESOURCES) {
|
||||||
|
const add = (cargo && cargo[r]) || 0;
|
||||||
|
if (!add) continue;
|
||||||
|
const cur = town.res[r];
|
||||||
|
const next = Math.min(Math.max(cap, cur), cur + add);
|
||||||
|
lost[r] = Math.max(0, Math.round(cur + add - next));
|
||||||
|
town.res[r] = next;
|
||||||
|
}
|
||||||
|
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
|
||||||
|
return lost;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The movement cannot do what it came for: its units (and cargo) turn around and a report tells the sender why.
|
||||||
|
function bounce(ctx, mv, now, reason, details) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||||
|
if (dest && !U.isEmpty(mv.units)) {
|
||||||
|
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: mv.units, cargo: mv.cargo, parentId: mv.id, extra: { bounced: reason } });
|
||||||
|
}
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'movement_failed', now,
|
||||||
|
summary: { movementType: mv.type, reason, to: mv.to },
|
||||||
|
data: { movementType: mv.type, reason, details: details || {}, to: mv.to, units: mv.units },
|
||||||
|
recipients: [{ userId: U.userOfOperator(db, mv.ownerId), role: 'sender' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function arriveReinforce(ctx, mv, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const now = ev.dueAt;
|
||||||
|
const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null;
|
||||||
|
if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied');
|
||||||
|
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||||
|
if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to
|
||||||
|
const host = loadTown(db, target.id);
|
||||||
|
settle(db, host, now); // the host's draw rises at this moment
|
||||||
|
// Moving units between your own POPs: they simply live in the new POP now. Only other operators' units are "stationed".
|
||||||
|
if (ownerTown.id === host.id || target.owner_id === mv.ownerId) U.addHome(db, host.id, mv.units);
|
||||||
|
else U.addStationed(db, host.id, ownerTown.id, mv.units);
|
||||||
|
P.reschedule(ctx, host.id, now);
|
||||||
|
const sender = U.getOperator(db, mv.ownerId), hostOp = U.getOperator(db, target.owner_id);
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'reinforce', now,
|
||||||
|
summary: { host: townBrief(target), from: townBrief(ownerTown), units: mv.units },
|
||||||
|
data: { host: townBrief(target), hostOperator: opBrief(hostOp), from: townBrief(ownerTown), operator: opBrief(sender), units: mv.units },
|
||||||
|
recipients: [{ userId: U.userOfOperator(db, sender.id), role: 'sender' }, { userId: U.userOfOperator(db, hostOp.id), role: 'target' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function arriveTransport(ctx, mv, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const now = ev.dueAt;
|
||||||
|
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
|
||||||
|
let lost = {};
|
||||||
|
if (target) {
|
||||||
|
settle(db, target, now);
|
||||||
|
lost = addCargo(db, target, mv.cargo);
|
||||||
|
const sender = U.userOfOperator(db, mv.ownerId), receiver = U.userOfOperator(db, target.ownerId);
|
||||||
|
if (receiver) ctx.notify(receiver, mv.worldId, 'transport_arrived', { movementId: mv.id, townId: target.id, fromTownId: mv.fromTownId, cargo: mv.cargo, cargoLost: lost, own: receiver === sender });
|
||||||
|
if (sender && sender !== receiver) ctx.notify(sender, mv.worldId, 'transport_delivered', { movementId: mv.id, toTownId: target.id, cargo: mv.cargo, cargoLost: lost });
|
||||||
|
for (const fn of M.hooks.transportArrived) fn(ctx, mv, { added: mv.cargo, lost });
|
||||||
|
}
|
||||||
|
const cargoBack = target ? {} : mv.cargo; // no such POP any more: the cargo rides home with the carriers
|
||||||
|
// The empty carriers drive back; the link is busy until they are home.
|
||||||
|
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||||
|
if (dest) {
|
||||||
|
const world = loadWorld(db, mv.worldId);
|
||||||
|
const dist = R.distance(mv.to.x, mv.to.y, dest.x, dest.y);
|
||||||
|
M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: {}, cargo: cargoBack, arriveAt: now + R.transportMs(dist, world.speed), parentId: mv.id, extra: Object.assign({}, mv.extra, { link: 1 }) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Three Rollout crews found a new POP on the empty tile, if it is still empty land, still in range, footprint still enough.
|
||||||
|
function arriveSettle(ctx, mv, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const now = ev.dueAt;
|
||||||
|
const world = loadWorld(db, mv.worldId);
|
||||||
|
const op = U.getOperator(db, mv.ownerId);
|
||||||
|
const { x, y } = mv.to;
|
||||||
|
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||||
|
const occupied = !!db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||||
|
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, x, y));
|
||||||
|
const chk = R.settleCheck({ tileType: tile.type, occupied, nearestOwnDist: nearest, ownedCount: own.length, footprint: U.operatorFootprint(db, op.id, now) });
|
||||||
|
if (!chk.ok) return bounce(ctx, mv, now, chk.code, chk);
|
||||||
|
const wild = R.cleanWild(mv.extra.wild);
|
||||||
|
const name = op.name + ' POP ' + (own.length + 1);
|
||||||
|
const id = createTown(db, { worldId: world.id, ownerId: op.id, name, x, y, isCapital: false, now, buildings: R.newTownBuildings(wild), res: D.EXPANSION.startResources });
|
||||||
|
db.run('UPDATE towns SET battery = 0, loyalty = ? WHERE id = ?', D.EXPANSION.foundedLoyalty, id);
|
||||||
|
const founded = { id, name, x, y };
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: world.id, type: 'settle', now,
|
||||||
|
summary: { success: true, town: founded },
|
||||||
|
data: { success: true, town: founded, wild, crews: mv.units, from: mv.fromTownId },
|
||||||
|
recipients: [{ userId: U.userOfOperator(db, op.id), role: 'sender' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { addCargo, bounce, arriveReinforce, arriveTransport, arriveSettle, townBrief, opBrief };
|
||||||
282
server/military/combat.js
Normal file
282
server/military/combat.js
Normal file
|
|
@ -0,0 +1,282 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Arrival of scan / raid / attack / takeover. Everything here runs inside the `arrive` event's transaction at the
|
||||||
|
* event's own due time, after every earlier event, so combat order is exactly event order. Deterministic: the only
|
||||||
|
* dice (the loyalty roll) are seeded from (world seed, movement id).
|
||||||
|
*
|
||||||
|
* Steps: re-check the target (it may have changed since departure) -> settle the target to the due time -> gather
|
||||||
|
* defenders (home crews + reinforcements, only while online) -> rules.resolveBattle -> apply losses, loot, siege,
|
||||||
|
* takeover -> survivors drive home with the loot -> reports + battle points.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { loadTown, settle, loadWorld } = require('../state');
|
||||||
|
const U = require('./units');
|
||||||
|
const M = require('./movements');
|
||||||
|
const P = require('./power');
|
||||||
|
const { createReport } = require('./reports');
|
||||||
|
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||||
|
|
||||||
|
const DAY = 24 * D.HOUR_MS;
|
||||||
|
|
||||||
|
// All groups standing in the target: home crews then each reinforcing POP's units, with the research that applies.
|
||||||
|
function defenderGroups(db, target) {
|
||||||
|
const groups = [];
|
||||||
|
const home = U.homeUnits(db, target.id);
|
||||||
|
if (!U.isEmpty(home)) groups.push({ id: 'home', ownerTownId: target.id, ownerOpId: target.ownerId, units: home, research: U.researchLevels(db, target.id) });
|
||||||
|
for (const g of U.hostedGroups(db, target.id)) {
|
||||||
|
const ot = db.get('SELECT owner_id FROM towns WHERE id = ?', g.ownerTownId);
|
||||||
|
groups.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: ot ? ot.owner_id : null, units: g.units, research: U.researchLevels(db, g.ownerTownId) });
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write a defending group's units back after the battle.
|
||||||
|
function writeGroup(db, hostTownId, group, units) {
|
||||||
|
const keys = new Set(Object.keys(group.units).concat(Object.keys(units)));
|
||||||
|
for (const k of keys) {
|
||||||
|
if (group.id === 'home') U.setHomeUnit(db, hostTownId, k, units[k] || 0);
|
||||||
|
else U.setStationed(db, hostTownId, group.ownerTownId, k, units[k] || 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addPoints(db, operatorId, column, v) {
|
||||||
|
if (!operatorId || !(v > 0)) return;
|
||||||
|
db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId);
|
||||||
|
db.run('UPDATE operator_stats SET ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' = ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' + ? WHERE operator_id = ?', v, operatorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {});
|
||||||
|
|
||||||
|
// Survivors drive home (with loot). No survivors, no movement.
|
||||||
|
function sendHome(ctx, mv, survivors, cargo) {
|
||||||
|
const { db } = ctx;
|
||||||
|
if (U.isEmpty(survivors)) return null;
|
||||||
|
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
|
||||||
|
if (!dest) return null;
|
||||||
|
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: {} });
|
||||||
|
}
|
||||||
|
|
||||||
|
function arrive(ctx, mv, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const now = ev.dueAt;
|
||||||
|
const world = loadWorld(db, mv.worldId);
|
||||||
|
if (!mv.toTownId) return arriveSite(ctx, mv, now, world);
|
||||||
|
const targetRow = db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId);
|
||||||
|
if (!targetRow) return bounce(ctx, mv, now, 'target_gone');
|
||||||
|
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||||
|
const defOp = U.getOperator(db, targetRow.owner_id);
|
||||||
|
if (defOp.id === attackerOp.id) return bounce(ctx, mv, now, 'own_town');
|
||||||
|
if (mv.type !== 'scan') {
|
||||||
|
if (R.isProtected(defOp.protection_until, now)) return bounce(ctx, mv, now, 'protected', { until: defOp.protection_until });
|
||||||
|
if (U.pactBlocks(db, attackerOp.id, defOp.id)) return bounce(ctx, mv, now, 'pact');
|
||||||
|
}
|
||||||
|
const target = loadTown(db, targetRow.id);
|
||||||
|
settle(db, target, now);
|
||||||
|
const online = P.online(target, now);
|
||||||
|
const groups = defenderGroups(db, target);
|
||||||
|
const active = online ? groups : [];
|
||||||
|
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||||
|
|
||||||
|
if (mv.type === 'scan') return resolveScanOnTown(ctx, mv, now, { target, targetRow, defOp, attackerOp, origin, groups, active, online });
|
||||||
|
|
||||||
|
const kind = mv.type === 'raid' ? 'raid' : 'attack';
|
||||||
|
const fwLevel = target.buildings.firewall ? target.buildings.firewall.level : 0;
|
||||||
|
const b = R.resolveBattle({
|
||||||
|
kind, attackers: { units: mv.units, research: mv.extra.research || {} },
|
||||||
|
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: fwLevel,
|
||||||
|
});
|
||||||
|
const win = b.attackerWins;
|
||||||
|
|
||||||
|
// ---- defenders: losses (a full attack lost by the defender wipes everything in the POP, offline units included)
|
||||||
|
const wipe = b.defenderLossFraction >= 1;
|
||||||
|
const groupReports = [];
|
||||||
|
let defenderLost = {};
|
||||||
|
for (const g of groups) {
|
||||||
|
const res = b.defenders.find((d) => d.id === g.id);
|
||||||
|
let survivors, lost;
|
||||||
|
if (wipe) { survivors = {}; lost = g.units; }
|
||||||
|
else if (res) { survivors = res.survivors; lost = res.lost; }
|
||||||
|
else { survivors = g.units; lost = {}; } // offline and not wiped: untouched
|
||||||
|
writeGroup(db, target.id, g, survivors);
|
||||||
|
U.sumInto(defenderLost, lost);
|
||||||
|
groupReports.push({ id: g.id, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors, share: res ? res.share : 0, offline: !res });
|
||||||
|
}
|
||||||
|
const survivorsAtt = Object.assign({}, b.attacker.survivors);
|
||||||
|
|
||||||
|
// ---- loot
|
||||||
|
let loot = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
let hidden = 0;
|
||||||
|
if (win) {
|
||||||
|
hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0;
|
||||||
|
const avail = {};
|
||||||
|
for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden);
|
||||||
|
loot = R.lootSplit(R.carryOf(survivorsAtt), avail);
|
||||||
|
for (const r of D.RESOURCES) target.res[r] -= loot[r];
|
||||||
|
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- siege: exploit kits tear levels off the chosen building
|
||||||
|
let siege = null;
|
||||||
|
if (win && mv.type !== 'raid' && mv.extra.target) {
|
||||||
|
const levels = R.siegeLevels(survivorsAtt.exploit_kit || 0);
|
||||||
|
const cur = levels > 0 ? target.buildings[mv.extra.target] : null;
|
||||||
|
if (cur && cur.level > 0) {
|
||||||
|
const to = Math.max(0, cur.level - levels);
|
||||||
|
db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', to, target.id, mv.extra.target);
|
||||||
|
siege = { key: mv.extra.target, type: cur.type, from: cur.level, to };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- takeover
|
||||||
|
let takeover = null;
|
||||||
|
let captured = false;
|
||||||
|
if (mv.type === 'takeover' && win && (survivorsAtt[D.EXPANSION.conquestUnit] || 0) > 0) {
|
||||||
|
const defTowns = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
|
||||||
|
const block = R.takeoverBlock(!!targetRow.is_capital, defTowns);
|
||||||
|
const gate = R.footprintGate(U.operatorTowns(db, attackerOp.id).length, U.operatorFootprint(db, attackerOp.id, now));
|
||||||
|
takeover = { attempted: true, blocked: block === 'last_pop' ? 'last_pop' : (gate.ok ? null : 'footprint'), capital: block === 'capital', loyaltyBefore: target.loyalty, loyaltyAfter: target.loyalty, drop: 0, captured: false };
|
||||||
|
if (takeover.blocked === null) {
|
||||||
|
const rand = R.rng(R.hash(world.seed, mv.id, 0x7a11))();
|
||||||
|
const drop = R.loyaltyDrop(rand);
|
||||||
|
const after = Math.max(0, target.loyalty - drop);
|
||||||
|
const left = survivorsAtt[D.EXPANSION.conquestUnit] - 1; // the M&A team that did the talking is used up
|
||||||
|
if (left > 0) survivorsAtt[D.EXPANSION.conquestUnit] = left; else delete survivorsAtt[D.EXPANSION.conquestUnit];
|
||||||
|
db.run('UPDATE towns SET loyalty = ?, loyalty_at = ? WHERE id = ?', after, now, target.id);
|
||||||
|
Object.assign(takeover, { drop, loyaltyAfter: after });
|
||||||
|
if (after <= 0 && block === null) { transferTown(ctx, target, attackerOp, defOp, now); captured = true; takeover.captured = true; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- battle points
|
||||||
|
const attLost = b.attacker.lost;
|
||||||
|
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
|
||||||
|
const defPts = R.battlePoints(attLost);
|
||||||
|
for (const g of groupReports) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
|
||||||
|
|
||||||
|
P.reschedule(ctx, target.id, now);
|
||||||
|
const ret = sendHome(ctx, mv, survivorsAtt, loot);
|
||||||
|
|
||||||
|
// ---- reports
|
||||||
|
const data = {
|
||||||
|
type: mv.type, outcome: win ? 'attacker_won' : 'defender_won', arrivedAt: now,
|
||||||
|
attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } },
|
||||||
|
defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
|
||||||
|
power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall },
|
||||||
|
loot, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null,
|
||||||
|
};
|
||||||
|
const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured };
|
||||||
|
const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }];
|
||||||
|
for (const g of groupReports) if (g.id !== 'home' && g.ownerOpId) recipients.push({ userId: U.userOfOperator(db, g.ownerOpId), role: 'reinforcer' });
|
||||||
|
createReport(ctx, { worldId: mv.worldId, type: mv.type, now, summary, data, recipients });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- scans
|
||||||
|
function resolveScanOnTown(ctx, mv, now, s) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const { target, defOp, attackerOp, origin, groups, active, online } = s;
|
||||||
|
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||||
|
let sd = 0;
|
||||||
|
for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research);
|
||||||
|
const res = R.resolveScan(sa, sd);
|
||||||
|
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||||
|
let intel = null;
|
||||||
|
if (res.success) {
|
||||||
|
intel = {
|
||||||
|
detail: res.detail, online,
|
||||||
|
units: { home: U.homeUnits(db, target.id), stationed: groups.filter((g) => g.id !== 'home').map((g) => ({ ownerTownId: g.ownerTownId, units: g.units })) },
|
||||||
|
resources: { fiber: target.res.fiber, hardware: target.res.hardware, capital: target.res.capital },
|
||||||
|
};
|
||||||
|
if (res.detail === 'full') {
|
||||||
|
intel.buildings = Object.keys(target.buildings).map((k) => ({ key: k, type: target.buildings[k].type, level: target.buildings[k].level }));
|
||||||
|
intel.loyalty = target.loyalty;
|
||||||
|
intel.outgoing = db.all("SELECT id, type, to_x, to_y, arrive_at FROM movements WHERE from_town_id = ? AND status = 'out' AND type != 'return' ORDER BY arrive_at, id", target.id)
|
||||||
|
.map((m) => ({ type: m.type, to: { x: m.to_x, y: m.to_y }, arriveAt: m.arrive_at }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const aData = { success: res.success, detail: res.detail, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, strength: { attacker: sa, defender: sd }, target: townBrief(target), operator: opBrief(defOp), intel };
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, target: townBrief(target), operator: opBrief(defOp) },
|
||||||
|
data: aData, recipients: [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }],
|
||||||
|
});
|
||||||
|
const dData = { identityRevealed: res.identityRevealed, target: townBrief(target), by: res.identityRevealed ? { operator: opBrief(attackerOp), town: townBrief(origin) } : null };
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'scan_detected', now, summary: { identityRevealed: res.identityRevealed, target: townBrief(target), by: dData.by && dData.by.operator },
|
||||||
|
data: dData, recipients: [{ userId: U.userOfOperator(db, defOp.id), role: 'defender' }],
|
||||||
|
});
|
||||||
|
sendHome(ctx, mv, loss.survivors, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- incumbent sites (NPC): static defence, no losses for the site, never attack
|
||||||
|
function arriveSite(ctx, mv, now, world) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const { x, y } = mv.to;
|
||||||
|
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||||
|
if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target');
|
||||||
|
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||||
|
const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed);
|
||||||
|
const staticDef = R.incumbentDefence(world.seed, x, y, ageDays);
|
||||||
|
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||||
|
const site = { x, y, type: 'incumbent' };
|
||||||
|
const uid = U.userOfOperator(db, attackerOp.id);
|
||||||
|
|
||||||
|
if (mv.type === 'scan') {
|
||||||
|
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||||
|
const res = R.resolveScan(sa, D.INCUMBENT.scanStrength);
|
||||||
|
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||||
|
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, attackerOp.id);
|
||||||
|
const intel = res.success ? { defence: staticDef, bonusAvailable: !taken, hardwareBonus: D.INCUMBENT.hardwareBonus } : null;
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site },
|
||||||
|
data: { success: res.success, detail: res.detail, site, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
|
||||||
|
recipients: [{ userId: uid, role: 'attacker' }],
|
||||||
|
});
|
||||||
|
sendHome(ctx, mv, loss.survivors, {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
|
||||||
|
const survivors = Object.assign({}, b.attacker.survivors);
|
||||||
|
let bonus = null;
|
||||||
|
const cargo = {};
|
||||||
|
if (b.attackerWins) {
|
||||||
|
const first = db.run('INSERT OR IGNORE INTO incumbent_takes (world_id, x, y, operator_id, taken_at) VALUES (?, ?, ?, ?, ?)', world.id, x, y, attackerOp.id, now);
|
||||||
|
if (first.changes) {
|
||||||
|
cargo.hardware = D.INCUMBENT.hardwareBonus;
|
||||||
|
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ret = sendHome(ctx, mv, survivors, cargo);
|
||||||
|
createReport(ctx, {
|
||||||
|
worldId: mv.worldId, type: 'incumbent', now,
|
||||||
|
summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus },
|
||||||
|
data: {
|
||||||
|
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site, origin: townBrief(origin),
|
||||||
|
attacker: { operator: opBrief(attackerOp), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
|
||||||
|
power: { attack: b.A, defence: b.D }, bonus, returnMovementId: ret ? ret.id : null,
|
||||||
|
},
|
||||||
|
recipients: [{ userId: uid, role: 'attacker' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// A takeover completed: the POP changes owner. Pending work of the old owner stops, reinforcements of the old owner
|
||||||
|
// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty.
|
||||||
|
function transferTown(ctx, town, newOp, oldOp, now) {
|
||||||
|
const { db } = ctx;
|
||||||
|
db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id);
|
||||||
|
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id);
|
||||||
|
db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id);
|
||||||
|
// units of the old owner that were hosted here (should be dead already) or that belonged to this POP and stand elsewhere
|
||||||
|
const home = U.homeTownFor(db, oldOp.id);
|
||||||
|
for (const g of U.awayGroups(db, town.id)) {
|
||||||
|
db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', g.hostTownId, town.id);
|
||||||
|
if (!home) continue;
|
||||||
|
if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units);
|
||||||
|
}
|
||||||
|
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
||||||
|
const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id);
|
||||||
|
if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) });
|
||||||
|
if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { arrive, defenderGroups, transferTown };
|
||||||
8
server/military/ctx.js
Normal file
8
server/military/ctx.js
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
'use strict';
|
||||||
|
/* Commands get { db, clock, now, scheduler }, events additionally { enqueue, notify }. Military code uses the event shape
|
||||||
|
* everywhere, so command entry points call `ctxOf(ctx)` first (idempotent). */
|
||||||
|
module.exports = function ctxOf(ctx) {
|
||||||
|
if (ctx.enqueue && ctx.notify) return ctx;
|
||||||
|
const s = ctx.scheduler;
|
||||||
|
return Object.assign({}, ctx, { enqueue: (e) => s.enqueue(e), notify: (u, w, t, p) => s.notify(u, w, t, p) });
|
||||||
|
};
|
||||||
58
server/military/movements.js
Normal file
58
server/military/movements.js
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Movement rows: creating them (together with their arrive/return event), reading them, return legs.
|
||||||
|
* A movement is `out` until its event runs; a recall turns it into `recalled` and creates a return movement.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
const j = (s) => JSON.parse(s || '{}');
|
||||||
|
|
||||||
|
function fromRow(r) {
|
||||||
|
if (!r) return null;
|
||||||
|
return {
|
||||||
|
id: r.id, worldId: r.world_id, ownerId: r.owner_id, type: r.type, fromTownId: r.from_town_id, toTownId: r.to_town_id,
|
||||||
|
from: { x: r.from_x, y: r.from_y }, to: { x: r.to_x, y: r.to_y }, units: j(r.units), cargo: j(r.cargo),
|
||||||
|
departAt: r.depart_at, arriveAt: r.arrive_at, status: r.status, eventId: r.event_id, parentId: r.parent_id, extra: j(r.extra),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function getMovement(db, id) { return fromRow(db.get('SELECT * FROM movements WHERE id = ?', id)); }
|
||||||
|
|
||||||
|
// Insert a movement and the event that will resolve it ('arrive' for everything but returns, 'return' for returns).
|
||||||
|
// o: { worldId, ownerId, type, fromTownId, toTownId, from:{x,y}, to:{x,y}, units, cargo, departAt, arriveAt, parentId, extra }
|
||||||
|
function insertMovement(ctx, o) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const r = db.run(`INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo,
|
||||||
|
depart_at, arrive_at, status, parent_id, extra, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'out', ?, ?, ?)`,
|
||||||
|
o.worldId, o.ownerId, o.type, o.fromTownId || null, o.toTownId || null, o.from.x, o.from.y, o.to.x, o.to.y,
|
||||||
|
JSON.stringify(o.units || {}), JSON.stringify(o.cargo || {}), o.departAt, Math.round(o.arriveAt), o.parentId || null, JSON.stringify(o.extra || {}), ctx.now);
|
||||||
|
const id = Number(r.lastInsertRowid);
|
||||||
|
const eventId = ctx.enqueue({ worldId: o.worldId, dueAt: o.arriveAt, type: o.type === 'return' ? 'return' : 'arrive', townId: o.toTownId || null, payload: { movementId: id } });
|
||||||
|
db.run('UPDATE movements SET event_id = ? WHERE id = ?', eventId, id);
|
||||||
|
return getMovement(db, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Units (and cargo) heading home from where they are. `fromTown` may be null (an incumbent site or an empty tile);
|
||||||
|
// `at` = where they are ({x,y}); `to` = the destination POP row. arriveAt defaults to now + travel time.
|
||||||
|
function launchReturn(ctx, o) {
|
||||||
|
const to = o.to;
|
||||||
|
const dist = R.distance(o.at.x, o.at.y, to.x, to.y);
|
||||||
|
const world = ctx.db.get('SELECT speed FROM worlds WHERE id = ?', o.worldId);
|
||||||
|
const arriveAt = o.arriveAt !== undefined ? o.arriveAt : ctx.now + R.movementMs(dist, o.units, world.speed);
|
||||||
|
return insertMovement(ctx, {
|
||||||
|
worldId: o.worldId, ownerId: o.ownerId, type: 'return', fromTownId: o.fromTownId || null, toTownId: to.id,
|
||||||
|
from: o.at, to: { x: to.x, y: to.y }, units: o.units, cargo: o.cargo, departAt: ctx.now, arriveAt, parentId: o.parentId, extra: o.extra,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
|
||||||
|
function activeLinks(db, townId) {
|
||||||
|
return db.get(`SELECT COUNT(*) AS n FROM movements WHERE status = 'out' AND
|
||||||
|
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
|
||||||
|
const hooks = { transportArrived: [] };
|
||||||
|
|
||||||
|
module.exports = { fromRow, getMovement, insertMovement, launchReturn, activeLinks, hooks };
|
||||||
109
server/military/power.js
Normal file
109
server/military/power.js
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or
|
||||||
|
* defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive
|
||||||
|
* units are decommissioned until the draw fits the output again.
|
||||||
|
*
|
||||||
|
* Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat
|
||||||
|
* never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline"
|
||||||
|
* notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues
|
||||||
|
* the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a
|
||||||
|
* POP (units arriving or leaving, losses, buildings finishing or being damaged).
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { loadTown, settle } = require('../state');
|
||||||
|
const U = require('./units');
|
||||||
|
|
||||||
|
const EPS = D.MILITARY.batteryEpsilon;
|
||||||
|
|
||||||
|
// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it)
|
||||||
|
function online(town, now) {
|
||||||
|
const c = R.resourcesAt(town, now);
|
||||||
|
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }.
|
||||||
|
function drawingUnits(db, townId) {
|
||||||
|
const out = U.homeUnits(db, townId);
|
||||||
|
for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reschedule(ctx, townId, now) {
|
||||||
|
const { db } = ctx;
|
||||||
|
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId);
|
||||||
|
const town = loadTown(db, townId);
|
||||||
|
if (!town) return;
|
||||||
|
if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; }
|
||||||
|
if (online(town, now)) {
|
||||||
|
db.run('DELETE FROM town_power WHERE town_id = ?', townId);
|
||||||
|
const at = R.batteryEmptyAt(town, now);
|
||||||
|
if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId);
|
||||||
|
if (!row || row.offline_since === null) {
|
||||||
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now);
|
||||||
|
row = { offline_since: now };
|
||||||
|
}
|
||||||
|
ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled.
|
||||||
|
function decommission(ctx, town, now) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const units = drawingUnits(db, town.id);
|
||||||
|
const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 }));
|
||||||
|
const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw);
|
||||||
|
const removed = {};
|
||||||
|
const byOwner = new Map(); // userId -> { unit: n }, who lost units
|
||||||
|
const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; };
|
||||||
|
const ownerUser = U.userOfOperator(db, town.ownerId);
|
||||||
|
for (const unit of Object.keys(plan)) {
|
||||||
|
let left = plan[unit];
|
||||||
|
const home = U.homeUnits(db, town.id)[unit] || 0;
|
||||||
|
const fromHome = Math.min(home, left);
|
||||||
|
if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); }
|
||||||
|
for (const g of U.hostedGroups(db, town.id)) {
|
||||||
|
if (left <= 0) break;
|
||||||
|
const have = g.units[unit] || 0;
|
||||||
|
const n = Math.min(have, left);
|
||||||
|
if (n > 0) {
|
||||||
|
U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n;
|
||||||
|
const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId);
|
||||||
|
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
removed[unit] = plan[unit] - left;
|
||||||
|
}
|
||||||
|
for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost });
|
||||||
|
return removed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds.
|
||||||
|
function powerCheck(ctx, ev) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const town = loadTown(db, ev.townId);
|
||||||
|
if (!town) return;
|
||||||
|
settle(db, town, ev.dueAt);
|
||||||
|
if (town.unitDraw > 0 && !online(town, ev.dueAt)) {
|
||||||
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id);
|
||||||
|
if (!row || row.offline_since === null) {
|
||||||
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt);
|
||||||
|
row = { offline_since: ev.dueAt };
|
||||||
|
const uid = U.userOfOperator(db, town.ownerId);
|
||||||
|
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt });
|
||||||
|
}
|
||||||
|
if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) {
|
||||||
|
const removed = decommission(ctx, town, ev.dueAt);
|
||||||
|
if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop
|
||||||
|
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reschedule(ctx, town.id, ev.dueAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { online, drawingUnits, reschedule, decommission, powerCheck };
|
||||||
32
server/military/reports.js
Normal file
32
server/military/reports.js
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Reports: one `reports` row shared by every participant (`report_recipients`, with a per-user read flag). Kept
|
||||||
|
* MILITARY.reportRetentionMs (real time); the `reportCleanup` event deletes expired ones and re-arms itself only while
|
||||||
|
* reports remain.
|
||||||
|
*/
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
// o: { worldId, type, now, summary, data, recipients: [{ userId, role }] } -> report id
|
||||||
|
function createReport(ctx, o) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const r = db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)',
|
||||||
|
o.worldId, o.type, o.now, o.now + D.MILITARY.reportRetentionMs, JSON.stringify(o.summary || {}), JSON.stringify(o.data || {}));
|
||||||
|
const id = Number(r.lastInsertRowid);
|
||||||
|
const seen = new Set();
|
||||||
|
for (const rc of o.recipients) {
|
||||||
|
if (!rc.userId || seen.has(rc.userId)) continue;
|
||||||
|
seen.add(rc.userId);
|
||||||
|
db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', id, rc.userId, rc.role);
|
||||||
|
ctx.notify(rc.userId, o.worldId, 'report', { reportId: id, type: o.type, role: rc.role });
|
||||||
|
}
|
||||||
|
ensureCleanup(ctx, o.worldId, o.now);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureCleanup(ctx, worldId, now) {
|
||||||
|
const { db } = ctx;
|
||||||
|
const pending = db.get("SELECT 1 AS x FROM events WHERE type = 'reportCleanup' AND world_id = ? AND status = 'pending' LIMIT 1", worldId);
|
||||||
|
if (!pending) ctx.enqueue({ worldId, dueAt: now + D.MILITARY.reportRetentionMs, type: 'reportCleanup', payload: { worldId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createReport, ensureCleanup };
|
||||||
153
server/military/units.js
Normal file
153
server/military/units.js
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Data helpers for units, reinforcements, research and operators, shared by the military commands, events and views.
|
||||||
|
* Units are always { unitId: count }. Always settle() a town before changing its units: unit power draw is part of its
|
||||||
|
* rates (state.unitDraw reads town_units and stationed).
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { GameError } = require('../errors');
|
||||||
|
const { loadTown } = require('../state');
|
||||||
|
|
||||||
|
function homeUnits(db, townId) {
|
||||||
|
const out = {};
|
||||||
|
for (const r of db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId)) out[r.unit] = r.count;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setHomeUnit(db, townId, unit, count) {
|
||||||
|
if (count > 0) db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, ?) ON CONFLICT (town_id, unit) DO UPDATE SET count = excluded.count', townId, unit, count);
|
||||||
|
else db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', townId, unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addHome(db, townId, units) {
|
||||||
|
const cur = homeUnits(db, townId);
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, (cur[k] || 0) + units[k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes `units` from home; throws not_enough_units when the town does not have them (callers check first).
|
||||||
|
function removeHome(db, townId, units) {
|
||||||
|
const cur = homeUnits(db, townId);
|
||||||
|
for (const k of Object.keys(units || {})) {
|
||||||
|
if (!(units[k] > 0)) continue;
|
||||||
|
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
|
||||||
|
}
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0) setHomeUnit(db, townId, k, cur[k] - units[k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reinforcements standing in a host town: [{ ownerTownId, units }] grouped by the POP they belong to.
|
||||||
|
function hostedGroups(db, hostTownId) {
|
||||||
|
const by = new Map();
|
||||||
|
for (const r of db.all('SELECT owner_town_id, unit, count FROM stationed WHERE host_town_id = ? ORDER BY owner_town_id, unit', hostTownId)) {
|
||||||
|
if (!by.has(r.owner_town_id)) by.set(r.owner_town_id, {});
|
||||||
|
by.get(r.owner_town_id)[r.unit] = r.count;
|
||||||
|
}
|
||||||
|
return Array.from(by, ([ownerTownId, units]) => ({ ownerTownId, units }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Units of owner_town_id's operator standing in other POPs: [{ hostTownId, units }].
|
||||||
|
function awayGroups(db, ownerTownId) {
|
||||||
|
const by = new Map();
|
||||||
|
for (const r of db.all('SELECT host_town_id, unit, count FROM stationed WHERE owner_town_id = ? ORDER BY host_town_id, unit', ownerTownId)) {
|
||||||
|
if (!by.has(r.host_town_id)) by.set(r.host_town_id, {});
|
||||||
|
by.get(r.host_town_id)[r.unit] = r.count;
|
||||||
|
}
|
||||||
|
return Array.from(by, ([hostTownId, units]) => ({ hostTownId, units }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function stationedOf(db, hostTownId, ownerTownId) {
|
||||||
|
const out = {};
|
||||||
|
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', hostTownId, ownerTownId)) out[r.unit] = r.count;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setStationed(db, hostTownId, ownerTownId, unit, count) {
|
||||||
|
if (count > 0) db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (host_town_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', hostTownId, ownerTownId, unit, count);
|
||||||
|
else db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ? AND unit = ?', hostTownId, ownerTownId, unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addStationed(db, hostTownId, ownerTownId, units) {
|
||||||
|
const cur = stationedOf(db, hostTownId, ownerTownId);
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, (cur[k] || 0) + units[k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeStationed(db, hostTownId, ownerTownId, units) {
|
||||||
|
const cur = stationedOf(db, hostTownId, ownerTownId);
|
||||||
|
for (const k of Object.keys(units || {})) {
|
||||||
|
if (!(units[k] > 0)) continue;
|
||||||
|
if ((cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
|
||||||
|
}
|
||||||
|
for (const k of Object.keys(units || {})) if (units[k] > 0) setStationed(db, hostTownId, ownerTownId, k, cur[k] - units[k]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Research levels of a POP as { 'unit:stat': level }.
|
||||||
|
function researchLevels(db, townId) {
|
||||||
|
const out = {};
|
||||||
|
for (const r of db.all('SELECT unit, stat, level FROM town_research WHERE town_id = ?', townId)) out[R.researchKey(r.unit, r.stat)] = r.level;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot of the research of `townId` for the unit types in `units` (stored on a movement at departure).
|
||||||
|
function researchSnapshot(db, townId, units) {
|
||||||
|
const all = researchLevels(db, townId);
|
||||||
|
const out = {};
|
||||||
|
for (const u of Object.keys(units)) for (const stat of D.RESEARCH.stats) { const k = R.researchKey(u, stat); if (all[k]) out[k] = all[k]; }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validates and normalises the `units` object of a request: known ids, whole numbers >= 0, zeros dropped.
|
||||||
|
function cleanUnits(raw) {
|
||||||
|
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new GameError('validation_failed', { errors: [{ path: 'units', message: 'must be an object' }] });
|
||||||
|
const out = {};
|
||||||
|
for (const k of Object.keys(raw)) {
|
||||||
|
if (!R.unitDef(k)) throw new GameError('unknown_unit', { unit: k });
|
||||||
|
const n = raw[k];
|
||||||
|
if (!Number.isInteger(n) || n < 0 || n > 1e7) throw new GameError('validation_failed', { errors: [{ path: 'units.' + k, message: 'must be a whole number >= 0' }] });
|
||||||
|
if (n > 0) out[k] = n;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sumInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; };
|
||||||
|
const isEmpty = (units) => !Object.keys(units || {}).some((k) => units[k] > 0);
|
||||||
|
|
||||||
|
// ---- operators
|
||||||
|
function getOperator(db, id) { return db.get('SELECT * FROM operators WHERE id = ?', id); }
|
||||||
|
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
|
||||||
|
function operatorTowns(db, operatorId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY id', operatorId); }
|
||||||
|
|
||||||
|
// Footprint over all POPs of the operator at `now` (each POP's footprint keeps growing from its buildings).
|
||||||
|
function operatorFootprint(db, operatorId, now) {
|
||||||
|
let sum = 0;
|
||||||
|
for (const t of operatorTowns(db, operatorId)) sum += R.footprintAt(loadTown(db, t.id), now);
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
function incumbentTakes(db, operatorId) { return db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', operatorId).n; }
|
||||||
|
function researchBonusOf(db, operatorId) { return R.researchSpeedBonus(incumbentTakes(db, operatorId)); }
|
||||||
|
|
||||||
|
// Where do units of `operatorId` go when their origin POP is gone: the capital, else the oldest POP; null if none.
|
||||||
|
function homeTownFor(db, operatorId, preferTownId) {
|
||||||
|
if (preferTownId) {
|
||||||
|
const t = db.get('SELECT * FROM towns WHERE id = ? AND owner_id = ?', preferTownId, operatorId);
|
||||||
|
if (t) return t;
|
||||||
|
}
|
||||||
|
return db.get('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id LIMIT 1', operatorId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// May `fromOp` stand units in a POP of `toOp`? Own POPs, same alliance, confederation.
|
||||||
|
function mayReinforce(db, fromOp, toOp) {
|
||||||
|
if (fromOp === toOp) return true;
|
||||||
|
return require('../alliances').confederated(db, fromOp, toOp);
|
||||||
|
}
|
||||||
|
// Pacts (same alliance, NAP, confederation) forbid hostile movements between the partners.
|
||||||
|
function pactBlocks(db, fromOp, toOp) {
|
||||||
|
if (fromOp === toOp) return false;
|
||||||
|
return require('../alliances').pactPartners(db, fromOp, toOp);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
homeUnits, setHomeUnit, addHome, removeHome, hostedGroups, awayGroups, stationedOf, setStationed, addStationed, removeStationed,
|
||||||
|
researchLevels, researchSnapshot, cleanUnits, sumInto, isEmpty,
|
||||||
|
getOperator, userOfOperator, operatorTowns, operatorFootprint, incumbentTakes, researchBonusOf, homeTownFor, mayReinforce, pactBlocks,
|
||||||
|
};
|
||||||
155
server/military/views.js
Normal file
155
server/military/views.js
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Read models for the military stage: the military part of GET /towns/:id, the movements list with incoming warnings,
|
||||||
|
* reports, and tile info for the send dialog. Reads catch the event queue up first (via `fresh`) and never write.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { GameError } = require('../errors');
|
||||||
|
const { loadWorld } = require('../state');
|
||||||
|
const U = require('./units');
|
||||||
|
const P = require('./power');
|
||||||
|
|
||||||
|
const j = (s) => JSON.parse(s || '{}');
|
||||||
|
|
||||||
|
function townNames(db, ids) {
|
||||||
|
const out = new Map();
|
||||||
|
for (const id of ids) {
|
||||||
|
if (!id || out.has(id)) continue;
|
||||||
|
const t = db.get('SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?', id);
|
||||||
|
out.set(id, t ? { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital, owner: { id: t.oid, name: t.oname, asNumber: t.asn } } : null);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the owner of a movement sees.
|
||||||
|
function ownerView(m, names) {
|
||||||
|
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
|
||||||
|
const extra = j(m.extra);
|
||||||
|
return {
|
||||||
|
id: m.id, type: m.type, status: m.status, ownerId: m.owner_id,
|
||||||
|
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null },
|
||||||
|
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
|
||||||
|
units: j(m.units), cargo: j(m.cargo), departAt: m.depart_at, arriveAt: m.arrive_at,
|
||||||
|
recallableUntil: m.type === 'return' ? null : m.depart_at + D.MILITARY.recallWindowMs,
|
||||||
|
target: extra.target || null, parentId: m.parent_id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the target of somebody else's movement sees: origin and ETA, never the type, units or cargo.
|
||||||
|
function incomingView(m, names) {
|
||||||
|
const f = m.from_town_id ? names.get(m.from_town_id) : null, t = m.to_town_id ? names.get(m.to_town_id) : null;
|
||||||
|
return {
|
||||||
|
id: m.id, type: 'unknown', status: m.status, incoming: true,
|
||||||
|
from: { townId: m.from_town_id, x: m.from_x, y: m.from_y, name: f ? f.name : null, owner: f ? f.owner : null },
|
||||||
|
to: { townId: m.to_town_id, x: m.to_x, y: m.to_y, name: t ? t.name : null },
|
||||||
|
departAt: m.depart_at, arriveAt: m.arrive_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active movements: the operator's own (outgoing legs, returns, transports) and other operators' movements heading for
|
||||||
|
// the operator's POPs. `townId` limits both to one POP.
|
||||||
|
function movementLists(db, operatorId, townId) {
|
||||||
|
const own = db.all(`SELECT * FROM movements WHERE owner_id = ? AND status = 'out' ${townId ? 'AND (from_town_id = ? OR to_town_id = ?)' : ''} ORDER BY arrive_at, id LIMIT ?`,
|
||||||
|
...(townId ? [operatorId, townId, townId, D.MILITARY.maxLists] : [operatorId, D.MILITARY.maxLists]));
|
||||||
|
const inc = db.all(`SELECT m.* FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id = ? AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return'
|
||||||
|
${townId ? 'AND m.to_town_id = ?' : ''} ORDER BY m.arrive_at, m.id LIMIT ?`,
|
||||||
|
...(townId ? [operatorId, operatorId, townId, D.MILITARY.maxLists] : [operatorId, operatorId, D.MILITARY.maxLists]));
|
||||||
|
const names = townNames(db, own.concat(inc).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||||
|
return { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
|
||||||
|
function townMilitary(db, t, now, world) {
|
||||||
|
const home = U.homeUnits(db, t.id);
|
||||||
|
const online = P.online(t, now);
|
||||||
|
const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId)));
|
||||||
|
const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units }));
|
||||||
|
const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units }));
|
||||||
|
const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id)
|
||||||
|
.map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; });
|
||||||
|
const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id);
|
||||||
|
const rp = rq ? JSON.parse(rq.payload) : null;
|
||||||
|
const bonus = U.researchBonusOf(db, t.ownerId);
|
||||||
|
const trainable = D.UNIT_ORDER.map((unit) => {
|
||||||
|
const def = D.UNITS[unit];
|
||||||
|
const missing = R.unitMissing(t, unit);
|
||||||
|
return { unit, building: def.building, role: def.role, cost: R.unitCost(unit, 1), timeMs: R.trainTimeMs(unit, 1, t.buildings[def.building] ? t.buildings[def.building].level : 0, world.speed), missing, locked: missing.length > 0 };
|
||||||
|
});
|
||||||
|
const offline = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', t.id);
|
||||||
|
const op = U.getOperator(db, t.ownerId);
|
||||||
|
const links = R.transportLinks(t);
|
||||||
|
return {
|
||||||
|
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away },
|
||||||
|
training, trainable,
|
||||||
|
research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel },
|
||||||
|
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink },
|
||||||
|
movements: movementLists(db, t.ownerId, t.id),
|
||||||
|
protectionUntil: op.protection_until,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMilitaryQueries({ db, clock, scheduler }) {
|
||||||
|
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||||
|
|
||||||
|
function operatorFor(userId, worldId) {
|
||||||
|
const op = worldId ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, worldId) : db.get('SELECT * FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', userId);
|
||||||
|
if (!op) throw new GameError('not_found', { what: 'operator' });
|
||||||
|
return op;
|
||||||
|
}
|
||||||
|
|
||||||
|
function movements(userId, { worldId }) {
|
||||||
|
const now = fresh();
|
||||||
|
const op = operatorFor(userId, worldId);
|
||||||
|
return Object.assign({ serverTime: now }, movementLists(db, op.id, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
function reports(userId, { after, limit, unread }) {
|
||||||
|
const now = fresh();
|
||||||
|
const n = limit || 25;
|
||||||
|
const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id
|
||||||
|
WHERE rr.user_id = ? ${after ? 'AND r.id < ?' : ''} ${unread ? 'AND rr.read_at IS NULL' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [userId, after, n + 1] : [userId, n + 1]));
|
||||||
|
const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, role: r.role, read: r.read_at !== null, summary: j(r.summary) }));
|
||||||
|
const unreadCount = db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NULL', userId).n;
|
||||||
|
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null, unread: unreadCount };
|
||||||
|
}
|
||||||
|
|
||||||
|
function report(userId, id) {
|
||||||
|
const now = fresh();
|
||||||
|
const r = db.get(`SELECT r.*, rr.role, rr.read_at FROM report_recipients rr JOIN reports r ON r.id = rr.report_id WHERE rr.user_id = ? AND r.id = ?`, userId, id);
|
||||||
|
if (!r) throw new GameError('not_found', { what: 'report' });
|
||||||
|
return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, role: r.role, read: r.read_at !== null, summary: j(r.summary), data: j(r.data) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public information about a tile, for the send dialog: what is there, who owns it, how far it is from each of my POPs,
|
||||||
|
// whether I could found a POP there.
|
||||||
|
function tileInfo(userId, { worldId, x, y }) {
|
||||||
|
const now = fresh();
|
||||||
|
const op = operatorFor(userId, worldId);
|
||||||
|
const world = loadWorld(db, op.world_id);
|
||||||
|
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||||
|
if (tile.type === 'void') throw new GameError('not_found', { what: 'tile' });
|
||||||
|
const row = db.get('SELECT * FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y);
|
||||||
|
const mine = U.operatorTowns(db, op.id);
|
||||||
|
const out = { serverTime: now, x, y, type: row ? 'pop' : tile.type, bonus: tile.bonus || null, distances: mine.map((t) => ({ townId: t.id, distance: R.distance(t.x, t.y, x, y) })) };
|
||||||
|
if (row) {
|
||||||
|
const o = U.getOperator(db, row.owner_id);
|
||||||
|
out.town = { id: row.id, name: row.name, isCapital: !!row.is_capital, owner: { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protected: R.isProtected(o.protection_until, now), protectionUntil: o.protection_until }, mine: o.id === op.id };
|
||||||
|
}
|
||||||
|
if (tile.type === 'incumbent') {
|
||||||
|
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, op.id);
|
||||||
|
out.incumbent = { takenByYou: taken, hardwareBonus: taken ? 0 : D.INCUMBENT.hardwareBonus };
|
||||||
|
}
|
||||||
|
const fp = U.operatorFootprint(db, op.id, now);
|
||||||
|
const gate = R.footprintGate(mine.length, fp);
|
||||||
|
let nearest = Infinity;
|
||||||
|
for (const t of mine) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||||
|
const sc = R.settleCheck({ tileType: tile.type, occupied: !!row, nearestOwnDist: nearest, ownedCount: mine.length, footprint: fp });
|
||||||
|
out.settle = { possible: sc.ok, code: sc.ok ? null : sc.code, footprint: fp, footprintNeeded: gate.need, maxDistance: D.EXPANSION.maxDistance };
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { movements, reports, report, tileInfo };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { townMilitary, movementLists, createMilitaryQueries };
|
||||||
|
|
@ -7,6 +7,7 @@ const R = require('../public/js/rules.js');
|
||||||
const D = require('../public/js/data.js');
|
const D = require('../public/js/data.js');
|
||||||
const { GameError } = require('./errors');
|
const { GameError } = require('./errors');
|
||||||
const { loadWorld, townFromRow, pendingBuilds } = require('./state');
|
const { loadWorld, townFromRow, pendingBuilds } = require('./state');
|
||||||
|
const { allianceBrief } = require('./alliances');
|
||||||
|
|
||||||
function createQueries({ db, clock, scheduler }) {
|
function createQueries({ db, clock, scheduler }) {
|
||||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||||
|
|
@ -23,7 +24,7 @@ function createQueries({ db, clock, scheduler }) {
|
||||||
const world = loadWorld(db, o.world_id);
|
const world = loadWorld(db, o.world_id);
|
||||||
const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id)
|
const towns = db.all('SELECT id, name, x, y, is_capital FROM towns WHERE owner_id = ? ORDER BY id', o.id)
|
||||||
.map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital }));
|
.map((t) => ({ id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital }));
|
||||||
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, protectionUntil: o.protection_until, world: worldView(world), towns };
|
return { id: o.id, name: o.name, asNumber: o.as_number, allianceId: o.alliance_id, alliance: allianceBrief(db, o.alliance_id), protectionUntil: o.protection_until, world: worldView(world), towns };
|
||||||
});
|
});
|
||||||
return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators };
|
return { serverTime: now, user: { id: user.id, username: user.username, createdAt: user.created_at }, operators };
|
||||||
}
|
}
|
||||||
|
|
@ -68,6 +69,7 @@ function createQueries({ db, clock, scheduler }) {
|
||||||
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
|
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
|
||||||
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
|
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
|
||||||
bonus: t.bonus,
|
bonus: t.bonus,
|
||||||
|
military: require('./military/views').townMilitary(db, t, now, world),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -93,11 +95,11 @@ function createQueries({ db, clock, scheduler }) {
|
||||||
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, o.protection_until AS prot
|
const towns = db.all(`SELECT t.id, t.name, t.x, t.y, t.is_capital, o.id AS oid, o.name AS oname, o.as_number AS asn, o.alliance_id AS ally, a.tag AS atag, a.name AS aname, o.protection_until AS prot
|
||||||
FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
|
FROM towns t JOIN operators o ON o.id = t.owner_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE t.world_id = ? AND t.x BETWEEN ? AND ? AND t.y BETWEEN ? AND ? ORDER BY t.id`,
|
||||||
world.id, x0, x1, y0, y1).map((t) => ({
|
world.id, x0, x1, y0, y1).map((t) => ({
|
||||||
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital,
|
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: !!t.is_capital,
|
||||||
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, protected: t.prot > now },
|
owner: { id: t.oid, name: t.oname, asNumber: t.asn, allianceId: t.ally, alliance: t.ally ? { id: t.ally, tag: t.atag, name: t.aname } : null, protected: t.prot > now },
|
||||||
}));
|
}));
|
||||||
return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns };
|
return { serverTime: now, world: worldView(world), bounds: { x0, x1, y0, y1 }, specials, towns };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
140
server/routes/alliances.js
Normal file
140
server/routes/alliances.js
Normal file
|
|
@ -0,0 +1,140 @@
|
||||||
|
'use strict';
|
||||||
|
/* Alliances, invites, pinned notes and diplomacy (stage 5). Fixed paths are registered before /alliances/:id. */
|
||||||
|
const { reply } = require('../http');
|
||||||
|
const { GameError } = require('../errors');
|
||||||
|
const { createSocialQueries } = require('../socialQueries');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
const S = D.SOCIAL;
|
||||||
|
const int1 = { type: 'integer', minimum: 1 };
|
||||||
|
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
|
||||||
|
const worldQ = { worldId: int1 };
|
||||||
|
|
||||||
|
function register(router, services) {
|
||||||
|
const { commands } = services;
|
||||||
|
const social = createSocialQueries(services);
|
||||||
|
const run = (name, args) => commands.run(name, args);
|
||||||
|
const base = ['unauthorized', 'not_found', 'validation_failed'];
|
||||||
|
const roleErrs = base.concat(['forbidden']);
|
||||||
|
|
||||||
|
router.get('/alliances/mine', {
|
||||||
|
summary: 'Your alliance, role and permissions (null alliance when you are not in one)', tag: 'alliances',
|
||||||
|
query: { type: 'object', properties: worldQ }, response: { $ref: 'AllianceMine' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, query }) => social.mine(user.id, query.worldId));
|
||||||
|
|
||||||
|
router.get('/alliances', {
|
||||||
|
summary: 'Alliance directory of a world, optional name/tag search (cursor: after = last id)', tag: 'alliances',
|
||||||
|
query: { type: 'object', properties: Object.assign({ q: { type: 'string', maxLength: 40 } }, page, worldQ) }, response: { $ref: 'AllianceList' }, errors: base,
|
||||||
|
}, ({ user, query }) => social.list(user.id, query));
|
||||||
|
|
||||||
|
router.post('/alliances', {
|
||||||
|
summary: 'Found an alliance (needs Peering office 1+); you become its leader', tag: 'alliances', status: 201,
|
||||||
|
body: { type: 'object', required: ['name', 'tag'], properties: { name: { type: 'string', minLength: S.nameLen[0], maxLength: S.nameLen[1] * 2 }, tag: { type: 'string', minLength: S.tagLen[0], maxLength: S.tagLen[1] }, worldId: int1 } },
|
||||||
|
response: { $ref: 'AllianceCreated' }, errors: base.concat(['peering_office_required', 'already_in_alliance', 'alliance_name_taken', 'alliance_tag_taken']),
|
||||||
|
}, ({ user, body }) => reply(201, run('allianceCreate', { userId: user.id, worldId: body.worldId, name: body.name, tag: body.tag })));
|
||||||
|
|
||||||
|
router.get('/alliance-invites', {
|
||||||
|
summary: 'Open invites addressed to you', tag: 'alliances', response: { $ref: 'ReceivedInviteList' }, errors: ['unauthorized'],
|
||||||
|
}, ({ user }) => social.invitesReceived(user.id));
|
||||||
|
|
||||||
|
const answerErrs = ['unauthorized', 'not_found', 'conflict', 'invite_expired', 'already_in_alliance', 'peering_office_required', 'alliance_full'];
|
||||||
|
router.post('/alliance-invites/:id/accept', {
|
||||||
|
summary: 'Accept an invite (needs Peering office 1+ and no alliance yet)', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs,
|
||||||
|
}, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: true }));
|
||||||
|
router.post('/alliance-invites/:id/decline', {
|
||||||
|
summary: 'Decline an invite', tag: 'alliances', response: { $ref: 'Changed' }, errors: answerErrs,
|
||||||
|
}, ({ user, params }) => run('allianceInviteAnswer', { userId: user.id, inviteId: params.id, accept: false }));
|
||||||
|
|
||||||
|
router.get('/alliances/:id', {
|
||||||
|
summary: 'Public alliance profile: size, leader, footprint, your role and relation to it', tag: 'alliances', response: { $ref: 'AllianceDetail' }, errors: ['unauthorized', 'not_found'],
|
||||||
|
}, ({ user, params }) => social.get(user.id, params.id));
|
||||||
|
|
||||||
|
router.get('/alliances/:id/members', {
|
||||||
|
summary: 'Member list with role, POP count, footprint and last online (members only)', tag: 'alliances', response: { $ref: 'AllianceMemberList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => social.members(user.id, params.id));
|
||||||
|
|
||||||
|
router.get('/alliances/:id/invites', {
|
||||||
|
summary: 'Pending invites sent by this alliance (needs viewInvites)', tag: 'alliances', response: { $ref: 'AllianceInviteList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => social.invitesSent(user.id, params.id));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/invite', {
|
||||||
|
summary: 'Invite an operator by id or name (needs invite). Repeating it returns the pending invite', tag: 'alliances', status: 201,
|
||||||
|
body: { type: 'object', properties: { operatorId: int1, name: { type: 'string', minLength: 1, maxLength: 40 } } },
|
||||||
|
response: { $ref: 'InviteResult' }, errors: roleErrs.concat(['already_in_alliance', 'alliance_full', 'conflict']),
|
||||||
|
}, ({ user, params, body }) => {
|
||||||
|
if ((body.operatorId === undefined) === (body.name === undefined)) throw new GameError('validation_failed', { errors: [{ path: 'operatorId', message: 'give exactly one of operatorId, name' }] });
|
||||||
|
const r = run('allianceInvite', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, name: body.name });
|
||||||
|
return reply(r.changed ? 201 : 200, r);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.del('/alliances/:id/invites/:inviteId', {
|
||||||
|
summary: 'Cancel a pending invite (needs cancelInvite)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'],
|
||||||
|
}, ({ user, params }) => run('allianceInviteCancel', { userId: user.id, allianceId: params.id, inviteId: params.inviteId }));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/leave', {
|
||||||
|
summary: 'Leave the alliance. The leader must transfer first unless alone (then it is disbanded)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'leader_must_transfer'],
|
||||||
|
}, ({ user, params }) => run('allianceLeave', { userId: user.id, allianceId: params.id }));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/kick', {
|
||||||
|
summary: 'Remove a member you outrank (needs kick)', tag: 'alliances', body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } },
|
||||||
|
response: { $ref: 'Changed' }, errors: roleErrs,
|
||||||
|
}, ({ user, params, body }) => run('allianceKick', { userId: user.id, allianceId: params.id, operatorId: body.operatorId }));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/role', {
|
||||||
|
summary: 'Set a member role: diplomat, officer or member (leader only)', tag: 'alliances',
|
||||||
|
body: { type: 'object', required: ['operatorId', 'role'], properties: { operatorId: int1, role: { type: 'string', enum: ['diplomat', 'officer', 'member'] } } },
|
||||||
|
response: { $ref: 'Changed' }, errors: roleErrs,
|
||||||
|
}, ({ user, params, body }) => run('allianceRole', { userId: user.id, allianceId: params.id, operatorId: body.operatorId, role: body.role }));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/transfer', {
|
||||||
|
summary: 'Hand leadership to another member; you become an officer (leader only)', tag: 'alliances',
|
||||||
|
body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: roleErrs,
|
||||||
|
}, ({ user, params, body }) => run('allianceTransfer', { userId: user.id, allianceId: params.id, operatorId: body.operatorId }));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/disband', {
|
||||||
|
summary: 'Disband the alliance (leader only)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => run('allianceDisband', { userId: user.id, allianceId: params.id }));
|
||||||
|
|
||||||
|
// ---- pinned notes
|
||||||
|
const noteBody = { type: 'object', required: ['text'], properties: { text: { type: 'string', minLength: 1, maxLength: S.noteMax } } };
|
||||||
|
router.get('/alliances/:id/notes', {
|
||||||
|
summary: 'Pinned notes (members only)', tag: 'alliances', response: { $ref: 'AllianceNoteList' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => social.notes(user.id, params.id));
|
||||||
|
router.post('/alliances/:id/notes', {
|
||||||
|
summary: 'Pin a note (needs editNotes)', tag: 'alliances', status: 201, body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs.concat(['notes_full']),
|
||||||
|
}, ({ user, params, body }) => reply(201, run('allianceNoteAdd', { userId: user.id, allianceId: params.id, text: body.text })));
|
||||||
|
router.post('/alliances/:id/notes/:noteId', {
|
||||||
|
summary: 'Edit a pinned note (needs editNotes)', tag: 'alliances', body: noteBody, response: { $ref: 'AllianceNoteResponse' }, errors: roleErrs,
|
||||||
|
}, ({ user, params, body }) => run('allianceNoteEdit', { userId: user.id, allianceId: params.id, noteId: params.noteId, text: body.text }));
|
||||||
|
router.del('/alliances/:id/notes/:noteId', {
|
||||||
|
summary: 'Remove a pinned note (needs editNotes)', tag: 'alliances', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => run('allianceNoteDelete', { userId: user.id, allianceId: params.id, noteId: params.noteId }));
|
||||||
|
|
||||||
|
// ---- diplomacy
|
||||||
|
router.get('/alliances/:id/diplomacy', {
|
||||||
|
summary: 'Relations with other alliances (with scheduled changes) and open proposals (members only)', tag: 'diplomacy', response: { $ref: 'Diplomacy' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => social.diplomacy(user.id, params.id));
|
||||||
|
|
||||||
|
router.post('/alliances/:id/diplomacy', {
|
||||||
|
summary: 'Change the relation to another alliance (needs diplomacy): war applies at once from neutral, pacts need acceptance, cancelling a pact takes 24 h / world speed', tag: 'diplomacy',
|
||||||
|
body: { type: 'object', required: ['targetId', 'state'], properties: { targetId: int1, state: { type: 'string', enum: S.diplomacyStates } } },
|
||||||
|
response: { $ref: 'DiplomacyResult' }, errors: roleErrs.concat(['diplomacy_invalid', 'diplomacy_pending', 'proposal_exists']),
|
||||||
|
}, ({ user, params, body }) => run('diploPropose', { userId: user.id, allianceId: params.id, targetId: body.targetId, state: body.state }));
|
||||||
|
|
||||||
|
router.del('/alliances/:id/diplomacy/:otherId/pending', {
|
||||||
|
summary: 'Take back a scheduled cancel before it takes effect (the alliance that started it, needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden'],
|
||||||
|
}, ({ user, params }) => run('diploRevoke', { userId: user.id, allianceId: params.id, otherId: params.otherId }));
|
||||||
|
|
||||||
|
const propErrs = ['unauthorized', 'not_found', 'forbidden', 'conflict', 'proposal_expired', 'diplomacy_invalid', 'diplomacy_pending'];
|
||||||
|
router.post('/diplomacy/proposals/:proposalId/accept', {
|
||||||
|
summary: 'Accept a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs,
|
||||||
|
}, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: true }));
|
||||||
|
router.post('/diplomacy/proposals/:proposalId/decline', {
|
||||||
|
summary: 'Decline a diplomatic proposal addressed to your alliance (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: propErrs,
|
||||||
|
}, ({ user, params }) => run('diploAnswer', { userId: user.id, proposalId: params.proposalId, accept: false }));
|
||||||
|
router.del('/diplomacy/proposals/:proposalId', {
|
||||||
|
summary: 'Withdraw a proposal your alliance made (needs diplomacy)', tag: 'diplomacy', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'forbidden', 'conflict'],
|
||||||
|
}, ({ user, params }) => run('diploWithdraw', { userId: user.id, proposalId: params.proposalId }));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
/* Registers every REST route. One file per resource; each exports register(router, services). */
|
/* Registers every REST route. One file per resource; each exports register(router, services). */
|
||||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map')];
|
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')];
|
||||||
|
|
||||||
function register(router, services) {
|
function register(router, services) {
|
||||||
for (const f of files) f.register(router, services);
|
for (const f of files) f.register(router, services);
|
||||||
|
|
|
||||||
71
server/routes/messages.js
Normal file
71
server/routes/messages.js
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
'use strict';
|
||||||
|
/* Player messages and alliance broadcasts (stage 5). Fixed paths first, /messages/:id last. */
|
||||||
|
const { reply } = require('../http');
|
||||||
|
const { createSocialQueries } = require('../socialQueries');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
const int1 = { type: 'integer', minimum: 1 };
|
||||||
|
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
|
||||||
|
const listQuery = (extra) => ({ type: 'object', properties: Object.assign({}, page, { worldId: int1 }, extra || {}) });
|
||||||
|
|
||||||
|
function register(router, services) {
|
||||||
|
const { commands } = services;
|
||||||
|
const social = createSocialQueries(services);
|
||||||
|
const run = (name, args) => commands.run(name, args);
|
||||||
|
|
||||||
|
router.get('/messages/inbox', {
|
||||||
|
summary: 'Received messages, newest first (cursor: after = last id of the previous page); `unread` counts all unread', tag: 'messages',
|
||||||
|
query: listQuery({ unread: { type: 'boolean' } }), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, query }) => social.inbox(user.id, query));
|
||||||
|
|
||||||
|
router.get('/messages/outbox', {
|
||||||
|
summary: 'Sent messages, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, query }) => social.outbox(user.id, query));
|
||||||
|
|
||||||
|
router.get('/messages/alliance', {
|
||||||
|
summary: 'Broadcasts of your alliance, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'not_in_alliance', 'validation_failed'],
|
||||||
|
}, ({ user, query }) => social.allianceFeed(user.id, query));
|
||||||
|
|
||||||
|
router.get('/messages/thread/:operatorId', {
|
||||||
|
summary: 'The conversation with one operator, both directions, newest first', tag: 'messages', query: listQuery(), response: { $ref: 'MessageList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, params, query }) => social.thread(user.id, params.operatorId, query));
|
||||||
|
|
||||||
|
router.get('/messages/blocks', {
|
||||||
|
summary: 'Operators you blocked', tag: 'messages', query: { type: 'object', properties: { worldId: int1 } }, response: { $ref: 'BlockList' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, query }) => social.blocks(user.id, query));
|
||||||
|
|
||||||
|
router.post('/messages/blocks', {
|
||||||
|
summary: 'Block an operator: their messages are no longer delivered to you (they are not told)', tag: 'messages',
|
||||||
|
body: { type: 'object', required: ['operatorId'], properties: { operatorId: int1 } }, response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'conflict'],
|
||||||
|
}, ({ user, body }) => run('messageBlock', { userId: user.id, operatorId: body.operatorId }));
|
||||||
|
|
||||||
|
router.del('/messages/blocks/:operatorId', {
|
||||||
|
summary: 'Unblock an operator', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found', 'validation_failed'],
|
||||||
|
}, ({ user, params }) => run('messageUnblock', { userId: user.id, operatorId: params.operatorId }));
|
||||||
|
|
||||||
|
router.post('/messages/read', {
|
||||||
|
summary: 'Mark received messages read: a list of ids (max 100) or all', tag: 'messages',
|
||||||
|
body: { type: 'object', properties: { ids: { type: 'array', maxItems: 100, items: int1 }, all: { type: 'boolean' }, worldId: int1 } },
|
||||||
|
response: { $ref: 'Changed' }, errors: ['unauthorized', 'validation_failed'],
|
||||||
|
}, ({ user, body }) => {
|
||||||
|
const r = commands.run('messageRead', { userId: user.id, ids: body.ids, all: body.all, worldId: body.worldId });
|
||||||
|
return { changed: r.changed > 0, count: r.changed };
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/messages', {
|
||||||
|
summary: 'Send a message to an operator (toOperatorId or toName) or to your alliance (toAlliance). Plain text, max 2000 characters, rate-limited', tag: 'messages', status: 201,
|
||||||
|
body: { type: 'object', required: ['text'], properties: {
|
||||||
|
text: { type: 'string', minLength: 1, maxLength: D.SOCIAL.messageMax }, toOperatorId: int1, toName: { type: 'string', minLength: 1, maxLength: 40 }, toAlliance: { type: 'boolean' }, worldId: int1 } },
|
||||||
|
response: { $ref: 'MessageSent' }, errors: ['unauthorized', 'not_found', 'validation_failed', 'forbidden', 'not_in_alliance', 'rate_limited'],
|
||||||
|
}, ({ user, body }) => reply(201, run('messageSend', { userId: user.id, worldId: body.worldId, toOperatorId: body.toOperatorId, toName: body.toName, toAlliance: body.toAlliance, text: body.text })));
|
||||||
|
|
||||||
|
router.get('/messages/:id', {
|
||||||
|
summary: 'One message you sent or received', tag: 'messages', response: { $ref: 'MessageResponse' }, errors: ['unauthorized', 'not_found'],
|
||||||
|
}, ({ user, params }) => social.message(user.id, params.id));
|
||||||
|
|
||||||
|
router.del('/messages/:id', {
|
||||||
|
summary: 'Delete your own copy of a message (the other side keeps theirs)', tag: 'messages', response: { $ref: 'Changed' }, errors: ['unauthorized', 'not_found'],
|
||||||
|
}, ({ user, params }) => run('messageDelete', { userId: user.id, messageId: params.id }));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
65
server/routes/movements.js
Normal file
65
server/routes/movements.js
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
'use strict';
|
||||||
|
/* Movements: send, recall, list (with incoming warnings), withdraw reinforcements, tile info for the send dialog. */
|
||||||
|
const { reply } = require('../http');
|
||||||
|
const { GameError } = require('../errors');
|
||||||
|
const { createMilitaryQueries } = require('../military/views');
|
||||||
|
|
||||||
|
function register(router, services) {
|
||||||
|
const { commands, db, clock, scheduler } = services;
|
||||||
|
const mq = createMilitaryQueries({ db, clock, scheduler });
|
||||||
|
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||||
|
|
||||||
|
router.post('/movements', {
|
||||||
|
summary: 'Send units (scan, raid, attack, takeover, reinforce, settle) or resources (transport) from one of your POPs. Target = toTownId or the tile x,y', tag: 'movements',
|
||||||
|
body: {
|
||||||
|
type: 'object', required: ['fromTownId', 'type'],
|
||||||
|
properties: {
|
||||||
|
fromTownId: { type: 'integer', minimum: 1 },
|
||||||
|
type: { type: 'string', enum: ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle', 'transport'] },
|
||||||
|
toTownId: { type: 'integer', minimum: 1 },
|
||||||
|
x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 },
|
||||||
|
units: { type: 'object', additionalProperties: true, description: 'unit id -> count' },
|
||||||
|
cargo: { type: 'object', additionalProperties: true, description: 'transport only: fiber/hardware/capital -> amount' },
|
||||||
|
target: { type: 'string', maxLength: 32, pattern: '^[a-z0-9_]+$', description: 'exploit kits: the building (f1..f18 or an infrastructure type) to damage on a win' },
|
||||||
|
wild: { type: 'array', maxItems: 2, items: { type: 'string', maxLength: 32 }, description: 'settle: the two wild slot field types of the new POP' },
|
||||||
|
confirmEndProtection: { type: 'boolean', description: 'raid/attack/takeover from a protected operator: attacking ends beginner protection' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
response: { $ref: 'MovementSent' }, status: 201,
|
||||||
|
errors: errs.concat(['unknown_unit', 'not_enough_units', 'units_offline', 'invalid_target', 'target_protected', 'protection_active', 'out_of_range', 'footprint_too_low',
|
||||||
|
'cannot_takeover', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources']),
|
||||||
|
}, ({ user, body }) => {
|
||||||
|
if (body.type === 'transport') {
|
||||||
|
if (body.toTownId === undefined) throw new GameError('validation_failed', { errors: [{ path: 'toTownId', message: 'is required for a transport' }] });
|
||||||
|
return reply(201, commands.run('sendTransport', { userId: user.id, fromTownId: body.fromTownId, toTownId: body.toTownId, cargo: body.cargo }));
|
||||||
|
}
|
||||||
|
return reply(201, commands.run('sendMovement', {
|
||||||
|
userId: user.id, fromTownId: body.fromTownId, type: body.type, toTownId: body.toTownId, x: body.x, y: body.y, units: body.units,
|
||||||
|
target: body.target, wild: body.wild, confirmEndProtection: body.confirmEndProtection,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/movements', {
|
||||||
|
summary: 'Your active movements and other operators\' movements heading for your POPs (incoming warnings: origin and ETA only, type hidden)', tag: 'movements',
|
||||||
|
query: { type: 'object', properties: { worldId: { type: 'integer', minimum: 1 } } },
|
||||||
|
response: { $ref: 'MovementList' }, errors: errs,
|
||||||
|
}, ({ user, query }) => mq.movements(user.id, { worldId: query.worldId }));
|
||||||
|
|
||||||
|
router.post('/movements/:id/recall', {
|
||||||
|
summary: 'Turn an outbound movement around within the first 90 seconds', tag: 'movements',
|
||||||
|
response: { $ref: 'RecallResult' }, errors: errs.concat(['conflict', 'recall_expired']),
|
||||||
|
}, ({ user, params }) => commands.run('recallMovement', { userId: user.id, movementId: params.id }));
|
||||||
|
|
||||||
|
router.post('/towns/:id/withdraw', {
|
||||||
|
summary: 'Send reinforcements standing in this POP home (host kicks them out, or the units\' owner calls them back)', tag: 'movements',
|
||||||
|
body: { type: 'object', required: ['ownerTownId'], properties: { ownerTownId: { type: 'integer', minimum: 1 }, units: { type: 'object', additionalProperties: true, description: 'defaults to the whole group' } } },
|
||||||
|
response: { $ref: 'WithdrawResult' }, errors: errs.concat(['not_enough_units', 'unknown_unit']),
|
||||||
|
}, ({ user, params, body }) => commands.run('withdrawStationed', { userId: user.id, hostTownId: params.id, ownerTownId: body.ownerTownId, units: body.units }));
|
||||||
|
|
||||||
|
router.get('/map/tile', {
|
||||||
|
summary: 'Public information about one tile for the send dialog: what is there, owner, distance from your POPs, whether you could settle it', tag: 'map',
|
||||||
|
query: { type: 'object', required: ['x', 'y'], properties: { x: { type: 'integer', minimum: -1000, maximum: 1000 }, y: { type: 'integer', minimum: -1000, maximum: 1000 }, worldId: { type: 'integer', minimum: 1 } } },
|
||||||
|
response: { $ref: 'TileInfo' }, errors: errs,
|
||||||
|
}, ({ user, query }) => mq.tileInfo(user.id, { worldId: query.worldId, x: query.x, y: query.y }));
|
||||||
|
}
|
||||||
|
module.exports = { register };
|
||||||
28
server/routes/rankings.js
Normal file
28
server/routes/rankings.js
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
'use strict';
|
||||||
|
/* Rankings (stage 5): operators by footprint, alliances by summed footprint, attackers/defenders by battle points. */
|
||||||
|
const { createSocialQueries } = require('../socialQueries');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
const q = (extra) => ({ type: 'object', properties: Object.assign({
|
||||||
|
worldId: { type: 'integer', minimum: 1 }, after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: D.SOCIAL.rankingsPageMax },
|
||||||
|
}, extra || {}) });
|
||||||
|
|
||||||
|
function register(router, services) {
|
||||||
|
const social = createSocialQueries(services);
|
||||||
|
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||||
|
|
||||||
|
router.get('/rankings/operators', {
|
||||||
|
summary: 'Operators by footprint (cursor: after = number of ranks already seen)', tag: 'rankings', query: q(), response: { $ref: 'RankOperators' }, errors: errs,
|
||||||
|
}, ({ user, query }) => social.rankOperators(user.id, query));
|
||||||
|
|
||||||
|
router.get('/rankings/alliances', {
|
||||||
|
summary: 'Alliances by summed footprint of their members', tag: 'rankings', query: q(), response: { $ref: 'RankAlliances' }, errors: errs,
|
||||||
|
}, ({ user, query }) => social.rankAlliances(user.id, query));
|
||||||
|
|
||||||
|
router.get('/rankings/battles', {
|
||||||
|
summary: 'Attackers / defenders by battle points (`by`: attack, defense or total). Empty with available=false until the military stage records points', tag: 'rankings',
|
||||||
|
query: q({ by: { type: 'string', enum: ['attack', 'defense', 'total'] } }), response: { $ref: 'RankBattles' }, errors: errs,
|
||||||
|
}, ({ user, query }) => social.rankBattles(user.id, query));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { register };
|
||||||
26
server/routes/reports.js
Normal file
26
server/routes/reports.js
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
'use strict';
|
||||||
|
/* Reports of battles, scans, settles and reinforcements (kept 14 days). Newest first; `after` = the last id you have,
|
||||||
|
* the next page holds older ones. */
|
||||||
|
const { createMilitaryQueries } = require('../military/views');
|
||||||
|
|
||||||
|
function register(router, services) {
|
||||||
|
const { commands, db, clock, scheduler } = services;
|
||||||
|
const mq = createMilitaryQueries({ db, clock, scheduler });
|
||||||
|
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||||
|
|
||||||
|
router.get('/reports', {
|
||||||
|
summary: 'Your reports, newest first (cursor: after = id of the last report seen, returns older ones)', tag: 'reports',
|
||||||
|
query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 }, unread: { type: 'boolean' } } },
|
||||||
|
response: { $ref: 'ReportList' }, errors: errs,
|
||||||
|
}, ({ user, query }) => mq.reports(user.id, query));
|
||||||
|
|
||||||
|
router.post('/reports/read-all', { summary: 'Mark all your reports as read', tag: 'reports', response: { $ref: 'Marked' }, errors: ['unauthorized'] },
|
||||||
|
({ user }) => commands.run('markReportRead', { userId: user.id, all: true }));
|
||||||
|
|
||||||
|
router.get('/reports/:id', { summary: 'One report with its full data', tag: 'reports', response: { $ref: 'ReportResponse' }, errors: errs },
|
||||||
|
({ user, params }) => mq.report(user.id, params.id));
|
||||||
|
|
||||||
|
router.post('/reports/:id/read', { summary: 'Mark a report as read', tag: 'reports', response: { $ref: 'Marked' }, errors: errs },
|
||||||
|
({ user, params }) => commands.run('markReportRead', { userId: user.id, reportId: params.id }));
|
||||||
|
}
|
||||||
|
module.exports = { register };
|
||||||
|
|
@ -15,7 +15,7 @@ const schemas = {
|
||||||
Error: obj({ serverTime: int, error: obj({ code: str, message: str, details: { type: 'object', additionalProperties: true } }) }),
|
Error: obj({ serverTime: int, error: obj({ code: str, message: str, details: { type: 'object', additionalProperties: true } }) }),
|
||||||
World: obj({ id: int, name: str, speed: num, mapRadius: int, seed: int, startAt: int, endAt: { type: ['integer', 'null'] }, status: str, preset: str }),
|
World: obj({ id: int, name: str, speed: num, mapRadius: int, seed: int, startAt: int, endAt: { type: ['integer', 'null'] }, status: str, preset: str }),
|
||||||
TownSummary: obj({ id: int, name: str, x: int, y: int, isCapital: bool }),
|
TownSummary: obj({ id: int, name: str, x: int, y: int, isCapital: bool }),
|
||||||
Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }),
|
Operator: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protectionUntil: int, world: { $ref: 'World' }, towns: arr({ $ref: 'TownSummary' }) }),
|
||||||
Me: obj({ serverTime: int, user: obj({ id: int, username: str, createdAt: int }), operators: arr({ $ref: 'Operator' }) }),
|
Me: obj({ serverTime: int, user: obj({ id: int, username: str, createdAt: int }), operators: arr({ $ref: 'Operator' }) }),
|
||||||
AuthResult: obj({ serverTime: int, token: str, tokenId: int, user: obj({ id: int, username: str }), operators: arr({ $ref: 'Operator' }) }),
|
AuthResult: obj({ serverTime: int, token: str, tokenId: int, user: obj({ id: int, username: str }), operators: arr({ $ref: 'Operator' }) }),
|
||||||
Token: obj({ id: int, device: str, createdAt: int, lastUsedAt: int, current: bool }),
|
Token: obj({ id: int, device: str, createdAt: int, lastUsedAt: int, current: bool }),
|
||||||
|
|
@ -31,13 +31,52 @@ const schemas = {
|
||||||
bonus: obj({ fiber: num, hardware: num, capital: num }),
|
bonus: obj({ fiber: num, hardware: num, capital: num }),
|
||||||
}),
|
}),
|
||||||
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
|
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
|
||||||
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, protected: bool }) }),
|
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }),
|
||||||
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
|
MapSpecial: obj({ x: int, y: int, type: str, bonus: { type: ['string', 'null'] } }),
|
||||||
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
|
MapResponse: obj({ serverTime: int, world: { $ref: 'World' }, bounds: obj({ x0: int, x1: int, y0: int, y1: int }), specials: arr({ $ref: 'MapSpecial' }), towns: arr({ $ref: 'MapTown' }) }),
|
||||||
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
|
BuildResult: obj({ serverTime: int, eventId: int, key: str, type: str, toLevel: int, startedAt: int, dueAt: int, cost: { $ref: 'Cost' } }),
|
||||||
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
|
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
|
||||||
NotificationList: obj({ serverTime: int, items: arr({ $ref: 'Notification' }), next: { type: ['integer', 'null'] } }),
|
NotificationList: obj({ serverTime: int, items: arr({ $ref: 'Notification' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
// ---- stage 5: alliances, diplomacy, messages, rankings
|
||||||
|
AllianceBrief: obj({ id: int, tag: str, name: str }),
|
||||||
|
OperatorBrief: obj({ operatorId: int, name: str }),
|
||||||
|
AllianceInfo: obj({ id: int, worldId: int, name: str, tag: str, sizeCap: int, memberCount: int, leader: { type: ['object', 'null'], additionalProperties: true }, createdAt: int }),
|
||||||
|
AllianceDetail: obj({ serverTime: int, alliance: { $ref: 'AllianceInfo' } }),
|
||||||
|
AllianceMine: obj({ serverTime: int, operatorId: int, worldId: int, alliance: { type: ['object', 'null'], additionalProperties: true }, role: { type: ['string', 'null'] }, permissions: arr(str), peeringLevel: int }),
|
||||||
|
AllianceList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInfo' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
AllianceMember: obj({ operatorId: int, name: str, asNumber: int, role: str, joinedAt: int, towns: int, footprint: num, lastOnline: { type: ['integer', 'null'] } }),
|
||||||
|
AllianceMemberList: obj({ serverTime: int, items: arr({ $ref: 'AllianceMember' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
AllianceCreated: obj({ serverTime: int, allianceId: int, name: str, tag: str, sizeCap: int, role: str }),
|
||||||
|
AllianceInvite: obj({ id: int, operator: { $ref: 'OperatorBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }),
|
||||||
|
AllianceInviteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceInvite' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
ReceivedInvite: obj({ id: int, operatorId: int, alliance: { $ref: 'AllianceBrief' }, invitedBy: { $ref: 'OperatorBrief' }, createdAt: int, expiresAt: int }),
|
||||||
|
ReceivedInviteList: obj({ serverTime: int, items: arr({ $ref: 'ReceivedInvite' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
InviteResult: obj({ serverTime: int, inviteId: int, operatorId: int, expiresAt: int, changed: bool }),
|
||||||
|
Changed: obj({ serverTime: int, changed: bool }),
|
||||||
|
AllianceNote: obj({ id: int, authorId: int, text: str, createdAt: int, updatedAt: int }),
|
||||||
|
AllianceNoteResponse: obj({ serverTime: int, note: { $ref: 'AllianceNote' } }),
|
||||||
|
AllianceNoteList: obj({ serverTime: int, items: arr({ $ref: 'AllianceNote' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
Relation: obj({ other: { type: 'object', additionalProperties: true }, state: str, since: int, pending: { type: ['object', 'null'], additionalProperties: true } }),
|
||||||
|
Proposal: obj({ id: int, other: { type: 'object', additionalProperties: true }, state: str, createdAt: int, expiresAt: int }),
|
||||||
|
Diplomacy: obj({ serverTime: int, allianceId: int, relations: arr({ $ref: 'Relation' }), proposalsIn: arr({ $ref: 'Proposal' }), proposalsOut: arr({ $ref: 'Proposal' }) }),
|
||||||
|
DiplomacyResult: obj({ serverTime: int, result: str, from: str, state: str }, ['serverTime', 'result', 'from', 'state']),
|
||||||
|
Message: obj({
|
||||||
|
id: int, kind: str, direction: str, thread: str, from: { $ref: 'OperatorBrief' }, to: { type: ['object', 'null'], additionalProperties: true },
|
||||||
|
alliance: { type: ['object', 'null'], additionalProperties: true }, text: str, createdAt: int, readAt: { type: ['integer', 'null'] },
|
||||||
|
}),
|
||||||
|
MessageList: obj({ serverTime: int, items: arr({ $ref: 'Message' }), next: { type: ['integer', 'null'] }, unread: int }, ['serverTime', 'items', 'next']),
|
||||||
|
MessageResponse: obj({ serverTime: int, message: { $ref: 'Message' } }),
|
||||||
|
MessageSent: obj({ serverTime: int, messageId: int, kind: str, recipients: int, createdAt: int }),
|
||||||
|
BlockList: obj({ serverTime: int, items: arr(obj({ operatorId: int, name: str, createdAt: int })), next: { type: ['integer', 'null'] } }),
|
||||||
|
RankOperator: obj({ rank: int, operatorId: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, allianceTag: { type: ['string', 'null'] }, towns: int, footprint: num }),
|
||||||
|
RankAlliance: obj({ rank: int, allianceId: int, name: str, tag: str, members: int, towns: int, footprint: num }),
|
||||||
|
RankBattle: obj({ rank: int, operatorId: int, name: str, allianceTag: { type: ['string', 'null'] }, attackPoints: num, defensePoints: num }),
|
||||||
|
RankOperators: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankOperator' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
RankAlliances: obj({ serverTime: int, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankAlliance' }), next: { type: ['integer', 'null'] } }),
|
||||||
|
RankBattles: obj({ serverTime: int, by: str, available: bool, total: int, you: { type: ['object', 'null'], additionalProperties: true }, items: arr({ $ref: 'RankBattle' }), next: { type: ['integer', 'null'] } }),
|
||||||
Ok: obj({ serverTime: int }),
|
Ok: obj({ serverTime: int }),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr });
|
||||||
|
|
||||||
module.exports = { schemas, int, num, str, bool, obj, arr };
|
module.exports = { schemas, int, num, str, bool, obj, arr };
|
||||||
|
|
|
||||||
42
server/routes/schemasMilitary.js
Normal file
42
server/routes/schemasMilitary.js
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
'use strict';
|
||||||
|
/* Response schemas of the military stage (merged into routes/schemas.js). Documentation only, like the others. */
|
||||||
|
module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj, arr }) {
|
||||||
|
const nint = { type: ['integer', 'null'] };
|
||||||
|
const free = { type: 'object', additionalProperties: true };
|
||||||
|
const Units = { type: 'object', additionalProperties: true, description: 'unit id -> count' };
|
||||||
|
const Cost = { $ref: 'Cost' };
|
||||||
|
Object.assign(schemas, {
|
||||||
|
Units,
|
||||||
|
TrainResult: obj({ serverTime: int, eventId: int, unit: str, count: int, building: str, startAt: int, dueAt: int, cost: Cost }),
|
||||||
|
ResearchResult: obj({ serverTime: int, eventId: int, unit: str, stat: str, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
|
||||||
|
MovementSent: obj({ serverTime: int, movementId: int, type: str, fromTownId: int, toTownId: nint, to: obj({ x: int, y: int }), units: Units, cargo: free, departAt: int, arriveAt: int, protectionEnded: bool }, ['serverTime', 'movementId', 'type', 'fromTownId', 'toTownId', 'departAt', 'arriveAt']),
|
||||||
|
RecallResult: obj({ serverTime: int, recalled: int, returnMovementId: int, arriveAt: int }),
|
||||||
|
WithdrawResult: obj({ serverTime: int, movementId: int, units: Units, arriveAt: int }),
|
||||||
|
MovementEnd: obj({ townId: nint, x: int, y: int, name: { type: ['string', 'null'] }, owner: { type: ['object', 'null'], additionalProperties: true } }, ['townId', 'x', 'y']),
|
||||||
|
Movement: obj({
|
||||||
|
id: int, type: str, status: str, ownerId: int, from: { $ref: 'MovementEnd' }, to: { $ref: 'MovementEnd' }, units: Units, cargo: free,
|
||||||
|
departAt: int, arriveAt: int, recallableUntil: nint, target: { type: ['string', 'null'] }, parentId: nint, incoming: bool,
|
||||||
|
}, ['id', 'type', 'status', 'from', 'to', 'departAt', 'arriveAt']),
|
||||||
|
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
|
||||||
|
Marked: obj({ serverTime: int, marked: int }),
|
||||||
|
ReportItem: obj({ id: int, type: str, createdAt: int, role: str, read: bool, summary: free }),
|
||||||
|
ReportList: obj({ serverTime: int, items: arr({ $ref: 'ReportItem' }), next: nint, unread: int }),
|
||||||
|
Report: obj({ id: int, type: str, createdAt: int, expiresAt: int, role: str, read: bool, summary: free, data: free }),
|
||||||
|
ReportResponse: obj({ serverTime: int, report: { $ref: 'Report' } }),
|
||||||
|
TileInfo: obj({
|
||||||
|
serverTime: int, x: int, y: int, type: str, bonus: { type: ['string', 'null'] },
|
||||||
|
distances: arr(obj({ townId: int, distance: num })), town: free, incumbent: free,
|
||||||
|
settle: obj({ possible: bool, code: { type: ['string', 'null'] }, footprint: num, footprintNeeded: num, maxDistance: int }),
|
||||||
|
}, ['serverTime', 'x', 'y', 'type', 'distances', 'settle']),
|
||||||
|
TownMilitary: obj({
|
||||||
|
units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free) }),
|
||||||
|
training: arr(obj({ id: int, unit: str, count: int, building: str, startAt: int, dueAt: int })),
|
||||||
|
trainable: arr(obj({ unit: str, building: str, role: str, cost: Cost, timeMs: int, missing: arr(free), locked: bool })),
|
||||||
|
research: obj({ levels: free, queue: { type: ['object', 'null'], additionalProperties: true }, speedBonus: num, maxLevel: int }),
|
||||||
|
transport: obj({ links: int, active: int, capacityPerLink: int }),
|
||||||
|
movements: obj({ outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }) }),
|
||||||
|
protectionUntil: int,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (schemas.Town && schemas.Town.properties) schemas.Town.properties.military = { $ref: 'TownMilitary' }; // optional: not in `required`
|
||||||
|
};
|
||||||
21
server/routes/units.js
Normal file
21
server/routes/units.js
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
'use strict';
|
||||||
|
/* Training queue and research of a POP (stage 3). */
|
||||||
|
const { reply } = require('../http');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
|
||||||
|
function register(router, { commands }) {
|
||||||
|
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||||
|
|
||||||
|
router.post('/towns/:id/train', {
|
||||||
|
summary: 'Queue a batch of one unit type. Batches of the same training building run in order; units appear when the batch is done', tag: 'units',
|
||||||
|
body: { type: 'object', required: ['unit', 'count'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, count: { type: 'integer', minimum: 1, maximum: D.MILITARY.maxBatch } } },
|
||||||
|
response: { $ref: 'TrainResult' }, status: 201, errors: errs.concat(['unknown_unit', 'requirements_not_met', 'not_enough_resources', 'queue_full']),
|
||||||
|
}, ({ user, params, body }) => reply(201, commands.run('train', { userId: user.id, townId: params.id, unit: body.unit, count: body.count })));
|
||||||
|
|
||||||
|
router.post('/towns/:id/research', {
|
||||||
|
summary: 'Research +5% attack or defence for one unit type (one research at a time per POP, needs a Research lab)', tag: 'units',
|
||||||
|
body: { type: 'object', required: ['unit', 'stat'], properties: { unit: { type: 'string', maxLength: 32, pattern: '^[a-z_]+$' }, stat: { type: 'string', enum: ['attack', 'defence'] } } },
|
||||||
|
response: { $ref: 'ResearchResult' }, status: 201, errors: errs.concat(['unknown_unit', 'not_researchable', 'max_level', 'requirements_not_met', 'not_enough_resources', 'queue_full']),
|
||||||
|
}, ({ user, params, body }) => reply(201, commands.run('research', { userId: user.id, townId: params.id, unit: body.unit, stat: body.stat })));
|
||||||
|
}
|
||||||
|
module.exports = { register };
|
||||||
313
server/socialQueries.js
Normal file
313
server/socialQueries.js
Normal file
|
|
@ -0,0 +1,313 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Read models for stage 5: alliances, diplomacy, messages, rankings. Like queries.js, every read first catches the
|
||||||
|
* event queue up to now and reads never write. List cursors: alliances/invites/notes by id ascending, messages newest
|
||||||
|
* first (cursor = the last id of the previous page, next page holds smaller ids), rankings by rank offset.
|
||||||
|
*/
|
||||||
|
const R = require('../public/js/rules.js');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
const { GameError } = require('./errors');
|
||||||
|
const { loadWorld, hasTable } = require('./state');
|
||||||
|
const A = require('./alliances');
|
||||||
|
const { noteView } = require('./commands/allianceNote');
|
||||||
|
|
||||||
|
const S = D.SOCIAL;
|
||||||
|
const MAX_ID = Number.MAX_SAFE_INTEGER;
|
||||||
|
|
||||||
|
function createSocialQueries({ db, clock, scheduler }) {
|
||||||
|
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||||
|
const opBrief = (id, name) => ({ operatorId: id, name });
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- footprint (rankings and alliance sums)
|
||||||
|
|
||||||
|
// operatorId -> { footprint, towns } for a whole world, from two queries (no per-town round trips).
|
||||||
|
function footprints(worldId, now) {
|
||||||
|
const world = loadWorld(db, worldId);
|
||||||
|
const towns = new Map();
|
||||||
|
for (const t of db.all('SELECT id, owner_id, footprint, res_at FROM towns WHERE world_id = ?', worldId)) {
|
||||||
|
towns.set(t.id, { owner: t.owner_id, town: { speed: world.speed, footprint: t.footprint, updatedAt: t.res_at, buildings: {} } });
|
||||||
|
}
|
||||||
|
for (const b of db.all('SELECT b.town_id AS tid, b.key AS key, b.level AS level FROM buildings b JOIN towns t ON t.id = b.town_id WHERE t.world_id = ?', worldId)) {
|
||||||
|
const e = towns.get(b.tid);
|
||||||
|
if (e) e.town.buildings[b.key] = { level: b.level };
|
||||||
|
}
|
||||||
|
const out = new Map();
|
||||||
|
for (const e of towns.values()) {
|
||||||
|
const cur = out.get(e.owner) || { footprint: 0, towns: 0 };
|
||||||
|
cur.footprint += R.footprintAt(e.town, now);
|
||||||
|
cur.towns += 1;
|
||||||
|
out.set(e.owner, cur);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- alliances
|
||||||
|
|
||||||
|
function allianceInfo(a) {
|
||||||
|
const lead = db.get(`SELECT o.id AS id, o.name AS name FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ? AND m.role = 'leader'`, a.id);
|
||||||
|
return {
|
||||||
|
id: a.id, worldId: a.world_id, name: a.name, tag: a.tag, sizeCap: A.effectiveCap(db, a), memberCount: A.memberCount(db, a.id),
|
||||||
|
leader: lead ? opBrief(lead.id, lead.name) : null, createdAt: a.created_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function permissionsOf(role) { return Object.keys(S.permissions).filter((k) => R.allianceCan(role, k)); }
|
||||||
|
|
||||||
|
// Caller's operator + membership in a world (default: their oldest operator).
|
||||||
|
function mine(userId, worldId) {
|
||||||
|
const now = fresh();
|
||||||
|
const op = A.operatorOf(db, userId, worldId);
|
||||||
|
const m = A.membership(db, op.id);
|
||||||
|
const a = m ? A.getAlliance(db, m.alliance_id) : null;
|
||||||
|
return {
|
||||||
|
serverTime: now, operatorId: op.id, worldId: op.world_id,
|
||||||
|
alliance: a ? allianceInfo(a) : null, role: m ? m.role : null, permissions: m ? permissionsOf(m.role) : [],
|
||||||
|
peeringLevel: A.peeringLevel(db, op.id),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function list(userId, { worldId, after, limit, q }) {
|
||||||
|
const now = fresh();
|
||||||
|
const op = A.operatorOf(db, userId, worldId);
|
||||||
|
limit = limit || 30;
|
||||||
|
const needle = q ? String(q).toLowerCase() : '';
|
||||||
|
const rows = db.all(`SELECT * FROM alliances WHERE world_id = ? AND id > ? AND (? = '' OR instr(lower(name), ?) > 0 OR instr(lower(tag), ?) > 0)
|
||||||
|
ORDER BY id LIMIT ?`, op.world_id, after || 0, needle, needle, needle, limit + 1);
|
||||||
|
const items = rows.slice(0, limit).map(allianceInfo);
|
||||||
|
return { serverTime: now, items, next: rows.length > limit ? items[items.length - 1].id : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function get(userId, id) {
|
||||||
|
const now = fresh();
|
||||||
|
const a = A.getAlliance(db, id);
|
||||||
|
const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id);
|
||||||
|
if (!a || !op) throw new GameError('not_found', { what: 'alliance' });
|
||||||
|
const fp = footprints(a.world_id, now);
|
||||||
|
let footprint = 0;
|
||||||
|
for (const m of db.all('SELECT operator_id FROM alliance_members WHERE alliance_id = ?', a.id)) footprint += (fp.get(m.operator_id) || { footprint: 0 }).footprint;
|
||||||
|
const mm = A.membership(db, op.id);
|
||||||
|
const info = allianceInfo(a);
|
||||||
|
info.footprint = Math.round(footprint * 100) / 100;
|
||||||
|
info.myRole = mm && mm.alliance_id === a.id ? mm.role : null;
|
||||||
|
info.relation = !mm ? null : mm.alliance_id === a.id ? 'same' : A.relationBetween(db, mm.alliance_id, a.id);
|
||||||
|
return { serverTime: now, alliance: info };
|
||||||
|
}
|
||||||
|
|
||||||
|
function memberOnly(userId, allianceId) {
|
||||||
|
const a = A.getAlliance(db, allianceId);
|
||||||
|
const op = a && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, a.world_id);
|
||||||
|
if (!a || !op) throw new GameError('not_found', { what: 'alliance' });
|
||||||
|
const m = A.membership(db, op.id);
|
||||||
|
if (!m || m.alliance_id !== a.id) throw new GameError('forbidden', { need: 'member' });
|
||||||
|
return { a, op, m };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Member list with POP count, footprint and last online (newest token use of the user; tokens.last_used_at is
|
||||||
|
// refreshed at most once a minute by auth.authenticate). The list is bounded by the size cap, so it is not paginated.
|
||||||
|
function members(userId, allianceId) {
|
||||||
|
const now = fresh();
|
||||||
|
const { a } = memberOnly(userId, allianceId);
|
||||||
|
const fp = footprints(a.world_id, now);
|
||||||
|
const rows = db.all(`SELECT m.operator_id AS id, m.role AS role, m.joined_at AS joined, o.name AS name, o.as_number AS asn,
|
||||||
|
(SELECT MAX(t.last_used_at) FROM tokens t WHERE t.user_id = o.user_id) AS seen
|
||||||
|
FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE m.alliance_id = ?`, a.id);
|
||||||
|
const items = rows.map((r) => {
|
||||||
|
const f = fp.get(r.id) || { footprint: 0, towns: 0 };
|
||||||
|
return { operatorId: r.id, name: r.name, asNumber: r.asn, role: r.role, joinedAt: r.joined, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100, lastOnline: r.seen };
|
||||||
|
}).sort((x, y) => R.roleRank(y.role) - R.roleRank(x.role) || x.name.localeCompare(y.name));
|
||||||
|
return { serverTime: now, items, next: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function invitesSent(userId, allianceId) {
|
||||||
|
const now = fresh();
|
||||||
|
const { a, m } = memberOnly(userId, allianceId);
|
||||||
|
if (!R.allianceCan(m.role, 'viewInvites')) throw new GameError('forbidden', { need: 'viewInvites', role: m.role });
|
||||||
|
const rows = db.all(`SELECT i.id, i.operator_id AS oid, i.created_at, i.expires_at, t.name AS tname, b.name AS bname, i.invited_by AS bid
|
||||||
|
FROM alliance_invites i JOIN operators t ON t.id = i.operator_id JOIN operators b ON b.id = i.invited_by
|
||||||
|
WHERE i.alliance_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, a.id, now);
|
||||||
|
return { serverTime: now, items: rows.map((r) => ({ id: r.id, operator: opBrief(r.oid, r.tname), invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function invitesReceived(userId) {
|
||||||
|
const now = fresh();
|
||||||
|
const rows = db.all(`SELECT i.id, i.alliance_id AS aid, i.created_at, i.expires_at, a.tag AS tag, a.name AS name, b.id AS bid, b.name AS bname, o.id AS oid
|
||||||
|
FROM alliance_invites i JOIN operators o ON o.id = i.operator_id JOIN alliances a ON a.id = i.alliance_id JOIN operators b ON b.id = i.invited_by
|
||||||
|
WHERE o.user_id = ? AND i.status = 'pending' AND i.expires_at > ? ORDER BY i.id`, userId, now);
|
||||||
|
return { serverTime: now, items: rows.map((r) => ({ id: r.id, operatorId: r.oid, alliance: { id: r.aid, tag: r.tag, name: r.name }, invitedBy: opBrief(r.bid, r.bname), createdAt: r.created_at, expiresAt: r.expires_at })), next: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function notes(userId, allianceId) {
|
||||||
|
const now = fresh();
|
||||||
|
const { a } = memberOnly(userId, allianceId);
|
||||||
|
const rows = db.all('SELECT * FROM alliance_notes WHERE alliance_id = ? ORDER BY id', a.id);
|
||||||
|
return { serverTime: now, items: rows.map(noteView), next: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function diplomacy(userId, allianceId) {
|
||||||
|
const now = fresh();
|
||||||
|
const { a } = memberOnly(userId, allianceId);
|
||||||
|
const brief = (id) => { const x = A.allianceBrief(db, id); return x || { id, tag: null, name: null }; };
|
||||||
|
const relations = db.all('SELECT * FROM alliance_relations WHERE a_id = ? OR b_id = ? ORDER BY since, a_id', a.id, a.id).map((r) => {
|
||||||
|
const other = r.a_id === a.id ? r.b_id : r.a_id;
|
||||||
|
return {
|
||||||
|
other: brief(other), state: r.state, since: r.since,
|
||||||
|
pending: r.pending_to ? { to: r.pending_to, effectiveAt: r.pending_at, startedBy: r.pending_by, byUs: r.pending_by === a.id } : null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const prop = (r, otherId) => ({ id: r.id, other: brief(otherId), state: r.state, createdAt: r.created_at, expiresAt: r.expires_at });
|
||||||
|
const incoming = db.all("SELECT * FROM alliance_proposals WHERE to_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.from_id));
|
||||||
|
const outgoing = db.all("SELECT * FROM alliance_proposals WHERE from_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id", a.id, now).map((r) => prop(r, r.to_id));
|
||||||
|
return { serverTime: now, allianceId: a.id, relations, proposalsIn: incoming, proposalsOut: outgoing };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- rankings
|
||||||
|
|
||||||
|
function rankingWorld(userId, worldId) {
|
||||||
|
const op = A.operatorOf(db, userId, worldId);
|
||||||
|
return op;
|
||||||
|
}
|
||||||
|
|
||||||
|
function page(rows, after, limit) {
|
||||||
|
const start = after || 0, n = limit || 50;
|
||||||
|
const slice = rows.slice(start, start + n).map((r, i) => Object.assign({ rank: start + i + 1 }, r));
|
||||||
|
return { items: slice, next: start + n < rows.length ? start + n : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
function rankOperators(userId, { worldId, after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = rankingWorld(userId, worldId);
|
||||||
|
const fp = footprints(me.world_id, now);
|
||||||
|
const ops = db.all('SELECT o.id AS id, o.name AS name, o.as_number AS asn, a.id AS aid, a.tag AS tag FROM operators o LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?', me.world_id);
|
||||||
|
const rows = ops.map((o) => {
|
||||||
|
const f = fp.get(o.id) || { footprint: 0, towns: 0 };
|
||||||
|
return { operatorId: o.id, name: o.name, asNumber: o.asn, allianceId: o.aid, allianceTag: o.tag, towns: f.towns, footprint: Math.round(f.footprint * 100) / 100 };
|
||||||
|
}).sort((x, y) => y.footprint - x.footprint || x.operatorId - y.operatorId);
|
||||||
|
const you = rows.findIndex((r) => r.operatorId === me.id);
|
||||||
|
return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
function rankAlliances(userId, { worldId, after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = rankingWorld(userId, worldId);
|
||||||
|
const fp = footprints(me.world_id, now);
|
||||||
|
const byAlliance = new Map();
|
||||||
|
for (const o of db.all('SELECT o.id AS id, o.alliance_id AS aid FROM operators o WHERE o.world_id = ? AND o.alliance_id IS NOT NULL', me.world_id)) {
|
||||||
|
const cur = byAlliance.get(o.aid) || { footprint: 0, members: 0, towns: 0 };
|
||||||
|
const f = fp.get(o.id) || { footprint: 0, towns: 0 };
|
||||||
|
cur.footprint += f.footprint; cur.towns += f.towns; cur.members += 1;
|
||||||
|
byAlliance.set(o.aid, cur);
|
||||||
|
}
|
||||||
|
const rows = db.all('SELECT id, name, tag FROM alliances WHERE world_id = ?', me.world_id).map((a) => {
|
||||||
|
const s = byAlliance.get(a.id) || { footprint: 0, members: 0, towns: 0 };
|
||||||
|
return { allianceId: a.id, name: a.name, tag: a.tag, members: s.members, towns: s.towns, footprint: Math.round(s.footprint * 100) / 100 };
|
||||||
|
}).sort((x, y) => y.footprint - x.footprint || x.allianceId - y.allianceId);
|
||||||
|
const mm = A.membership(db, me.id);
|
||||||
|
const you = mm ? rows.findIndex((r) => r.allianceId === mm.alliance_id) : -1;
|
||||||
|
return Object.assign({ serverTime: now, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Battle points come from operator_stats, created by the military stage (migration 002). Without the table the
|
||||||
|
// list is simply empty (`available: false`).
|
||||||
|
function rankBattles(userId, { worldId, by, after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = rankingWorld(userId, worldId);
|
||||||
|
by = by || 'attack';
|
||||||
|
if (!hasTable(db, 'operator_stats')) return Object.assign({ serverTime: now, by, available: false, total: 0, you: null }, page([], after, limit));
|
||||||
|
const rows = db.all(`SELECT o.id AS id, o.name AS name, a.tag AS tag, s.attack_points AS att, s.defense_points AS def
|
||||||
|
FROM operator_stats s JOIN operators o ON o.id = s.operator_id LEFT JOIN alliances a ON a.id = o.alliance_id WHERE o.world_id = ?`, me.world_id)
|
||||||
|
.map((r) => ({ operatorId: r.id, name: r.name, allianceTag: r.tag, attackPoints: r.att || 0, defensePoints: r.def || 0 }))
|
||||||
|
.filter((r) => r.attackPoints > 0 || r.defensePoints > 0)
|
||||||
|
.sort((x, y) => {
|
||||||
|
const k = (r) => (by === 'defense' ? r.defensePoints : by === 'total' ? r.attackPoints + r.defensePoints : r.attackPoints);
|
||||||
|
return k(y) - k(x) || x.operatorId - y.operatorId;
|
||||||
|
});
|
||||||
|
const you = rows.findIndex((r) => r.operatorId === me.id);
|
||||||
|
return Object.assign({ serverTime: now, by, available: true, total: rows.length, you: you < 0 ? null : Object.assign({ rank: you + 1 }, rows[you]) }, page(rows, after, limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- messages
|
||||||
|
|
||||||
|
const BASE = `SELECT m.*, s.name AS sname, t.name AS tname, r.operator_id AS rop, r.read_at AS rread
|
||||||
|
FROM messages m JOIN operators s ON s.id = m.sender_id LEFT JOIN operators t ON t.id = m.to_id
|
||||||
|
LEFT JOIN message_recipients r ON r.message_id = m.id AND r.operator_id = ?`;
|
||||||
|
const VISIBLE_IN = '(r.operator_id IS NOT NULL AND r.deleted_at IS NULL)';
|
||||||
|
const VISIBLE_OUT = '(m.sender_id = ? AND m.sender_deleted_at IS NULL)';
|
||||||
|
|
||||||
|
function msgView(row, meId) {
|
||||||
|
const out = row.sender_id === meId;
|
||||||
|
return {
|
||||||
|
id: row.id, kind: row.kind, direction: out ? 'out' : 'in', thread: row.thread,
|
||||||
|
from: opBrief(row.sender_id, row.sname), to: row.kind === 'dm' ? opBrief(row.to_id, row.tname) : null,
|
||||||
|
alliance: row.kind === 'alliance' ? { id: row.alliance_id, tag: row.alliance_tag } : null,
|
||||||
|
text: row.body, createdAt: row.created_at, readAt: out ? null : row.rread,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function messagePage(me, sql, params, limit) {
|
||||||
|
limit = limit || 30;
|
||||||
|
const rows = db.all(sql + ' ORDER BY m.id DESC LIMIT ?', me.id, ...params, limit + 1);
|
||||||
|
const items = rows.slice(0, limit).map((r) => msgView(r, me.id));
|
||||||
|
return { items, next: rows.length > limit ? items[items.length - 1].id : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const unreadCount = (opId) => db.get('SELECT COUNT(*) AS n FROM message_recipients WHERE operator_id = ? AND read_at IS NULL AND deleted_at IS NULL', opId).n;
|
||||||
|
|
||||||
|
function inbox(userId, { worldId, after, limit, unread }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = A.operatorOf(db, userId, worldId);
|
||||||
|
const sql = BASE + ' WHERE ' + VISIBLE_IN + (unread ? ' AND r.read_at IS NULL' : '') + ' AND m.id < ?';
|
||||||
|
return Object.assign({ serverTime: now, unread: unreadCount(me.id) }, messagePage(me, sql, [after || MAX_ID], limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
function outbox(userId, { worldId, after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = A.operatorOf(db, userId, worldId);
|
||||||
|
return Object.assign({ serverTime: now }, messagePage(me, BASE + ' WHERE ' + VISIBLE_OUT + ' AND m.id < ?', [me.id, after || MAX_ID], limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conversation with one operator, both directions, newest first.
|
||||||
|
function thread(userId, otherId, { after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const other = db.get('SELECT id, world_id FROM operators WHERE id = ?', otherId);
|
||||||
|
const me = other && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, other.world_id);
|
||||||
|
if (!other || !me) throw new GameError('not_found', { what: 'operator' });
|
||||||
|
const key = 'dm:' + Math.min(me.id, other.id) + ':' + Math.max(me.id, other.id);
|
||||||
|
const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?';
|
||||||
|
return Object.assign({ serverTime: now }, messagePage(me, sql, [key, me.id, after || MAX_ID], limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Broadcasts of the caller's current alliance.
|
||||||
|
function allianceFeed(userId, { worldId, after, limit }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = A.operatorOf(db, userId, worldId);
|
||||||
|
const m = A.membership(db, me.id);
|
||||||
|
if (!m) throw new GameError('not_in_alliance');
|
||||||
|
const sql = BASE + ' WHERE m.thread = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ') AND m.id < ?';
|
||||||
|
return Object.assign({ serverTime: now }, messagePage(me, sql, ['alliance:' + m.alliance_id, me.id, after || MAX_ID], limit));
|
||||||
|
}
|
||||||
|
|
||||||
|
function message(userId, id) {
|
||||||
|
const now = fresh();
|
||||||
|
const m = db.get('SELECT world_id FROM messages WHERE id = ?', id);
|
||||||
|
const me = m && db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, m.world_id);
|
||||||
|
if (!m || !me) throw new GameError('not_found', { what: 'message' });
|
||||||
|
const row = db.get(BASE + ' WHERE m.id = ? AND (' + VISIBLE_OUT + ' OR ' + VISIBLE_IN + ')', me.id, id, me.id);
|
||||||
|
if (!row) throw new GameError('not_found', { what: 'message' });
|
||||||
|
return { serverTime: now, message: msgView(row, me.id) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function blocks(userId, { worldId }) {
|
||||||
|
const now = fresh();
|
||||||
|
const me = A.operatorOf(db, userId, worldId);
|
||||||
|
const rows = db.all('SELECT b.blocked_id AS id, o.name AS name, b.created_at AS at FROM message_blocks b JOIN operators o ON o.id = b.blocked_id WHERE b.operator_id = ? ORDER BY b.created_at, b.blocked_id', me.id);
|
||||||
|
return { serverTime: now, items: rows.map((r) => ({ operatorId: r.id, name: r.name, createdAt: r.at })), next: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
mine, list, get, members, invitesSent, invitesReceived, notes, diplomacy,
|
||||||
|
rankOperators, rankAlliances, rankBattles,
|
||||||
|
inbox, outbox, thread, allianceFeed, message, blocks, footprints,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createSocialQueries };
|
||||||
|
|
@ -35,6 +35,10 @@ function unitDraw(db, townId) {
|
||||||
const rows = db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId);
|
const rows = db.all('SELECT unit, count FROM town_units WHERE town_id = ?', townId);
|
||||||
let draw = 0;
|
let draw = 0;
|
||||||
for (const r of rows) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
|
for (const r of rows) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
|
||||||
|
// Reinforcements draw from the host, not from their owner.
|
||||||
|
if (hasTable(db, 'stationed')) {
|
||||||
|
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ?', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
|
||||||
|
}
|
||||||
return draw;
|
return draw;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
26
server/text.js
Normal file
26
server/text.js
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Plain-text hygiene for everything players type that other players read (messages, notes, alliance names).
|
||||||
|
* Strips control characters and the invisible/bidirectional formatting characters that can be used to spoof text
|
||||||
|
* ("Trojan Source" style reordering, zero-width padding to hide content), normalises to NFC and fixes lone surrogates.
|
||||||
|
* Newlines and tabs survive only in multiline text.
|
||||||
|
*/
|
||||||
|
// C0 (except \t \n, CR is normalised first), DEL + C1, ALM, zero-width space, LRM/RLM, bidi embeddings/overrides
|
||||||
|
// (202A-202E), word joiner and invisible operators (2060-2064), bidi isolates and deprecated formatting (2066-206F),
|
||||||
|
// BOM, interlinear annotation, and the invisible Unicode tag block. ZWJ/ZWNJ (200C/200D) stay: emoji and some scripts need them.
|
||||||
|
const STRIP = new RegExp('[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u061C\\u200B\\u200E\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\uFEFF\\uFFF9-\\uFFFB\\u{E0000}-\\u{E007F}]', 'gu');
|
||||||
|
|
||||||
|
function cleanText(input, opts) {
|
||||||
|
const multiline = !!(opts && opts.multiline);
|
||||||
|
let s = String(input === undefined || input === null ? '' : input);
|
||||||
|
if (s.toWellFormed) s = s.toWellFormed();
|
||||||
|
s = s.normalize('NFC').replace(/\r\n?/g, '\n').replace(/[\u2028\u2029\u0085]/g, '\n').replace(STRIP, '');
|
||||||
|
if (multiline) s = s.replace(/[ \t]+\n/g, '\n').replace(/\n{4,}/g, '\n\n\n');
|
||||||
|
else s = s.replace(/[\n\t]+/g, ' ').replace(/ {2,}/g, ' ');
|
||||||
|
return s.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Length in code points (what a player counts), not UTF-16 units.
|
||||||
|
const textLength = (s) => { let n = 0; for (const _ of s) n++; return n; }; // eslint-disable-line no-unused-vars
|
||||||
|
|
||||||
|
module.exports = { cleanText, textLength };
|
||||||
284
test/admin-cli.test.js
Normal file
284
test/admin-cli.test.js
Normal file
|
|
@ -0,0 +1,284 @@
|
||||||
|
'use strict';
|
||||||
|
// tools/admin.js against temp databases. The ban test runs the real HTTP server and the CLI on the same DB file
|
||||||
|
// at the same time, which is exactly how the CLI is used in production.
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const admin = require('../tools/admin.js');
|
||||||
|
const { createServer } = require('../server');
|
||||||
|
const { openDb, migrate } = require('../server/db');
|
||||||
|
|
||||||
|
function tmp() { return fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-admin-test-')); }
|
||||||
|
|
||||||
|
// run the CLI in-process; returns { code, out, err, json }
|
||||||
|
function cli(dbPath, args, now) {
|
||||||
|
const out = [], err = [];
|
||||||
|
const code = admin.main(args.concat(['--db', dbPath]), { out: (s) => out.push(s), err: (s) => err.push(s), env: {}, now: now ? () => now : undefined });
|
||||||
|
const text = out.join('\n');
|
||||||
|
let json = null;
|
||||||
|
if (args.includes('--json')) { try { json = JSON.parse(text); } catch (e) { /* not json */ } }
|
||||||
|
return { code, out: text, err: err.join('\n'), json };
|
||||||
|
}
|
||||||
|
|
||||||
|
function freshDb(dir) {
|
||||||
|
const file = path.join(dir, 'game.db');
|
||||||
|
const db = openDb(file); migrate(db); db.close();
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function api(srv, method, url, body, token) {
|
||||||
|
const res = await fetch('http://127.0.0.1:' + srv.port + '/api/v1' + url, {
|
||||||
|
method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}),
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
});
|
||||||
|
return { status: res.status, body: await res.json() };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('parseArgs, parseTime, parseDuration', () => {
|
||||||
|
const a = admin.parseArgs(['backup', '/x', '--keep', '5', '--yes', '--type=buildDone']);
|
||||||
|
assert.deepEqual(a._, ['backup', '/x']);
|
||||||
|
assert.deepEqual(a.flags, { keep: '5', yes: true, type: 'buildDone' });
|
||||||
|
assert.throws(() => admin.parseArgs(['events', '--limit']), /needs a value/);
|
||||||
|
const now = Date.UTC(2026, 0, 1);
|
||||||
|
assert.equal(admin.parseTime('now', now), now);
|
||||||
|
assert.equal(admin.parseTime('+2h', now), now + 7200e3);
|
||||||
|
assert.equal(admin.parseTime('-30m', now), now - 1800e3);
|
||||||
|
assert.equal(admin.parseTime('2026-01-02T00:00:00Z', now), now + 86400e3);
|
||||||
|
assert.equal(admin.parseDuration('14d'), 14 * 86400e3);
|
||||||
|
assert.throws(() => admin.parseTime('soon', now), /bad time/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('help and unknown command', () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const h = cli(path.join(dir, 'none.db'), ['help']);
|
||||||
|
assert.equal(h.code, 0);
|
||||||
|
assert.match(h.out, /reset-world/);
|
||||||
|
const u = cli(path.join(dir, 'none.db'), ['frobnicate']);
|
||||||
|
assert.equal(u.code, 2);
|
||||||
|
assert.match(u.err, /unknown command/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing database is an error, not a silently created empty file', () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const file = path.join(dir, 'nope.db');
|
||||||
|
const r = cli(file, ['worlds']);
|
||||||
|
assert.equal(r.code, 1);
|
||||||
|
assert.match(r.err, /database not found/);
|
||||||
|
assert.equal(fs.existsSync(file), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('create-world, worlds, end-world needs --yes', () => {
|
||||||
|
const file = freshDb(tmp());
|
||||||
|
const c = cli(file, ['create-world', '--name', 'Lab', '--speed', '3', '--radius', '12', '--seed', '42', '--json']);
|
||||||
|
assert.equal(c.code, 0);
|
||||||
|
assert.equal(c.json.world.name, 'Lab');
|
||||||
|
assert.equal(c.json.world.seed, 42);
|
||||||
|
assert.equal(c.json.world.map_radius, 12);
|
||||||
|
assert.equal(cli(file, ['create-world', '--speed', 'fast']).code, 2);
|
||||||
|
const w = cli(file, ['worlds', '--json']);
|
||||||
|
assert.equal(w.json.worlds.length, 1);
|
||||||
|
const id = w.json.worlds[0].id;
|
||||||
|
assert.equal(cli(file, ['end-world', String(id)]).code, 2);
|
||||||
|
assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'running');
|
||||||
|
assert.equal(cli(file, ['end-world', String(id), '--yes']).code, 0);
|
||||||
|
assert.equal(cli(file, ['worlds', '--json']).json.worlds[0].status, 'ended');
|
||||||
|
assert.equal(cli(file, ['end-world', '99', '--yes']).code, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('backup: readable verified snapshot, never overwrites, retention prunes only its own files', () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const file = freshDb(dir);
|
||||||
|
cli(file, ['create-world', '--name', 'Backed up']);
|
||||||
|
const dest = path.join(dir, 'bk');
|
||||||
|
fs.mkdirSync(dest);
|
||||||
|
fs.writeFileSync(path.join(dest, 'notes.txt'), 'keep me');
|
||||||
|
const t0 = Date.UTC(2026, 5, 1, 4, 0, 0);
|
||||||
|
|
||||||
|
const b1 = cli(file, ['backup', dest, '--json'], t0);
|
||||||
|
assert.equal(b1.code, 0, b1.err);
|
||||||
|
assert.match(path.basename(b1.json.file), /^upstream-20260601T040000Z\.db$/);
|
||||||
|
const v = admin.verifySnapshot(b1.json.file);
|
||||||
|
assert.equal(v.integrity, 'ok');
|
||||||
|
assert.equal(v.worlds, 1);
|
||||||
|
assert.equal(cli(file, ['verify-backup', b1.json.file]).code, 0);
|
||||||
|
|
||||||
|
// the snapshot opens as an ordinary database and holds the data
|
||||||
|
const snap = openDb(b1.json.file);
|
||||||
|
assert.equal(snap.get('SELECT name FROM worlds').name, 'Backed up');
|
||||||
|
snap.close();
|
||||||
|
|
||||||
|
// same second: a second file, the first one untouched
|
||||||
|
const before = fs.readFileSync(b1.json.file);
|
||||||
|
const b2 = cli(file, ['backup', dest, '--json'], t0);
|
||||||
|
assert.equal(b2.code, 0);
|
||||||
|
assert.notEqual(b2.json.file, b1.json.file);
|
||||||
|
assert.deepEqual(fs.readFileSync(b1.json.file), before);
|
||||||
|
|
||||||
|
// retention by count: three more days of snapshots, keep 2
|
||||||
|
for (let d = 1; d <= 3; d++) assert.equal(cli(file, ['backup', dest], t0 + d * 86400e3).code, 0);
|
||||||
|
const r = cli(file, ['backup', dest, '--keep', '2', '--json'], t0 + 4 * 86400e3);
|
||||||
|
assert.equal(r.code, 0);
|
||||||
|
const left = admin.listBackups(dest).map((b) => b.name);
|
||||||
|
assert.equal(left.length, 2);
|
||||||
|
assert.ok(left[0].includes('20260605'));
|
||||||
|
assert.ok(fs.existsSync(path.join(dest, 'notes.txt')), 'foreign files are never touched');
|
||||||
|
assert.equal(fs.readdirSync(dest).filter((n) => n.startsWith('.partial')).length, 0);
|
||||||
|
|
||||||
|
// a corrupt target is not a backup
|
||||||
|
fs.writeFileSync(path.join(dir, 'junk.db'), 'not a database');
|
||||||
|
assert.notEqual(cli(file, ['verify-backup', path.join(dir, 'junk.db')]).code, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pruneSet: count, age, both, never the newest', () => {
|
||||||
|
const now = Date.UTC(2026, 5, 10);
|
||||||
|
const mk = (daysAgo) => ({ name: 'd' + daysAgo, at: now - daysAgo * 86400e3, seq: 0 });
|
||||||
|
const list = [mk(0), mk(1), mk(2), mk(5), mk(9)];
|
||||||
|
assert.deepEqual(admin.pruneSet(list, now, {}), []);
|
||||||
|
assert.deepEqual(admin.pruneSet(list, now, { keep: 2 }).map((b) => b.name), ['d2', 'd5', 'd9']);
|
||||||
|
assert.deepEqual(admin.pruneSet(list, now, { keepDays: 3 }).map((b) => b.name), ['d5', 'd9']);
|
||||||
|
assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 3 }).map((b) => b.name), ['d5', 'd9']);
|
||||||
|
assert.deepEqual(admin.pruneSet(list, now, { keep: 1, keepDays: 0.1 }).map((b) => b.name), ['d1', 'd2', 'd5', 'd9']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ban stops login and revokes tokens on a RUNNING server; unban restores; output never leaks secrets', async () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const file = path.join(dir, 'game.db');
|
||||||
|
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, world: { mapRadius: 20 } });
|
||||||
|
try {
|
||||||
|
const s = await api(srv, 'POST', '/auth/signup', { username: 'mallory', password: 'correct horse battery' });
|
||||||
|
assert.equal(s.status, 201);
|
||||||
|
const token = s.body.token;
|
||||||
|
assert.equal((await api(srv, 'GET', '/me', null, token)).status, 200);
|
||||||
|
|
||||||
|
const u = cli(file, ['users']);
|
||||||
|
assert.match(u.out, /mallory/);
|
||||||
|
assert.ok(!u.out.includes(token));
|
||||||
|
assert.ok(!/scrypt/.test(u.out + cli(file, ['inspect-operator', 'mallory']).out), 'no password hashes in output');
|
||||||
|
|
||||||
|
const b = cli(file, ['ban', 'mallory', '--json']);
|
||||||
|
assert.equal(b.code, 0, b.err);
|
||||||
|
assert.equal(b.json.tokensRevoked, 1);
|
||||||
|
assert.equal((await api(srv, 'GET', '/me', null, token)).status, 401, 'old token is dead');
|
||||||
|
const login = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' });
|
||||||
|
assert.equal(login.status, 403);
|
||||||
|
assert.equal(login.body.error.code, 'forbidden');
|
||||||
|
assert.match(cli(file, ['users', '--banned']).out, /BANNED/);
|
||||||
|
|
||||||
|
assert.equal(cli(file, ['unban', 'mallory']).code, 0);
|
||||||
|
const again = await api(srv, 'POST', '/auth/login', { username: 'mallory', password: 'correct horse battery' });
|
||||||
|
assert.equal(again.status, 200);
|
||||||
|
|
||||||
|
assert.equal(cli(file, ['revoke-tokens', 'mallory', '--json']).json.revoked, 1);
|
||||||
|
assert.equal((await api(srv, 'GET', '/me', null, again.body.token)).status, 401);
|
||||||
|
assert.equal(cli(file, ['ban', 'nobody']).code, 3);
|
||||||
|
} finally { await srv.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inspect-town, grant (needs --yes), events and replay-events leave the database untouched', async () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const file = path.join(dir, 'game.db');
|
||||||
|
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } });
|
||||||
|
let townId;
|
||||||
|
try {
|
||||||
|
const s = await api(srv, 'POST', '/auth/signup', { username: 'ada', password: 'analytical engine' });
|
||||||
|
townId = s.body.operators[0].towns ? s.body.operators[0].towns[0].id : (await api(srv, 'GET', '/me', null, s.body.token)).body.operators[0].towns[0].id;
|
||||||
|
const built = await api(srv, 'POST', '/towns/' + townId + '/build', { key: 'f1' }, s.body.token);
|
||||||
|
assert.equal(built.status, 201, JSON.stringify(built.body));
|
||||||
|
} finally { await srv.close(); }
|
||||||
|
|
||||||
|
const it = cli(file, ['inspect-town', String(townId), '--json']);
|
||||||
|
assert.equal(it.code, 0, it.err);
|
||||||
|
assert.equal(it.json.town.id, townId);
|
||||||
|
assert.ok(it.json.buildings.length >= 1);
|
||||||
|
assert.equal(it.json.queue.length, 1);
|
||||||
|
assert.ok(it.json.town.resources.fiber > 0);
|
||||||
|
assert.equal(cli(file, ['inspect-town', '99999']).code, 3);
|
||||||
|
assert.equal(cli(file, ['inspect-operator', 'ada', '--json']).json.operators[0].towns[0].id, townId);
|
||||||
|
|
||||||
|
// grant: refused without --yes, nothing changes
|
||||||
|
const before = it.json.town.resources.fiber;
|
||||||
|
assert.equal(cli(file, ['grant', String(townId), '--fiber', '500']).code, 2);
|
||||||
|
assert.equal(cli(file, ['inspect-town', String(townId), '--json']).json.town.resources.fiber, before);
|
||||||
|
const g = cli(file, ['grant', String(townId), '--fiber', '10', '--yes', '--json']);
|
||||||
|
assert.equal(g.code, 0, g.err);
|
||||||
|
assert.ok(g.json.after.fiber >= g.json.before.fiber + 9.9);
|
||||||
|
assert.equal(cli(file, ['grant', String(townId), '--yes']).code, 2);
|
||||||
|
|
||||||
|
// events
|
||||||
|
const ev = cli(file, ['events', '--pending', '--json']);
|
||||||
|
assert.equal(ev.json.events.length, 1);
|
||||||
|
assert.equal(ev.json.events[0].type, 'buildDone');
|
||||||
|
assert.equal(cli(file, ['events', '--type', 'nothing', '--json']).json.events.length, 0);
|
||||||
|
|
||||||
|
// replay: dry run and simulation never change the real queue
|
||||||
|
const dbSnapshot = () => { const db = openDb(file); const r = db.all('SELECT id, status, due_at FROM events ORDER BY id'); const n = db.get('SELECT COUNT(*) AS n FROM notifications').n; const b = db.all('SELECT * FROM buildings ORDER BY town_id, key'); db.close(); return JSON.stringify([r, n, b]); };
|
||||||
|
const snap = dbSnapshot();
|
||||||
|
const far = cli(file, ['replay-events', '--until', '+30d', '--simulate', '--json']);
|
||||||
|
assert.equal(far.code, 0, far.err);
|
||||||
|
assert.equal(far.json.dueCount, 1);
|
||||||
|
assert.equal(far.json.simulated.outcome[0].status, 'done');
|
||||||
|
assert.ok(far.json.simulated.notifications >= 1);
|
||||||
|
assert.equal(dbSnapshot(), snap, 'the real database is unchanged');
|
||||||
|
const near = cli(file, ['replay-events', '--json']);
|
||||||
|
assert.equal(near.json.dueCount, 0);
|
||||||
|
assert.ok(near.json.next && near.json.next.type === 'buildDone');
|
||||||
|
assert.equal(dbSnapshot(), snap);
|
||||||
|
assert.deepEqual(fs.readdirSync(os.tmpdir()).filter((n) => n.startsWith('upstream-replay-')).length, 0, 'scratch copy removed');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reset-world refuses without --yes-destroy, then wipes the world and keeps accounts', async () => {
|
||||||
|
const dir = tmp();
|
||||||
|
const file = path.join(dir, 'game.db');
|
||||||
|
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false, world: { mapRadius: 20 } });
|
||||||
|
try {
|
||||||
|
const s = await api(srv, 'POST', '/auth/signup', { username: 'grace', password: 'compiler compiler' });
|
||||||
|
assert.equal(s.status, 201);
|
||||||
|
} finally { await srv.close(); }
|
||||||
|
const counts = () => { const db = openDb(file); const r = { users: db.get('SELECT COUNT(*) AS n FROM users').n, tokens: db.get('SELECT COUNT(*) AS n FROM tokens').n, towns: db.get('SELECT COUNT(*) AS n FROM towns').n, operators: db.get('SELECT COUNT(*) AS n FROM operators').n, buildings: db.get('SELECT COUNT(*) AS n FROM buildings').n }; db.close(); return r; };
|
||||||
|
const before = counts();
|
||||||
|
assert.equal(before.towns, 1);
|
||||||
|
|
||||||
|
const refused = cli(file, ['reset-world', '1']);
|
||||||
|
assert.equal(refused.code, 2);
|
||||||
|
assert.match(refused.err, /--yes-destroy/);
|
||||||
|
assert.deepEqual(counts(), before, 'refusal changes nothing');
|
||||||
|
assert.equal(cli(file, ['reset-world', '1', '--yes']).code, 2, '--yes is not enough for reset-world');
|
||||||
|
|
||||||
|
const bk = path.join(dir, 'bk');
|
||||||
|
const done = cli(file, ['reset-world', '1', '--yes-destroy', '--backup', bk, '--new-seed', '--json']);
|
||||||
|
assert.equal(done.code, 0, done.err);
|
||||||
|
const after = counts();
|
||||||
|
assert.equal(after.towns, 0);
|
||||||
|
assert.equal(after.operators, 0);
|
||||||
|
assert.equal(after.buildings, 0);
|
||||||
|
assert.equal(after.users, 1, 'accounts are kept');
|
||||||
|
assert.equal(after.tokens, 1, 'tokens are kept');
|
||||||
|
assert.equal(admin.listBackups(bk).length, 1, 'a backup was taken first');
|
||||||
|
assert.equal(admin.verifySnapshot(path.join(bk, admin.listBackups(bk)[0].name)).towns, 1, 'the backup still has the town');
|
||||||
|
assert.equal(cli(file, ['reset-world', '77', '--yes-destroy']).code, 3);
|
||||||
|
|
||||||
|
// the world is playable again: the account can join it
|
||||||
|
const srv2 = await createServer({ port: 0, host: '127.0.0.1', dbPath: file, log: () => {}, autoArm: false });
|
||||||
|
try {
|
||||||
|
const login = await api(srv2, 'POST', '/auth/login', { username: 'grace', password: 'compiler compiler' });
|
||||||
|
assert.equal(login.status, 200);
|
||||||
|
assert.equal(login.body.operators.length, 0);
|
||||||
|
assert.equal(srv2.db.get('SELECT COUNT(*) AS n FROM worlds').n, 1);
|
||||||
|
} finally { await srv2.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('resetPlan finds tables of later stages by world_id and foreign keys', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
migrate(db);
|
||||||
|
db.exec('CREATE TABLE zz_movements (id INTEGER PRIMARY KEY, world_id INTEGER NOT NULL, town_id INTEGER); CREATE TABLE zz_units (town_id INTEGER, unit TEXT, count INTEGER); CREATE TABLE zz_global (id INTEGER PRIMARY KEY, note TEXT)');
|
||||||
|
const plan = admin.resetPlan(db, 1);
|
||||||
|
const names = plan.steps.map((s) => s.table);
|
||||||
|
for (const t of ['zz_movements', 'zz_units', 'towns', 'buildings', 'events', 'operators']) assert.ok(names.includes(t), t);
|
||||||
|
assert.ok(names.indexOf('buildings') < names.indexOf('towns'), 'children before parents');
|
||||||
|
assert.ok(names.indexOf('towns') < names.indexOf('operators'));
|
||||||
|
assert.ok(plan.skipped.includes('zz_global'));
|
||||||
|
for (const t of ['users', 'tokens', 'worlds', 'schema_migrations']) assert.ok(!names.includes(t), t);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
186
test/client-api.test.js
Normal file
186
test/client-api.test.js
Normal file
|
|
@ -0,0 +1,186 @@
|
||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const { createApi, ApiError } = require('../public/js/api.js');
|
||||||
|
|
||||||
|
// A scripted fetch: each call takes the next response (or throws when given an Error).
|
||||||
|
function harness(script, extra) {
|
||||||
|
const calls = [];
|
||||||
|
const sleeps = [];
|
||||||
|
let t = 1000;
|
||||||
|
const store = new Map();
|
||||||
|
const api = createApi(Object.assign({
|
||||||
|
fetch: async (url, init) => {
|
||||||
|
calls.push({ url, init });
|
||||||
|
const step = script.shift();
|
||||||
|
if (step instanceof Error) throw step;
|
||||||
|
t += step.rtt || 0;
|
||||||
|
return {
|
||||||
|
ok: step.status >= 200 && step.status < 300, status: step.status,
|
||||||
|
headers: { get: (k) => (step.headers || {})[k] || null },
|
||||||
|
json: async () => step.body,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
now: () => t, sleep: async (ms) => { sleeps.push(ms); t += ms; }, jitter: () => 0.5,
|
||||||
|
storage: { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => store.set(k, v), removeItem: (k) => store.delete(k) },
|
||||||
|
randomHex: (() => { let n = 0; return () => 'abcdef' + String(++n).padStart(6, '0'); })(),
|
||||||
|
}, extra));
|
||||||
|
return { api, calls, sleeps, store, tick: (ms) => { t += ms; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = (body, more) => Object.assign({ status: 200, body: Object.assign({ serverTime: 5000 }, body) }, more);
|
||||||
|
const err = (status, code, more) => Object.assign({ status, body: { serverTime: 5000, error: { code, message: code, details: {} } } }, more);
|
||||||
|
|
||||||
|
test('bearer token, JSON body and Idempotency-Key on authenticated POST', async () => {
|
||||||
|
const h = harness([ok({ a: 1 })]);
|
||||||
|
h.api.setToken('tok');
|
||||||
|
assert.strictEqual(h.store.get('upstream.token'), 'tok');
|
||||||
|
await h.api.post('/towns/1/build', { key: 'f1' });
|
||||||
|
const { url, init } = h.calls[0];
|
||||||
|
assert.strictEqual(url, 'api/v1/towns/1/build');
|
||||||
|
assert.strictEqual(init.headers.Authorization, 'Bearer tok');
|
||||||
|
assert.strictEqual(init.headers['Content-Type'], 'application/json');
|
||||||
|
assert.ok(h.api.isValidKey(init.headers['Idempotency-Key']));
|
||||||
|
assert.strictEqual(init.body, '{"key":"f1"}');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('login POST carries no token and no idempotency key; GET carries no key', async () => {
|
||||||
|
const h = harness([ok({}), ok({})]);
|
||||||
|
await h.api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false });
|
||||||
|
assert.strictEqual(h.calls[0].init.headers['Idempotency-Key'], undefined);
|
||||||
|
assert.strictEqual(h.calls[0].init.headers.Authorization, undefined);
|
||||||
|
h.api.setToken('t');
|
||||||
|
await h.api.get('/me');
|
||||||
|
assert.strictEqual(h.calls[1].init.headers['Idempotency-Key'], undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('query string is encoded and skips undefined values', async () => {
|
||||||
|
const h = harness([ok({})]);
|
||||||
|
await h.api.get('/map', { x: -3, y: 4, r: 20, worldId: undefined });
|
||||||
|
assert.strictEqual(h.calls[0].url, 'api/v1/map?x=-3&y=4&r=20');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('error envelope becomes ApiError with code, status and details', async () => {
|
||||||
|
const h = harness([{ status: 409, body: { serverTime: 1, error: { code: 'not_enough_resources', message: 'no', details: { key: 'f1' } } } }]);
|
||||||
|
h.api.setToken('t');
|
||||||
|
await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }), (e) => e instanceof ApiError && e.code === 'not_enough_resources' && e.status === 409 && e.details.key === 'f1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('401 clears the token and emits unauthorized', async () => {
|
||||||
|
const h = harness([err(401, 'unauthorized')]);
|
||||||
|
h.api.setToken('t');
|
||||||
|
let fired = 0;
|
||||||
|
h.api.on('unauthorized', () => fired++);
|
||||||
|
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'unauthorized');
|
||||||
|
assert.strictEqual(fired, 1);
|
||||||
|
assert.strictEqual(h.api.hasToken(), false);
|
||||||
|
assert.strictEqual(h.store.has('upstream.token'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('network errors on GET retry with growing backoff, then succeed', async () => {
|
||||||
|
const h = harness([new TypeError('fail'), new TypeError('fail'), ok({ fine: true })]);
|
||||||
|
const events = [];
|
||||||
|
h.api.on('offline', () => events.push('offline')); h.api.on('online', () => events.push('online'));
|
||||||
|
const r = await h.api.get('/me');
|
||||||
|
assert.strictEqual(r.fine, true);
|
||||||
|
assert.deepStrictEqual(h.sleeps, [400, 800]);
|
||||||
|
assert.deepStrictEqual(events, ['offline', 'online']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('network errors give up as network_error after the retry budget', async () => {
|
||||||
|
const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x')], { maxRetries: 2 });
|
||||||
|
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'network_error' && e.status === 0);
|
||||||
|
assert.strictEqual(h.calls.length, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unkeyed POST (login) is NOT retried on a network error', async () => {
|
||||||
|
const h = harness([new TypeError('x'), ok({})]);
|
||||||
|
await assert.rejects(() => h.api.post('/auth/signup', { username: 'a' }, { auth: false }), (e) => e.code === 'network_error');
|
||||||
|
assert.strictEqual(h.calls.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('429 honours Retry-After (seconds) and is retried even for unkeyed POSTs', async () => {
|
||||||
|
const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '3' } }), ok({ done: 1 })]);
|
||||||
|
const r = await h.api.post('/auth/login', {}, { auth: false });
|
||||||
|
assert.strictEqual(r.done, 1);
|
||||||
|
assert.deepStrictEqual(h.sleeps, [3000]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Retry-After beyond the cap is handed to the caller instead of blocking', async () => {
|
||||||
|
const h = harness([err(429, 'rate_limited', { headers: { 'Retry-After': '120' } })]);
|
||||||
|
await assert.rejects(() => h.api.get('/me'), (e) => e.code === 'rate_limited' && e.retryAfter === 120);
|
||||||
|
assert.deepStrictEqual(h.sleeps, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('retries of one call reuse its Idempotency-Key; the next call gets a new one', async () => {
|
||||||
|
const h = harness([new TypeError('x'), ok({}), ok({})]);
|
||||||
|
h.api.setToken('t');
|
||||||
|
await h.api.post('/towns/1/build', { key: 'f1' });
|
||||||
|
await h.api.post('/towns/1/build', { key: 'f1' });
|
||||||
|
const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']);
|
||||||
|
assert.strictEqual(keys[0], keys[1]);
|
||||||
|
assert.notStrictEqual(keys[1], keys[2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an intent keeps its key across failed attempts until the server answers', async () => {
|
||||||
|
const h = harness([new TypeError('x'), new TypeError('x'), new TypeError('x'), err(409, 'not_enough_resources'), ok({})], { maxRetries: 0 });
|
||||||
|
h.api.setToken('t');
|
||||||
|
for (let i = 0; i < 3; i++) await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'network_error');
|
||||||
|
assert.deepStrictEqual(h.api.pendingIntents(), ['build:1:f1']);
|
||||||
|
await assert.rejects(() => h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' }), (e) => e.code === 'not_enough_resources');
|
||||||
|
assert.deepStrictEqual(h.api.pendingIntents(), []); // definite answer: the intent is over
|
||||||
|
await h.api.post('/towns/1/build', { key: 'f1' }, { intent: 'build:1:f1' });
|
||||||
|
const keys = h.calls.map((c) => c.init.headers['Idempotency-Key']);
|
||||||
|
assert.strictEqual(new Set(keys.slice(0, 4)).size, 1);
|
||||||
|
assert.notStrictEqual(keys[4], keys[3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('request_in_progress is retried after a short delay', async () => {
|
||||||
|
const h = harness([err(409, 'request_in_progress'), ok({ x: 1 })]);
|
||||||
|
h.api.setToken('t');
|
||||||
|
const r = await h.api.post('/towns/1/build', { key: 'f1' });
|
||||||
|
assert.strictEqual(r.x, 1);
|
||||||
|
assert.strictEqual(h.sleeps.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('503 on GET is retried, on unkeyed POST is not', async () => {
|
||||||
|
const a = harness([err(503, 'internal_error'), ok({ y: 1 })]);
|
||||||
|
assert.strictEqual((await a.api.get('/me')).y, 1);
|
||||||
|
const b = harness([err(503, 'internal_error'), ok({})]);
|
||||||
|
await assert.rejects(() => b.api.post('/auth/login', {}, { auth: false }), (e) => e.status === 503);
|
||||||
|
assert.strictEqual(b.calls.length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('server clock offset comes from the lowest-latency sample; replayed responses are ignored', async () => {
|
||||||
|
// t0=1000, rtt 400, serverTime 5000 -> offset 5000 - 1200 = 3800
|
||||||
|
const h = harness([ok({}, { rtt: 400 }), ok({ serverTime: 99999 }, { rtt: 100 }), ok({ serverTime: 1 }, { rtt: 900 }), ok({ serverTime: 99999 }, { rtt: 1, headers: { 'Idempotent-Replay': 'true' } })]);
|
||||||
|
await h.api.get('/me');
|
||||||
|
assert.strictEqual(h.api.serverOffset(), 3800);
|
||||||
|
await h.api.get('/me'); // better rtt (100): adopted. t0 was 1400 -> mid 1450 -> offset 99999-1450
|
||||||
|
assert.strictEqual(h.api.serverOffset(), 99999 - 1450);
|
||||||
|
const before = h.api.serverOffset();
|
||||||
|
await h.api.get('/me'); // worse rtt: kept
|
||||||
|
assert.strictEqual(h.api.serverOffset(), before);
|
||||||
|
await h.api.get('/me'); // replay: ignored
|
||||||
|
assert.strictEqual(h.api.serverOffset(), before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('push events can be emitted and unsubscribed; a throwing listener does not break others', () => {
|
||||||
|
const h = harness([]);
|
||||||
|
const got = [];
|
||||||
|
const off = h.api.on('push', (m) => got.push(m));
|
||||||
|
h.api.on('push', () => { throw new Error('boom'); });
|
||||||
|
h.api.on('push', (m) => got.push('2:' + m.type));
|
||||||
|
h.api.emit('push', { type: 'town', id: 1 });
|
||||||
|
off();
|
||||||
|
h.api.emit('push', { type: 'x' });
|
||||||
|
assert.deepStrictEqual(got, [{ type: 'town', id: 1 }, '2:town', '2:x']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('storage failures fall back to memory', () => {
|
||||||
|
const api = createApi({ fetch: async () => { throw new Error('unused'); }, storage: { getItem() { throw new Error('denied'); }, setItem() { throw new Error('denied'); }, removeItem() { throw new Error('denied'); } } });
|
||||||
|
api.setToken('abc');
|
||||||
|
assert.strictEqual(api.getToken(), 'abc');
|
||||||
|
api.clearToken();
|
||||||
|
assert.strictEqual(api.getToken(), null);
|
||||||
|
});
|
||||||
71
test/client-i18n.test.js
Normal file
71
test/client-i18n.test.js
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const I = require('../public/js/i18n.js');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
|
||||||
|
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(',');
|
||||||
|
|
||||||
|
test('en and nb have identical key sets and placeholders', () => {
|
||||||
|
const en = Object.keys(I.strings.en).sort(), nb = Object.keys(I.strings.nb).sort();
|
||||||
|
assert.deepStrictEqual(nb.filter((k) => !en.includes(k)), [], 'keys only in nb');
|
||||||
|
assert.deepStrictEqual(en.filter((k) => !nb.includes(k)), [], 'keys only in en');
|
||||||
|
for (const k of en) assert.strictEqual(placeholders(I.strings.nb[k]), placeholders(I.strings.en[k]), 'placeholders differ for ' + k);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every building, resource and tile type has a player-facing name in both languages', () => {
|
||||||
|
for (const l of I.LANGS) {
|
||||||
|
for (const b of Object.keys(D.BUILDINGS)) {
|
||||||
|
assert.ok(I.strings[l]['building.' + b + '.name'], l + ' name for ' + b);
|
||||||
|
assert.ok(I.strings[l]['building.' + b + '.desc'], l + ' desc for ' + b);
|
||||||
|
}
|
||||||
|
for (const r of D.RESOURCES.concat(['power', 'battery'])) assert.ok(I.strings[l]['res.' + r], l + ' res.' + r);
|
||||||
|
for (const t of ['land', 'rural', 'incumbent', 'pop', 'void']) assert.ok(I.strings[l]['tile.' + t], l + ' tile.' + t);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every error code the client can meet is translated', () => {
|
||||||
|
// codes the current screens can see (auth, build, cancel, rename, map, notifications, tokens) + client-side ones
|
||||||
|
const codes = ['bad_request', 'validation_failed', 'unauthorized', 'invalid_credentials', 'forbidden', 'not_found', 'conflict', 'request_in_progress',
|
||||||
|
'idempotency_key_reuse', 'payload_too_large', 'rate_limited', 'internal_error', 'signup_closed', 'username_taken', 'world_full', 'unknown_building',
|
||||||
|
'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources', 'network_error', 'unknown', 'method_not_allowed'];
|
||||||
|
for (const l of I.LANGS) for (const c of codes) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('t() fills placeholders, falls back to en then to the key', () => {
|
||||||
|
assert.strictEqual(I.t('en', 'sheet.build', { n: 3 }), 'Build level 3');
|
||||||
|
assert.strictEqual(I.t('nb', 'sheet.build', { n: 3 }), 'Bygg nivå 3');
|
||||||
|
assert.strictEqual(I.t('xx', 'common.close'), 'Close');
|
||||||
|
assert.strictEqual(I.t('en', 'no.such.key'), 'no.such.key');
|
||||||
|
assert.strictEqual(I.t('en', 'sheet.build'), 'Build level {n}');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('duration and clock formatting', () => {
|
||||||
|
assert.strictEqual(I.fmtDuration('en', 0), '0s');
|
||||||
|
assert.strictEqual(I.fmtDuration('en', 45000), '45s');
|
||||||
|
assert.strictEqual(I.fmtDuration('en', 133000), '2m 13s');
|
||||||
|
assert.strictEqual(I.fmtDuration('en', 3600000), '1h');
|
||||||
|
assert.strictEqual(I.fmtDuration('en', 3600000 * 26 + 60000 * 5), '1d 2h');
|
||||||
|
assert.strictEqual(I.fmtDuration('nb', 3600000 * 2 + 60000 * 5), '2t 5m');
|
||||||
|
assert.strictEqual(I.fmtClock(1), '0:01');
|
||||||
|
assert.strictEqual(I.fmtClock(65000), '1:05');
|
||||||
|
assert.strictEqual(I.fmtClock(3661000), '1:01:01');
|
||||||
|
assert.strictEqual(I.fmtClock(-5), '0:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('number formatting', () => {
|
||||||
|
assert.strictEqual(I.fmtNum('en', 749.9), '749');
|
||||||
|
assert.strictEqual(I.fmtNum('en', 123456), '123k');
|
||||||
|
assert.strictEqual(I.fmtNum('en', 2500000), '2.5M');
|
||||||
|
assert.strictEqual(I.fmtDec('en', 12.34, true), '+12.3');
|
||||||
|
assert.strictEqual(I.fmtDec('en', -3, true), '−3.0');
|
||||||
|
assert.strictEqual(I.fmtDec('en', 420.4), '420');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('language detection', () => {
|
||||||
|
assert.strictEqual(I.detectLang('nb-NO'), 'nb');
|
||||||
|
assert.strictEqual(I.detectLang('nn'), 'nb');
|
||||||
|
assert.strictEqual(I.detectLang('no'), 'nb');
|
||||||
|
assert.strictEqual(I.detectLang('en-GB'), 'en');
|
||||||
|
assert.strictEqual(I.detectLang(undefined), 'en');
|
||||||
|
});
|
||||||
111
test/helpers.js
Normal file
111
test/helpers.js
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Shared test helpers (no tests in here). An in-memory server on port 0 with a fake clock and no background timer:
|
||||||
|
* events only run when a request, a command or the test calls scheduler.runDue().
|
||||||
|
*
|
||||||
|
* const { createTestServer } = require('./helpers');
|
||||||
|
* const t = await createTestServer();
|
||||||
|
* const alice = await t.signup('alice'); // { token, userId, operatorId, townId, name }
|
||||||
|
* const r = await t.api('/alliances', { method: 'POST', body: { name: 'X', tag: 'X1' } }, alice.token);
|
||||||
|
* t.clock.advance(3600e3); t.srv.scheduler.runDue();
|
||||||
|
* await t.close();
|
||||||
|
*/
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const { createServer } = require('../server');
|
||||||
|
const { FakeClock } = require('../server/clock');
|
||||||
|
|
||||||
|
// ---- optional response contract check: every 2xx JSON body must satisfy its route's declared `response` schema
|
||||||
|
// (server/routes/schemas.js), error bodies the Error schema. Opt-in: createTestServer({ contract: true }).
|
||||||
|
let contractRouter = null;
|
||||||
|
function contract() {
|
||||||
|
if (contractRouter) return contractRouter;
|
||||||
|
const { Router } = require('../server/http');
|
||||||
|
const routes = require('../server/routes');
|
||||||
|
const router = new Router();
|
||||||
|
routes.register(router, new Proxy({}, { get: () => new Proxy(function () {}, { get: () => () => null, apply: () => null }) }));
|
||||||
|
contractRouter = { router, schemas: require('../server/routes/schemas').schemas };
|
||||||
|
return contractRouter;
|
||||||
|
}
|
||||||
|
|
||||||
|
function conforms(schemas, schema, v, path, errs) {
|
||||||
|
if (schema.$ref) return conforms(schemas, schemas[schema.$ref], v, path, errs);
|
||||||
|
const types = Array.isArray(schema.type) ? schema.type : [schema.type];
|
||||||
|
if (v === null) { if (!types.includes('null')) errs.push(path + ' is null'); return; }
|
||||||
|
const t = types.find((x) => x !== 'null');
|
||||||
|
if (t === 'integer') { if (!Number.isInteger(v)) errs.push(path + ' not an integer: ' + JSON.stringify(v)); }
|
||||||
|
else if (t === 'number') { if (typeof v !== 'number') errs.push(path + ' not a number'); }
|
||||||
|
else if (t === 'string') { if (typeof v !== 'string') errs.push(path + ' not a string'); }
|
||||||
|
else if (t === 'boolean') { if (typeof v !== 'boolean') errs.push(path + ' not a boolean'); }
|
||||||
|
else if (t === 'array') {
|
||||||
|
if (!Array.isArray(v)) errs.push(path + ' not an array');
|
||||||
|
else if (schema.items) v.forEach((x, i) => conforms(schemas, schema.items, x, path + '[' + i + ']', errs));
|
||||||
|
} else if (t === 'object') {
|
||||||
|
if (typeof v !== 'object' || Array.isArray(v)) { errs.push(path + ' not an object'); return; }
|
||||||
|
for (const k of schema.required || []) if (!(k in v)) errs.push(path + '.' + k + ' missing');
|
||||||
|
for (const k of Object.keys(schema.properties || {})) if (k in v) conforms(schemas, schema.properties[k], v[k], path + '.' + k, errs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkContract(method, path, status, body) {
|
||||||
|
const { router, schemas } = contract();
|
||||||
|
const found = router.find(method, path.split('?')[0].replace(/^\/api\/v1/, ''));
|
||||||
|
if (!found || !found.route) return;
|
||||||
|
const errs = [];
|
||||||
|
conforms(schemas, status < 300 ? (found.route.meta.response || { $ref: 'Ok' }) : { $ref: 'Error' }, body, '', errs);
|
||||||
|
if (errs.length) throw new assert.AssertionError({ message: method + ' ' + path + ' -> ' + status + ' breaks its response schema: ' + errs.join('; ') + ' in ' + JSON.stringify(body).slice(0, 400) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createTestServer(o) {
|
||||||
|
o = o || {};
|
||||||
|
const clock = o.clock || new FakeClock();
|
||||||
|
const srv = await createServer(Object.assign({
|
||||||
|
port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {},
|
||||||
|
// many signups and calls from one IP: lift the per-IP/token/auth rate limits
|
||||||
|
ipRate: 1e6, ipBurst: 1e6, tokenRate: 1e6, tokenBurst: 1e6, authRate: 1e6, authBurst: 1e6,
|
||||||
|
}, o.server || {}));
|
||||||
|
const base = 'http://127.0.0.1:' + srv.port + '/api/v1';
|
||||||
|
|
||||||
|
// api(path, { method, body, headers }, token) -> { status, body, headers }
|
||||||
|
async function api(path, opts, token) {
|
||||||
|
opts = opts || {};
|
||||||
|
const headers = Object.assign({ 'content-type': 'application/json' }, opts.headers || {});
|
||||||
|
if (token) headers.authorization = 'Bearer ' + token;
|
||||||
|
const r = await fetch(base + path, { method: opts.method || 'GET', headers, body: opts.body === undefined ? undefined : JSON.stringify(opts.body) });
|
||||||
|
const out = { status: r.status, body: await r.json(), headers: r.headers };
|
||||||
|
if (o.contract) checkContract(opts.method || 'GET', path, out.status, out.body);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const names = new Map();
|
||||||
|
async function signup(name) {
|
||||||
|
const r = await api('/auth/signup', { method: 'POST', body: { username: name, password: 'correct horse battery' } });
|
||||||
|
assert.equal(r.status, 201, 'signup ' + name + ': ' + JSON.stringify(r.body));
|
||||||
|
const op = r.body.operators[0];
|
||||||
|
const u = { token: r.body.token, userId: r.body.user.id, operatorId: op.id, townId: op.towns[0].id, name };
|
||||||
|
names.set(name, u);
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set a building level directly (tests that need a Peering office without playing through the build chain).
|
||||||
|
function setBuilding(townId, type, level) {
|
||||||
|
srv.db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?) ON CONFLICT (town_id, key) DO UPDATE SET level = excluded.level', townId, type, type, level);
|
||||||
|
}
|
||||||
|
|
||||||
|
// signup + Peering office level (default 1), ready to found or join an alliance.
|
||||||
|
async function signupPeering(name, level) {
|
||||||
|
const u = await signup(name);
|
||||||
|
setBuilding(u.townId, 'peering_office', level === undefined ? 1 : level);
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bulk operators without the scrypt cost and without a usable token (drive them through srv.commands.run).
|
||||||
|
function quickSignup(name) {
|
||||||
|
const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: require('crypto').randomBytes(16).toString('hex'), device: 'test' });
|
||||||
|
return { userId: r.userId, operatorId: r.operatorId, townId: r.townId, name };
|
||||||
|
}
|
||||||
|
|
||||||
|
const close = () => srv.close();
|
||||||
|
return { srv, clock, api, signup, signupPeering, quickSignup, setBuilding, close, base };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createTestServer, checkContract };
|
||||||
121
test/military-api.test.js
Normal file
121
test/military-api.test.js
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const { createServer } = require('../server');
|
||||||
|
const { FakeClock } = require('../server/clock');
|
||||||
|
const T = require('./military-helpers');
|
||||||
|
const { D, H } = T;
|
||||||
|
|
||||||
|
// A real server on port 0 with a fake clock: signup two players over HTTP, then drive the military routes.
|
||||||
|
async function boot() {
|
||||||
|
const clock = new FakeClock();
|
||||||
|
const srv = await createServer({ port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false, log: () => {} });
|
||||||
|
const base = 'http://127.0.0.1:' + srv.port + '/api/v1';
|
||||||
|
const call = async (p, o, token) => {
|
||||||
|
o = o || {};
|
||||||
|
const headers = Object.assign({ 'content-type': 'application/json' }, o.headers || {});
|
||||||
|
if (token) headers.authorization = 'Bearer ' + token;
|
||||||
|
const r = await fetch(base + p, Object.assign({}, o, { headers, body: o.body && JSON.stringify(o.body) }));
|
||||||
|
return { status: r.status, body: await r.json() };
|
||||||
|
};
|
||||||
|
const signup = async (username) => {
|
||||||
|
const r = await call('/auth/signup', { method: 'POST', body: { username, password: 'correct horse battery' } });
|
||||||
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||||
|
const t = r.body.operators[0].towns[0];
|
||||||
|
return { token: r.body.token, townId: t.id, x: t.x, y: t.y, opId: r.body.operators[0].id, userId: r.body.user.id };
|
||||||
|
};
|
||||||
|
return { srv, clock, call, signup };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('API: train, send a raid, warning for the target, reports, recall, error codes', async () => {
|
||||||
|
const { srv, clock, call, signup } = await boot();
|
||||||
|
try {
|
||||||
|
const a = await signup('alice'), b = await signup('bobby');
|
||||||
|
const db = srv.db;
|
||||||
|
// both start protected (72 h): move the clock past it, give alice infrastructure to train
|
||||||
|
clock.advance(73 * H);
|
||||||
|
for (const [t, lv] of [['ops_lab', 3], ['research_lab', 3], ['noc', 2]]) db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, t, t, lv);
|
||||||
|
db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
|
||||||
|
|
||||||
|
let r = await call('/towns/' + a.townId + '/train', { method: 'POST', body: { unit: 'script_crew', count: 20 } }, a.token);
|
||||||
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||||
|
assert.equal(typeof r.body.serverTime, 'number');
|
||||||
|
r = await call('/towns/' + a.townId, {}, a.token);
|
||||||
|
assert.equal(r.body.town.military.training.length, 1);
|
||||||
|
assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'script_crew').locked, false);
|
||||||
|
assert.equal(r.body.town.military.trainable.find((u) => u.unit === 'botnet').locked, true);
|
||||||
|
clock.advance(3 * H);
|
||||||
|
r = await call('/towns/' + a.townId, {}, a.token);
|
||||||
|
assert.deepEqual(r.body.town.military.units.home, { script_crew: 20 });
|
||||||
|
|
||||||
|
// errors are enveloped with stable codes
|
||||||
|
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 99 } } }, a.token);
|
||||||
|
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'not_enough_units');
|
||||||
|
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 } } }, b.token);
|
||||||
|
assert.equal(r.status, 404, 'cannot send from somebody else\'s POP');
|
||||||
|
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 5 }, extra: 1 } }, a.token);
|
||||||
|
assert.equal(r.status, 422);
|
||||||
|
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'teleport', toTownId: b.townId, units: {} } }, a.token);
|
||||||
|
assert.equal(r.status, 422);
|
||||||
|
|
||||||
|
// alice is protected no more (73 h passed) and bob neither: the raid goes out
|
||||||
|
r = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token);
|
||||||
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||||
|
const mid = r.body.movementId;
|
||||||
|
const replay = await call('/movements', { method: 'POST', headers: { 'idempotency-key': 'raid-key-0001' }, body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } } }, a.token);
|
||||||
|
assert.equal(replay.body.movementId, mid, 'idempotent replay: no second movement');
|
||||||
|
assert.equal(db.get('SELECT COUNT(*) AS n FROM movements').n, 1);
|
||||||
|
|
||||||
|
r = await call('/movements', {}, b.token);
|
||||||
|
assert.equal(r.body.incoming.length, 1); assert.equal(r.body.incoming[0].type, 'unknown');
|
||||||
|
r = await call('/movements', {}, a.token);
|
||||||
|
assert.equal(r.body.outgoing[0].type, 'raid');
|
||||||
|
|
||||||
|
// recall inside 90 s, then send again and let it land
|
||||||
|
r = await call('/movements/' + mid + '/recall', { method: 'POST' }, a.token);
|
||||||
|
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||||
|
clock.advance(H);
|
||||||
|
r = await call('/movements', { method: 'POST', body: { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 } } }, a.token);
|
||||||
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||||
|
clock.advance(100 * 1000);
|
||||||
|
r = await call('/movements/' + r.body.movementId + '/recall', { method: 'POST' }, a.token);
|
||||||
|
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'recall_expired');
|
||||||
|
clock.advance(5 * H);
|
||||||
|
|
||||||
|
r = await call('/reports', {}, a.token);
|
||||||
|
assert.equal(r.status, 200); assert.equal(r.body.items.length, 1); assert.equal(r.body.unread, 1);
|
||||||
|
const id = r.body.items[0].id;
|
||||||
|
const rb = await call('/reports', {}, b.token);
|
||||||
|
assert.equal(rb.body.items[0].id, id, 'defender sees the same report');
|
||||||
|
r = await call('/reports/' + id, {}, a.token);
|
||||||
|
assert.equal(r.body.report.type, 'raid'); assert.equal(r.body.report.data.outcome, 'attacker_won');
|
||||||
|
r = await call('/reports/' + id + '/read', { method: 'POST' }, a.token);
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
r = await call('/reports?unread=true', {}, a.token);
|
||||||
|
assert.equal(r.body.items.length, 0);
|
||||||
|
r = await call('/reports/999999', {}, a.token);
|
||||||
|
assert.equal(r.status, 404);
|
||||||
|
|
||||||
|
// tile info and research over the API
|
||||||
|
r = await call('/map/tile?x=' + b.x + '&y=' + b.y, {}, a.token);
|
||||||
|
assert.equal(r.body.type, 'pop'); assert.equal(r.body.town.owner.name, 'bobby');
|
||||||
|
r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token);
|
||||||
|
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||||
|
r = await call('/towns/' + a.townId + '/research', { method: 'POST', body: { unit: 'script_crew', stat: 'attack' } }, a.token);
|
||||||
|
assert.equal(r.status, 409); assert.equal(r.body.error.code, 'queue_full');
|
||||||
|
r = await call('/notifications', {}, b.token);
|
||||||
|
assert.ok(r.body.items.some((n) => n.type === 'incoming'));
|
||||||
|
assert.ok(r.body.items.some((n) => n.type === 'report'));
|
||||||
|
} finally { await srv.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('API: openapi describes every military route', () => {
|
||||||
|
const { build } = require('../tools/gen-openapi');
|
||||||
|
const spec = build();
|
||||||
|
for (const [p, m] of [['/towns/{id}/train', 'post'], ['/towns/{id}/research', 'post'], ['/movements', 'post'], ['/movements', 'get'], ['/movements/{id}/recall', 'post'],
|
||||||
|
['/towns/{id}/withdraw', 'post'], ['/reports', 'get'], ['/reports/{id}', 'get'], ['/reports/{id}/read', 'post'], ['/reports/read-all', 'post'], ['/map/tile', 'get']]) {
|
||||||
|
assert.ok(spec.paths[p] && spec.paths[p][m], m + ' ' + p + ' is in openapi.json');
|
||||||
|
}
|
||||||
|
for (const c of ['not_enough_units', 'units_offline', 'target_protected', 'protection_active', 'footprint_too_low', 'cannot_takeover', 'recall_expired']) assert.ok(spec['x-error-codes'][c], c);
|
||||||
|
assert.ok(D.UNIT_ORDER.length === 10);
|
||||||
|
});
|
||||||
203
test/military-expansion.test.js
Normal file
203
test/military-expansion.test.js
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const T = require('./military-helpers');
|
||||||
|
const { R, D, H } = T;
|
||||||
|
const { loadTown } = require('../server/state');
|
||||||
|
|
||||||
|
function sendTakeover(h, att, targetTownId, units) {
|
||||||
|
return h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: targetTownId, units: units || { script_crew: 80, ma_team: 2 } });
|
||||||
|
}
|
||||||
|
|
||||||
|
test('takeover: loyalty drops by the seeded roll, the POP changes owner at zero, pending work stops', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 80, ma_team: 2 } });
|
||||||
|
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
|
||||||
|
const extra = T.addTown(h, def, { x: 12, y: 2, infra: { noc: 2 } });
|
||||||
|
h.db.run('UPDATE towns SET loyalty = 40, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
|
||||||
|
h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, 4)', extra.townId, 'soc_analyst');
|
||||||
|
h.run('train', { userId: def.userId, townId: extra.townId, unit: 'soc_analyst', count: 5 }); // pending work that must be cancelled
|
||||||
|
|
||||||
|
let s = sendTakeover(h, att, extra.townId);
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
let rep = T.reportsOf(h, att.userId)[0].data;
|
||||||
|
assert.equal(rep.outcome, 'attacker_won');
|
||||||
|
assert.equal(rep.takeover.attempted, true);
|
||||||
|
assert.ok(rep.takeover.drop >= 15 && rep.takeover.drop <= 30, 'drop in range');
|
||||||
|
assert.equal(rep.takeover.captured, false, '40 loyalty needs two hits');
|
||||||
|
assert.ok(Math.abs(T.town(h, extra.townId).loyalty - (rep.takeover.loyaltyBefore - rep.takeover.drop)) < 0.01);
|
||||||
|
assert.equal(T.town(h, extra.townId).owner_id, def.opId);
|
||||||
|
const retMv = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
|
||||||
|
assert.equal(JSON.parse(retMv.units).ma_team, 1, 'one M&A team was used up, the other comes home');
|
||||||
|
|
||||||
|
// second hit
|
||||||
|
h.advanceTo(retMv.arrive_at);
|
||||||
|
h.db.run('UPDATE towns SET loyalty = 10, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
|
||||||
|
s = sendTakeover(h, att, extra.townId, { script_crew: 70, ma_team: 1 });
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
rep = T.reportsOf(h, att.userId)[1].data;
|
||||||
|
assert.equal(rep.takeover.captured, true);
|
||||||
|
const taken = T.town(h, extra.townId);
|
||||||
|
assert.equal(taken.owner_id, att.opId);
|
||||||
|
assert.equal(taken.is_capital, 0);
|
||||||
|
assert.equal(taken.loyalty, D.EXPANSION.conqueredLoyalty);
|
||||||
|
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending'", extra.townId).n, 0, 'old owner training cancelled');
|
||||||
|
assert.deepEqual(T.units(h, extra.townId), {}, 'the defenders died with the loss');
|
||||||
|
assert.equal(T.notes(h, def.userId, 'town_lost').length, 1);
|
||||||
|
assert.equal(T.notes(h, att.userId, 'town_gained').length, 1);
|
||||||
|
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', def.opId).n, 1);
|
||||||
|
// loyalty then regenerates for the new owner (+1/h)
|
||||||
|
const t = loadTown(h.db, extra.townId);
|
||||||
|
assert.equal(R.loyaltyAt(t.loyalty, t.loyaltyAt, t.loyaltyAt + 10 * H, 1), D.EXPANSION.conqueredLoyalty + 10);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('takeover protections: capital is only drained, last POP and low footprint are refused', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 160, ma_team: 4 } });
|
||||||
|
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
|
||||||
|
const second = T.addTown(h, def, { x: 12, y: 2 });
|
||||||
|
const lone = T.addOperator(h, 'lone', { x: 20, y: 0 });
|
||||||
|
// last POP: refused at send
|
||||||
|
assert.throws(() => sendTakeover(h, att, lone.townId), (e) => e.code === 'cannot_takeover');
|
||||||
|
// capital: loyalty is dragged to zero, the owner stays
|
||||||
|
h.db.run('UPDATE towns SET loyalty = 5, loyalty_at = ? WHERE id = ?', h.clock.now(), def.townId);
|
||||||
|
const s = sendTakeover(h, att, def.townId, { script_crew: 80, ma_team: 2 });
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const rep = T.reportsOf(h, att.userId)[0].data;
|
||||||
|
assert.equal(rep.takeover.capital, true);
|
||||||
|
assert.equal(rep.takeover.captured, false);
|
||||||
|
assert.equal(T.town(h, def.townId).loyalty, 0);
|
||||||
|
assert.equal(T.town(h, def.townId).owner_id, def.opId);
|
||||||
|
// footprint gate
|
||||||
|
const poor = T.addOperator(h, 'poor', { x: 30, y: 0, footprint: 10, units: { script_crew: 80, ma_team: 1 } });
|
||||||
|
assert.throws(() => sendTakeover(h, poor, second.townId, { script_crew: 80, ma_team: 1 }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(1));
|
||||||
|
// a takeover needs an M&A team, which only goes on takeovers
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: second.townId, units: { script_crew: 5 } }), (e) => e.code === 'validation_failed');
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: second.townId, units: { script_crew: 5, ma_team: 1 } }), (e) => e.code === 'validation_failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exploit kits damage the chosen building on a win; DDoS rigs lower the firewall in the battle', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'siege', { x: 5, y: 0, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 } });
|
||||||
|
const def = T.addOperator(h, 'wall', { x: 9, y: 0, units: { soc_analyst: 40 }, infra: { firewall: 10, noc: 7 } });
|
||||||
|
const s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 }, target: 'noc' });
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const rep = T.reportsOf(h, att.userId)[0].data;
|
||||||
|
assert.equal(rep.outcome, 'attacker_won');
|
||||||
|
assert.equal(rep.power.effectiveFirewall, 8, '20 rigs lower a level-10 firewall by 2');
|
||||||
|
assert.equal(rep.siege.key, 'noc');
|
||||||
|
const kits = rep.attacker.units.survivors.exploit_kit;
|
||||||
|
assert.equal(rep.siege.to, 7 - R.siegeLevels(kits));
|
||||||
|
assert.equal(h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', def.townId, 'noc').level, rep.siege.to);
|
||||||
|
// the lost units are gone for good
|
||||||
|
assert.deepEqual(T.units(h, def.townId), {});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('protection: protected targets cannot be attacked, attacking ends your own protection, arrival re-checks', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const now = h.clock.now();
|
||||||
|
const newbie = T.addOperator(h, 'newbie', { x: 5, y: 0, protectedUntil: now + 72 * H, units: { script_crew: 20, port_scanner: 3 } });
|
||||||
|
const vet = T.addOperator(h, 'vet', { x: 9, y: 0, units: { script_crew: 40, port_scanner: 3 } });
|
||||||
|
// nobody may attack a protected operator ...
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'raid', toTownId: newbie.townId, units: { script_crew: 10 } }), (e) => e.code === 'target_protected');
|
||||||
|
// ... but scouting is allowed
|
||||||
|
h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'scan', toTownId: newbie.townId, units: { port_scanner: 3 } });
|
||||||
|
// a protected operator must confirm to attack, which ends the protection at once
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 } }), (e) => e.code === 'protection_active');
|
||||||
|
assert.ok(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p > now, 'the refused send changed nothing');
|
||||||
|
const r = h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 }, confirmEndProtection: true });
|
||||||
|
assert.equal(r.protectionEnded, true);
|
||||||
|
assert.equal(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p, now);
|
||||||
|
// protection that lasts past the arrival blocks the attack at arrival time (units turn around, report to the sender)
|
||||||
|
const h2 = T.setup();
|
||||||
|
const a2 = T.addOperator(h2, 'a', { x: 5, y: 0, units: { script_crew: 30 } });
|
||||||
|
const d2 = T.addOperator(h2, 'd', { x: 9, y: 0, units: { soc_analyst: 2 } });
|
||||||
|
const s2 = h2.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'raid', toTownId: d2.townId, units: { script_crew: 30 } });
|
||||||
|
h2.db.run('UPDATE operators SET protection_until = ? WHERE id = ?', s2.arriveAt + H, d2.opId); // e.g. an admin grants protection
|
||||||
|
h2.advanceTo(s2.arriveAt);
|
||||||
|
const rep = T.reportsOf(h2, a2.userId)[0];
|
||||||
|
assert.equal(rep.type, 'movement_failed');
|
||||||
|
assert.equal(rep.data.reason, 'protected');
|
||||||
|
assert.equal(T.reportsOf(h2, d2.userId).length, 0, 'the protected side is not bothered');
|
||||||
|
assert.deepEqual(T.units(h2, d2.townId), { soc_analyst: 2 });
|
||||||
|
h2.advance(10 * H);
|
||||||
|
assert.equal(T.units(h2, a2.townId).script_crew, 30, 'the units came back untouched');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('expansion: three Rollout crews found a POP; wild slots, empty start, range, footprint, occupied tile', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const a = T.addOperator(h, 'founder', { x: 5, y: 0, footprint: 3000, units: { rollout_crew: 9 } });
|
||||||
|
const spot = T.landNear(h, 12, 3);
|
||||||
|
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 }, wild: ['substation', 'sales_office'] });
|
||||||
|
assert.equal(T.units(h, a.townId).rollout_crew, 6);
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const t = h.db.get('SELECT * FROM towns WHERE x = ? AND y = ?', spot.x, spot.y);
|
||||||
|
assert.ok(t, 'a new POP exists');
|
||||||
|
assert.equal(t.owner_id, a.opId); assert.equal(t.is_capital, 0);
|
||||||
|
const b = h.db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', t.id);
|
||||||
|
assert.ok(b.every((x) => x.level === 0), 'everything at level 0');
|
||||||
|
assert.equal(b.length, D.FIELD_SLOTS, 'fields only, no infrastructure');
|
||||||
|
assert.equal(b.find((x) => x.key === 'f17').type, 'substation');
|
||||||
|
assert.equal(b.find((x) => x.key === 'f18').type, 'sales_office');
|
||||||
|
assert.equal(t.fiber, D.EXPANSION.startResources.fiber);
|
||||||
|
assert.equal(T.reportsOf(h, a.userId)[0].type, 'settle');
|
||||||
|
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'the crews were consumed');
|
||||||
|
|
||||||
|
// the second extra POP needs more footprint (500 * 2^1.8 = 1741 for the 2nd extra; the operator has 3000 + ...)
|
||||||
|
h.db.run('UPDATE towns SET footprint = 700 WHERE id = ?', a.townId);
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x + 2, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(2));
|
||||||
|
// too far from every own POP
|
||||||
|
const far = T.landNear(h, 30, 0);
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: far.x, y: far.y, units: { rollout_crew: 3 } }), (e) => e.code === 'out_of_range');
|
||||||
|
// not exactly three crews
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y + 3, units: { rollout_crew: 2 } }), (e) => e.code === 'validation_failed');
|
||||||
|
// an occupied tile
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'invalid_target');
|
||||||
|
|
||||||
|
// somebody else takes the tile while the crews are on the way: the crews come home with a report
|
||||||
|
h.db.run('UPDATE towns SET footprint = 99999 WHERE id = ?', a.townId);
|
||||||
|
const free = T.landNear(h, 10, -4);
|
||||||
|
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: free.x, y: free.y, units: { rollout_crew: 3 } });
|
||||||
|
const squatter = T.addOperator(h, 'squatter', { x: free.x, y: free.y }); // lands exactly on `free`
|
||||||
|
assert.equal(squatter.x, free.x);
|
||||||
|
h.advanceTo(s2.arriveAt);
|
||||||
|
const failed = T.reportsOf(h, a.userId).filter((r) => r.type === 'movement_failed');
|
||||||
|
assert.equal(failed.length, 1);
|
||||||
|
assert.equal(failed[0].data.reason, 'invalid_target');
|
||||||
|
h.advance(48 * H);
|
||||||
|
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'crews returned');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('incumbent site: static defence, one-time Hardware bonus per operator, research speed bonus', () => {
|
||||||
|
const h = T.setup({ seed: 99 });
|
||||||
|
let site = null;
|
||||||
|
for (let x = -20; x <= 20 && !site; x++) for (let y = -20; y <= 20 && !site; y++) if (R.tileAt(h.world.seed, 50, x, y).type === 'incumbent' && Math.abs(x) + Math.abs(y) > 6) site = { x, y };
|
||||||
|
assert.ok(site, 'the test world has an incumbent site');
|
||||||
|
const need = R.incumbentDefence(h.world.seed, site.x, site.y, 0);
|
||||||
|
const crews = Math.ceil(need / 40 * 1.6);
|
||||||
|
const a = T.addOperator(h, 'raider', { x: site.x - 3, y: site.y, res: 3000, units: { script_crew: crews } });
|
||||||
|
const hwBefore = T.town(h, a.townId).hardware;
|
||||||
|
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } });
|
||||||
|
assert.equal(s.toTownId, null);
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const rep = T.reportsOf(h, a.userId)[0];
|
||||||
|
assert.equal(rep.type, 'incumbent');
|
||||||
|
assert.equal(rep.data.outcome, 'attacker_won');
|
||||||
|
assert.equal(rep.data.bonus.hardware, D.INCUMBENT.hardwareBonus);
|
||||||
|
assert.ok(rep.data.bonus.researchSpeedBonus > 0);
|
||||||
|
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', a.opId).n, 1);
|
||||||
|
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
|
||||||
|
h.advanceTo(ret.arrive_at);
|
||||||
|
assert.ok(T.town(h, a.townId).hardware > hwBefore + 1000, 'the bonus arrived with the survivors');
|
||||||
|
// a second take gives no second bonus
|
||||||
|
const back = JSON.parse(ret.units);
|
||||||
|
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: back });
|
||||||
|
h.advanceTo(s2.arriveAt);
|
||||||
|
assert.equal(T.reportsOf(h, a.userId)[1].data.bonus, null);
|
||||||
|
// research gets faster
|
||||||
|
const plain = R.researchTimeMs('script_crew', 1, 8, 1, 0), fast = R.researchTimeMs('script_crew', 1, 8, 1, R.researchSpeedBonus(1));
|
||||||
|
assert.ok(fast < plain);
|
||||||
|
// incumbent sites accept only scans and attacks, and defence scales with world age
|
||||||
|
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', x: site.x, y: site.y, units: { script_crew: 1 } }), (e) => e.code === 'invalid_target' || e.code === 'not_enough_units');
|
||||||
|
assert.ok(R.incumbentDefence(h.world.seed, site.x, site.y, 50) > need);
|
||||||
|
});
|
||||||
148
test/military-flow.test.js
Normal file
148
test/military-flow.test.js
Normal file
|
|
@ -0,0 +1,148 @@
|
||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const T = require('./military-helpers');
|
||||||
|
const { R, D, H } = T;
|
||||||
|
|
||||||
|
test('training: batches of one building run in order, other buildings in parallel, requirements and queue limit', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const a = T.addOperator(h, 'alice');
|
||||||
|
const t0 = h.clock.now();
|
||||||
|
const r1 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 10 });
|
||||||
|
const r2 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'port_scanner', count: 4 }); // same building (noc): after r1
|
||||||
|
const r3 = h.run('train', { userId: a.userId, townId: a.townId, unit: 'script_crew', count: 5 }); // ops_lab: in parallel
|
||||||
|
assert.equal(r1.startAt, t0);
|
||||||
|
assert.equal(r2.startAt, r1.dueAt, 'second noc batch starts when the first is done');
|
||||||
|
assert.equal(r3.startAt, t0, 'other buildings train in parallel');
|
||||||
|
assert.equal(r1.dueAt - r1.startAt, R.trainTimeMs('soc_analyst', 10, 5, 1));
|
||||||
|
assert.deepEqual(T.units(h, a.townId), {});
|
||||||
|
h.advanceTo(r3.dueAt);
|
||||||
|
assert.deepEqual(T.units(h, a.townId), { script_crew: 5 }, 'only the parallel batch is done so far');
|
||||||
|
h.advanceTo(r1.dueAt);
|
||||||
|
assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10 });
|
||||||
|
h.advanceTo(r2.dueAt);
|
||||||
|
assert.deepEqual(T.units(h, a.townId), { script_crew: 5, soc_analyst: 10, port_scanner: 4 });
|
||||||
|
assert.equal(T.notes(h, a.userId, 'train_done').length, 3);
|
||||||
|
|
||||||
|
// unit power draw is part of the town's rates once the units exist
|
||||||
|
const t = require('../server/state').loadTown(h.db, a.townId);
|
||||||
|
assert.equal(t.unitDraw, 10 * 1 + 4 * 1 + 5 * 1);
|
||||||
|
|
||||||
|
// costs were paid; requirements are enforced; the queue is limited
|
||||||
|
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'exploit_kit', count: 1 }), (e) => e.code === 'requirements_not_met');
|
||||||
|
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'nonsense', count: 1 }), (e) => e.code === 'unknown_unit');
|
||||||
|
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 100000 }), (e) => e.code === 'validation_failed');
|
||||||
|
const b = T.addOperator(h, 'bob', { res: 100 });
|
||||||
|
assert.throws(() => h.run('train', { userId: b.userId, townId: b.townId, unit: 'botnet', count: 50 }), (e) => e.code === 'not_enough_resources' || e.code === 'requirements_not_met');
|
||||||
|
for (let i = 0; i < D.MILITARY.maxTrainQueue; i++) h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 });
|
||||||
|
assert.throws(() => h.run('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 }), (e) => e.code === 'queue_full');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raid end to end: send, incoming warning, arrive, loot, reports for both sides, return', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 40 } });
|
||||||
|
const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 20 }, infra: { rack_hall: 2 } });
|
||||||
|
h.db.run('UPDATE towns SET fiber = 600, hardware = 600, capital = 600 WHERE id = ?', def.townId);
|
||||||
|
const before = T.town(h, def.townId);
|
||||||
|
|
||||||
|
const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } });
|
||||||
|
assert.equal(T.units(h, att.townId).script_crew, undefined, 'units left home');
|
||||||
|
assert.equal(sent.arriveAt - sent.departAt, R.latencyMs(4, 8, 1));
|
||||||
|
|
||||||
|
// the target sees origin and ETA but not the type
|
||||||
|
const mv = h.mq.movements(def.userId, {});
|
||||||
|
assert.equal(mv.incoming.length, 1);
|
||||||
|
assert.equal(mv.incoming[0].type, 'unknown');
|
||||||
|
assert.equal(mv.incoming[0].units, undefined);
|
||||||
|
assert.equal(mv.incoming[0].arriveAt, sent.arriveAt);
|
||||||
|
assert.equal(h.mq.movements(att.userId, {}).outgoing[0].type, 'raid');
|
||||||
|
assert.equal(T.notes(h, def.userId, 'incoming').length, 1);
|
||||||
|
assert.equal(T.notes(h, def.userId, 'incoming')[0].type, undefined);
|
||||||
|
|
||||||
|
h.advanceTo(sent.arriveAt);
|
||||||
|
const ra = T.reportsOf(h, att.userId), rd = T.reportsOf(h, def.userId);
|
||||||
|
assert.equal(ra.length, 1); assert.equal(rd.length, 1);
|
||||||
|
assert.equal(ra[0].id, rd[0].id, 'one report shared by both sides');
|
||||||
|
assert.equal(ra[0].role, 'attacker'); assert.equal(rd[0].role, 'defender');
|
||||||
|
const rep = ra[0].data;
|
||||||
|
assert.equal(rep.outcome, 'attacker_won');
|
||||||
|
assert.ok(rep.loot.fiber > 0 && rep.loot.fiber === rep.loot.hardware, 'loot is split evenly');
|
||||||
|
// 10% per rack hall level hides stock from a raid: level 2 hides 20%
|
||||||
|
assert.equal(rep.cacheHidden, 0.2);
|
||||||
|
const d1 = T.town(h, def.townId);
|
||||||
|
assert.ok(d1.fiber < before.fiber, 'target lost fiber');
|
||||||
|
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
|
||||||
|
assert.ok(ret, 'a return movement carries the loot');
|
||||||
|
assert.deepEqual(JSON.parse(ret.cargo), rep.loot);
|
||||||
|
const attBefore = T.town(h, att.townId).fiber;
|
||||||
|
|
||||||
|
h.advanceTo(ret.arrive_at);
|
||||||
|
assert.equal(T.units(h, att.townId).script_crew, 40 - (rep.attacker.units.lost.script_crew || 0));
|
||||||
|
assert.ok(T.town(h, att.townId).fiber > attBefore, 'loot arrived home');
|
||||||
|
assert.equal(T.notes(h, att.userId, 'movement_returned').length, 1);
|
||||||
|
const stats = h.db.get('SELECT * FROM operator_stats WHERE operator_id = ?', att.opId);
|
||||||
|
assert.ok(stats.attack_points > 0, 'killed units give battle points');
|
||||||
|
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed raid loses units and loots nothing; both sides still get the report', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'weak', { x: 5, y: 0, units: { script_crew: 2 } });
|
||||||
|
const def = T.addOperator(h, 'strong', { x: 8, y: 0, units: { blue_team: 20 }, infra: { firewall: 10 } });
|
||||||
|
const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 2 } });
|
||||||
|
h.advanceTo(sent.arriveAt);
|
||||||
|
const rep = T.reportsOf(h, att.userId)[0].data;
|
||||||
|
assert.equal(rep.outcome, 'defender_won');
|
||||||
|
assert.deepEqual(rep.loot, { fiber: 0, hardware: 0, capital: 0 });
|
||||||
|
assert.equal(T.units(h, def.townId).blue_team, 20 - (rep.defender.groups[0].lost.blue_team || 0));
|
||||||
|
assert.equal(T.reportsOf(h, def.userId).length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scan: success shows units, resources, buildings at 2:1; failed scan loses scanners and reveals the scanner', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const att = T.addOperator(h, 'spy', { x: 5, y: 0, units: { port_scanner: 10 } });
|
||||||
|
const def = T.addOperator(h, 'watched', { x: 8, y: 0, units: { port_scanner: 3, soc_analyst: 4 } });
|
||||||
|
let s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 10 } });
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const ok = T.reportsOf(h, att.userId).find((r) => r.type === 'scan').data;
|
||||||
|
assert.equal(ok.success, true);
|
||||||
|
assert.equal(ok.detail, 'full'); // 10 >= 2 * 3
|
||||||
|
assert.deepEqual(ok.intel.units.home, { port_scanner: 3, soc_analyst: 4 });
|
||||||
|
assert.ok(ok.intel.buildings.length > 0 && ok.intel.resources.fiber > 0);
|
||||||
|
const det = T.reportsOf(h, def.userId).find((r) => r.type === 'scan_detected').data;
|
||||||
|
assert.equal(det.identityRevealed, false, 'the defender only learns who scanned when their scanners win');
|
||||||
|
assert.equal(det.by, null);
|
||||||
|
|
||||||
|
// now a scan that fails: 2 scanners against 3
|
||||||
|
h.advance(3 * H);
|
||||||
|
h.db.run("UPDATE town_units SET count = 2 WHERE town_id = ? AND unit = 'port_scanner'", att.townId); // 10 came home (minus losses); keep 2 for the test
|
||||||
|
s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'scan', toTownId: def.townId, units: { port_scanner: 2 } });
|
||||||
|
h.advanceTo(s.arriveAt);
|
||||||
|
const bad = T.reportsOf(h, att.userId).filter((r) => r.type === 'scan')[1].data;
|
||||||
|
assert.equal(bad.success, false);
|
||||||
|
assert.deepEqual(bad.scanners.survivors, {});
|
||||||
|
const det2 = T.reportsOf(h, def.userId).filter((r) => r.type === 'scan_detected')[1].data;
|
||||||
|
assert.equal(det2.identityRevealed, true);
|
||||||
|
assert.equal(det2.by.operator.name, 'spy');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('event order: combat resolves in (arrive time, id) order and the whole run is deterministic', () => {
|
||||||
|
function run() {
|
||||||
|
const h = T.setup({ seed: 777 });
|
||||||
|
const slow = T.addOperator(h, 'slow', { x: 40, y: 0, units: { script_crew: 60 } });
|
||||||
|
const fast = T.addOperator(h, 'fast', { x: 20, y: 0, units: { botnet: 25 } });
|
||||||
|
const def = T.addOperator(h, 'victim', { x: 8, y: 0, units: { soc_analyst: 30 } });
|
||||||
|
h.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', def.townId);
|
||||||
|
const a = h.run('sendMovement', { userId: slow.userId, fromTownId: slow.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 60 } });
|
||||||
|
const b = h.run('sendMovement', { userId: fast.userId, fromTownId: fast.townId, type: 'raid', toTownId: def.townId, units: { botnet: 25 } });
|
||||||
|
assert.ok(a.movementId < b.movementId);
|
||||||
|
h.advance(200 * H);
|
||||||
|
return { h, a, b, slow, fast, def };
|
||||||
|
}
|
||||||
|
const x = run(), y = run();
|
||||||
|
assert.ok(x.b.arriveAt < x.a.arriveAt, 'the botnet raid is faster although it was sent second');
|
||||||
|
const reps = x.h.db.all("SELECT id, type, created_at FROM reports WHERE type IN ('raid','attack') ORDER BY id");
|
||||||
|
assert.deepEqual(reps.map((r) => r.type), ['raid', 'attack'], 'reports are created in arrival order');
|
||||||
|
assert.ok(T.snapshot(x.h) === T.snapshot(y.h), 'same inputs, same world seed: identical state');
|
||||||
|
assert.equal(x.h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue