Phase 2: client military/social screens, WebSocket push, trade + endgame, review findings pending
Built: units/movements/reports/send/expansion screens, alliance/messages/rankings screens, ws client + server /ws push (docs/PROTOCOL.md), Internet exchange trade, backbone endgame + world end, shared reports, buildDone relative levels. Tested: npm test 175/175. Two adversarial reviews found issues (trade-leg recall exploit, __proto__ via validate.js, rankings DoS, static headers, ...): fixes follow in the next commit. NOT done: bots/balance, e2e suite, real-device checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
249818a7aa
commit
b18645dca1
87 changed files with 10201 additions and 71 deletions
53
docs/API.md
53
docs/API.md
|
|
@ -118,3 +118,56 @@ firewall, loot, siege, takeover/loyalty), `scan` (attacker; intel when it succee
|
|||
if the defender's scanners won), `incumbent`, `settle`, `reinforce`, `movement_failed`.
|
||||
|
||||
Later stages append their routes here and to the route table.
|
||||
|
||||
## Trade, end game, shared reports (stage 5 rest, stage 7 start)
|
||||
|
||||
**Internet exchange trade.** Offers "give X of A for Y of B within Z tiles". Amounts are whole numbers, each side 1..500 (one transport
|
||||
link), the two amounts differ by at most 1:2, the resources differ; `maxDistance` 1..300. Lists are newest first, `after` = id of the last
|
||||
offer you have (older ones follow). `status`: `open`, `accepted`, `completed`, `cancelled`, `expired`, `void`.
|
||||
|
||||
| Route | Purpose |
|
||||
| ----- | ------- |
|
||||
| `POST /trade/offers {townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance}` | post (201). The offered amount leaves the POP (escrow) and one transport link is held in reserve. `trade_ratio`, `capacity_exceeded`, `no_transport_link` (no exchange, or all links busy/reserved), `not_enough_resources` |
|
||||
| `GET /trade/offers?worldId&townId&give&want&after&limit` | open offers of others that one of your POPs (or `townId`) can take: within `min(maxDistance, 10 x exchange level)`. Each carries `acceptableFrom: [{townId, distance}]`; `exchangeLevels` lists your exchanges and their reach |
|
||||
| `GET /trade/offers/mine?worldId&status&after&limit` | offers you posted or accepted, any status, with `role` |
|
||||
| `GET /trade/offers/:id` | one offer: open ones to every operator of the world, closed ones to the two parties (`not_found` otherwise) |
|
||||
| `DELETE /trade/offers/:id` | cancel your open offer; the escrow returns to the POP (`offer_closed` when it is not open) |
|
||||
| `POST /trade/offers/:id/accept {townId}` | take it with one of your POPs (201): two transports leave at once (your payment, their goods); `own_offer`, `offer_closed`, `trade_out_of_range`, `no_transport_link`, `not_enough_resources`; all or nothing |
|
||||
|
||||
Notifications: `trade_accepted` (poster), `trade_completed` (both, when both transports arrived), `trade_expired`, `trade_void` (the POP
|
||||
was taken over). Delivery notifications are the existing `transport_arrived` / `transport_delivered`. Direct transports (own POPs, any
|
||||
player) stay `POST /movements` with `type: "transport"`.
|
||||
|
||||
**World status and the end game.** The backbone sites open at world day 100 (real days x speed).
|
||||
|
||||
| Route | Purpose |
|
||||
| ----- | ------- |
|
||||
| `GET /worlds/:id/status` | `phase` (`running`, `backbone_open`, `ended`), `ageDays`, `opensAt`, the 7 `sites` (empty before opening: `id` (null until first touched), `index`, `x`, `y`, `holder` `{allianceId, tag, name}` or null = incumbent, `takenBy`, `level`/`maxLevel`/`progress`, `pool` (stockpile), `build` `{toLevel, startedAt, dueAt}`, `next` `{toLevel, cost, durationMs}`), `winner`, `endsAt` (set once somebody won), `endedAt` |
|
||||
| `GET /worlds/:id/results` | the final snapshot once ended (`available: false` before): `winner`, `results.{operators, alliances, attackers, defenders, sites, totals}` (top 100 each, ranked) |
|
||||
| `GET /backbone/:id` | one site; holders also get `contributions` (who shipped what) and `you` `{holder, canBuild, canShip, canAttack}` |
|
||||
| `POST /backbone/:id/ship {fromTownId, cargo}` | send resources to a site your alliance holds (201, a transport: same links and capacity); arrives into the stockpile, or rides home if the site changed hands |
|
||||
| `POST /backbone/:id/build` | start the next node level (201), paid from the stockpile at once, one level at a time, any holder with `backboneBuild`; `max_level`, `already_queued`, `not_enough_resources`, `forbidden` (not a holder), `backbone_closed` |
|
||||
|
||||
Taking a site is `POST /movements` with `type: "scan"` or `"attack"` and the site's `x, y` (no `toTownId`): needs an alliance, not against
|
||||
the own alliance or a NAP/confederation partner (`invalid_target`, `details.reason`: `no_alliance`, `own_site`, `pact`,
|
||||
`landing_scan_or_attack_only`); before opening `backbone_closed`. Settling a landing tile is `invalid_target` (`backbone_site`), also before
|
||||
it opens. Defence is static: `incumbentDefence x 12 x (1 + 0.03 x node level)`; a scan report shows it. Reports: scans as `scan` (with
|
||||
`site.type: "backbone"`), attacks as the new type `landing` (outcome, attack/defence, `taken`; recipients: the attacker and every member of the
|
||||
previous holder). `GET /map` lists open sites in `specials` as `type: "backbone"` with `site: {id, index, holder, level, maxLevel}`;
|
||||
`GET /map/tile` returns `type: "backbone"` and `backbone: {siteId, holder, level, pool, build, mine, canAttack}`.
|
||||
|
||||
Notifications: `backbone_open` (first touch), `backbone_taken` / `backbone_lost` (alliance members), `backbone_level` (every 10th level and the
|
||||
last, holder members), `backbone_delivered` / `backbone_ship_bounced` (sender), `backbone_won` (everybody), `world_ended` (everybody).
|
||||
|
||||
**An ended world** answers every game command with `409 world_ended` (build, send, train, trade, alliances, diplomacy, backbone, report
|
||||
sharing, ...). Still allowed: `GET` everything (map, reports, rankings, towns, status, results), `POST /reports/read-all`, `POST
|
||||
/reports/:id/read`, messages (send, read, delete, block).
|
||||
|
||||
**Shared report folder.** `POST /reports/:id/share` puts one of YOUR reports into your alliance's folder (needs `shareReport`; the report
|
||||
is kept 14 days from the share), `DELETE /reports/:id/share` takes it out (the sharer, or `unshareReport`: leader, officer), `GET
|
||||
/alliances/:id/reports?after&limit` lists the folder newest first (cursor: id of the last report seen), `GET /alliances/:id/reports/:reportId`
|
||||
reads one with its full data. Members with `viewSharedReports` only; `GET /alliances/mine` permissions list the new keys.
|
||||
|
||||
**Allied incoming.** `GET /movements` has a new `alliedIncoming` list: movements heading for POPs of your alliance mates and of
|
||||
confederated alliances, same shape as `incoming` (type `unknown`, origin and ETA only) plus `ally: true` and `toOperator`. Friendly traffic
|
||||
(from partners of the target) is left out.
|
||||
|
|
|
|||
|
|
@ -128,3 +128,85 @@ nothing is spent. New POPs start with every field at level 0, no infrastructure,
|
|||
## 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.
|
||||
|
||||
## S6-1 — Push hints leave only after the commit, through an outbox
|
||||
`scheduler.notify` runs inside the transaction of the event or command, so pushing there would announce changes that may still roll
|
||||
back. `notify` queues into `scheduler.outbox` (only when a listener is set); `process()` and `commands.run` flush it after COMMIT
|
||||
(`db.depth === 0`) and truncate it to their mark on rollback. `town` hints use the existing `scheduler.onEvent` (post-commit already)
|
||||
and a new `commands.hooks.onCommand`. `push.js` itself knows no game rules (it gets `townOwner` / `tokenValid` injected), the routing
|
||||
lives in `pushHooks.js`. No new dependency (`ws` was already listed).
|
||||
|
||||
## S6-2 — Revocation is polled, not pushed
|
||||
Tokens are revoked by plain SQL in routes and the admin tool. Instead of hooking each place, the ping tick (30 s) re-checks
|
||||
`tokens.revoked_at` and `users.banned` for every authenticated socket and closes with 4401. Worst case 30 s of hints after logout on
|
||||
another device; hints carry no data, so nothing leaks. If that is ever not good enough, call a `push.disconnectToken(id)` from the routes.
|
||||
|
||||
## S6-3 — Hints are merged per tick, `town` is not sent to the target at launch
|
||||
Identical JSON hints produced in one tick (a catch-up) are deduplicated per socket via `setImmediate`. A launched movement tells the
|
||||
target's owner `incoming` (town + ETA) and no plain `town` hint, so the type and origin of a launch cannot be inferred from extra traffic.
|
||||
|
||||
|
||||
## E1 — A landing site is a row of its own, not a POP
|
||||
`landing_sites(world_id, idx, x, y, holder_alliance_id, holder_operator_id, level, stockpile, build_*)` (migration 004), positions from
|
||||
`rules.backboneSites(seed, radius)`. A town row of kind `landing` owned by the leader was considered and rejected: a "POP" that nobody plays
|
||||
would have to be excluded from footprint rankings, the last-POP / capital / footprint-gate counts, `homeTownFor`, `/me`, spawn spacing and
|
||||
the Rack hall cap (shipped resources would be thrown away at 250), and a leader change would have to re-own it. The holder is the
|
||||
alliance (`holder_alliance_id`, FK `ON DELETE SET NULL`, the disband hook also clears it), `holder_operator_id` only records who took it.
|
||||
Consequence, on purpose and to be revisited after the first world: **no units can stand at a site**, so there is no garrison and no
|
||||
reinforcement. A site is defended by the static value `incumbentDefence x 12 x (1 + 0.03 x level)` only, i.e. exactly the "incumbent
|
||||
with a backbone multiplier" of DESIGN.md; holders defend by growing the node (higher level = harder to take), attackers can scan the exact
|
||||
number. Hooks into the military code are small: `combat.arriveSite` hands `backbone` tiles to `military/landing.js`,
|
||||
`arrivals.arriveTransport` hands shipments (`extra.siteId`) to `endgame.deliverShipment`, `sendMovement` calls `endgame.checkLandingTarget`.
|
||||
|
||||
## E2 — Site rows are created lazily, there is no timer event
|
||||
`ensureSites` creates the 7 rows when something first touches a site (an attack/scan sent or arriving, a shipment, a build) once the world is
|
||||
at day 100 / speed; that first call also writes a `backbone_open` notification for every operator. Reads (`/worlds/:id/status`, `/map`, tile
|
||||
info) never write: untouched sites are shown as the incumbent's, level 0, `id: null`. A `backboneOpen` event at world creation was
|
||||
dropped: a pending event 100 days ahead sits in every quiet world and breaks tooling that counts pending events (the admin CLI test).
|
||||
Cost: nobody is pushed the moment the sites appear unless a first touch happens; clients see `phase: backbone_open` when they poll status.
|
||||
|
||||
## E3 — The winner is fixed at level 100; the world is frozen when it ends
|
||||
The holder of a node whose level completes at 100 wins (`worlds.winner_*`, once per world) and `worldEnd` is scheduled
|
||||
`graceDays x 24 h / speed` later. Losing the node meanwhile does not change the winner (the race is over; the grace days are for the ranking
|
||||
and the post-game). If a level-100 node is taken while nobody holds it (the holder disbanded mid-build) the new holder wins. `worldEnd`
|
||||
writes the ranking snapshot, sets `status = 'ended'`, closes open trade offers (`expired`, escrow back in its POP: every unit stays accounted
|
||||
for) and CANCELS every other pending event of the world: nothing arrives, trains,
|
||||
expires or builds after the snapshot, so the stored ranking stays the truth. Movements still `out` and queued builds stay as they were.
|
||||
A running build of a site continues for whoever holds the site when it lands (the level belongs to the site; the cost was paid from the
|
||||
stockpile at the start); the stockpile and the ledger stay with the site when it is taken.
|
||||
|
||||
## E4 — `world_ended` is one gate in `commands.run`, found by probing the arguments
|
||||
`ownedTown`, `operatorOf` and `requireRole` are shared with reads (rankings, map), so gating there would break "readable after the end".
|
||||
`commands.run` calls `endgame.guard(db, name, args)`: the world is `args.worldId`, else the world of `townId/fromTownId/hostTownId`,
|
||||
`allianceId`, `movementId`, `inviteId`, `proposalId`, `offerId`, `siteId`, `reportId`, else the caller's oldest operator (the default every
|
||||
command already uses). Allowed after the end: `markReportRead`, `messageSend/Read/Delete`, `messageBlock/Unblock`. New commands are gated
|
||||
automatically as long as they carry one of those arguments.
|
||||
|
||||
## E5 — Backbone cost curve is not the building curve
|
||||
`4000 x 1.28^99` is unreachable; the node has its own `ENDGAME.costGrowth = 1.045` and `timeGrowth = 1.025` (about 7.2 M of each resource and
|
||||
about 36 world days of building in total, level 100 alone 312 k each and 23 h). Pure guesses until a bot run (stage 7) says how much an
|
||||
alliance can ship; nothing here is balanced.
|
||||
|
||||
## T1 — Trade: escrow, one link per side, reach by exchange level
|
||||
- Offers are escrowed in `trade_offers` and hold one transport link of the poster's POP while open (`movements.activeLinks` counts open
|
||||
offers), so accepting never fails for lack of a link on the poster's side and cannot exceed the exchange level.
|
||||
- Each side of an offer must fit ONE transport (<= 500); larger deals are several offers. The ratio band is count-based 1:2.
|
||||
- Escrow returns without the Rack hall cap (conservation beats the cap here); deliveries keep the existing cap rule (`cargoLost`).
|
||||
- Reach: `10 tiles x exchange level` of the taker's POP, and the offer's own `maxDistance`; the poster's level only matters for the number of
|
||||
offers they can hold open.
|
||||
- A POP changing hands voids its open offers (`combat.transferTown` calls `trade.onTownTransferred`); the escrow stays in the POP.
|
||||
- `transportArrived` hook: `server/trade.js` registers itself when required (both `commands/index.js` and `events/index.js` load it), so the
|
||||
consumer exists in every test fixture that builds commands or events.
|
||||
- Offer expiry: one `tradeExpire` event per offer, cancelled on accept/cancel/void, idempotent (acts only while `open`).
|
||||
|
||||
## T2 — Shared reports extend the report's life
|
||||
Sharing sets `expires_at = max(expires_at, now + 14 days)` on the single shared `reports` row, so the folder is not emptied by a report that
|
||||
was nearly due; the cascade `report_shares.report_id ... ON DELETE CASCADE` removes the share when the report is cleaned up.
|
||||
|
||||
## G1 — `buildDone` adds one level to what the building is NOW
|
||||
Each build event adds exactly one level to the current level (never lowers, never above the queued `toLevel`), so an upgrade in flight
|
||||
cannot undo exploit-kit damage; a building knocked to 0 comes back at 1. The notification reports the real level.
|
||||
|
||||
## G2 — Allied incoming is a separate list
|
||||
`GET /movements` keeps `incoming` as "heading for YOUR POPs" and adds `alliedIncoming` for partners' POPs (own alliance + confederations),
|
||||
each entry with `ally: true` and `toOperator`. Mixing them would make clients count allies' attacks as their own.
|
||||
|
|
|
|||
|
|
@ -148,6 +148,12 @@ A new POP starts at level 0 everything and 1 h of resources. Takeover requires t
|
|||
- Diplomacy states between alliances: war, neutral, non-aggression pact, confederation (can reinforce each other,
|
||||
see each other's incoming). Pacts take 24 h to cancel.
|
||||
- Messages: player-to-player and alliance broadcast, plain text, 2000 chars, basic rate limit.
|
||||
- **Shared report folder (server):** a member puts one of their own reports (any type) into the alliance's folder (`shareReport`); every
|
||||
member reads it (`viewSharedReports`), the sharer or leader/officer (`unshareReport`) takes it out. Sharing pushes the report's expiry
|
||||
out to 14 days from the share (it is one row for everybody) and it goes with the report or the alliance.
|
||||
- **Seeing each other's incoming (server):** members of one alliance and of confederated alliances get `alliedIncoming` in `GET /movements`:
|
||||
movements heading for a partner's POP, origin and ETA only (type, units and cargo hidden), except traffic from operators who are partners
|
||||
of the target themselves (friendly).
|
||||
|
||||
## Trade
|
||||
|
||||
|
|
@ -155,6 +161,22 @@ The Internet exchange lists offers "give X of A for Y of B, max distance Z". Rat
|
|||
pump-feeding. Accepting an offer spawns two transport movements. Direct transports to own POPs or to any player
|
||||
(e.g. alliance support) use the same links. Transport links: level of the exchange, capacity 500 each.
|
||||
|
||||
**Clarified (what the server does).**
|
||||
- An offer is "give `giveAmount` of `giveRes` for `wantAmount` of `wantRes`, within `maxDistance` tiles", posted from one POP that has
|
||||
an Internet exchange. Each side must fit ONE transport link (1..500) and the two amounts differ by at most 1:2:
|
||||
`give <= 2 x want` and `want <= 2 x give` (count-based, the resources are not weighted). The resources must differ.
|
||||
- The offered amount is **escrowed**: it leaves the POP when the offer is posted. Cancelling or expiry (48 h / world speed) credits it back
|
||||
to the POP without the Rack hall cap (an amount above the cap is kept, it only stops growing), so nothing is created or lost.
|
||||
- **Reach:** a POP sees and takes offers of other operators within `min(offer.maxDistance, 10 x Internet exchange level)` tiles. The poster
|
||||
cannot take their own offer.
|
||||
- **Links:** an open offer holds one transport link of the poster's POP in reserve (open offers + running transports + returning carriers
|
||||
<= links); accepting converts the reservation into the real transport. Direct transports see the reservation as a busy link.
|
||||
- **Accepting** (one transaction): the acceptor's payment leaves their POP as a transport to the poster's POP (needs a free link and the
|
||||
resources there), the escrow leaves the poster's POP as a transport to the acceptor's POP; both arrive after `distance / 12 tiles/h /
|
||||
world speed`. The offer is `accepted`, then `completed` when both have been delivered. A delivery above the receiver's Rack hall cap
|
||||
loses the overflow and says so (the existing transport rule). If the poster's POP is taken over while the offer is open, the offer
|
||||
ends (`void`) and the escrow stays in the POP.
|
||||
|
||||
## Incumbent (NPC)
|
||||
|
||||
The legacy telco. Holds incumbent sites spread over the map with large static defences that scale with world age.
|
||||
|
|
@ -169,6 +191,33 @@ far more than anything else and requiring resources shipped in from members (tra
|
|||
wins and the world ends two days later with a final ranking. Backbone nodes can be attacked and taken; the level
|
||||
stays with the site. Landing sites cannot be settled, only taken.
|
||||
|
||||
**Clarified (what the server does).** World age is in world days (real days x speed). All numbers below are first guesses, no bot run.
|
||||
- **Sites:** `rules.backboneSites(seed, radius)`: 7 fixed positions, one per sector of the circle (jittered), on plain land between 35% and
|
||||
80% of the map radius, at least 6 tiles apart, never in the free centre. They exist from the start (spawning and settling refuse them),
|
||||
the tile reads `backbone` from day 100 / speed (`rules.tileAt(seed, radius, x, y, ageDays)`; without the age argument terrain is unchanged).
|
||||
- **A site is not a POP** (DECISIONS E1): it has a holder alliance, a Backbone node level, a stockpile of Fiber/Hardware/Capital and at most
|
||||
one level in progress. No units can stand there, so a site is defended by a static value only:
|
||||
`defence = incumbentDefence(seed, x, y, age) x 12 x (1 + 0.03 x node level)`. At day 100 that is about 40 000 with no node, 160 000 at
|
||||
level 100 (a Script crew attacks with 40).
|
||||
- **Taking:** `scan` and `attack` only (no raid: the stockpile would be lootable; no takeover, no reinforce, no settle). The attacker must be in
|
||||
an alliance, and may not be in the holder's alliance or in a NAP / confederation with it (checked when sent and again on arrival, units come
|
||||
home otherwise). A full attack with attack > defence wins: the attacker's alliance holds the site. No loot, the site loses nothing, the
|
||||
survivors drive home. Level, stockpile and a running build stay with the site. A holder that disbands leaves the site to the incumbent
|
||||
(level kept).
|
||||
- **Feeding the node:** members of the holder alliance send resources by transport (`POST /backbone/:id/ship`, same links, 500 per link, 12
|
||||
tiles/h). On arrival they join the stockpile if the sender's alliance still holds the site, otherwise they ride home. A ledger records
|
||||
who sent what.
|
||||
- **Building:** level L (1..100) costs `4000 x 1.045^(L-1)` of each resource (level 100: 312 301; about 7.2 million of each in total) and
|
||||
takes `2 h x 1.025^(L-1) / world speed` (level 100: 23 h; about 36 days of world time in total, one level at a time). The cost is paid from
|
||||
the stockpile when the level starts; any holder with `backboneBuild` may start it.
|
||||
- **Winning:** when a level completes and the node is at level 100, the holder at that moment wins (once per world) and the world ends two world
|
||||
days later (`worlds.end_at`). The winner is final: losing the node during those two days does not change it. If a finished node is taken while
|
||||
nobody held it, the new holder wins.
|
||||
- **Ending:** the `worldEnd` event stores a ranking snapshot (operators by footprint, alliances by the sum, top attackers and defenders by
|
||||
battle points, winner, the sites), sets the status `ended`, and cancels everything still pending in that world. An ended world refuses
|
||||
every game command with `world_ended`; reading (map, reports, rankings, town views, status, results) and chatting (messages, marking reports
|
||||
read) keep working.
|
||||
|
||||
Rankings throughout: operators by footprint, alliances by sum, attackers/defenders by points from battles.
|
||||
|
||||
## Fairness and anti-frustration
|
||||
|
|
|
|||
138
docs/NEXT.md
138
docs/NEXT.md
|
|
@ -17,11 +17,10 @@ Tests: `test/social-*.test.js` (pure rules, alliances, diplomacy with the fake c
|
|||
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).
|
||||
- Marketplace / Internet exchange: DONE on the server, see "Trade, end game, gaps" below.
|
||||
- Shared report folder and "see each other's incoming": DONE on the server (below). The pact effect "no attacks inside a NAP/confederation"
|
||||
is enforced by the military stage (`pactBlocks`).
|
||||
- No web client; WebSocket push (stage 6) now exists server-side, see "Stage 6" below.
|
||||
- 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.
|
||||
|
|
@ -43,11 +42,9 @@ recall, research, reports/cursor/retention, API smoke over HTTP). Fake clock, in
|
|||
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).
|
||||
- Training cannot be cancelled; no sitter, no night protection. (Report sharing and allied incoming: done, see below.)
|
||||
- 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.
|
||||
- Backbone landing sites and the Backbone node: see "Trade, end game, gaps" below.
|
||||
|
||||
## Client (stages 1-2 web client)
|
||||
Built: `public/` vanilla JS, no build step, strict-CSP friendly (no inline scripts or handlers, no external requests).
|
||||
|
|
@ -66,5 +63,128 @@ Built: `public/` vanilla JS, no build step, strict-CSP friendly (no inline scrip
|
|||
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.
|
||||
|
||||
## Client: social (alliance, messages, rankings)
|
||||
Built (all in the nav "More" group, `navGroup: 'more'`): `screens/alliance.js` (found with Peering office gate and translated server
|
||||
errors; received invites accept/decline; overview with size, pinned notes add/remove, leave/disband; members with role, POPs,
|
||||
footprint, last online, a member sheet for message / role / transfer / kick; invite by name, pending invites with cancel; diplomacy
|
||||
with relations, proposals in/out, "new move" via directory search with only the moves `rules.diplomacyMove` allows, pact-cancel
|
||||
and proposal countdowns, take-back), `screens/messages.js` (inbox with unread filter / mark all read, sent, alliance feed with
|
||||
broadcast composer, per-operator thread with older-page cursor, compose by name, 2000 char counter, delete own copy, block list and
|
||||
block/unblock, 429 shown as a countdown with the text kept, unread count on the nav via `App.setBadge`, polled every 60 s),
|
||||
`screens/rankings.js` (operators, alliances, battles attack/defense/total, your row highlighted plus the server's `you` card, rank-offset
|
||||
"load more"). Shared bits: `screens/social-ui.js` (`window.SocUI`: composer, confirm sheet, alliance profile sheet, error mapping),
|
||||
`js/social.js` (pure logic: what to show per role via `rules.allianceCan/outranks`, diplomacy options, counters, cursor merges),
|
||||
`js/strings/social.js` (en + nb), new sprite icons users / mail / trophy / back, `.soc-` CSS. All player text goes in with
|
||||
`textContent` (a test fails on any `innerHTML` in these files).
|
||||
Tests: `test/client-social.test.js` (pure logic, string coverage of every static key the screens use, error codes, no HTML sinks).
|
||||
Looked at with headless Chromium (phone portrait/landscape, desktop) against the real server in-process, plus a scripted flow on
|
||||
a phone profile (markup in a message stays text, counter/over-limit, 429 countdown, unknown recipient, leader vs member views, diplomacy
|
||||
move sheet, name-taken error, nb). Not run: real devices, Safari, Playwright suite, a long-list scroll test (>100 ranks), accepting an
|
||||
invite when the alliance is full, alliances at the size cap.
|
||||
Gaps: alliance rename/description and note editing have no UI (server has edit-note); no operator profile page; blocking needs an existing
|
||||
conversation or message (the API takes an operator id and there is no name lookup); no live refresh (push is not wired, screens refetch
|
||||
on open and on manual refresh); the alliance screen does not auto-refresh countdowns' targets after they pass; `App.state.operator.alliance`
|
||||
is refreshed from `/me` after alliance changes but is stale if you are kicked while away until the screen is opened.
|
||||
|
||||
## Client: military, expansion, WebSocket
|
||||
Built (`public/`, same rules as before: no innerHTML for player text, no inline handlers):
|
||||
- **Nav overflow** (`main.js`): 5 slots; `registerScreen({ navGroup: 'main' | 'more' })`, with any `more` screen the 5th slot is a
|
||||
"More" sheet; `App.setBadge(screenId, n, 'alert'|'info')` (More sums its screens, red if any is an alert). Bar now: POP, Map, Units,
|
||||
Moves, More (Reports, Alerts, Settings, the social screens). `App.alertKinds[type]` lets a screen describe its own notification types in
|
||||
the Alerts feed; `App.popSections` lets screens add cards to the POP screen (incoming banner, expansion card).
|
||||
- **Shared state** (`milstate.js`): `App.mil.moves` (last `GET /movements`: outgoing, incoming, alliedIncoming) is the one source for the
|
||||
nav badge, POP banner, movements screen and map lines; `App.refreshMovements/refreshReportsUnread/refreshTowns` (the last refetches `/me`
|
||||
without the destructive `setSession`, used after a settle/takeover); `[data-cd]` countdown elements driven by one ticker; refetch when
|
||||
anything on the wire is overdue.
|
||||
- **Units** (`screens/units.js`): home units with research-adjusted stats, reinforcements here (send home) and your units elsewhere (call
|
||||
back), training queue with countdowns + train sheet (`rules.trainPlan` preview, max-affordable, queue-full), research list + sheet
|
||||
(`rules.researchPlan`, lab level / cost / time / reason), offline warning with the decommission countdown.
|
||||
- **Movements** (`screens/movements.js`): incoming list on top in red (origin + ETA only, as the API gives it), your outgoing legs with
|
||||
progress and a Recall button for the first 90 s, allied incoming; the POP screen gets a pulsing banner, the nav button a red badge.
|
||||
- **Send dialog** (`screens/send.js`, `App.openSend({x,y,fromTownId,type})`, from the map tile sheet, Units, Movements): `GET /map/tile`,
|
||||
types filtered by `milcore.moveOptions` (greyed ones say why), unit pickers (slider + stepper + all), cargo for transport, settle with
|
||||
the wild-slot choice, latency/ETA/carry preview from `rules.movementMs`, `confirmEndProtection` checkbox, exploit-kit target, an
|
||||
idempotency intent per opened dialog, server errors shown inline (`invalid_target` reasons translated).
|
||||
- **Reports** (`screens/reports.js`, in More): cursor-paginated list, unread highlight + badge, mark read on open, mark all read, detail
|
||||
layouts for raid/attack/takeover (role-aware victory/defeat, units sent/lost/left per group, strength, loot, siege, takeover loyalty),
|
||||
scan (+ incumbent intel), scan_detected, incumbent, settle (opens the new POP), reinforce, movement_failed; coordinates jump to the map.
|
||||
- **Expansion** (`screens/expand.js`, `send.js`, `main.js`, `render.js`): POP switcher in the resource bar, expansion card on the POP screen
|
||||
(crews at home, footprint gate, POP list), settle through the send dialog; map draws your/incoming/allied movement lines with markers,
|
||||
a red ring on your POPs that something is heading for, and a Send button in the tile sheet.
|
||||
- **WebSocket** (`ws.js`): `createSocketClient` (injectable WebSocket and timers) + browser wiring. Auth as first message, ping every 25 s with
|
||||
an 8 s pong timeout, jittered backoff 1 s .. 60 s, PROTOCOL close codes (4401/4400/1009 stop, 4429 waits 30 s), refetch after every
|
||||
re-`ready`. Pushes go to `api.emit('push')` and refetch the affected thing; slow REST poll (45 s with the socket down, 3 min with it up).
|
||||
- Tests: `test/client-mil.test.js` (type filter, unit roles, previews, perspective, backoff), `test/client-ws.test.js` (auth, ping/pong, backoff,
|
||||
close codes, no token, throwing constructor); `client-i18n` parity covers `strings/military.js`.
|
||||
- Looked at: headless Chromium (phone portrait/landscape, desktop; en and nb on the phone) against the real server in-process with a real
|
||||
clock, seeded units/movements/reports, plus scripted flows on a phone profile: real WebSocket `open`, an `incoming` push from another
|
||||
operator adding a row and a toast without polling, recall, raid/attack/transport/settle sends through the dialog (protection checkbox
|
||||
gates the button, exploit-kit target reaches the server), train, withdraw, offline warning, report details of every type, POP list after
|
||||
a settle resolved (`refreshTowns`).
|
||||
Not done / not claimed:
|
||||
- Not run: real devices or Safari, throttled networks, a socket behind nginx Proxy Manager, long sessions, the Playwright suite. The settle and
|
||||
takeover resolution was exercised by fast-forwarding movement times in the DB, not by waiting.
|
||||
- Takeover and capture flows (town_lost/town_gained pushes, losing the current POP) and the confederation `alliedIncoming` view have no
|
||||
browser run. The Hostile takeover button stays enabled on a capital / last POP (the client cannot know); the server's refusal is shown.
|
||||
- Withdraw and "call back" are one-tap with no confirmation. No unit icons (role icons only), no battle simulator / odds preview, no
|
||||
cancel of training (the server has none), no sound or system notifications, no reports search/filter.
|
||||
- The exploit-kit target picker only offers infrastructure types (the server also takes field slots f1..f18). Report group labels for
|
||||
reinforcements show `#<townId>` because the report carries no names.
|
||||
- Close 4401 stops the socket but does not itself send the player to login: that happens on the next REST 401 (`api` `unauthorized`).
|
||||
- `ready.serverTime` is not used for the clock offset (no round-trip estimate on the socket); REST responses keep doing that.
|
||||
|
||||
## Stage 6 (server half): WebSocket push
|
||||
Built: `/ws` on the game's HTTP server (`server/push.js` transport, `server/pushHooks.js` routing), contract in `docs/PROTOCOL.md`.
|
||||
Auth as first message (`ready` / close 4401), Origin check (`net.originAllowed`), per-IP cap `MAX_CONN_PER_IP` (HTTP 429), 1 KB frames,
|
||||
10 s auth timeout (4408), per-socket token bucket (4429), bad-message budget (4400), ping/pong keepalive that terminates dead sockets and
|
||||
re-checks the token on every tick (revoked/banned: 4401), graceful 1001 close inside `srv.close()`. Hints: `town`, `incoming`,
|
||||
`notification`, `report`, `message`, `pong`. Every `notifications` row (via `scheduler.notify` -> post-commit outbox -> `onNotify`) pushes a
|
||||
`notification` hint, plus the typed ones; finished events and committed commands push `town` to the owners of the POPs they touched.
|
||||
Hints go out only after the transaction that caused them committed (a rolled-back event or command pushes nothing); identical hints of
|
||||
one tick are merged. Small edits outside the new files: `scheduler.js` (outbox, `notify` returns the row id), `commands/index.js`
|
||||
(`hooks.onCommand`, outbox flush/rollback), `index.js` (upgrade + shutdown).
|
||||
Tests: `test/push-ws.test.js` (auth ok/bad/timeout, origin, path, per-IP cap and its release, rate limit, bad budget, oversize frame, dead
|
||||
socket, revoked token, banned user, shutdown, REST with no socket) and `test/push-game.test.js` (build/train done, incoming only to the
|
||||
defender, report/message/alliance invite hints, recall, coalescing, rollback). Real `ws` client, fake clock, port 0. `npm test`: 113 pass
|
||||
(run after the push work, with the other agents' changes in the tree at that moment).
|
||||
Not done / not claimed:
|
||||
- The client now exists (`public/js/ws.js`, see "Client: military, expansion, WebSocket") and was run against this server in a headless browser; not through a proxy.
|
||||
- Revocation closes the socket at the next ping tick (default 30 s), not instantly: `POST /auth/logout` and token deletion do not call push.
|
||||
- No load test (many sockets, large catch-ups), no test behind a real nginx Proxy Manager (upgrade headers, idle timeouts, `X-Forwarded-For`
|
||||
for the per-IP cap); only the code paths of `net.clientIp` are reused. The proxy's idle timeout (NPM default 60 s) is above nothing we
|
||||
send: the 30 s ping keeps sockets alive, but that is reasoning, not a measurement.
|
||||
- Hint gaps: owners of reinforcements standing in an attacked POP get `report` but no `town` hint for their home POP; no `incoming` for
|
||||
confederates; no APNs/FCM sender (the `notifications` table plus `scheduler.onNotify` is where it would attach); no resume after a gap.
|
||||
- The ws tuning knobs (`wsPingMs`, `wsRate`, ...) are `createServer` options only, not environment variables.
|
||||
|
||||
## Trade, end game, gaps (server only; migration `004_trade_endgame.sql`)
|
||||
Built and tested (`test/trade-*.test.js`, `test/endgame-*.test.js`; fake clock, in-memory db, port 0; contract-checked responses over HTTP):
|
||||
- **Trade:** offers "give X of A for Y of B within Z tiles" with escrow, a link reserved per open offer, 1:2 ratio band, expiry event,
|
||||
cancel, accept = two transports in one transaction (all or nothing), the `transportArrived` consumer completes the offer, void when the
|
||||
POP is taken over. Conservation is asserted (every unit in POPs + escrow + on the road, before and after; the only loss is the existing
|
||||
Rack hall overflow, asserted too). Routes under `/trade/offers`.
|
||||
- **End game:** 7 seed-derived landing sites (`rules.backboneSites`, `tileAt` with the world age; spawn and settle refuse them from day 0),
|
||||
open at world day 100 / speed, taken with scan/attack against a static heavy defence, node level 1..100 built from a stockpile fed by
|
||||
transports (`/backbone/:id/ship`, `/build`), winner at level 100, `worldEnd` two world days later with a stored ranking snapshot and a frozen
|
||||
world, `world_ended` for every game command, `GET /worlds/:id/status` and `/results`. One end-to-end test runs day 100 -> take -> ship ->
|
||||
build -> win -> ended on a speed-2 world; the ended-world gate is also driven over HTTP.
|
||||
- **Gaps closed:** shared report folder (`report_shares`, `/reports/:id/share`, `/alliances/:id/reports`), `alliedIncoming` in `GET /movements`,
|
||||
`buildDone` is relative to the building's current level (test written first, failed before the fix).
|
||||
Not done / not claimed:
|
||||
- **Nothing here is balanced.** Defence multiplier 12 (+3% per level), node cost 4000 x 1.045^(L-1) (about 7.2 M of each resource in total),
|
||||
node time 2 h x 1.025^(L-1) (about 36 world days), 48 h offer ttl, 10 tiles of reach per exchange level, 500-per-side offers: first guesses,
|
||||
no bot run (`tools/bot.js` still does not exist). Whether an alliance can actually ship 7 M of everything in time is unknown.
|
||||
- **No garrison at landing sites** (E1): defence is static, holders cannot station units. If the first world shows the race is decided by who
|
||||
hits first, the next step is a small `site_units` table with reinforce-to-site and defenders in `landing.js`.
|
||||
- No `backbone_open` push at the moment the sites appear unless something touches a site first (E2); clients see the phase by polling status.
|
||||
- Trade: no multi-link deals (each side <= 500), no price history or order book, no counter-offers, no notification when a new offer appears
|
||||
in reach, offers are not hidden from enemies, the escrow of a taken-over POP goes to the conqueror.
|
||||
- Ended worlds: movements still `out` and queued builds are left as they were (events cancelled, E3); there is no admin "end world now" or
|
||||
"reset" yet (stage 7 world lifecycle: the `worldEnd` event can be enqueued by hand); several winners are impossible by design.
|
||||
- The ranking snapshot is the same numbers as `/rankings`, computed once; `/rankings/*` after the end still compute live from the frozen state.
|
||||
- Client: nothing in `public/` was touched. New notification types (`trade_*`, `backbone_*`, `world_ended`), the `landing` report type, the
|
||||
`backbone` map special / tile, `world_ended` and the new error codes (`trade_ratio`, `offer_closed`, `own_offer`, `trade_out_of_range`,
|
||||
`world_ended`, `backbone_closed`) need strings and screens.
|
||||
|
||||
## Not done
|
||||
- Everything else. See CLAUDE.md "Working in stages".
|
||||
|
|
|
|||
146
docs/PROTOCOL.md
Normal file
146
docs/PROTOCOL.md
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
# PROTOCOL: WebSocket push
|
||||
|
||||
Endpoint `/ws` on the same HTTP server and port as the REST API (`ws://host:port/ws`, `wss://` behind the proxy).
|
||||
Implementation: `server/push.js` (sockets), `server/pushHooks.js` (who gets which hint). Tests: `test/push-ws.test.js`,
|
||||
`test/push-game.test.js`.
|
||||
|
||||
**Push is a hint, never state.** A message says "something changed, go and look" and carries ids and times only. The client
|
||||
refetches over REST (`GET /towns/:id`, `/movements`, `/reports`, `/notifications` ...). The game is fully playable with the socket
|
||||
disconnected, lost hints are harmless, and nothing a hint says may be trusted without the REST read. Hints are sent only after
|
||||
the database transaction that caused them committed.
|
||||
|
||||
All messages are JSON text frames, one object per frame with a string `type`. Times are integer ms since the epoch (UTC),
|
||||
server clock.
|
||||
|
||||
## Connecting
|
||||
|
||||
1. Open `/ws`. The upgrade is refused with plain HTTP status (the client sees a failed handshake, not a close code):
|
||||
|
||||
| HTTP | Why |
|
||||
| ---- | --- |
|
||||
| 403 | `Origin` header present and not allowed: same host as `Host`, or listed in `ALLOWED_ORIGINS` (same rule as `net.originAllowed`). No `Origin` (non-browser clients) is fine. |
|
||||
| 404 | any path other than `/ws` |
|
||||
| 429 | already `MAX_CONN_PER_IP` (default 40, `0` = off) open sockets from this client address (`net.clientIp`, proxy aware). Counts sockets that have not authenticated yet. |
|
||||
| 503 | server is shutting down |
|
||||
| 426 | not from us: nginx Proxy Manager with **Websockets Support** off, see `docs/DEPLOY.md` |
|
||||
|
||||
2. Send the first message within **10 s**. It must be exactly this, **never put the token in the URL** (proxy logs):
|
||||
|
||||
```json
|
||||
{"type":"auth","token":"<bearer token from /auth/login or /auth/signup>"}
|
||||
```
|
||||
|
||||
3. The server answers `{"type":"ready","serverTime":1767225600000}`. Only after `ready` do hints flow.
|
||||
Anything else as first message, an invalid, revoked or banned token, or no message in time closes the socket (below).
|
||||
|
||||
One socket per device is enough; a user may have several (phone + desktop), each gets every hint.
|
||||
|
||||
## Server to client
|
||||
|
||||
| Message | Meaning | Client reaction |
|
||||
| ------- | ------- | --------------- |
|
||||
| `{"type":"ready","serverTime":n}` | authenticated | use `serverTime` to refresh the clock offset |
|
||||
| `{"type":"pong","serverTime":n}` | answer to `ping` | same |
|
||||
| `{"type":"town","townId":n}` | POP `n` (yours) changed: build/train/research done, resources spent, units arrived, returned or died, attacked, ownership changed, a command from another device | refetch `GET /towns/:id` (if on screen) |
|
||||
| `{"type":"incoming","townId":n,"arriveAt":n}` | a movement from another operator was launched at your POP `townId`, arrives at `arriveAt`. Type and origin hidden on purpose (could be a scan, a raid, reinforcements or a transport). | show a warning with a countdown, refetch `GET /movements` for the details the API allows |
|
||||
| `{"type":"notification","id":n,"kind":"..."}` | a row was added to your notifications. `kind` is `notifications.type`: `build_done`, `train_done`, `research_done`, `incoming`, `report`, `message`, `alliance_message`, `alliance_invite`, `town_lost`, `town_gained`, `transport_arrived`, `movement_returned`, `units_offline`, ... (the list grows, treat unknown kinds as generic) | bump the unread badge, `GET /notifications` |
|
||||
| `{"type":"report","id":n}` | a battle or scan report with id `n` is ready for you | `GET /reports/:id` or refresh the list |
|
||||
| `{"type":"message","id":n}` | a direct or alliance message with id `n` arrived for you (not sent to its sender) | refresh the inbox |
|
||||
|
||||
`incoming`, `report` and `message` always come together with the matching `notification` hint (same event, two messages).
|
||||
The generic `notification` hint is the one to build the badge on; the typed ones let the client skip a round trip.
|
||||
|
||||
Guarantees and non-guarantees:
|
||||
|
||||
* Hints are best effort: after a reconnect, refetch what is on screen (and `/notifications`, `/movements`); do not assume nothing
|
||||
was missed.
|
||||
* Identical hints produced in the same tick are merged (a 50 event catch-up gives one `town` hint per POP), order is otherwise
|
||||
preserved per socket.
|
||||
* A command's own `town` hint is also sent to the device that issued it (ignore your own echo if you already refetch).
|
||||
* Reads (`GET`) never push. A hint is not sent for a refused or rolled-back command.
|
||||
* At launch of a movement the target's owner gets `incoming`, not a plain `town` hint; `town` for that POP follows when it
|
||||
arrives.
|
||||
|
||||
## Client to server
|
||||
|
||||
| Message | Answer |
|
||||
| ------- | ------ |
|
||||
| `{"type":"auth","token":"..."}` | only as the first message (see above); a second one counts as a bad message |
|
||||
| `{"type":"ping"}` | `{"type":"pong","serverTime":n}` |
|
||||
|
||||
Anything else (unknown `type`, invalid JSON, not an object, binary frame) is a **bad message**: ignored, counted. The 5th bad
|
||||
message on a socket closes it with 4400. Before authentication any non-auth first message is fatal (4401).
|
||||
|
||||
Keepalive: the server sends a protocol ping every 30 s and terminates a socket that did not answer (or send anything) by the next
|
||||
tick. Browsers answer protocol pings automatically. The `{"type":"ping"}` message is for clients that want a clock sample or a
|
||||
liveness probe of their own; it is not required.
|
||||
|
||||
## Limits
|
||||
|
||||
| Limit | Value | On exceeding |
|
||||
| ----- | ----- | ------------ |
|
||||
| Client message size | 1024 bytes | close 1009 |
|
||||
| Time to send `auth` | 10 s | close 4408 |
|
||||
| Messages per socket | 5 per second sustained, burst 15 (`net.TokenBucket`; authentication counts) | close 4429 |
|
||||
| Bad messages | 5 per socket | close 4400 |
|
||||
| Sockets per client address | `MAX_CONN_PER_IP`, default 40 | HTTP 429 on upgrade |
|
||||
| Server-side backlog | a client that leaves 1 MB unread is terminated | close 1006 on the client |
|
||||
|
||||
Server-side tuning for tests lives in the `createServer` options `wsAuthTimeoutMs`, `wsPingMs`, `wsRate`, `wsBurst`, `wsBadBudget`
|
||||
(no environment variables; the defaults above are what production runs).
|
||||
|
||||
## Close codes
|
||||
|
||||
| Code | Reason string | Meaning | Client should |
|
||||
| ---- | ------------- | ------- | ------------- |
|
||||
| 1001 | `shutdown` | server is restarting | reconnect with backoff (a few seconds, then up to 30 s) and refetch |
|
||||
| 1006 | | abnormal (network, proxy, server terminated a dead or backlogged socket) | reconnect with backoff, refetch |
|
||||
| 1009 | | a client frame was larger than 1024 bytes | bug in the client; do not retry in a loop |
|
||||
| 4400 | `too_many_bad_messages` | 5 bad messages | bug in the client; do not retry in a loop |
|
||||
| 4401 | `invalid_token`, `auth_required`, `token_revoked` | token unknown, revoked, user banned, or first message was not `auth` | **do not reconnect** with this token: go to login. `token_revoked` is sent as soon as the next ping tick (at most 30 s) notices the revocation (logout on that device, revoked in settings, ban) |
|
||||
| 4408 | `auth_timeout` | no `auth` within 10 s | reconnect |
|
||||
| 4429 | `rate_limited` | more than 5 msg/s sustained | back off at least 30 s |
|
||||
|
||||
Suggested client loop: connect, send auth, on `ready` reset the backoff, on close with 4401/4400/1009 stop, otherwise retry after
|
||||
`min(30 s, 1 s * 2^n)` plus jitter; after every `ready` following a gap, refetch the visible screen and `/notifications`.
|
||||
|
||||
## Example session
|
||||
|
||||
```text
|
||||
C: {"type":"auth","token":"mQ3...43 chars"}
|
||||
S: {"type":"ready","serverTime":1767225600000}
|
||||
... alice queues a building on a phone ...
|
||||
S: {"type":"town","townId":1} (the other devices; the phone gets its echo)
|
||||
... the building finishes ...
|
||||
S: {"type":"town","townId":1}
|
||||
S: {"type":"notification","id":14,"kind":"build_done"}
|
||||
... bobby sends a raid at POP 1 ...
|
||||
S: {"type":"incoming","townId":1,"arriveAt":1767236400000}
|
||||
S: {"type":"notification","id":15,"kind":"incoming"}
|
||||
... it lands ...
|
||||
S: {"type":"town","townId":1}
|
||||
S: {"type":"report","id":3}
|
||||
S: {"type":"notification","id":16,"kind":"report"}
|
||||
C: {"type":"ping"}
|
||||
S: {"type":"pong","serverTime":1767236401000}
|
||||
```
|
||||
|
||||
## Where the hints come from
|
||||
|
||||
| Source | Hint |
|
||||
| ------ | ---- |
|
||||
| any `notifications` row (`scheduler.notify`, after the transaction committed) | `notification`; plus `incoming` / `report` / `message` for kinds `incoming` / `report` / `message`, `alliance_message`; plus `town` for kinds that change a POP whose owner may differ from the event's POP (`town_lost`, `town_gained`, `transport_arrived`, `transport_delivered`, `movement_returned`, `reinforcements_sent_home`) |
|
||||
| a finished event (`scheduler.onEvent`) | `town` to the owner of `events.town_id` (build, train, research, power check) and of both ends of the movement for `arrive` / `return` |
|
||||
| a committed command (`commands.hooks.onCommand`) | `town` to the owner of the POP named in `townId`, `fromTownId`, `hostTownId`, `ownerTownId` or the new POP of `joinWorld`; for `recallMovement` both ends of the movement |
|
||||
|
||||
Adding a notification kind needs no change here (it arrives as a generic `notification`). A new kind that deserves its own typed
|
||||
hint is one `case` in `server/pushHooks.js` plus a row in the table above.
|
||||
|
||||
## Not covered (yet)
|
||||
|
||||
* No APNs/FCM: the `notifications` table is the hook for it (`scheduler.onNotify` sees every row).
|
||||
* No subscription channels: every authenticated socket gets all hints of its user, across worlds (the hint carries `townId`).
|
||||
* No per-device mute, no "last seen id" resume: reconnect and refetch.
|
||||
* Reinforcing owners (units stationed in a POP that gets attacked) are told by the `report` hint, not by a `town` hint for their
|
||||
home POP.
|
||||
* Confederates do not get `incoming` for each other's POPs (nothing in the game layer produces it yet).
|
||||
2236
docs/openapi.json
2236
docs/openapi.json
File diff suppressed because it is too large
Load diff
|
|
@ -84,7 +84,10 @@ button:focus:not(:focus-visible), [tabindex="-1"]:focus { outline: none; }
|
|||
.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-badge { position: absolute; top: -5px; right: -9px; min-width: 17px; height: 17px; padding: 0 4px; border-radius: 9px; background: var(--cyan); color: #04222b; font-size: 11px; font-weight: 700; display: grid; place-items: center; }
|
||||
.nav-badge.is-alert { background: var(--red); color: #1a0710; animation: mil-pulse 1.4s ease-in-out infinite; }
|
||||
@keyframes mil-pulse { 50% { box-shadow: 0 0 0 5px rgba(255, 107, 135, .0), 0 0 0 0 rgba(255, 107, 135, .5); transform: scale(1.12); } }
|
||||
.more-list { display: grid; gap: 8px; padding-bottom: 6px; }
|
||||
.nav-lbl { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) {
|
||||
|
|
@ -321,4 +324,190 @@ input:focus-visible, select:focus-visible { outline: 2px solid var(--cyan); outl
|
|||
.device .row-sub { white-space: normal; }
|
||||
.card .btn.wide { margin-top: 10px; }
|
||||
|
||||
/* ---------------------------------------------------------------- social (alliance, messages, rankings): .soc- */
|
||||
.soc-page { gap: 10px; }
|
||||
.soc-body, .soc-content, .soc-listbox { display: grid; gap: 10px; align-content: start; min-width: 0; }
|
||||
.soc-card .card-head { margin-bottom: 8px; }
|
||||
.soc-card > .detail-desc { margin-bottom: 10px; }
|
||||
.soc-card .field { margin-top: 10px; }
|
||||
.soc-head-actions { display: flex; align-items: center; gap: 4px; }
|
||||
.soc-stack { grid-auto-flow: row; grid-auto-columns: auto; }
|
||||
.soc-title { display: flex; align-items: center; gap: 10px; margin-bottom: 4px; min-width: 0; }
|
||||
.soc-name { font-size: 20px; font-weight: 700; overflow-wrap: anywhere; }
|
||||
.soc-head .bar { --c: var(--cyan); height: 6px; margin-top: 4px; }
|
||||
.soc-tag { font-family: var(--mono); color: var(--cyan); flex: none; }
|
||||
.soc-role-leader { color: #2b2204; background: var(--amber); border-color: var(--amber); font-weight: 650; }
|
||||
.soc-role-diplomat { color: var(--violet); border-color: color-mix(in srgb, var(--violet) 60%, var(--line2)); }
|
||||
.soc-role-officer { color: var(--cyan); border-color: color-mix(in srgb, var(--cyan) 55%, var(--line2)); }
|
||||
.soc-state-war { color: var(--red); border-color: #7a2a3f; background: #2d1019; }
|
||||
.soc-state-nap { color: var(--cyan); border-color: color-mix(in srgb, var(--cyan) 55%, var(--line2)); }
|
||||
.soc-state-confed { color: var(--green); border-color: #1a6a4f; background: #0e2b23; }
|
||||
.soc-state-same { color: var(--amber); }
|
||||
|
||||
.soc-tabs { margin-bottom: 0; }
|
||||
.soc-tabs .seg-btn { min-width: 0; padding: 0 4px; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.soc-tabs4 .seg-btn { font-size: 13px; display: inline-flex; align-items: center; justify-content: center; gap: 5px; }
|
||||
.soc-tabn { min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--red); color: #1a0710; font-size: 11px; font-weight: 700; display: inline-grid; place-items: center; }
|
||||
.soc-subtabs { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.soc-subtabs .chip-btn { flex: 1; }
|
||||
.soc-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
|
||||
.soc-list { display: grid; gap: 8px; min-width: 0; }
|
||||
.soc-item { display: flex; align-items: center; gap: 8px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 56px; flex-wrap: wrap; min-width: 0; }
|
||||
.soc-item > .row-main { min-width: 0; flex: 1 1 140px; }
|
||||
.soc-item .row-sub { white-space: normal; overflow-wrap: anywhere; }
|
||||
.soc-item .form-error { flex-basis: 100%; margin: 4px 0 0; }
|
||||
.soc-actions { display: flex; gap: 8px; flex: none; }
|
||||
.soc-invite .soc-actions { margin-left: auto; }
|
||||
.soc-member .row-title b { overflow-wrap: anywhere; }
|
||||
.soc-member .row-sub { white-space: normal; }
|
||||
.soc-wrap { white-space: normal !important; }
|
||||
.soc-req { margin: 2px 0 8px; }
|
||||
.soc-hint { padding: 0 2px; }
|
||||
.soc-inline { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; }
|
||||
.soc-err { display: grid; gap: 8px; justify-items: start; }
|
||||
|
||||
.soc-text { width: 100%; min-height: 76px; max-height: 40vh; padding: 10px 12px; border-radius: 12px; background: #080e1c; border: 1px solid var(--line2); color: var(--text); font-size: 16px; line-height: 1.35; resize: vertical; font-family: var(--font); }
|
||||
.soc-text:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; border-color: var(--cyan); }
|
||||
.soc-composer { display: grid; gap: 8px; }
|
||||
.soc-composer-bar { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.soc-addnote { display: grid; gap: 8px; margin-top: 10px; }
|
||||
.soc-count { font-size: 12px; color: var(--dimmer); }
|
||||
.soc-count.over { color: var(--red); font-weight: 700; }
|
||||
.soc-rate { color: var(--amber); background: #2b2204; border: 1px solid #6b5a1f; border-radius: 10px; padding: 8px 12px; font-size: 14px; }
|
||||
.soc-text-out, .soc-msg-body { white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; font-size: 15px; line-height: 1.4; }
|
||||
.soc-note .soc-text-out { margin-bottom: 2px; }
|
||||
|
||||
.soc-msgrow { display: flex; align-items: center; gap: 2px; }
|
||||
.soc-msgrow .soc-msg { flex: 1; min-width: 0; align-items: flex-start; }
|
||||
.soc-msg.unread { border-color: var(--cyan); background: #0c1f33; }
|
||||
.soc-msg .when { margin-top: 2px; }
|
||||
.soc-preview { color: var(--dim); font-size: 14px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; white-space: normal; }
|
||||
.soc-feed { align-items: flex-start; }
|
||||
.soc-feed.unread { border-color: var(--cyan); background: #0c1f33; }
|
||||
.soc-feed .row-title { align-items: center; }
|
||||
.soc-feed .when { margin-left: auto; }
|
||||
|
||||
.soc-thread-head { display: flex; align-items: center; gap: 6px; }
|
||||
.soc-thread-name { flex: 1; min-width: 0; font-size: 18px; overflow-wrap: anywhere; }
|
||||
.soc-thread { display: grid; gap: 8px; }
|
||||
.soc-bubble { max-width: 86%; padding: 8px 12px 6px; border-radius: 14px; background: var(--panel2); border: 1px solid var(--line); justify-self: start; min-width: 0; }
|
||||
.soc-bubble.out { justify-self: end; background: #11304a; border-color: #1f5b86; }
|
||||
.soc-bubble.unread { border-color: var(--cyan); }
|
||||
.soc-bubble-meta { display: flex; align-items: center; justify-content: flex-end; gap: 6px; margin-top: 2px; color: var(--dimmer); }
|
||||
.soc-del { width: 32px; height: 32px; display: inline-grid; place-items: center; background: none; border: 0; color: var(--dimmer); border-radius: 8px; }
|
||||
.soc-del svg.ic { width: 14px; height: 14px; }
|
||||
.soc-reply { position: sticky; bottom: 0; background: var(--bg); border-top: 1px solid var(--line); padding: 8px 0 calc(8px + 0px); margin-top: 4px; }
|
||||
|
||||
.soc-dip { display: grid; gap: 10px; }
|
||||
.soc-rel .row-sub { white-space: normal; display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
.soc-eta { color: var(--amber); }
|
||||
.soc-moves { display: grid; gap: 8px; }
|
||||
.soc-move { min-height: 64px; }
|
||||
|
||||
.soc-yourank { display: flex; align-items: center; gap: 12px; border-color: var(--cyan); background: #0c1f33; padding: 10px 12px; }
|
||||
.soc-yr-n { font-size: 24px; font-weight: 700; color: var(--cyan); min-width: 2.4ch; }
|
||||
.soc-ranklist { display: grid; gap: 6px; list-style: none; padding: 0; margin: 0; }
|
||||
.soc-rank { 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: 54px; text-align: left; }
|
||||
.soc-rank.you { border-color: var(--cyan); background: #0c1f33; box-shadow: 0 0 0 1px rgba(77, 227, 255, .3); }
|
||||
.soc-rk { color: var(--dimmer); min-width: 3.2ch; font-size: 14px; }
|
||||
.soc-rank .row-sub { white-space: normal; overflow-wrap: anywhere; }
|
||||
.soc-val { font-size: 16px; color: var(--text); flex: none; }
|
||||
@media (max-width: 380px) { .soc-tabs .seg-btn { font-size: 13px; } .soc-bubble { max-width: 94%; } }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) { .sheet, .backdrop, .toast, .bar i { transition: none; } }
|
||||
|
||||
/* ---------------------------------------------------------------- military + expansion (prefix mil-, send-, rep-) */
|
||||
.row-sub.wrap { white-space: normal; overflow: visible; }
|
||||
.head-actions { display: flex; align-items: center; gap: 6px; }
|
||||
.mil-sections { display: grid; gap: 12px; }
|
||||
.mil-list { display: grid; gap: 8px; }
|
||||
.mil-row { display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; }
|
||||
.mil-row.current { border-color: var(--cyan); }
|
||||
.mil-row.out.type-return { opacity: .8; }
|
||||
.mil-row .row-main { min-width: 0; }
|
||||
.mil-row .lv { color: var(--dim); font-size: 13px; }
|
||||
.mil-when { display: grid; justify-items: end; gap: 1px; flex: none; text-align: right; }
|
||||
.mil-when small { color: var(--dimmer); font-size: 11px; }
|
||||
.mil-cd { font-size: 15px; }
|
||||
.mil-cd.big { font-size: 19px; color: var(--red); }
|
||||
.mil-bar { margin-top: 5px; --c: var(--cyan); }
|
||||
.mil-group { background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; display: grid; gap: 4px; }
|
||||
.row-ic.bad { background: #3a1620; color: var(--red); }
|
||||
.warn-card { border-color: #7a2a3f; background: rgba(48, 14, 24, .9); }
|
||||
.warn-card .card-head h2 { color: #ffc4d0; }
|
||||
.mil-banner { display: flex; align-items: center; gap: 10px; }
|
||||
.mil-banner .row-main { flex: 1; min-width: 0; }
|
||||
.mil-banner b { color: #ffd0da; }
|
||||
.mil-banner .mil-cd { color: var(--red); }
|
||||
.mil-banner:not([hidden]) .row-ic { animation: mil-pulse-ic 1.4s ease-in-out infinite; }
|
||||
@keyframes mil-pulse-ic { 50% { box-shadow: 0 0 0 6px rgba(255, 107, 135, .18); } }
|
||||
.mil-recall { margin-top: 8px; width: max-content; }
|
||||
.mil-recall .mil-cd { font-size: 13px; }
|
||||
.mil-row .arrow { display: inline-flex; vertical-align: middle; margin: 0 4px; color: var(--dimmer); }
|
||||
.mil-row .arrow svg.ic { width: 14px; height: 14px; }
|
||||
.mil-end { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 4px; }
|
||||
.mil-coord { display: inline-flex; align-items: center; gap: 4px; background: none; border: 0; color: var(--cyan); padding: 2px 4px; min-height: 28px; font-size: 12px; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.mil-coord svg.ic { width: 13px; height: 13px; }
|
||||
.pop-top { max-width: 1100px; margin: 0 auto; padding: 4px 12px 0; display: grid; gap: 8px; }
|
||||
.row-btn.locked { opacity: .6; }
|
||||
.card.inner { background: var(--panel2); }
|
||||
.stepper { display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto auto; gap: 6px; align-items: center; }
|
||||
.stepper .btn { min-width: 46px; padding: 0 8px; }
|
||||
input.mil-num { width: 100%; min-height: 46px; padding: 0 10px; border-radius: 12px; background: #080e1c; border: 1px solid var(--line2); color: var(--text); font-size: 16px; text-align: center; font-family: var(--mono); -moz-appearance: textfield; }
|
||||
input.mil-num::-webkit-outer-spin-button, input.mil-num::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
|
||||
.send { gap: 14px; }
|
||||
.send-sec { display: grid; gap: 8px; }
|
||||
.send-sec:empty { display: none; }
|
||||
.send-coords { display: grid; grid-template-columns: auto minmax(0, 1fr) auto minmax(0, 1fr) auto; gap: 6px; align-items: center; }
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.send-target { background: var(--panel2); border-radius: 12px; padding: 10px 12px; display: grid; gap: 4px; }
|
||||
.wrap-seg { grid-auto-flow: row; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); }
|
||||
.wrap-seg .seg-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 6px 8px; font-size: 14px; }
|
||||
.seg-btn:disabled { opacity: .4; cursor: not-allowed; }
|
||||
.send-why { display: grid; gap: 2px; }
|
||||
.mil-pick { background: var(--panel2); border-radius: 12px; padding: 8px 10px; display: grid; gap: 6px; }
|
||||
.pick-ctl { display: grid; grid-template-columns: auto minmax(60px, 1fr) auto 64px auto; gap: 6px; align-items: center; }
|
||||
.pick-ctl .btn.small { min-width: 40px; padding: 0 8px; }
|
||||
.pick-ctl input.mil-num { min-height: 40px; padding: 0 4px; }
|
||||
.pick-ctl input[type="range"] { width: 100%; min-height: 40px; accent-color: var(--cyan); }
|
||||
.send-preview { background: var(--panel2); border-radius: 12px; padding: 4px 12px; }
|
||||
.send-warn { display: grid; gap: 8px; }
|
||||
.warn-check { display: flex; gap: 10px; align-items: flex-start; background: #2a210a; border: 1px solid #6b5a1f; border-radius: 12px; padding: 10px 12px; color: var(--amber); font-size: 14px; }
|
||||
.warn-check input { width: 22px; height: 22px; flex: none; margin-top: 2px; accent-color: var(--amber); }
|
||||
select { width: 100%; }
|
||||
|
||||
.alert.rep.tone-good .row-ic { color: var(--green); }
|
||||
.alert.rep.tone-bad .row-ic { color: var(--red); }
|
||||
.alert.rep.tone-warn .row-ic { color: var(--amber); }
|
||||
.rep-detail { gap: 12px; }
|
||||
.rep-verdict { display: flex; align-items: center; gap: 8px; padding: 10px 14px; border-radius: 12px; font-size: 18px; }
|
||||
.rep-verdict.victory { background: #0e2b23; color: var(--green); border: 1px solid #1a6a4f; }
|
||||
.rep-verdict.defeat { background: #2d1019; color: #ffc4d0; border: 1px solid #7a2a3f; }
|
||||
.rep-sec { display: grid; gap: 6px; }
|
||||
.rep-party { display: inline-flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 4px; }
|
||||
.mil-table { width: 100%; border-collapse: collapse; font-size: 14px; }
|
||||
.mil-table th { text-align: right; font-weight: 500; color: var(--dimmer); font-size: 12px; padding: 2px 6px; }
|
||||
.mil-table td { padding: 5px 6px; border-top: 1px solid var(--line); }
|
||||
.mil-table td:not(:first-child) { text-align: right; }
|
||||
.rep-group { display: grid; gap: 4px; margin-bottom: 8px; }
|
||||
.rep-buildings { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 4px 12px; font-size: 14px; }
|
||||
.rep-buildings li { display: flex; justify-content: space-between; gap: 8px; border-bottom: 1px solid var(--line); padding: 3px 0; }
|
||||
.rep-raw { white-space: pre-wrap; font-size: 12px; color: var(--dim); }
|
||||
|
||||
.hud-town { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; color: var(--cyan); }
|
||||
.hud-town select { min-height: 36px; font-size: 14px; padding: 0 10px; width: auto; max-width: 100%; flex: 0 1 280px; }
|
||||
.hud-town svg.ic { width: 18px; height: 18px; }
|
||||
.lg.mv-out { height: 0; width: 14px; border-top: 2px dashed var(--cyan); }
|
||||
.lg.mv-in { height: 0; width: 14px; border-top: 2px dashed var(--red); }
|
||||
@media (orientation: landscape) and (max-height: 520px) { .hud-town select { min-height: 30px; } }
|
||||
@media (prefers-reduced-motion: reduce) { .nav-badge.is-alert, .mil-banner .row-ic { animation: none; } }
|
||||
.units-head { max-width: 1100px; margin: 0 auto; padding: 4px 12px 0; }
|
||||
.send-foot { position: sticky; bottom: -1px; z-index: 2; display: grid; gap: 8px; padding: 10px 0 2px; margin-top: 4px; background: linear-gradient(180deg, rgba(12, 19, 34, 0), var(--panel) 22%); }
|
||||
.send-foot .form-error { margin-bottom: 0; }
|
||||
.row-btn.mil-train { flex-wrap: wrap; row-gap: 6px; }
|
||||
.mil-train .costs { flex-basis: 100%; gap: 6px; padding-left: 48px; }
|
||||
.mil-train .cost { padding: 3px 8px; }
|
||||
.mil-train .cost svg.ic { width: 15px; height: 15px; }
|
||||
.mil-train .pill { max-width: none; }
|
||||
|
|
|
|||
|
|
@ -45,5 +45,22 @@
|
|||
<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>
|
||||
<symbol id="i-more" viewBox="0 0 24 24"><circle fill="currentColor" cx="5.5" cy="12" r="1.9"/><circle fill="currentColor" cx="12" cy="12" r="1.9"/><circle fill="currentColor" cx="18.5" cy="12" r="1.9"/></symbol>
|
||||
<symbol id="i-units" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5l7 3v5c0 4-3 7-7 9-4-2-7-5-7-9v-5z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 8v7M8.5 11.5h7"/></symbol>
|
||||
<symbol id="i-move" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 12h15M13 6.5l5.5 5.5-5.5 5.5"/></symbol>
|
||||
<symbol id="i-report" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6 3.5h8l4 4v13H6z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14 3.5v4h4M9 12h6M9 15.5h6"/></symbol>
|
||||
<symbol id="i-target" 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"/><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 1.8v4M12 18.2v4M1.8 12h4M18.2 12h4"/></symbol>
|
||||
<symbol id="i-eye" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3"/></symbol>
|
||||
<symbol id="i-flask" 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.5 15h9"/></symbol>
|
||||
<symbol id="i-box" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3l8 4v10l-8 4-8-4V7z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 7l8 4 8-4M12 11v10"/></symbol>
|
||||
<symbol id="i-flag" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6 21V4M6 4.5h11l-2.2 3.5L17 11.5H6"/></symbol>
|
||||
<symbol id="i-swap" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 8h14M14.5 4.5L18 8l-3.5 3.5M20 16H6M9.5 12.5L6 16l3.5 3.5"/></symbol>
|
||||
<symbol id="i-return" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9 7L4.5 11.5 9 16M4.5 11.5H15a4.5 4.5 0 010 9h-2"/></symbol>
|
||||
<symbol id="i-handshake" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3 12l4-4 4 1.5 3-1.5 4 3.5-4 5-3 2-3.5-1.5L3 17z"/></symbol>
|
||||
<!-- social -->
|
||||
<symbol id="i-users" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="9" cy="8.5" r="3.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3 19.5c.4-3.3 2.9-5 6-5s5.6 1.7 6 5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M15.5 5.6a3 3 0 010 5.8M17.5 14.9c2 .5 3.2 2 3.5 4.6" opacity=".7"/></symbol>
|
||||
<symbol id="i-mail" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3.5" y="5.5" width="17" height="13" rx="2.4"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4.5 7.5l7.5 5.8 7.5-5.8"/></symbol>
|
||||
<symbol id="i-trophy" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7.5 4h9v5.5a4.5 4.5 0 01-9 0z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7.5 6H4.5c0 3 1.2 4.5 3.2 4.8M16.5 6h3c0 3-1.2 4.5-3.2 4.8M12 14v3.5M8.5 20h7M9.5 17.5h5"/></symbol>
|
||||
<symbol id="i-back" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14.5 5.5L8 12l6.5 6.5"/></symbol>
|
||||
</defs>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 18 KiB |
|
|
@ -33,14 +33,29 @@
|
|||
<script src="js/data.js" defer></script>
|
||||
<script src="js/rules.js" defer></script>
|
||||
<script src="js/i18n.js" defer></script>
|
||||
<script src="js/strings/military.js" defer></script>
|
||||
<script src="js/strings/social.js" defer></script>
|
||||
<script src="js/api.js" defer></script>
|
||||
<script src="js/ui.js" defer></script>
|
||||
<script src="js/social.js" defer></script>
|
||||
<script src="js/render.js" defer></script>
|
||||
<script src="js/milcore.js" defer></script>
|
||||
<script src="js/main.js" defer></script>
|
||||
<script src="js/milstate.js" defer></script>
|
||||
<script src="js/ws.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/units.js" defer></script>
|
||||
<script src="js/screens/movements.js" defer></script>
|
||||
<script src="js/screens/reports.js" defer></script>
|
||||
<script src="js/screens/send.js" defer></script>
|
||||
<script src="js/screens/expand.js" defer></script>
|
||||
<script src="js/screens/alerts.js" defer></script>
|
||||
<script src="js/screens/settings.js" defer></script>
|
||||
<script src="js/screens/social-ui.js" defer></script>
|
||||
<script src="js/screens/alliance.js" defer></script>
|
||||
<script src="js/screens/messages.js" defer></script>
|
||||
<script src="js/screens/rankings.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -109,6 +109,10 @@
|
|||
editNotes: ['leader', 'diplomat', 'officer'],
|
||||
broadcast: ['leader', 'diplomat', 'officer', 'member'],
|
||||
disband: ['leader'],
|
||||
shareReport: ['leader', 'diplomat', 'officer', 'member'], // put one of YOUR reports into the alliance folder
|
||||
viewSharedReports: ['leader', 'diplomat', 'officer', 'member'],
|
||||
unshareReport: ['leader', 'officer'], // plus whoever shared it
|
||||
backboneBuild: ['leader', 'diplomat', 'officer', 'member'], // start the next Backbone node level on a held landing site
|
||||
},
|
||||
allianceBaseSize: 10, // size cap = base + perLevel * Peering office level (best POP of the leader)
|
||||
allianceSizePerLevel: 2,
|
||||
|
|
@ -235,6 +239,34 @@
|
|||
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,
|
||||
// Trade at the Internet exchange. Offers are "give X of A for Y of B, max distance Z"; each side must fit one transport
|
||||
// link (TRANSPORT.capacityPerLink). The exchange level sets how far you see and trade (reachPerLevel tiles per level)
|
||||
// and how many offers you may keep open per POP together with running transports (links).
|
||||
const TRADE = {
|
||||
ratioMax: 2, // give/want must lie in [1/ratioMax, ratioMax] (pump-feeding guard)
|
||||
ttlHours: 48, // an offer expires after this long, divided by world speed
|
||||
reachPerLevel: 10, // tiles
|
||||
maxDistance: 300, // upper bound of an offer's max distance
|
||||
scanChunk: 200, // offers read per round trip when listing (the range filter runs in JS)
|
||||
};
|
||||
|
||||
// End game (backbone race). World age is in WORLD days: real days * world speed.
|
||||
const ENDGAME = {
|
||||
openDay: 100, // the landing sites appear at this world age
|
||||
sites: 7,
|
||||
graceDays: 2, // after level maxLevel is reached the world ends this long after (divided by world speed)
|
||||
siteRingMin: 0.35, siteRingMax: 0.8, // landing sites sit between these fractions of the map radius
|
||||
siteMinSpacing: 6, // tiles between two sites
|
||||
defenceMult: 12, // incumbent site defence x this = the heavy defence of a landing site
|
||||
defencePerLevel: 0.03, // + 3% per built Backbone node level (the node is a bigger target)
|
||||
scanStrength: 40, // a landing site counts as this many scanners when scanned
|
||||
maxLevel: 100, // = BUILDINGS.backbone_node.maxLevel
|
||||
costGrowth: 1.045, // level L costs BUILDINGS.backbone_node.cost * costGrowth^(L-1) of each resource
|
||||
timeGrowth: 1.025, // level L takes BUILDINGS.backbone_node.time * timeGrowth^(L-1) seconds at 1x
|
||||
notifyEvery: 10, // alliance members hear about every n-th level (and the last one)
|
||||
rankingTop: 100, // final snapshot: entries per list
|
||||
};
|
||||
|
||||
return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, TRADE, ENDGAME, 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 };
|
||||
}));
|
||||
|
|
|
|||
|
|
@ -372,5 +372,17 @@
|
|||
// 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 };
|
||||
// Screens added by later stages bring their own strings: public/js/strings/<area>.js calls
|
||||
// UpstreamI18n.extend({ en: {...}, nb: {...} }). Duplicate keys are an error (loud, not last-one-wins).
|
||||
function extend(dicts) {
|
||||
for (const l of LANGS) {
|
||||
const d = dicts[l] || {};
|
||||
for (const k of Object.keys(d)) {
|
||||
if (Object.prototype.hasOwnProperty.call(strings[l], k)) throw new Error('duplicate i18n key ' + k + ' (' + l + ')');
|
||||
strings[l][k] = d[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { LANGS, strings, extend, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs };
|
||||
}));
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
*
|
||||
* App.registerScreen({
|
||||
* id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav
|
||||
* navGroup: 'main' | 'more', // bar button (default) or behind the "More" sheet
|
||||
* 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
|
||||
|
|
@ -13,6 +14,8 @@
|
|||
* });
|
||||
*
|
||||
* Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag.
|
||||
* The bar holds 5 slots; with any 'more' screen the 5th is the More button (see "Bottom nav with overflow" below).
|
||||
* App.setBadge(screenId, n, 'alert'|'info') puts a count on a screen's nav button (the More button sums its screens).
|
||||
* Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone.
|
||||
*/
|
||||
(function () {
|
||||
|
|
@ -94,32 +97,102 @@
|
|||
const elApp = () => document.getElementById('app');
|
||||
|
||||
App.registerScreen = (def) => { App.screens.set(def.id, def); };
|
||||
App.alertKinds = {}; // notification type -> describer, see screens/alerts.js
|
||||
App.popSections = []; // extra cards of the POP screen: { slot: 'top' | 'main', render(townData) -> Node | null }
|
||||
|
||||
// Bottom nav with overflow. A screen picks where it lives with `navGroup`:
|
||||
// 'main' (default) one of the primary screens in the bar (registration order)
|
||||
// 'more' behind the "More" button, which opens a sheet listing these screens
|
||||
// The bar holds NAV_SLOTS buttons. If any 'more' screen exists, or there are more 'main' screens than slots, the last slot
|
||||
// becomes "More" and the surplus 'main' screens go into the sheet in front of the 'more' ones. Keep it to about 4 primary
|
||||
// screens. Badges: App.setBadge(screenId, n, 'alert'|'info') shows a count on the screen's button; the More button
|
||||
// shows the sum of its screens' badges (red if any of them is an alert). Add the screen's script tag and you are done.
|
||||
const NAV_SLOTS = 5;
|
||||
const badges = new Map(); // screen id -> { n, kind }
|
||||
function navSplit() {
|
||||
const all = Array.from(App.screens.values()).filter((d) => d.nav !== false);
|
||||
const main = all.filter((d) => d.navGroup !== 'more'), more = all.filter((d) => d.navGroup === 'more');
|
||||
if (!more.length && main.length <= NAV_SLOTS) return { bar: main, over: [] };
|
||||
return { bar: main.slice(0, NAV_SLOTS - 1), over: main.slice(NAV_SLOTS - 1).concat(more) };
|
||||
}
|
||||
|
||||
function navButton(def, onclick) {
|
||||
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
|
||||
return h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick },
|
||||
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
|
||||
}
|
||||
|
||||
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');
|
||||
const { bar, over } = navSplit();
|
||||
for (const def of bar) nav.appendChild(navButton(def, () => App.go(def.id)));
|
||||
if (over.length) {
|
||||
const btn = navButton({ id: 'more', icon: 'more', navKey: 'nav.more' }, () => openMore());
|
||||
btn.setAttribute('aria-haspopup', 'dialog');
|
||||
nav.appendChild(btn);
|
||||
}
|
||||
updateBadge();
|
||||
markCurrent();
|
||||
updateBadges();
|
||||
}
|
||||
|
||||
function updateBadge() {
|
||||
const n = App.state.unread;
|
||||
const b = elNav().querySelector('[data-screen="alerts"] .nav-badge');
|
||||
function markCurrent() {
|
||||
const id = App.current ? App.current.id : null;
|
||||
const { over } = navSplit();
|
||||
const inMore = over.some((d) => d.id === id);
|
||||
for (const b of elNav().children) {
|
||||
const on = b.dataset.screen === id || (b.dataset.screen === 'more' && inMore);
|
||||
if (on) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current');
|
||||
}
|
||||
}
|
||||
|
||||
function openMore() {
|
||||
const { over } = navSplit();
|
||||
const list = h('div', { class: 'more-list' });
|
||||
const sheet = UI.openSheet({ title: App.t('nav.more'), icon: 'more', closeLabel: App.t('common.close'), body: list });
|
||||
for (const def of over) {
|
||||
const bd = badges.get(def.id);
|
||||
list.appendChild(h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(true); App.go(def.id); } },
|
||||
h('span', { class: 'row-ic' }, icon(def.icon)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: App.t(def.navKey || def.titleKey) }))),
|
||||
bd && bd.n ? h('span', { class: 'pill ' + (bd.kind === 'alert' ? 'amber' : 'accent'), text: String(bd.n) }) : null));
|
||||
}
|
||||
}
|
||||
|
||||
function paintBadge(btn, n, kind, label) {
|
||||
const b = btn.querySelector('.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 }) + ')' : ''));
|
||||
b.classList.toggle('is-alert', kind === 'alert');
|
||||
const lbl = btn.querySelector('.nav-lbl');
|
||||
btn.setAttribute('aria-label', (lbl ? lbl.textContent : label || '') + (n ? ' (' + n + ')' : ''));
|
||||
}
|
||||
|
||||
function updateBadges() {
|
||||
const { over } = navSplit();
|
||||
const overIds = new Set(over.map((d) => d.id));
|
||||
let sum = 0, kind = 'info';
|
||||
for (const [id, bd] of badges) {
|
||||
if (overIds.has(id)) { sum += bd.n; if (bd.kind === 'alert' && bd.n) kind = 'alert'; }
|
||||
}
|
||||
for (const btn of elNav().children) {
|
||||
const id = btn.dataset.screen;
|
||||
if (id === 'more') paintBadge(btn, sum, kind);
|
||||
else { const bd = badges.get(id); paintBadge(btn, bd ? bd.n : 0, bd ? bd.kind : 'info'); }
|
||||
}
|
||||
}
|
||||
|
||||
App.setBadge = (id, n, kind) => {
|
||||
const prev = badges.get(id);
|
||||
n = Math.max(0, Math.floor(n) || 0);
|
||||
if (prev && prev.n === n && prev.kind === (kind || 'info')) return;
|
||||
badges.set(id, { n, kind: kind || 'info' });
|
||||
updateBadges();
|
||||
};
|
||||
const updateBadge = () => App.setBadge('alerts', App.state.unread, 'info'); // alerts feed unread count
|
||||
|
||||
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.
|
||||
|
|
@ -150,7 +223,7 @@
|
|||
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'); }
|
||||
markCurrent();
|
||||
setTitle(def);
|
||||
renderHud(false);
|
||||
if (def.onShow) def.onShow(App.params);
|
||||
|
|
@ -225,9 +298,16 @@
|
|||
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;
|
||||
const td = App.state.townData;
|
||||
if (!td || !App.state.world) return null;
|
||||
if (rulesCache && rulesCache.src === td) return rulesCache.town;
|
||||
const town = App.rulesTownFrom(td, App.fetchedServerTime || 0);
|
||||
rulesCache = { src: td, town };
|
||||
return town;
|
||||
};
|
||||
// Same for any POP payload of GET /towns/:id fetched at server time `at` (the send dialog looks at other POPs too).
|
||||
App.rulesTownFrom = (td, at) => {
|
||||
const st = App.state;
|
||||
const buildings = {};
|
||||
let bdraw = 0;
|
||||
for (const b of td.buildings) {
|
||||
|
|
@ -237,11 +317,10 @@
|
|||
if (def && def.kind === 'infra') bdraw += def.draw * b.level;
|
||||
}
|
||||
const town = {
|
||||
id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0,
|
||||
id: td.id, speed: st.world.speed, updatedAt: at,
|
||||
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;
|
||||
};
|
||||
|
||||
|
|
@ -262,6 +341,8 @@
|
|||
|
||||
// ------------------------------------------------------------------ resource bar
|
||||
const hudRefs = {};
|
||||
App.on('towns', () => renderHud(true)); // POP list changed (founded / conquered / lost / renamed)
|
||||
App.on('townchange', () => renderHud(true)); // the switcher shows the selected POP
|
||||
|
||||
function renderHud(rebuild) {
|
||||
const hud = document.getElementById('hud');
|
||||
|
|
@ -272,6 +353,12 @@
|
|||
if (!want) return;
|
||||
if (!rebuild && hud.firstChild) return;
|
||||
clear(hud);
|
||||
// POP switcher (only with more than one POP): every screen with the resource bar gets it
|
||||
if (App.state.towns.length > 1) {
|
||||
hud.appendChild(h('label', { class: 'hud-town' }, icon('pop'),
|
||||
h('select', { 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
|
||||
App.state.towns.map((x) => h('option', { value: x.id, selected: x.id === App.state.townId, text: x.name + (x.isCapital ? ' ★' : '') })))));
|
||||
}
|
||||
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'),
|
||||
|
|
|
|||
121
public/js/milcore.js
Normal file
121
public/js/milcore.js
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Pure helpers of the military / expansion screens (no DOM, no storage, no clock): what can be sent where, which units go
|
||||
* on which movement, report perspective, reconnect backoff. Loads as a browser script (window.UpstreamMil) and as a Node
|
||||
* module (test/client-mil.test.js). The SERVER decides everything; this only hides choices that can never work, so the
|
||||
* sheet is short, and says why the rest is greyed out.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js'), require('./rules.js'));
|
||||
else root.UpstreamMil = factory(root.UpstreamData, root.UpstreamRules);
|
||||
}(typeof self !== 'undefined' ? self : this, function (D, R) {
|
||||
const TYPES = ['scan', 'raid', 'attack', 'takeover', 'reinforce', 'settle', 'transport'];
|
||||
const HOSTILE = ['raid', 'attack', 'takeover'];
|
||||
const ROLE_ICON = { scout: 'eye', defender: 'shield', attacker: 'target', siege: 'alert', settler: 'flag', conquest: 'handshake' };
|
||||
const TYPE_ICON = { scan: 'eye', raid: 'target', attack: 'target', takeover: 'handshake', reinforce: 'shield', settle: 'flag', transport: 'box', return: 'return', unknown: 'alert' };
|
||||
|
||||
// Units of `home` ({id: n}) that may go on a movement of `type`: [{ unit, have }] in display order.
|
||||
function unitsForType(type, home) {
|
||||
const roles = D.MOVE_ROLES[type];
|
||||
if (!roles) return [];
|
||||
const out = [];
|
||||
for (const unit of D.UNIT_ORDER) {
|
||||
const def = D.UNITS[unit];
|
||||
const have = (home && home[unit]) || 0;
|
||||
if (have > 0 && !def.fixed && roles.indexOf(def.role) >= 0) out.push({ unit, have });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/*
|
||||
* What can be sent to a tile. c = {
|
||||
* tile: GET /map/tile response,
|
||||
* home: units at the sending POP, transport: { links, active } of the sending POP,
|
||||
* allianceId: my alliance id or null, crews: number of rollout crews at home
|
||||
* } -> [{ type, ok, reason }] (reason is a code the sheet turns into text; null when ok)
|
||||
* Hidden (not even greyed): types that make no sense for this kind of tile. Pact rules (NAP, confederation) are not
|
||||
* known to the client: the server refuses those and the sheet shows its message.
|
||||
*/
|
||||
function moveOptions(c) {
|
||||
const t = c.tile, home = c.home || {};
|
||||
const out = [];
|
||||
if (!t) return out;
|
||||
const has = (type) => unitsForType(type, home).length > 0;
|
||||
const add = (type, ok, reason) => out.push({ type, ok: !!ok, reason: ok ? null : reason });
|
||||
if (t.town) {
|
||||
if (t.town.mine) {
|
||||
add('reinforce', has('reinforce'), 'no_units');
|
||||
const links = (c.transport && c.transport.links) || 0, active = (c.transport && c.transport.active) || 0;
|
||||
add('transport', links > active, links === 0 ? 'no_link' : 'links_busy');
|
||||
} else {
|
||||
add('scan', has('scan'), 'no_units');
|
||||
const prot = !!(t.town.owner && t.town.owner.protected);
|
||||
for (const type of HOSTILE) {
|
||||
let ok = !prot && has(type), reason = prot ? 'target_protected' : 'no_units';
|
||||
if (ok && type === 'takeover' && !(home[D.EXPANSION.conquestUnit] > 0)) { ok = false; reason = 'needs_ma_team'; }
|
||||
add(type, ok, reason);
|
||||
}
|
||||
if (c.allianceId && t.town.owner && t.town.owner.allianceId === c.allianceId) add('reinforce', has('reinforce'), 'no_units');
|
||||
}
|
||||
} else if (t.type === 'incumbent') {
|
||||
add('scan', has('scan'), 'no_units');
|
||||
add('attack', has('attack'), 'no_units');
|
||||
} else if (t.type === 'land') {
|
||||
const s = t.settle || {};
|
||||
if (!s.possible) add('settle', false, 'settle:' + (s.code || 'invalid_target'));
|
||||
else add('settle', (c.crews || 0) >= D.EXPANSION.crews, 'needs_crews');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Default selection when a type is picked: settle takes exactly the crews, everything else starts empty.
|
||||
function defaultUnits(type, home) {
|
||||
if (type === 'settle') { const o = {}; o[D.EXPANSION.settleUnit] = D.EXPANSION.crews; return o; }
|
||||
return {};
|
||||
}
|
||||
|
||||
// Drop zero entries and clamp to what is at home.
|
||||
function cleanSelection(sel, home) {
|
||||
const out = {};
|
||||
for (const k of Object.keys(sel || {})) {
|
||||
const n = Math.max(0, Math.min(Math.floor(sel[k] || 0), (home && home[k]) || 0));
|
||||
if (n > 0) out[k] = n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Preview of a movement: distance, latency (ms), carry capacity, slowest unit.
|
||||
function preview(type, from, to, units, cargo, worldSpeed) {
|
||||
const dist = R.distance(from.x, from.y, to.x, to.y);
|
||||
const ms = type === 'transport' ? R.transportMs(dist, worldSpeed) : R.movementMs(dist, units, worldSpeed);
|
||||
const s = R.slowestSpeed(units);
|
||||
return { dist, ms, carry: R.carryOf(units), slowest: isFinite(s) ? s : null };
|
||||
}
|
||||
|
||||
const isHostile = (type) => HOSTILE.indexOf(type) >= 0;
|
||||
|
||||
// Report perspective: did *I* win? role is the recipient role of the report.
|
||||
function perspective(role, outcome) {
|
||||
const attackerSide = role === 'attacker';
|
||||
const attackerWon = outcome === 'attacker_won';
|
||||
return attackerSide === attackerWon ? 'victory' : 'defeat';
|
||||
}
|
||||
|
||||
// When units that went offline are decommissioned (ms, server clock).
|
||||
const decommissionAt = (offlineSince, speed) => offlineSince + R.decommissionMs(speed);
|
||||
|
||||
// Reconnect delay for the WebSocket: exponential from 1 s, capped at 60 s, +-25% jitter (rnd in [0,1)).
|
||||
function backoffMs(attempt, rnd) {
|
||||
const base = Math.min(60000, 1000 * Math.pow(2, Math.min(attempt, 10)));
|
||||
return Math.round(base * (0.75 + 0.5 * (rnd === undefined ? Math.random() : rnd)));
|
||||
}
|
||||
|
||||
const sumUnits = (u) => Object.keys(u || {}).reduce((s, k) => s + (u[k] || 0), 0);
|
||||
|
||||
// Exploit-kit target choices: infrastructure types (the server also takes f1..f18 slots; the client does not know them).
|
||||
function siegeTargets() {
|
||||
return Object.keys(D.BUILDINGS).filter((k) => D.BUILDINGS[k].kind === 'infra' && !D.BUILDINGS[k].special);
|
||||
}
|
||||
|
||||
return { TYPES, HOSTILE, ROLE_ICON, TYPE_ICON, unitsForType, moveOptions, defaultUnits, cleanSelection, preview, isHostile, perspective, decommissionAt, backoffMs, sumUnits, siegeTargets };
|
||||
}));
|
||||
167
public/js/milstate.js
Normal file
167
public/js/milstate.js
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Shared state and small view helpers of the military / expansion screens (browser only; loads after main.js).
|
||||
*
|
||||
* App.mil.moves { outgoing, incoming, at }: the last GET /movements, the single source for the nav badge,
|
||||
* the POP banner, the movements screen and the map lines. Emits App.emit('movements').
|
||||
* App.refreshMovements() refetch it (coalesced). Called by the ticker when something arrived, by push, by the poll.
|
||||
* App.refreshReportsUnread() refetch the unread count of reports (nav badge on Reports).
|
||||
* App.refreshTowns() refetch /me and update the POP list WITHOUT resetting the session (after a settle/takeover).
|
||||
* App.mil.* helpers unitName, unitsText, typeLabel, coordLink, countdown, chips ...
|
||||
*
|
||||
* Countdowns are elements with data-cd = server-clock deadline in ms; one ticker keeps all of them current, so screens
|
||||
* only create them (mil.countdown) and never run their own timers for display.
|
||||
*/
|
||||
(function () {
|
||||
const { h, icon } = UI;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
const api = App.api;
|
||||
|
||||
const mil = App.mil = { moves: { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false }, reportsUnread: 0 };
|
||||
|
||||
// ------------------------------------------------------------------ names and small pieces
|
||||
mil.unitName = (id) => (UpstreamI18n.strings.en['unit.' + id + '.name'] ? App.t('unit.' + id + '.name') : id);
|
||||
mil.unitDesc = (id) => (UpstreamI18n.strings.en['unit.' + id + '.desc'] ? App.t('unit.' + id + '.desc') : '');
|
||||
mil.typeLabel = (type) => (UpstreamI18n.strings.en['move.type.' + type] ? App.t('move.type.' + type) : type);
|
||||
mil.reportTypeLabel = (type) => (UpstreamI18n.strings.en['report.type.' + type] ? App.t('report.type.' + type) : type);
|
||||
mil.unitIcon = (id) => icon(Mil.ROLE_ICON[(D.UNITS[id] || {}).role] || 'units');
|
||||
mil.townName = (id) => { const t = App.state.towns.find((x) => x.id === id); return t ? t.name : null; };
|
||||
mil.ownTown = (id) => App.state.towns.find((x) => x.id === id) || null;
|
||||
|
||||
// "3 × Script crew, 2 × Botnet"
|
||||
mil.unitsText = (units) => {
|
||||
const parts = [];
|
||||
for (const u of D.UNIT_ORDER) if (units && units[u] > 0) parts.push(App.fmt.num(units[u]) + ' × ' + mil.unitName(u));
|
||||
return parts.length ? parts.join(', ') : '—';
|
||||
};
|
||||
|
||||
// Clock time (local) at server time `ms`.
|
||||
mil.clockTime = (ms) => {
|
||||
try { return new Date(ms).toLocaleTimeString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
|
||||
};
|
||||
mil.dayTime = (ms) => {
|
||||
try { return new Date(ms).toLocaleString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
|
||||
};
|
||||
|
||||
// A link that jumps to the map at (x, y). Closes any sheet first.
|
||||
mil.coordLink = (x, y, label) => h('button', { class: 'mil-coord mono', type: 'button', 'aria-label': App.t('mil.showOnMap', { x, y }), onclick: () => { UI.closeSheet(); App.go('map', { x, y, zoom: 40 }); } },
|
||||
icon('map'), label || (x + ', ' + y));
|
||||
|
||||
// A movement endpoint ({ townId, x, y, name, owner? }) as text + coordinates link.
|
||||
mil.endLink = (end) => h('span', { class: 'mil-end' }, end.name ? h('span', { class: 'mil-end-name', text: end.name }) : null, mil.coordLink(end.x, end.y));
|
||||
|
||||
// Resource chips: { fiber, hardware, capital } (zero entries are skipped).
|
||||
mil.resChips = (res, signed) => {
|
||||
const out = [];
|
||||
for (const r of D.RESOURCES) if (res && res[r]) out.push(h('span', { class: 'cost ' + r }, icon(r), h('b', { text: (signed ? '+' : '') + App.fmt.num(res[r]) })));
|
||||
return h('div', { class: 'costs' }, out.length ? out : h('span', { class: 'dimmer', text: '—' }));
|
||||
};
|
||||
|
||||
// <b class="mono" data-cd="<deadline ms>">m:ss</b>, kept current by the ticker below.
|
||||
mil.countdown = (deadline, opts) => {
|
||||
const el = h('b', { class: 'mono mil-cd' + (opts && opts.cls ? ' ' + opts.cls : ''), dataset: { cd: String(deadline) } });
|
||||
el.textContent = App.fmt.clock(deadline - App.now());
|
||||
return el;
|
||||
};
|
||||
|
||||
// Progress 0..1 of a movement.
|
||||
mil.progress = (m, now) => Math.max(0, Math.min(1, (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt)));
|
||||
|
||||
// ------------------------------------------------------------------ the ticker: countdowns + "something arrived" refetch
|
||||
let lastMovesFetch = 0;
|
||||
App.onTick((now) => {
|
||||
for (const el of document.querySelectorAll('[data-cd]')) {
|
||||
const s = App.fmt.clock(Number(el.dataset.cd) - now);
|
||||
if (el.textContent !== s) el.textContent = s;
|
||||
}
|
||||
if (!App.state.user || !mil.moves.loaded) return;
|
||||
// a movement is over (arrived / returned): the server dropped it, so refetch (retry no more often than every 3 s)
|
||||
const due = mil.moves.outgoing.concat(mil.moves.incoming, mil.moves.alliedIncoming || []).some((m) => m.arriveAt - now < -600);
|
||||
if (due && Date.now() - lastMovesFetch > 3000) { lastMovesFetch = Date.now(); App.refreshMovements().catch(() => {}); }
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ refetchers
|
||||
let movesFlight = null;
|
||||
App.refreshMovements = () => {
|
||||
if (!App.state.user) return Promise.resolve(null);
|
||||
if (movesFlight) return movesFlight;
|
||||
lastMovesFetch = Date.now();
|
||||
movesFlight = api.get('/movements').then((r) => {
|
||||
// a settle that is no longer on the wire has resolved: the POP list changed (the push-less path to the same refresh)
|
||||
const settled = mil.moves.loaded && mil.moves.outgoing.some((m) => m.type === 'settle' && !(r.outgoing || []).some((n) => n.id === m.id));
|
||||
if (settled) App.refreshTowns().catch(() => {});
|
||||
mil.moves = { outgoing: r.outgoing || [], incoming: r.incoming || [], alliedIncoming: r.alliedIncoming || [], at: r.serverTime, loaded: true };
|
||||
App.setBadge('movements', mil.moves.incoming.length, 'alert');
|
||||
App.emit('movements', mil.moves);
|
||||
return mil.moves;
|
||||
}).finally(() => { movesFlight = null; });
|
||||
return movesFlight;
|
||||
};
|
||||
|
||||
let reportsFlight = null;
|
||||
App.refreshReportsUnread = () => {
|
||||
if (!App.state.user) return Promise.resolve(null);
|
||||
if (reportsFlight) return reportsFlight;
|
||||
reportsFlight = api.get('/reports', { limit: 1 }).then((r) => {
|
||||
mil.reportsUnread = r.unread || 0;
|
||||
App.setBadge('reports', mil.reportsUnread, 'info');
|
||||
App.emit('reportsUnread', mil.reportsUnread);
|
||||
return mil.reportsUnread;
|
||||
}).finally(() => { reportsFlight = null; });
|
||||
return reportsFlight;
|
||||
};
|
||||
|
||||
// The POP list changed (founded, conquered, lost): refresh /me without the destructive parts of setSession.
|
||||
let townsFlight = null;
|
||||
const townSig = (list) => list.map((t) => t.id + ':' + t.name + ':' + (t.isCapital ? 1 : 0)).join('|');
|
||||
App.refreshTowns = () => {
|
||||
const st = App.state;
|
||||
if (!st.user) return Promise.resolve();
|
||||
if (townsFlight) return townsFlight;
|
||||
townsFlight = (async () => {
|
||||
const me = await api.get('/me');
|
||||
const op = (me.operators || [])[0] || null;
|
||||
if (!op) return;
|
||||
const before = townSig(st.towns);
|
||||
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
|
||||
let gone = false;
|
||||
if (!st.towns.some((t) => t.id === st.townId)) {
|
||||
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;
|
||||
st.townId = pick ? pick.id : null; st.townData = null; gone = true;
|
||||
}
|
||||
// only a real change rebuilds the screens (a redraw resets the scroll position, and this runs on every poll)
|
||||
if (gone) { App.emit('townchange', st.townId); if (st.townId) App.refreshTown().catch(() => {}); }
|
||||
if (gone || townSig(st.towns) !== before) App.emit('towns', st.towns);
|
||||
})().finally(() => { townsFlight = null; });
|
||||
return townsFlight;
|
||||
};
|
||||
|
||||
// Another of the player's POPs (GET /towns/:id), for the send dialog. -> { town, serverTime }
|
||||
mil.loadTown = (id) => api.get('/towns/' + id);
|
||||
|
||||
App.on('session', (st) => {
|
||||
if (st && st.user) { App.refreshMovements().catch(() => {}); App.refreshReportsUnread().catch(() => {}); return; }
|
||||
mil.moves = { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false };
|
||||
mil.reportsUnread = 0;
|
||||
App.setBadge('movements', 0, 'alert'); App.setBadge('reports', 0, 'info');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ the notification feed (screens/alerts.js) learns our types
|
||||
const kinds = App.alertKinds;
|
||||
const townTxt = (id) => mil.townName(id) || '#' + id;
|
||||
kinds.incoming = (n, p) => ({ icon: 'alert', title: App.t('alerts.incoming'), detail: App.t('alerts.incoming.at', { town: townTxt(p.toTownId), time: mil.clockTime(p.arriveAt) }), go: 'movements' });
|
||||
kinds.report = (n, p) => ({ icon: 'report', title: App.t('alerts.report', { type: mil.reportTypeLabel(p.type) }), detail: '', go: 'reports', params: { open: p.reportId } });
|
||||
kinds.train_done = (n, p) => ({ icon: 'units', title: App.t('alerts.train_done', { n: App.fmt.num(p.count), unit: mil.unitName(p.unit) }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
|
||||
kinds.research_done = (n, p) => ({ icon: 'flask', title: App.t('alerts.research_done', { unit: mil.unitName(p.unit), stat: App.t('stat.' + p.stat), level: p.level }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
|
||||
kinds.movement_returned = (n, p) => ({ icon: 'return', title: App.t('alerts.movement_returned'), detail: [mil.unitsText(p.units)].concat(D.RESOURCES.some((r) => p.cargo && p.cargo[r]) ? [Object.keys(p.cargo).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', ')] : []).join(' · '), go: 'movements' });
|
||||
kinds.movement_lost = () => ({ icon: 'alert', title: App.t('alerts.movement_lost'), detail: '', go: 'movements' });
|
||||
kinds.transport_arrived = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_arrived', { town: townTxt(p.townId) }), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' });
|
||||
kinds.transport_delivered = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_delivered'), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' });
|
||||
kinds.units_offline = (n, p) => ({ icon: 'power', title: App.t('alerts.units_offline'), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
|
||||
kinds.units_decommissioned = (n, p) => ({ icon: 'power', title: App.t('alerts.units_decommissioned'), detail: mil.unitsText(p.units), go: 'units' });
|
||||
kinds.town_lost = (n, p) => ({ icon: 'alert', title: App.t('alerts.town_lost', { name: p.name }), detail: p.by ? App.t('alerts.town_lost.by', { name: p.by.name }) : '', go: 'pop' });
|
||||
kinds.town_gained = (n, p) => ({ icon: 'pop', title: App.t('alerts.town_gained', { name: p.name }), detail: '', go: 'pop' });
|
||||
kinds.reinforcements_sent_home = (n, p) => ({ icon: 'return', title: App.t('alerts.reinforcements_home'), detail: mil.unitsText(p.units), go: 'units' });
|
||||
|
||||
}());
|
||||
|
|
@ -6,6 +6,8 @@
|
|||
* 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
|
||||
* source.movements() -> [{ from: {x,y}, to: {x,y}, kind: 'out' | 'in' | 'ret' | 'ally', p: 0..1 }] optional: lines with a marker at progress p
|
||||
* source.threatened(town) -> bool optional: an incoming movement is heading for this own POP (red ring)
|
||||
* 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 }
|
||||
*
|
||||
|
|
@ -292,6 +294,7 @@
|
|||
}
|
||||
ctx.restore();
|
||||
}
|
||||
if (this.src.movements) this._movements(this.src.movements());
|
||||
for (const t of towns) this._pop(t);
|
||||
|
||||
// world border
|
||||
|
|
@ -365,6 +368,10 @@
|
|||
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 (own && this.src.threatened && this.src.threatened(t)) {
|
||||
ctx.strokeStyle = '#ff6b87'; ctx.lineWidth = Math.max(2, z * 0.08);
|
||||
this._hex(s.x, s.y, rad + Math.max(4, z * 0.2)); 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([]);
|
||||
|
|
@ -380,6 +387,35 @@
|
|||
}
|
||||
}
|
||||
|
||||
// Movement lines: dashed, cyan outgoing, red incoming, dim return legs, green allied traffic; a marker sits at progress p.
|
||||
_movements(list) {
|
||||
const { ctx, zoom: z } = this;
|
||||
const col = { out: COLORS.own, in: '#ff6b87', ret: 'rgba(155,178,214,0.8)', ally: '#35e0a1' };
|
||||
ctx.save();
|
||||
ctx.lineCap = 'round';
|
||||
for (const m of list) {
|
||||
const a = this.toScreen(m.from.x, m.from.y), b = this.toScreen(m.to.x, m.to.y);
|
||||
if (Math.max(a.x, b.x) < -20 || Math.min(a.x, b.x) > this.w + 20 || Math.max(a.y, b.y) < -20 || Math.min(a.y, b.y) > this.h + 20) continue;
|
||||
const c = col[m.kind] || COLORS.own;
|
||||
ctx.strokeStyle = c; ctx.fillStyle = c;
|
||||
ctx.globalAlpha = m.kind === 'ret' ? 0.55 : 0.85;
|
||||
ctx.lineWidth = m.kind === 'in' ? 2.4 : 1.6;
|
||||
ctx.setLineDash(m.kind === 'in' ? [3, 5] : [7, 6]);
|
||||
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
const p = Math.max(0, Math.min(1, m.p));
|
||||
const px = a.x + (b.x - a.x) * p, py = a.y + (b.y - a.y) * p;
|
||||
const ang = Math.atan2(b.y - a.y, b.x - a.x), r = Math.max(4, Math.min(8, z * 0.3));
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(px + Math.cos(ang) * r, py + Math.sin(ang) * r);
|
||||
ctx.lineTo(px + Math.cos(ang + 2.5) * r, py + Math.sin(ang + 2.5) * r);
|
||||
ctx.lineTo(px + Math.cos(ang - 2.5) * r, py + Math.sin(ang - 2.5) * r);
|
||||
ctx.closePath(); ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
_selection(sel) {
|
||||
const { ctx, zoom: z } = this;
|
||||
const s = this.toScreen(sel.x, sel.y);
|
||||
|
|
|
|||
|
|
@ -52,7 +52,19 @@
|
|||
// ------------------------------------------------------------------ the map
|
||||
// Pure function of the world seed: 'land' | 'rural' | 'incumbent' | 'void' (outside the map). A rural tile also
|
||||
// says which resource it boosts. Towns are not part of this; they live in the database.
|
||||
function tileAt(seed, radius, x, y) {
|
||||
// `ageDays` (optional, world days) adds the end game: from D.ENDGAME.openDay on, the landing sites report 'backbone'
|
||||
// (with `site`: its index). Without it (old callers, previews without a clock) the map is the plain terrain.
|
||||
// Terrain never changes: a landing site is always a land tile underneath, see backboneSites.
|
||||
function tileAt(seed, radius, x, y, ageDays) {
|
||||
const t = terrainAt(seed, radius, x, y);
|
||||
if (t.type === 'land' && ageDays !== undefined && ageDays >= D.ENDGAME.openDay) {
|
||||
const s = backboneSiteAt(seed, radius, x, y);
|
||||
if (s) return { type: 'backbone', site: s.index };
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
function terrainAt(seed, radius, x, y) {
|
||||
if (Math.abs(x) > radius || Math.abs(y) > radius) return { type: 'void' };
|
||||
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) return { type: 'land' }; // keep the centre free
|
||||
const h = hash(seed, x, y) / 4294967296;
|
||||
|
|
@ -64,6 +76,54 @@
|
|||
return { type: 'land' };
|
||||
}
|
||||
|
||||
// The backbone landing sites: D.ENDGAME.sites fixed positions, a pure function of (seed, radius). One per sector of the
|
||||
// circle (jittered), on plain land tiles between siteRingMin and siteRingMax of the radius, never in the free centre and
|
||||
// at least siteMinSpacing apart. They exist from the start (spawn and settling refuse them) but only SHOW from openDay.
|
||||
// -> [{ index, x, y }]
|
||||
const siteCache = new Map();
|
||||
function backboneSites(seed, radius) {
|
||||
const key = seed + '|' + radius;
|
||||
if (siteCache.has(key)) return siteCache.get(key);
|
||||
const E = D.ENDGAME;
|
||||
const out = [];
|
||||
for (let k = 0; k < E.sites; k++) {
|
||||
const rand = rng(hash(seed, k, 0xb4cb));
|
||||
const ang = (k + 0.15 + 0.7 * rand()) * 2 * Math.PI / E.sites;
|
||||
const rr = radius * (E.siteRingMin + (E.siteRingMax - E.siteRingMin) * rand());
|
||||
const cx = Math.round(Math.cos(ang) * rr), cy = Math.round(Math.sin(ang) * rr);
|
||||
let found = null;
|
||||
for (let d = 0; d <= radius && !found; d++) { // spiral outwards until a free land tile turns up
|
||||
for (let dy = -d; dy <= d && !found; dy++) {
|
||||
for (let dx = -d; dx <= d && !found; dx++) {
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) !== d) continue;
|
||||
const x = cx + dx, y = cy + dy;
|
||||
if (terrainAt(seed, radius, x, y).type !== 'land') continue;
|
||||
if (Math.abs(x) <= 2 && Math.abs(y) <= 2) continue;
|
||||
if (out.some((s) => distance(s.x, s.y, x, y) < E.siteMinSpacing)) continue;
|
||||
found = { index: k, x, y };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (found) out.push(found);
|
||||
}
|
||||
if (siteCache.size > 64) siteCache.clear();
|
||||
siteCache.set(key, out);
|
||||
return out;
|
||||
}
|
||||
function backboneSiteAt(seed, radius, x, y) {
|
||||
for (const s of backboneSites(seed, radius)) if (s.x === x && s.y === y) return s;
|
||||
return null;
|
||||
}
|
||||
const isBackboneSite = (seed, radius, x, y) => !!backboneSiteAt(seed, radius, x, y);
|
||||
|
||||
// World age in world days (real days * speed). Negative ages are 0.
|
||||
function worldAgeDays(startAt, now, speed) { return Math.max(0, (now - startAt) / DAY * (speed || 1)); }
|
||||
// 'running' | 'backbone_open' | 'ended'.
|
||||
function worldPhase(status, ageDays) {
|
||||
if (status === 'ended') return 'ended';
|
||||
return ageDays >= D.ENDGAME.openDay ? 'backbone_open' : 'running';
|
||||
}
|
||||
|
||||
// Rural areas within reach of (x, y): the tiles whose bonus a POP there enjoys. Biggest bonus counts max 3.
|
||||
function ruralNear(seed, radius, x, y) {
|
||||
const out = [];
|
||||
|
|
@ -101,7 +161,7 @@
|
|||
const ang = rand() * Math.PI * 2;
|
||||
const rr = lo + rand() * (hi - lo);
|
||||
const x = Math.round(Math.cos(ang) * rr), y = Math.round(Math.sin(ang) * rr);
|
||||
if (tileAt(seed, radius, x, y).type !== 'land') continue;
|
||||
if (tileAt(seed, radius, x, y).type !== 'land' || isBackboneSite(seed, radius, x, y)) continue;
|
||||
if (near(x, y)) continue;
|
||||
return { x, y };
|
||||
}
|
||||
|
|
@ -577,6 +637,7 @@
|
|||
|
||||
// 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.backbone) return { ok: false, code: 'invalid_target', reason: 'backbone_site' }; // landing sites are taken, never settled
|
||||
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);
|
||||
|
|
@ -654,8 +715,62 @@
|
|||
return { ok: true, total };
|
||||
}
|
||||
|
||||
// ---- trade (Internet exchange offers: give X of A for Y of B, max distance Z)
|
||||
// How far (tiles) a POP with this Internet exchange level sees and trades. Level 0 = no exchange = 0.
|
||||
const tradeReach = (level) => (level > 0 ? level * D.TRADE.reachPerLevel : 0);
|
||||
// Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])?
|
||||
const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax;
|
||||
// Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed,
|
||||
// trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does.
|
||||
function tradeTermsCheck(o) {
|
||||
const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] });
|
||||
if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', '));
|
||||
if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', '));
|
||||
if (o.giveRes === o.wantRes) return bad('wantRes', 'must differ from giveRes');
|
||||
if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1');
|
||||
if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1');
|
||||
if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance);
|
||||
const cap = D.TRANSPORT.capacityPerLink;
|
||||
if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap };
|
||||
if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax };
|
||||
return { ok: true };
|
||||
}
|
||||
// May a POP at `dist` tiles with Internet exchange `level` take an offer (max distance `maxDistance`)? Both the offer's own
|
||||
// limit and the taker's reach apply.
|
||||
const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level);
|
||||
|
||||
// ---- end game: backbone landing sites
|
||||
// Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level.
|
||||
function backboneDefence(seed, x, y, ageDays, level) {
|
||||
return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0)));
|
||||
}
|
||||
// Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource.
|
||||
function backboneCost(level) {
|
||||
const def = D.BUILDINGS.backbone_node;
|
||||
const out = {};
|
||||
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * Math.pow(D.ENDGAME.costGrowth, level - 1));
|
||||
return out;
|
||||
}
|
||||
function backboneTimeMs(level, speed) {
|
||||
return Math.max(F.minBuildMs, Math.round(D.BUILDINGS.backbone_node.time * Math.pow(D.ENDGAME.timeGrowth, level - 1) / (speed || 1) * 1000));
|
||||
}
|
||||
// Can the holder alliance start the next level? site = { level, build (null | { to }), pool: { fiber, hardware, capital } }. Codes: max_level, already_queued, not_enough_resources.
|
||||
function backbonePlan(site, speed) {
|
||||
const toLevel = site.level + 1;
|
||||
const base = { ok: false, fromLevel: site.level, toLevel };
|
||||
if (toLevel > D.ENDGAME.maxLevel) return Object.assign(base, { code: 'max_level' });
|
||||
base.cost = backboneCost(toLevel);
|
||||
base.durationMs = backboneTimeMs(toLevel, speed);
|
||||
if (site.build) return Object.assign(base, { code: 'already_queued' });
|
||||
for (const r of D.RESOURCES) if ((site.pool[r] || 0) + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
|
||||
base.ok = true;
|
||||
return base;
|
||||
}
|
||||
|
||||
return {
|
||||
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,
|
||||
terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange,
|
||||
backboneDefence, backboneCost, backboneTimeMs, backbonePlan,
|
||||
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
|
||||
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
|
||||
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@
|
|||
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' };
|
||||
}
|
||||
// Other screens describe their own notification types: App.alertKinds[type] = (n, p) => ({ icon, title, detail, go, params })
|
||||
const ext = App.alertKinds && App.alertKinds[n.type];
|
||||
if (ext) return ext(n, p);
|
||||
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +31,7 @@
|
|||
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('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go, d.params); } },
|
||||
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),
|
||||
|
|
@ -57,7 +60,7 @@
|
|||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
|
||||
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('ul', { class: 'alert-list' });
|
||||
|
|
|
|||
542
public/js/screens/alliance.js
Normal file
542
public/js/screens/alliance.js
Normal file
|
|
@ -0,0 +1,542 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Alliance screen. Not in an alliance: found one (Peering office needed) and answer invitations. In one: overview with pinned
|
||||
* notes, members (role changes, kick, transfer, invite), diplomacy. What is offered follows data.js SOCIAL.permissions through
|
||||
* rules.js allianceCan/outranks (via UpstreamSocial); the server re-checks everything and its error codes are translated.
|
||||
* Every player-controlled string is set with textContent.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const S = D.SOCIAL;
|
||||
const X = () => window.SocUI;
|
||||
|
||||
let box, body, tabsEl, content;
|
||||
let mine = null; // GET /alliances/mine
|
||||
let members = null; // GET /alliances/:id/members items
|
||||
let tab = 'overview';
|
||||
let gen = 0; // bumped on every load: stale async results are dropped
|
||||
let offTick = null;
|
||||
const cache = {}; // per-tab data
|
||||
|
||||
const myRole = () => (mine ? mine.role : null);
|
||||
const acts = () => Soc.selfActions(myRole(), members ? members.length : (mine && mine.alliance ? mine.alliance.memberCount : 0));
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
|
||||
// ------------------------------------------------------------------ load
|
||||
async function load() {
|
||||
const my = ++gen;
|
||||
const had = !!mine;
|
||||
if (!had) { clear(body); body.appendChild(X().loading()); }
|
||||
try {
|
||||
const m = await App.api.get('/alliances/mine');
|
||||
if (my !== gen) return;
|
||||
mine = m;
|
||||
const al = m.alliance;
|
||||
const cur = X().myAlliance();
|
||||
if ((al && (!cur || cur.id !== al.id)) || (!al && cur)) X().refreshOperator().catch(() => {});
|
||||
if (al) {
|
||||
const r = await App.api.get('/alliances/' + al.id + '/members');
|
||||
if (my !== gen) return;
|
||||
members = r.items;
|
||||
for (const k of Object.keys(cache)) delete cache[k];
|
||||
drawIn();
|
||||
} else {
|
||||
members = null;
|
||||
const inv = await App.api.get('/alliance-invites');
|
||||
if (my !== gen) return;
|
||||
cache.invites = inv.items;
|
||||
drawNone();
|
||||
}
|
||||
} catch (e) {
|
||||
if (my !== gen) return;
|
||||
clear(body);
|
||||
body.appendChild(X().errorBox(e, load));
|
||||
}
|
||||
}
|
||||
|
||||
// Reload after a change of membership (found, join, leave, kick...).
|
||||
function reload() { mine = null; members = null; tab = 'overview'; return load(); }
|
||||
|
||||
// ------------------------------------------------------------------ not in an alliance
|
||||
function drawNone() {
|
||||
clear(body);
|
||||
stopTick();
|
||||
const have = mine.peeringLevel, need = S.minPeeringLevel, ok = have >= need;
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const nameIn = h('input', { type: 'text', maxlength: String(S.nameLen[1] * 2), autocomplete: 'off', autocapitalize: 'words', spellcheck: 'false', id: 'soc-name' });
|
||||
const tagIn = h('input', { type: 'text', maxlength: String(S.tagLen[1]), autocomplete: 'off', autocapitalize: 'characters', spellcheck: 'false', id: 'soc-tag' });
|
||||
const create = h('button', { class: 'btn primary wide', type: 'button' }, icon('plus'), App.t('soc.create.go'));
|
||||
const valid = () => {
|
||||
const n = Array.from(Soc.cleanName(nameIn.value)).length, t = tagIn.value.trim();
|
||||
return ok && n >= S.nameLen[0] && n <= S.nameLen[1] && /^[A-Za-z0-9]+$/.test(t) && t.length >= S.tagLen[0] && t.length <= S.tagLen[1];
|
||||
};
|
||||
const sync = () => { create.disabled = !valid(); };
|
||||
nameIn.addEventListener('input', sync); tagIn.addEventListener('input', sync);
|
||||
create.addEventListener('click', () => X().guard(create, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
await App.api.post('/alliances', { name: Soc.cleanName(nameIn.value), tag: tagIn.value.trim() }, { intent: 'ally:create' });
|
||||
toast(App.t('soc.create.done'), 'ok');
|
||||
await reload();
|
||||
} catch (e) {
|
||||
err.textContent = e.code === 'validation_failed' ? App.t('soc.create.invalid', { n1: S.nameLen[0], n2: S.nameLen[1], t1: S.tagLen[0], t2: S.tagLen[1] }) : X().err(e);
|
||||
err.hidden = false;
|
||||
}
|
||||
}));
|
||||
sync();
|
||||
|
||||
body.appendChild(h('div', { class: 'card soc-card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.create.title'))),
|
||||
h('p', { class: 'detail-desc', text: App.t('soc.create.intro') }),
|
||||
h('ul', { class: 'reqs soc-req' }, h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
|
||||
h('span', { text: App.buildingName('peering_office') + ' ' + App.t('pop.level', { n: need }) }), h('small', { text: App.t('sheet.have', { n: have }) }))),
|
||||
ok ? null : h('p', { class: 'reason', text: App.t('soc.create.needOffice', { building: App.buildingName('peering_office'), n: need }) }),
|
||||
h('label', { class: 'field', for: 'soc-name' }, h('span', { class: 'field-lbl', text: App.t('soc.create.name') }), nameIn,
|
||||
h('span', { class: 'field-hint', text: App.t('soc.create.nameHint', { a: S.nameLen[0], b: S.nameLen[1] }) })),
|
||||
h('label', { class: 'field', for: 'soc-tag' }, h('span', { class: 'field-lbl', text: App.t('soc.create.tag') }), tagIn,
|
||||
h('span', { class: 'field-hint', text: App.t('soc.create.tagHint', { a: S.tagLen[0], b: S.tagLen[1] }) })),
|
||||
err, create));
|
||||
|
||||
const invCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invites.title')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))));
|
||||
const items = cache.invites || [];
|
||||
if (!items.length) invCard.appendChild(h('p', { class: 'empty', text: App.t('soc.invites.none') }));
|
||||
else {
|
||||
if (!ok) invCard.appendChild(h('p', { class: 'reason', text: App.t('soc.invites.needOffice', { building: App.buildingName('peering_office') }) }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
const now = App.now();
|
||||
for (const inv of items) {
|
||||
const e2 = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const acc = h('button', { class: 'btn small primary', type: 'button', text: App.t('soc.invites.accept') });
|
||||
const dec = h('button', { class: 'btn small', type: 'button', text: App.t('soc.invites.decline') });
|
||||
const answer = (accept) => X().guard(accept ? acc : dec, async () => {
|
||||
e2.hidden = true;
|
||||
try {
|
||||
await App.api.post('/alliance-invites/' + inv.id + (accept ? '/accept' : '/decline'), {}, { intent: 'ally:invite:' + inv.id });
|
||||
toast(App.t(accept ? 'soc.invites.accepted' : 'soc.invites.declined'), 'ok');
|
||||
await reload();
|
||||
} catch (e) { e2.textContent = X().err(e); e2.hidden = false; }
|
||||
});
|
||||
acc.addEventListener('click', () => answer(true));
|
||||
dec.addEventListener('click', () => answer(false));
|
||||
list.appendChild(h('li', { class: 'soc-item soc-invite' },
|
||||
h('div', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, X().tagPill(inv.alliance.tag), h('b', { text: inv.alliance.name })),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
|
||||
h('div', { class: 'soc-actions' }, dec, acc), e2));
|
||||
}
|
||||
invCard.appendChild(list);
|
||||
}
|
||||
body.appendChild(invCard);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ in an alliance
|
||||
function drawIn() {
|
||||
clear(body);
|
||||
stopTick();
|
||||
const a = mine.alliance;
|
||||
const sizeP = a.sizeCap > 0 ? Math.min(1, a.memberCount / a.sizeCap) : 0;
|
||||
body.appendChild(h('div', { class: 'card soc-card soc-head' },
|
||||
h('div', { class: 'soc-title' }, X().tagPill(a.tag), h('h2', { class: 'soc-name', text: a.name })),
|
||||
h('div', { class: 'pill-row' }, X().rolePill(mine.role),
|
||||
h('span', { class: 'pill', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) }),
|
||||
h('span', { class: 'pill', text: App.t('soc.leaderIs', { name: a.leader ? a.leader.name : '-' }) })),
|
||||
h('div', { class: 'bar', 'aria-hidden': 'true', style: { '--p': String(sizeP) } }, h('i'))));
|
||||
|
||||
const tabs = [['overview', 'soc.tab.overview'], ['members', 'soc.tab.members'], ['diplomacy', 'soc.tab.diplomacy']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
|
||||
content = h('div', { class: 'soc-content' });
|
||||
body.appendChild(tabsEl);
|
||||
body.appendChild(content);
|
||||
drawTab();
|
||||
}
|
||||
|
||||
function setTab(id) {
|
||||
tab = id;
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === id));
|
||||
drawTab();
|
||||
}
|
||||
|
||||
function drawTab() {
|
||||
stopTick();
|
||||
clear(content);
|
||||
if (tab === 'members') drawMembers();
|
||||
else if (tab === 'diplomacy') drawDiplomacy();
|
||||
else drawOverview();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- overview: notes, leave / disband
|
||||
const nameOf = (id) => { const m = (members || []).find((x) => x.operatorId === id); return m ? m.name : '#' + id; };
|
||||
|
||||
async function drawOverview() {
|
||||
const my = gen;
|
||||
const A = acts();
|
||||
const notesCard = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('pencil'), App.t('soc.notes.title')),
|
||||
h('span', { class: 'pill dim mono', id: 'soc-notes-count' })));
|
||||
const notesList = h('ul', { class: 'soc-list' });
|
||||
notesCard.appendChild(notesList);
|
||||
content.appendChild(notesCard);
|
||||
|
||||
function drawNotes(items) {
|
||||
clear(notesList);
|
||||
notesCard.querySelector('#soc-notes-count').textContent = items.length + '/' + S.maxNotes;
|
||||
if (!items.length) notesList.appendChild(h('li', { class: 'empty', text: App.t('soc.notes.none') }));
|
||||
for (const n of items) {
|
||||
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.notes.remove'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/notes/' + n.id);
|
||||
cache.notes = cache.notes.filter((x) => x.id !== n.id);
|
||||
drawNotes(cache.notes);
|
||||
}) }, icon('x'));
|
||||
notesList.appendChild(h('li', { class: 'soc-item soc-note' },
|
||||
h('div', { class: 'row-main' }, h('p', { class: 'soc-text-out', text: n.text }),
|
||||
h('span', { class: 'row-sub', text: nameOf(n.authorId) + ' · ' + App.fmt.ago(App.now() - n.createdAt) })),
|
||||
A.editNotes ? del : null));
|
||||
}
|
||||
}
|
||||
|
||||
if (A.editNotes) {
|
||||
const ta = h('textarea', { class: 'soc-text', rows: 2, maxlength: String(S.noteMax * 2), 'aria-label': App.t('soc.notes.add'), placeholder: App.t('soc.notes.placeholder') });
|
||||
const cnt = h('span', { class: 'soc-count mono' });
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const add = h('button', { class: 'btn small primary', type: 'button' }, icon('plus'), App.t('soc.notes.add'));
|
||||
const sync = () => {
|
||||
const st = Soc.composeState(ta.value, S.noteMax);
|
||||
cnt.textContent = st.n + '/' + S.noteMax; cnt.classList.toggle('over', st.over);
|
||||
add.disabled = st.empty || st.over || (cache.notes && cache.notes.length >= S.maxNotes);
|
||||
};
|
||||
ta.addEventListener('input', sync);
|
||||
add.addEventListener('click', () => X().guard(add, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/notes', { text: ta.value });
|
||||
cache.notes = (cache.notes || []).concat([r.note]);
|
||||
ta.value = '';
|
||||
drawNotes(cache.notes); sync();
|
||||
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
|
||||
}));
|
||||
notesCard.appendChild(h('div', { class: 'soc-addnote' }, ta, h('div', { class: 'soc-composer-bar' }, cnt, add), err));
|
||||
sync();
|
||||
}
|
||||
|
||||
// leave / disband
|
||||
const danger = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.manage.title'))));
|
||||
const row = h('div', { class: 'btn-row soc-stack' });
|
||||
if (A.leaveNeedsTransfer) {
|
||||
danger.appendChild(h('p', { class: 'reason', text: App.t('soc.leave.mustTransfer') }));
|
||||
row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => setTab('members') }, icon('users'), App.t('soc.leave.goTransfer')));
|
||||
} else {
|
||||
row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmLeave }, icon('logout'), App.t('soc.leave.go')));
|
||||
}
|
||||
if (A.disband) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: confirmDisband }, icon('x'), App.t('soc.disband.go')));
|
||||
danger.appendChild(row);
|
||||
content.appendChild(danger);
|
||||
|
||||
if (cache.notes) { drawNotes(cache.notes); return; }
|
||||
notesList.appendChild(X().loading());
|
||||
try {
|
||||
const r = await App.api.get('/alliances/' + mine.alliance.id + '/notes');
|
||||
if (my !== gen) return;
|
||||
cache.notes = r.items;
|
||||
if (tab === 'overview') drawNotes(cache.notes);
|
||||
} catch (e) { if (my === gen && tab === 'overview') { clear(notesList); notesList.appendChild(X().errorBox(e, drawTab)); } }
|
||||
}
|
||||
|
||||
function confirmLeave() {
|
||||
const alone = members && members.length <= 1;
|
||||
X().confirmSheet({
|
||||
title: App.t('soc.leave.go'), icon: 'logout', danger: true, ok: App.t('soc.leave.go'),
|
||||
text: App.t(alone ? 'soc.leave.confirmAlone' : 'soc.leave.confirm', { name: mine.alliance.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/leave', {}, { intent: 'ally:leave' }); toast(App.t('soc.leave.done'), 'ok'); await reload(); },
|
||||
});
|
||||
}
|
||||
|
||||
function confirmDisband() {
|
||||
X().confirmSheet({
|
||||
title: App.t('soc.disband.go'), icon: 'alert', danger: true, ok: App.t('soc.disband.go'),
|
||||
text: App.t('soc.disband.confirm', { name: mine.alliance.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/disband', {}, { intent: 'ally:disband' }); toast(App.t('soc.disband.done'), 'ok'); await reload(); },
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- members
|
||||
function drawMembers() {
|
||||
const A = acts();
|
||||
const now = App.now();
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('users'), App.t('soc.members')),
|
||||
h('span', { class: 'pill dim mono', text: App.t('soc.size', { n: members.length, cap: mine.alliance.sizeCap }) })));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
for (const m of members) {
|
||||
const you = m.operatorId === X().myOperatorId();
|
||||
list.appendChild(h('li', null, h('button', { class: 'row-btn soc-member', type: 'button', onclick: () => openMember(m) },
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: m.name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null, X().rolePill(m.role)),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.member.stats', { towns: m.towns, fp: App.fmt.dec(m.footprint) }) + ' · ' + (m.lastOnline ? App.t('soc.member.online', { t: App.fmt.ago(now - m.lastOnline) }) : App.t('soc.member.never')) })))));
|
||||
}
|
||||
card.appendChild(list);
|
||||
content.appendChild(card);
|
||||
|
||||
if (A.invite) drawInvite();
|
||||
}
|
||||
|
||||
async function drawInvite() {
|
||||
const my = gen;
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('mail'), App.t('soc.invite.title'))));
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', 'aria-label': App.t('soc.invite.name'), placeholder: App.t('soc.invite.name'), enterkeyhint: 'send' });
|
||||
const go = h('button', { class: 'btn primary', type: 'button' }, icon('up'), App.t('soc.invite.go'));
|
||||
const pend = h('ul', { class: 'soc-list' });
|
||||
const sync = () => { go.disabled = !Soc.cleanName(nameIn.value); };
|
||||
nameIn.addEventListener('input', sync);
|
||||
nameIn.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' && !go.disabled) go.click(); });
|
||||
go.addEventListener('click', () => X().guard(go, async () => {
|
||||
err.hidden = true;
|
||||
const name = Soc.cleanName(nameIn.value);
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/invite', { name }, { intent: 'ally:invite:' + name.toLowerCase() });
|
||||
toast(App.t(r.changed ? 'soc.invite.sent' : 'soc.invite.already', { name }), 'ok');
|
||||
nameIn.value = ''; sync();
|
||||
loadPending();
|
||||
} catch (e) { err.textContent = e.code === 'not_found' ? App.t('soc.invite.unknown', { name }) : X().err(e); err.hidden = false; }
|
||||
}));
|
||||
sync();
|
||||
card.appendChild(h('div', { class: 'soc-inline' }, nameIn, go));
|
||||
card.appendChild(err);
|
||||
if (acts().viewInvites) { card.appendChild(h('div', { class: 'sub', text: App.t('soc.invite.pending') })); card.appendChild(pend); }
|
||||
content.appendChild(card);
|
||||
|
||||
async function loadPending() {
|
||||
if (!acts().viewInvites) return;
|
||||
try {
|
||||
const r = await App.api.get('/alliances/' + mine.alliance.id + '/invites');
|
||||
if (my !== gen || tab !== 'members') return;
|
||||
clear(pend);
|
||||
if (!r.items.length) pend.appendChild(h('li', { class: 'empty', text: App.t('soc.invite.none') }));
|
||||
const now = App.now();
|
||||
for (const inv of r.items) {
|
||||
const cancel = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.invite.cancel'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/invites/' + inv.id);
|
||||
loadPending();
|
||||
}) }, icon('x'));
|
||||
pend.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: inv.operator.name }),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.invites.from', { name: inv.invitedBy.name }) + ' · ' + App.t('soc.invites.expires', { t: App.fmt.dur(Math.max(0, inv.expiresAt - now), 2) }) })),
|
||||
acts().cancelInvite ? cancel : null));
|
||||
}
|
||||
} catch (e) { if (my === gen && tab === 'members') { clear(pend); pend.appendChild(X().errorBox(e, loadPending)); } }
|
||||
}
|
||||
loadPending();
|
||||
}
|
||||
|
||||
// Member sheet: message, role (leader), transfer (leader), kick (outranking).
|
||||
function openMember(m) {
|
||||
const act = Soc.memberActions(myRole(), m, X().myOperatorId());
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const bodyEl = h('div', { class: 'detail' });
|
||||
const sheet = openSheet({ title: m.name, icon: 'users', closeLabel: App.t('common.close'), body: bodyEl });
|
||||
const after = async () => { sheet.close(); await load(); };
|
||||
const run = (btn, fn) => X().guard(btn, async () => { err.hidden = true; try { await fn(); } catch (e) { err.textContent = X().err(e); err.hidden = false; } });
|
||||
|
||||
bodyEl.appendChild(h('div', { class: 'pill-row' }, X().rolePill(m.role), h('span', { class: 'pill mono', text: 'AS' + m.asNumber })));
|
||||
bodyEl.appendChild(h('div', null,
|
||||
kv(App.t('soc.member.pops'), String(m.towns)), kv(App.t('soc.footprint'), App.fmt.dec(m.footprint)),
|
||||
kv(App.t('soc.member.lastOnline'), m.lastOnline ? App.fmt.ago(App.now() - m.lastOnline) : App.t('soc.member.never')),
|
||||
kv(App.t('soc.member.joined'), App.fmt.ago(App.now() - m.joinedAt))));
|
||||
if (act.message) bodyEl.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: m.operatorId, name: m.name } }); } }, icon('mail'), App.t('soc.member.message')));
|
||||
if (act.roles.length) {
|
||||
bodyEl.appendChild(h('div', { class: 'sub', text: App.t('soc.member.setRole') }));
|
||||
bodyEl.appendChild(h('div', { class: 'seg' }, act.roles.map((r) => h('button', { class: 'seg-btn', type: 'button', text: X().role(r), onclick: (ev) => run(ev.currentTarget, async () => {
|
||||
await App.api.post('/alliances/' + mine.alliance.id + '/role', { operatorId: m.operatorId, role: r }, { intent: 'ally:role:' + m.operatorId + ':' + r });
|
||||
toast(App.t('soc.member.roleSet', { name: m.name, role: X().role(r) }), 'ok');
|
||||
await after();
|
||||
}) }))));
|
||||
bodyEl.appendChild(h('p', { class: 'field-hint', text: App.t('soc.member.roleHint') }));
|
||||
}
|
||||
const row = h('div', { class: 'btn-row soc-stack' });
|
||||
if (act.transfer) row.appendChild(h('button', { class: 'btn', type: 'button', onclick: () => {
|
||||
sheet.close();
|
||||
X().confirmSheet({ title: App.t('soc.transfer.go'), icon: 'shield', ok: App.t('soc.transfer.go'), text: App.t('soc.transfer.confirm', { name: m.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/transfer', { operatorId: m.operatorId }, { intent: 'ally:transfer:' + m.operatorId }); toast(App.t('soc.transfer.done', { name: m.name }), 'ok'); await load(); } });
|
||||
} }, icon('shield'), App.t('soc.transfer.go')));
|
||||
if (act.kick) row.appendChild(h('button', { class: 'btn danger', type: 'button', onclick: () => {
|
||||
sheet.close();
|
||||
X().confirmSheet({ title: App.t('soc.kick.go'), icon: 'alert', danger: true, ok: App.t('soc.kick.go'), text: App.t('soc.kick.confirm', { name: m.name }),
|
||||
onOk: async () => { await App.api.post('/alliances/' + mine.alliance.id + '/kick', { operatorId: m.operatorId }, { intent: 'ally:kick:' + m.operatorId }); toast(App.t('soc.kick.done', { name: m.name }), 'ok'); await load(); } });
|
||||
} }, icon('x'), App.t('soc.kick.go')));
|
||||
if (row.children.length) bodyEl.appendChild(row);
|
||||
bodyEl.appendChild(err);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- diplomacy
|
||||
async function drawDiplomacy() {
|
||||
const my = gen;
|
||||
const A = acts();
|
||||
const card = h('div', { class: 'card soc-card' }, h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('soc.dip.title')),
|
||||
A.diplomacy ? h('button', { class: 'btn small primary', type: 'button', onclick: openPicker }, icon('plus'), App.t('soc.dip.new')) : null));
|
||||
const holder = h('div', { class: 'soc-dip' }, X().loading());
|
||||
card.appendChild(holder);
|
||||
if (!A.diplomacy) card.appendChild(h('p', { class: 'field-hint', text: App.t('soc.dip.readOnly') }));
|
||||
content.appendChild(card);
|
||||
|
||||
const draw = (d) => {
|
||||
cache.dip = d;
|
||||
clear(holder);
|
||||
stopTick();
|
||||
if (d.proposalsIn.length) holder.appendChild(proposalBlock('soc.dip.incoming', d.proposalsIn, 'in'));
|
||||
holder.appendChild(h('div', { class: 'sub', text: App.t('soc.dip.relations') }));
|
||||
if (!d.relations.length) holder.appendChild(h('p', { class: 'empty', text: App.t('soc.dip.none') }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
for (const r of d.relations) list.appendChild(relationRow(r));
|
||||
holder.appendChild(list);
|
||||
if (d.proposalsOut.length) holder.appendChild(proposalBlock('soc.dip.outgoing', d.proposalsOut, 'out'));
|
||||
const cds = holder.querySelectorAll('[data-eff]');
|
||||
if (cds.length) {
|
||||
offTick = App.onTick((now) => {
|
||||
for (const el of cds) {
|
||||
if (!el.isConnected) continue;
|
||||
const left = Math.max(0, Number(el.dataset.eff) - now);
|
||||
const s = left > 0 ? App.t('soc.dip.in', { t: App.fmt.dur(left, 2) }) : App.t('soc.dip.applying');
|
||||
if (el.textContent !== s) el.textContent = s;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const refetch = async () => {
|
||||
try {
|
||||
const d = await App.api.get('/alliances/' + mine.alliance.id + '/diplomacy');
|
||||
if (my !== gen || tab !== 'diplomacy') return;
|
||||
draw(d);
|
||||
} catch (e) { if (my === gen && tab === 'diplomacy') { clear(holder); holder.appendChild(X().errorBox(e, drawTab)); } }
|
||||
};
|
||||
refreshDip = refetch;
|
||||
if (cache.dip) draw(cache.dip);
|
||||
refetch();
|
||||
}
|
||||
let refreshDip = () => {};
|
||||
|
||||
function allianceLabel(other) {
|
||||
return h('span', { class: 'row-title' }, other.tag ? X().tagPill(other.tag) : null, h('b', { text: other.name || '#' + other.id }));
|
||||
}
|
||||
|
||||
function relationRow(r) {
|
||||
const A = acts();
|
||||
const now = App.now();
|
||||
const p = r.pending;
|
||||
const eta = p ? h('span', { class: 'soc-eta mono', dataset: { eff: p.effectiveAt }, text: App.t('soc.dip.in', { t: App.fmt.dur(Math.max(0, p.effectiveAt - now), 2) }) }) : null;
|
||||
const revoke = p && p.byUs && A.diplomacy
|
||||
? h('button', { class: 'btn small', type: 'button', text: App.t('soc.dip.revoke'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/alliances/' + mine.alliance.id + '/diplomacy/' + r.other.id + '/pending');
|
||||
toast(App.t('soc.dip.revoked'), 'ok'); refreshDip();
|
||||
}) }) : null;
|
||||
return h('li', { class: 'soc-item soc-rel' },
|
||||
h('div', { class: 'row-main' }, allianceLabel(r.other),
|
||||
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + r.state, text: X().state(r.state) }),
|
||||
p ? h('span', { class: 'soc-pending' }, ' → ', h('b', { text: X().state(p.to) }), ' · ', eta, ' · ', p.byUs ? App.t('soc.dip.byUs') : App.t('soc.dip.byThem')) : null)),
|
||||
revoke);
|
||||
}
|
||||
|
||||
function proposalBlock(titleKey, items, dir) {
|
||||
const A = acts();
|
||||
const wrap = h('div', null, h('div', { class: 'sub', text: App.t(titleKey) }));
|
||||
const list = h('ul', { class: 'soc-list' });
|
||||
const now = App.now();
|
||||
for (const pr of items) {
|
||||
const mk = (label, cls, path, method) => h('button', { class: 'btn small ' + cls, type: 'button', text: label, onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
try {
|
||||
if (method === 'del') await App.api.del(path); else await App.api.post(path, {}, { intent: 'dip:' + path });
|
||||
refreshDip();
|
||||
} catch (e) { toast(X().err(e), 'error'); refreshDip(); }
|
||||
}) });
|
||||
const btns = !A.diplomacy ? [] : dir === 'in'
|
||||
? [mk(App.t('soc.dip.decline'), '', '/diplomacy/proposals/' + pr.id + '/decline'), mk(App.t('soc.dip.accept'), 'primary', '/diplomacy/proposals/' + pr.id + '/accept')]
|
||||
: [mk(App.t('soc.dip.withdraw'), '', '/diplomacy/proposals/' + pr.id, 'del')];
|
||||
list.appendChild(h('li', { class: 'soc-item soc-rel' },
|
||||
h('div', { class: 'row-main' }, allianceLabel(pr.other),
|
||||
h('span', { class: 'row-sub' }, h('span', { class: 'pill soc-state soc-state-' + pr.state, text: X().state(pr.state) }), h('span', { text: App.t('soc.dip.expires', { t: App.fmt.dur(Math.max(0, pr.expiresAt - now), 2) }) }))),
|
||||
h('div', { class: 'soc-actions' }, btns)));
|
||||
}
|
||||
wrap.appendChild(list);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Pick another alliance (directory search), then the move.
|
||||
function openPicker() {
|
||||
const results = h('ul', { class: 'soc-list' });
|
||||
const q = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', spellcheck: 'false', placeholder: App.t('soc.dip.search'), 'aria-label': App.t('soc.dip.search'), enterkeyhint: 'search' });
|
||||
const more = h('button', { class: 'btn small wide', type: 'button', hidden: true, text: App.t('soc.more') });
|
||||
let items = [], next = null, seq = 0, timer = null;
|
||||
const sheet = openSheet({ title: App.t('soc.dip.pick'), icon: 'shield', closeLabel: App.t('common.close'), onClose: () => clearTimeout(timer),
|
||||
body: h('div', { class: 'detail' }, q, results, more) });
|
||||
|
||||
function drawResults() {
|
||||
clear(results);
|
||||
const rows = items.filter((x) => x.id !== mine.alliance.id);
|
||||
if (!rows.length) results.appendChild(h('li', { class: 'empty', text: App.t('soc.dip.noResults') }));
|
||||
for (const a of rows) {
|
||||
results.appendChild(h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => { sheet.close(); openMove(a); } },
|
||||
h('span', { class: 'row-main' }, allianceLabel(a), h('span', { class: 'row-sub', text: App.t('soc.size', { n: a.memberCount, cap: a.sizeCap }) })))));
|
||||
}
|
||||
more.hidden = next === null;
|
||||
}
|
||||
async function search(append) {
|
||||
const my = ++seq;
|
||||
try {
|
||||
const r = await App.api.get('/alliances', { q: q.value.trim() || undefined, after: append ? next : undefined, limit: 30 });
|
||||
if (my !== seq) return;
|
||||
items = append ? items.concat(r.items) : r.items; next = r.next;
|
||||
drawResults();
|
||||
} catch (e) { if (my === seq) { clear(results); results.appendChild(X().errorBox(e, () => search(false))); } }
|
||||
}
|
||||
q.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(() => search(false), 250); });
|
||||
more.addEventListener('click', () => search(true));
|
||||
search(false);
|
||||
}
|
||||
|
||||
function openMove(other) {
|
||||
const d = cache.dip || { relations: [] };
|
||||
const cur = Soc.relationTo(d.relations, other.id);
|
||||
const opts = Soc.diplomacyOptions(cur.state, cur.pending);
|
||||
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const list = h('div', { class: 'soc-moves' });
|
||||
const sheet = openSheet({ title: other.name, icon: 'shield', closeLabel: App.t('common.close'),
|
||||
body: h('div', { class: 'detail' },
|
||||
h('div', { class: 'pill-row' }, X().tagPill(other.tag), h('span', { class: 'pill soc-state soc-state-' + cur.state, text: App.t('soc.dip.current', { state: X().state(cur.state) }) })),
|
||||
cur.pending ? h('p', { class: 'reason', text: App.t('soc.dip.locked') }) : null,
|
||||
!opts.length && !cur.pending ? h('p', { class: 'empty', text: App.t('soc.dip.noMoves') }) : null,
|
||||
list, err) });
|
||||
for (const o of opts) {
|
||||
const hint = o.kind === 'delayed' ? App.t('soc.kind.delayed.hint', { t: App.fmt.dur(R.pactCancelMs(App.state.world ? App.state.world.speed : 1), 2) }) : App.t('soc.kind.' + o.kind + '.hint');
|
||||
list.appendChild(h('button', { class: 'row-btn soc-move', type: 'button', onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
err.hidden = true;
|
||||
try {
|
||||
const r = await App.api.post('/alliances/' + mine.alliance.id + '/diplomacy', { targetId: other.id, state: o.state }, { intent: 'dip:' + other.id + ':' + o.state });
|
||||
toast(App.t('soc.dip.result.' + r.result, { state: X().state(r.state), name: other.name }), 'ok');
|
||||
sheet.close();
|
||||
cache.dip = null;
|
||||
if (tab === 'diplomacy') drawTab();
|
||||
} catch (e) { err.textContent = X().err(e); err.hidden = false; }
|
||||
}) },
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('span', { class: 'pill soc-state soc-state-' + o.state, text: X().state(o.state) }), h('b', { text: App.t('soc.kind.' + o.kind) })), h('span', { class: 'row-sub soc-wrap', text: hint }))));
|
||||
}
|
||||
}
|
||||
|
||||
function stopTick() { if (offTick) { offTick(); offTick = null; } }
|
||||
|
||||
App.registerScreen({
|
||||
id: 'alliance', titleKey: 'screen.alliance', navKey: 'nav.alliance', icon: 'users', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
body = h('div', { class: 'soc-body' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-alliance-h', text: App.t('screen.alliance') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
|
||||
body));
|
||||
App.on('session', () => { mine = null; members = null; tab = 'overview'; for (const k of Object.keys(cache)) delete cache[k]; });
|
||||
},
|
||||
onShow() { box.querySelector('#soc-alliance-h').textContent = App.t('screen.alliance'); load(); },
|
||||
onHide() { stopTick(); gen++; },
|
||||
});
|
||||
}());
|
||||
50
public/js/screens/expand.js
Normal file
50
public/js/screens/expand.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Expansion on the POP screen (App.popSections, slot 'main'): your POPs (switch between them), and what founding the next
|
||||
* one takes: rollout crews at home, the footprint gate, a shortcut to the map to pick a site (the map tile sheet then offers
|
||||
* "Send" -> Settle with the wild-slot choice, see send.js). The founding itself is a settle movement; the settle report has
|
||||
* an "Open POP" button. The POP switcher in the resource bar lives in main.js.
|
||||
*/
|
||||
(function () {
|
||||
const { h, icon, toast } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const mil = () => App.mil;
|
||||
|
||||
function popsList(t) {
|
||||
const st = App.state;
|
||||
return h('ul', { class: 'mil-list' }, st.towns.map((x) => h('li', { class: 'mil-row' + (x.id === t.id ? ' current' : '') },
|
||||
h('span', { class: 'row-ic' }, icon('pop')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: x.name }), x.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null),
|
||||
h('span', { class: 'row-sub' }, mil().coordLink(x.x, x.y))),
|
||||
x.id === t.id ? h('span', { class: 'pill green', text: App.t('exp.current') })
|
||||
: h('button', { class: 'btn small', type: 'button', onclick: () => { App.setTown(x.id); } }, App.t('exp.open')))));
|
||||
}
|
||||
|
||||
function card(t) {
|
||||
const m = t.military;
|
||||
const owned = App.state.towns.length;
|
||||
const need = R.footprintNeeded(owned);
|
||||
const crews = m ? (m.units.home[D.EXPANSION.settleUnit] || 0) : 0;
|
||||
const canTrain = m && m.trainable.some((u) => u.unit === D.EXPANSION.settleUnit && !u.locked);
|
||||
const rows = [
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.crews') }), h('span', { class: 'v mono' + (crews >= D.EXPANSION.crews ? ' good' : ''), text: crews + ' / ' + D.EXPANSION.crews })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.footprint') }), h('span', { class: 'v mono', text: App.t('exp.footprint.v', { have: App.fmt.num(t.footprint), need: App.fmt.num(need) }) })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('exp.range') }), h('span', { class: 'v mono', text: D.EXPANSION.maxDistance + ' ' + App.t('common.tiles') })),
|
||||
];
|
||||
const actions = [];
|
||||
if (crews >= D.EXPANSION.crews) {
|
||||
actions.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { App.go('map', { x: t.x, y: t.y, zoom: 24 }); toast(App.t('exp.pick'), 'ok'); } }, icon('flag'), App.t('exp.found')));
|
||||
} else {
|
||||
actions.push(h('p', { class: 'row-sub wrap', text: canTrain ? App.t('exp.needCrews', { n: D.EXPANSION.crews - crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) : App.t('exp.needDepot') }));
|
||||
if (canTrain) actions.push(h('button', { class: 'btn wide', type: 'button', onclick: () => App.go('units') }, icon('units'), App.t('exp.train')));
|
||||
}
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('exp.title')), h('span', { class: 'pill', text: App.t('exp.count', { n: owned }) })),
|
||||
rows, h('p', { class: 'row-sub wrap', text: App.t('exp.hint') }), actions,
|
||||
owned > 1 ? [h('h3', { class: 'sub', text: App.t('exp.pops') }), popsList(t)] : null);
|
||||
}
|
||||
|
||||
App.popSections.push({ slot: 'main', render: card });
|
||||
}());
|
||||
|
|
@ -77,7 +77,7 @@
|
|||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
|
||||
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own', offMoveTick = null;
|
||||
const store = new Store();
|
||||
let infoSheet = null;
|
||||
|
||||
|
|
@ -113,6 +113,8 @@
|
|||
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(),
|
||||
movements: () => moveLines(),
|
||||
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
|
||||
};
|
||||
view = new MapRender.MapView(canvas, source, {
|
||||
onTap: onTap,
|
||||
|
|
@ -128,6 +130,21 @@
|
|||
drawLegend();
|
||||
}
|
||||
|
||||
// Lines for the movements of the shared cache (App.mil.moves): yours, incoming and allied ones, with progress at draw time.
|
||||
function moveLines() {
|
||||
const mv = App.mil && App.mil.moves;
|
||||
if (!mv) return [];
|
||||
const now = App.now(), out = [];
|
||||
const add = (m, kind) => {
|
||||
if (!m.from || !m.to || m.from.x === undefined || m.to.x === undefined) return;
|
||||
out.push({ from: m.from, to: m.to, kind, p: (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt) });
|
||||
};
|
||||
for (const m of mv.outgoing) add(m, m.type === 'return' ? 'ret' : 'out');
|
||||
for (const m of mv.incoming) add(m, 'in');
|
||||
for (const m of mv.alliedIncoming || []) add(m, 'ally');
|
||||
return out;
|
||||
}
|
||||
|
||||
function drawLegend() {
|
||||
UI.clear(legendEl);
|
||||
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
|
||||
|
|
@ -135,6 +152,8 @@
|
|||
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')));
|
||||
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
|
||||
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tile info
|
||||
|
|
@ -174,6 +193,9 @@
|
|||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
||||
}
|
||||
body.push(row('', App.t('map.info.coords', { x, y })));
|
||||
if (App.openSend && App.state.towns.length && (town || (special && special.type === 'incumbent') || (!special && known))) {
|
||||
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
|
||||
}
|
||||
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')));
|
||||
|
|
@ -192,10 +214,19 @@
|
|||
render(container) {
|
||||
box = container;
|
||||
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
|
||||
App.on('movements', () => { if (visible && view) view.invalidate(); });
|
||||
App.on('towns', () => { if (view) view.invalidate(); });
|
||||
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
|
||||
},
|
||||
onShow(params) {
|
||||
visible = true;
|
||||
// marker positions move with the clock: redraw about once a second while any movement is on the wire
|
||||
if (offMoveTick) offMoveTick();
|
||||
let lastSec = 0;
|
||||
offMoveTick = App.onTick((now) => {
|
||||
const sec = Math.floor(now / 1000), mv = App.mil.moves;
|
||||
if (sec !== lastSec && view && (mv.outgoing.length || mv.incoming.length || (mv.alliedIncoming || []).length)) { lastSec = sec; view.invalidate(); }
|
||||
});
|
||||
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);
|
||||
|
|
@ -208,7 +239,7 @@
|
|||
// 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(); },
|
||||
onHide() { visible = false; if (offMoveTick) offMoveTick(); offMoveTick = null; closeSheet(); },
|
||||
onLang() {
|
||||
if (!ready) return;
|
||||
canvas.setAttribute('aria-label', App.t('map.label'));
|
||||
|
|
|
|||
334
public/js/screens/messages.js
Normal file
334
public/js/screens/messages.js
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Messages: inbox, sent, alliance broadcast feed, blocked operators, one thread per operator, compose. Message text is
|
||||
* plain text and only ever set with textContent (the CSS keeps line breaks). Lists are newest first and paged with
|
||||
* `after` = the last id (the next page holds OLDER ids). The unread count of the inbox is polled in the background and
|
||||
* shown through App.setBadge on the nav entry (or the "More" button).
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const D = UpstreamData;
|
||||
const X = () => window.SocUI;
|
||||
const PAGE = 30;
|
||||
|
||||
let box, tabsEl, listBox, tab = 'inbox';
|
||||
let thread = null; // { peer: {operatorId, name}, items, next, loading } while a conversation is open
|
||||
let blocked = null; // Map operatorId -> name (loaded lazily)
|
||||
let unreadOnly = false;
|
||||
let offTick = null, gen = 0;
|
||||
const feeds = { inbox: blank(), sent: blank(), alliance: blank() };
|
||||
let blocks = { items: null, err: null };
|
||||
|
||||
function blank() { return { items: [], next: null, loaded: false, loading: false, err: null }; }
|
||||
const inAlliance = () => !!X().myAlliance();
|
||||
const urls = { inbox: '/messages/inbox', sent: '/messages/outbox', alliance: '/messages/alliance' };
|
||||
|
||||
// ------------------------------------------------------------------ unread badge (works without the screen being open)
|
||||
const badge = { n: 0, polling: false };
|
||||
async function pollUnread() {
|
||||
if (!App.state.user || badge.polling || document.hidden) return;
|
||||
badge.polling = true;
|
||||
try { const r = await App.api.get('/messages/inbox', { limit: 1 }); setUnread(r.unread || 0); } catch (e) { /* a badge is a convenience */ } finally { badge.polling = false; }
|
||||
}
|
||||
// App.setBadge (main.js) shows it on this screen's nav button, or summed on the "More" button when the screen lives there.
|
||||
function setUnread(n) { badge.n = n; App.state.unreadMsgs = n; App.setBadge('messages', n, 'info'); }
|
||||
setInterval(pollUnread, 60000);
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden) pollUnread(); });
|
||||
App.on('session', () => { setUnread(0); for (const k of Object.keys(feeds)) feeds[k] = blank(); blocks = { items: null, err: null }; thread = null; setTimeout(pollUnread, 800); });
|
||||
|
||||
// ------------------------------------------------------------------ loading
|
||||
async function loadFeed(kind, more) {
|
||||
const f = feeds[kind];
|
||||
if (f.loading) return;
|
||||
f.loading = true; f.err = null;
|
||||
const my = gen;
|
||||
if (kind === tab && !thread) drawList();
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && f.next) q.after = f.next;
|
||||
if (kind === 'inbox' && unreadOnly) q.unread = true;
|
||||
const r = await App.api.get(urls[kind], q);
|
||||
f.items = more ? Soc.mergeMessages(f.items, r.items) : r.items;
|
||||
f.next = r.next; f.loaded = true;
|
||||
if (kind === 'inbox' && typeof r.unread === 'number') setUnread(r.unread);
|
||||
} catch (e) { f.err = e; if (kind === 'alliance' && e.code === 'not_in_alliance') { f.items = []; f.next = null; f.loaded = true; f.err = null; } } finally {
|
||||
f.loading = false;
|
||||
if (my === gen && kind === tab && !thread) drawList();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBlocks() {
|
||||
blocks.err = null;
|
||||
try { blocks.items = (await App.api.get('/messages/blocks')).items; blocked = new Map(blocks.items.map((b) => [b.operatorId, b.name])); } catch (e) { blocks.err = e; }
|
||||
if (tab === 'blocked' && !thread) drawList();
|
||||
}
|
||||
|
||||
async function markRead(ids) {
|
||||
if (!ids.length) return;
|
||||
try {
|
||||
await App.api.post('/messages/read', { ids: ids.slice(0, 100) });
|
||||
const now = App.now(), set = new Set(ids);
|
||||
for (const k of Object.keys(feeds)) for (const m of feeds[k].items) if (set.has(m.id) && !m.readAt) m.readAt = now;
|
||||
if (thread) for (const m of thread.items) if (set.has(m.id) && !m.readAt) m.readAt = now;
|
||||
pollUnread();
|
||||
} catch (e) { /* unread state only */ }
|
||||
}
|
||||
|
||||
async function deleteMessage(m, btn) {
|
||||
await X().guard(btn, async () => {
|
||||
await App.api.del('/messages/' + m.id);
|
||||
for (const k of Object.keys(feeds)) feeds[k].items = feeds[k].items.filter((x) => x.id !== m.id);
|
||||
if (thread) thread.items = thread.items.filter((x) => x.id !== m.id);
|
||||
toast(App.t('soc.msg.deleted'), 'ok');
|
||||
pollUnread();
|
||||
thread ? drawThread() : drawList();
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ list view
|
||||
const ago = (at) => h('span', { class: 'when mono', dataset: { at }, text: App.fmt.ago(App.now() - at) });
|
||||
|
||||
function msgRow(m) {
|
||||
const out = m.direction === 'out';
|
||||
const unread = !out && !m.readAt;
|
||||
const alliance = m.kind === 'alliance';
|
||||
const who = out ? (alliance ? App.t('soc.msg.allianceFeed') : App.t('soc.msg.toShort', { name: m.to ? m.to.name : '?' })) : m.from.name;
|
||||
const del = h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x'));
|
||||
return h('li', { class: 'soc-msgrow' },
|
||||
h('button', { class: 'row-btn soc-msg' + (unread ? ' unread' : ''), type: 'button', onclick: () => openMessage(m) },
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: who }), alliance && m.alliance ? X().tagPill(m.alliance.tag) : null, unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null),
|
||||
h('span', { class: 'soc-preview', text: m.text })),
|
||||
ago(m.createdAt)),
|
||||
del);
|
||||
}
|
||||
|
||||
function openMessage(m) {
|
||||
if (m.kind === 'alliance') {
|
||||
if (m.direction === 'in' && !m.readAt) markRead([m.id]);
|
||||
if (tab !== 'alliance') setTab('alliance'); else drawList();
|
||||
return;
|
||||
}
|
||||
const peer = Soc.peerOf(m);
|
||||
openThread({ operatorId: peer.operatorId, name: peer.name });
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!listBox) return;
|
||||
clear(listBox);
|
||||
if (thread) return;
|
||||
tabsEl.hidden = !!thread;
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
|
||||
const inb = tabsEl.querySelector('[data-tab="inbox"] .soc-tabn');
|
||||
if (inb) { inb.textContent = badge.n ? String(badge.n) : ''; inb.hidden = !badge.n; }
|
||||
const allyBtn = tabsEl.querySelector('[data-tab="alliance"]');
|
||||
if (allyBtn) allyBtn.hidden = !inAlliance();
|
||||
|
||||
if (tab === 'blocked') { drawBlocked(); return; }
|
||||
const f = feeds[tab];
|
||||
|
||||
if (tab === 'inbox') {
|
||||
listBox.appendChild(h('div', { class: 'soc-toolbar' },
|
||||
h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(unreadOnly), text: App.t('soc.msg.unreadOnly'), onclick: () => { unreadOnly = !unreadOnly; feeds.inbox = blank(); loadFeed('inbox'); } }),
|
||||
h('button', { class: 'btn small', type: 'button', disabled: !badge.n, text: App.t('soc.msg.markAll'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.post('/messages/read', { all: true });
|
||||
const now = App.now();
|
||||
for (const m of feeds.inbox.items) if (!m.readAt) m.readAt = now;
|
||||
setUnread(0); drawList();
|
||||
}) })));
|
||||
}
|
||||
if (tab === 'alliance') drawBroadcast();
|
||||
|
||||
if (f.err) { listBox.appendChild(X().errorBox(f.err, () => loadFeed(tab))); return; }
|
||||
if (!f.loaded && f.loading) { listBox.appendChild(X().loading()); return; }
|
||||
if (!f.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.empty.' + tab) })); return; }
|
||||
const ul = h('ul', { class: 'soc-list' });
|
||||
for (const m of f.items) ul.appendChild(tab === 'alliance' ? feedItem(m) : msgRow(m));
|
||||
listBox.appendChild(ul);
|
||||
if (f.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: f.loading, text: App.t('soc.more'), onclick: () => loadFeed(tab, true) }));
|
||||
}
|
||||
|
||||
// One alliance broadcast shown in full.
|
||||
function feedItem(m) {
|
||||
const out = m.direction === 'out';
|
||||
const unread = !out && !m.readAt;
|
||||
return h('li', { class: 'soc-item soc-feed' + (unread ? ' unread' : '') },
|
||||
h('div', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: m.from.name }), unread ? h('span', { class: 'pill accent', text: App.t('soc.msg.new') }) : null, ago(m.createdAt)),
|
||||
h('p', { class: 'soc-msg-body', text: m.text })),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')));
|
||||
}
|
||||
|
||||
let bc = null;
|
||||
function drawBroadcast() {
|
||||
if (!bc) {
|
||||
bc = X().composer({
|
||||
label: App.t('soc.msg.toAlliance'), placeholder: App.t('soc.msg.broadcastPlaceholder'), sendLabel: App.t('soc.msg.broadcast'), rows: 2,
|
||||
onSend: async (text) => { await App.api.post('/messages', { text, toAlliance: true }, { retries: 0 }); toast(App.t('soc.msg.sent'), 'ok'); feeds.alliance = blank(); loadFeed('alliance'); },
|
||||
});
|
||||
}
|
||||
listBox.appendChild(h('div', { class: 'card soc-card' }, h('div', { class: 'sub', text: App.t('soc.msg.toAlliance') }), bc.el));
|
||||
}
|
||||
|
||||
function drawBlocked() {
|
||||
if (blocks.err) { listBox.appendChild(X().errorBox(blocks.err, loadBlocks)); return; }
|
||||
if (!blocks.items) { listBox.appendChild(X().loading()); return; }
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.hint') }));
|
||||
if (!blocks.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.block.none') })); return; }
|
||||
const ul = h('ul', { class: 'soc-list' });
|
||||
for (const b of blocks.items) {
|
||||
ul.appendChild(h('li', { class: 'soc-item' }, h('div', { class: 'row-main' }, h('b', { text: b.name }), h('span', { class: 'row-sub', text: App.t('soc.block.since', { t: App.fmt.ago(App.now() - b.createdAt) }) })),
|
||||
h('button', { class: 'btn small', type: 'button', text: App.t('soc.block.unblock'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
await App.api.del('/messages/blocks/' + b.operatorId);
|
||||
toast(App.t('soc.block.unblocked', { name: b.name }), 'ok');
|
||||
await loadBlocks();
|
||||
}) })));
|
||||
}
|
||||
listBox.appendChild(ul);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ thread view
|
||||
async function openThread(peer) {
|
||||
thread = { peer, items: [], next: null, loading: true, err: null };
|
||||
if (!blocked) loadBlocks();
|
||||
drawThread();
|
||||
await fetchThread(false);
|
||||
}
|
||||
|
||||
async function fetchThread(more) {
|
||||
const t = thread;
|
||||
if (!t) return;
|
||||
t.loading = true; t.err = null;
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && t.next) q.after = t.next;
|
||||
const r = await App.api.get('/messages/thread/' + t.peer.operatorId, q);
|
||||
if (thread !== t) return;
|
||||
t.items = more ? Soc.mergeMessages(t.items, r.items) : r.items;
|
||||
t.next = r.next;
|
||||
const ids = Soc.unreadIds(t.items);
|
||||
if (ids.length) markRead(ids);
|
||||
} catch (e) { if (thread === t) t.err = e; } finally {
|
||||
t.loading = false;
|
||||
if (thread === t) drawThread(more ? undefined : 'bottom');
|
||||
}
|
||||
}
|
||||
|
||||
let threadComposer = null, threadFor = 0;
|
||||
function drawThread(scroll) {
|
||||
clear(listBox);
|
||||
if (!thread) return;
|
||||
tabsEl.hidden = true;
|
||||
const t = thread;
|
||||
const isBlocked = blocked && blocked.has(t.peer.operatorId);
|
||||
const blockBtn = h('button', { class: 'btn small' + (isBlocked ? '' : ' danger'), type: 'button', text: App.t(isBlocked ? 'soc.block.unblock' : 'soc.block.go'), onclick: (ev) => X().guard(ev.currentTarget, async () => {
|
||||
if (isBlocked) { await App.api.del('/messages/blocks/' + t.peer.operatorId); toast(App.t('soc.block.unblocked', { name: t.peer.name }), 'ok'); } else { await App.api.post('/messages/blocks', { operatorId: t.peer.operatorId }); toast(App.t('soc.block.blocked', { name: t.peer.name }), 'ok'); }
|
||||
await loadBlocks(); drawThread();
|
||||
}) });
|
||||
listBox.appendChild(h('div', { class: 'soc-thread-head' },
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.back'), onclick: closeThread }, icon('back')),
|
||||
h('h2', { class: 'soc-thread-name', text: t.peer.name }), blockBtn));
|
||||
if (isBlocked) listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.block.threadHint') }));
|
||||
if (t.err) listBox.appendChild(X().errorBox(t.err, () => fetchThread(false)));
|
||||
if (t.loading && !t.items.length) listBox.appendChild(X().loading());
|
||||
if (t.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: t.loading, text: App.t('soc.msg.older'), onclick: () => fetchThread(true) }));
|
||||
if (!t.items.length && !t.loading && !t.err) listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.msg.thread.empty', { name: t.peer.name }) }));
|
||||
const ul = h('ul', { class: 'soc-thread' });
|
||||
for (const m of Soc.chronological(t.items)) {
|
||||
const out = m.direction === 'out';
|
||||
ul.appendChild(h('li', { class: 'soc-bubble ' + (out ? 'out' : 'in') + (!out && !m.readAt ? ' unread' : '') },
|
||||
h('p', { class: 'soc-msg-body', text: m.text }),
|
||||
h('div', { class: 'soc-bubble-meta' }, ago(m.createdAt), h('button', { class: 'soc-del', type: 'button', 'aria-label': App.t('soc.msg.delete'), onclick: (ev) => deleteMessage(m, ev.currentTarget) }, icon('x')))));
|
||||
}
|
||||
listBox.appendChild(ul);
|
||||
if (!threadComposer || threadFor !== t.peer.operatorId) {
|
||||
if (threadComposer) threadComposer.destroy();
|
||||
threadFor = t.peer.operatorId;
|
||||
threadComposer = X().composer({
|
||||
label: App.t('soc.msg.to', { name: t.peer.name }), placeholder: App.t('soc.msg.reply'), rows: 2,
|
||||
onSend: async (text) => { await App.api.post('/messages', { text, toOperatorId: t.peer.operatorId }, { retries: 0 }); feeds.sent = blank(); await fetchThread(false); },
|
||||
});
|
||||
}
|
||||
listBox.appendChild(h('div', { class: 'soc-reply' }, threadComposer.el));
|
||||
if (scroll === 'bottom') requestAnimationFrame(() => { const v = document.getElementById('view'); if (v) v.scrollTop = v.scrollHeight; });
|
||||
}
|
||||
|
||||
function closeThread() {
|
||||
thread = null;
|
||||
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
|
||||
for (const k of ['inbox', 'sent']) feeds[k] = blank();
|
||||
drawList(); loadFeed(tab === 'blocked' ? 'inbox' : tab === 'alliance' ? 'alliance' : tab);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ new message sheet
|
||||
function openNew(prefill) {
|
||||
const nameIn = h('input', { type: 'text', maxlength: '40', autocomplete: 'off', autocapitalize: 'off', spellcheck: 'false', id: 'soc-to', value: prefill || '' });
|
||||
const hintEl = h('p', { class: 'field-hint', text: App.t('soc.msg.nameHint') });
|
||||
const comp = X().composer({
|
||||
onSend: async (text) => {
|
||||
const name = Soc.cleanName(nameIn.value);
|
||||
if (!name) { nameIn.focus(); throw Object.assign(new Error('name'), { code: 'validation_failed' }); }
|
||||
try { await App.api.post('/messages', { text, toName: name }, { retries: 0 }); } catch (e) {
|
||||
if (e.code === 'not_found') throw Object.assign(new Error(App.t('soc.msg.unknown', { name })), { code: 'x', message: App.t('soc.msg.unknown', { name }) });
|
||||
throw e;
|
||||
}
|
||||
toast(App.t('soc.msg.sent'), 'ok');
|
||||
sheet.close();
|
||||
feeds.sent = blank(); feeds.inbox = blank();
|
||||
if (tab === 'sent' || tab === 'inbox') loadFeed(tab);
|
||||
},
|
||||
});
|
||||
const sheet = openSheet({ title: App.t('soc.msg.new.title'), icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
|
||||
body: h('div', { class: 'detail' }, h('label', { class: 'field', for: 'soc-to' }, h('span', { class: 'field-lbl', text: App.t('soc.msg.recipient') }), nameIn, hintEl), comp.el) });
|
||||
setTimeout(() => (prefill ? comp.focus() : nameIn.focus()), 220);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tabs + shell
|
||||
function setTab(t) {
|
||||
if (t === tab && !thread) return;
|
||||
tab = t; thread = null;
|
||||
if (threadComposer) { threadComposer.destroy(); threadComposer = null; }
|
||||
if (t === 'blocked') { if (!blocks.items) loadBlocks(); } else if (!feeds[t].loaded) loadFeed(t); else drawList();
|
||||
drawList();
|
||||
}
|
||||
|
||||
function startTick() {
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(() => {
|
||||
const now = App.now();
|
||||
for (const el of listBox.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
|
||||
});
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'messages', titleKey: 'screen.messages', navKey: 'nav.messages', icon: 'mail', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
const tabs = [['inbox', 'soc.msg.tab.inbox'], ['sent', 'soc.msg.tab.sent'], ['alliance', 'soc.msg.tab.alliance'], ['blocked', 'soc.msg.tab.blocked']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs soc-tabs4', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), onclick: () => setTab(id) },
|
||||
h('span', { class: 'soc-tabt', text: App.t(key) }), id === 'inbox' ? h('span', { class: 'soc-tabn', hidden: true }) : null)));
|
||||
listBox = h('div', { class: 'soc-listbox' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-msg-h', text: App.t('screen.messages') }),
|
||||
h('div', { class: 'soc-head-actions' },
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { if (thread) fetchThread(false); else if (tab === 'blocked') loadBlocks(); else { feeds[tab] = blank(); loadFeed(tab); } } }, icon('refresh')),
|
||||
h('button', { class: 'btn small primary', type: 'button', onclick: () => openNew() }, icon('pencil'), App.t('soc.msg.new.go')))),
|
||||
tabsEl, listBox));
|
||||
},
|
||||
onShow(params) {
|
||||
gen++;
|
||||
box.querySelector('#soc-msg-h').textContent = App.t('screen.messages');
|
||||
const labels = { inbox: 'soc.msg.tab.inbox', sent: 'soc.msg.tab.sent', alliance: 'soc.msg.tab.alliance', blocked: 'soc.msg.tab.blocked' };
|
||||
for (const b of tabsEl.children) b.querySelector('.soc-tabt').textContent = App.t(labels[b.dataset.tab]);
|
||||
bc = null;
|
||||
if (!inAlliance() && tab === 'alliance') tab = 'inbox';
|
||||
if (params && params.to) { tab = 'inbox'; openNew(params.to); }
|
||||
if (thread) drawThread(); else { drawList(); if (tab === 'blocked') loadBlocks(); else loadFeed(tab); }
|
||||
startTick();
|
||||
pollUnread();
|
||||
},
|
||||
onHide() { if (offTick) { offTick(); offTick = null; } gen++; },
|
||||
});
|
||||
}());
|
||||
151
public/js/screens/movements.js
Normal file
151
public/js/screens/movements.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Movements: what is on the wire right now. Incoming movements of other operators come first and are deliberately loud
|
||||
* (the server hides their type and units: origin and ETA only); your own outgoing legs and returns follow, with live
|
||||
* countdowns and a Recall button during the first 90 seconds. Also registers the incoming-warning banner on the POP screen.
|
||||
* Data comes from App.mil.moves (milstate.js), which push, the poll and the ticker keep current.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast } = UI;
|
||||
const Mil = UpstreamMil;
|
||||
|
||||
let box, listEl, visible = false, offTick = null, dirty = true;
|
||||
|
||||
// ------------------------------------------------------------------ rows
|
||||
function incomingRow(m) {
|
||||
const from = m.from || {};
|
||||
const owner = from.owner;
|
||||
return h('li', { class: 'mil-row incoming' },
|
||||
h('span', { class: 'row-ic bad' }, icon('alert')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.incoming.title', { town: (m.to && m.to.name) || '?' }) })),
|
||||
h('span', { class: 'row-sub wrap' }, owner ? App.t('mov.incoming.from', { operator: owner.name }) + ' · ' : '', mil().endLink(from)),
|
||||
h('span', { class: 'row-sub wrap', text: App.t('mov.incoming.hint') })),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt, { cls: 'big' }), h('small', { text: mil().clockTime(m.arriveAt) })));
|
||||
}
|
||||
|
||||
const mil = () => App.mil;
|
||||
|
||||
function outgoingRow(m, now) {
|
||||
const type = m.type;
|
||||
const sub = [];
|
||||
if (m.units && Mil.sumUnits(m.units) > 0) sub.push(h('span', { class: 'row-sub wrap', text: mil().unitsText(m.units) }));
|
||||
if (m.cargo && Object.keys(m.cargo).some((r) => m.cargo[r] > 0)) sub.push(mil().resChips(m.cargo));
|
||||
if (m.target) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.target', { name: App.buildingName(m.target) }) }));
|
||||
const recallable = m.recallableUntil && m.recallableUntil > now;
|
||||
const bar = h('i');
|
||||
const row = h('li', { class: 'mil-row out type-' + type, dataset: { id: m.id } },
|
||||
h('span', { class: 'row-ic' }, icon(Mil.TYPE_ICON[type] || 'move')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().typeLabel(type) })),
|
||||
h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)),
|
||||
sub,
|
||||
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar),
|
||||
recallable ? h('button', { class: 'btn small danger mil-recall', type: 'button', dataset: { until: String(m.recallableUntil), id: String(m.id) }, onclick: (ev) => recall(m, ev.currentTarget) },
|
||||
icon('return'), h('span', { text: App.t('mov.recall') }), mil().countdown(m.recallableUntil)) : null),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })));
|
||||
row._bar = bar; row._m = m;
|
||||
return row;
|
||||
}
|
||||
|
||||
async function recall(m, btn) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await App.api.post('/movements/' + m.id + '/recall', {}, { intent: 'recall:' + m.id });
|
||||
toast(App.t('mov.recalled'), 'ok');
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
}
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
function draw() {
|
||||
dirty = false;
|
||||
clear(listEl);
|
||||
const mv = mil().moves, now = App.now();
|
||||
const inc = mv.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
const out = mv.outgoing.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
if (inc.length) {
|
||||
listEl.appendChild(h('section', { class: 'card warn-card', role: 'alert' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('alert'), App.t('mov.incoming.head', { n: inc.length }))),
|
||||
h('ul', { class: 'mil-list' }, inc.map(incomingRow))));
|
||||
}
|
||||
const allied = (mv.alliedIncoming || []).slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
if (allied.length) {
|
||||
listEl.appendChild(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('handshake'), App.t('mov.allied.head'))),
|
||||
h('ul', { class: 'mil-list' }, allied.map((m) => h('li', { class: 'mil-row' },
|
||||
h('span', { class: 'row-ic' }, icon('shield')),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: App.t('mov.allied.title', { operator: m.toOperator ? m.toOperator.name : '?', town: (m.to && m.to.name) || '?' }) })),
|
||||
h('span', { class: 'row-sub wrap' }, m.from && m.from.owner ? App.t('mov.incoming.from', { operator: m.from.owner.name }) + ' · ' : '', mil().endLink(m.from))),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt), h('small', { text: mil().clockTime(m.arriveAt) })))))));
|
||||
}
|
||||
listEl.appendChild(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('move'), App.t('mov.outgoing.head')), h('span', { class: 'pill', text: String(out.length) })),
|
||||
out.length ? h('ul', { class: 'mil-list' }, out.map((m) => outgoingRow(m, now))) : h('p', { class: 'empty', text: mv.loaded ? App.t('mov.empty') : App.t('common.loading') })));
|
||||
tick(now);
|
||||
}
|
||||
|
||||
function tick(now) {
|
||||
if (!listEl) return;
|
||||
for (const row of listEl.querySelectorAll('li.out')) {
|
||||
if (!row._m) continue;
|
||||
row._bar.style.setProperty('--p', String(mil().progress(row._m, now)));
|
||||
}
|
||||
for (const b of listEl.querySelectorAll('.mil-recall')) if (Number(b.dataset.until) <= now) b.remove();
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'movements', titleKey: 'screen.movements', navKey: 'nav.movements', icon: 'move', hud: false,
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('div', { class: 'mil-sections' });
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.movements') }),
|
||||
h('div', { class: 'head-actions' },
|
||||
h('button', { class: 'btn small primary', type: 'button', onclick: () => App.openSend({}) }, icon('target'), App.t('mov.send')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshMovements().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')))),
|
||||
listEl));
|
||||
App.on('movements', () => { if (visible) draw(); else dirty = true; });
|
||||
App.on('lang', () => { if (box) box.querySelector('h1').textContent = App.t('screen.movements'); });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
box.querySelector('h1').textContent = App.t('screen.movements');
|
||||
draw();
|
||||
App.refreshMovements().catch(() => {});
|
||||
if (offTick) offTick();
|
||||
offTick = App.onTick(tick);
|
||||
},
|
||||
onHide() { visible = false; if (offTick) offTick(); offTick = null; },
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ incoming banner on the POP screen
|
||||
function fillBanner(el) {
|
||||
clear(el);
|
||||
const inc = mil().moves.incoming.slice().sort((a, b) => a.arriveAt - b.arriveAt);
|
||||
el.hidden = !inc.length;
|
||||
if (!inc.length) return;
|
||||
const next = inc[0];
|
||||
el.appendChild(h('div', { class: 'row-ic bad' }, icon('alert')));
|
||||
el.appendChild(h('div', { class: 'row-main' },
|
||||
h('b', { text: App.t('mov.banner.title', { n: inc.length }) }),
|
||||
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.next', { town: (next.to && next.to.name) || '?', operator: next.from && next.from.owner ? next.from.owner.name : '?' }) + ' '),
|
||||
h('span', { class: 'row-sub wrap' }, App.t('mov.banner.in') + ' ', mil().countdown(next.arriveAt))));
|
||||
el.appendChild(h('button', { class: 'btn small', type: 'button', onclick: () => App.go('movements') }, App.t('mov.banner.details')));
|
||||
}
|
||||
|
||||
App.popSections.push({
|
||||
slot: 'top',
|
||||
render() {
|
||||
const el = h('section', { class: 'card warn-card mil-banner', role: 'alert', 'aria-live': 'assertive' });
|
||||
fillBanner(el);
|
||||
return el;
|
||||
},
|
||||
});
|
||||
App.on('movements', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
|
||||
App.on('lang', () => { for (const el of document.querySelectorAll('.mil-banner')) fillBanner(el); });
|
||||
}());
|
||||
|
|
@ -275,10 +275,7 @@
|
|||
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 });
|
||||
const title = h('h1', { class: 'town-name', text: t.name }); // switching POPs lives in the resource bar (main.js)
|
||||
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'))),
|
||||
|
|
@ -376,8 +373,12 @@
|
|||
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; }
|
||||
// other screens add cards here through App.popSections (military: incoming banner on top, expansion below the power card)
|
||||
const extra = (slot) => (App.popSections || []).filter((s) => s.slot === slot).map((s) => { try { return s.render(t); } catch (e) { console.error(e); return null; } });
|
||||
const tops = extra('top');
|
||||
if (tops.some(Boolean)) box.appendChild(h('div', { class: 'pop-top' }, tops));
|
||||
box.appendChild(h('div', { class: 'cols' },
|
||||
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
|
||||
h('div', { class: 'col' }, header(t), queueCard(t), powerCard(), extra('main')),
|
||||
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
|
||||
tick(App.now());
|
||||
}
|
||||
|
|
@ -482,6 +483,7 @@
|
|||
App.on('town', onTown);
|
||||
App.on('session', () => { dirty = true; prevQueue = null; });
|
||||
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||
App.on('towns', () => { dirty = true; if (visible) draw(); });
|
||||
},
|
||||
onShow() {
|
||||
visible = true;
|
||||
|
|
|
|||
146
public/js/screens/rankings.js
Normal file
146
public/js/screens/rankings.js
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Rankings: operators by footprint, alliances by summed footprint, battle points (attack / defense / total). The server
|
||||
* returns `you` (your own rank, even when it is not on the loaded page) and a rank-offset cursor (`next`). Rows of your own
|
||||
* operator or alliance are highlighted. Names are set with textContent only.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const PAGE = 50;
|
||||
const X = () => window.SocUI;
|
||||
|
||||
let box, listBox, tabsEl, subEl;
|
||||
let tab = 'operators', by = 'attack';
|
||||
const sets = {};
|
||||
let gen = 0;
|
||||
|
||||
const keyOf = () => (tab === 'battles' ? 'battles:' + by : tab);
|
||||
const cur = () => sets[keyOf()] || (sets[keyOf()] = { items: [], next: null, total: 0, you: null, available: true, loaded: false, loading: false, err: null });
|
||||
const path = () => '/rankings/' + tab;
|
||||
|
||||
async function load(more) {
|
||||
const key = keyOf(), s = cur();
|
||||
if (s.loading) return;
|
||||
s.loading = true; s.err = null;
|
||||
const my = gen;
|
||||
if (key === keyOf()) draw();
|
||||
try {
|
||||
const q = { limit: PAGE };
|
||||
if (more && s.next !== null) q.after = s.next;
|
||||
if (tab === 'battles') q.by = by;
|
||||
const r = await App.api.get(path(), q);
|
||||
s.items = more ? Soc.mergeRanks(s.items, r.items) : r.items;
|
||||
s.next = r.next; s.total = r.total; s.you = r.you; s.loaded = true;
|
||||
if (typeof r.available === 'boolean') s.available = r.available;
|
||||
} catch (e) { s.err = e; } finally {
|
||||
s.loading = false;
|
||||
if (my === gen && key === keyOf()) draw();
|
||||
}
|
||||
}
|
||||
|
||||
const num = (n) => App.fmt.num(Math.round(n));
|
||||
|
||||
// One row: rank, name (+ tag), the value columns. `main` is the metric shown big, `sub` the small line.
|
||||
function row(r) {
|
||||
const you = Soc.isYou(tab, r, youRow());
|
||||
let name, sub, val, tap;
|
||||
if (tab === 'operators') {
|
||||
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
|
||||
tap = () => openOperator(r);
|
||||
} else if (tab === 'alliances') {
|
||||
name = r.name; sub = '[' + r.tag + '] ' + App.t('soc.rank.members', { n: r.members }) + ' · ' + App.t('soc.rank.pops', { n: r.towns }); val = App.fmt.dec(r.footprint);
|
||||
tap = () => X().openProfile(r.allianceId, { name: r.name });
|
||||
} else {
|
||||
name = r.name; sub = (r.allianceTag ? '[' + r.allianceTag + '] ' : '') + App.t('soc.rank.att', { n: num(r.attackPoints) }) + ' · ' + App.t('soc.rank.def', { n: num(r.defensePoints) });
|
||||
val = num(Soc.battlePoints(r, by));
|
||||
tap = () => openOperator(r);
|
||||
}
|
||||
return h('li', null, h('button', { class: 'soc-rank' + (you ? ' you' : ''), type: 'button', onclick: tap, 'aria-current': you ? 'true' : null },
|
||||
h('span', { class: 'soc-rk mono', text: '#' + r.rank }),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), you ? h('span', { class: 'pill accent', text: App.t('soc.you') }) : null), h('span', { class: 'row-sub', text: sub })),
|
||||
h('span', { class: 'soc-val mono', text: val })));
|
||||
}
|
||||
|
||||
const youRow = () => cur().you;
|
||||
|
||||
function openOperator(r) {
|
||||
const me = X().myOperatorId();
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v', text: v }));
|
||||
const body = h('div', { class: 'detail' },
|
||||
h('div', { class: 'pill-row' }, h('span', { class: 'pill soc-tag mono', text: '#' + r.rank }), r.allianceTag ? X().tagPill(r.allianceTag) : null, r.asNumber ? h('span', { class: 'pill mono', text: UpstreamI18n.fmtAs(r.asNumber) }) : null),
|
||||
h('div', null,
|
||||
r.footprint !== undefined ? kv(App.t('soc.footprint'), App.fmt.dec(r.footprint)) : null,
|
||||
r.towns !== undefined ? kv(App.t('soc.member.pops'), String(r.towns)) : null,
|
||||
r.attackPoints !== undefined ? kv(App.t('soc.rank.attack'), num(r.attackPoints)) : null,
|
||||
r.defensePoints !== undefined ? kv(App.t('soc.rank.defense'), num(r.defensePoints)) : null));
|
||||
const sheet = openSheet({ title: r.name, icon: 'users', closeLabel: App.t('common.close'), body });
|
||||
if (r.allianceId) body.appendChild(h('button', { class: 'btn wide', type: 'button', onclick: () => { sheet.close(); X().openProfile(r.allianceId, { name: r.allianceTag }); } }, icon('users'), App.t('soc.rank.viewAlliance')));
|
||||
if (r.operatorId !== me) body.appendChild(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { sheet.close(); X().openCompose({ operator: { operatorId: r.operatorId, name: r.name } }); } }, icon('mail'), App.t('soc.member.message')));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!listBox) return;
|
||||
clear(listBox);
|
||||
for (const b of tabsEl.children) b.setAttribute('aria-pressed', String(b.dataset.tab === tab));
|
||||
subEl.hidden = tab !== 'battles';
|
||||
for (const b of subEl.children) b.setAttribute('aria-pressed', String(b.dataset.by === by));
|
||||
const s = cur();
|
||||
if (s.err) { listBox.appendChild(X().errorBox(s.err, () => load(false))); return; }
|
||||
if (!s.loaded) { listBox.appendChild(X().loading()); return; }
|
||||
if (tab === 'battles' && !s.available) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t('soc.rank.unavailable') })); return; }
|
||||
|
||||
if (s.you) {
|
||||
const y = s.you;
|
||||
const inList = s.items.some((r) => r.rank === y.rank);
|
||||
listBox.appendChild(h('div', { class: 'card soc-card soc-yourank' },
|
||||
h('span', { class: 'soc-yr-n mono', text: '#' + y.rank }),
|
||||
h('span', { class: 'row-main' }, h('b', { text: App.t('soc.rank.yours') }),
|
||||
h('span', { class: 'row-sub', text: App.t('soc.rank.of', { n: s.total }) + (tab === 'battles' ? ' · ' + num(Soc.battlePoints(y, by)) : ' · ' + App.fmt.dec(y.footprint)) })),
|
||||
inList ? null : h('span', { class: 'pill dim', text: App.t('soc.rank.notShown') })));
|
||||
} else if (tab === 'alliances') {
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noAlliance') }));
|
||||
} else if (tab === 'battles') {
|
||||
listBox.appendChild(h('p', { class: 'field-hint soc-hint', text: App.t('soc.rank.noPoints') }));
|
||||
}
|
||||
if (!s.items.length) { listBox.appendChild(h('p', { class: 'empty pad', text: App.t(tab === 'battles' ? 'soc.rank.noBattles' : 'soc.rank.empty') })); return; }
|
||||
const ol = h('ol', { class: 'soc-ranklist' });
|
||||
for (const r of s.items) ol.appendChild(row(r));
|
||||
listBox.appendChild(ol);
|
||||
if (s.next !== null) listBox.appendChild(h('button', { class: 'btn small wide', type: 'button', disabled: s.loading, text: App.t('soc.more') + ' (' + s.items.length + '/' + s.total + ')', onclick: () => load(true) }));
|
||||
}
|
||||
|
||||
function setTab(t) {
|
||||
tab = t;
|
||||
draw();
|
||||
if (!cur().loaded) load(false);
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'rankings', titleKey: 'screen.rankings', navKey: 'nav.rankings', icon: 'trophy', hud: false, navGroup: 'more',
|
||||
render(container) {
|
||||
box = container;
|
||||
const tabs = [['operators', 'soc.rank.tab.operators'], ['alliances', 'soc.rank.tab.alliances'], ['battles', 'soc.rank.tab.battles']];
|
||||
tabsEl = h('div', { class: 'seg soc-tabs', role: 'group', 'aria-label': App.t('soc.tab.label') },
|
||||
tabs.map(([id, key]) => h('button', { class: 'seg-btn', type: 'button', dataset: { tab: id }, 'aria-pressed': String(tab === id), text: App.t(key), onclick: () => setTab(id) })));
|
||||
subEl = h('div', { class: 'seg soc-subtabs', role: 'group', 'aria-label': App.t('soc.rank.by'), hidden: true },
|
||||
['attack', 'defense', 'total'].map((k) => h('button', { class: 'chip-btn', type: 'button', dataset: { by: k }, 'aria-pressed': String(by === k), text: App.t('soc.rank.by.' + k), onclick: () => { by = k; draw(); if (!cur().loaded) load(false); } })));
|
||||
listBox = h('div', { class: 'soc-listbox' });
|
||||
box.appendChild(h('div', { class: 'page soc-page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-rank-h', text: App.t('screen.rankings') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { delete sets[keyOf()]; load(false); } }, icon('refresh'))),
|
||||
tabsEl, subEl, listBox));
|
||||
App.on('session', () => { for (const k of Object.keys(sets)) delete sets[k]; });
|
||||
},
|
||||
onShow() {
|
||||
gen++;
|
||||
box.querySelector('#soc-rank-h').textContent = App.t('screen.rankings');
|
||||
const labels = { operators: 'soc.rank.tab.operators', alliances: 'soc.rank.tab.alliances', battles: 'soc.rank.tab.battles' };
|
||||
for (const b of tabsEl.children) b.textContent = App.t(labels[b.dataset.tab]);
|
||||
for (const b of subEl.children) b.textContent = App.t('soc.rank.by.' + b.dataset.by);
|
||||
draw();
|
||||
load(false); // rankings move: always refresh the first page when the screen opens
|
||||
},
|
||||
onHide() { gen++; },
|
||||
});
|
||||
}());
|
||||
316
public/js/screens/reports.js
Normal file
316
public/js/screens/reports.js
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
|
||||
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), scan,
|
||||
* scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that jump to the map.
|
||||
* `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
const mil = () => App.mil;
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const PAGE = 25;
|
||||
|
||||
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
|
||||
|
||||
// ------------------------------------------------------------------ list rows
|
||||
const nameOf = (o) => (o && o.name) || '?';
|
||||
const townOf = (t) => (t ? t.name : '?');
|
||||
|
||||
// { icon, title, sub, tone } for the list
|
||||
function describe(it) {
|
||||
const s = it.summary || {};
|
||||
switch (it.type) {
|
||||
case 'raid': case 'attack': case 'takeover': {
|
||||
const res = Mil.perspective(it.role, s.outcome);
|
||||
const mine = it.role === 'attacker';
|
||||
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
|
||||
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
|
||||
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
|
||||
}
|
||||
case 'scan': {
|
||||
const where = s.target ? townOf(s.target) : (s.site ? s.site.x + ', ' + s.site.y : '?');
|
||||
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
|
||||
}
|
||||
case 'scan_detected':
|
||||
return { icon: 'eye', title: App.t('rep.detected.title', { town: townOf(s.target) }), sub: s.identityRevealed && s.by ? App.t('rep.sub.by', { name: nameOf(s.by) }) : App.t('rep.detected.unknown'), tone: 'warn' };
|
||||
case 'incumbent':
|
||||
return { icon: 'b-core_router', title: App.t('rep.incumbent.title', { x: s.site ? s.site.x : '?', y: s.site ? s.site.y : '?' }), sub: '', tone: s.outcome === 'attacker_won' ? 'good' : 'bad', badge: s.outcome === 'attacker_won' ? App.t('rep.victory') : App.t('rep.defeat') };
|
||||
case 'settle':
|
||||
return { icon: 'flag', title: App.t('rep.settle.title', { name: s.town ? s.town.name : '?' }), sub: '', tone: 'good' };
|
||||
case 'reinforce':
|
||||
return { icon: 'shield', title: it.role === 'sender' ? App.t('rep.reinforce.sender', { town: townOf(s.host) }) : App.t('rep.reinforce.target', { town: townOf(s.host) }), sub: mil().unitsText(s.units), tone: 'neutral' };
|
||||
case 'movement_failed':
|
||||
return { icon: 'alert', title: App.t('rep.failed.title', { type: mil().typeLabel(s.movementType) }), sub: reasonText(s.reason), tone: 'bad' };
|
||||
default:
|
||||
return { icon: 'report', title: mil().reportTypeLabel(it.type), sub: '', tone: 'neutral' };
|
||||
}
|
||||
}
|
||||
|
||||
function reasonText(code) {
|
||||
if (!code) return '';
|
||||
if (UpstreamI18n.strings.en['rep.reason.' + code]) return App.t('rep.reason.' + code);
|
||||
if (UpstreamI18n.strings.en['err.' + code]) return App.t('err.' + code);
|
||||
return code;
|
||||
}
|
||||
|
||||
function row(it) {
|
||||
const d = describe(it);
|
||||
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (it.read ? '' : ' new'), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id) },
|
||||
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, it.read ? null : h('span', { class: 'pill accent', text: App.t('alerts.new') })),
|
||||
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null),
|
||||
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
clear(listEl);
|
||||
if (!items.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading ? App.t('common.loading') : App.t('rep.empty') }))); }
|
||||
for (const it of items) listEl.appendChild(row(it));
|
||||
moreBtn.hidden = next === null;
|
||||
}
|
||||
|
||||
async function load(more) {
|
||||
if (loading) return;
|
||||
loading = true; statusEl.hidden = true;
|
||||
try {
|
||||
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
|
||||
items = more ? items.concat(r.items.filter((x) => !items.some((y) => y.id === x.id))) : r.items;
|
||||
next = r.next;
|
||||
mil().reportsUnread = r.unread;
|
||||
App.setBadge('reports', r.unread, 'info');
|
||||
} catch (e) {
|
||||
statusEl.textContent = App.errMsg(e); statusEl.hidden = false;
|
||||
} finally { loading = false; }
|
||||
draw();
|
||||
}
|
||||
|
||||
async function markAll() {
|
||||
try {
|
||||
await App.api.post('/reports/read-all', {}, { intent: 'reports:read-all' });
|
||||
for (const it of items) it.read = true;
|
||||
App.setBadge('reports', 0, 'info');
|
||||
draw();
|
||||
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ detail pieces
|
||||
const sec = (title, ...kids) => h('section', { class: 'rep-sec' }, h('h3', { class: 'sub', text: title }), kids);
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
|
||||
function unitsTable(sent, lost, survivors) {
|
||||
const ids = D.UNIT_ORDER.filter((u) => (sent && sent[u]) || (lost && lost[u]) || (survivors && survivors[u]));
|
||||
if (!ids.length) return h('p', { class: 'empty', text: App.t('rep.noUnits') });
|
||||
return h('table', { class: 'mil-table' },
|
||||
h('thead', null, h('tr', null, h('th', { text: '' }), h('th', { text: App.t('rep.sent') }), h('th', { text: App.t('rep.lost') }), h('th', { text: App.t('rep.left') }))),
|
||||
h('tbody', null, ids.map((u) => h('tr', null,
|
||||
h('td', { text: mil().unitName(u) }),
|
||||
h('td', { class: 'mono', text: num((sent && sent[u]) || 0) }),
|
||||
h('td', { class: 'mono' + (lost && lost[u] ? ' bad' : ''), text: num((lost && lost[u]) || 0) }),
|
||||
h('td', { class: 'mono', text: num((survivors && survivors[u]) || 0) })))));
|
||||
}
|
||||
|
||||
const party = (label, operator, town) => kv(label, h('span', { class: 'rep-party' },
|
||||
h('b', { text: operator ? operator.name : '?' }), operator && operator.asNumber ? h('small', { class: 'dimmer', text: ' ' + UpstreamI18n.fmtAs(operator.asNumber) }) : null,
|
||||
town ? mil().endLink(town) : null));
|
||||
|
||||
function verdict(role, outcome) {
|
||||
const res = Mil.perspective(role, outcome);
|
||||
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
|
||||
}
|
||||
|
||||
function combatBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(verdict(r.role, d.outcome));
|
||||
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) + ' · ' + mil().reportTypeLabel(d.type) }));
|
||||
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.attacker.town));
|
||||
out.push(party(App.t('rep.defender'), d.defender.operator, d.defender.town));
|
||||
const p = d.power || {};
|
||||
out.push(sec(App.t('rep.power'),
|
||||
kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })),
|
||||
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) })),
|
||||
p.firewallLevel !== undefined ? kv(App.t('rep.power.firewall'), h('span', { class: 'mono', text: p.firewallLevel + (p.effectiveFirewall !== undefined && p.effectiveFirewall !== p.firewallLevel ? ' → ' + App.fmt.dec(p.effectiveFirewall) : '') })) : null));
|
||||
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
|
||||
const groups = (d.defender.groups || []);
|
||||
out.push(sec(App.t('rep.defenderUnits'), groups.length ? groups.map((g) => h('div', { class: 'rep-group' },
|
||||
h('p', { class: 'row-sub wrap' }, g.ownerTownId === (d.defender.town && d.defender.town.id) ? App.t('rep.group.home') : App.t('rep.group.reinf', { town: '#' + g.ownerTownId }), g.offline ? ' · ' + App.t('rep.group.offline') : ''),
|
||||
unitsTable(g.sent, g.lost, g.survivors))) : h('p', { class: 'empty', text: App.t('rep.noUnits') })));
|
||||
if (d.loot && D.RESOURCES.some((x) => d.loot[x])) {
|
||||
out.push(sec(App.t('rep.loot'), mil().resChips(d.loot, true), d.cacheHidden ? h('p', { class: 'row-sub', text: App.t('rep.cache', { p: Math.round(d.cacheHidden * 100) }) }) : null));
|
||||
}
|
||||
if (d.siege) out.push(sec(App.t('rep.siege'), h('p', { text: App.t('rep.siege.line', { name: App.buildingName(d.siege.type), a: d.siege.from, b: d.siege.to }) })));
|
||||
if (d.takeover) {
|
||||
const t = d.takeover;
|
||||
const lines = [];
|
||||
if (t.blocked) lines.push(h('p', { class: 'reason', text: App.t('rep.takeover.blocked.' + t.blocked) }));
|
||||
else {
|
||||
lines.push(kv(App.t('rep.takeover.loyalty'), h('b', { class: 'mono', text: num(t.loyaltyBefore) + ' → ' + num(t.loyaltyAfter) + ' (−' + num(t.drop) + ')' })));
|
||||
if (t.capital) lines.push(h('p', { class: 'row-sub wrap', text: App.t('rep.takeover.capital') }));
|
||||
}
|
||||
if (d.capturedTown) lines.push(h('p', { class: 'good', text: App.t('rep.takeover.captured') }));
|
||||
out.push(sec(App.t('rep.takeover'), lines));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function scanBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict ' + (d.success ? 'victory' : 'defeat') }, icon(d.success ? 'eye' : 'alert'), h('b', { text: d.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed') })));
|
||||
if (d.site) out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
||||
if (d.target) out.push(party(App.t('rep.defender'), d.operator, d.target));
|
||||
if (d.strength) out.push(kv(App.t('rep.scan.strength'), h('span', { class: 'mono', text: App.fmt.dec(d.strength.attacker) + ' vs ' + App.fmt.dec(d.strength.defender) })));
|
||||
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
|
||||
const intel = d.intel;
|
||||
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
|
||||
if (d.site) { // incumbent site
|
||||
out.push(sec(App.t('rep.intel'),
|
||||
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
|
||||
intel.bonusAvailable ? h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.bonus', { n: num(intel.hardwareBonus) }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.incumbent.taken') })));
|
||||
return out;
|
||||
}
|
||||
out.push(sec(App.t('rep.intel.resources'), mil().resChips(intel.resources)));
|
||||
out.push(sec(App.t('rep.intel.units'),
|
||||
!intel.online ? h('p', { class: 'reason', text: App.t('rep.intel.offline') }) : null,
|
||||
unitsTable(intel.units.home, {}, intel.units.home),
|
||||
(intel.units.stationed || []).map((g) => h('div', { class: 'rep-group' }, h('p', { class: 'row-sub wrap', text: App.t('rep.group.reinf', { town: '#' + g.ownerTownId }) }), h('p', { text: mil().unitsText(g.units) })))));
|
||||
if (intel.buildings) {
|
||||
out.push(sec(App.t('rep.intel.buildings'),
|
||||
h('ul', { class: 'rep-buildings' }, intel.buildings.filter((b) => b.level > 0).map((b) => h('li', null, h('span', { text: App.buildingName(b.type) }), h('b', { class: 'mono', text: String(b.level) }))))));
|
||||
}
|
||||
if (intel.loyalty !== undefined) out.push(kv(App.t('pop.loyalty'), h('b', { class: 'mono', text: num(intel.loyalty) })));
|
||||
if (intel.outgoing && intel.outgoing.length) {
|
||||
out.push(sec(App.t('rep.intel.outgoing'), h('ul', { class: 'rep-buildings' }, intel.outgoing.map((m) => h('li', null, h('span', { text: mil().typeLabel(m.type) }), mil().coordLink(m.to.x, m.to.y), h('small', { class: 'dimmer', text: mil().clockTime(m.arriveAt) }))))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function detectedBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict defeat' }, icon('eye'), h('b', { text: App.t('rep.detected.title', { town: townOf(d.target) }) })));
|
||||
if (d.target) out.push(kv(App.t('rep.target'), mil().endLink(d.target)));
|
||||
if (d.identityRevealed && d.by) out.push(party(App.t('rep.scannedBy'), d.by.operator, d.by.town));
|
||||
else out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.detected.unknown') }));
|
||||
return out;
|
||||
}
|
||||
|
||||
function incumbentBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(verdict('attacker', d.outcome));
|
||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
||||
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
|
||||
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
|
||||
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
|
||||
if (d.bonus) out.push(sec(App.t('rep.incumbent.reward'), mil().resChips({ hardware: d.bonus.hardware }, true), d.bonus.researchSpeedBonus ? h('p', { class: 'row-sub', text: App.t('units.research.speed', { p: Math.round(d.bonus.researchSpeedBonus * 100) }) }) : null));
|
||||
return out;
|
||||
}
|
||||
|
||||
function settleBody(r, ctl) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
|
||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
|
||||
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
|
||||
out.push(h('button', { class: 'btn primary wide', type: 'button', onclick: async () => {
|
||||
ctl.close();
|
||||
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
|
||||
App.setTown(d.town.id); App.go('pop');
|
||||
} }, icon('pop'), App.t('rep.settle.open')));
|
||||
out.push(h('p', { class: 'row-sub wrap', text: App.t('rep.settle.hint') }));
|
||||
return out;
|
||||
}
|
||||
|
||||
function reinforceBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(kv(App.t('rep.from'), h('span', null, h('b', { text: nameOf(d.operator) }), mil().endLink(d.from))));
|
||||
out.push(kv(App.t('rep.host'), h('span', null, h('b', { text: nameOf(d.hostOperator) }), mil().endLink(d.host))));
|
||||
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) })));
|
||||
return out;
|
||||
}
|
||||
|
||||
function failedBody(r) {
|
||||
const d = r.data, out = [];
|
||||
out.push(h('div', { class: 'rep-verdict defeat' }, icon('alert'), h('b', { text: App.t('rep.failed.title', { type: mil().typeLabel(d.movementType) }) })));
|
||||
out.push(h('p', { text: reasonText(d.reason) }));
|
||||
if (d.to) out.push(kv(App.t('rep.target'), mil().coordLink(d.to.x, d.to.y)));
|
||||
out.push(sec(App.t('rep.units'), h('p', { text: mil().unitsText(d.units) }), h('p', { class: 'row-sub wrap', text: App.t('rep.failed.home') })));
|
||||
return out;
|
||||
}
|
||||
|
||||
function genericBody(r) {
|
||||
return [h('pre', { class: 'rep-raw', text: JSON.stringify(r.summary || {}, null, 1).slice(0, 1500) })];
|
||||
}
|
||||
|
||||
function bodyFor(r, ctl) {
|
||||
switch (r.type) {
|
||||
case 'raid': case 'attack': case 'takeover': return combatBody(r);
|
||||
case 'scan': return scanBody(r);
|
||||
case 'scan_detected': return detectedBody(r);
|
||||
case 'incumbent': return incumbentBody(r);
|
||||
case 'settle': return settleBody(r, ctl);
|
||||
case 'reinforce': return reinforceBody(r);
|
||||
case 'movement_failed': return failedBody(r);
|
||||
default: return genericBody(r);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ detail sheet
|
||||
async function openReport(id) {
|
||||
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
|
||||
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
|
||||
try {
|
||||
const res = await App.api.get('/reports/' + id);
|
||||
const r = res.report;
|
||||
ctl.setTitle(mil().reportTypeLabel(r.type));
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + App.t('rep.role.' + r.role) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
|
||||
let parts;
|
||||
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
|
||||
for (const p of parts.flat(2)) if (p) body.appendChild(p);
|
||||
if (!r.read) {
|
||||
App.api.post('/reports/' + id + '/read', {}).then(() => {
|
||||
const it = items.find((x) => x.id === id); if (it) it.read = true;
|
||||
if (visible) draw();
|
||||
App.refreshReportsUnread().catch(() => {});
|
||||
}).catch(() => {});
|
||||
}
|
||||
} catch (e) {
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'form-error', text: App.errMsg(e) }));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
App.registerScreen({
|
||||
id: 'reports', titleKey: 'screen.reports', navKey: 'nav.reports', icon: 'report', navGroup: 'more', hud: false,
|
||||
render(container) {
|
||||
box = container;
|
||||
listEl = h('ul', { class: 'alert-list' });
|
||||
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
|
||||
box.appendChild(h('div', { class: 'page' },
|
||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
|
||||
h('div', { class: 'head-actions' },
|
||||
h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll')),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
|
||||
statusEl, listEl, moreBtn));
|
||||
App.on('session', () => { items = []; next = null; });
|
||||
App.on('report', () => { if (visible) load(false); });
|
||||
},
|
||||
onShow(params) {
|
||||
visible = true;
|
||||
box.querySelector('h1').textContent = App.t('screen.reports');
|
||||
moreBtn.textContent = App.t('rep.older');
|
||||
draw();
|
||||
load(false);
|
||||
if (params && params.open) openReport(Number(params.open));
|
||||
if (offAgo) offAgo();
|
||||
offAgo = 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() { visible = false; if (offAgo) offAgo(); offAgo = null; },
|
||||
});
|
||||
}());
|
||||
339
public/js/screens/send.js
Normal file
339
public/js/screens/send.js
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The send dialog: App.openSend({ x, y, fromTownId, type }). Opened from a map tile, the POP screen, the units screen and the
|
||||
* movements screen. It looks the target up (GET /map/tile), offers the movement types that can work, lets you pick units
|
||||
* (or cargo, or the wild slots of a new POP), previews latency and arrival from rules.js and sends POST /movements. The
|
||||
* server re-validates everything; this dialog only avoids obviously doomed sends and explains the greyed-out ones.
|
||||
* An Idempotency intent is generated per opened dialog (and again after a successful send), so a retried tap cannot send twice.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
const mil = () => App.mil;
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
||||
|
||||
App.openSend = function openSend(opts) {
|
||||
opts = opts || {};
|
||||
const st = {
|
||||
x: Number.isInteger(opts.x) ? opts.x : null, y: Number.isInteger(opts.y) ? opts.y : null,
|
||||
tile: null, tileErr: null, fromId: null, from: null, type: null, units: {}, cargo: {}, target: '',
|
||||
wild: D.START.wild.slice(), endProtection: false, busy: false, nonce: nonce(), loadSeq: 0, tileSeq: 0, options: [],
|
||||
};
|
||||
const own = App.state.towns;
|
||||
st.fromId = own.some((t) => t.id === opts.fromTownId) ? opts.fromTownId : (App.state.townId || (own[0] && own[0].id));
|
||||
if (!st.fromId) { toast(App.t('pop.noTown'), 'error'); return; }
|
||||
|
||||
const body = h('div', { class: 'detail send' });
|
||||
let offTick = null;
|
||||
const ctl = openSheet({ title: App.t('send.title'), icon: 'target', closeLabel: App.t('common.close'), body, onClose: () => { if (offTick) offTick(); } });
|
||||
|
||||
const secTarget = h('div', { class: 'send-sec' });
|
||||
const secFrom = h('div', { class: 'send-sec' });
|
||||
const secType = h('div', { class: 'send-sec' });
|
||||
const secUnits = h('div', { class: 'send-sec' });
|
||||
const secPreview = h('div', { class: 'send-sec' });
|
||||
const secWarn = h('div', { class: 'send-sec' });
|
||||
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go() }, icon('target'), h('span', { text: App.t('send.go') }));
|
||||
body.appendChild(secTarget); body.appendChild(secFrom); body.appendChild(secType); body.appendChild(secUnits); body.appendChild(secPreview); body.appendChild(secWarn);
|
||||
body.appendChild(h('div', { class: 'send-foot' }, errEl, submit));
|
||||
|
||||
const fromTown = () => own.find((t) => t.id === st.fromId);
|
||||
const home = () => (st.from ? st.from.td.military.units.home : {});
|
||||
const op = () => App.state.operator;
|
||||
|
||||
// ------------------------------------------------------------------ data
|
||||
async function loadFrom() {
|
||||
const seq = ++st.loadSeq;
|
||||
let r;
|
||||
try {
|
||||
if (st.fromId === App.state.townId && App.state.townData && App.state.townData.military) r = { td: App.state.townData, rt: App.rulesTown(), at: App.fetchedServerTime };
|
||||
else { const x = await mil().loadTown(st.fromId); r = { td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime), at: x.serverTime }; }
|
||||
} catch (e) { if (seq === st.loadSeq) showErr(App.errMsg(e)); return; }
|
||||
if (seq !== st.loadSeq) return;
|
||||
st.from = r;
|
||||
afterData();
|
||||
}
|
||||
|
||||
async function loadTile() {
|
||||
if (st.x === null || st.y === null) { st.tile = null; return; }
|
||||
const seq = ++st.tileSeq;
|
||||
st.tile = null; st.tileErr = null;
|
||||
drawTarget();
|
||||
try {
|
||||
const t = await App.api.get('/map/tile', { x: st.x, y: st.y });
|
||||
if (seq !== st.tileSeq) return;
|
||||
st.tile = t;
|
||||
} catch (e) {
|
||||
if (seq !== st.tileSeq) return;
|
||||
st.tileErr = e.code === 'not_found' ? App.t('tile.void') : App.errMsg(e);
|
||||
}
|
||||
afterData();
|
||||
}
|
||||
|
||||
function afterData() {
|
||||
drawTarget();
|
||||
drawFrom();
|
||||
if (!st.tile || !st.from) { drawTypes(); return; }
|
||||
computeOptions();
|
||||
drawTypes();
|
||||
}
|
||||
|
||||
function computeOptions() {
|
||||
const m = st.from.td.military;
|
||||
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0 });
|
||||
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
|
||||
const first = st.options.find((o) => o.ok);
|
||||
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
|
||||
}
|
||||
|
||||
function setType(type, keep) {
|
||||
if (!keep && type === st.type) return;
|
||||
st.type = type;
|
||||
st.units = type ? Mil.defaultUnits(type, home()) : {};
|
||||
st.cargo = {}; st.target = ''; st.endProtection = false;
|
||||
showErr('');
|
||||
drawTypes(); drawUnits(); refresh();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ sections
|
||||
function drawTarget() {
|
||||
clear(secTarget);
|
||||
const t = st.tile;
|
||||
const xin = h('input', { type: 'number', inputmode: 'numeric', value: st.x === null ? '' : String(st.x), class: 'mil-num', 'aria-label': 'x', placeholder: 'x' });
|
||||
const yin = h('input', { type: 'number', inputmode: 'numeric', value: st.y === null ? '' : String(st.y), class: 'mil-num', 'aria-label': 'y', placeholder: 'y' });
|
||||
const lookup = () => {
|
||||
const x = Math.round(Number(xin.value)), y = Math.round(Number(yin.value));
|
||||
if (xin.value === '' || yin.value === '' || !Number.isFinite(x) || !Number.isFinite(y)) return;
|
||||
st.x = x; st.y = y; st.type = null; loadTile();
|
||||
};
|
||||
secTarget.appendChild(h('h3', { class: 'sub', text: App.t('send.target') }));
|
||||
secTarget.appendChild(h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin,
|
||||
h('button', { class: 'btn small', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))));
|
||||
if (!t) {
|
||||
secTarget.appendChild(h('div', { class: 'chips' }, own.map((o) => h('button', { class: 'chip-btn', type: 'button', onclick: () => { st.x = o.x; st.y = o.y; st.type = null; loadTile(); } }, o.name))));
|
||||
}
|
||||
if (st.tileErr) { secTarget.appendChild(h('p', { class: 'reason', text: st.tileErr })); return; }
|
||||
if (st.x !== null && !t) { secTarget.appendChild(h('p', { class: 'dimmer', text: App.t('common.loading') })); return; }
|
||||
if (!t) return;
|
||||
const pills = [h('span', { class: 'pill', text: App.t('tile.' + t.type) })];
|
||||
if (t.town) {
|
||||
if (t.town.mine) pills.push(h('span', { class: 'pill accent', text: App.t('map.info.yours') }));
|
||||
if (t.town.isCapital) pills.push(h('span', { class: 'pill', text: App.t('map.info.capital') }));
|
||||
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
|
||||
}
|
||||
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
|
||||
secTarget.appendChild(h('div', { class: 'send-target' },
|
||||
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : App.t('tile.' + t.type) }), mil().coordLink(t.x, t.y)),
|
||||
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
|
||||
h('div', { class: 'pill-row' }, pills)));
|
||||
}
|
||||
|
||||
function drawFrom() {
|
||||
clear(secFrom);
|
||||
if (own.length < 2) return;
|
||||
secFrom.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
|
||||
h('select', { onchange: (e) => { st.fromId = Number(e.target.value); st.from = null; st.type = null; st.units = {}; drawUnits(); drawTypes(); loadFrom(); } },
|
||||
own.map((o) => h('option', { value: o.id, selected: o.id === st.fromId, text: o.name })))));
|
||||
}
|
||||
|
||||
function reasonText(o) {
|
||||
const r = o.reason || '';
|
||||
if (r.indexOf('settle:') === 0) {
|
||||
const code = r.slice(7), s = st.tile && st.tile.settle ? st.tile.settle : {};
|
||||
if (code === 'footprint_too_low') return App.t('send.reason.footprint', { have: num(s.footprint), need: num(s.footprintNeeded) });
|
||||
if (code === 'out_of_range') return App.t('send.reason.range', { n: s.maxDistance || D.EXPANSION.maxDistance });
|
||||
return App.t('send.reason.cannotSettle');
|
||||
}
|
||||
return App.t('send.reason.' + r);
|
||||
}
|
||||
|
||||
function drawTypes() {
|
||||
clear(secType);
|
||||
if (!st.tile || !st.from) return;
|
||||
if (!st.options.length) { secType.appendChild(h('p', { class: 'empty', text: App.t('send.nothing') })); return; }
|
||||
secType.appendChild(h('h3', { class: 'sub', text: App.t('send.what') }));
|
||||
secType.appendChild(h('div', { class: 'seg wrap-seg', role: 'group', 'aria-label': App.t('send.what') }, st.options.map((o) =>
|
||||
h('button', { class: 'seg-btn', type: 'button', disabled: !o.ok, 'aria-pressed': String(o.type === st.type), onclick: () => setType(o.type) }, icon(Mil.TYPE_ICON[o.type]), h('span', { text: mil().typeLabel(o.type) })))));
|
||||
const off = st.options.filter((o) => !o.ok);
|
||||
if (off.length) secType.appendChild(h('ul', { class: 'send-why' }, off.map((o) => h('li', { class: 'row-sub wrap', text: mil().typeLabel(o.type) + ': ' + reasonText(o) }))));
|
||||
}
|
||||
|
||||
function pickRow(label, have, cur, onChange, sub) {
|
||||
const range = h('input', { type: 'range', min: '0', max: String(have), step: '1', value: String(cur), 'aria-label': label });
|
||||
const numIn = h('input', { type: 'number', inputmode: 'numeric', min: '0', max: String(have), value: String(cur), class: 'mil-num', 'aria-label': label });
|
||||
const set = (v) => { v = Math.max(0, Math.min(have, Math.floor(Number(v)) || 0)); range.value = String(v); numIn.value = String(v); onChange(v); };
|
||||
range.addEventListener('input', () => set(range.value));
|
||||
numIn.addEventListener('input', () => set(numIn.value));
|
||||
return h('div', { class: 'mil-pick' },
|
||||
h('div', { class: 'row' }, h('span', null, h('b', { text: label }), h('span', { class: 'dimmer', text: ' / ' + num(have) })), sub || null),
|
||||
h('div', { class: 'pick-ctl' },
|
||||
h('button', { class: 'btn small', type: 'button', 'aria-label': '-1', onclick: () => set(Number(numIn.value) - 1) }, '−'),
|
||||
range,
|
||||
h('button', { class: 'btn small', type: 'button', 'aria-label': '+1', onclick: () => set(Number(numIn.value) + 1) }, '+'),
|
||||
numIn,
|
||||
h('button', { class: 'btn small', type: 'button', onclick: () => set(have) }, App.t('send.all'))));
|
||||
}
|
||||
|
||||
function drawUnits() {
|
||||
clear(secUnits);
|
||||
const type = st.type;
|
||||
if (!type || !st.from) return;
|
||||
const opt = st.options.find((o) => o.type === type);
|
||||
if (!opt || !opt.ok) return; // greyed out: the reason is shown with the type picker
|
||||
const h0 = home();
|
||||
if (type === 'settle') {
|
||||
const s = st.tile.settle || {};
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.settle.title') }));
|
||||
secUnits.appendChild(h('p', { class: 'preview', text: App.t('send.settle.crews', { n: D.EXPANSION.crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) }));
|
||||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.settle.footprint', { have: num(s.footprint), need: num(s.footprintNeeded), n: s.maxDistance || D.EXPANSION.maxDistance }) }));
|
||||
for (let i = 0; i < D.WILD_SLOTS; i++) {
|
||||
secUnits.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.settle.wild', { n: i + 1 }) }),
|
||||
h('select', { onchange: (e) => { st.wild[i] = e.target.value; } },
|
||||
D.FIELD_TYPES.map((ft) => h('option', { value: ft, selected: st.wild[i] === ft, text: App.buildingName(ft) + ' (' + App.resName(D.FIELD_PRODUCES[ft]) + ')' })))));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (type === 'transport') {
|
||||
const m = st.from.td.military;
|
||||
const cur = R.resourcesAt(st.from.rt, App.now()).amounts;
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.cargo') }));
|
||||
secUnits.appendChild(h('p', { class: 'row-sub wrap', text: App.t('send.cargo.cap', { n: num(m.transport.capacityPerLink), free: Math.max(0, m.transport.links - m.transport.active), links: m.transport.links }) }));
|
||||
for (const r of D.RESOURCES) {
|
||||
const have = Math.floor(cur[r] || 0);
|
||||
secUnits.appendChild(pickRow(App.resName(r), have, st.cargo[r] || 0, (v) => { if (v > 0) st.cargo[r] = v; else delete st.cargo[r]; refresh(); }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const rows = Mil.unitsForType(type, h0);
|
||||
secUnits.appendChild(h('h3', { class: 'sub', text: App.t('send.units') }));
|
||||
if (!rows.length) { secUnits.appendChild(h('p', { class: 'empty', text: App.t('send.reason.no_units') })); return; }
|
||||
for (const r of rows) {
|
||||
const def = D.UNITS[r.unit];
|
||||
secUnits.appendChild(pickRow(mil().unitName(r.unit), r.have, st.units[r.unit] || 0, (v) => { if (v > 0) st.units[r.unit] = v; else delete st.units[r.unit]; refresh(); },
|
||||
h('span', { class: 'row-sub', text: def.speed + ' ' + App.t('send.tilesPerHour') })));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ preview, warnings, button state
|
||||
function ready() {
|
||||
if (!st.tile || !st.from || !st.type) return { ok: false, why: '' };
|
||||
const o = st.options.find((x) => x.type === st.type);
|
||||
if (!o || !o.ok) return { ok: false, why: '' };
|
||||
const m = st.from.td.military;
|
||||
if (!m.units.online) return { ok: false, why: App.t('err.units_offline') };
|
||||
if (st.type === 'transport') {
|
||||
const total = Object.keys(st.cargo).reduce((s, k) => s + st.cargo[k], 0);
|
||||
if (total < 1) return { ok: false, why: '' };
|
||||
if (total > m.transport.capacityPerLink) return { ok: false, why: App.t('err.capacity_exceeded') };
|
||||
} else {
|
||||
const sel = Mil.cleanSelection(st.units, home());
|
||||
if (Mil.sumUnits(sel) < 1) return { ok: false, why: '' };
|
||||
if (st.type === 'takeover' && !(sel[D.EXPANSION.conquestUnit] > 0)) return { ok: false, why: App.t('send.reason.needs_ma_team') };
|
||||
const chk = R.checkUnitsForType(st.type, sel);
|
||||
if (chk) return { ok: false, why: '' };
|
||||
}
|
||||
if (needsProtectionConfirm() && !st.endProtection) return { ok: false, why: App.t('send.protection.need') };
|
||||
return { ok: true, why: '' };
|
||||
}
|
||||
|
||||
const needsProtectionConfirm = () => Mil.isHostile(st.type) && op() && op().protectionUntil > App.now();
|
||||
|
||||
function refresh() {
|
||||
drawPreview();
|
||||
drawWarn();
|
||||
const r = ready();
|
||||
submit.disabled = !r.ok || st.busy;
|
||||
}
|
||||
|
||||
function drawPreview() {
|
||||
clear(secPreview);
|
||||
if (!st.tile || !st.from || !st.type) return;
|
||||
const from = fromTown();
|
||||
if (!from) return;
|
||||
const units = st.type === 'transport' ? {} : Mil.cleanSelection(st.units, home());
|
||||
const hasSel = st.type === 'transport' ? Object.keys(st.cargo).length > 0 : Mil.sumUnits(units) > 0;
|
||||
if (!hasSel) { secPreview.appendChild(h('p', { class: 'dimmer', text: App.t('send.pickSome') })); return; }
|
||||
const p = Mil.preview(st.type, from, { x: st.tile.x, y: st.tile.y }, units, st.cargo, App.state.world.speed);
|
||||
secPreview.appendChild(h('div', { class: 'send-preview' },
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.distance') }), h('span', { class: 'v mono', text: App.fmt.dec(p.dist) + ' ' + App.t('common.tiles') })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.latency') }), h('span', { class: 'v mono', text: App.fmt.dur(p.ms) })),
|
||||
h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.arrives') }), h('span', { class: 'v mono', text: mil().clockTime(App.now() + p.ms) })),
|
||||
p.slowest ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.slowest') }), h('span', { class: 'v mono', text: p.slowest + ' ' + App.t('send.tilesPerHour') })) : null,
|
||||
(st.type === 'raid' || st.type === 'attack' || st.type === 'takeover') && p.carry > 0 ? h('div', { class: 'kv' }, h('span', { class: 'k', text: App.t('send.carry') }), h('span', { class: 'v mono', text: num(p.carry) })) : null));
|
||||
}
|
||||
|
||||
function drawWarn() {
|
||||
clear(secWarn);
|
||||
if (!st.tile || !st.from || !st.type) return;
|
||||
const type = st.type;
|
||||
const items = [];
|
||||
if (needsProtectionConfirm()) {
|
||||
const cb = h('input', { type: 'checkbox', checked: st.endProtection, onchange: (e) => { st.endProtection = e.target.checked; refresh(); } });
|
||||
items.push(h('label', { class: 'warn-check' }, cb, h('span', null, h('b', { text: App.t('send.protection.title') }), ' ', App.t('send.protection.body', { t: mil().dayTime(op().protectionUntil) }))));
|
||||
}
|
||||
if ((type === 'attack' || type === 'takeover') && (st.units.exploit_kit || 0) > 0) {
|
||||
items.push(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.siege') }),
|
||||
h('select', { onchange: (e) => { st.target = e.target.value; } },
|
||||
h('option', { value: '', text: App.t('send.siege.none') }),
|
||||
Mil.siegeTargets().map((k) => h('option', { value: k, selected: st.target === k, text: App.buildingName(k) }))),
|
||||
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
|
||||
}
|
||||
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
|
||||
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
|
||||
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
|
||||
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
|
||||
if (Mil.isHostile(type) && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.hostile.hint') }));
|
||||
const r = ready();
|
||||
if (r.why) items.push(h('p', { class: 'reason', text: r.why }));
|
||||
secWarn.appendChild(h('div', { class: 'send-warn' }, items));
|
||||
}
|
||||
|
||||
function showErr(msg) { errEl.textContent = msg || ''; errEl.hidden = !msg; }
|
||||
|
||||
// ------------------------------------------------------------------ send
|
||||
async function go() {
|
||||
const r = ready();
|
||||
if (!r.ok || st.busy) return;
|
||||
st.busy = true; submit.disabled = true; showErr('');
|
||||
const body = { fromTownId: st.fromId, type: st.type };
|
||||
if (st.tile.town) body.toTownId = st.tile.town.id; else { body.x = st.tile.x; body.y = st.tile.y; }
|
||||
if (st.type === 'transport') body.cargo = Object.assign({}, st.cargo);
|
||||
else body.units = Mil.cleanSelection(st.units, home());
|
||||
if (st.type === 'settle') body.wild = st.wild.slice(0, D.WILD_SLOTS);
|
||||
if ((st.type === 'attack' || st.type === 'takeover') && st.target && (body.units.exploit_kit || 0) > 0) body.target = st.target;
|
||||
if (needsProtectionConfirm() && st.endProtection) body.confirmEndProtection = true;
|
||||
try {
|
||||
const res = await App.api.post('/movements', body, { intent: 'send:' + st.fromId + ':' + st.nonce });
|
||||
st.nonce = nonce();
|
||||
toast(App.t('send.sent', { type: mil().typeLabel(res.type), t: App.fmt.dur(res.arriveAt - res.departAt) }), 'ok');
|
||||
ctl.close();
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
if (App.state.operator && res.protectionEnded) App.state.operator.protectionUntil = 0;
|
||||
} catch (e) {
|
||||
st.busy = false;
|
||||
let msg = App.errMsg(e);
|
||||
const reason = e.details && e.details.reason;
|
||||
if (e.code === 'invalid_target' && reason && UpstreamI18n.strings.en['send.invalid.' + reason]) msg += ' ' + App.t('send.invalid.' + reason);
|
||||
showErr(msg);
|
||||
if (e.code === 'not_enough_units' || e.code === 'units_offline' || e.code === 'conflict') { st.from = null; loadFrom(); }
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
// keep the arrival clock and affordability honest while the dialog stays open
|
||||
let lastSlot = 0;
|
||||
offTick = App.onTick((now) => {
|
||||
const slot = Math.floor(now / 15000);
|
||||
if (slot !== lastSlot && !st.busy && st.from && st.tile && st.type) { lastSlot = slot; drawPreview(); }
|
||||
});
|
||||
drawTarget(); drawFrom();
|
||||
loadFrom();
|
||||
if (st.x !== null) loadTile();
|
||||
refresh();
|
||||
};
|
||||
}());
|
||||
|
|
@ -77,7 +77,7 @@
|
|||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
|
||||
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false, navGroup: 'more',
|
||||
render(container) { box = container; App.on('session', () => { tokens = null; }); },
|
||||
onShow() { draw(); loadTokens(); },
|
||||
});
|
||||
|
|
|
|||
166
public/js/screens/social-ui.js
Normal file
166
public/js/screens/social-ui.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Pieces shared by the social screens (alliance, messages, rankings): window.SocUI. Everything player-controlled (operator
|
||||
* names, alliance names and tags, notes, message text) goes in through textContent / text nodes only, never innerHTML.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet } = UI;
|
||||
const Soc = UpstreamSocial;
|
||||
const D = UpstreamData;
|
||||
|
||||
const role = (r) => (D.SOCIAL.roles.includes(r) ? App.t('soc.role.' + r) : String(r));
|
||||
const state = (s) => (D.SOCIAL.diplomacyStates.includes(s) ? App.t('soc.state.' + s) : String(s));
|
||||
const kindLabel = (k) => App.t('soc.kind.' + k);
|
||||
|
||||
// Error text for a failed call. A 429 from the message limiter carries retryAfter (seconds).
|
||||
function err(e) {
|
||||
if (e && e.code === 'rate_limited' && e.retryAfter && (!e.details || !e.details.scope || e.details.scope === 'messages')) return App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) });
|
||||
return App.errMsg(e);
|
||||
}
|
||||
|
||||
// /me caches the operator's alliance; after founding, joining, leaving or being kicked refresh just that, without
|
||||
// App.setSession (which would reset the POP view).
|
||||
async function refreshOperator() {
|
||||
const me = await App.api.get('/me');
|
||||
const mineOp = (me.operators || []).find((o) => App.state.operator && o.id === App.state.operator.id);
|
||||
if (mineOp && App.state.operator) {
|
||||
App.state.operator.alliance = mineOp.alliance;
|
||||
App.state.operator.allianceId = mineOp.allianceId;
|
||||
App.emit('alliance', mineOp.alliance);
|
||||
}
|
||||
return mineOp;
|
||||
}
|
||||
const myAlliance = () => (App.state.operator && App.state.operator.alliance) || null;
|
||||
const myOperatorId = () => (App.state.operator ? App.state.operator.id : 0);
|
||||
|
||||
const tagPill = (tag) => h('span', { class: 'pill soc-tag', text: '[' + tag + ']' });
|
||||
const rolePill = (r) => h('span', { class: 'pill soc-role soc-role-' + r, text: role(r) });
|
||||
|
||||
// A busy button: disables itself while the promise runs and reports errors as a toast (or via `onError`).
|
||||
async function guard(btn, fn, onError) {
|
||||
if (btn) btn.disabled = true;
|
||||
try { return await fn(); } catch (e) {
|
||||
if (onError) onError(e); else toast(err(e), 'error');
|
||||
return undefined;
|
||||
} finally { if (btn && btn.isConnected) btn.disabled = false; }
|
||||
}
|
||||
|
||||
// Confirmation sheet. onOk() may throw: the error is shown inside the sheet and it stays open.
|
||||
function confirmSheet(o) {
|
||||
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||
const ok = h('button', { class: 'btn ' + (o.danger ? 'danger' : 'primary'), type: 'button', text: o.ok || App.t('common.confirm') });
|
||||
const sheet = openSheet({
|
||||
title: o.title, icon: o.icon || 'alert', closeLabel: App.t('common.close'),
|
||||
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: o.text }), msg,
|
||||
h('div', { class: 'btn-row' }, h('button', { class: 'btn', type: 'button', onclick: () => sheet.close(), text: App.t('common.cancel') }), ok)),
|
||||
});
|
||||
ok.addEventListener('click', async () => {
|
||||
ok.disabled = true; msg.hidden = true;
|
||||
try { await o.onOk(); sheet.close(); } catch (e) { msg.textContent = err(e); msg.hidden = false; ok.disabled = false; }
|
||||
});
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ composer: textarea + live counter + send
|
||||
// composer({ onSend(text) -> Promise, placeholder, sendLabel, label }) -> { el, focus(), clear(), input }
|
||||
// A rate_limited answer disables sending and counts the seconds down; the text is kept.
|
||||
function composer(o) {
|
||||
const max = D.SOCIAL.messageMax;
|
||||
const input = h('textarea', { class: 'soc-text', rows: o.rows || 3, maxlength: String(max * 2), placeholder: o.placeholder || '', 'aria-label': o.label || App.t('soc.msg.text'), enterkeyhint: 'enter' });
|
||||
const counter = h('span', { class: 'soc-count mono' });
|
||||
const note = h('p', { class: 'soc-rate', role: 'alert', hidden: true });
|
||||
const send = h('button', { class: 'btn primary', type: 'button' }, icon('up'), o.sendLabel || App.t('soc.msg.send'));
|
||||
const el = h('div', { class: 'soc-composer' }, input, h('div', { class: 'soc-composer-bar' }, counter, send), note);
|
||||
let until = 0, off = null, busy = false;
|
||||
|
||||
function refresh() {
|
||||
const st = Soc.composeState(input.value, max);
|
||||
counter.textContent = st.n + '/' + max;
|
||||
counter.classList.toggle('over', st.over);
|
||||
counter.setAttribute('aria-label', App.t('soc.msg.counter', { n: st.n, max }));
|
||||
const waiting = until > App.now();
|
||||
send.disabled = busy || st.empty || st.over || waiting;
|
||||
}
|
||||
function tick() {
|
||||
if (!el.isConnected) { stopTick(); return; }
|
||||
const left = Math.ceil((until - App.now()) / 1000);
|
||||
if (left <= 0) { until = 0; note.hidden = true; stopTick(); refresh(); return; }
|
||||
const s = App.t('soc.rate', { t: App.fmt.dur(left * 1000, 2) });
|
||||
if (note.textContent !== s) note.textContent = s;
|
||||
}
|
||||
function startTick() { if (!off) off = App.onTick(tick); }
|
||||
function stopTick() { if (off) { off(); off = null; } }
|
||||
|
||||
input.addEventListener('input', refresh);
|
||||
send.addEventListener('click', async () => {
|
||||
const text = input.value;
|
||||
if (send.disabled) return;
|
||||
busy = true; refresh(); note.hidden = true;
|
||||
try {
|
||||
await o.onSend(text);
|
||||
input.value = '';
|
||||
} catch (e) {
|
||||
if (e && e.code === 'rate_limited') {
|
||||
until = App.now() + Soc.retrySeconds(e) * 1000;
|
||||
note.textContent = App.t('soc.rate', { t: App.fmt.dur(Soc.retrySeconds(e) * 1000, 2) }); note.hidden = false;
|
||||
startTick();
|
||||
} else { note.textContent = err(e); note.hidden = false; }
|
||||
} finally { busy = false; refresh(); }
|
||||
});
|
||||
refresh();
|
||||
return { el, input, focus: () => { try { input.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, refresh, destroy: stopTick };
|
||||
}
|
||||
|
||||
// Compose sheet. target: { operator: { operatorId, name } } or { alliance: true }.
|
||||
function openCompose(target, onSent) {
|
||||
const toAlliance = !!target.alliance;
|
||||
const to = toAlliance ? '[' + ((myAlliance() || {}).tag || '') + ']' : target.operator.name;
|
||||
const comp = composer({
|
||||
onSend: async (text) => {
|
||||
const body = toAlliance ? { text, toAlliance: true } : { text, toOperatorId: target.operator.operatorId };
|
||||
await App.api.post('/messages', body, { retries: 0 });
|
||||
toast(App.t('soc.msg.sent'), 'ok');
|
||||
sheet.close();
|
||||
if (onSent) onSent();
|
||||
},
|
||||
});
|
||||
const sheet = openSheet({
|
||||
title: toAlliance ? App.t('soc.msg.toAlliance') : App.t('soc.msg.to', { name: to }),
|
||||
icon: 'mail', closeLabel: App.t('common.close'), onClose: comp.destroy,
|
||||
body: h('div', { class: 'detail' }, toAlliance ? h('p', { class: 'detail-desc', text: App.t('soc.msg.broadcastHint', { tag: to }) }) : null, comp.el),
|
||||
});
|
||||
setTimeout(comp.focus, 220);
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ alliance profile sheet (public view)
|
||||
async function openProfile(allianceId, extra) {
|
||||
const body = h('div', { class: 'detail' }, h('p', { class: 'empty', text: App.t('common.loading') }));
|
||||
const sheet = openSheet({ title: extra && extra.name ? extra.name : App.t('soc.profile'), icon: 'users', closeLabel: App.t('common.close'), body });
|
||||
try {
|
||||
const a = (await App.api.get('/alliances/' + allianceId)).alliance;
|
||||
sheet.setTitle(a.name);
|
||||
clear(body);
|
||||
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||
body.appendChild(h('div', { class: 'pill-row' }, tagPill(a.tag),
|
||||
a.relation ? h('span', { class: 'pill soc-state soc-state-' + a.relation, text: a.relation === 'same' ? App.t('soc.relation.same') : state(a.relation) }) : null,
|
||||
a.myRole ? rolePill(a.myRole) : null));
|
||||
body.appendChild(h('div', null,
|
||||
kv(App.t('soc.members'), App.t('soc.size', { n: a.memberCount, cap: a.sizeCap })),
|
||||
kv(App.t('soc.leader'), a.leader ? a.leader.name : '-'),
|
||||
kv(App.t('soc.footprint'), App.fmt.dec(a.footprint || 0)),
|
||||
kv(App.t('soc.founded'), App.fmt.ago(App.now() - a.createdAt))));
|
||||
} catch (e) {
|
||||
clear(body);
|
||||
body.appendChild(h('p', { class: 'form-error', role: 'alert', text: err(e) }));
|
||||
}
|
||||
return sheet;
|
||||
}
|
||||
|
||||
// Loading / error / empty placeholders for a list container.
|
||||
const loading = () => h('p', { class: 'empty', text: App.t('common.loading') });
|
||||
const errorBox = (e, retry) => h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: err(e) }),
|
||||
retry ? h('button', { class: 'btn small', type: 'button', onclick: retry }, icon('refresh'), App.t('common.retry')) : null);
|
||||
|
||||
window.SocUI = { role, state, kindLabel, err, refreshOperator, myAlliance, myOperatorId, tagPill, rolePill, guard, confirmSheet, composer, openCompose, openProfile, loading, errorBox };
|
||||
}());
|
||||
368
public/js/screens/units.js
Normal file
368
public/js/screens/units.js
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Units: what stands in this POP (home, reinforcements from others, your units standing elsewhere), the training queue
|
||||
* with a train form, research, and the power/offline status. Everything comes from GET /towns/:id (town.military); the
|
||||
* client previews cost/time with rules.trainPlan / researchPlan (same functions the server runs) and the server decides.
|
||||
*/
|
||||
(function () {
|
||||
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
|
||||
const R = UpstreamRules;
|
||||
const D = UpstreamData;
|
||||
const Mil = UpstreamMil;
|
||||
|
||||
const td = () => App.state.townData;
|
||||
const mi = () => (td() ? td().military : null);
|
||||
const mil = () => App.mil;
|
||||
|
||||
let box, bodyEl, visible = false, dirty = true, offTick = null;
|
||||
const refetch = new Map(); // training/research event id -> { n, at }
|
||||
|
||||
const num = (n) => App.fmt.num(n);
|
||||
const val = (x) => (Number.isInteger(x) ? num(x) : App.fmt.dec(x));
|
||||
|
||||
// ------------------------------------------------------------------ pieces
|
||||
function statLine(unit, levels) {
|
||||
const def = D.UNITS[unit];
|
||||
const a = R.unitStat(unit, 'attack', levels), d = R.unitStat(unit, 'defence', levels);
|
||||
return App.t('unit.stats', { a: val(a), d: val(d), s: def.speed || 0, c: def.carry || 0 }) + (def.fixed ? ' · ' + App.t('unit.fixed') : '');
|
||||
}
|
||||
|
||||
function unitRow(unit, count, levels, right) {
|
||||
return h('li', { class: 'mil-row unit' },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(unit) }), count !== null ? h('span', { class: 'lv mono', text: '× ' + num(count) }) : null),
|
||||
h('span', { class: 'row-sub wrap', text: statLine(unit, levels) })),
|
||||
right || null);
|
||||
}
|
||||
|
||||
function unitList(units, levels) {
|
||||
const rows = D.UNIT_ORDER.filter((u) => units && units[u] > 0).map((u) => unitRow(u, units[u], levels));
|
||||
return rows.length ? h('ul', { class: 'mil-list' }, rows) : null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
function statusCard(m) {
|
||||
const t = td();
|
||||
if (!m.units.online) {
|
||||
const until = Mil.decommissionAt(m.units.offlineSince || App.now(), App.state.world.speed);
|
||||
return h('section', { class: 'card warn-card', role: 'alert' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('units.offline.title'))),
|
||||
h('p', { class: 'detail-desc', text: App.t('units.offline.body') }),
|
||||
h('p', { class: 'row-sub wrap' }, App.t('units.offline.decom') + ' ', mil().countdown(until)));
|
||||
}
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.status')),
|
||||
h('span', { class: 'pill green', text: App.t('units.online') })),
|
||||
h('p', { class: 'row-sub wrap', text: App.t('units.powerNet', { n: App.fmt.dec(t.power.net, true) }) }));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ home / stationed
|
||||
function homeCard(m) {
|
||||
const levels = m.research.levels;
|
||||
const list = unitList(m.units.home, levels);
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('units'), App.t('units.home')),
|
||||
h('button', { class: 'btn small primary', type: 'button', disabled: !list, onclick: () => App.openSend({ fromTownId: td().id }) }, icon('target'), App.t('mov.send'))),
|
||||
list || h('p', { class: 'empty', text: App.t('units.home.empty') }));
|
||||
}
|
||||
|
||||
async function withdraw(hostTownId, ownerTownId, btn) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await App.api.post('/towns/' + hostTownId + '/withdraw', { ownerTownId }, { intent: 'withdraw:' + hostTownId + ':' + ownerTownId });
|
||||
toast(App.t('units.withdrawn'), 'ok');
|
||||
} catch (e) { toast(App.errMsg(e), 'error'); }
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshTown().catch(() => {});
|
||||
}
|
||||
|
||||
function stationedCards(m) {
|
||||
const out = [];
|
||||
if (m.units.stationedHere.length) {
|
||||
out.push(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('shield'), App.t('units.hosted'))),
|
||||
h('ul', { class: 'mil-list' }, m.units.stationedHere.map((g) => h('li', { class: 'mil-group' },
|
||||
h('div', { class: 'row' },
|
||||
h('span', null, h('b', { text: g.ownerTownName || '#' + g.ownerTownId }), g.owner ? h('span', { class: 'dimmer', text: ' · ' + g.owner.name }) : null),
|
||||
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(td().id, g.ownerTownId, ev.currentTarget) }, icon('return'), App.t('units.sendHome'))),
|
||||
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
|
||||
}
|
||||
if (m.units.stationedAway.length) {
|
||||
out.push(h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('units.away'))),
|
||||
h('ul', { class: 'mil-list' }, m.units.stationedAway.map((g) => h('li', { class: 'mil-group' },
|
||||
h('div', { class: 'row' },
|
||||
h('span', null, h('b', { text: g.hostTownName || '#' + g.hostTownId })),
|
||||
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(g.hostTownId, td().id, ev.currentTarget) }, icon('return'), App.t('units.callBack'))),
|
||||
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ training
|
||||
const tailFor = (m, building) => m.training.filter((b) => b.building === building).reduce((t, b) => Math.max(t, b.dueAt), 0);
|
||||
|
||||
function trainingCard(m) {
|
||||
const queue = h('ul', { class: 'mil-list queue' });
|
||||
for (const b of m.training) {
|
||||
const bar = h('i');
|
||||
const li = h('li', { class: 'mil-row batch' },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(b.unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(b.unit) }), h('span', { class: 'lv mono', text: '× ' + num(b.count) }), h('span', { class: 'lv', text: App.buildingName(b.building) })),
|
||||
h('span', { class: 'bar mil-bar', 'aria-hidden': 'true' }, bar)),
|
||||
h('span', { class: 'mil-when' }, mil().countdown(b.dueAt)));
|
||||
li._bar = bar; li._b = b;
|
||||
queue.appendChild(li);
|
||||
}
|
||||
const trainable = h('ul', { class: 'mil-list' }, m.trainable.map((u) => {
|
||||
const def = D.UNITS[u.unit];
|
||||
const row = h('button', { class: 'row-btn mil-train' + (u.locked ? ' locked' : ''), type: 'button', dataset: { unit: u.unit }, onclick: () => openTrain(u.unit) },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(u.unit)),
|
||||
h('span', { class: 'row-main' },
|
||||
h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u.unit) }), h('span', { class: 'lv', text: App.buildingName(def.building) })),
|
||||
u.locked
|
||||
? h('span', { class: 'row-sub wrap', text: App.t('units.needs') + ' ' + u.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ') })
|
||||
: h('span', { class: 'row-sub wrap', text: App.t('units.perUnit', { t: App.fmt.dur(u.timeMs) }) })),
|
||||
u.locked ? h('span', { class: 'pill dim' }, icon('lock')) : mil().resChips(u.cost));
|
||||
return h('li', null, row);
|
||||
}));
|
||||
return h('section', { class: 'card' },
|
||||
h('div', { class: 'card-head' }, h('h2', null, icon('clock'), App.t('units.training')), h('span', { class: 'pill', text: String(m.training.length) })),
|
||||
m.training.length ? queue : h('p', { class: 'empty', text: App.t('units.training.empty') }),
|
||||
h('h3', { class: 'sub', text: App.t('units.train') }), trainable);
|
||||
}
|
||||
|
||||
function openTrain(unit) {
|
||||
const body = h('div', { class: 'detail' });
|
||||
let off = null;
|
||||
const ctl = openSheet({ title: mil().unitName(unit), icon: 'units', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
|
||||
const els = {};
|
||||
let count = 1, busy = false;
|
||||
const def = D.UNITS[unit];
|
||||
|
||||
function plan() {
|
||||
const t = td(), m = mi();
|
||||
const rt = App.rulesTown();
|
||||
if (!t || !rt) return null;
|
||||
const p = R.trainPlan(rt, unit, count, App.now(), tailFor(m, def.building));
|
||||
if (p.ok && m.training.filter((b) => b.building === def.building).length >= D.MILITARY.maxTrainQueue) return Object.assign(p, { ok: false, code: 'queue_full' });
|
||||
return p;
|
||||
}
|
||||
function maxAffordable() {
|
||||
const cur = App.resourcesNow();
|
||||
if (!cur) return 1;
|
||||
let n = D.MILITARY.maxBatch;
|
||||
for (const r of D.RESOURCES) if (def.cost[r] > 0) n = Math.min(n, Math.floor(cur.amounts[r] / def.cost[r] + 1e-6));
|
||||
return Math.max(0, n);
|
||||
}
|
||||
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: mil().unitDesc(unit) }));
|
||||
body.appendChild(h('p', { class: 'preview', text: statLine(unit, mi().research.levels) + ' · ' + App.t('unit.draw', { n: def.draw }) }));
|
||||
els.input = h('input', { type: 'number', inputmode: 'numeric', min: '1', max: String(D.MILITARY.maxBatch), value: '1', class: 'mil-num', 'aria-label': App.t('units.count') });
|
||||
const step = (d) => { count = Math.max(1, Math.min(D.MILITARY.maxBatch, count + d)); els.input.value = String(count); live(); };
|
||||
els.input.addEventListener('input', () => { const v = Math.floor(Number(els.input.value)); count = Number.isFinite(v) && v >= 1 ? Math.min(v, D.MILITARY.maxBatch) : 1; live(); });
|
||||
body.appendChild(h('div', { class: 'stepper' },
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '-10', onclick: () => step(-10) }, '−10'),
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '-1', onclick: () => step(-1) }, '−'),
|
||||
els.input,
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '+1', onclick: () => step(1) }, '+'),
|
||||
h('button', { class: 'btn', type: 'button', 'aria-label': '+10', onclick: () => step(10) }, '+10')));
|
||||
body.appendChild(h('button', { class: 'btn small wide', type: 'button', onclick: () => { count = Math.max(1, maxAffordable()); els.input.value = String(count); live(); } }, App.t('units.max')));
|
||||
els.costs = h('div', { class: 'costs' });
|
||||
els.time = h('b');
|
||||
els.done = h('span', { class: 'dimmer' });
|
||||
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('units.time') + ': ' }), els.time, els.done));
|
||||
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
|
||||
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: go }, icon('units'), h('span', { text: App.t('units.trainBtn') }));
|
||||
body.appendChild(els.reason); body.appendChild(els.btn);
|
||||
|
||||
function live() {
|
||||
const p = plan();
|
||||
if (!p) return;
|
||||
const cur = App.resourcesNow();
|
||||
clear(els.costs);
|
||||
for (const r of D.RESOURCES) {
|
||||
const short = cur && cur.amounts[r] + 1e-6 < p.cost[r];
|
||||
els.costs.appendChild(h('span', { class: 'cost ' + r + (short ? ' short' : '') }, icon(r), h('b', { text: num(p.cost[r]) }), cur ? h('small', { text: App.t('sheet.have', { n: num(cur.amounts[r]) }) }) : null));
|
||||
}
|
||||
els.time.textContent = App.fmt.dur(p.durationMs);
|
||||
els.done.textContent = ' · ' + App.t('units.readyAt', { t: mil().clockTime(p.dueAt) });
|
||||
let reason = '';
|
||||
if (!p.ok) {
|
||||
reason = App.t('err.' + p.code);
|
||||
if (p.code === 'requirements_not_met' && p.missing && p.missing.length) reason += ' ' + p.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
|
||||
}
|
||||
els.reason.textContent = reason; els.reason.hidden = !reason;
|
||||
els.btn.disabled = !p.ok || busy;
|
||||
}
|
||||
async function go() {
|
||||
if (busy) return;
|
||||
busy = true; els.btn.disabled = true;
|
||||
const t = td();
|
||||
try {
|
||||
await App.api.post('/towns/' + t.id + '/train', { unit, count }, { intent: 'train:' + t.id + ':' + unit + ':' + count });
|
||||
toast(App.t('units.queued', { n: num(count), unit: mil().unitName(unit) }), 'ok');
|
||||
ctl.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
busy = false;
|
||||
App.refreshTown().catch(() => {});
|
||||
live();
|
||||
}
|
||||
}
|
||||
off = App.onTick(() => { if (!busy) live(); });
|
||||
live();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ research
|
||||
function researchCard(m) {
|
||||
const levels = m.research.levels;
|
||||
const q = m.research.queue;
|
||||
const head = h('div', { class: 'card-head' }, h('h2', null, icon('flask'), App.t('units.research')),
|
||||
m.research.speedBonus > 0 ? h('span', { class: 'pill green', text: App.t('units.research.speed', { p: Math.round(m.research.speedBonus * 100) }) }) : null);
|
||||
const busy = q ? h('div', { class: 'detail-queue' },
|
||||
h('div', { class: 'row' }, h('span', { text: App.t('units.research.busy', { unit: mil().unitName(q.unit), stat: App.t('stat.' + q.stat), level: q.toLevel }) }), mil().countdown(q.dueAt)),
|
||||
h('div', { class: 'bar' }, h('i', { dataset: { rs: '1' } }))) : null;
|
||||
const rows = D.UNIT_ORDER.filter((u) => D.UNITS[u].attack > 0 || D.UNITS[u].defence > 0).map((u) => {
|
||||
const a = levels[R.researchKey(u, 'attack')] || 0, d = levels[R.researchKey(u, 'defence')] || 0;
|
||||
return h('li', null, h('button', { class: 'row-btn', type: 'button', onclick: () => openResearch(u) },
|
||||
h('span', { class: 'row-ic' }, mil().unitIcon(u)),
|
||||
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: mil().unitName(u) })),
|
||||
h('span', { class: 'row-sub wrap', text: App.t('stat.attack') + ' ' + a + ' · ' + App.t('stat.defence') + ' ' + d })),
|
||||
h('span', { class: 'pill', text: '+' + Math.round((a + d) * D.MILITARY.researchPerLevel * 100) + '%' })));
|
||||
});
|
||||
return h('section', { class: 'card' }, head, busy, h('ul', { class: 'mil-list' }, rows));
|
||||
}
|
||||
|
||||
function openResearch(unit) {
|
||||
const body = h('div', { class: 'detail' });
|
||||
let off = null;
|
||||
const ctl = openSheet({ title: mil().unitName(unit), icon: 'flask', closeLabel: App.t('common.close'), body, onClose: () => { if (off) off(); } });
|
||||
let busy = false;
|
||||
const def = D.UNITS[unit];
|
||||
const parts = {};
|
||||
|
||||
function build() {
|
||||
clear(body);
|
||||
const m = mi();
|
||||
body.appendChild(h('p', { class: 'detail-desc', text: App.t('units.research.hint', { p: Math.round(D.MILITARY.researchPerLevel * 100), max: D.RESEARCH.maxLevel }) }));
|
||||
for (const stat of D.RESEARCH.stats) {
|
||||
if (!(def[stat] > 0)) continue;
|
||||
const level = m.research.levels[R.researchKey(unit, stat)] || 0;
|
||||
const sec = h('section', { class: 'card inner' });
|
||||
sec.appendChild(h('div', { class: 'card-head' }, h('h2', { text: App.t('stat.' + stat) }),
|
||||
h('span', { class: 'pill', text: App.t('units.research.level', { n: level, max: D.RESEARCH.maxLevel }) })));
|
||||
if (level >= D.RESEARCH.maxLevel) { sec.appendChild(h('p', { class: 'empty', text: App.t('sheet.maxed') })); body.appendChild(sec); continue; }
|
||||
const costs = h('div', { class: 'costs' }), reason = h('p', { class: 'reason', 'aria-live': 'polite' }), time = h('b');
|
||||
const btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => go(stat, btn) }, icon('flask'), h('span', { text: App.t('units.research.start', { n: level + 1 }) }));
|
||||
sec.appendChild(h('p', { class: 'preview', text: App.t('units.research.effect', { a: val(def[stat] * R.researchMult(level)), b: val(def[stat] * R.researchMult(level + 1)) }) }));
|
||||
sec.appendChild(costs);
|
||||
sec.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('units.research.time') + ': ' }), time));
|
||||
sec.appendChild(reason); sec.appendChild(btn);
|
||||
parts[stat] = { level, costs, reason, time, btn };
|
||||
body.appendChild(sec);
|
||||
}
|
||||
live();
|
||||
}
|
||||
function live() {
|
||||
const m = mi(), rt = App.rulesTown();
|
||||
if (!m || !rt) return;
|
||||
const cur = App.resourcesNow();
|
||||
for (const stat of Object.keys(parts)) {
|
||||
const p = parts[stat];
|
||||
const plan = R.researchPlan(rt, unit, stat, p.level, !!m.research.queue, App.now(), m.research.speedBonus);
|
||||
clear(p.costs);
|
||||
for (const r of D.RESOURCES) p.costs.appendChild(h('span', { class: 'cost ' + r + (cur && cur.amounts[r] + 1e-6 < plan.cost[r] ? ' short' : '') }, icon(r), h('b', { text: num(plan.cost[r]) })));
|
||||
p.time.textContent = App.fmt.dur(plan.durationMs);
|
||||
let reason = '';
|
||||
if (!plan.ok) {
|
||||
reason = App.t('err.' + plan.code);
|
||||
if (plan.code === 'requirements_not_met' && plan.missing && plan.missing.length) reason += ' ' + plan.missing.map((x) => App.buildingName(x.type) + ' ' + App.t('pop.level', { n: x.level })).join(', ');
|
||||
}
|
||||
p.reason.textContent = reason; p.reason.hidden = !reason;
|
||||
p.btn.disabled = !plan.ok || busy;
|
||||
}
|
||||
}
|
||||
async function go(stat, btn) {
|
||||
if (busy) return;
|
||||
busy = true; btn.disabled = true;
|
||||
const t = td();
|
||||
try {
|
||||
await App.api.post('/towns/' + t.id + '/research', { unit, stat }, { intent: 'research:' + t.id + ':' + unit + ':' + stat });
|
||||
toast(App.t('units.research.queued'), 'ok');
|
||||
ctl.close();
|
||||
await App.refreshTown();
|
||||
} catch (e) {
|
||||
toast(App.errMsg(e), 'error');
|
||||
busy = false;
|
||||
App.refreshTown().then(() => build()).catch(() => {});
|
||||
}
|
||||
}
|
||||
build();
|
||||
off = App.onTick(live);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ screen
|
||||
function head() {
|
||||
return h('div', { class: 'card-head page-head units-head' }, h('h1', { text: App.t('screen.units') }),
|
||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => App.refreshTown().catch((e) => toast(App.errMsg(e), 'error')) }, icon('refresh')));
|
||||
}
|
||||
|
||||
function draw() {
|
||||
dirty = false;
|
||||
clear(bodyEl);
|
||||
const t = td(), m = mi();
|
||||
if (!App.state.townId) { bodyEl.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
|
||||
if (!t || !m) { bodyEl.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
|
||||
bodyEl.appendChild(head());
|
||||
bodyEl.appendChild(h('div', { class: 'cols' },
|
||||
h('div', { class: 'col' }, statusCard(m), homeCard(m), stationedCards(m)),
|
||||
h('div', { class: 'col' }, trainingCard(m), researchCard(m))));
|
||||
tick(App.now());
|
||||
}
|
||||
|
||||
function tick(now) {
|
||||
const m = mi();
|
||||
if (!m || !bodyEl) return;
|
||||
for (const li of bodyEl.querySelectorAll('li.batch')) {
|
||||
const b = li._b;
|
||||
if (!b) continue;
|
||||
li._bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - b.startAt) / Math.max(1, b.dueAt - b.startAt)))));
|
||||
}
|
||||
const rs = bodyEl.querySelector('[data-rs]');
|
||||
if (rs && m.research.queue) rs.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - m.research.queue.startedAt) / Math.max(1, m.research.queue.dueAt - m.research.queue.startedAt)))));
|
||||
// something came due: refetch (with a gentle retry, like the build queue)
|
||||
const items = m.training.map((b) => ({ id: 't' + b.id, due: b.dueAt })).concat(m.research.queue ? [{ id: 'r' + m.research.queue.id, due: m.research.queue.dueAt }] : []);
|
||||
for (const it of items) {
|
||||
if (now - it.due < 300) continue;
|
||||
const tries = refetch.get(it.id) || { n: 0, at: 0 };
|
||||
if (Date.now() >= tries.at) { refetch.set(it.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) }); App.refreshTown().catch(() => {}); }
|
||||
}
|
||||
}
|
||||
|
||||
App.registerScreen({
|
||||
id: 'units', titleKey: 'screen.units', navKey: 'nav.units', icon: 'units', hud: true,
|
||||
render(container) {
|
||||
box = container;
|
||||
bodyEl = h('div', { class: 'units-body' });
|
||||
box.appendChild(bodyEl);
|
||||
App.on('town', () => { if (visible) draw(); else dirty = true; });
|
||||
App.on('townchange', () => { dirty = true; if (visible) draw(); });
|
||||
App.on('session', () => { dirty = true; refetch.clear(); });
|
||||
App.on('towns', () => { if (visible) draw(); else dirty = true; });
|
||||
},
|
||||
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(); },
|
||||
});
|
||||
}());
|
||||
111
public/js/social.js
Normal file
111
public/js/social.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Pure client logic of the social screens (alliance, messages, rankings): no DOM, no I/O, no clocks. Loads as a browser
|
||||
* script (window.UpstreamSocial) and as a Node module (test/client-social.test.js). Permissions and diplomacy moves are
|
||||
* never re-implemented here: they come from rules.js (allianceCan, outranks, diplomacyMove) over the tables in data.js, so
|
||||
* the buttons the screens show are exactly the ones the server would accept. The server still checks everything.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) module.exports = factory(require('./rules.js'), require('./data.js'));
|
||||
else root.UpstreamSocial = factory(root.UpstreamRules, root.UpstreamData);
|
||||
}(typeof self !== 'undefined' ? self : this, function (R, D) {
|
||||
const S = D.SOCIAL;
|
||||
|
||||
// What the viewer may do in their own alliance (role from GET /alliances/mine). `memberCount` decides whether a leader
|
||||
// can simply leave (alone: the alliance is disbanded) or must hand over leadership first.
|
||||
function selfActions(role, memberCount) {
|
||||
const can = (a) => !!role && R.allianceCan(role, a);
|
||||
return {
|
||||
invite: can('invite'), viewInvites: can('viewInvites'), cancelInvite: can('cancelInvite'),
|
||||
editNotes: can('editNotes'), diplomacy: can('diplomacy'), broadcast: can('broadcast'),
|
||||
disband: can('disband'), transfer: can('transfer'), setRole: can('setRole'),
|
||||
leave: !!role, leaveNeedsTransfer: role === 'leader' && memberCount > 1,
|
||||
};
|
||||
}
|
||||
|
||||
// What the viewer may do to one listed member. `kick` needs the permission AND a strictly higher rank; roles are set by the
|
||||
// leader to diplomat/officer/member only (leadership moves through `transfer`).
|
||||
function memberActions(myRole, member, myOperatorId) {
|
||||
const self = member.operatorId === myOperatorId;
|
||||
const settable = S.roles.filter((r) => r !== 'leader');
|
||||
return {
|
||||
self,
|
||||
message: !self,
|
||||
kick: !self && !!myRole && R.allianceCan(myRole, 'kick') && R.outranks(myRole, member.role),
|
||||
roles: !self && !!myRole && R.allianceCan(myRole, 'setRole') && member.role !== 'leader' ? settable.filter((r) => r !== member.role) : [],
|
||||
transfer: !self && !!myRole && R.allianceCan(myRole, 'transfer'),
|
||||
};
|
||||
}
|
||||
|
||||
// Relation of the own alliance to another: `relations` is the list of GET /alliances/:id/diplomacy. No row = neutral.
|
||||
function relationTo(relations, otherId) {
|
||||
const r = (relations || []).find((x) => x.other && x.other.id === otherId);
|
||||
return r ? { state: r.state, since: r.since, pending: r.pending || null } : { state: 'neutral', since: null, pending: null };
|
||||
}
|
||||
|
||||
// Moves offered from the current state: [{ state, kind: 'immediate' | 'proposal' | 'delayed' }]. A pair with a scheduled
|
||||
// change is locked (the server answers diplomacy_pending), so nothing is offered.
|
||||
function diplomacyOptions(current, pending) {
|
||||
if (pending) return [];
|
||||
return S.diplomacyStates.filter((s) => s !== current && R.diplomacyMove(current, s)).map((s) => ({ state: s, kind: R.diplomacyMove(current, s) }));
|
||||
}
|
||||
|
||||
// Milliseconds until a scheduled pact change takes effect (never negative).
|
||||
const pendingRemaining = (pending, now) => (pending ? Math.max(0, pending.effectiveAt - now) : 0);
|
||||
|
||||
// Characters as the server counts them (code points, CRLF folded to LF). The server also strips control characters, so the
|
||||
// counter can only over-count, never let through something the server then refuses for length.
|
||||
function charCount(text) { return Array.from(String(text == null ? '' : text).replace(/\r\n?/g, '\n')).length; }
|
||||
|
||||
function composeState(text, max) {
|
||||
max = max || S.messageMax;
|
||||
const n = charCount(text);
|
||||
return { n, left: max - n, over: n > max, empty: !String(text == null ? '' : text).trim(), max };
|
||||
}
|
||||
|
||||
// Seconds to show for a rate_limited error (details.retryAfter / Retry-After, already parsed into err.retryAfter).
|
||||
const retrySeconds = (err) => Math.max(1, Math.ceil((err && err.retryAfter) || 1));
|
||||
|
||||
// Messages are listed newest first with `after` = the last id, so the next page holds OLDER ids. Merge without duplicates,
|
||||
// keep newest first.
|
||||
function mergeMessages(existing, incoming) {
|
||||
const seen = new Set(existing.map((m) => m.id));
|
||||
return existing.concat(incoming.filter((m) => !seen.has(m.id))).sort((a, b) => b.id - a.id);
|
||||
}
|
||||
|
||||
// A conversation reads oldest to newest.
|
||||
const chronological = (items) => items.slice().sort((a, b) => a.id - b.id);
|
||||
|
||||
// The other party of a direct message from the viewer's side.
|
||||
const peerOf = (m) => (m.direction === 'out' ? m.to : m.from);
|
||||
|
||||
// Received, not yet read direct or broadcast messages among `items`.
|
||||
const unreadIds = (items) => items.filter((m) => m.direction === 'in' && !m.readAt).map((m) => m.id);
|
||||
|
||||
// Rankings page by rank offset: the cursor is the number of ranks already seen. Merge by rank so a refetch does not duplicate.
|
||||
function mergeRanks(existing, incoming) {
|
||||
const seen = new Set(existing.map((r) => r.rank));
|
||||
return existing.concat(incoming.filter((r) => !seen.has(r.rank))).sort((a, b) => a.rank - b.rank);
|
||||
}
|
||||
|
||||
// Is this ranking row the viewer's own (kind: 'operators' | 'alliances' | 'battles')?
|
||||
function isYou(kind, row, you) {
|
||||
if (!you || !row) return false;
|
||||
return kind === 'alliances' ? row.allianceId === you.allianceId : row.operatorId === you.operatorId;
|
||||
}
|
||||
|
||||
// Battle ranking value for the tab (attack, defense or total).
|
||||
const battlePoints = (row, by) => (by === 'defense' ? row.defensePoints : by === 'total' ? row.attackPoints + row.defensePoints : row.attackPoints);
|
||||
|
||||
// Where to put a number-or-null "last online": ms since, or null when unknown.
|
||||
const sinceMs = (at, now) => (at ? Math.max(0, now - at) : null);
|
||||
|
||||
// Operator names may be typed or pasted: trim and collapse so " Bob " matches. The server looks names up case-insensitively.
|
||||
const cleanName = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
|
||||
|
||||
return {
|
||||
selfActions, memberActions, relationTo, diplomacyOptions, pendingRemaining,
|
||||
charCount, composeState, retrySeconds, mergeMessages, chronological, peerOf, unreadIds,
|
||||
mergeRanks, isYou, battlePoints, sinceMs, cleanName,
|
||||
};
|
||||
}));
|
||||
13
public/js/strings/README.md
Normal file
13
public/js/strings/README.md
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
Per-area string files. Each is a browser script AND a Node module:
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||
else factory(root.UpstreamI18n);
|
||||
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||
I.extend({ en: { 'units.title': 'Units' }, nb: { 'units.title': 'Enheter' } });
|
||||
}));
|
||||
```
|
||||
|
||||
Load it from index.html after i18n.js. test/client-i18n.test.js requires every .js here and enforces en/nb key parity.
|
||||
251
public/js/strings/military.js
Normal file
251
public/js/strings/military.js
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
'use strict';
|
||||
/* Strings of the military / expansion screens (units, movements, reports, send dialog, expansion) in en + nb. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||
else factory(root.UpstreamI18n);
|
||||
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||
I.extend({
|
||||
en: {
|
||||
'nav.more': 'More', 'nav.units': 'Units', 'nav.movements': 'Moves', 'nav.reports': 'Reports',
|
||||
'screen.units': 'Units', 'screen.movements': 'Movements', 'screen.reports': 'Reports',
|
||||
|
||||
// ---- unit names and descriptions (ids are generic, names live here)
|
||||
'unit.port_scanner.name': 'Port scanner', 'unit.port_scanner.desc': 'Quiet little probes. Scout a POP before you commit anything expensive.',
|
||||
'unit.soc_analyst.name': 'SOC analyst', 'unit.soc_analyst.desc': 'Staring at dashboards so you do not have to. Cheap, steady defence.',
|
||||
'unit.blue_team.name': 'Blue team', 'unit.blue_team.desc': 'Incident response with proper coffee. Strong defenders.',
|
||||
'unit.honeypot.name': 'Honeypot', 'unit.honeypot.desc': 'A very attractive, very fake server. Defends in place and never leaves.',
|
||||
'unit.script_crew.name': 'Script crew', 'unit.script_crew.desc': 'Cheap, fast raiders that carry some loot home.',
|
||||
'unit.botnet.name': 'Botnet', 'unit.botnet.desc': 'Many small machines with one bad idea. Strong, fast, carries a lot.',
|
||||
'unit.ddos_rig.name': 'DDoS rig', 'unit.ddos_rig.desc': 'Floods the firewall. Every 10 rigs lower the target firewall by one level.',
|
||||
'unit.exploit_kit.name': 'Exploit kit', 'unit.exploit_kit.desc': 'Finds the one unpatched thing. Damages a chosen building when you win.',
|
||||
'unit.rollout_crew.name': 'Rollout crew', 'unit.rollout_crew.desc': 'Trenches, ducts and optimism. Three of them found a new POP.',
|
||||
'unit.ma_team.name': 'M&A team', 'unit.ma_team.desc': 'Suits with a term sheet. Wears down customer loyalty until the POP changes hands.',
|
||||
'unit.stats': 'ATK {a} · DEF {d} · {s} tiles/h · carries {c}', 'unit.fixed': 'stays in place', 'unit.draw': 'Power draw {n}/h',
|
||||
'stat.attack': 'Attack', 'stat.defence': 'Defence',
|
||||
|
||||
'move.type.scan': 'Scan', 'move.type.raid': 'Phishing raid', 'move.type.attack': 'Attack', 'move.type.takeover': 'Hostile takeover',
|
||||
'move.type.reinforce': 'Peering support', 'move.type.settle': 'Found a POP', 'move.type.transport': 'Transport', 'move.type.return': 'Returning home', 'move.type.unknown': 'Unknown',
|
||||
'report.type.raid': 'Phishing raid', 'report.type.attack': 'Attack', 'report.type.takeover': 'Hostile takeover', 'report.type.scan': 'Scan',
|
||||
'report.type.scan_detected': 'Scan detected', 'report.type.incumbent': 'Incumbent site', 'report.type.settle': 'New POP', 'report.type.reinforce': 'Reinforcements',
|
||||
'report.type.movement_failed': 'Movement failed',
|
||||
|
||||
'mil.showOnMap': 'Show {x}, {y} on the map',
|
||||
|
||||
// ---- units screen
|
||||
'units.status': 'Status', 'units.online': 'Online', 'units.powerNet': 'Net power {n}/h',
|
||||
'units.offline.title': 'Units offline', 'units.offline.body': 'The battery is empty, so your units are switched off and cannot be sent. Add power (Substation) or get rid of draw.',
|
||||
'units.offline.decom': 'Units are decommissioned in',
|
||||
'units.home': 'At home', 'units.home.empty': 'No units here yet. Train some below.',
|
||||
'units.hosted': 'Reinforcements here', 'units.away': 'Your units elsewhere',
|
||||
'units.sendHome': 'Send home', 'units.callBack': 'Call back', 'units.withdrawn': 'On their way home.',
|
||||
'units.training': 'Training', 'units.training.empty': 'Nothing in training.', 'units.train': 'Train units',
|
||||
'units.needs': 'Needs', 'units.perUnit': '{t} each', 'units.count': 'Number of units', 'units.max': 'As many as I can afford',
|
||||
'units.trainBtn': 'Train', 'units.time': 'Training time', 'units.research.time': 'Research time', 'units.readyAt': 'ready {t}', 'units.queued': 'Queued {n} × {unit}.',
|
||||
'units.research': 'Research', 'units.research.speed': '+{p}% research speed',
|
||||
'units.research.busy': 'Researching {unit}: {stat} level {level}',
|
||||
'units.research.hint': 'Each level gives +{p}% attack or defence for this unit type, up to level {max}. One research at a time per POP.',
|
||||
'units.research.level': 'Level {n} / {max}', 'units.research.effect': 'Per unit: {a} → {b}', 'units.research.start': 'Research level {n}', 'units.research.queued': 'Research started.',
|
||||
|
||||
// ---- movements screen + POP banner + push
|
||||
'mov.send': 'Send', 'mov.empty': 'Nothing on the wire. Pick a target on the map and send something.',
|
||||
'mov.incoming.head': 'Incoming movements ({n})', 'mov.incoming.title': 'Heading for {town}',
|
||||
'mov.incoming.from': 'From {operator}', 'mov.incoming.hint': 'Type and size are hidden. Treat it as hostile: raise defence or bring reinforcements.',
|
||||
'mov.outgoing.head': 'Your movements', 'mov.target': 'Target building: {name}',
|
||||
'mov.recall': 'Recall', 'mov.recalled': 'Recalled. They are turning around.',
|
||||
'mov.allied.head': 'Heading for allied POPs', 'mov.allied.title': '{operator}: {town}',
|
||||
'mov.banner.title': 'Incoming movement ({n})', 'mov.banner.next': 'Next one heads for {town}, from {operator}.', 'mov.banner.in': 'Arrives in', 'mov.banner.details': 'Details',
|
||||
'push.incoming': 'Incoming movement spotted!',
|
||||
|
||||
// ---- send dialog
|
||||
'send.title': 'Send', 'send.open': 'Send units here', 'send.target': 'Target', 'send.lookup': 'Look up', 'send.from': 'Send from',
|
||||
'send.what': 'What to do', 'send.nothing': 'There is nothing to send to this tile.', 'send.units': 'Units', 'send.all': 'All',
|
||||
'send.cargo': 'Cargo', 'send.cargo.cap': 'Up to {n} per transport. {free} of {links} transport links free.',
|
||||
'send.tilesPerHour': 'tiles/h', 'send.pickSome': 'Pick some units to see latency and arrival.',
|
||||
'send.distance': 'Distance', 'send.latency': 'Latency', 'send.arrives': 'Arrives about', 'send.slowest': 'Slowest unit', 'send.carry': 'Carries loot',
|
||||
'send.go': 'Send', 'send.sent': '{type} sent. Latency {t}.',
|
||||
'send.reason.no_units': 'no suitable units at home', 'send.reason.target_protected': 'target is under beginner protection',
|
||||
'send.reason.not_allied': 'not in your alliance', 'send.reason.no_link': 'needs an Internet exchange', 'send.reason.links_busy': 'all transport links are busy',
|
||||
'send.reason.needs_ma_team': 'needs at least one M&A team', 'send.reason.needs_crews': 'needs three Rollout crews at home',
|
||||
'send.reason.footprint': 'footprint {have} is below the {need} needed', 'send.reason.range': 'must be within {n} tiles of one of your POPs', 'send.reason.cannotSettle': 'only empty land can be settled',
|
||||
'send.settle.title': 'New POP', 'send.settle.crews': '{n} × {unit} will go and are used up.',
|
||||
'send.settle.footprint': 'Footprint {have}, {need} needed. Within {n} tiles of one of your POPs.', 'send.settle.wild': 'Wild field {n}',
|
||||
'send.protection.title': 'This ends your beginner protection.', 'send.protection.body': 'You are protected until {t}. Attacking gives that up for good. Tick to confirm.', 'send.protection.need': 'Confirm that you give up your beginner protection.',
|
||||
'send.siege': 'Exploit kits: building to damage', 'send.siege.none': 'No preference', 'send.siege.hint': 'Needs at least {n} kits left after the fight to damage anything.',
|
||||
'send.takeover.hint': 'An M&A team lowers customer loyalty on every win. At zero the POP is yours. Capitals and last POPs cannot be taken.',
|
||||
'send.raid.hint': 'A raid steals Capital, Fiber and Hardware up to what the survivors carry. Both sides lose fewer units than in an attack.',
|
||||
'send.scan.hint': 'Scanners come back if they survive. More scanners than the defender gets you more detail.',
|
||||
'send.reinforce.own': 'Units move into that POP and defend it. Pull them back from the Units screen.',
|
||||
'send.hostile.hint': 'The target is warned that something is coming, but not what.',
|
||||
'send.invalid.own_town': 'You cannot target yourself.', 'send.invalid.nothing_there': 'There is nothing there to target.', 'send.invalid.pact': 'A pact prevents that.',
|
||||
'send.invalid.not_allied': 'Only alliance members and confederates can be reinforced.', 'send.invalid.no_town': 'No POP there.', 'send.invalid.occupied': 'That tile is taken.',
|
||||
'send.invalid.not_empty_land': 'Only empty land can be settled.', 'send.invalid.outside_map': 'That is off the map.', 'send.invalid.same_town': 'Pick a different POP.',
|
||||
'send.invalid.incumbent_scan_or_attack_only': 'Incumbent sites can only be scanned or attacked.',
|
||||
|
||||
// ---- reports
|
||||
'rep.empty': 'No reports yet.', 'rep.markAll': 'Mark all read', 'rep.older': 'Older reports',
|
||||
'rep.victory': 'Victory', 'rep.defeat': 'Defeat', 'rep.captured': 'POP captured',
|
||||
'rep.sub.you_vs': 'You vs {name}', 'rep.sub.by': 'By {name}',
|
||||
'rep.scan.title': 'Scan of {where}', 'rep.scan.ok': 'Scan succeeded', 'rep.scan.failed': 'Scan failed', 'rep.scan.noIntel': 'The defender spotted your scanners before they learned anything.',
|
||||
'rep.scan.strength': 'Scan strength (you vs them)',
|
||||
'rep.detected.title': 'Scan detected at {town}', 'rep.detected.unknown': 'Somebody scanned this POP. Your scanners could not tell who.',
|
||||
'rep.incumbent.title': 'Incumbent site {x}, {y}', 'rep.incumbent.bonus': 'First win here pays {n} Hardware.', 'rep.incumbent.taken': 'You already took this site.', 'rep.incumbent.reward': 'Reward',
|
||||
'rep.settle.title': 'New POP: {name}', 'rep.settle.wild': 'Wild fields', 'rep.settle.open': 'Open the new POP', 'rep.settle.hint': 'It starts with a little Fiber, Hardware and Capital and no infrastructure. Build it up.',
|
||||
'rep.reinforce.sender': 'Reinforcements arrived at {town}', 'rep.reinforce.target': 'Reinforcements arrived at {town}',
|
||||
'rep.failed.title': '{type} failed', 'rep.failed.home': 'Units and cargo are on their way home.',
|
||||
'rep.reason.invalid_target': 'The target is no longer valid.', 'rep.reason.not_allied': 'The target is no longer an ally.', 'rep.reason.own_town': 'The POP changed hands and is yours now.',
|
||||
'rep.reason.pact': 'A pact with the target now prevents this.', 'rep.reason.protected': 'The target is under beginner protection.', 'rep.reason.target_gone': 'The target is gone.',
|
||||
'rep.reason.out_of_range': 'The site is out of range.', 'rep.reason.footprint_too_low': 'Your footprint was too low.',
|
||||
'rep.role.attacker': 'You attacked', 'rep.role.defender': 'You were attacked', 'rep.role.reinforcer': 'Your reinforcements were there', 'rep.role.sender': 'You sent', 'rep.role.target': 'You were the target',
|
||||
'rep.expires': 'kept until {t}', 'rep.arrived': 'Arrived {t}',
|
||||
'rep.attacker': 'Attacker', 'rep.defender': 'Defender', 'rep.target': 'Target', 'rep.from': 'From', 'rep.host': 'Host', 'rep.site': 'Site', 'rep.scannedBy': 'Scanned by',
|
||||
'rep.power': 'Strength', 'rep.power.attack': 'Attack', 'rep.power.defence': 'Defence', 'rep.power.firewall': 'Firewall level',
|
||||
'rep.attackerUnits': 'Attacking units', 'rep.defenderUnits': 'Defending units', 'rep.units': 'Units', 'rep.scanners': 'Scanners',
|
||||
'rep.sent': 'Sent', 'rep.lost': 'Lost', 'rep.left': 'Left', 'rep.noUnits': 'No units.',
|
||||
'rep.group.home': 'Home defence', 'rep.group.reinf': 'Reinforcements from {town}', 'rep.group.offline': 'offline, no defence',
|
||||
'rep.loot': 'Loot', 'rep.cache': '{p}% of the stock was hidden in the Rack hall.', 'rep.siege': 'Siege', 'rep.siege.line': '{name} damaged: level {a} → {b}',
|
||||
'rep.takeover': 'Takeover', 'rep.takeover.loyalty': 'Customer loyalty', 'rep.takeover.capital': 'A capital cannot change hands, it can only be drained.', 'rep.takeover.captured': 'The POP is now under new ownership.',
|
||||
'rep.takeover.blocked.last_pop': 'The target\'s last POP cannot be taken.', 'rep.takeover.blocked.footprint': 'Your footprint is too low to hold another POP.',
|
||||
'rep.intel': 'Intel', 'rep.intel.resources': 'Resources in stock', 'rep.intel.units': 'Units', 'rep.intel.offline': 'Their units are offline.', 'rep.intel.buildings': 'Buildings', 'rep.intel.outgoing': 'Their movements',
|
||||
|
||||
// ---- notification feed
|
||||
'alerts.incoming': 'Incoming movement', 'alerts.incoming.at': 'Heading for {town}, arrives {time}',
|
||||
'alerts.report': 'New report: {type}', 'alerts.train_done': '{n} × {unit} trained', 'alerts.research_done': '{unit}: {stat} level {level} researched',
|
||||
'alerts.movement_returned': 'Units are home', 'alerts.movement_lost': 'A movement lost its way home',
|
||||
'alerts.transport_arrived': 'Cargo arrived at {town}', 'alerts.transport_delivered': 'Your cargo was delivered',
|
||||
'alerts.units_offline': 'Units went offline: battery empty', 'alerts.units_decommissioned': 'Units decommissioned after too long without power',
|
||||
'alerts.town_lost': '{name} was taken over', 'alerts.town_lost.by': 'By {name}', 'alerts.town_gained': '{name} is now yours', 'alerts.reinforcements_home': 'Reinforcements sent home',
|
||||
|
||||
// ---- expansion
|
||||
'exp.title': 'Expansion', 'exp.count': '{n} POPs', 'exp.crews': 'Rollout crews at home', 'exp.footprint': 'Footprint (this POP / needed in total)', 'exp.footprint.v': '{have} / {need}',
|
||||
'exp.range': 'Range from your POPs', 'exp.hint': 'Three Rollout crews found a POP on empty land. A new POP also needs enough total footprint.',
|
||||
'exp.found': 'Pick a site on the map', 'exp.pick': 'Tap an empty tile and choose Send units here.', 'exp.train': 'Train Rollout crews', 'exp.needCrews': 'Train {n} more {unit}.',
|
||||
'exp.needDepot': 'Needs a Rollout depot (Core router level 10).', 'exp.pops': 'Your POPs', 'exp.current': 'Viewing', 'exp.open': 'Switch to',
|
||||
'map.legend.out': 'Your movement', 'map.legend.in': 'Incoming',
|
||||
|
||||
// ---- errors of the military routes
|
||||
'err.not_enough_units': 'Not enough of those units at home.', 'err.units_offline': 'Your units are offline: the battery is empty.',
|
||||
'err.invalid_target': 'That target does not work.', 'err.target_protected': 'The target is under beginner protection.',
|
||||
'err.protection_active': 'You are under beginner protection. Confirm that attacking ends it.', 'err.out_of_range': 'That is too far from your POPs.',
|
||||
'err.footprint_too_low': 'Your footprint is too low for another POP.', 'err.cannot_takeover': 'That POP cannot be taken over.',
|
||||
'err.capacity_exceeded': 'That is more than one transport can carry.', 'err.no_transport_link': 'No free transport link: build or wait for an Internet exchange.',
|
||||
'err.unknown_unit': 'No such unit.', 'err.not_researchable': 'That cannot be researched.', 'err.recall_expired': 'Too late to recall: the first 90 seconds are over.',
|
||||
},
|
||||
nb: {
|
||||
'nav.more': 'Mer', 'nav.units': 'Enheter', 'nav.movements': 'Ferd', 'nav.reports': 'Rapporter',
|
||||
'screen.units': 'Enheter', 'screen.movements': 'Bevegelser', 'screen.reports': 'Rapporter',
|
||||
|
||||
'unit.port_scanner.name': 'Portskanner', 'unit.port_scanner.desc': 'Stille små sonder. Speid en POP før du satser noe dyrt.',
|
||||
'unit.soc_analyst.name': 'SOC-analytiker', 'unit.soc_analyst.desc': 'Stirrer på dashbord så du slipper. Billig og stødig forsvar.',
|
||||
'unit.blue_team.name': 'Blått lag', 'unit.blue_team.desc': 'Hendelseshåndtering med skikkelig kaffe. Sterke forsvarere.',
|
||||
'unit.honeypot.name': 'Honeypot', 'unit.honeypot.desc': 'En svært fristende og svært falsk server. Forsvarer på stedet og går aldri noe sted.',
|
||||
'unit.script_crew.name': 'Skriptmannskap', 'unit.script_crew.desc': 'Billige, raske raidere som bærer med seg litt bytte hjem.',
|
||||
'unit.botnet.name': 'Botnett', 'unit.botnet.desc': 'Mange små maskiner med én dårlig idé. Sterkt, raskt og bærer mye.',
|
||||
'unit.ddos_rig.name': 'DDoS-rigg', 'unit.ddos_rig.desc': 'Flommer brannmuren. Hver 10. rigg senker målets brannmur ett nivå.',
|
||||
'unit.exploit_kit.name': 'Exploit-sett', 'unit.exploit_kit.desc': 'Finner den ene upatchede tingen. Skader en valgt bygning når du vinner.',
|
||||
'unit.rollout_crew.name': 'Utrullingslag', 'unit.rollout_crew.desc': 'Grøfter, rør og optimisme. Tre av dem etablerer en ny POP.',
|
||||
'unit.ma_team.name': 'Oppkjøpsteam', 'unit.ma_team.desc': 'Dress og en intensjonsavtale. Sliter ned kundelojaliteten til POP-en skifter eier.',
|
||||
'unit.stats': 'ANG {a} · FOR {d} · {s} ruter/t · bærer {c}', 'unit.fixed': 'blir stående', 'unit.draw': 'Strømtrekk {n}/t',
|
||||
'stat.attack': 'Angrep', 'stat.defence': 'Forsvar',
|
||||
|
||||
'move.type.scan': 'Skanning', 'move.type.raid': 'Phishing-raid', 'move.type.attack': 'Angrep', 'move.type.takeover': 'Fiendtlig oppkjøp',
|
||||
'move.type.reinforce': 'Peering-støtte', 'move.type.settle': 'Etabler POP', 'move.type.transport': 'Transport', 'move.type.return': 'På vei hjem', 'move.type.unknown': 'Ukjent',
|
||||
'report.type.raid': 'Phishing-raid', 'report.type.attack': 'Angrep', 'report.type.takeover': 'Fiendtlig oppkjøp', 'report.type.scan': 'Skanning',
|
||||
'report.type.scan_detected': 'Skanning oppdaget', 'report.type.incumbent': 'Gammeloperatørens anlegg', 'report.type.settle': 'Ny POP', 'report.type.reinforce': 'Forsterkninger',
|
||||
'report.type.movement_failed': 'Bevegelse mislyktes',
|
||||
|
||||
'mil.showOnMap': 'Vis {x}, {y} på kartet',
|
||||
|
||||
'units.status': 'Status', 'units.online': 'Online', 'units.powerNet': 'Netto strøm {n}/t',
|
||||
'units.offline.title': 'Enheter offline', 'units.offline.body': 'Batteriet er tomt, så enhetene er slått av og kan ikke sendes. Legg til strøm (Transformatorstasjon) eller kutt trekk.',
|
||||
'units.offline.decom': 'Enhetene avvikles om',
|
||||
'units.home': 'Hjemme', 'units.home.empty': 'Ingen enheter her ennå. Tren noen under.',
|
||||
'units.hosted': 'Forsterkninger her', 'units.away': 'Dine enheter andre steder',
|
||||
'units.sendHome': 'Send hjem', 'units.callBack': 'Kall tilbake', 'units.withdrawn': 'På vei hjem.',
|
||||
'units.training': 'Trening', 'units.training.empty': 'Ingenting under trening.', 'units.train': 'Tren enheter',
|
||||
'units.needs': 'Krever', 'units.perUnit': '{t} per stk.', 'units.count': 'Antall enheter', 'units.max': 'Så mange jeg har råd til',
|
||||
'units.trainBtn': 'Tren', 'units.time': 'Treningstid', 'units.research.time': 'Forskningstid', 'units.readyAt': 'ferdig {t}', 'units.queued': 'Satt i kø: {n} × {unit}.',
|
||||
'units.research': 'Forskning', 'units.research.speed': '+{p} % forskningsfart',
|
||||
'units.research.busy': 'Forsker på {unit}: {stat} nivå {level}',
|
||||
'units.research.hint': 'Hvert nivå gir +{p} % angrep eller forsvar for denne enhetstypen, opptil nivå {max}. Én forskning om gangen per POP.',
|
||||
'units.research.level': 'Nivå {n} / {max}', 'units.research.effect': 'Per enhet: {a} → {b}', 'units.research.start': 'Forsk nivå {n}', 'units.research.queued': 'Forskning startet.',
|
||||
|
||||
'mov.send': 'Send', 'mov.empty': 'Ingenting på vei. Velg et mål på kartet og send noe.',
|
||||
'mov.incoming.head': 'Innkommende bevegelser ({n})', 'mov.incoming.title': 'På vei mot {town}',
|
||||
'mov.incoming.from': 'Fra {operator}', 'mov.incoming.hint': 'Type og størrelse er skjult. Anta at det er fiendtlig: styrk forsvaret eller hent forsterkninger.',
|
||||
'mov.outgoing.head': 'Dine bevegelser', 'mov.target': 'Målbygning: {name}',
|
||||
'mov.recall': 'Kall tilbake', 'mov.recalled': 'Kalt tilbake. De snur.',
|
||||
'mov.allied.head': 'På vei mot allierte POP-er', 'mov.allied.title': '{operator}: {town}',
|
||||
'mov.banner.title': 'Innkommende bevegelse ({n})', 'mov.banner.next': 'Den neste går mot {town}, fra {operator}.', 'mov.banner.in': 'Ankommer om', 'mov.banner.details': 'Detaljer',
|
||||
'push.incoming': 'Innkommende bevegelse oppdaget!',
|
||||
|
||||
'send.title': 'Send', 'send.open': 'Send enheter hit', 'send.target': 'Mål', 'send.lookup': 'Slå opp', 'send.from': 'Send fra',
|
||||
'send.what': 'Hva skal skje', 'send.nothing': 'Det er ingenting å sende til denne ruta.', 'send.units': 'Enheter', 'send.all': 'Alle',
|
||||
'send.cargo': 'Last', 'send.cargo.cap': 'Opptil {n} per transport. {free} av {links} transportlenker er ledige.',
|
||||
'send.tilesPerHour': 'ruter/t', 'send.pickSome': 'Velg noen enheter for å se latens og ankomst.',
|
||||
'send.distance': 'Avstand', 'send.latency': 'Latens', 'send.arrives': 'Ankommer ca.', 'send.slowest': 'Tregeste enhet', 'send.carry': 'Bærer bytte',
|
||||
'send.go': 'Send', 'send.sent': '{type} sendt. Latens {t}.',
|
||||
'send.reason.no_units': 'ingen egnede enheter hjemme', 'send.reason.target_protected': 'målet har nybegynnerbeskyttelse',
|
||||
'send.reason.not_allied': 'ikke i din allianse', 'send.reason.no_link': 'krever et Internettknutepunkt', 'send.reason.links_busy': 'alle transportlenker er opptatt',
|
||||
'send.reason.needs_ma_team': 'krever minst ett oppkjøpsteam', 'send.reason.needs_crews': 'krever tre utrullingslag hjemme',
|
||||
'send.reason.footprint': 'fotavtrykket {have} er lavere enn de {need} som kreves', 'send.reason.range': 'må ligge innenfor {n} ruter fra en av dine POP-er', 'send.reason.cannotSettle': 'bare tomt land kan bebygges',
|
||||
'send.settle.title': 'Ny POP', 'send.settle.crews': '{n} × {unit} drar av gårde og brukes opp.',
|
||||
'send.settle.footprint': 'Fotavtrykk {have}, {need} kreves. Innenfor {n} ruter fra en av dine POP-er.', 'send.settle.wild': 'Fritt felt {n}',
|
||||
'send.protection.title': 'Dette avslutter nybegynnerbeskyttelsen din.', 'send.protection.body': 'Du er beskyttet til {t}. Et angrep gir den fra seg for godt. Kryss av for å bekrefte.', 'send.protection.need': 'Bekreft at du gir fra deg nybegynnerbeskyttelsen.',
|
||||
'send.siege': 'Exploit-sett: bygning som skal skades', 'send.siege.none': 'Ingen preferanse', 'send.siege.hint': 'Trenger minst {n} sett igjen etter kampen for å skade noe.',
|
||||
'send.takeover.hint': 'Et oppkjøpsteam senker kundelojaliteten for hver seier. Ved null er POP-en din. Hovedsteder og siste POP kan ikke tas.',
|
||||
'send.raid.hint': 'En raid stjeler Kapital, Fiber og Maskinvare opptil det de overlevende bærer. Begge sider mister færre enheter enn i et angrep.',
|
||||
'send.scan.hint': 'Skannerne kommer tilbake hvis de overlever. Flere skannere enn forsvareren gir flere detaljer.',
|
||||
'send.reinforce.own': 'Enhetene flytter inn i den POP-en og forsvarer den. Hent dem tilbake fra Enheter-skjermen.',
|
||||
'send.hostile.hint': 'Målet blir varslet om at noe er på vei, men ikke hva.',
|
||||
'send.invalid.own_town': 'Du kan ikke velge deg selv.', 'send.invalid.nothing_there': 'Det er ingenting der å angripe.', 'send.invalid.pact': 'En avtale hindrer det.',
|
||||
'send.invalid.not_allied': 'Bare alliansemedlemmer og konfødererte kan få forsterkninger.', 'send.invalid.no_town': 'Ingen POP der.', 'send.invalid.occupied': 'Den ruta er tatt.',
|
||||
'send.invalid.not_empty_land': 'Bare tomt land kan bebygges.', 'send.invalid.outside_map': 'Det er utenfor kartet.', 'send.invalid.same_town': 'Velg en annen POP.',
|
||||
'send.invalid.incumbent_scan_or_attack_only': 'Gammeloperatørens anlegg kan bare skannes eller angripes.',
|
||||
|
||||
'rep.empty': 'Ingen rapporter ennå.', 'rep.markAll': 'Merk alle som lest', 'rep.older': 'Eldre rapporter',
|
||||
'rep.victory': 'Seier', 'rep.defeat': 'Nederlag', 'rep.captured': 'POP overtatt',
|
||||
'rep.sub.you_vs': 'Du mot {name}', 'rep.sub.by': 'Av {name}',
|
||||
'rep.scan.title': 'Skanning av {where}', 'rep.scan.ok': 'Skanningen lyktes', 'rep.scan.failed': 'Skanningen mislyktes', 'rep.scan.noIntel': 'Forsvareren oppdaget skannerne dine før de fikk vite noe.',
|
||||
'rep.scan.strength': 'Skannestyrke (du mot dem)',
|
||||
'rep.detected.title': 'Skanning oppdaget ved {town}', 'rep.detected.unknown': 'Noen skannet denne POP-en. Skannerne dine kunne ikke si hvem.',
|
||||
'rep.incumbent.title': 'Gammeloperatørens anlegg {x}, {y}', 'rep.incumbent.bonus': 'Første seier her gir {n} Maskinvare.', 'rep.incumbent.taken': 'Du har allerede tatt dette anlegget.', 'rep.incumbent.reward': 'Belønning',
|
||||
'rep.settle.title': 'Ny POP: {name}', 'rep.settle.wild': 'Frie felt', 'rep.settle.open': 'Åpne den nye POP-en', 'rep.settle.hint': 'Den starter med litt Fiber, Maskinvare og Kapital og ingen infrastruktur. Bygg den opp.',
|
||||
'rep.reinforce.sender': 'Forsterkninger kom frem til {town}', 'rep.reinforce.target': 'Forsterkninger kom frem til {town}',
|
||||
'rep.failed.title': '{type} mislyktes', 'rep.failed.home': 'Enheter og last er på vei hjem.',
|
||||
'rep.reason.invalid_target': 'Målet er ikke gyldig lenger.', 'rep.reason.not_allied': 'Målet er ikke lenger alliert.', 'rep.reason.own_town': 'POP-en skiftet eier og er din nå.',
|
||||
'rep.reason.pact': 'En avtale med målet hindrer dette nå.', 'rep.reason.protected': 'Målet har nybegynnerbeskyttelse.', 'rep.reason.target_gone': 'Målet finnes ikke lenger.',
|
||||
'rep.reason.out_of_range': 'Stedet er utenfor rekkevidde.', 'rep.reason.footprint_too_low': 'Fotavtrykket ditt var for lavt.',
|
||||
'rep.role.attacker': 'Du angrep', 'rep.role.defender': 'Du ble angrepet', 'rep.role.reinforcer': 'Forsterkningene dine var der', 'rep.role.sender': 'Du sendte', 'rep.role.target': 'Du var målet',
|
||||
'rep.expires': 'lagres til {t}', 'rep.arrived': 'Ankom {t}',
|
||||
'rep.attacker': 'Angriper', 'rep.defender': 'Forsvarer', 'rep.target': 'Mål', 'rep.from': 'Fra', 'rep.host': 'Vert', 'rep.site': 'Sted', 'rep.scannedBy': 'Skannet av',
|
||||
'rep.power': 'Styrke', 'rep.power.attack': 'Angrep', 'rep.power.defence': 'Forsvar', 'rep.power.firewall': 'Brannmurnivå',
|
||||
'rep.attackerUnits': 'Angripende enheter', 'rep.defenderUnits': 'Forsvarende enheter', 'rep.units': 'Enheter', 'rep.scanners': 'Skannere',
|
||||
'rep.sent': 'Sendt', 'rep.lost': 'Tapt', 'rep.left': 'Igjen', 'rep.noUnits': 'Ingen enheter.',
|
||||
'rep.group.home': 'Hjemmeforsvar', 'rep.group.reinf': 'Forsterkninger fra {town}', 'rep.group.offline': 'offline, uten forsvar',
|
||||
'rep.loot': 'Bytte', 'rep.cache': '{p} % av lageret var skjult i Racksalen.', 'rep.siege': 'Beleiring', 'rep.siege.line': '{name} skadet: nivå {a} → {b}',
|
||||
'rep.takeover': 'Oppkjøp', 'rep.takeover.loyalty': 'Kundelojalitet', 'rep.takeover.capital': 'En hovedstad kan ikke skifte eier, bare tappes.', 'rep.takeover.captured': 'POP-en har nå ny eier.',
|
||||
'rep.takeover.blocked.last_pop': 'Målets siste POP kan ikke tas.', 'rep.takeover.blocked.footprint': 'Fotavtrykket ditt er for lavt til å holde enda en POP.',
|
||||
'rep.intel': 'Etterretning', 'rep.intel.resources': 'Ressurser på lager', 'rep.intel.units': 'Enheter', 'rep.intel.offline': 'Enhetene deres er offline.', 'rep.intel.buildings': 'Bygninger', 'rep.intel.outgoing': 'Bevegelsene deres',
|
||||
|
||||
'alerts.incoming': 'Innkommende bevegelse', 'alerts.incoming.at': 'På vei mot {town}, ankommer {time}',
|
||||
'alerts.report': 'Ny rapport: {type}', 'alerts.train_done': '{n} × {unit} ferdig trent', 'alerts.research_done': '{unit}: {stat} nivå {level} ferdig forsket',
|
||||
'alerts.movement_returned': 'Enhetene er hjemme', 'alerts.movement_lost': 'En bevegelse fant ikke veien hjem',
|
||||
'alerts.transport_arrived': 'Last kom frem til {town}', 'alerts.transport_delivered': 'Lasten din er levert',
|
||||
'alerts.units_offline': 'Enheter gikk offline: tomt batteri', 'alerts.units_decommissioned': 'Enheter avviklet etter for lenge uten strøm',
|
||||
'alerts.town_lost': '{name} ble overtatt', 'alerts.town_lost.by': 'Av {name}', 'alerts.town_gained': '{name} er nå din', 'alerts.reinforcements_home': 'Forsterkninger sendt hjem',
|
||||
|
||||
'exp.title': 'Ekspansjon', 'exp.count': '{n} POP-er', 'exp.crews': 'Utrullingslag hjemme', 'exp.footprint': 'Fotavtrykk (denne POP-en / kreves totalt)', 'exp.footprint.v': '{have} / {need}',
|
||||
'exp.range': 'Rekkevidde fra dine POP-er', 'exp.hint': 'Tre utrullingslag etablerer en POP på tomt land. En ny POP krever også nok totalt fotavtrykk.',
|
||||
'exp.found': 'Velg sted på kartet', 'exp.pick': 'Trykk på en tom rute og velg Send enheter hit.', 'exp.train': 'Tren utrullingslag', 'exp.needCrews': 'Tren {n} flere {unit}.',
|
||||
'exp.needDepot': 'Krever et Utrullingsdepot (Kjerneruter nivå 10).', 'exp.pops': 'Dine POP-er', 'exp.current': 'Vises nå', 'exp.open': 'Bytt til',
|
||||
'map.legend.out': 'Din bevegelse', 'map.legend.in': 'Innkommende',
|
||||
|
||||
'err.not_enough_units': 'Ikke nok av de enhetene hjemme.', 'err.units_offline': 'Enhetene dine er offline: batteriet er tomt.',
|
||||
'err.invalid_target': 'Det målet fungerer ikke.', 'err.target_protected': 'Målet har nybegynnerbeskyttelse.',
|
||||
'err.protection_active': 'Du har nybegynnerbeskyttelse. Bekreft at et angrep avslutter den.', 'err.out_of_range': 'Det er for langt fra POP-ene dine.',
|
||||
'err.footprint_too_low': 'Fotavtrykket ditt er for lavt for enda en POP.', 'err.cannot_takeover': 'Den POP-en kan ikke overtas.',
|
||||
'err.capacity_exceeded': 'Det er mer enn én transport kan bære.', 'err.no_transport_link': 'Ingen ledig transportlenke: bygg eller vent på et Internettknutepunkt.',
|
||||
'err.unknown_unit': 'Ingen slik enhet.', 'err.not_researchable': 'Det kan ikke forskes på.', 'err.recall_expired': 'For sent å kalle tilbake: de første 90 sekundene er over.',
|
||||
},
|
||||
});
|
||||
}));
|
||||
232
public/js/strings/social.js
Normal file
232
public/js/strings/social.js
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
'use strict';
|
||||
/* Strings of the social screens (alliance, messages, rankings). en + nb, key parity enforced by test/client-i18n.test.js. */
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||
else factory(root.UpstreamI18n);
|
||||
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||
I.extend({
|
||||
en: {
|
||||
'nav.alliance': 'Alliance', 'nav.messages': 'Messages', 'nav.rankings': 'Rankings',
|
||||
'screen.alliance': 'Alliance', 'screen.messages': 'Messages', 'screen.rankings': 'Rankings',
|
||||
|
||||
// errors the social routes can return (existing codes such as forbidden / not_found / rate_limited are translated elsewhere)
|
||||
'err.peering_office_required': 'You need a Peering office (level 1 or higher) to found or join an alliance.',
|
||||
'err.already_in_alliance': 'That operator is already in an alliance.',
|
||||
'err.not_in_alliance': 'You are not in an alliance.',
|
||||
'err.alliance_name_taken': 'That alliance name is taken.',
|
||||
'err.alliance_tag_taken': 'That alliance tag is taken.',
|
||||
'err.alliance_full': 'The alliance has no room for more members.',
|
||||
'err.invite_expired': 'The invitation has expired.',
|
||||
'err.leader_must_transfer': 'The leader must hand over leadership before leaving.',
|
||||
'err.notes_full': 'The pinned-note limit is reached. Remove one first.',
|
||||
'err.diplomacy_invalid': 'That diplomatic move is not possible from the current state.',
|
||||
'err.diplomacy_pending': 'A change between these alliances is already scheduled.',
|
||||
'err.proposal_exists': 'They already proposed this. Accept their proposal instead.',
|
||||
'err.proposal_expired': 'The proposal has expired.',
|
||||
|
||||
'soc.you': 'You', 'soc.more': 'Load more', 'soc.tab.label': 'Sections',
|
||||
'soc.tab.overview': 'Overview', 'soc.tab.members': 'Members', 'soc.tab.diplomacy': 'Diplomacy',
|
||||
'soc.role.leader': 'Leader', 'soc.role.diplomat': 'Diplomat', 'soc.role.officer': 'Officer', 'soc.role.member': 'Member',
|
||||
'soc.state.war': 'War', 'soc.state.neutral': 'Neutral', 'soc.state.nap': 'Non-aggression', 'soc.state.confed': 'Confederation',
|
||||
'soc.relation.same': 'Your alliance',
|
||||
'soc.members': 'Members', 'soc.leader': 'Leader', 'soc.footprint': 'Footprint', 'soc.founded': 'Founded', 'soc.profile': 'Alliance',
|
||||
'soc.size': '{n}/{cap} members', 'soc.leaderIs': 'Leader: {name}',
|
||||
'soc.rate': 'You are sending too fast. Try again in {t}.',
|
||||
|
||||
// not in an alliance
|
||||
'soc.create.title': 'Found an alliance',
|
||||
'soc.create.intro': 'Rival operators are easier to outlast with friends. Found an alliance and invite others, or accept an invitation below.',
|
||||
'soc.create.name': 'Name', 'soc.create.tag': 'Tag',
|
||||
'soc.create.nameHint': '{a}-{b} characters: letters, digits, spaces, . _ \' -',
|
||||
'soc.create.tagHint': '{a}-{b} letters or digits, shown in brackets next to names',
|
||||
'soc.create.go': 'Found alliance', 'soc.create.done': 'Alliance founded.',
|
||||
'soc.create.needOffice': 'Build a {building} (level {n}) in one of your POPs first.',
|
||||
'soc.create.invalid': 'Name: {n1}-{n2} characters. Tag: {t1}-{t2} letters or digits.',
|
||||
'soc.invites.title': 'Invitations', 'soc.invites.none': 'No open invitations.',
|
||||
'soc.invites.needOffice': 'Accepting needs a {building} too.',
|
||||
'soc.invites.from': 'from {name}', 'soc.invites.expires': 'expires in {t}',
|
||||
'soc.invites.accept': 'Accept', 'soc.invites.decline': 'Decline',
|
||||
'soc.invites.accepted': 'You joined the alliance.', 'soc.invites.declined': 'Invitation declined.',
|
||||
|
||||
// overview
|
||||
'soc.notes.title': 'Pinned notes', 'soc.notes.none': 'No pinned notes yet.', 'soc.notes.add': 'Pin note', 'soc.notes.remove': 'Remove note',
|
||||
'soc.notes.placeholder': 'Rally points, rules, targets...',
|
||||
'soc.manage.title': 'Membership',
|
||||
'soc.leave.go': 'Leave alliance', 'soc.leave.done': 'You left the alliance.',
|
||||
'soc.leave.confirm': 'Leave {name}? You can be invited again.',
|
||||
'soc.leave.confirmAlone': 'You are the only member of {name}. Leaving disbands it.',
|
||||
'soc.leave.mustTransfer': 'You are the leader. Hand over leadership to a member before you can leave.',
|
||||
'soc.leave.goTransfer': 'Choose a successor',
|
||||
'soc.disband.go': 'Disband alliance', 'soc.disband.done': 'Alliance disbanded.',
|
||||
'soc.disband.confirm': 'Disband {name} for everyone? This cannot be undone.',
|
||||
|
||||
// members
|
||||
'soc.member.stats': 'POPs {towns} · footprint {fp}', 'soc.member.online': 'online {t}', 'soc.member.never': 'never online',
|
||||
'soc.member.pops': 'POPs', 'soc.member.lastOnline': 'Last online', 'soc.member.joined': 'Joined',
|
||||
'soc.member.message': 'Send message', 'soc.member.setRole': 'Set role',
|
||||
'soc.member.roleHint': 'Officers invite and remove members, diplomats handle other alliances.',
|
||||
'soc.member.roleSet': '{name} is now {role}.',
|
||||
'soc.transfer.go': 'Make leader', 'soc.transfer.confirm': 'Hand leadership to {name}? You become an officer.', 'soc.transfer.done': '{name} is the new leader.',
|
||||
'soc.kick.go': 'Remove from alliance', 'soc.kick.confirm': 'Remove {name} from the alliance?', 'soc.kick.done': '{name} was removed.',
|
||||
'soc.invite.title': 'Invite an operator', 'soc.invite.name': 'Operator name', 'soc.invite.go': 'Invite',
|
||||
'soc.invite.sent': 'Invitation sent to {name}.', 'soc.invite.already': '{name} already has an open invitation.',
|
||||
'soc.invite.unknown': 'No operator called {name} in this world.',
|
||||
'soc.invite.pending': 'Open invitations', 'soc.invite.none': 'None pending.', 'soc.invite.cancel': 'Cancel invitation',
|
||||
|
||||
// diplomacy
|
||||
'soc.dip.title': 'Diplomacy', 'soc.dip.new': 'New move', 'soc.dip.relations': 'Relations', 'soc.dip.none': 'Neutral with everyone.',
|
||||
'soc.dip.readOnly': 'Only leaders and diplomats change diplomatic relations.',
|
||||
'soc.dip.incoming': 'Proposals to you', 'soc.dip.outgoing': 'Your proposals',
|
||||
'soc.dip.accept': 'Accept', 'soc.dip.decline': 'Decline', 'soc.dip.withdraw': 'Withdraw', 'soc.dip.revoke': 'Take back',
|
||||
'soc.dip.revoked': 'Scheduled change cancelled.',
|
||||
'soc.dip.expires': 'expires in {t}', 'soc.dip.in': 'in {t}', 'soc.dip.applying': 'applying...',
|
||||
'soc.dip.byUs': 'started by you', 'soc.dip.byThem': 'started by them',
|
||||
'soc.dip.pick': 'Choose an alliance', 'soc.dip.search': 'Search name or tag', 'soc.dip.noResults': 'No other alliances found.',
|
||||
'soc.dip.current': 'Now: {state}', 'soc.dip.locked': 'A change is already scheduled for this pair.', 'soc.dip.noMoves': 'No move is possible from here.',
|
||||
'soc.dip.result.applied': 'Now {state} with {name}.',
|
||||
'soc.dip.result.proposed': 'Proposal sent: {state} with {name}.',
|
||||
'soc.dip.result.scheduled': 'Change to {state} with {name} scheduled.',
|
||||
'soc.kind.immediate': 'Takes effect at once', 'soc.kind.immediate.hint': 'No consent needed.',
|
||||
'soc.kind.proposal': 'Needs their consent', 'soc.kind.proposal.hint': 'They get a proposal and must accept it.',
|
||||
'soc.kind.delayed': 'Cancels after a delay', 'soc.kind.delayed.hint': 'Leaving a pact takes {t}, so a partner is never surprised.',
|
||||
|
||||
// messages
|
||||
'soc.msg.tab.inbox': 'Inbox', 'soc.msg.tab.sent': 'Sent', 'soc.msg.tab.alliance': 'Alliance', 'soc.msg.tab.blocked': 'Blocked',
|
||||
'soc.msg.new.go': 'New', 'soc.msg.new.title': 'New message', 'soc.msg.new': 'New',
|
||||
'soc.msg.recipient': 'To (operator name)', 'soc.msg.nameHint': 'Names are not case sensitive.',
|
||||
'soc.msg.text': 'Message', 'soc.msg.send': 'Send', 'soc.msg.sent': 'Message sent.', 'soc.msg.counter': '{n} of {max} characters',
|
||||
'soc.msg.to': 'Message to {name}', 'soc.msg.toShort': 'To {name}', 'soc.msg.toAlliance': 'Message to your alliance',
|
||||
'soc.msg.unknown': 'No operator called {name} in this world.',
|
||||
'soc.msg.reply': 'Write a reply...', 'soc.msg.older': 'Older messages',
|
||||
'soc.msg.thread.empty': 'No messages with {name} yet.',
|
||||
'soc.msg.allianceFeed': 'Alliance broadcast',
|
||||
'soc.msg.broadcast': 'Broadcast', 'soc.msg.broadcastPlaceholder': 'Tell everyone in the alliance...',
|
||||
'soc.msg.broadcastHint': 'Everyone currently in {tag} gets this message.',
|
||||
'soc.msg.unreadOnly': 'Unread only', 'soc.msg.markAll': 'Mark all read',
|
||||
'soc.msg.delete': 'Delete my copy', 'soc.msg.deleted': 'Deleted. The other side keeps their copy.',
|
||||
'soc.msg.empty.inbox': 'Nothing in your inbox.', 'soc.msg.empty.sent': 'You have not sent anything.', 'soc.msg.empty.alliance': 'No alliance broadcasts yet.',
|
||||
'soc.block.go': 'Block', 'soc.block.unblock': 'Unblock', 'soc.block.blocked': '{name} is blocked.', 'soc.block.unblocked': '{name} is unblocked.',
|
||||
'soc.block.hint': 'Blocked operators cannot reach you and are not told.', 'soc.block.none': 'You have not blocked anyone.',
|
||||
'soc.block.since': 'blocked {t}', 'soc.block.threadHint': 'You blocked this operator. Their messages are not delivered to you.',
|
||||
|
||||
// rankings
|
||||
'soc.rank.tab.operators': 'Operators', 'soc.rank.tab.alliances': 'Alliances', 'soc.rank.tab.battles': 'Battles',
|
||||
'soc.rank.by': 'Battle ranking by', 'soc.rank.by.attack': 'Attack', 'soc.rank.by.defense': 'Defense', 'soc.rank.by.total': 'Total',
|
||||
'soc.rank.yours': 'Your rank', 'soc.rank.of': 'of {n}', 'soc.rank.notShown': 'below the loaded list',
|
||||
'soc.rank.pops': 'POPs {n}', 'soc.rank.members': '{n} members', 'soc.rank.att': 'attack {n}', 'soc.rank.def': 'defense {n}',
|
||||
'soc.rank.attack': 'Attack points', 'soc.rank.defense': 'Defense points', 'soc.rank.viewAlliance': 'View alliance',
|
||||
'soc.rank.empty': 'Nobody is ranked yet.', 'soc.rank.noBattles': 'Nobody has battle points yet.',
|
||||
'soc.rank.unavailable': 'Battle rankings are not recorded yet.',
|
||||
'soc.rank.noAlliance': 'You are not in an alliance, so you are not ranked here.',
|
||||
'soc.rank.noPoints': 'You have no battle points yet.',
|
||||
},
|
||||
nb: {
|
||||
'nav.alliance': 'Allianse', 'nav.messages': 'Meldinger', 'nav.rankings': 'Rangering',
|
||||
'screen.alliance': 'Allianse', 'screen.messages': 'Meldinger', 'screen.rankings': 'Rangering',
|
||||
|
||||
'err.peering_office_required': 'Du trenger et peeringkontor (nivå 1 eller høyere) for å stifte eller bli med i en allianse.',
|
||||
'err.already_in_alliance': 'Den operatøren er allerede i en allianse.',
|
||||
'err.not_in_alliance': 'Du er ikke i en allianse.',
|
||||
'err.alliance_name_taken': 'Det alliansenavnet er opptatt.',
|
||||
'err.alliance_tag_taken': 'Den alliansetaggen er opptatt.',
|
||||
'err.alliance_full': 'Alliansen har ikke plass til flere medlemmer.',
|
||||
'err.invite_expired': 'Invitasjonen har utløpt.',
|
||||
'err.leader_must_transfer': 'Lederen må gi fra seg ledelsen før hen kan forlate alliansen.',
|
||||
'err.notes_full': 'Grensen for festede notater er nådd. Fjern ett først.',
|
||||
'err.diplomacy_invalid': 'Det diplomatiske trekket er ikke mulig fra nåværende tilstand.',
|
||||
'err.diplomacy_pending': 'En endring mellom disse alliansene er allerede planlagt.',
|
||||
'err.proposal_exists': 'De har allerede foreslått dette. Godta forslaget deres i stedet.',
|
||||
'err.proposal_expired': 'Forslaget har utløpt.',
|
||||
|
||||
'soc.you': 'Du', 'soc.more': 'Last flere', 'soc.tab.label': 'Seksjoner',
|
||||
'soc.tab.overview': 'Oversikt', 'soc.tab.members': 'Medlemmer', 'soc.tab.diplomacy': 'Diplomati',
|
||||
'soc.role.leader': 'Leder', 'soc.role.diplomat': 'Diplomat', 'soc.role.officer': 'Offiser', 'soc.role.member': 'Medlem',
|
||||
'soc.state.war': 'Krig', 'soc.state.neutral': 'Nøytral', 'soc.state.nap': 'Ikke-angrep', 'soc.state.confed': 'Konføderasjon',
|
||||
'soc.relation.same': 'Din allianse',
|
||||
'soc.members': 'Medlemmer', 'soc.leader': 'Leder', 'soc.footprint': 'Fotavtrykk', 'soc.founded': 'Stiftet', 'soc.profile': 'Allianse',
|
||||
'soc.size': '{n}/{cap} medlemmer', 'soc.leaderIs': 'Leder: {name}',
|
||||
'soc.rate': 'Du sender for fort. Prøv igjen om {t}.',
|
||||
|
||||
'soc.create.title': 'Stift en allianse',
|
||||
'soc.create.intro': 'Rivaliserende operatører er lettere å overleve med venner. Stift en allianse og inviter andre, eller godta en invitasjon under.',
|
||||
'soc.create.name': 'Navn', 'soc.create.tag': 'Tagg',
|
||||
'soc.create.nameHint': '{a}-{b} tegn: bokstaver, tall, mellomrom, . _ \' -',
|
||||
'soc.create.tagHint': '{a}-{b} bokstaver eller tall, vises i klammer ved siden av navn',
|
||||
'soc.create.go': 'Stift allianse', 'soc.create.done': 'Alliansen er stiftet.',
|
||||
'soc.create.needOffice': 'Bygg først et {building} (nivå {n}) i en av POP-ene dine.',
|
||||
'soc.create.invalid': 'Navn: {n1}-{n2} tegn. Tagg: {t1}-{t2} bokstaver eller tall.',
|
||||
'soc.invites.title': 'Invitasjoner', 'soc.invites.none': 'Ingen åpne invitasjoner.',
|
||||
'soc.invites.needOffice': 'For å godta trenger du også et {building}.',
|
||||
'soc.invites.from': 'fra {name}', 'soc.invites.expires': 'utløper om {t}',
|
||||
'soc.invites.accept': 'Godta', 'soc.invites.decline': 'Avslå',
|
||||
'soc.invites.accepted': 'Du ble med i alliansen.', 'soc.invites.declined': 'Invitasjonen er avslått.',
|
||||
|
||||
'soc.notes.title': 'Festede notater', 'soc.notes.none': 'Ingen festede notater ennå.', 'soc.notes.add': 'Fest notat', 'soc.notes.remove': 'Fjern notat',
|
||||
'soc.notes.placeholder': 'Samlingspunkter, regler, mål...',
|
||||
'soc.manage.title': 'Medlemskap',
|
||||
'soc.leave.go': 'Forlat alliansen', 'soc.leave.done': 'Du forlot alliansen.',
|
||||
'soc.leave.confirm': 'Forlate {name}? Du kan bli invitert igjen.',
|
||||
'soc.leave.confirmAlone': 'Du er eneste medlem av {name}. Hvis du forlater den, oppløses den.',
|
||||
'soc.leave.mustTransfer': 'Du er leder. Gi ledelsen til et medlem før du kan forlate alliansen.',
|
||||
'soc.leave.goTransfer': 'Velg etterfølger',
|
||||
'soc.disband.go': 'Oppløs alliansen', 'soc.disband.done': 'Alliansen er oppløst.',
|
||||
'soc.disband.confirm': 'Oppløse {name} for alle? Dette kan ikke angres.',
|
||||
|
||||
'soc.member.stats': 'POP-er {towns} · fotavtrykk {fp}', 'soc.member.online': 'pålogget {t}', 'soc.member.never': 'aldri pålogget',
|
||||
'soc.member.pops': 'POP-er', 'soc.member.lastOnline': 'Sist pålogget', 'soc.member.joined': 'Ble med',
|
||||
'soc.member.message': 'Send melding', 'soc.member.setRole': 'Sett rolle',
|
||||
'soc.member.roleHint': 'Offiserer inviterer og fjerner medlemmer, diplomater tar seg av andre allianser.',
|
||||
'soc.member.roleSet': '{name} er nå {role}.',
|
||||
'soc.transfer.go': 'Gjør til leder', 'soc.transfer.confirm': 'Gi ledelsen til {name}? Du blir offiser.', 'soc.transfer.done': '{name} er ny leder.',
|
||||
'soc.kick.go': 'Fjern fra alliansen', 'soc.kick.confirm': 'Fjerne {name} fra alliansen?', 'soc.kick.done': '{name} ble fjernet.',
|
||||
'soc.invite.title': 'Inviter en operatør', 'soc.invite.name': 'Operatørnavn', 'soc.invite.go': 'Inviter',
|
||||
'soc.invite.sent': 'Invitasjon sendt til {name}.', 'soc.invite.already': '{name} har allerede en åpen invitasjon.',
|
||||
'soc.invite.unknown': 'Ingen operatør heter {name} i denne verdenen.',
|
||||
'soc.invite.pending': 'Åpne invitasjoner', 'soc.invite.none': 'Ingen ventende.', 'soc.invite.cancel': 'Trekk tilbake invitasjon',
|
||||
|
||||
'soc.dip.title': 'Diplomati', 'soc.dip.new': 'Nytt trekk', 'soc.dip.relations': 'Forhold', 'soc.dip.none': 'Nøytral til alle.',
|
||||
'soc.dip.readOnly': 'Bare ledere og diplomater endrer diplomatiske forhold.',
|
||||
'soc.dip.incoming': 'Forslag til deg', 'soc.dip.outgoing': 'Dine forslag',
|
||||
'soc.dip.accept': 'Godta', 'soc.dip.decline': 'Avslå', 'soc.dip.withdraw': 'Trekk tilbake', 'soc.dip.revoke': 'Angre',
|
||||
'soc.dip.revoked': 'Planlagt endring avbrutt.',
|
||||
'soc.dip.expires': 'utløper om {t}', 'soc.dip.in': 'om {t}', 'soc.dip.applying': 'trer i kraft...',
|
||||
'soc.dip.byUs': 'startet av dere', 'soc.dip.byThem': 'startet av dem',
|
||||
'soc.dip.pick': 'Velg en allianse', 'soc.dip.search': 'Søk etter navn eller tagg', 'soc.dip.noResults': 'Fant ingen andre allianser.',
|
||||
'soc.dip.current': 'Nå: {state}', 'soc.dip.locked': 'En endring er allerede planlagt for dette paret.', 'soc.dip.noMoves': 'Ingen trekk er mulige herfra.',
|
||||
'soc.dip.result.applied': 'Nå {state} med {name}.',
|
||||
'soc.dip.result.proposed': 'Forslag sendt: {state} med {name}.',
|
||||
'soc.dip.result.scheduled': 'Endring til {state} med {name} er planlagt.',
|
||||
'soc.kind.immediate': 'Trer i kraft med en gang', 'soc.kind.immediate.hint': 'Trenger ikke samtykke.',
|
||||
'soc.kind.proposal': 'Trenger deres samtykke', 'soc.kind.proposal.hint': 'De får et forslag og må godta det.',
|
||||
'soc.kind.delayed': 'Sies opp med frist', 'soc.kind.delayed.hint': 'Å forlate en avtale tar {t}, så en partner aldri overraskes.',
|
||||
|
||||
'soc.msg.tab.inbox': 'Innboks', 'soc.msg.tab.sent': 'Sendt', 'soc.msg.tab.alliance': 'Allianse', 'soc.msg.tab.blocked': 'Blokkert',
|
||||
'soc.msg.new.go': 'Ny', 'soc.msg.new.title': 'Ny melding', 'soc.msg.new': 'Ny',
|
||||
'soc.msg.recipient': 'Til (operatørnavn)', 'soc.msg.nameHint': 'Store og små bokstaver spiller ingen rolle.',
|
||||
'soc.msg.text': 'Melding', 'soc.msg.send': 'Send', 'soc.msg.sent': 'Melding sendt.', 'soc.msg.counter': '{n} av {max} tegn',
|
||||
'soc.msg.to': 'Melding til {name}', 'soc.msg.toShort': 'Til {name}', 'soc.msg.toAlliance': 'Melding til alliansen din',
|
||||
'soc.msg.unknown': 'Ingen operatør heter {name} i denne verdenen.',
|
||||
'soc.msg.reply': 'Skriv et svar...', 'soc.msg.older': 'Eldre meldinger',
|
||||
'soc.msg.thread.empty': 'Ingen meldinger med {name} ennå.',
|
||||
'soc.msg.allianceFeed': 'Alliansemelding',
|
||||
'soc.msg.broadcast': 'Send til alle', 'soc.msg.broadcastPlaceholder': 'Si det til alle i alliansen...',
|
||||
'soc.msg.broadcastHint': 'Alle som er i {tag} nå får denne meldingen.',
|
||||
'soc.msg.unreadOnly': 'Bare uleste', 'soc.msg.markAll': 'Merk alle som lest',
|
||||
'soc.msg.delete': 'Slett min kopi', 'soc.msg.deleted': 'Slettet. Den andre siden beholder sin kopi.',
|
||||
'soc.msg.empty.inbox': 'Ingenting i innboksen.', 'soc.msg.empty.sent': 'Du har ikke sendt noe.', 'soc.msg.empty.alliance': 'Ingen alliansemeldinger ennå.',
|
||||
'soc.block.go': 'Blokker', 'soc.block.unblock': 'Opphev blokkering', 'soc.block.blocked': '{name} er blokkert.', 'soc.block.unblocked': 'Blokkeringen av {name} er opphevet.',
|
||||
'soc.block.hint': 'Blokkerte operatører når ikke fram til deg og får ikke beskjed.', 'soc.block.none': 'Du har ikke blokkert noen.',
|
||||
'soc.block.since': 'blokkert {t}', 'soc.block.threadHint': 'Du har blokkert denne operatøren. Meldingene deres leveres ikke til deg.',
|
||||
|
||||
'soc.rank.tab.operators': 'Operatører', 'soc.rank.tab.alliances': 'Allianser', 'soc.rank.tab.battles': 'Kamper',
|
||||
'soc.rank.by': 'Kamprangering etter', 'soc.rank.by.attack': 'Angrep', 'soc.rank.by.defense': 'Forsvar', 'soc.rank.by.total': 'Totalt',
|
||||
'soc.rank.yours': 'Din plassering', 'soc.rank.of': 'av {n}', 'soc.rank.notShown': 'under den lastede lista',
|
||||
'soc.rank.pops': 'POP-er {n}', 'soc.rank.members': '{n} medlemmer', 'soc.rank.att': 'angrep {n}', 'soc.rank.def': 'forsvar {n}',
|
||||
'soc.rank.attack': 'Angrepspoeng', 'soc.rank.defense': 'Forsvarspoeng', 'soc.rank.viewAlliance': 'Vis allianse',
|
||||
'soc.rank.empty': 'Ingen er rangert ennå.', 'soc.rank.noBattles': 'Ingen har kamppoeng ennå.',
|
||||
'soc.rank.unavailable': 'Kamprangering registreres ikke ennå.',
|
||||
'soc.rank.noAlliance': 'Du er ikke i en allianse og er derfor ikke rangert her.',
|
||||
'soc.rank.noPoints': 'Du har ingen kamppoeng ennå.',
|
||||
},
|
||||
});
|
||||
}));
|
||||
174
public/js/ws.js
Normal file
174
public/js/ws.js
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
'use strict';
|
||||
/*
|
||||
* WebSocket push client (docs/PROTOCOL.md). Push is only a HINT: the game is fully playable with the socket down, so
|
||||
* every failure here is silent (no toasts, no thrown errors) and a slow REST poll runs as the fallback.
|
||||
*
|
||||
* connect to ws(s)://<same origin>/ws; first message {"type":"auth","token":"..."}; server answers {"type":"ready","serverTime"}
|
||||
* server pushes {"type":"town","townId"} {"type":"incoming","townId","arriveAt"} {"type":"notification","id","kind"}
|
||||
* {"type":"report","id"} {"type":"message","id"}
|
||||
* client pings {"type":"ping"} every ~25 s and expects {"type":"pong"} within a few seconds, else it reconnects
|
||||
* reconnect: exponential backoff from 1 s to 60 s with jitter, reset by a successful "ready"
|
||||
*
|
||||
* createSocketClient() is pure plumbing with everything injected (WebSocket constructor, timers, token), so
|
||||
* test/client-ws.test.js can drive it. The browser wiring (bind) feeds pushes into api.emit('push', msg) and refetches
|
||||
* the affected screens. The token is never logged and never put in the URL.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) module.exports = factory(require('./milcore.js'));
|
||||
else root.UpstreamWs = factory(root.UpstreamMil);
|
||||
}(typeof self !== 'undefined' ? self : this, function (Mil) {
|
||||
function createSocketClient(o) {
|
||||
const WS = o.WebSocket;
|
||||
const setT = o.setTimeout || setTimeout, clearT = o.clearTimeout || clearTimeout;
|
||||
const pingMs = o.pingMs || 25000, pongMs = o.pongTimeoutMs || 8000;
|
||||
const rnd = o.random || Math.random;
|
||||
let sock = null, state = 'idle', attempt = 0, wanted = false, hadReady = false;
|
||||
let retryTimer = null, pingTimer = null, pongTimer = null;
|
||||
|
||||
function setState(s) { if (s !== state) { state = s; if (o.onState) o.onState(s); } }
|
||||
function clearTimers() { clearT(retryTimer); clearT(pingTimer); clearT(pongTimer); retryTimer = pingTimer = pongTimer = null; }
|
||||
|
||||
function schedule(minWait) {
|
||||
if (!wanted || retryTimer) return;
|
||||
const wait = Math.max(minWait || 0, Mil.backoffMs(attempt, rnd()));
|
||||
attempt++;
|
||||
retryTimer = setT(() => { retryTimer = null; connect(); }, wait);
|
||||
}
|
||||
|
||||
function startPing() {
|
||||
clearT(pingTimer);
|
||||
pingTimer = setT(() => {
|
||||
if (!sock || state !== 'open') return;
|
||||
try { sock.send('{"type":"ping"}'); } catch (e) { drop(); return; }
|
||||
clearT(pongTimer);
|
||||
pongTimer = setT(() => drop(), pongMs); // no pong: the connection is dead although nobody told us
|
||||
startPing();
|
||||
}, pingMs);
|
||||
}
|
||||
|
||||
function drop(minWait) {
|
||||
const s = sock;
|
||||
sock = null;
|
||||
clearT(pingTimer); clearT(pongTimer); pingTimer = pongTimer = null;
|
||||
if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* already gone */ } }
|
||||
setState(wanted ? 'closed' : 'idle');
|
||||
schedule(minWait);
|
||||
}
|
||||
|
||||
// Close codes of docs/PROTOCOL.md: 4401 (token refused), 4400 and 1009 (a client bug) must not be retried in a loop;
|
||||
// 4429 (rate limited) waits at least 30 s; everything else is a plain reconnect.
|
||||
function onClosed(ev) {
|
||||
const code = ev && ev.code;
|
||||
if (code === 4401 || code === 4400 || code === 1009) {
|
||||
wanted = false; clearTimers(); sock = null; setState('idle');
|
||||
if (o.onFatal) o.onFatal(code);
|
||||
return;
|
||||
}
|
||||
drop(code === 4429 ? 30000 : 0);
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (!wanted || sock) return;
|
||||
const token = o.token();
|
||||
if (!token || !WS) return;
|
||||
let s;
|
||||
try { s = new WS(o.url()); } catch (e) { setState('closed'); schedule(); return; }
|
||||
sock = s;
|
||||
setState('connecting');
|
||||
s.onopen = () => { try { s.send(JSON.stringify({ type: 'auth', token })); } catch (e) { drop(); } };
|
||||
s.onmessage = (ev) => {
|
||||
let msg = null;
|
||||
try { msg = JSON.parse(ev.data); } catch (e) { return; }
|
||||
if (!msg || typeof msg.type !== 'string') return;
|
||||
if (msg.type === 'ready') { attempt = 0; const again = hadReady; hadReady = true; setState('open'); startPing(); if (o.onReady) o.onReady(msg, again); return; }
|
||||
if (msg.type === 'pong') { clearT(pongTimer); pongTimer = null; return; }
|
||||
if (o.onMessage) o.onMessage(msg);
|
||||
};
|
||||
s.onclose = (ev) => { if (sock === s) onClosed(ev); };
|
||||
s.onerror = () => { /* the close event follows; stay quiet */ };
|
||||
}
|
||||
|
||||
return {
|
||||
start() { if (wanted) return; wanted = true; attempt = 0; hadReady = false; connect(); },
|
||||
stop() { wanted = false; clearTimers(); const s = sock; sock = null; if (s) { try { s.onopen = s.onmessage = s.onclose = s.onerror = null; s.close(); } catch (e) { /* ignore */ } } setState('idle'); },
|
||||
// Try now (back online, tab visible again): skips the backoff wait.
|
||||
kick() { if (!wanted || sock) return; clearT(retryTimer); retryTimer = null; attempt = 0; connect(); },
|
||||
get state() { return state; },
|
||||
get open() { return state === 'open'; },
|
||||
get attempts() { return attempt; },
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ browser wiring
|
||||
function bind(App, UI, windowRef) {
|
||||
const api = App.api;
|
||||
const wsUrl = () => (windowRef.location.protocol === 'https:' ? 'wss://' : 'ws://') + windowRef.location.host + '/ws';
|
||||
const client = createSocketClient({
|
||||
WebSocket: windowRef.WebSocket,
|
||||
url: wsUrl,
|
||||
token: () => api.getToken(),
|
||||
onMessage: (msg) => api.emit('push', msg),
|
||||
// after every ready that follows a gap, refetch what is on screen (PROTOCOL.md): hints sent while we were away are lost
|
||||
onReady: (msg, again) => { poll(true); if (again && App.state.user) { App.refreshTown().catch(() => {}); App.refreshTowns().catch(() => {}); } },
|
||||
onFatal: () => { /* token refused or a client bug: stay quiet, the REST layer reports a dead token itself */ },
|
||||
});
|
||||
App.ws = client;
|
||||
|
||||
const timers = {};
|
||||
function debounce(key, fn, ms) { clearTimeout(timers[key]); timers[key] = setTimeout(fn, ms); }
|
||||
|
||||
// ---- what a push means for the screens (everything is a refetch over REST)
|
||||
api.on('push', (msg) => {
|
||||
if (!App.state.user) return;
|
||||
switch (msg.type) {
|
||||
case 'town':
|
||||
if (msg.townId === App.state.townId) debounce('town', () => App.refreshTown().catch(() => {}), 250);
|
||||
break;
|
||||
case 'incoming':
|
||||
debounce('moves', () => App.refreshMovements().catch(() => {}), 150);
|
||||
UI.toast(App.t('push.incoming'), 'error');
|
||||
break;
|
||||
case 'report':
|
||||
App.refreshReportsUnread().catch(() => {});
|
||||
debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list
|
||||
App.emit('report', msg);
|
||||
break;
|
||||
case 'notification':
|
||||
App.checkAlerts();
|
||||
if (msg.kind === 'town_gained' || msg.kind === 'town_lost') App.refreshTowns().catch(() => {});
|
||||
if (/^(train_done|research_done|movement_returned|reinforcements_sent_home|units_offline|units_decommissioned|transport_arrived|town_gained|town_lost)$/.test(msg.kind || '')) {
|
||||
debounce('town', () => App.refreshTown().catch(() => {}), 400);
|
||||
debounce('moves', () => App.refreshMovements().catch(() => {}), 400);
|
||||
}
|
||||
break;
|
||||
default: break; // 'message' etc. belong to other screens (api.on('push') there)
|
||||
}
|
||||
});
|
||||
|
||||
// ---- REST fallback: slow when the socket is open (it only backs the hints up), faster when it is down
|
||||
let lastPoll = 0;
|
||||
function poll(force) {
|
||||
if (!App.state.user || windowRef.document.hidden) return;
|
||||
const gap = client.open ? 180000 : 45000;
|
||||
if (!force && Date.now() - lastPoll < gap) return;
|
||||
lastPoll = Date.now();
|
||||
App.refreshMovements().catch(() => {});
|
||||
App.refreshReportsUnread().catch(() => {});
|
||||
App.refreshTowns().catch(() => {});
|
||||
App.checkAlerts();
|
||||
}
|
||||
setInterval(() => poll(false), 15000);
|
||||
|
||||
// ---- lifecycle
|
||||
App.on('session', (st) => {
|
||||
if (st && st.user) { client.start(); poll(true); } else client.stop();
|
||||
});
|
||||
api.on('unauthorized', () => client.stop());
|
||||
api.on('online', () => client.kick());
|
||||
windowRef.document.addEventListener('visibilitychange', () => { if (!windowRef.document.hidden && App.state.user) { client.kick(); poll(false); } });
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined' && window.App && window.UI) bind(window.App, window.UI, window);
|
||||
|
||||
return { createSocketClient, bind };
|
||||
}));
|
||||
|
|
@ -127,6 +127,7 @@ function dissolve(ctx, allianceId, reason) {
|
|||
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);
|
||||
require('./endgame').onAllianceDissolved(ctx, a.id); // its backbone landing sites are the incumbent's again
|
||||
db.run('DELETE FROM alliances WHERE id = ?', a.id);
|
||||
}
|
||||
|
||||
|
|
@ -172,9 +173,19 @@ const confederated = (db, opA, opB) => { const r = operatorRelation(db, opA, opB
|
|||
// 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'; };
|
||||
|
||||
// Every other operator for whom `confederated(db, operatorId, x)` holds: the rest of the own alliance plus the members of
|
||||
// alliances in a confederation with it. [] without an alliance.
|
||||
function confederatedOperators(db, operatorId) {
|
||||
const me = db.get('SELECT alliance_id FROM operators WHERE id = ?', operatorId);
|
||||
if (!me || !me.alliance_id) return [];
|
||||
const ids = [me.alliance_id];
|
||||
for (const r of db.all("SELECT a_id, b_id FROM alliance_relations WHERE state = 'confed' AND (a_id = ? OR b_id = ?)", me.alliance_id, me.alliance_id)) ids.push(r.a_id === me.alliance_id ? r.b_id : r.a_id);
|
||||
return db.all('SELECT id FROM operators WHERE alliance_id IN (' + ids.map(() => '?').join(',') + ') AND id != ? ORDER BY id', ...ids, operatorId).map((r) => r.id);
|
||||
}
|
||||
|
||||
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,
|
||||
relationBetween, operatorRelation, atWar, confederated, pactPartners, confederatedOperators,
|
||||
};
|
||||
|
|
|
|||
40
server/commands/backboneBuild.js
Normal file
40
server/commands/backboneBuild.js
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /backbone/:id/build: start the next Backbone node level on a landing site your alliance holds. The level's cost comes out
|
||||
* of the site's stockpile (shipped in by the holders, see backboneShip) at once; one level at a time; the level lands when the
|
||||
* `backboneDone` event runs. Needs the `backboneBuild` permission.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { loadWorld } = require('../state');
|
||||
const A = require('../alliances');
|
||||
const E = require('../endgame');
|
||||
const ctxOf = require('../military/ctx');
|
||||
|
||||
// The site, the caller's operator in its world, and proof that the caller's alliance holds it. Shared with backboneShip.
|
||||
function holderContext(db, userId, siteId, now) {
|
||||
const site = E.siteRow(db, siteId);
|
||||
if (!site) throw new GameError('not_found', { what: 'landing site' });
|
||||
const world = loadWorld(db, site.world_id);
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, site.world_id);
|
||||
if (!op) throw new GameError('not_found', { what: 'landing site' });
|
||||
if (!E.isOpen(world, now)) throw new GameError('backbone_closed', { opensAtDay: require('../../public/js/data.js').ENDGAME.openDay });
|
||||
const m = A.membership(db, op.id);
|
||||
if (!site.holder_alliance_id || !m || m.alliance_id !== site.holder_alliance_id) throw new GameError('forbidden', { need: 'holder' });
|
||||
return { site, world, op, member: m };
|
||||
}
|
||||
|
||||
module.exports = function backboneBuild(ctx0, { userId, siteId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const { site, world, op, member } = holderContext(db, userId, siteId, now);
|
||||
if (!R.allianceCan(member.role, 'backboneBuild')) throw new GameError('forbidden', { need: 'backboneBuild', role: member.role });
|
||||
const plan = R.backbonePlan({ level: site.level, build: site.build_to ? { to: site.build_to } : null, pool: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } }, world.speed);
|
||||
if (!plan.ok) throw new GameError(plan.code, { siteId: site.id, toLevel: plan.toLevel, cost: plan.cost, have: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } });
|
||||
const dueAt = now + plan.durationMs;
|
||||
const ev = ctx.enqueue({ worldId: site.world_id, dueAt, type: 'backboneDone', payload: { siteId: site.id, toLevel: plan.toLevel, by: op.id } });
|
||||
db.run(`UPDATE landing_sites SET fiber = fiber - ?, hardware = hardware - ?, capital = capital - ?, build_to = ?, build_event_id = ?, build_started_at = ?, build_due_at = ?, build_cost = ? WHERE id = ?`,
|
||||
plan.cost.fiber, plan.cost.hardware, plan.cost.capital, plan.toLevel, ev, now, dueAt, JSON.stringify(plan.cost), site.id);
|
||||
return { siteId: site.id, eventId: ev, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost };
|
||||
};
|
||||
module.exports.holderContext = holderContext;
|
||||
23
server/commands/backboneShip.js
Normal file
23
server/commands/backboneShip.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /backbone/:id/ship {fromTownId, cargo}: send resources from one of your POPs to a landing site your alliance holds, to
|
||||
* feed its stockpile. A normal transport (same links, 500 per link, 12 tiles/h) whose target is the site's tile; on arrival it is
|
||||
* added to the stockpile if the sender's alliance still holds the site, otherwise it rides home.
|
||||
*/
|
||||
const { GameError } = require('../errors');
|
||||
const { settle } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
const { launchTransport } = require('./sendTransport');
|
||||
const { holderContext } = require('./backboneBuild');
|
||||
const ctxOf = require('../military/ctx');
|
||||
|
||||
module.exports = function backboneShip(ctx0, { userId, siteId, fromTownId, cargo }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const { site } = holderContext(db, userId, siteId, now);
|
||||
const from = ownedTown(db, userId, fromTownId);
|
||||
if (from.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' });
|
||||
settle(db, from, now);
|
||||
const mv = launchTransport(ctx, from, { x: site.x, y: site.y }, cargo || {}, { siteId: site.id });
|
||||
return { movementId: mv.id, type: 'transport', siteId: site.id, fromTownId: from.id, toTownId: null, to: { x: site.x, y: site.y }, cargo: mv.cargo, departAt: mv.departAt, arriveAt: mv.arriveAt };
|
||||
};
|
||||
|
|
@ -40,19 +40,35 @@ const handlers = {
|
|||
messageDelete: require('./messageDelete'),
|
||||
messageBlock: require('./messageBlock').messageBlock,
|
||||
messageUnblock: require('./messageBlock').messageUnblock,
|
||||
// trade, end game, shared reports
|
||||
reportShare: require('./reportShare').reportShare,
|
||||
reportUnshare: require('./reportShare').reportUnshare,
|
||||
tradeOffer: require('./tradeOffer'),
|
||||
tradeCancel: require('./tradeCancel'),
|
||||
tradeAccept: require('./tradeAccept'),
|
||||
backboneBuild: require('./backboneBuild'),
|
||||
backboneShip: require('./backboneShip'),
|
||||
};
|
||||
|
||||
function createCommands({ db, clock, scheduler }) {
|
||||
// hooks.onCommand(name, args, out): optional, called after a command committed (stage 6 push). Never throws into the caller.
|
||||
const hooks = { onCommand: null };
|
||||
function run(name, args) {
|
||||
const fn = handlers[name];
|
||||
if (!fn) throw new Error('unknown command ' + name);
|
||||
scheduler.runDue();
|
||||
require('../endgame').guard(db, name, args); // an ended world refuses every command except reading state and chatting
|
||||
const now = clock.now();
|
||||
const out = db.tx(() => fn({ db, clock, now, scheduler }, args));
|
||||
const mark = scheduler.outboxMark();
|
||||
let out;
|
||||
try { out = db.tx(() => fn({ db, clock, now, scheduler }, args)); }
|
||||
catch (err) { scheduler.outboxRollback(mark); throw err; }
|
||||
scheduler.flushOutbox(); // notifications written by the command go out now that it is committed
|
||||
if (hooks.onCommand) { try { hooks.onCommand(name, args, out); } catch (e) { if (scheduler.log) scheduler.log('onCommand hook failed: ' + e.message); } }
|
||||
scheduler.arm();
|
||||
return out;
|
||||
}
|
||||
return { run, handlers };
|
||||
return { run, handlers, hooks };
|
||||
}
|
||||
|
||||
module.exports = { createCommands };
|
||||
|
|
|
|||
51
server/commands/reportShare.js
Normal file
51
server/commands/reportShare.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The alliance's shared report folder. Two commands in one file (registered separately in commands/index.js):
|
||||
* reportShare { userId, reportId } put one of YOUR reports into your alliance's folder (needs `shareReport`)
|
||||
* reportUnshare { userId, reportId } take it out again: whoever shared it, or `unshareReport` (leader, officer)
|
||||
* The alliance is the caller's alliance in the report's world. Sharing an already shared report changes nothing
|
||||
* ({ changed: false }). A shared report lives at least reportRetentionMs from the moment it was shared (the expiry is pushed
|
||||
* out; it is one row for everybody, so the participants keep it that long too) and is deleted with the report.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const { GameError } = require('../errors');
|
||||
const A = require('../alliances');
|
||||
const { ensureCleanup } = require('../military/reports');
|
||||
|
||||
function context(db, userId, reportId) {
|
||||
const rep = db.get(`SELECT r.id, r.world_id, r.expires_at FROM reports r JOIN report_recipients rr ON rr.report_id = r.id AND rr.user_id = ? WHERE r.id = ?`, userId, reportId);
|
||||
if (!rep) throw new GameError('not_found', { what: 'report' }); // not yours: never reveal it exists
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, rep.world_id);
|
||||
if (!op) throw new GameError('not_found', { what: 'report' });
|
||||
const m = A.membership(db, op.id);
|
||||
if (!m) throw new GameError('not_in_alliance');
|
||||
return { rep, op, member: m };
|
||||
}
|
||||
|
||||
function reportShare(ctx, { userId, reportId }) {
|
||||
const { db, now } = ctx;
|
||||
const { rep, op, member } = context(db, userId, reportId);
|
||||
if (!R.allianceCan(member.role, 'shareReport')) throw new GameError('forbidden', { need: 'shareReport', role: member.role });
|
||||
const r = db.run('INSERT OR IGNORE INTO report_shares (report_id, alliance_id, shared_by, created_at) VALUES (?, ?, ?, ?)', rep.id, member.alliance_id, op.id, now);
|
||||
if (!r.changes) return { changed: false, reportId: rep.id, allianceId: member.alliance_id };
|
||||
const until = now + D.MILITARY.reportRetentionMs;
|
||||
if (rep.expires_at < until) db.run('UPDATE reports SET expires_at = ? WHERE id = ?', until, rep.id);
|
||||
ensureCleanup(ctx, rep.world_id, now);
|
||||
return { changed: true, reportId: rep.id, allianceId: member.alliance_id };
|
||||
}
|
||||
|
||||
function reportUnshare(ctx, { userId, reportId }) {
|
||||
const { db } = ctx;
|
||||
// the report may no longer list the caller as a recipient (it is only theirs through the alliance): look the share up directly
|
||||
const share = db.get(`SELECT s.*, r.world_id FROM report_shares s JOIN reports r ON r.id = s.report_id WHERE s.report_id = ?
|
||||
AND s.alliance_id IN (SELECT m.alliance_id FROM alliance_members m JOIN operators o ON o.id = m.operator_id WHERE o.user_id = ?)`, reportId, userId);
|
||||
if (!share) throw new GameError('not_found', { what: 'shared report' });
|
||||
const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, share.world_id);
|
||||
const member = A.membership(db, op.id);
|
||||
if (op.id !== share.shared_by && !R.allianceCan(member.role, 'unshareReport')) throw new GameError('forbidden', { need: 'unshareReport', role: member.role });
|
||||
db.run('DELETE FROM report_shares WHERE report_id = ? AND alliance_id = ?', share.report_id, share.alliance_id);
|
||||
return { changed: true, reportId: share.report_id, allianceId: share.alliance_id };
|
||||
}
|
||||
|
||||
module.exports = { reportShare, reportUnshare };
|
||||
|
|
@ -18,7 +18,7 @@ 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) {
|
||||
function resolveTarget(db, world, args, now) {
|
||||
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);
|
||||
|
|
@ -30,7 +30,7 @@ function resolveTarget(db, world, args) {
|
|||
} 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);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'void') throw new GameError('invalid_target', { reason: 'outside_map' });
|
||||
return { town, x, y, tile };
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
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);
|
||||
const tgt = resolveTarget(db, world, args, now);
|
||||
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);
|
||||
|
|
@ -81,6 +81,10 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
}
|
||||
} else if (tgt.tile.type === 'incumbent') {
|
||||
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'incumbent_scan_or_attack_only' });
|
||||
} else if (tgt.tile.type === 'backbone') {
|
||||
require('../endgame').checkLandingTarget(db, world, op, tgt, type, now, ctx); // scan or attack only, alliance members, no pact partners
|
||||
} else if (R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y)) {
|
||||
throw new GameError('backbone_closed', { opensAtDay: D.ENDGAME.openDay }); // the landing site is not there yet
|
||||
} else {
|
||||
throw new GameError('invalid_target', { reason: 'nothing_there' });
|
||||
}
|
||||
|
|
@ -98,7 +102,7 @@ module.exports = function sendMovement(ctx0, args) {
|
|||
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) });
|
||||
const chk2 = R.settleCheck({ tileType: tgt.tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, tgt.x, tgt.y), 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);
|
||||
}
|
||||
|
|
|
|||
54
server/commands/tradeAccept.js
Normal file
54
server/commands/tradeAccept.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /trade/offers/:id/accept {townId}: take an open offer with one of your POPs. In ONE transaction:
|
||||
* - the payment (the wanted resource) leaves the acceptor's POP as a transport to the poster's POP (needs a free link there,
|
||||
* the usual transport rules: capacity, resources),
|
||||
* - the poster's escrow leaves as a transport to the acceptor's POP (on the link the open offer held in reserve),
|
||||
* - the offer becomes `accepted`; it is `completed` when both transports have been delivered (see server/trade.js).
|
||||
* Any failure rolls everything back. Not your own offer; the acceptor's POP needs an Internet exchange and must be in range
|
||||
* (the offer's max distance and the exchange's reach).
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const { GameError } = require('../errors');
|
||||
const { settle, loadWorld } = require('../state');
|
||||
const { ownedTown } = require('./build');
|
||||
const { launchTransport } = require('./sendTransport');
|
||||
const ctxOf = require('../military/ctx');
|
||||
const M = require('../military/movements');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeAccept(ctx0, { userId, offerId, townId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const o = T.getOffer(db, offerId);
|
||||
const mine = ownedTown(db, userId, townId);
|
||||
if (!o || o.world_id !== mine.worldId) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
|
||||
if (mine.ownerId === o.operator_id) throw new GameError('own_offer');
|
||||
const poster = db.get('SELECT * FROM towns WHERE id = ?', o.town_id);
|
||||
if (!poster || poster.owner_id !== o.operator_id) throw new GameError('offer_closed', { status: 'void' });
|
||||
const level = R.transportLinks(mine);
|
||||
const dist = R.distance(mine.x, mine.y, poster.x, poster.y);
|
||||
if (level < 1) throw new GameError('no_transport_link', { links: 0, active: 0 });
|
||||
if (!R.tradeInRange(dist, o.max_distance, level)) throw new GameError('trade_out_of_range', { distance: dist, maxDistance: o.max_distance, reach: R.tradeReach(level) });
|
||||
settle(db, mine, now);
|
||||
|
||||
// acceptor -> poster: the wanted resource (validates links, capacity and resources, deducts, inserts the movement)
|
||||
const pay = launchTransport(ctx, mine, poster, { [o.want_res]: o.want_amount }, { tradeId: o.id, role: 'payment' });
|
||||
// poster -> acceptor: the escrow
|
||||
const world = loadWorld(db, o.world_id);
|
||||
const goods = M.insertMovement(ctx, {
|
||||
worldId: o.world_id, ownerId: o.operator_id, type: 'transport', fromTownId: poster.id, toTownId: mine.id,
|
||||
from: { x: poster.x, y: poster.y }, to: { x: mine.x, y: mine.y }, units: {}, cargo: { [o.give_res]: o.give_amount },
|
||||
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: { tradeId: o.id, role: 'goods' },
|
||||
});
|
||||
db.run("UPDATE trade_offers SET status = 'accepted', accepted_by_operator = ?, accepted_town_id = ?, accepted_at = ?, goods_movement_id = ?, payment_movement_id = ? WHERE id = ?",
|
||||
mine.ownerId, mine.id, now, goods.id, pay.id, o.id);
|
||||
if (o.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, o.expire_event_id);
|
||||
const posterUser = T.userOfOperator(db, o.operator_id);
|
||||
if (posterUser) ctx.notify(posterUser, o.world_id, 'trade_accepted', { offerId: o.id, townId: poster.id, byTownId: mine.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } });
|
||||
return {
|
||||
offerId: o.id, status: 'accepted', goodsMovementId: goods.id, paymentMovementId: pay.id, distance: dist,
|
||||
arriveAt: goods.arriveAt, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
|
||||
};
|
||||
};
|
||||
15
server/commands/tradeCancel.js
Normal file
15
server/commands/tradeCancel.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
'use strict';
|
||||
/* DELETE /trade/offers/:id: take your open offer back; the escrow returns to the POP. */
|
||||
const { GameError } = require('../errors');
|
||||
const ctxOf = require('../military/ctx');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeCancel(ctx0, { userId, offerId }) {
|
||||
const ctx = ctxOf(ctx0);
|
||||
const { db, now } = ctx;
|
||||
const o = T.getOffer(db, offerId);
|
||||
if (!o || T.userOfOperator(db, o.operator_id) !== userId) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
|
||||
T.closeOffer(ctx, o, 'cancelled', now);
|
||||
return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: o.give_amount } };
|
||||
};
|
||||
33
server/commands/tradeOffer.js
Normal file
33
server/commands/tradeOffer.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
'use strict';
|
||||
/*
|
||||
* POST /trade/offers: "give X of A for Y of B, max distance Z" from one of your POPs with an Internet exchange. The offered
|
||||
* amount leaves the POP now (escrow), one transport link stays reserved for it, and the offer expires after TRADE.ttlHours
|
||||
* (divided by world speed). Both amounts must fit one transport link and differ by at most 1:2.
|
||||
*/
|
||||
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');
|
||||
const M = require('../military/movements');
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeOffer(ctx, { userId, townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance }) {
|
||||
const { db, now, scheduler } = ctx;
|
||||
const town = ownedTown(db, userId, townId);
|
||||
const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance });
|
||||
if (!terms.ok) throw new GameError(terms.code, terms);
|
||||
const links = R.transportLinks(town);
|
||||
const inUse = M.activeLinks(db, town.id);
|
||||
if (links < 1 || inUse >= links) throw new GameError('no_transport_link', { links, active: inUse });
|
||||
settle(db, town, now);
|
||||
if (R.resourcesAt(town, now).amounts[giveRes] + 1e-6 < giveAmount) throw new GameError('not_enough_resources', { resource: giveRes, want: giveAmount });
|
||||
spend(db, town, { [giveRes]: giveAmount });
|
||||
const expiresAt = now + T.expiryMs(town.speed);
|
||||
const id = Number(db.run(`INSERT INTO trade_offers (world_id, town_id, operator_id, give_res, give_amount, want_res, want_amount, max_distance, status, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)`, town.worldId, town.id, town.ownerId, giveRes, giveAmount, wantRes, wantAmount, maxDistance, now, expiresAt).lastInsertRowid);
|
||||
const ev = scheduler.enqueue({ worldId: town.worldId, dueAt: expiresAt, type: 'tradeExpire', townId: town.id, payload: { offerId: id } });
|
||||
db.run('UPDATE trade_offers SET expire_event_id = ? WHERE id = ?', ev, id);
|
||||
const o = T.getOffer(db, id);
|
||||
return { offer: T.offerView(db, o, new Map([[town.id, town]])) };
|
||||
};
|
||||
192
server/endgame.js
Normal file
192
server/endgame.js
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
'use strict';
|
||||
/*
|
||||
* End game: backbone landing sites, the Backbone node race, the winner, the end of the world.
|
||||
*
|
||||
* Representation (DECISIONS.md E1): a landing site is NOT a POP. It is a row of `landing_sites` (position from the world seed,
|
||||
* holder alliance, node level, stockpile, build in progress). The tile reads 'backbone' (rules.tileAt with the world age) from
|
||||
* D.ENDGAME.openDay on; before that it is plain land that nobody may settle or spawn on. A site is defended by a static value
|
||||
* only (rules.backboneDefence: incumbent defence x defenceMult, + a bonus per node level), so there are no reinforcements at a
|
||||
* site. Holders keep the level when the site is taken; the stockpile and a running build stay with the site as well.
|
||||
*
|
||||
* Time: world age is in world days (real days x speed). Everything here takes `now` (ms) from the caller.
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const { loadWorld } = require('./state');
|
||||
|
||||
const DAY = 24 * D.HOUR_MS;
|
||||
const E = D.ENDGAME;
|
||||
|
||||
const ageDays = (world, now) => R.worldAgeDays(world.start_at, now, world.speed);
|
||||
const phase = (world, now) => R.worldPhase(world.status, ageDays(world, now));
|
||||
const isOpen = (world, now) => ageDays(world, now) >= E.openDay;
|
||||
|
||||
// ---------------------------------------------------------------- site rows
|
||||
|
||||
// Create the site rows (idempotent). Writers call this; reads use `siteStates`, which never writes. The first call that really
|
||||
// creates them (whatever touches a site first once the world is old enough) tells every operator, when it was given a `ctx`
|
||||
// with notify. There is no timer event for this on purpose: nothing is pending in a quiet world.
|
||||
function ensureSites(db, world, now, ctx) {
|
||||
if (!isOpen(world, now)) return [];
|
||||
let created = 0;
|
||||
for (const s of R.backboneSites(world.seed, world.map_radius)) created += Number(db.run('INSERT OR IGNORE INTO landing_sites (world_id, idx, x, y) VALUES (?, ?, ?, ?)', world.id, s.index, s.x, s.y).changes);
|
||||
const rows = db.all('SELECT * FROM landing_sites WHERE world_id = ? ORDER BY idx', world.id);
|
||||
if (created && ctx && ctx.notify) notifyWorld(ctx, world.id, 'backbone_open', { sites: rows.map((r) => ({ siteId: r.id, index: r.idx, x: r.x, y: r.y })) });
|
||||
return rows;
|
||||
}
|
||||
const siteRow = (db, id) => db.get('SELECT * FROM landing_sites WHERE id = ?', id) || null;
|
||||
const siteAt = (db, worldId, idx) => db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', worldId, idx) || null;
|
||||
|
||||
// Every site of the world as { site: {index,x,y}, row: landing_sites row | null } (no row = never touched: still the incumbent's).
|
||||
function siteStates(db, world, now) {
|
||||
if (!isOpen(world, now)) return [];
|
||||
const rows = new Map(db.all('SELECT * FROM landing_sites WHERE world_id = ?', world.id).map((r) => [r.idx, r]));
|
||||
return R.backboneSites(world.seed, world.map_radius).map((s) => ({ site: s, row: rows.get(s.index) || null }));
|
||||
}
|
||||
|
||||
function allianceInfo(db, id) {
|
||||
if (!id) return null;
|
||||
const a = db.get('SELECT id, tag, name FROM alliances WHERE id = ?', id);
|
||||
return a ? { allianceId: a.id, tag: a.tag, name: a.name } : null;
|
||||
}
|
||||
const opBrief = (db, id) => { const o = id ? db.get('SELECT id, name FROM operators WHERE id = ?', id) : null; return o ? { operatorId: o.id, name: o.name } : null; };
|
||||
|
||||
// Public view of one site. `row` may be null (untouched).
|
||||
function siteView(db, world, s, row) {
|
||||
const level = row ? row.level : 0;
|
||||
const pool = { fiber: row ? row.fiber : 0, hardware: row ? row.hardware : 0, capital: row ? row.capital : 0 };
|
||||
const build = row && row.build_to ? { toLevel: row.build_to, startedAt: row.build_started_at, dueAt: row.build_due_at } : null;
|
||||
return {
|
||||
id: row ? row.id : null, index: s.index, x: s.x, y: s.y,
|
||||
holder: row ? allianceInfo(db, row.holder_alliance_id) : null,
|
||||
takenBy: row ? opBrief(db, row.holder_operator_id) : null, takenAt: row ? row.taken_at : null,
|
||||
level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build,
|
||||
next: level < E.maxLevel ? { toLevel: level + 1, cost: R.backboneCost(level + 1), durationMs: R.backboneTimeMs(level + 1, world.speed) } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function winnerView(w) {
|
||||
return w.winner_alliance_id || w.winner_name ? { allianceId: w.winner_alliance_id, name: w.winner_name, tag: w.winner_tag, siteId: w.winner_site_id, wonAt: w.won_at } : null;
|
||||
}
|
||||
|
||||
// GET /worlds/:id/status
|
||||
function statusView(db, world, now) {
|
||||
const age = ageDays(world, now);
|
||||
return {
|
||||
worldId: world.id, name: world.name, speed: world.speed, status: world.status, phase: phase(world, now),
|
||||
ageDays: age, openDay: E.openDay, opensAt: world.start_at + Math.round(E.openDay * DAY / world.speed),
|
||||
sites: siteStates(db, world, now).map(({ site, row }) => siteView(db, world, site, row)),
|
||||
winner: winnerView(world), endsAt: world.status === 'ended' ? world.end_at : (world.won_at ? world.end_at : null), endedAt: world.status === 'ended' ? world.end_at : null,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the ended-world gate
|
||||
|
||||
// Commands that stay possible after the world ended (reading state, chatting): everything else is refused with `world_ended`.
|
||||
const WHEN_ENDED = new Set(['markReportRead', 'messageSend', 'messageRead', 'messageDelete', 'messageBlock', 'messageUnblock']);
|
||||
const PROBES = [
|
||||
['townId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['fromTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'], ['hostTownId', 'SELECT world_id AS w FROM towns WHERE id = ?'],
|
||||
['allianceId', 'SELECT world_id AS w FROM alliances WHERE id = ?'], ['movementId', 'SELECT world_id AS w FROM movements WHERE id = ?'],
|
||||
['inviteId', 'SELECT a.world_id AS w FROM alliance_invites i JOIN alliances a ON a.id = i.alliance_id WHERE i.id = ?'],
|
||||
['proposalId', 'SELECT world_id AS w FROM alliance_proposals WHERE id = ?'], ['offerId', 'SELECT world_id AS w FROM trade_offers WHERE id = ?'],
|
||||
['siteId', 'SELECT world_id AS w FROM landing_sites WHERE id = ?'], ['reportId', 'SELECT world_id AS w FROM reports WHERE id = ?'],
|
||||
];
|
||||
// The world a command acts in: an explicit worldId, else the world of whatever it points at, else the caller's default operator's.
|
||||
function worldOfCommand(db, args) {
|
||||
if (args.worldId) return args.worldId;
|
||||
for (const [key, sql] of PROBES) {
|
||||
if (args[key]) { const r = db.get(sql, args[key]); if (r) return r.w; }
|
||||
}
|
||||
if (args.userId) { const r = db.get('SELECT world_id AS w FROM operators WHERE user_id = ? ORDER BY id LIMIT 1', args.userId); if (r) return r.w; }
|
||||
return null;
|
||||
}
|
||||
// Called by commands.run before every command. Throws world_ended when the world of the command has ended.
|
||||
function guard(db, name, args) {
|
||||
if (WHEN_ENDED.has(name) || !args) return;
|
||||
const w = worldOfCommand(db, args);
|
||||
if (!w) return;
|
||||
const row = db.get('SELECT status FROM worlds WHERE id = ?', w);
|
||||
if (row && row.status === 'ended') throw new GameError('world_ended', { worldId: w });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- notifications
|
||||
|
||||
function notifyAlliance(ctx, allianceId, type, payload) {
|
||||
for (const m of ctx.db.all('SELECT o.user_id AS uid, o.world_id AS wid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', allianceId)) ctx.notify(m.uid, m.wid, type, payload);
|
||||
}
|
||||
function notifyWorld(ctx, worldId, type, payload) {
|
||||
for (const o of ctx.db.all('SELECT user_id FROM operators WHERE world_id = ?', worldId)) ctx.notify(o.user_id, worldId, type, payload);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- taking a site, winning, the end
|
||||
|
||||
// Sending checks (sendMovement): landing sites can be scanned and attacked, nothing else. Attacking needs an alliance; you cannot
|
||||
// attack a site your own alliance or a pact partner holds.
|
||||
function checkLandingTarget(db, world, op, tgt, type, now, ctx) {
|
||||
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'landing_scan_or_attack_only' });
|
||||
if (type !== 'attack') return;
|
||||
if (!op.alliance_id) throw new GameError('invalid_target', { reason: 'no_alliance' });
|
||||
const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site);
|
||||
denyIfFriendly(db, op, row);
|
||||
}
|
||||
function denyIfFriendly(db, op, row) {
|
||||
if (!row || !row.holder_alliance_id) return;
|
||||
if (row.holder_alliance_id === op.alliance_id) throw new GameError('invalid_target', { reason: 'own_site' });
|
||||
const rel = require('./alliances').relationBetween(db, op.alliance_id, row.holder_alliance_id);
|
||||
if (rel === 'nap' || rel === 'confed') throw new GameError('invalid_target', { reason: 'pact' });
|
||||
}
|
||||
|
||||
// The site changes hands: the attacking operator's alliance holds it now. Level, stockpile and a running build stay.
|
||||
function transferSite(ctx, site, attackerOp, now) {
|
||||
const { db } = ctx;
|
||||
const old = site.holder_alliance_id;
|
||||
db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, taken_at = ? WHERE id = ?', attackerOp.alliance_id, attackerOp.id, now, site.id);
|
||||
const body = { siteId: site.id, index: site.idx, x: site.x, y: site.y, level: site.level, by: allianceInfo(db, attackerOp.alliance_id), from: allianceInfo(db, old) };
|
||||
if (old) notifyAlliance(ctx, old, 'backbone_lost', body);
|
||||
notifyAlliance(ctx, attackerOp.alliance_id, 'backbone_taken', body);
|
||||
maybeWin(ctx, siteRow(db, site.id), now); // a finished node taken while nobody held it completes for the new holder
|
||||
}
|
||||
|
||||
// The holder of a node at maxLevel wins, once per world. Called when a level completes and when such a site changes hands.
|
||||
function maybeWin(ctx, site, now) {
|
||||
const { db } = ctx;
|
||||
if (!site || site.level < E.maxLevel || !site.holder_alliance_id) return false;
|
||||
const world = loadWorld(db, site.world_id);
|
||||
if (!world || world.status === 'ended' || world.winner_alliance_id) return false;
|
||||
const a = allianceInfo(db, site.holder_alliance_id);
|
||||
const endsAt = now + Math.round(E.graceDays * DAY / world.speed);
|
||||
db.run('UPDATE worlds SET winner_alliance_id = ?, winner_name = ?, winner_tag = ?, winner_site_id = ?, won_at = ?, end_at = ? WHERE id = ?', a.allianceId, a.name, a.tag, site.id, now, endsAt, world.id);
|
||||
ctx.enqueue({ worldId: world.id, dueAt: endsAt, type: 'worldEnd', payload: { reason: 'backbone', siteId: site.id } });
|
||||
notifyWorld(ctx, world.id, 'backbone_won', { allianceId: a.allianceId, name: a.name, tag: a.tag, siteId: site.id, endsAt });
|
||||
return true;
|
||||
}
|
||||
|
||||
// An alliance is gone: its sites are the incumbent's again (the level stays with the site).
|
||||
function onAllianceDissolved(ctx, allianceId) {
|
||||
ctx.db.run('UPDATE landing_sites SET holder_alliance_id = NULL WHERE holder_alliance_id = ?', allianceId);
|
||||
}
|
||||
|
||||
// A shipment of resources reached a landing site (called from military/arrivals.arriveTransport). Only the holder alliance's
|
||||
// members may feed the stockpile: if the site changed hands on the way the cargo rides home. -> true when it was stored
|
||||
function deliverShipment(ctx, mv, now) {
|
||||
const { db } = ctx;
|
||||
const site = siteRow(db, mv.extra.siteId);
|
||||
const sender = db.get('SELECT * FROM operators WHERE id = ?', mv.ownerId);
|
||||
const uid = sender ? sender.user_id : null;
|
||||
if (!site || !site.holder_alliance_id || !sender || sender.alliance_id !== site.holder_alliance_id) {
|
||||
if (uid) ctx.notify(uid, mv.worldId, 'backbone_ship_bounced', { movementId: mv.id, siteId: mv.extra.siteId, cargo: mv.cargo });
|
||||
return false;
|
||||
}
|
||||
const c = { fiber: mv.cargo.fiber || 0, hardware: mv.cargo.hardware || 0, capital: mv.cargo.capital || 0 };
|
||||
db.run('UPDATE landing_sites SET fiber = fiber + ?, hardware = hardware + ?, capital = capital + ? WHERE id = ?', c.fiber, c.hardware, c.capital, site.id);
|
||||
db.run(`INSERT INTO landing_contributions (site_id, operator_id, fiber, hardware, capital) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (site_id, operator_id) DO UPDATE SET fiber = fiber + excluded.fiber, hardware = hardware + excluded.hardware, capital = capital + excluded.capital`, site.id, sender.id, c.fiber, c.hardware, c.capital);
|
||||
if (uid) ctx.notify(uid, mv.worldId, 'backbone_delivered', { movementId: mv.id, siteId: site.id, cargo: c });
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DAY, ageDays, phase, isOpen, ensureSites, siteRow, siteAt, siteStates, siteView, allianceInfo, opBrief, winnerView, statusView,
|
||||
guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment,
|
||||
};
|
||||
50
server/endgameQueries.js
Normal file
50
server/endgameQueries.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
'use strict';
|
||||
/* Read models of the end game: world status (the race), the final results, one landing site. Reads catch the event queue up first
|
||||
* and never write (an untouched site has no row yet and shows as the incumbent's, level 0). */
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const { loadWorld } = require('./state');
|
||||
const A = require('./alliances');
|
||||
const E = require('./endgame');
|
||||
|
||||
function createEndgameQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
const world = (id) => { const w = loadWorld(db, id); if (!w) throw new GameError('not_found', { what: 'world' }); return w; };
|
||||
|
||||
function status(userId, worldId) {
|
||||
const now = fresh();
|
||||
return Object.assign({ serverTime: now }, E.statusView(db, world(worldId), now));
|
||||
}
|
||||
|
||||
function results(userId, worldId) {
|
||||
const now = fresh();
|
||||
const w = world(worldId);
|
||||
const row = db.get('SELECT created_at, data FROM world_rankings WHERE world_id = ?', w.id);
|
||||
if (!row) return { serverTime: now, available: false, status: w.status, winner: E.winnerView(w), endsAt: w.won_at ? w.end_at : null, results: null };
|
||||
return { serverTime: now, available: true, status: w.status, winner: E.winnerView(w), endsAt: w.end_at, results: JSON.parse(row.data) };
|
||||
}
|
||||
|
||||
// One site. Holders (members of the holding alliance) also get the contribution ledger and what they may do.
|
||||
function site(userId, siteId) {
|
||||
const now = fresh();
|
||||
const row = E.siteRow(db, siteId);
|
||||
const w = row ? world(row.world_id) : null;
|
||||
const op = w ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, w.id) : null;
|
||||
if (!row || !op || !E.isOpen(w, now)) throw new GameError('not_found', { what: 'landing site' });
|
||||
const s = R.backboneSites(w.seed, w.map_radius).find((x) => x.index === row.idx);
|
||||
const m = A.membership(db, op.id);
|
||||
const holder = !!(m && row.holder_alliance_id && m.alliance_id === row.holder_alliance_id);
|
||||
const out = { serverTime: now, site: E.siteView(db, w, s, row), you: { holder, canBuild: holder && R.allianceCan(m.role, 'backboneBuild'), canShip: holder, canAttack: !!op.alliance_id && !(holder) } };
|
||||
if (holder) {
|
||||
out.contributions = db.all(`SELECT c.operator_id AS oid, o.name AS name, c.fiber, c.hardware, c.capital FROM landing_contributions c JOIN operators o ON o.id = c.operator_id
|
||||
WHERE c.site_id = ? ORDER BY (c.fiber + c.hardware + c.capital) DESC, c.operator_id`, row.id)
|
||||
.map((c) => ({ operatorId: c.oid, name: c.name, fiber: c.fiber, hardware: c.hardware, capital: c.capital }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
return { status, results, site };
|
||||
}
|
||||
|
||||
module.exports = { createEndgameQueries };
|
||||
|
|
@ -56,6 +56,13 @@ const CODES = {
|
|||
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).'],
|
||||
// trade and end game
|
||||
trade_ratio: [409, 'The offered and the wanted amount may differ by at most 1:2.'],
|
||||
offer_closed: [409, 'That offer is not open any more.'],
|
||||
own_offer: [409, 'You cannot accept your own offer.'],
|
||||
trade_out_of_range: [409, 'That POP is too far from the offer (its max distance or your Internet exchange reach).'],
|
||||
world_ended: [409, 'This world has ended: it can still be read, but nothing can be changed.'],
|
||||
backbone_closed: [409, 'The backbone landing sites have not appeared yet.'],
|
||||
};
|
||||
|
||||
class GameError extends Error {
|
||||
|
|
|
|||
22
server/events/backboneDone.js
Normal file
22
server/events/backboneDone.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
'use strict';
|
||||
/* A Backbone node level finished. Payload { siteId, toLevel, by }. Idempotent: only acts while the site's build points at THIS
|
||||
* event. The level lands on the SITE (a capture during the build does not stop it); level maxLevel makes the holder alliance the
|
||||
* winner (once per world) and schedules the end of the world. */
|
||||
const D = require('../../public/js/data.js');
|
||||
const { loadWorld } = require('../state');
|
||||
const E = require('../endgame');
|
||||
|
||||
module.exports = function backboneDone(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const site = E.siteRow(db, ev.payload.siteId);
|
||||
if (!site || site.build_event_id !== ev.id) return;
|
||||
const world = loadWorld(db, site.world_id);
|
||||
if (!world || world.status === 'ended') return;
|
||||
const level = site.build_to;
|
||||
db.run('UPDATE landing_sites SET level = ?, build_to = NULL, build_event_id = NULL, build_started_at = NULL, build_due_at = NULL, build_cost = NULL WHERE id = ?', level, site.id);
|
||||
const fresh = E.siteRow(db, site.id);
|
||||
if (fresh.holder_alliance_id && (level % D.ENDGAME.notifyEvery === 0 || level >= D.ENDGAME.maxLevel)) {
|
||||
E.notifyAlliance(ctx, fresh.holder_alliance_id, 'backbone_level', { siteId: site.id, index: site.idx, level });
|
||||
}
|
||||
E.maybeWin(ctx, fresh, ev.dueAt);
|
||||
};
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
'use strict';
|
||||
/* A building level finished. Payload: { key, type, toLevel, userId }. Idempotent: a level never goes down. */
|
||||
/* A building level finished. Payload: { key, type, toLevel, userId }. Each build event adds exactly ONE level to what the
|
||||
* building is at the moment it finishes (relative, not absolute): exploit kits may have knocked the building down while the
|
||||
* upgrade was in flight, and the finished level must not undo that. Never lowers a level; `toLevel` is the level the
|
||||
* upgrade was queued for and is only an upper bound. Events run once (status), so +1 is safe. */
|
||||
const { loadTown, settle } = require('../state');
|
||||
|
||||
module.exports = function buildDone(ctx, ev) {
|
||||
|
|
@ -9,8 +12,12 @@ module.exports = function buildDone(ctx, ev) {
|
|||
if (!town) return;
|
||||
settle(db, town, ev.dueAt); // values up to the moment of completion, at the OLD rates
|
||||
const cur = town.buildings[key];
|
||||
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);
|
||||
let level;
|
||||
if (!cur) { level = 1; db.run('INSERT INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', town.id, key, type, level); }
|
||||
else {
|
||||
level = cur.level < toLevel ? cur.level + 1 : cur.level;
|
||||
if (level !== cur.level) db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', level, 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 });
|
||||
};
|
||||
|
|
|
|||
|
|
@ -10,4 +10,8 @@ module.exports = {
|
|||
reportCleanup: require('./reportCleanup'),
|
||||
buildDone: require('./buildDone'),
|
||||
diploChange: require('./diploChange'),
|
||||
// trade and end game
|
||||
tradeExpire: require('./tradeExpire'),
|
||||
backboneDone: require('./backboneDone'),
|
||||
worldEnd: require('./worldEnd'),
|
||||
};
|
||||
|
|
|
|||
12
server/events/tradeExpire.js
Normal file
12
server/events/tradeExpire.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
'use strict';
|
||||
/* An open Internet exchange offer ran out of time: the escrow goes back to the POP. Payload { offerId }. Idempotent: acts only
|
||||
* while the offer is still open (accepted/cancelled offers cancel their own expiry event, this is the second line of defence). */
|
||||
const T = require('../trade');
|
||||
|
||||
module.exports = function tradeExpire(ctx, ev) {
|
||||
const o = T.getOffer(ctx.db, ev.payload.offerId);
|
||||
if (!o || o.status !== 'open') return;
|
||||
T.closeOffer(ctx, o, 'expired', ev.dueAt);
|
||||
const uid = T.userOfOperator(ctx.db, o.operator_id);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: o.give_amount } });
|
||||
};
|
||||
20
server/events/worldEnd.js
Normal file
20
server/events/worldEnd.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
/* The world ends (two world days after a node reached the last level; payload { reason, siteId }). Stores the final ranking
|
||||
* snapshot, sets status 'ended', gives the escrow of open trade offers back to its POPs, cancels everything still pending in this world (the world is frozen: no arrival, training or
|
||||
* trade changes anything any more; reads keep working) and tells every operator. Idempotent: an ended world is left alone. */
|
||||
const { loadWorld } = require('../state');
|
||||
const E = require('../endgame');
|
||||
const T = require('../trade');
|
||||
const { finalRanking } = require('../finalRanking');
|
||||
|
||||
module.exports = function worldEnd(ctx, ev) {
|
||||
const { db } = ctx;
|
||||
const world = loadWorld(db, ev.worldId);
|
||||
if (!world || world.status === 'ended') return;
|
||||
const snapshot = finalRanking(db, world, ev.dueAt);
|
||||
db.run('INSERT OR REPLACE INTO world_rankings (world_id, created_at, data) VALUES (?, ?, ?)', world.id, ev.dueAt, JSON.stringify(snapshot));
|
||||
db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ev.dueAt, world.id);
|
||||
for (const o of db.all("SELECT * FROM trade_offers WHERE world_id = ? AND status = 'open'", world.id)) T.closeOffer(ctx, o, 'expired', ev.dueAt); // escrow back in its POP: every unit stays accounted for
|
||||
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE world_id = ? AND status = 'pending' AND id != ?", ev.dueAt, world.id, ev.id);
|
||||
E.notifyWorld(ctx, world.id, 'world_ended', { winner: snapshot.winner, endedAt: ev.dueAt });
|
||||
};
|
||||
49
server/finalRanking.js
Normal file
49
server/finalRanking.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The final ranking snapshot written when a world ends (events/worldEnd.js) and served by GET /worlds/:id/results:
|
||||
* operators by footprint, alliances by the sum over their members, top attackers and defenders by battle points, the winner.
|
||||
* Same footprint numbers as /rankings (socialQueries.footprints), computed at the end time. Top D.ENDGAME.rankingTop per list.
|
||||
*/
|
||||
const D = require('../public/js/data.js');
|
||||
const { createSocialQueries } = require('./socialQueries');
|
||||
const E = require('./endgame');
|
||||
|
||||
const round2 = (v) => Math.round(v * 100) / 100;
|
||||
|
||||
function finalRanking(db, world, at) {
|
||||
const social = createSocialQueries({ db, clock: { now: () => at }, scheduler: { runDue() {} } });
|
||||
const fp = social.footprints(world.id, at);
|
||||
const top = D.ENDGAME.rankingTop;
|
||||
const ranked = (rows) => rows.slice(0, top).map((r, i) => Object.assign({ rank: i + 1 }, r));
|
||||
|
||||
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 = ?', world.id)
|
||||
.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: round2(f.footprint) }; })
|
||||
.sort((x, y) => y.footprint - x.footprint || x.operatorId - y.operatorId);
|
||||
|
||||
const byAlliance = new Map();
|
||||
for (const o of ops) {
|
||||
if (!o.allianceId) continue;
|
||||
const c = byAlliance.get(o.allianceId) || { footprint: 0, members: 0, towns: 0 };
|
||||
c.footprint += o.footprint; c.members += 1; c.towns += o.towns;
|
||||
byAlliance.set(o.allianceId, c);
|
||||
}
|
||||
const alliances = db.all('SELECT id, name, tag FROM alliances WHERE world_id = ?', world.id)
|
||||
.map((a) => { const c = byAlliance.get(a.id) || { footprint: 0, members: 0, towns: 0 }; return { allianceId: a.id, name: a.name, tag: a.tag, members: c.members, towns: c.towns, footprint: round2(c.footprint) }; })
|
||||
.sort((x, y) => y.footprint - x.footprint || x.allianceId - y.allianceId);
|
||||
|
||||
const stats = 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 = ?`, world.id)
|
||||
.map((r) => ({ operatorId: r.id, name: r.name, allianceTag: r.tag, attackPoints: round2(r.att || 0), defensePoints: round2(r.def || 0) }));
|
||||
const attackers = stats.filter((r) => r.attackPoints > 0).sort((x, y) => y.attackPoints - x.attackPoints || x.operatorId - y.operatorId);
|
||||
const defenders = stats.filter((r) => r.defensePoints > 0).sort((x, y) => y.defensePoints - x.defensePoints || x.operatorId - y.operatorId);
|
||||
|
||||
const winner = E.winnerView(db.get('SELECT * FROM worlds WHERE id = ?', world.id));
|
||||
const sites = E.siteStates(db, world, at).map(({ site, row }) => E.siteView(db, world, site, row));
|
||||
return {
|
||||
worldId: world.id, at, winner, sites,
|
||||
totals: { operators: ops.length, alliances: alliances.length },
|
||||
operators: ranked(ops), alliances: ranked(alliances), attackers: ranked(attackers), defenders: ranked(defenders),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { finalRanking };
|
||||
|
|
@ -17,7 +17,7 @@ const { TokenBucket, clientIp } = require('./net');
|
|||
const { applySecurityHeaders } = require('./static');
|
||||
|
||||
const MAX_BODY = 32 * 1024;
|
||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId']);
|
||||
const INT_PARAMS = new Set(['id', 'townId', 'eventId', 'tokenId', 'inviteId', 'noteId', 'proposalId', 'otherId', 'operatorId', 'reportId']);
|
||||
|
||||
// Per-key token buckets (per IP, per token). Idle full buckets are pruned so the map cannot grow without bound.
|
||||
class Limiter {
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ const routes = require('./routes');
|
|||
const eventHandlers = require('./events');
|
||||
const { createStaticHandler, applySecurityHeaders } = require('./static');
|
||||
const { parseTrustProxy, parseTrustedProxies, listenDual, listUrls } = require('./net');
|
||||
const { createPush } = require('./push');
|
||||
const { bindGame, pushDeps } = require('./pushHooks');
|
||||
|
||||
function defaultLog(msg) { console.log(new Date().toISOString() + ' ' + msg); }
|
||||
|
||||
|
|
@ -55,6 +57,11 @@ async function createServer(userOpts) {
|
|||
routes.register(api.router, services);
|
||||
api.services = services;
|
||||
|
||||
// WebSocket push on /ws (docs/PROTOCOL.md): hints only, the REST API stays the source of truth and works without it
|
||||
const push = createPush(Object.assign({ clock, authenticate: auth.authenticate, opts: o, log }, pushDeps(db)));
|
||||
bindGame({ push, db, scheduler, commands });
|
||||
services.push = push;
|
||||
|
||||
const serveStatic = createStaticHandler(o.publicDir);
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = req.url || '/';
|
||||
|
|
@ -66,6 +73,7 @@ async function createServer(userOpts) {
|
|||
if (url.startsWith('/api/')) return api.handle(req, res);
|
||||
return serveStatic(req, res).catch((err) => { log('static error: ' + (err && err.message)); if (!res.headersSent) res.writeHead(500); res.end(); });
|
||||
});
|
||||
server.on('upgrade', push.onUpgrade);
|
||||
server.headersTimeout = 20000; server.requestTimeout = 30000; server.keepAliveTimeout = 5000;
|
||||
const sockets = new Set();
|
||||
server.on('connection', (s) => { sockets.add(s); s.on('close', () => sockets.delete(s)); });
|
||||
|
|
@ -81,6 +89,7 @@ async function createServer(userOpts) {
|
|||
if (closePromise) return closePromise;
|
||||
closePromise = (async () => {
|
||||
scheduler.stop(); clearInterval(idemTimer);
|
||||
await push.close(); // 1001 to every socket, so server.close() below is not held up
|
||||
await new Promise((r) => { server.close(() => r()); if (server.closeIdleConnections) server.closeIdleConnections(); setTimeout(() => { for (const s of sockets) s.destroy(); }, 1000).unref(); });
|
||||
db.close();
|
||||
})();
|
||||
|
|
|
|||
90
server/migrations/004_trade_endgame.sql
Normal file
90
server/migrations/004_trade_endgame.sql
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
-- Trade (Internet exchange offers), shared report folder, end game (backbone landing sites, winner, final ranking).
|
||||
-- Times are integer ms since the epoch (UTC). Every game row carries world_id.
|
||||
|
||||
-- An offer "give X of A for Y of B, max distance Z". The offered amount is ESCROWED: it left the POP when the offer was
|
||||
-- created and lives in this row until the offer is accepted (it then travels as a transport), cancelled or expired (it goes
|
||||
-- back to the POP). status: open | accepted | completed | cancelled | expired | void (the POP changed hands).
|
||||
CREATE TABLE trade_offers (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
town_id INTEGER NOT NULL REFERENCES towns(id), -- the POP that posted it (the escrow came from there)
|
||||
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||
give_res TEXT NOT NULL,
|
||||
give_amount INTEGER NOT NULL CHECK (give_amount > 0),
|
||||
want_res TEXT NOT NULL,
|
||||
want_amount INTEGER NOT NULL CHECK (want_amount > 0),
|
||||
max_distance INTEGER NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'open',
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
expire_event_id INTEGER,
|
||||
accepted_by_operator INTEGER REFERENCES operators(id),
|
||||
accepted_town_id INTEGER REFERENCES towns(id),
|
||||
accepted_at INTEGER,
|
||||
goods_movement_id INTEGER, -- transport poster -> acceptor (the escrow)
|
||||
payment_movement_id INTEGER, -- transport acceptor -> poster
|
||||
legs_done INTEGER NOT NULL DEFAULT 0,
|
||||
closed_at INTEGER
|
||||
);
|
||||
CREATE INDEX trade_offers_open ON trade_offers(world_id, status, id);
|
||||
CREATE INDEX trade_offers_town ON trade_offers(town_id, status);
|
||||
CREATE INDEX trade_offers_operator ON trade_offers(operator_id, id);
|
||||
|
||||
-- Reports shared to an alliance (the shared report folder). Gone with the report (cleanup) or the alliance.
|
||||
CREATE TABLE report_shares (
|
||||
report_id INTEGER NOT NULL REFERENCES reports(id) ON DELETE CASCADE,
|
||||
alliance_id INTEGER NOT NULL REFERENCES alliances(id) ON DELETE CASCADE,
|
||||
shared_by INTEGER NOT NULL REFERENCES operators(id),
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (report_id, alliance_id)
|
||||
);
|
||||
CREATE INDEX report_shares_alliance ON report_shares(alliance_id, report_id);
|
||||
|
||||
-- Backbone landing sites (end game). Positions are a pure function of the world seed (rules.backboneSites); a row is
|
||||
-- created lazily by whatever touches a site first once the world is at day D.ENDGAME.openDay (no timer event). holder_alliance_id NULL = still held by the incumbent
|
||||
-- (or the holder disbanded: the level stays with the site). `fiber/hardware/capital` is the stockpile shipped in by the holders
|
||||
-- for the next level. build_* describe the level being built (one at a time).
|
||||
CREATE TABLE landing_sites (
|
||||
id INTEGER PRIMARY KEY,
|
||||
world_id INTEGER NOT NULL REFERENCES worlds(id),
|
||||
idx INTEGER NOT NULL,
|
||||
x INTEGER NOT NULL,
|
||||
y INTEGER NOT NULL,
|
||||
holder_alliance_id INTEGER REFERENCES alliances(id) ON DELETE SET NULL,
|
||||
holder_operator_id INTEGER REFERENCES operators(id), -- who took it
|
||||
taken_at INTEGER,
|
||||
level INTEGER NOT NULL DEFAULT 0,
|
||||
fiber INTEGER NOT NULL DEFAULT 0,
|
||||
hardware INTEGER NOT NULL DEFAULT 0,
|
||||
capital INTEGER NOT NULL DEFAULT 0,
|
||||
build_to INTEGER,
|
||||
build_event_id INTEGER,
|
||||
build_started_at INTEGER,
|
||||
build_due_at INTEGER,
|
||||
build_cost TEXT,
|
||||
UNIQUE (world_id, idx),
|
||||
UNIQUE (world_id, x, y)
|
||||
);
|
||||
|
||||
-- What each operator shipped into a site's stockpile (kept when the site changes hands: it is a ledger, not a balance).
|
||||
CREATE TABLE landing_contributions (
|
||||
site_id INTEGER NOT NULL REFERENCES landing_sites(id),
|
||||
operator_id INTEGER NOT NULL REFERENCES operators(id),
|
||||
fiber INTEGER NOT NULL DEFAULT 0,
|
||||
hardware INTEGER NOT NULL DEFAULT 0,
|
||||
capital INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (site_id, operator_id)
|
||||
);
|
||||
|
||||
-- The winner and the end of the world. The ranking snapshot is written once, when the world enters status 'ended'.
|
||||
ALTER TABLE worlds ADD COLUMN winner_alliance_id INTEGER;
|
||||
ALTER TABLE worlds ADD COLUMN winner_name TEXT;
|
||||
ALTER TABLE worlds ADD COLUMN winner_tag TEXT;
|
||||
ALTER TABLE worlds ADD COLUMN winner_site_id INTEGER;
|
||||
ALTER TABLE worlds ADD COLUMN won_at INTEGER;
|
||||
|
||||
CREATE TABLE world_rankings (
|
||||
world_id INTEGER PRIMARY KEY REFERENCES worlds(id),
|
||||
created_at INTEGER NOT NULL,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
|
|
@ -72,6 +72,8 @@ function arriveReinforce(ctx, mv, ev) {
|
|||
function arriveTransport(ctx, mv, ev) {
|
||||
const { db } = ctx;
|
||||
const now = ev.dueAt;
|
||||
// A shipment to a backbone landing site (extra.siteId) feeds the site's stockpile; refused ones ride home like any undeliverable cargo.
|
||||
const siteDelivered = !!(mv.extra && mv.extra.siteId) && require('../endgame').deliverShipment(ctx, mv, now);
|
||||
const target = mv.toTownId ? loadTown(db, mv.toTownId) : null;
|
||||
let lost = {};
|
||||
if (target) {
|
||||
|
|
@ -82,7 +84,7 @@ function arriveTransport(ctx, mv, ev) {
|
|||
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
|
||||
const cargoBack = target || siteDelivered ? {} : 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) {
|
||||
|
|
@ -99,12 +101,12 @@ function arriveSettle(ctx, mv, ev) {
|
|||
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 tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
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) });
|
||||
const chk = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), 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);
|
||||
|
|
|
|||
|
|
@ -211,7 +211,8 @@ function resolveScanOnTown(ctx, mv, now, s) {
|
|||
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);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
if (tile.type === 'backbone') return require('./landing')(ctx, mv, now, world, tile); // end game: backbone landing site
|
||||
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);
|
||||
|
|
@ -274,6 +275,7 @@ function transferTown(ctx, town, newOp, oldOp, now) {
|
|||
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);
|
||||
require('../trade').onTownTransferred(ctx, town.id, now); // open Internet exchange offers of the old owner end, the escrow stays in the POP
|
||||
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 });
|
||||
|
|
|
|||
67
server/military/landing.js
Normal file
67
server/military/landing.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Arrival of a scan or an attack at a backbone landing site (hooked from combat.arriveSite, runs inside the `arrive` event).
|
||||
* A site is defended by a static value only: rules.backboneDefence(seed, x, y, world age, node level). Beating it as a member
|
||||
* of an alliance makes that alliance the holder (level, stockpile and a running build stay with the site). The site never
|
||||
* loses anything, so there is no loot and no raid; survivors drive home. Re-validates at arrival like every movement.
|
||||
*/
|
||||
const R = require('../../public/js/rules.js');
|
||||
const D = require('../../public/js/data.js');
|
||||
const U = require('./units');
|
||||
const M = require('./movements');
|
||||
const E = require('../endgame');
|
||||
const { createReport } = require('./reports');
|
||||
const { bounce, townBrief, opBrief } = require('./arrivals');
|
||||
|
||||
const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners
|
||||
|
||||
function sendHome(ctx, mv, survivors) {
|
||||
if (U.isEmpty(survivors)) return null;
|
||||
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
|
||||
if (!dest) return null;
|
||||
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} });
|
||||
}
|
||||
|
||||
module.exports = function arriveLanding(ctx, mv, now, world, tile) {
|
||||
const { db } = ctx;
|
||||
if (mv.type !== 'scan' && mv.type !== 'attack') return bounce(ctx, mv, now, 'invalid_target');
|
||||
const rows = E.ensureSites(db, world, now, ctx);
|
||||
const site = rows.find((r) => r.idx === tile.site);
|
||||
const attackerOp = U.getOperator(db, mv.ownerId);
|
||||
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
|
||||
const uid = U.userOfOperator(db, attackerOp.id);
|
||||
const where = { x: site.x, y: site.y, index: site.idx, siteId: site.id, level: site.level, holder: E.allianceInfo(db, site.holder_alliance_id) };
|
||||
const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level);
|
||||
|
||||
if (mv.type === 'scan') {
|
||||
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
|
||||
const res = R.resolveScan(sa, SCAN_STRENGTH);
|
||||
const loss = R.applyLoss(mv.units, res.lossFraction);
|
||||
const intel = res.success ? { defence: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null } : null;
|
||||
createReport(ctx, {
|
||||
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site: Object.assign({ type: 'backbone' }, where) },
|
||||
data: { success: res.success, detail: res.detail, site: Object.assign({ type: 'backbone' }, where), scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
|
||||
recipients: [{ userId: uid, role: 'attacker' }],
|
||||
});
|
||||
sendHome(ctx, mv, loss.survivors);
|
||||
return;
|
||||
}
|
||||
|
||||
// attack: alliance members only, and not against the own alliance or a pact partner (the world may have changed since it left)
|
||||
if (!attackerOp.alliance_id) return bounce(ctx, mv, now, 'no_alliance');
|
||||
try { E.denyIfFriendly(db, attackerOp, site); } catch (e) { return bounce(ctx, mv, now, e.details.reason || 'invalid_target'); }
|
||||
|
||||
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);
|
||||
const oldHolder = site.holder_alliance_id;
|
||||
if (b.attackerWins) E.transferSite(ctx, site, attackerOp, now);
|
||||
const ret = sendHome(ctx, mv, survivors);
|
||||
const data = {
|
||||
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site: Object.assign({ type: 'backbone' }, where), origin: townBrief(origin),
|
||||
attacker: { operator: opBrief({ id: attackerOp.id, name: attackerOp.name, as_number: attackerOp.as_number }), alliance: E.allianceInfo(db, attackerOp.alliance_id), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
|
||||
power: { attack: b.A, defence: b.D }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
|
||||
};
|
||||
const recipients = [{ userId: uid, role: 'attacker' }];
|
||||
if (oldHolder) for (const m of db.all('SELECT o.user_id AS uid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', oldHolder)) recipients.push({ userId: m.uid, role: 'defender' });
|
||||
createReport(ctx, { worldId: mv.worldId, type: 'landing', now, summary: { outcome: data.outcome, site: data.site, attacker: data.attacker.operator, taken: b.attackerWins }, data, recipients });
|
||||
};
|
||||
|
|
@ -46,10 +46,12 @@ function launchReturn(ctx, o) {
|
|||
});
|
||||
}
|
||||
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports.
|
||||
// Transport links in use by a POP: transports it sent that are still out, plus the empty return legs of transports, plus the
|
||||
// open Internet exchange offers it posted (an open offer holds a link in reserve: accepting it sends the escrow on that link).
|
||||
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;
|
||||
((type = 'transport' AND from_town_id = ?) OR (type = 'return' AND to_town_id = ? AND json_extract(extra, '$.link') = 1))`, townId, townId).n
|
||||
+ db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", townId).n;
|
||||
}
|
||||
|
||||
// Hooks for later stages (trade): called after a transport has been delivered. fn(ctx, movement, { added, lost }).
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ function ownerView(m, names) {
|
|||
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,
|
||||
target: extra.target || null, parentId: m.parent_id, siteId: extra.siteId || null, // siteId: a shipment to a backbone landing site
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -55,8 +55,27 @@ function movementLists(db, operatorId, townId) {
|
|||
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)) };
|
||||
// Confederation members (own alliance included) see what is heading for each other's POPs: origin and ETA only, the type
|
||||
// stays hidden. Movements of operators who are themselves partners of the target are friendly traffic and left out.
|
||||
// Only in the whole-operator list, not in the per-POP lists.
|
||||
let allied = [];
|
||||
if (!townId) {
|
||||
const partners = require('../alliances').confederatedOperators(db, operatorId);
|
||||
if (partners.length) {
|
||||
allied = db.all(`SELECT m.*, t.owner_id AS target_owner FROM movements m JOIN towns t ON t.id = m.to_town_id WHERE t.owner_id IN (${partners.map(() => '?').join(',')})
|
||||
AND m.owner_id != t.owner_id AND m.owner_id != ? AND m.status = 'out' AND m.type != 'return' ORDER BY m.arrive_at, m.id LIMIT ?`, ...partners, operatorId, D.MILITARY.maxLists)
|
||||
.filter((m) => !U.pactBlocks(db, m.owner_id, m.target_owner));
|
||||
}
|
||||
}
|
||||
const names = townNames(db, own.concat(inc, allied).flatMap((m) => [m.from_town_id, m.to_town_id]));
|
||||
const out = { outgoing: own.map((m) => ownerView(m, names)), incoming: inc.map((m) => incomingView(m, names)) };
|
||||
if (!townId) {
|
||||
out.alliedIncoming = allied.map((m) => {
|
||||
const o = db.get('SELECT id, name FROM operators WHERE id = ?', m.target_owner);
|
||||
return Object.assign(incomingView(m, names), { ally: true, toOperator: { id: o.id, name: o.name } });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
|
||||
|
|
@ -127,7 +146,7 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
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);
|
||||
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
|
||||
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);
|
||||
|
|
@ -140,11 +159,18 @@ function createMilitaryQueries({ db, clock, scheduler }) {
|
|||
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 };
|
||||
}
|
||||
if (tile.type === 'backbone') { // end game: who holds the site, its node level and stockpile, whether you could attack it
|
||||
const E = require('../endgame');
|
||||
const st = E.siteStates(db, world, now).find((s) => s.site.index === tile.site);
|
||||
const v = E.siteView(db, world, st.site, st.row);
|
||||
const holds = !!(op.alliance_id && v.holder && v.holder.allianceId === op.alliance_id);
|
||||
out.backbone = { siteId: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel, pool: v.pool, build: v.build, mine: holds, canAttack: !!op.alliance_id && !holds };
|
||||
}
|
||||
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 });
|
||||
const sc = R.settleCheck({ tileType: tile.type, backbone: R.isBackboneSite(world.seed, world.map_radius, x, y), 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;
|
||||
}
|
||||
|
|
|
|||
201
server/push.js
Normal file
201
server/push.js
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
'use strict';
|
||||
/*
|
||||
* WebSocket push (stage 6): transport and connection registry only, no game knowledge (that lives in pushHooks.js).
|
||||
* Push is a HINT: small JSON messages saying "something changed, refetch over REST". See docs/PROTOCOL.md.
|
||||
*
|
||||
* const push = createPush({ clock, authenticate, tokenValid, townOwner, opts, log });
|
||||
* httpServer.on('upgrade', push.onUpgrade);
|
||||
* push.toUser(userId, { type: 'town', townId: 7 }); // all sockets of that user
|
||||
* push.toTown(7, { type: 'town', townId: 7 }); // the user who owns POP 7 right now
|
||||
* await push.close(); // 1001 to everybody, resolves when the sockets are gone
|
||||
*
|
||||
* Deps: authenticate(header, now) -> { user, tokenId } | null (auth.authenticate), tokenValid(tokenId) -> bool (re-checked on
|
||||
* every ping tick: revoked token or banned user), townOwner(townId) -> userId | null, opts (the createServer options:
|
||||
* trustProxy, trustedProxies, allowedOrigins, maxConnPerIp, optional wsAuthTimeoutMs / wsPingMs / wsRate / wsBurst / wsBadBudget).
|
||||
*/
|
||||
const { WebSocketServer } = require('ws');
|
||||
const { originAllowed, clientIp, TokenBucket } = require('./net');
|
||||
|
||||
const CLOSE = { SHUTDOWN: 1001, BAD_MESSAGES: 4400, UNAUTHORIZED: 4401, AUTH_TIMEOUT: 4408, RATE_LIMITED: 4429 };
|
||||
const MAX_PAYLOAD = 1024; // bytes per client message
|
||||
const MAX_BUFFERED = 1024 * 1024; // a client that does not read 1 MB of hints is dead weight
|
||||
|
||||
function createPush(deps) {
|
||||
const { clock, authenticate, tokenValid, townOwner, opts } = deps;
|
||||
const log = deps.log || (() => {});
|
||||
const cfg = {
|
||||
authTimeoutMs: opts.wsAuthTimeoutMs || 10000, pingMs: opts.wsPingMs || 30000,
|
||||
rate: opts.wsRate || 5, burst: opts.wsBurst || 15, badBudget: opts.wsBadBudget || 5,
|
||||
maxConnPerIp: opts.maxConnPerIp === undefined ? 40 : opts.maxConnPerIp, closeGraceMs: 1000,
|
||||
};
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_PAYLOAD, perMessageDeflate: false, clientTracking: false });
|
||||
const conns = new Set();
|
||||
const byUser = new Map(); // userId -> Set<conn> (authenticated sockets)
|
||||
const perIp = new Map(); // ip -> open sockets (also not yet authenticated ones)
|
||||
let closing = false;
|
||||
|
||||
// ------------------------------------------------------------ upgrade
|
||||
function refuse(socket, status, text, why) {
|
||||
log('refused ws ' + why);
|
||||
try { socket.write('HTTP/1.1 ' + status + ' ' + text + '\r\nConnection: close\r\nContent-Length: 0\r\n\r\n'); } catch (e) { /* gone */ }
|
||||
socket.destroy();
|
||||
}
|
||||
|
||||
function onUpgrade(req, socket, head) {
|
||||
socket.on('error', () => {}); // a reset during the handshake must not crash the process
|
||||
let pathname = '';
|
||||
try { pathname = new URL(req.url || '/', 'http://x').pathname; } catch (e) { /* stays '' */ }
|
||||
const ip = clientIp(req, opts.trustProxy, opts.trustedProxies);
|
||||
if (pathname !== '/ws') return refuse(socket, 404, 'Not Found', 'path=' + JSON.stringify(pathname.slice(0, 60)) + ' ip=' + ip);
|
||||
if (closing) return refuse(socket, 503, 'Service Unavailable', 'shutting down ip=' + ip);
|
||||
if (!originAllowed(req, opts)) return refuse(socket, 403, 'Forbidden', 'origin=' + JSON.stringify(String(req.headers.origin).slice(0, 100)) + ' ip=' + ip);
|
||||
if (cfg.maxConnPerIp > 0 && (perIp.get(ip) || 0) >= cfg.maxConnPerIp) return refuse(socket, 429, 'Too Many Requests', 'conn_cap ip=' + ip + ' max=' + cfg.maxConnPerIp);
|
||||
// handleUpgrade calls back synchronously on success and not at all when the handshake is malformed, so the per-IP
|
||||
// count is taken in the callback: nothing can leak it.
|
||||
wss.handleUpgrade(req, socket, head, (ws) => accept(ws, ip));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ connections
|
||||
function accept(ws, ip) {
|
||||
perIp.set(ip, (perIp.get(ip) || 0) + 1);
|
||||
const c = {
|
||||
ws, ip, userId: null, tokenId: null, alive: true, bad: 0, bucket: new TokenBucket(cfg.rate, cfg.burst),
|
||||
out: new Map(), flushing: false, authTimer: null, killTimer: null, gone: false,
|
||||
};
|
||||
conns.add(c);
|
||||
if (ws._socket && ws._socket.setNoDelay) ws._socket.setNoDelay(true);
|
||||
c.authTimer = setTimeout(() => { log('ws closed auth_timeout ip=' + ip); closeConn(c, CLOSE.AUTH_TIMEOUT, 'auth_timeout'); }, cfg.authTimeoutMs);
|
||||
ws.on('message', (data, isBinary) => onMessage(c, data, isBinary));
|
||||
ws.on('pong', () => { c.alive = true; });
|
||||
ws.on('error', (err) => { log('ws error ip=' + ip + ': ' + (err && err.message)); }); // 'close' follows
|
||||
ws.on('close', () => drop(c));
|
||||
}
|
||||
|
||||
function drop(c) {
|
||||
if (c.gone) return;
|
||||
c.gone = true;
|
||||
clearTimeout(c.authTimer); clearTimeout(c.killTimer);
|
||||
conns.delete(c);
|
||||
const n = (perIp.get(c.ip) || 1) - 1;
|
||||
if (n > 0) perIp.set(c.ip, n); else perIp.delete(c.ip);
|
||||
if (c.userId !== null) {
|
||||
const set = byUser.get(c.userId);
|
||||
if (set) { set.delete(c); if (!set.size) byUser.delete(c.userId); }
|
||||
}
|
||||
}
|
||||
|
||||
function closeConn(c, code, reason) {
|
||||
if (c.gone || c.closing) return;
|
||||
c.closing = true;
|
||||
try { c.ws.close(code, reason); } catch (e) { try { c.ws.terminate(); } catch (e2) { /* gone */ } }
|
||||
c.killTimer = setTimeout(() => { try { c.ws.terminate(); } catch (e) { /* gone */ } }, cfg.closeGraceMs);
|
||||
if (c.killTimer.unref) c.killTimer.unref();
|
||||
}
|
||||
|
||||
function sendNow(c, obj) {
|
||||
if (c.gone || c.closing || c.ws.readyState !== 1) return false;
|
||||
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return false; }
|
||||
c.ws.send(JSON.stringify(obj));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Hints are coalesced: identical messages produced in the same tick (many events of one catch-up) go out once.
|
||||
function queue(c, msg) {
|
||||
if (c.userId === null || c.gone || c.closing) return;
|
||||
c.out.set(JSON.stringify(msg), true);
|
||||
if (!c.flushing) { c.flushing = true; setImmediate(() => flush(c)); }
|
||||
}
|
||||
|
||||
function flush(c) {
|
||||
c.flushing = false;
|
||||
const items = c.out; c.out = new Map();
|
||||
if (c.gone || c.closing || c.ws.readyState !== 1) return;
|
||||
for (const text of items.keys()) {
|
||||
if (c.ws.bufferedAmount > MAX_BUFFERED) { log('ws terminated: client not reading ip=' + c.ip); c.ws.terminate(); return; }
|
||||
c.ws.send(text);
|
||||
}
|
||||
}
|
||||
|
||||
function bad(c, why) {
|
||||
c.bad++;
|
||||
log('ws bad message (' + why + ') ip=' + c.ip + ' user=' + c.userId + ' ' + c.bad + '/' + cfg.badBudget);
|
||||
if (c.bad >= cfg.badBudget) closeConn(c, CLOSE.BAD_MESSAGES, 'too_many_bad_messages');
|
||||
}
|
||||
|
||||
function onMessage(c, data, isBinary) {
|
||||
if (c.gone || c.closing) return;
|
||||
c.alive = true;
|
||||
if (!c.bucket.take()) { log('refused ws rate_limited ip=' + c.ip + ' user=' + c.userId); return closeConn(c, CLOSE.RATE_LIMITED, 'rate_limited'); }
|
||||
let m = null;
|
||||
if (!isBinary) { try { m = JSON.parse(data.toString('utf8')); } catch (e) { m = null; } }
|
||||
const ok = m && typeof m === 'object' && !Array.isArray(m) && typeof m.type === 'string';
|
||||
|
||||
if (c.userId === null) { // the FIRST message must authenticate; anything else is fatal
|
||||
if (!ok || m.type !== 'auth') { log('refused ws unauthorized (first message is not auth) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'auth_required'); }
|
||||
const a = typeof m.token === 'string' && m.token.length <= 200 ? authenticate('Bearer ' + m.token, clock.now()) : null;
|
||||
if (!a) { log('refused ws unauthorized (bad token) ip=' + c.ip); return closeConn(c, CLOSE.UNAUTHORIZED, 'invalid_token'); }
|
||||
clearTimeout(c.authTimer); c.authTimer = null;
|
||||
c.userId = a.user.id; c.tokenId = a.tokenId;
|
||||
let set = byUser.get(c.userId);
|
||||
if (!set) { set = new Set(); byUser.set(c.userId, set); }
|
||||
set.add(c);
|
||||
sendNow(c, { type: 'ready', serverTime: clock.now() });
|
||||
return;
|
||||
}
|
||||
if (!ok) return bad(c, isBinary ? 'binary' : 'not a JSON object with a type');
|
||||
if (m.type === 'ping') { sendNow(c, { type: 'pong', serverTime: clock.now() }); return; }
|
||||
return bad(c, 'unknown type ' + JSON.stringify(m.type.slice(0, 20)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ keepalive + revocation
|
||||
function tick() {
|
||||
for (const c of conns) {
|
||||
if (c.gone || c.closing) continue;
|
||||
if (!c.alive) { log('ws dead, terminating ip=' + c.ip + ' user=' + c.userId); try { c.ws.terminate(); } catch (e) { /* gone */ } continue; }
|
||||
if (c.tokenId !== null) {
|
||||
let valid = true;
|
||||
try { valid = tokenValid(c.tokenId); } catch (e) { log('ws token check failed: ' + e.message); }
|
||||
if (!valid) { log('ws closed token_revoked user=' + c.userId); closeConn(c, CLOSE.UNAUTHORIZED, 'token_revoked'); continue; }
|
||||
}
|
||||
c.alive = false;
|
||||
try { c.ws.ping(); } catch (e) { /* closing */ }
|
||||
}
|
||||
}
|
||||
const timer = setInterval(tick, cfg.pingMs);
|
||||
if (timer.unref) timer.unref();
|
||||
|
||||
// ------------------------------------------------------------ public API
|
||||
function toUser(userId, msg) {
|
||||
const set = byUser.get(userId);
|
||||
if (set) for (const c of set) queue(c, msg);
|
||||
}
|
||||
|
||||
function toTown(townId, msg) {
|
||||
if (!byUser.size) return; // nobody connected: no lookup
|
||||
const owner = townOwner(townId);
|
||||
if (owner) toUser(owner, msg);
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (closing) return closing_;
|
||||
closing = true;
|
||||
clearInterval(timer);
|
||||
closing_ = new Promise((resolve) => {
|
||||
for (const c of conns) { if (c.flushing) flush(c); closeConn(c, CLOSE.SHUTDOWN, 'shutdown'); }
|
||||
const done = () => { wss.close(); resolve(); };
|
||||
if (!conns.size) return done();
|
||||
const wait = setInterval(() => { if (!conns.size) { clearInterval(wait); done(); } }, 10);
|
||||
setTimeout(() => { for (const c of conns) { try { c.ws.terminate(); } catch (e) { /* gone */ } } }, cfg.closeGraceMs + 50).unref();
|
||||
});
|
||||
return closing_;
|
||||
}
|
||||
let closing_ = null;
|
||||
|
||||
return {
|
||||
onUpgrade, toUser, toTown, close,
|
||||
stats: () => ({ connections: conns.size, users: byUser.size, ips: perIp.size }),
|
||||
CLOSE,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createPush, CLOSE, MAX_PAYLOAD };
|
||||
84
server/pushHooks.js
Normal file
84
server/pushHooks.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
'use strict';
|
||||
/*
|
||||
* The game-aware half of push: which hint goes to whom. push.js knows sockets; this file knows notifications, events and
|
||||
* commands. Hooks fire only AFTER the transaction that caused them committed (scheduler outbox, commands.run).
|
||||
*
|
||||
* notification row (any kind) -> user: {type:'notification', id, kind}
|
||||
* kind incoming -> user: {type:'incoming', townId, arriveAt}
|
||||
* kind report -> user: {type:'report', id}
|
||||
* kind message | alliance_message -> user: {type:'message', id}
|
||||
* town_lost, town_gained, ... -> user: {type:'town', townId} (ownership changed: the old owner is not
|
||||
* reachable through toTown any more)
|
||||
* event done (build, train, research, arrive, return ...) -> owner of every POP it touched: {type:'town', townId}
|
||||
* command done (build, train, send, ...) -> owner of every POP it touched: {type:'town', townId}
|
||||
* (also the device that issued it: the client may ignore its own echo; other devices of the user learn from it)
|
||||
*
|
||||
* Not a hint source: reading (GET) never pushes.
|
||||
*/
|
||||
|
||||
const isId = (v) => Number.isInteger(v) && v > 0;
|
||||
|
||||
// notification kind -> payload key holding a POP id whose state changed for THAT user (kinds whose event does not already
|
||||
// carry the town in events.town_id, or whose owner changed)
|
||||
const TOWN_KINDS = {
|
||||
town_lost: 'townId', town_gained: 'townId',
|
||||
transport_arrived: 'townId', transport_delivered: 'toTownId',
|
||||
movement_returned: 'townId', reinforcements_sent_home: 'ownerTownId',
|
||||
};
|
||||
|
||||
// Command args that name a POP the command changed (the receiving POP of a movement is NOT listed: the defender gets
|
||||
// an 'incoming' hint, never a plain 'town' one that would give the launch away without its ETA).
|
||||
const COMMAND_TOWN_KEYS = ['townId', 'fromTownId', 'hostTownId', 'ownerTownId'];
|
||||
|
||||
// Deps for createPush that need the database.
|
||||
function pushDeps(db) {
|
||||
const owner = 'SELECT o.user_id AS uid FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.id = ?';
|
||||
const valid = 'SELECT 1 AS ok FROM tokens t JOIN users u ON u.id = t.user_id WHERE t.id = ? AND t.revoked_at IS NULL AND u.banned = 0';
|
||||
return {
|
||||
townOwner: (townId) => { const r = db.get(owner, townId); return r ? r.uid : null; },
|
||||
tokenValid: (tokenId) => !!db.get(valid, tokenId),
|
||||
};
|
||||
}
|
||||
|
||||
function bindGame({ push, db, scheduler, commands, log }) {
|
||||
const toTowns = (ids) => { for (const id of ids) push.toTown(id, { type: 'town', townId: id }); };
|
||||
|
||||
function movementTowns(movementId, ids) {
|
||||
if (!isId(movementId)) return;
|
||||
const mv = db.get('SELECT from_town_id AS f, to_town_id AS t FROM movements WHERE id = ?', movementId);
|
||||
if (mv) { if (isId(mv.f)) ids.add(mv.f); if (isId(mv.t)) ids.add(mv.t); }
|
||||
}
|
||||
|
||||
// ---- notifications: written by events and commands via scheduler.notify
|
||||
scheduler.onNotify = (n) => {
|
||||
const p = n.payload || {};
|
||||
push.toUser(n.userId, { type: 'notification', id: n.id, kind: n.type });
|
||||
if (n.type === 'incoming' && isId(p.toTownId)) push.toUser(n.userId, { type: 'incoming', townId: p.toTownId, arriveAt: p.arriveAt });
|
||||
else if (n.type === 'report' && isId(p.reportId)) push.toUser(n.userId, { type: 'report', id: p.reportId });
|
||||
else if ((n.type === 'message' || n.type === 'alliance_message') && isId(p.messageId)) push.toUser(n.userId, { type: 'message', id: p.messageId });
|
||||
const key = TOWN_KINDS[n.type];
|
||||
if (key && isId(p[key])) push.toUser(n.userId, { type: 'town', townId: p[key] });
|
||||
};
|
||||
|
||||
// ---- events: the POPs an event touched (events.town_id, or both ends of a movement)
|
||||
const prevOnEvent = scheduler.onEvent;
|
||||
scheduler.onEvent = (ev) => {
|
||||
if (prevOnEvent) prevOnEvent(ev);
|
||||
const ids = new Set();
|
||||
if (isId(ev.townId)) ids.add(ev.townId);
|
||||
if (ev.type === 'arrive' || ev.type === 'return') movementTowns(ev.payload && ev.payload.movementId, ids);
|
||||
toTowns(ids);
|
||||
};
|
||||
|
||||
// ---- commands
|
||||
commands.hooks.onCommand = (name, args, out) => {
|
||||
const ids = new Set();
|
||||
for (const k of COMMAND_TOWN_KEYS) if (args && isId(args[k])) ids.add(args[k]);
|
||||
if (out && isId(out.townId)) ids.add(out.townId); // joinWorld: the new POP
|
||||
if (name === 'recallMovement') movementTowns(args.movementId, ids); // also tells the target's owner the warning is gone
|
||||
toTowns(ids);
|
||||
};
|
||||
if (log) log('push hooks bound');
|
||||
}
|
||||
|
||||
module.exports = { bindGame, pushDeps, TOWN_KINDS, COMMAND_TOWN_KEYS };
|
||||
|
|
@ -89,10 +89,16 @@ function createQueries({ db, clock, scheduler }) {
|
|||
r = Math.min(r, 40);
|
||||
const x0 = Math.max(-rad, x - r), x1 = Math.min(rad, x + r), y0 = Math.max(-rad, y - r), y1 = Math.min(rad, y + r);
|
||||
const specials = [];
|
||||
const age = R.worldAgeDays(world.start_at, now, world.speed);
|
||||
const sites = new Map(require('./endgame').siteStates(db, world, now).map(({ site, row }) => [site.index, require('./endgame').siteView(db, world, site, row)]));
|
||||
for (let yy = y0; yy <= y1; yy++) {
|
||||
for (let xx = x0; xx <= x1; xx++) {
|
||||
const t = R.tileAt(world.seed, rad, xx, yy);
|
||||
const t = R.tileAt(world.seed, rad, xx, yy, age);
|
||||
if (t.type === 'rural' || t.type === 'incumbent') specials.push({ x: xx, y: yy, type: t.type, bonus: t.bonus || null });
|
||||
else if (t.type === 'backbone') { // end game: landing site with its holder and node level
|
||||
const v = sites.get(t.site);
|
||||
specials.push({ x: xx, y: yy, type: 'backbone', bonus: null, site: { id: v.id, index: v.index, holder: v.holder, level: v.level, maxLevel: v.maxLevel } });
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
'use strict';
|
||||
/* Registers every REST route. One file per resource; each exports register(router, services). */
|
||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports')];
|
||||
const files = [require('./auth'), require('./me'), require('./towns'), require('./map'), require('./alliances'), require('./messages'), require('./rankings'), require('./units'), require('./movements'), require('./reports'), require('./sharedReports'), require('./trade'), require('./world')];
|
||||
|
||||
function register(router, services) {
|
||||
for (const f of files) f.register(router, services);
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ const schemas = {
|
|||
}),
|
||||
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'] }, 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'] }, site: { type: 'object', additionalProperties: true } }, ['x', 'y', 'type', 'bonus']),
|
||||
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' } }),
|
||||
Notification: obj({ id: int, type: str, worldId: { type: ['integer', 'null'] }, payload: { type: 'object', additionalProperties: true }, createdAt: int, readAt: { type: ['integer', 'null'] } }),
|
||||
|
|
@ -78,5 +78,6 @@ const schemas = {
|
|||
};
|
||||
|
||||
require('./schemasMilitary')(schemas, { int, num, str, bool, obj, arr });
|
||||
require('./schemasEndgame')(schemas, { int, num, str, bool, obj, arr });
|
||||
|
||||
module.exports = { schemas, int, num, str, bool, obj, arr };
|
||||
|
|
|
|||
45
server/routes/schemasEndgame.js
Normal file
45
server/routes/schemasEndgame.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
'use strict';
|
||||
/* Response schemas of trade, the end game and the shared report folder (merged into routes/schemas.js). Documentation
|
||||
* only, like the others (test helpers can check them with createTestServer({ contract: true })). */
|
||||
module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj, arr }) {
|
||||
const nint = { type: ['integer', 'null'] };
|
||||
const nstr = { type: ['string', 'null'] };
|
||||
const free = { type: 'object', additionalProperties: true };
|
||||
const Cost = { $ref: 'Cost' };
|
||||
Object.assign(schemas, {
|
||||
// ---- trade
|
||||
TradeAmount: obj({ resource: str, amount: int }),
|
||||
TradeOffer: obj({
|
||||
id: int, status: str, worldId: int, townId: int, townName: nstr, x: nint, y: nint, operator: obj({ id: int, name: nstr }),
|
||||
give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' }, maxDistance: int, createdAt: int, expiresAt: int, acceptedAt: nint, closedAt: nint,
|
||||
role: str, acceptableFrom: arr(obj({ townId: int, distance: num })),
|
||||
}, ['id', 'status', 'townId', 'operator', 'give', 'want', 'maxDistance', 'createdAt', 'expiresAt']),
|
||||
TradeOfferList: obj({ serverTime: int, items: arr({ $ref: 'TradeOffer' }), next: nint, exchangeLevels: arr(obj({ townId: int, level: int, reach: num })) }, ['serverTime', 'items', 'next']),
|
||||
TradeOfferResponse: obj({ serverTime: int, offer: { $ref: 'TradeOffer' } }),
|
||||
TradeCancelled: obj({ serverTime: int, offerId: int, status: str, returned: { $ref: 'TradeAmount' } }),
|
||||
TradeAccepted: obj({ serverTime: int, offerId: int, status: str, goodsMovementId: int, paymentMovementId: int, distance: num, arriveAt: int, give: { $ref: 'TradeAmount' }, want: { $ref: 'TradeAmount' } }),
|
||||
// ---- end game
|
||||
LandingSite: obj({
|
||||
id: nint, index: int, x: int, y: int, holder: { type: ['object', 'null'], properties: { allianceId: int, tag: str, name: str }, additionalProperties: true },
|
||||
takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, level: int, maxLevel: int, progress: num, pool: Cost,
|
||||
build: { type: ['object', 'null'], properties: { toLevel: int, startedAt: int, dueAt: int }, additionalProperties: true },
|
||||
next: { type: ['object', 'null'], properties: { toLevel: int, cost: Cost, durationMs: int }, additionalProperties: true },
|
||||
}),
|
||||
WorldStatus: obj({
|
||||
serverTime: int, worldId: int, name: str, speed: num, status: str, phase: str, ageDays: num, openDay: int, opensAt: int,
|
||||
sites: arr({ $ref: 'LandingSite' }), winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, endedAt: nint,
|
||||
}),
|
||||
WorldResults: obj({ serverTime: int, available: bool, status: str, winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, results: { type: ['object', 'null'], additionalProperties: true } }),
|
||||
LandingSiteResponse: obj({
|
||||
serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool }),
|
||||
contributions: arr(obj({ operatorId: int, name: str, fiber: int, hardware: int, capital: int })),
|
||||
}, ['serverTime', 'site', 'you']),
|
||||
BackboneBuildStarted: obj({ serverTime: int, siteId: int, eventId: int, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
|
||||
// ---- shared reports
|
||||
ReportShared: obj({ serverTime: int, changed: bool, reportId: int, allianceId: int }),
|
||||
SharedReportItem: obj({ id: int, type: str, createdAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free }),
|
||||
SharedReportList: obj({ serverTime: int, items: arr({ $ref: 'SharedReportItem' }), next: nint }),
|
||||
SharedReport: obj({ id: int, type: str, createdAt: int, expiresAt: int, sharedAt: int, sharedBy: obj({ operatorId: int, name: str }), summary: free, data: free }),
|
||||
SharedReportResponse: obj({ serverTime: int, report: { $ref: 'SharedReport' } }),
|
||||
});
|
||||
};
|
||||
|
|
@ -17,7 +17,7 @@ module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, 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' }) }),
|
||||
MovementList: obj({ serverTime: int, outgoing: arr({ $ref: 'Movement' }), incoming: arr({ $ref: 'Movement' }), alliedIncoming: arr({ $ref: 'Movement' }) }, ['serverTime', 'outgoing', 'incoming']),
|
||||
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 }),
|
||||
|
|
|
|||
30
server/routes/sharedReports.js
Normal file
30
server/routes/sharedReports.js
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
'use strict';
|
||||
/* The alliance's shared report folder: share one of your reports, list and read the folder, take one out. */
|
||||
const { createSharedReportQueries } = require('../sharedReports');
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const folder = createSharedReportQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.post('/reports/:id/share', {
|
||||
summary: 'Put one of your reports into your alliance\'s shared folder (needs shareReport; keeps the report for another 14 days)', tag: 'reports',
|
||||
response: { $ref: 'ReportShared' }, errors: errs.concat(['not_in_alliance', 'forbidden', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('reportShare', { userId: user.id, reportId: params.id }));
|
||||
|
||||
router.del('/reports/:id/share', {
|
||||
summary: 'Take a report out of the alliance folder (whoever shared it, or leader/officer)', tag: 'reports',
|
||||
response: { $ref: 'ReportShared' }, errors: errs.concat(['forbidden', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('reportUnshare', { userId: user.id, reportId: params.id }));
|
||||
|
||||
router.get('/alliances/:id/reports', {
|
||||
summary: 'The alliance\'s shared reports, newest first (cursor: after = id of the last report seen; members only)', tag: 'reports',
|
||||
query: { type: 'object', properties: { after: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 100 } } },
|
||||
response: { $ref: 'SharedReportList' }, errors: errs.concat(['forbidden']),
|
||||
}, ({ user, params, query }) => folder.list(user.id, params.id, query));
|
||||
|
||||
router.get('/alliances/:id/reports/:reportId', {
|
||||
summary: 'One shared report with its full data (members only)', tag: 'reports', response: { $ref: 'SharedReportResponse' }, errors: errs.concat(['forbidden']),
|
||||
}, ({ user, params }) => folder.get(user.id, params.id, params.reportId));
|
||||
}
|
||||
module.exports = { register };
|
||||
53
server/routes/trade.js
Normal file
53
server/routes/trade.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
'use strict';
|
||||
/* Internet exchange: open offers, your offers, create / cancel / accept. Direct transports (to your own POPs or any player)
|
||||
* are POST /movements with type "transport". */
|
||||
const { reply } = require('../http');
|
||||
const { createTradeQueries } = require('../tradeQueries');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
const int1 = { type: 'integer', minimum: 1 };
|
||||
const res = { type: 'string', enum: D.RESOURCES };
|
||||
const page = { after: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } };
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const trade = createTradeQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.get('/trade/offers', {
|
||||
summary: 'Open offers you can take: within the offer\'s max distance and the reach of one of your Internet exchanges (newest first, cursor: after = last id seen)', tag: 'trade',
|
||||
query: { type: 'object', properties: Object.assign({ worldId: int1, townId: int1, give: res, want: res }, page) }, response: { $ref: 'TradeOfferList' }, errors: errs,
|
||||
}, ({ user, query }) => trade.offers(user.id, query));
|
||||
|
||||
router.get('/trade/offers/mine', {
|
||||
summary: 'Offers you posted or accepted, any status (newest first)', tag: 'trade',
|
||||
query: { type: 'object', properties: Object.assign({ worldId: int1, status: { type: 'string', enum: ['open', 'accepted', 'completed', 'cancelled', 'expired', 'void'] } }, page) },
|
||||
response: { $ref: 'TradeOfferList' }, errors: errs,
|
||||
}, ({ user, query }) => trade.mineOffers(user.id, query));
|
||||
|
||||
router.get('/trade/offers/:id', {
|
||||
summary: 'One offer (open ones to every operator of the world, closed ones to the two parties)', tag: 'trade', response: { $ref: 'TradeOfferResponse' }, errors: errs,
|
||||
}, ({ user, params }) => trade.offer(user.id, params.id));
|
||||
|
||||
router.post('/trade/offers', {
|
||||
summary: 'Post an offer from one of your POPs: give X of A for Y of B within a max distance. The offered amount is escrowed and a transport link reserved',
|
||||
tag: 'trade', status: 201,
|
||||
body: {
|
||||
type: 'object', required: ['townId', 'giveRes', 'giveAmount', 'wantRes', 'wantAmount', 'maxDistance'],
|
||||
properties: { townId: int1, giveRes: res, giveAmount: int1, wantRes: res, wantAmount: int1, maxDistance: { type: 'integer', minimum: 1, maximum: D.TRADE.maxDistance } },
|
||||
},
|
||||
response: { $ref: 'TradeOfferResponse' }, errors: errs.concat(['trade_ratio', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, body }) => reply(201, commands.run('tradeOffer', Object.assign({ userId: user.id }, body))));
|
||||
|
||||
router.del('/trade/offers/:id', {
|
||||
summary: 'Cancel your open offer; the escrow returns to the POP', tag: 'trade', response: { $ref: 'TradeCancelled' }, errors: errs.concat(['offer_closed', 'world_ended']),
|
||||
}, ({ user, params }) => commands.run('tradeCancel', { userId: user.id, offerId: params.id }));
|
||||
|
||||
router.post('/trade/offers/:id/accept', {
|
||||
summary: 'Take an open offer with one of your POPs: two transports leave at once (your payment, their goods) and the offer is settled when both arrive', tag: 'trade', status: 201,
|
||||
body: { type: 'object', required: ['townId'], properties: { townId: int1 } },
|
||||
response: { $ref: 'TradeAccepted' },
|
||||
errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params, body }) => reply(201, commands.run('tradeAccept', { userId: user.id, offerId: params.id, townId: body.townId })));
|
||||
}
|
||||
module.exports = { register };
|
||||
41
server/routes/world.js
Normal file
41
server/routes/world.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
'use strict';
|
||||
/* End game: the race (world status), the final results, landing sites (read, feed the stockpile, build the node). Taking a site is
|
||||
* POST /movements (scan / attack at its x,y). */
|
||||
const { reply } = require('../http');
|
||||
const { createEndgameQueries } = require('../endgameQueries');
|
||||
const D = require('../../public/js/data.js');
|
||||
|
||||
function register(router, services) {
|
||||
const { commands } = services;
|
||||
const eg = createEndgameQueries(services);
|
||||
const errs = ['unauthorized', 'not_found', 'validation_failed'];
|
||||
|
||||
router.get('/worlds/:id/status', {
|
||||
summary: 'The state of the world: phase (running, backbone_open, ended), world age, the landing sites with holder, node level, stockpile and build progress, the winner', tag: 'world',
|
||||
response: { $ref: 'WorldStatus' }, errors: errs,
|
||||
}, ({ user, params }) => eg.status(user.id, params.id));
|
||||
|
||||
router.get('/worlds/:id/results', {
|
||||
summary: 'The final ranking snapshot (operators, alliances, attackers, defenders, winner); available once the world has ended', tag: 'world',
|
||||
response: { $ref: 'WorldResults' }, errors: errs,
|
||||
}, ({ user, params }) => eg.results(user.id, params.id));
|
||||
|
||||
router.get('/backbone/:id', {
|
||||
summary: 'One landing site; members of the holding alliance also see the contribution ledger and what they may do', tag: 'world',
|
||||
response: { $ref: 'LandingSiteResponse' }, errors: errs,
|
||||
}, ({ user, params }) => eg.site(user.id, params.id));
|
||||
|
||||
router.post('/backbone/:id/ship', {
|
||||
summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)', tag: 'world', status: 201,
|
||||
body: { type: 'object', required: ['fromTownId', 'cargo'], properties: { fromTownId: { type: 'integer', minimum: 1 }, cargo: { type: 'object', additionalProperties: true, description: 'fiber/hardware/capital -> amount' } } },
|
||||
response: { $ref: 'MovementSent' },
|
||||
errors: errs.concat(['forbidden', 'backbone_closed', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params, body }) => reply(201, commands.run('backboneShip', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, cargo: body.cargo })));
|
||||
|
||||
router.post('/backbone/:id/build', {
|
||||
summary: 'Start the next Backbone node level on a landing site your alliance holds (paid from the site\'s stockpile; one level at a time, up to level ' + D.ENDGAME.maxLevel + ')', tag: 'world', status: 201,
|
||||
response: { $ref: 'BackboneBuildStarted' },
|
||||
errors: errs.concat(['forbidden', 'backbone_closed', 'max_level', 'already_queued', 'not_enough_resources', 'world_ended']),
|
||||
}, ({ user, params }) => reply(201, commands.run('backboneBuild', { userId: user.id, siteId: params.id })));
|
||||
}
|
||||
module.exports = { register };
|
||||
|
|
@ -19,6 +19,21 @@ class Scheduler {
|
|||
this.autoArm = autoArm !== false;
|
||||
this.timer = null; this.running = false; this.closed = false;
|
||||
this.onEvent = null; // optional hook: (event) => void after each processed event (push, tests)
|
||||
// Notification outbox (stage 6 push): every notify() row is also queued here and handed to onNotify only AFTER the
|
||||
// transaction that wrote it committed, so a rolled-back change never pushes. Nothing is queued without a listener.
|
||||
this.onNotify = null; // optional hook: ({ id, userId, worldId, type, payload }) => void, post-commit
|
||||
this.outbox = [];
|
||||
}
|
||||
|
||||
// Outbox helpers for code that owns a transaction (process() below, commands.run).
|
||||
outboxMark() { return this.outbox.length; }
|
||||
outboxRollback(mark) { if (this.outbox.length > mark) this.outbox.length = mark; }
|
||||
// Deliver queued notifications. A no-op inside a transaction: the outermost commit delivers them.
|
||||
flushOutbox() {
|
||||
if (!this.outbox.length || this.db.depth > 0) return;
|
||||
const items = this.outbox; this.outbox = [];
|
||||
if (!this.onNotify) return;
|
||||
for (const n of items) { try { this.onNotify(n); } catch (e) { this.log('onNotify hook failed: ' + e.message); } }
|
||||
}
|
||||
|
||||
register(type, fn) { this.handlers[type] = fn; }
|
||||
|
|
@ -30,9 +45,13 @@ class Scheduler {
|
|||
return Number(r.lastInsertRowid);
|
||||
}
|
||||
|
||||
// Write a notification row (call inside the transaction of the change it announces). Returns the row id.
|
||||
notify(userId, worldId, type, payload) {
|
||||
this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
const r = this.db.run('INSERT INTO notifications (user_id, world_id, type, payload, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
userId, worldId === undefined ? null : worldId, type, JSON.stringify(payload || {}), this.clock.now());
|
||||
const id = Number(r.lastInsertRowid);
|
||||
if (this.onNotify) { this.outbox.push({ id, userId, worldId: worldId === undefined ? null : worldId, type, payload: payload || {} }); this.flushOutbox(); }
|
||||
return id;
|
||||
}
|
||||
|
||||
next() { return this.db.get("SELECT id, due_at FROM events WHERE status = 'pending' ORDER BY due_at, id LIMIT 1"); }
|
||||
|
|
@ -58,6 +77,7 @@ class Scheduler {
|
|||
process(ev) {
|
||||
const handler = this.handlers[ev.type];
|
||||
const event = { id: ev.id, worldId: ev.world_id, dueAt: ev.due_at, type: ev.type, townId: ev.town_id, payload: JSON.parse(ev.payload) };
|
||||
const mark = this.outboxMark();
|
||||
try {
|
||||
this.db.tx(() => {
|
||||
if (!handler) throw new Error('no handler for event type ' + ev.type);
|
||||
|
|
@ -65,10 +85,12 @@ class Scheduler {
|
|||
this.db.run("UPDATE events SET status = 'done', done_at = ? WHERE id = ?", this.clock.now(), ev.id);
|
||||
});
|
||||
} catch (err) {
|
||||
this.outboxRollback(mark);
|
||||
this.log('event ' + ev.id + ' (' + ev.type + ') failed: ' + (err && err.stack || err));
|
||||
this.db.run("UPDATE events SET status = 'failed', done_at = ?, error = ? WHERE id = ?", this.clock.now(), String(err && err.message || err).slice(0, 500), ev.id);
|
||||
return;
|
||||
}
|
||||
this.flushOutbox();
|
||||
if (this.onEvent) { try { this.onEvent(event); } catch (e) { this.log('onEvent hook failed: ' + e.message); } }
|
||||
}
|
||||
|
||||
|
|
|
|||
35
server/sharedReports.js
Normal file
35
server/sharedReports.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
'use strict';
|
||||
/* Read model of the alliance's shared report folder. Newest first, `after` = id of the last report you have (older ones
|
||||
* follow), like GET /reports. Members with `viewSharedReports` only. */
|
||||
const { GameError } = require('./errors');
|
||||
const A = require('./alliances');
|
||||
|
||||
const j = (s) => JSON.parse(s || '{}');
|
||||
|
||||
function createSharedReportQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
|
||||
function list(userId, allianceId, { after, limit }) {
|
||||
const now = fresh();
|
||||
A.requireRole(db, userId, allianceId, 'viewSharedReports');
|
||||
const n = limit || 25;
|
||||
const rows = db.all(`SELECT r.id, r.type, r.created_at, r.summary, s.created_at AS shared_at, s.shared_by, o.name AS shared_name
|
||||
FROM report_shares s JOIN reports r ON r.id = s.report_id JOIN operators o ON o.id = s.shared_by
|
||||
WHERE s.alliance_id = ? ${after ? 'AND r.id < ?' : ''} ORDER BY r.id DESC LIMIT ?`, ...(after ? [allianceId, after, n + 1] : [allianceId, n + 1]));
|
||||
const items = rows.slice(0, n).map((r) => ({ id: r.id, type: r.type, createdAt: r.created_at, sharedAt: r.shared_at, sharedBy: { operatorId: r.shared_by, name: r.shared_name }, summary: j(r.summary) }));
|
||||
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null };
|
||||
}
|
||||
|
||||
function get(userId, allianceId, reportId) {
|
||||
const now = fresh();
|
||||
A.requireRole(db, userId, allianceId, 'viewSharedReports');
|
||||
const r = db.get(`SELECT r.*, s.created_at AS shared_at, s.shared_by, o.name AS shared_name FROM report_shares s JOIN reports r ON r.id = s.report_id JOIN operators o ON o.id = s.shared_by
|
||||
WHERE s.alliance_id = ? AND r.id = ?`, allianceId, reportId);
|
||||
if (!r) throw new GameError('not_found', { what: 'shared report' });
|
||||
return { serverTime: now, report: { id: r.id, type: r.type, createdAt: r.created_at, expiresAt: r.expires_at, sharedAt: r.shared_at, sharedBy: { operatorId: r.shared_by, name: r.shared_name }, summary: j(r.summary), data: j(r.data) } };
|
||||
}
|
||||
|
||||
return { list, get };
|
||||
}
|
||||
|
||||
module.exports = { createSharedReportQueries };
|
||||
|
|
@ -305,7 +305,7 @@ function createSocialQueries({ db, clock, scheduler }) {
|
|||
|
||||
return {
|
||||
mine, list, get, members, invitesSent, invitesReceived, notes, diplomacy,
|
||||
rankOperators, rankAlliances, rankBattles,
|
||||
rankOperators, rankAlliances, rankBattles, footprints,
|
||||
inbox, outbox, thread, allianceFeed, message, blocks, footprints,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
88
server/trade.js
Normal file
88
server/trade.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Internet exchange trade: shared helpers of the trade commands, the expiry event and the read model.
|
||||
*
|
||||
* Offer life cycle (table trade_offers, status):
|
||||
* open the offered amount is ESCROWED in the row (it left the POP at creation) and one transport link of the poster's POP is
|
||||
* held in reserve (military/movements.activeLinks counts open offers)
|
||||
* accepted two transports are on the road: poster -> acceptor carries the escrow, acceptor -> poster carries the payment
|
||||
* completed both legs were delivered (the `transportArrived` hook below)
|
||||
* cancelled the poster took it back: the escrow is credited to the POP again
|
||||
* expired ttl ran out (event `tradeExpire`): same
|
||||
* void the poster's POP changed hands while the offer was open: the escrow stays in that POP (it goes with the POP)
|
||||
* Nothing is created or lost: escrow is returned WITHOUT the Rack hall cap (an amount above the cap is kept, it only stops
|
||||
* growing); the only loss anywhere is what a delivery cannot store (the existing cargoLost rule of transports).
|
||||
*/
|
||||
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 COL = { fiber: 'fiber', hardware: 'hardware', capital: 'capital' };
|
||||
|
||||
// Credit `amount` of `res` to a POP (settled first, no storage cap: it is a refund of what left the POP).
|
||||
function refund(db, townId, res, amount, at) {
|
||||
const town = loadTown(db, townId);
|
||||
if (!town) return;
|
||||
settle(db, town, at);
|
||||
db.run('UPDATE towns SET ' + COL[res] + ' = ' + COL[res] + ' + ? WHERE id = ?', amount, townId);
|
||||
}
|
||||
|
||||
const getOffer = (db, id) => db.get('SELECT * FROM trade_offers WHERE id = ?', id) || null;
|
||||
|
||||
function expiryMs(speed) { return Math.round(D.TRADE.ttlHours * D.HOUR_MS / (speed || 1)); }
|
||||
|
||||
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
|
||||
|
||||
// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> the offer row (before)
|
||||
function closeOffer(ctx, offer, status, at) {
|
||||
const { db } = ctx;
|
||||
db.run('UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?', status, at, offer.id);
|
||||
if (offer.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", at, offer.expire_event_id);
|
||||
refund(db, offer.town_id, offer.give_res, offer.give_amount, at);
|
||||
return offer;
|
||||
}
|
||||
|
||||
// A POP changed hands (takeover): its open offers end and the escrow stays with the POP. Called from combat.transferTown.
|
||||
function onTownTransferred(ctx, townId, at) {
|
||||
const { db } = ctx;
|
||||
for (const o of db.all("SELECT * FROM trade_offers WHERE town_id = ? AND status = 'open'", townId)) {
|
||||
closeOffer(ctx, o, 'void', at);
|
||||
const uid = userOfOperator(db, o.operator_id);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_void', { offerId: o.id, townId });
|
||||
}
|
||||
}
|
||||
|
||||
// `transportArrived` consumer: both legs of an accepted offer delivered -> completed.
|
||||
function onTransportArrived(ctx, mv, res) {
|
||||
const tradeId = mv.extra && mv.extra.tradeId;
|
||||
if (!tradeId) return;
|
||||
const { db } = ctx;
|
||||
const o = getOffer(db, tradeId);
|
||||
if (!o || o.status !== 'accepted') return;
|
||||
const legs = o.legs_done + 1;
|
||||
if (legs < 2) { db.run('UPDATE trade_offers SET legs_done = ? WHERE id = ?', legs, o.id); return; }
|
||||
db.run("UPDATE trade_offers SET legs_done = ?, status = 'completed', closed_at = ? WHERE id = ?", legs, ctx.now, o.id);
|
||||
const body = { offerId: o.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } };
|
||||
for (const opId of [o.operator_id, o.accepted_by_operator]) {
|
||||
const uid = userOfOperator(db, opId);
|
||||
if (uid) ctx.notify(uid, o.world_id, 'trade_completed', body);
|
||||
}
|
||||
}
|
||||
|
||||
// Registered once, whoever requires this module first (commands and events both do): tests and the server see the same wiring.
|
||||
if (!M.hooks.transportArrived.some((f) => f.name === 'tradeTransportArrived')) {
|
||||
M.hooks.transportArrived.push(function tradeTransportArrived(ctx, mv, res) { return onTransportArrived(ctx, mv, res); });
|
||||
}
|
||||
|
||||
function offerView(db, o, towns) {
|
||||
const t = towns && towns.get(o.town_id);
|
||||
return {
|
||||
id: o.id, status: o.status, worldId: o.world_id, townId: o.town_id, townName: t ? t.name : null, x: t ? t.x : null, y: t ? t.y : null,
|
||||
operator: { id: o.operator_id, name: (db.get('SELECT name FROM operators WHERE id = ?', o.operator_id) || {}).name || null },
|
||||
give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
|
||||
maxDistance: o.max_distance, createdAt: o.created_at, expiresAt: o.expires_at, acceptedAt: o.accepted_at, closedAt: o.closed_at,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { refund, getOffer, expiryMs, closeOffer, onTownTransferred, onTransportArrived, offerView, userOfOperator };
|
||||
82
server/tradeQueries.js
Normal file
82
server/tradeQueries.js
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
'use strict';
|
||||
/*
|
||||
* Read models of the Internet exchange: the open offers you can see and take, your own offers, one offer. Reads catch the event
|
||||
* queue up first. Lists are newest first, `after` = id of the last offer you have (older ones follow).
|
||||
* Visibility: an open offer of somebody else is listed when one of your POPs (the one in `townId`, or any) has an Internet
|
||||
* exchange and the poster's POP is within min(the offer's max distance, that exchange's reach). `acceptableFrom` names those POPs.
|
||||
*/
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const { GameError } = require('./errors');
|
||||
const A = require('./alliances');
|
||||
const T = require('./trade');
|
||||
|
||||
function createTradeQueries({ db, clock, scheduler }) {
|
||||
const fresh = () => { scheduler.runDue(); return clock.now(); };
|
||||
const townsOf = (ids) => {
|
||||
const m = new Map();
|
||||
for (const id of ids) if (!m.has(id)) m.set(id, db.get('SELECT id, name, x, y FROM towns WHERE id = ?', id));
|
||||
return m;
|
||||
};
|
||||
|
||||
// My POPs with an exchange: [{ id, x, y, level }].
|
||||
function exchanges(operatorId, townId) {
|
||||
const rows = db.all(`SELECT t.id, t.x, t.y, b.level AS level FROM towns t JOIN buildings b ON b.town_id = t.id AND b.type = ? WHERE t.owner_id = ? AND b.level >= 1 ${townId ? 'AND t.id = ?' : ''} ORDER BY t.id`,
|
||||
...[D.TRANSPORT.building, operatorId].concat(townId ? [townId] : []));
|
||||
return rows;
|
||||
}
|
||||
|
||||
function offers(userId, { worldId, townId, give, want, after, limit }) {
|
||||
const now = fresh();
|
||||
const op = A.operatorOf(db, userId, worldId);
|
||||
if (townId && !db.get('SELECT 1 AS x FROM towns WHERE id = ? AND owner_id = ?', townId, op.id)) throw new GameError('not_found', { what: 'town' });
|
||||
const mine = exchanges(op.id, townId);
|
||||
const n = limit || 25;
|
||||
const out = [];
|
||||
let next = null;
|
||||
if (mine.length) {
|
||||
// newest first in chunks: the range filter drops rows, so keep reading until a page is full or the offers are used up
|
||||
let cur = after || 0, done = false;
|
||||
while (!done && !next) {
|
||||
const rows = db.all(`SELECT o.*, t.x AS tx, t.y AS ty FROM trade_offers o JOIN towns t ON t.id = o.town_id WHERE o.world_id = ? AND o.status = 'open' AND o.operator_id != ?
|
||||
${give ? 'AND o.give_res = ?' : ''} ${want ? 'AND o.want_res = ?' : ''} ${cur ? 'AND o.id < ?' : ''} ORDER BY o.id DESC LIMIT ?`,
|
||||
...[op.world_id, op.id].concat(give ? [give] : [], want ? [want] : [], cur ? [cur] : [], [D.TRADE.scanChunk]));
|
||||
const towns = townsOf(rows.map((r) => r.town_id));
|
||||
for (const r of rows) {
|
||||
cur = r.id;
|
||||
const from = mine.map((m) => ({ townId: m.id, distance: R.distance(m.x, m.y, r.tx, r.ty), level: m.level })).filter((m) => R.tradeInRange(m.distance, r.max_distance, m.level));
|
||||
if (!from.length) continue;
|
||||
if (out.length === n) { next = out[out.length - 1].id; break; }
|
||||
out.push(Object.assign(T.offerView(db, r, towns), { acceptableFrom: from.map((m) => ({ townId: m.townId, distance: m.distance })) }));
|
||||
}
|
||||
done = rows.length < D.TRADE.scanChunk;
|
||||
}
|
||||
}
|
||||
return { serverTime: now, items: out, next, exchangeLevels: mine.map((m) => ({ townId: m.id, level: m.level, reach: R.tradeReach(m.level) })) };
|
||||
}
|
||||
|
||||
function mineOffers(userId, { worldId, after, limit, status }) {
|
||||
const now = fresh();
|
||||
const op = A.operatorOf(db, userId, worldId);
|
||||
const n = limit || 25;
|
||||
const rows = db.all(`SELECT * FROM trade_offers WHERE (operator_id = ? OR accepted_by_operator = ?) ${status ? 'AND status = ?' : ''} ${after ? 'AND id < ?' : ''} ORDER BY id DESC LIMIT ?`,
|
||||
...[op.id, op.id].concat(status ? [status] : [], after ? [after] : [], [n + 1]));
|
||||
const towns = townsOf(rows.map((r) => r.town_id));
|
||||
const items = rows.slice(0, n).map((r) => Object.assign(T.offerView(db, r, towns), { role: r.operator_id === op.id ? 'poster' : 'acceptor' }));
|
||||
return { serverTime: now, items, next: rows.length > n ? items[items.length - 1].id : null };
|
||||
}
|
||||
|
||||
// One offer: open ones are public inside the world (to operators of it), the rest only to the two parties.
|
||||
function offer(userId, id) {
|
||||
const now = fresh();
|
||||
const o = T.getOffer(db, id);
|
||||
const op = o ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, o.world_id) : null;
|
||||
if (!o || !op) throw new GameError('not_found', { what: 'offer' });
|
||||
if (o.status !== 'open' && o.operator_id !== op.id && o.accepted_by_operator !== op.id) throw new GameError('not_found', { what: 'offer' });
|
||||
return { serverTime: now, offer: Object.assign(T.offerView(db, o, townsOf([o.town_id])), { role: o.operator_id === op.id ? 'poster' : (o.accepted_by_operator === op.id ? 'acceptor' : 'viewer') }) };
|
||||
}
|
||||
|
||||
return { offers, mineOffers, offer };
|
||||
}
|
||||
|
||||
module.exports = { createTradeQueries };
|
||||
|
|
@ -3,6 +3,10 @@ const test = require('node:test');
|
|||
const assert = require('node:assert');
|
||||
const I = require('../public/js/i18n.js');
|
||||
const D = require('../public/js/data.js');
|
||||
// Strings added by later screens: public/js/strings/*.js, loaded for the parity test the same way the browser loads them.
|
||||
for (const f of require('fs').readdirSync(require('path').join(__dirname, '..', 'public', 'js', 'strings')).sort()) {
|
||||
if (f.endsWith('.js')) require('../public/js/strings/' + f);
|
||||
}
|
||||
|
||||
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(',');
|
||||
|
||||
|
|
|
|||
83
test/client-mil.test.js
Normal file
83
test/client-mil.test.js
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const M = require('../public/js/milcore.js');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
const land = (settle) => ({ x: 3, y: 4, type: 'land', settle: Object.assign({ possible: true, code: null, footprint: 100, footprintNeeded: 50, maxDistance: 15 }, settle) });
|
||||
const rival = (owner) => ({ x: 5, y: 5, type: 'pop', town: { id: 9, name: 'R', mine: false, owner: Object.assign({ id: 2, protected: false, allianceId: null }, owner) } });
|
||||
const types = (o) => o.map((x) => x.type + (x.ok ? '' : '!'));
|
||||
|
||||
test('unitsForType: roles, fixed units and zero counts are filtered', () => {
|
||||
const home = { script_crew: 5, honeypot: 3, port_scanner: 2, soc_analyst: 0, rollout_crew: 3 };
|
||||
assert.deepStrictEqual(M.unitsForType('raid', home).map((u) => u.unit), ['script_crew']); // honeypot is fixed, scanner is a scout
|
||||
assert.deepStrictEqual(M.unitsForType('scan', home).map((u) => u.unit), ['port_scanner']);
|
||||
assert.deepStrictEqual(M.unitsForType('settle', home).map((u) => u.unit), ['rollout_crew']);
|
||||
assert.deepStrictEqual(M.unitsForType('reinforce', home).map((u) => u.unit), ['port_scanner', 'script_crew', 'rollout_crew']);
|
||||
assert.deepStrictEqual(M.unitsForType('transport', home), []);
|
||||
});
|
||||
|
||||
test('moveOptions on a rival POP: hostile types need units, protection blocks them, takeover needs an M&A team', () => {
|
||||
const home = { script_crew: 10, port_scanner: 1 };
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: rival(), home })), ['scan', 'raid', 'attack', 'takeover!']);
|
||||
assert.strictEqual(M.moveOptions({ tile: rival(), home }).find((o) => o.type === 'takeover').reason, 'needs_ma_team');
|
||||
const prot = M.moveOptions({ tile: rival({ protected: true }), home });
|
||||
assert.deepStrictEqual(types(prot), ['scan', 'raid!', 'attack!', 'takeover!']);
|
||||
assert.strictEqual(prot[1].reason, 'target_protected');
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: rival(), home: {} })), ['scan!', 'raid!', 'attack!', 'takeover!']);
|
||||
assert.ok(M.moveOptions({ tile: rival(), home: { ma_team: 1, script_crew: 1 } }).find((o) => o.type === 'takeover').ok);
|
||||
});
|
||||
|
||||
test('moveOptions: reinforce only for the same alliance; own POP offers reinforce and transport', () => {
|
||||
const home = { soc_analyst: 4 };
|
||||
const ally = rival({ allianceId: 7 });
|
||||
assert.ok(!M.moveOptions({ tile: ally, home, allianceId: 5 }).some((o) => o.type === 'reinforce'));
|
||||
assert.ok(M.moveOptions({ tile: ally, home, allianceId: 7 }).some((o) => o.type === 'reinforce' && o.ok));
|
||||
const mine = { x: 1, y: 1, type: 'pop', town: { id: 3, mine: true, owner: { id: 1 } } };
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: mine, home, transport: { links: 2, active: 2 } })), ['reinforce', 'transport!']);
|
||||
assert.strictEqual(M.moveOptions({ tile: mine, home, transport: { links: 0, active: 0 } })[1].reason, 'no_link');
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: mine, home, transport: { links: 2, active: 1 } })), ['reinforce', 'transport']);
|
||||
});
|
||||
|
||||
test('moveOptions: incumbent sites take scan and attack; land offers settle with its reason; rural nothing', () => {
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: { type: 'incumbent' }, home: { port_scanner: 1, script_crew: 1 } })), ['scan', 'attack']);
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: land(), home: {}, crews: 3 })), ['settle']);
|
||||
assert.deepStrictEqual(types(M.moveOptions({ tile: land(), home: {}, crews: 2 })), ['settle!']);
|
||||
const far = M.moveOptions({ tile: land({ possible: false, code: 'out_of_range' }), home: {}, crews: 3 });
|
||||
assert.strictEqual(far[0].reason, 'settle:out_of_range');
|
||||
assert.deepStrictEqual(M.moveOptions({ tile: { type: 'rural' }, home: { script_crew: 1 } }), []);
|
||||
});
|
||||
|
||||
test('defaultUnits / cleanSelection / preview', () => {
|
||||
assert.deepStrictEqual(M.defaultUnits('settle', {}), { rollout_crew: D.EXPANSION.crews });
|
||||
assert.deepStrictEqual(M.defaultUnits('raid', {}), {});
|
||||
assert.deepStrictEqual(M.cleanSelection({ a: 0, script_crew: 99, botnet: 2.7 }, { script_crew: 5, botnet: 1 }), { script_crew: 5, botnet: 1 });
|
||||
const p = M.preview('raid', { x: 0, y: 0 }, { x: 16, y: 0 }, { script_crew: 10, botnet: 1 }, {}, 1);
|
||||
assert.strictEqual(p.dist, 16);
|
||||
assert.strictEqual(p.slowest, 8); // script crew 8 tiles/h
|
||||
assert.strictEqual(p.ms, 2 * 3600 * 1000);
|
||||
assert.strictEqual(p.carry, 10 * 50 + 150);
|
||||
assert.strictEqual(M.preview('transport', { x: 0, y: 0 }, { x: 12, y: 0 }, {}, { fiber: 5 }, 2).ms, 30 * 60 * 1000); // 12 tiles at 12/h and speed 2x = 30 min
|
||||
});
|
||||
|
||||
test('perspective: the report role decides who won', () => {
|
||||
assert.strictEqual(M.perspective('attacker', 'attacker_won'), 'victory');
|
||||
assert.strictEqual(M.perspective('attacker', 'defender_won'), 'defeat');
|
||||
assert.strictEqual(M.perspective('defender', 'attacker_won'), 'defeat');
|
||||
assert.strictEqual(M.perspective('reinforcer', 'defender_won'), 'victory');
|
||||
});
|
||||
|
||||
test('backoffMs grows to a 60 s cap with +-25% jitter', () => {
|
||||
assert.strictEqual(M.backoffMs(0, 0.5), 1000);
|
||||
assert.strictEqual(M.backoffMs(1, 0.5), 2000);
|
||||
assert.strictEqual(M.backoffMs(3, 0.5), 8000);
|
||||
assert.strictEqual(M.backoffMs(20, 0.5), 60000);
|
||||
assert.strictEqual(M.backoffMs(2, 0), 3000);
|
||||
assert.ok(M.backoffMs(2, 0.999) >= 4990 && M.backoffMs(2, 0.999) <= 5000);
|
||||
});
|
||||
|
||||
test('siegeTargets are infrastructure types only', () => {
|
||||
const t = M.siegeTargets();
|
||||
assert.ok(t.includes('firewall') && t.includes('core_router'));
|
||||
assert.ok(!t.includes('backbone_node') && !t.some((k) => D.BUILDINGS[k].kind !== 'infra'));
|
||||
});
|
||||
161
test/client-social.test.js
Normal file
161
test/client-social.test.js
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const I = require('../public/js/i18n.js');
|
||||
const D = require('../public/js/data.js');
|
||||
const Soc = require('../public/js/social.js');
|
||||
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
|
||||
|
||||
const S = D.SOCIAL;
|
||||
|
||||
test('selfActions follows the permission table and the leader-must-transfer rule', () => {
|
||||
const leader = Soc.selfActions('leader', 4), officer = Soc.selfActions('officer', 4), diplomat = Soc.selfActions('diplomat', 4), member = Soc.selfActions('member', 4);
|
||||
assert.ok(leader.invite && leader.disband && leader.diplomacy && leader.editNotes && leader.transfer && leader.setRole);
|
||||
assert.ok(leader.leaveNeedsTransfer);
|
||||
assert.ok(!Soc.selfActions('leader', 1).leaveNeedsTransfer, 'alone: leaving disbands, no transfer needed');
|
||||
assert.ok(officer.invite && officer.viewInvites && officer.editNotes && !officer.diplomacy && !officer.disband && !officer.setRole);
|
||||
assert.ok(diplomat.diplomacy && diplomat.editNotes && !diplomat.invite);
|
||||
assert.ok(member.broadcast && !member.invite && !member.editNotes && !member.diplomacy && member.leave && !member.leaveNeedsTransfer);
|
||||
const none = Soc.selfActions(null, 0);
|
||||
assert.ok(!none.leave && !none.invite && !none.broadcast);
|
||||
// every key of SOCIAL.permissions the screens use is derived, not copied
|
||||
for (const [k, roles] of Object.entries(S.permissions)) {
|
||||
for (const r of S.roles) {
|
||||
const a = Soc.selfActions(r, 3);
|
||||
if (a[k] !== undefined) assert.strictEqual(a[k], roles.includes(r), k + ' for ' + r);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('memberActions: kick needs permission and strictly higher rank, roles and transfer are leader-only, never on yourself', () => {
|
||||
const m = (role, id) => ({ operatorId: id || 7, role });
|
||||
const lead = Soc.memberActions('leader', m('officer'), 1);
|
||||
assert.ok(lead.kick && lead.transfer && lead.message);
|
||||
assert.deepStrictEqual(lead.roles.sort(), ['diplomat', 'member']);
|
||||
assert.deepStrictEqual(Soc.memberActions('leader', m('member'), 1).roles.sort(), ['diplomat', 'officer']);
|
||||
const off = Soc.memberActions('officer', m('member'), 1);
|
||||
assert.ok(off.kick && !off.transfer && off.roles.length === 0);
|
||||
assert.ok(!Soc.memberActions('officer', m('officer'), 1).kick, 'equal rank');
|
||||
assert.ok(!Soc.memberActions('officer', m('leader'), 1).kick, 'higher rank');
|
||||
assert.ok(!Soc.memberActions('diplomat', m('member'), 1).kick, 'no kick permission');
|
||||
assert.ok(!Soc.memberActions('member', m('member'), 1).kick);
|
||||
const self = Soc.memberActions('leader', m('leader', 1), 1);
|
||||
assert.ok(self.self && !self.kick && !self.transfer && !self.message && self.roles.length === 0);
|
||||
assert.strictEqual(Soc.memberActions('leader', m('leader', 9), 1).roles.length, 0, 'the leader role is only moved by transfer');
|
||||
});
|
||||
|
||||
test('diplomacyOptions mirrors SOCIAL.diplomacyMoves and locks pending pairs', () => {
|
||||
const kinds = (from) => Object.fromEntries(Soc.diplomacyOptions(from, null).map((o) => [o.state, o.kind]));
|
||||
assert.deepStrictEqual(kinds('neutral'), { war: 'immediate', nap: 'proposal', confed: 'proposal' });
|
||||
assert.deepStrictEqual(kinds('nap'), { war: 'delayed', neutral: 'delayed', confed: 'proposal' });
|
||||
assert.deepStrictEqual(kinds('confed'), { war: 'delayed', neutral: 'delayed', nap: 'delayed' });
|
||||
assert.deepStrictEqual(kinds('war'), { neutral: 'proposal', nap: 'proposal' }, 'war -> confed is not allowed');
|
||||
assert.deepStrictEqual(Soc.diplomacyOptions('nap', { to: 'neutral' }), []);
|
||||
});
|
||||
|
||||
test('relationTo defaults to neutral and exposes pending changes', () => {
|
||||
const rels = [{ other: { id: 5 }, state: 'nap', since: 10, pending: { to: 'neutral', effectiveAt: 99, byUs: true } }];
|
||||
assert.deepStrictEqual(Soc.relationTo(rels, 6), { state: 'neutral', since: null, pending: null });
|
||||
assert.strictEqual(Soc.relationTo(rels, 5).state, 'nap');
|
||||
assert.strictEqual(Soc.relationTo(rels, 5).pending.byUs, true);
|
||||
assert.strictEqual(Soc.pendingRemaining({ effectiveAt: 1000 }, 400), 600);
|
||||
assert.strictEqual(Soc.pendingRemaining({ effectiveAt: 1000 }, 5000), 0);
|
||||
assert.strictEqual(Soc.pendingRemaining(null, 5), 0);
|
||||
});
|
||||
|
||||
test('character counting matches the server: code points, CRLF as one', () => {
|
||||
assert.strictEqual(Soc.charCount('abc'), 3);
|
||||
assert.strictEqual(Soc.charCount('a\r\nb'), 3);
|
||||
assert.strictEqual(Soc.charCount('\u{1F680}\u{1F680}'), 2, 'astral characters count once');
|
||||
assert.strictEqual(Soc.charCount(null), 0);
|
||||
const ok = Soc.composeState('x'.repeat(S.messageMax));
|
||||
assert.ok(!ok.over && ok.left === 0 && !ok.empty);
|
||||
assert.ok(Soc.composeState('x'.repeat(S.messageMax + 1)).over);
|
||||
assert.ok(Soc.composeState(' \n ').empty);
|
||||
assert.ok(Soc.composeState('').empty);
|
||||
assert.strictEqual(Soc.composeState('abc', 10).left, 7);
|
||||
});
|
||||
|
||||
test('retrySeconds is at least 1 and rounds up', () => {
|
||||
assert.strictEqual(Soc.retrySeconds({ retryAfter: 12.2 }), 13);
|
||||
assert.strictEqual(Soc.retrySeconds({ retryAfter: 0 }), 1);
|
||||
assert.strictEqual(Soc.retrySeconds(null), 1);
|
||||
});
|
||||
|
||||
test('message lists merge without duplicates, newest first; conversations read oldest first', () => {
|
||||
const a = [{ id: 9 }, { id: 8 }], b = [{ id: 8 }, { id: 7 }, { id: 6 }];
|
||||
assert.deepStrictEqual(Soc.mergeMessages(a, b).map((m) => m.id), [9, 8, 7, 6]);
|
||||
assert.deepStrictEqual(Soc.chronological([{ id: 3 }, { id: 1 }, { id: 2 }]).map((m) => m.id), [1, 2, 3]);
|
||||
assert.deepStrictEqual(a.map((m) => m.id), [9, 8], 'inputs are not mutated');
|
||||
});
|
||||
|
||||
test('peerOf and unreadIds', () => {
|
||||
const inMsg = { id: 1, direction: 'in', from: { operatorId: 2, name: 'b' }, to: { operatorId: 1, name: 'a' }, readAt: null };
|
||||
const outMsg = { id: 2, direction: 'out', from: { operatorId: 1, name: 'a' }, to: { operatorId: 2, name: 'b' }, readAt: null };
|
||||
const read = { id: 3, direction: 'in', readAt: 5 };
|
||||
assert.strictEqual(Soc.peerOf(inMsg).operatorId, 2);
|
||||
assert.strictEqual(Soc.peerOf(outMsg).operatorId, 2);
|
||||
assert.deepStrictEqual(Soc.unreadIds([inMsg, outMsg, read]), [1], 'own messages and read ones are not unread');
|
||||
});
|
||||
|
||||
test('ranking pages merge by rank and your row is recognised per kind', () => {
|
||||
const p1 = [{ rank: 1 }, { rank: 2 }], p2 = [{ rank: 2 }, { rank: 3 }];
|
||||
assert.deepStrictEqual(Soc.mergeRanks(p1, p2).map((r) => r.rank), [1, 2, 3]);
|
||||
assert.ok(Soc.isYou('operators', { operatorId: 4 }, { operatorId: 4, rank: 9 }));
|
||||
assert.ok(!Soc.isYou('operators', { operatorId: 5 }, { operatorId: 4 }));
|
||||
assert.ok(Soc.isYou('alliances', { allianceId: 2 }, { allianceId: 2 }));
|
||||
assert.ok(Soc.isYou('battles', { operatorId: 4 }, { operatorId: 4 }));
|
||||
assert.ok(!Soc.isYou('operators', { operatorId: 4 }, null));
|
||||
const r = { attackPoints: 30, defensePoints: 12 };
|
||||
assert.deepStrictEqual(['attack', 'defense', 'total'].map((by) => Soc.battlePoints(r, by)), [30, 12, 42]);
|
||||
});
|
||||
|
||||
test('cleanName collapses whitespace; sinceMs handles never-online', () => {
|
||||
assert.strictEqual(Soc.cleanName(' Bob the Builder '), 'Bob the Builder');
|
||||
assert.strictEqual(Soc.cleanName(null), '');
|
||||
assert.strictEqual(Soc.sinceMs(null, 100), null);
|
||||
assert.strictEqual(Soc.sinceMs(40, 100), 60);
|
||||
assert.strictEqual(Soc.sinceMs(400, 100), 0);
|
||||
});
|
||||
|
||||
// ---- strings: every key the three screens use exists in both languages, every role/state/kind has a name
|
||||
const dir = path.join(__dirname, '..', 'public', 'js', 'screens');
|
||||
const SRC = ['alliance.js', 'messages.js', 'rankings.js', 'social-ui.js'].map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join('\n');
|
||||
|
||||
test('every static i18n key used by the social screens exists in en and nb', () => {
|
||||
const used = new Set();
|
||||
for (const m of SRC.matchAll(/\bApp\.t\('([a-zA-Z0-9_.]+)'/g)) if (!m[1].endsWith('.')) used.add(m[1]);
|
||||
for (const m of SRC.matchAll(/\bt: '([a-zA-Z0-9_.]+)'/g)) used.add(m[1]);
|
||||
assert.ok(used.size > 100, 'found the keys (' + used.size + ')');
|
||||
for (const l of I.LANGS) for (const k of used) assert.ok(I.strings[l][k], l + ' is missing ' + k);
|
||||
});
|
||||
|
||||
test('dynamic i18n key families are complete', () => {
|
||||
const need = [];
|
||||
for (const r of S.roles) need.push('soc.role.' + r);
|
||||
for (const s of S.diplomacyStates) need.push('soc.state.' + s);
|
||||
for (const k of ['immediate', 'proposal', 'delayed']) need.push('soc.kind.' + k, 'soc.kind.' + k + '.hint');
|
||||
for (const k of ['applied', 'proposed', 'scheduled']) need.push('soc.dip.result.' + k);
|
||||
for (const k of ['inbox', 'sent', 'alliance']) need.push('soc.msg.empty.' + k);
|
||||
for (const k of ['attack', 'defense', 'total']) need.push('soc.rank.by.' + k);
|
||||
for (const k of ['inbox', 'sent', 'alliance', 'blocked']) need.push('soc.msg.tab.' + k);
|
||||
for (const k of ['operators', 'alliances', 'battles']) need.push('soc.rank.tab.' + k);
|
||||
for (const k of ['overview', 'members', 'diplomacy']) need.push('soc.tab.' + k);
|
||||
for (const l of I.LANGS) for (const k of need) assert.ok(I.strings[l][k], l + ' is missing ' + k);
|
||||
});
|
||||
|
||||
test('every error code the social routes can return is translated', () => {
|
||||
const errors = require('../server/errors');
|
||||
const social = ['peering_office_required', 'already_in_alliance', 'not_in_alliance', 'alliance_name_taken', 'alliance_tag_taken', 'alliance_full', 'invite_expired',
|
||||
'leader_must_transfer', 'notes_full', 'diplomacy_invalid', 'diplomacy_pending', 'proposal_exists', 'proposal_expired', 'forbidden', 'not_found', 'conflict', 'rate_limited', 'validation_failed'];
|
||||
for (const l of I.LANGS) for (const c of social) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
|
||||
const defined = Object.keys(errors.CODES || errors.codes || {});
|
||||
if (defined.length) for (const c of defined.filter((x) => social.includes(x))) assert.ok(I.strings.en['err.' + c]);
|
||||
});
|
||||
|
||||
test('screens never put player-controlled text through innerHTML', () => {
|
||||
const code = SRC.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
|
||||
assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(code), 'no HTML injection sinks in the social screens');
|
||||
});
|
||||
137
test/client-ws.test.js
Normal file
137
test/client-ws.test.js
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { createSocketClient } = require('../public/js/ws.js');
|
||||
|
||||
// A fake WebSocket and a manual clock: no real timers, no network.
|
||||
function rig(over) {
|
||||
const socks = [];
|
||||
class FakeWS {
|
||||
constructor(url) { this.url = url; this.sent = []; this.closed = false; socks.push(this); }
|
||||
send(s) { this.sent.push(JSON.parse(s)); }
|
||||
close() { this.closed = true; }
|
||||
// test helpers
|
||||
open() { this.onopen(); }
|
||||
recv(o) { this.onmessage({ data: JSON.stringify(o) }); }
|
||||
drop() { this.onclose(); }
|
||||
}
|
||||
const timers = []; let t = 0, seq = 0;
|
||||
const setTimeout_ = (fn, ms) => { const id = ++seq; timers.push({ id, at: t + ms, fn }); return id; };
|
||||
const clearTimeout_ = (id) => { const i = timers.findIndex((x) => x.id === id); if (i >= 0) timers.splice(i, 1); };
|
||||
const advance = (ms) => {
|
||||
const end = t + ms;
|
||||
for (;;) {
|
||||
timers.sort((a, b) => a.at - b.at);
|
||||
if (!timers.length || timers[0].at > end) break;
|
||||
const x = timers.shift(); t = x.at; x.fn();
|
||||
}
|
||||
t = end;
|
||||
};
|
||||
const got = [], states = [];
|
||||
const client = createSocketClient(Object.assign({
|
||||
WebSocket: FakeWS, url: () => 'ws://x/ws', token: () => 'tok', random: () => 0.5,
|
||||
setTimeout: setTimeout_, clearTimeout: clearTimeout_, onMessage: (m) => got.push(m), onState: (s) => states.push(s),
|
||||
}, over || {}));
|
||||
return { client, socks, advance, got, states };
|
||||
}
|
||||
|
||||
test('auth is the first message, ready opens the client, hints are passed on', () => {
|
||||
const r = rig();
|
||||
r.client.start();
|
||||
assert.strictEqual(r.socks.length, 1);
|
||||
r.socks[0].open();
|
||||
assert.deepStrictEqual(r.socks[0].sent, [{ type: 'auth', token: 'tok' }]);
|
||||
assert.strictEqual(r.client.open, false);
|
||||
r.socks[0].recv({ type: 'ready', serverTime: 5 });
|
||||
assert.strictEqual(r.client.open, true);
|
||||
r.socks[0].recv({ type: 'town', townId: 3 });
|
||||
r.socks[0].recv({ type: 'pong' }); // pong is plumbing, not a hint
|
||||
r.socks[0].onmessage({ data: 'not json' }); // garbage is ignored
|
||||
assert.deepStrictEqual(r.got, [{ type: 'town', townId: 3 }]);
|
||||
assert.ok(!JSON.stringify(r.socks[0].url).includes('tok'), 'the token never goes into the URL');
|
||||
});
|
||||
|
||||
test('pings every 25 s; a missing pong drops the socket and reconnects with backoff', () => {
|
||||
const r = rig();
|
||||
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
|
||||
r.advance(25000);
|
||||
assert.deepStrictEqual(r.socks[0].sent.slice(-1), [{ type: 'ping' }]);
|
||||
r.socks[0].recv({ type: 'pong' });
|
||||
r.advance(25000);
|
||||
assert.strictEqual(r.socks[0].sent.filter((m) => m.type === 'ping').length, 2);
|
||||
r.advance(8000); // no pong for the second ping
|
||||
assert.strictEqual(r.socks[0].closed, true);
|
||||
assert.strictEqual(r.client.open, false);
|
||||
assert.strictEqual(r.socks.length, 1);
|
||||
r.advance(1000); // backoff for attempt 0 = 1 s at jitter 0.5
|
||||
assert.strictEqual(r.socks.length, 2);
|
||||
});
|
||||
|
||||
test('reconnect backoff grows while the server is down and resets after ready', () => {
|
||||
const r = rig();
|
||||
r.client.start();
|
||||
r.socks[0].drop(); // never got ready
|
||||
r.advance(999); assert.strictEqual(r.socks.length, 1);
|
||||
r.advance(1); assert.strictEqual(r.socks.length, 2);
|
||||
r.socks[1].drop();
|
||||
r.advance(1999); assert.strictEqual(r.socks.length, 2);
|
||||
r.advance(1); assert.strictEqual(r.socks.length, 3);
|
||||
r.socks[2].open(); r.socks[2].recv({ type: 'ready' });
|
||||
assert.strictEqual(r.client.attempts, 0);
|
||||
r.socks[2].drop();
|
||||
r.advance(1000); assert.strictEqual(r.socks.length, 4);
|
||||
});
|
||||
|
||||
test('stop() closes for good; kick() connects now; no token means no socket', () => {
|
||||
const r = rig();
|
||||
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
|
||||
r.client.stop();
|
||||
assert.strictEqual(r.socks[0].closed, true);
|
||||
r.advance(120000); assert.strictEqual(r.socks.length, 1);
|
||||
assert.strictEqual(r.client.state, 'idle');
|
||||
|
||||
const r2 = rig();
|
||||
r2.client.start(); r2.socks[0].drop();
|
||||
r2.client.kick();
|
||||
assert.strictEqual(r2.socks.length, 2);
|
||||
|
||||
const r3 = rig({ token: () => null });
|
||||
r3.client.start();
|
||||
assert.strictEqual(r3.socks.length, 0);
|
||||
});
|
||||
|
||||
test('a throwing WebSocket constructor degrades silently and retries', () => {
|
||||
let n = 0;
|
||||
const r = rig({ WebSocket: class { constructor() { n++; throw new Error('blocked'); } } });
|
||||
r.client.start();
|
||||
assert.strictEqual(n, 1);
|
||||
r.advance(1000);
|
||||
assert.strictEqual(n, 2);
|
||||
});
|
||||
|
||||
test('close codes: 4401/4400/1009 stop for good, 4429 waits 30 s, others reconnect', () => {
|
||||
const fatal = [];
|
||||
const r = rig({ onFatal: (c) => fatal.push(c) });
|
||||
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
|
||||
r.socks[0].onclose({ code: 4401 });
|
||||
r.advance(300000);
|
||||
assert.strictEqual(r.socks.length, 1, 'no reconnect after 4401');
|
||||
assert.deepStrictEqual(fatal, [4401]);
|
||||
assert.strictEqual(r.client.state, 'idle');
|
||||
r.client.start(); // a fresh session starts again
|
||||
assert.strictEqual(r.socks.length, 2);
|
||||
r.socks[1].onclose({ code: 4429 });
|
||||
r.advance(29000); assert.strictEqual(r.socks.length, 2);
|
||||
r.advance(2000); assert.strictEqual(r.socks.length, 3);
|
||||
r.socks[2].onclose({ code: 1006 });
|
||||
r.advance(3000); assert.strictEqual(r.socks.length, 4);
|
||||
});
|
||||
|
||||
test('onReady tells a re-connect from the first connect', () => {
|
||||
const seen = [];
|
||||
const r = rig({ onReady: (m, again) => seen.push(again) });
|
||||
r.client.start(); r.socks[0].open(); r.socks[0].recv({ type: 'ready' });
|
||||
r.socks[0].onclose({ code: 1006 });
|
||||
r.advance(1000); r.socks[1].open(); r.socks[1].recv({ type: 'ready' });
|
||||
assert.deepStrictEqual(seen, [false, true]);
|
||||
});
|
||||
501
test/endgame-flow.test.js
Normal file
501
test/endgame-flow.test.js
Normal file
|
|
@ -0,0 +1,501 @@
|
|||
'use strict';
|
||||
/* End game on the server: sites open at day 100, taking them, shipping, building the node, winning, the end of the world.
|
||||
* Fake clock, in-memory db; the world is moved to day 100 by advancing the clock (nothing else is pending in these worlds). */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const T = require('./military-helpers');
|
||||
const A = require('../server/alliances');
|
||||
const E = require('../server/endgame');
|
||||
const { createEndgameQueries } = require('../server/endgameQueries');
|
||||
const { R, D, H } = T;
|
||||
const DAY = 24 * H;
|
||||
|
||||
function alliance(h, name, leader, members) {
|
||||
const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid);
|
||||
A.addMember(h.db, id, leader.opId, 'leader', h.clock.now());
|
||||
for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now());
|
||||
return id;
|
||||
}
|
||||
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
|
||||
|
||||
// A world at day `day`, with the sites at fixed positions; operators are created AFTER the clock moved so their POPs are fresh.
|
||||
function world(day, o) {
|
||||
const h = T.setup(Object.assign({ seed: 4242, radius: 50 }, o));
|
||||
h.advanceTo(h.world.start_at + Math.round(day * DAY / (h.world.speed || 1)));
|
||||
h.eg = createEndgameQueries(h);
|
||||
h.sites = R.backboneSites(h.world.seed, h.world.map_radius);
|
||||
return h;
|
||||
}
|
||||
// An operator next to site `i` with plenty of power so that its units stay online; no production unless asked.
|
||||
function near(h, name, i, o) {
|
||||
const s = h.sites[i];
|
||||
const op = T.addOperator(h, name, Object.assign({ x: s.x - 4, y: s.y, power: 25 }, o || {}));
|
||||
if (!(o && o.produce)) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%' AND key NOT IN ('f13','f14','f15','f16')", op.townId);
|
||||
return op;
|
||||
}
|
||||
const siteOf = (h, i) => h.db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', h.worldId, i);
|
||||
const attack = (h, who, i, units, type) => h.run('sendMovement', { userId: who.userId, fromTownId: who.townId, type: type || 'attack', x: h.sites[i].x, y: h.sites[i].y, units });
|
||||
const defenceNow = (h, i, level) => R.backboneDefence(h.world.seed, h.sites[i].x, h.sites[i].y, R.worldAgeDays(h.world.start_at, h.clock.now(), h.world.speed), level || 0);
|
||||
|
||||
test('before day 100: the sites are plain land - cannot be attacked, settled or seen; status says running', () => {
|
||||
const h = world(99.9);
|
||||
const a = near(h, 'alice', 0, { units: { script_crew: 50 } });
|
||||
alliance(h, 'Alpha', a);
|
||||
const s0 = h.sites[0];
|
||||
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 })).code, 'backbone_closed');
|
||||
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'raid')).code, 'backbone_closed');
|
||||
// settling the tile is refused although it looks like land: (the crews would otherwise found a POP on the future site)
|
||||
T.giveUnits(h, a.townId, { rollout_crew: 3 });
|
||||
h.db.run('UPDATE towns SET footprint = 1e9 WHERE id = ?', a.townId);
|
||||
const e = err(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: s0.x, y: s0.y, units: { rollout_crew: 3 } }));
|
||||
assert.equal(e.code, 'invalid_target');
|
||||
assert.equal(e.details.reason, 'backbone_site');
|
||||
const st = h.eg.status(a.userId, h.worldId);
|
||||
assert.equal(st.phase, 'running');
|
||||
assert.deepEqual(st.sites, []);
|
||||
assert.equal(st.winner, null);
|
||||
assert.equal(st.ageDays < 100, true);
|
||||
assert.equal(h.mq.tileInfo(a.userId, { x: s0.x, y: s0.y }).type, 'land');
|
||||
assert.equal(h.queries.map(a.userId, { x: s0.x, y: s0.y, r: 2 }).specials.some((s) => s.type === 'backbone'), false);
|
||||
h.advanceTo(h.world.start_at + 100 * DAY);
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).phase, 'backbone_open');
|
||||
});
|
||||
|
||||
test('day 100: 7 sites appear (status, map, tile), held by the incumbent; a scan reports the heavy defence', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 0, { units: { port_scanner: 100 } });
|
||||
const st = h.eg.status(a.userId, h.worldId);
|
||||
assert.equal(st.phase, 'backbone_open');
|
||||
assert.equal(st.sites.length, 7);
|
||||
assert.ok(st.sites.every((s) => s.holder === null && s.level === 0 && s.id === null && s.next.toLevel === 1));
|
||||
assert.deepEqual(st.sites.map((s) => [s.x, s.y]), h.sites.map((s) => [s.x, s.y]));
|
||||
assert.equal(st.opensAt, h.world.start_at + 100 * DAY);
|
||||
const m = h.queries.map(a.userId, { x: h.sites[0].x, y: h.sites[0].y, r: 3 });
|
||||
const sp = m.specials.find((s) => s.type === 'backbone');
|
||||
assert.ok(sp && sp.x === h.sites[0].x && sp.site.index === 0 && sp.site.holder === null && sp.site.level === 0);
|
||||
const ti = h.mq.tileInfo(a.userId, { x: h.sites[0].x, y: h.sites[0].y });
|
||||
assert.equal(ti.type, 'backbone');
|
||||
assert.equal(ti.backbone.holder, null);
|
||||
assert.equal(ti.backbone.canAttack, false, 'no alliance, no attack');
|
||||
assert.equal(ti.settle.possible, false);
|
||||
// scan (no alliance needed)
|
||||
const mv = attack(h, a, 0, { port_scanner: 100 }, 'scan');
|
||||
h.advanceTo(mv.arriveAt);
|
||||
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'scan');
|
||||
assert.equal(rep.data.site.type, 'backbone');
|
||||
assert.equal(rep.data.success, true);
|
||||
assert.equal(rep.data.intel.defence, defenceNow(h, 0, 0), 'the scan shows the exact static defence');
|
||||
assert.ok(rep.data.intel.defence > 10 * R.incumbentDefence(h.world.seed, h.sites[0].x, h.sites[0].y, 100));
|
||||
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM landing_sites').n, 7, 'the first touch created the rows');
|
||||
assert.equal(T.notes(h, a.userId, 'backbone_open').length, 1, 'and told the world once');
|
||||
});
|
||||
|
||||
test('taking a site: alliance members only, heavy defence, the winner holds it; losing attackers change nothing; friends and pacts are refused', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 0, { units: { script_crew: 1200 } });
|
||||
const a2 = near(h, 'alice2', 0, { x: h.sites[0].x - 4, y: h.sites[0].y + 3 });
|
||||
const b = near(h, 'bob', 0, { x: h.sites[0].x + 4, y: h.sites[0].y, units: { script_crew: 300 } });
|
||||
const loner = near(h, 'loner', 0, { x: h.sites[0].x, y: h.sites[0].y - 5, units: { script_crew: 1200 } });
|
||||
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
|
||||
|
||||
// an operator without an alliance cannot take a site
|
||||
assert.equal(err(() => attack(h, loner, 0, { script_crew: 1200 })).details.reason, 'no_alliance');
|
||||
T.giveUnits(h, a.townId, { ma_team: 1 });
|
||||
assert.equal(err(() => attack(h, a, 0, { script_crew: 10, ma_team: 1 }, 'takeover')).details.reason, 'landing_scan_or_attack_only');
|
||||
assert.equal(err(() => attack(h, a, 0, { script_crew: 10 }, 'reinforce')).code, 'invalid_target');
|
||||
|
||||
// too weak: bob's 300 crews (12 000) against ~40 000: lost, nothing changes
|
||||
const weak = attack(h, b, 0, { script_crew: 300 });
|
||||
h.advanceTo(weak.arriveAt);
|
||||
assert.equal(siteOf(h, 0).holder_alliance_id, null);
|
||||
const lost = T.reportsOf(h, b.userId).find((r) => r.type === 'landing');
|
||||
assert.equal(lost.data.outcome, 'defender_won');
|
||||
assert.equal(lost.data.taken, false);
|
||||
assert.equal(T.units(h, b.townId).script_crew, undefined, 'all lost');
|
||||
|
||||
// alice takes it
|
||||
const power = 1200 * 40;
|
||||
assert.ok(power > defenceNow(h, 0, 0) * 1.05);
|
||||
const mv = attack(h, a, 0, { script_crew: 1200 });
|
||||
h.advanceTo(mv.arriveAt);
|
||||
const site = siteOf(h, 0);
|
||||
assert.equal(site.holder_alliance_id, A1);
|
||||
assert.equal(site.holder_operator_id, a.opId);
|
||||
assert.equal(site.taken_at, mv.arriveAt);
|
||||
assert.equal(site.level, 0);
|
||||
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'landing');
|
||||
assert.equal(rep.data.outcome, 'attacker_won');
|
||||
assert.equal(rep.data.taken, true);
|
||||
assert.equal(rep.data.site.holder, null, 'the report says who held it BEFORE');
|
||||
assert.equal(T.notes(h, a2.userId, 'backbone_taken').length, 1, 'every member of the new holder hears it');
|
||||
const surv = h.db.get("SELECT units FROM movements WHERE type = 'return' AND owner_id = ?", a.opId);
|
||||
assert.ok(JSON.parse(surv.units).script_crew > 0 && JSON.parse(surv.units).script_crew < 1200, 'survivors drive home, with losses');
|
||||
// status and tile now show the holder
|
||||
const st = h.eg.status(a2.userId, h.worldId);
|
||||
assert.equal(st.sites[0].holder.allianceId, A1);
|
||||
assert.equal(st.sites[0].holder.tag, 'ALP');
|
||||
assert.equal(st.sites[0].takenBy.operatorId, a.opId);
|
||||
assert.equal(h.mq.tileInfo(a2.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.mine, true);
|
||||
assert.equal(h.mq.tileInfo(b.userId, { x: h.sites[0].x, y: h.sites[0].y }).backbone.canAttack, true);
|
||||
|
||||
// the holder's own members cannot attack it; a NAP partner cannot either
|
||||
T.giveUnits(h, a2.townId, { script_crew: 10 });
|
||||
assert.equal(err(() => attack(h, a2, 0, { script_crew: 10 })).details.reason, 'own_site');
|
||||
A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now());
|
||||
T.giveUnits(h, b.townId, { script_crew: 10 });
|
||||
assert.equal(err(() => attack(h, b, 0, { script_crew: 10 })).details.reason, 'pact');
|
||||
A.setRelation(h.db, h.worldId, A1, B1, 'war', h.clock.now());
|
||||
});
|
||||
|
||||
test('re-checked at arrival: a pact signed while the attack is on the road bounces it', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 1, { units: { script_crew: 1200 } });
|
||||
const b = near(h, 'bob', 1, { x: h.sites[1].x + 4, y: h.sites[1].y });
|
||||
const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b);
|
||||
// bob's alliance holds the site
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 1', B1, b.opId);
|
||||
const mv = attack(h, a, 1, { script_crew: 1200 });
|
||||
A.setRelation(h.db, h.worldId, A1, B1, 'nap', h.clock.now());
|
||||
h.advanceTo(mv.arriveAt);
|
||||
assert.equal(siteOf(h, 1).holder_alliance_id, B1, 'not taken');
|
||||
const rep = T.reportsOf(h, a.userId).find((r) => r.type === 'movement_failed');
|
||||
assert.equal(rep.data.reason, 'pact');
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM movements WHERE type = 'return' AND owner_id = ?", a.opId).n, 1, 'the units come home');
|
||||
});
|
||||
|
||||
test('shipping: members feed the stockpile by transport; strangers cannot; a shipment that arrives after the site changed hands rides home', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 2);
|
||||
const a2 = near(h, 'alice2', 2, { x: h.sites[2].x - 14, y: h.sites[2].y });
|
||||
const b = near(h, 'bob', 2, { x: h.sites[2].x + 4, y: h.sites[2].y, units: { script_crew: 1300 } });
|
||||
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 2', A1, a.opId);
|
||||
const site = siteOf(h, 2);
|
||||
const stock = (id) => { const t = T.town(h, id); return t.fiber + t.hardware + t.capital; };
|
||||
|
||||
assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden');
|
||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP");
|
||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 501 } })).code, 'capacity_exceeded');
|
||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found');
|
||||
|
||||
const before = stock(a2.townId);
|
||||
const s1 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 300, hardware: 200 } });
|
||||
assert.equal(stock(a2.townId), before - 500, 'it left the POP');
|
||||
assert.equal(s1.arriveAt - s1.departAt, R.transportMs(R.distance(a2.x, a2.y, site.x, site.y), 1));
|
||||
h.advanceTo(s1.arriveAt);
|
||||
let row = siteOf(h, 2);
|
||||
assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0]);
|
||||
assert.deepEqual(h.db.get('SELECT fiber, hardware, capital FROM landing_contributions WHERE site_id = ? AND operator_id = ?', site.id, a2.opId), { fiber: 300, hardware: 200, capital: 0 });
|
||||
assert.equal(T.notes(h, a2.userId, 'backbone_delivered').length, 1);
|
||||
assert.equal(stock(a2.townId), before - 500, 'nothing came back: it was delivered');
|
||||
|
||||
// second shipment is still on the road when bob takes the site
|
||||
const s2 = h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { capital: 400 } });
|
||||
const mid = stock(a2.townId);
|
||||
const atk = attack(h, b, 2, { script_crew: 1300 });
|
||||
assert.ok(atk.arriveAt < s2.arriveAt, 'the attack gets there first (a2 lives further away)');
|
||||
h.advanceTo(s2.arriveAt);
|
||||
assert.equal(siteOf(h, 2).holder_alliance_id, B1, 'bob took it first');
|
||||
row = siteOf(h, 2);
|
||||
assert.deepEqual([row.fiber, row.hardware, row.capital], [300, 200, 0], 'the late shipment was not added to the new holder\'s stockpile, the old stock stayed with the site');
|
||||
assert.equal(T.notes(h, a2.userId, 'backbone_ship_bounced').length, 1);
|
||||
assert.equal(stock(a2.townId), mid, 'still on its way home');
|
||||
h.advance(10 * H);
|
||||
assert.equal(stock(a2.townId), mid + 400, 'back home: nothing lost');
|
||||
});
|
||||
|
||||
test('building the node: from the stockpile, one level at a time, holders only; the level and the build stay with the site when it is taken', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 3);
|
||||
const a2 = near(h, 'alice2', 3, { x: h.sites[3].x - 4, y: h.sites[3].y + 3 });
|
||||
const b = near(h, 'bob', 3, { x: h.sites[3].x + 4, y: h.sites[3].y, units: { script_crew: 1300 } });
|
||||
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 3', A1, a.opId);
|
||||
const site = siteOf(h, 3);
|
||||
const build = (who) => h.run('backboneBuild', { userId: who.userId, siteId: site.id });
|
||||
|
||||
assert.equal(err(() => build(a)).code, 'not_enough_resources');
|
||||
assert.equal(err(() => build(b)).code, 'forbidden', 'not a holder');
|
||||
h.db.run('UPDATE landing_sites SET fiber = 5000, hardware = 4200, capital = 4000 WHERE id = ?', site.id);
|
||||
const t0 = h.clock.now();
|
||||
const q = build(a2);
|
||||
assert.equal(q.toLevel, 1);
|
||||
assert.deepEqual(q.cost, R.backboneCost(1));
|
||||
assert.equal(q.dueAt, t0 + R.backboneTimeMs(1, 1));
|
||||
let row = siteOf(h, 3);
|
||||
assert.deepEqual([row.fiber, row.hardware, row.capital], [1000, 200, 0], 'paid from the stockpile at once');
|
||||
assert.equal(row.build_to, 1);
|
||||
assert.equal(err(() => build(a)).code, 'already_queued');
|
||||
const view = h.eg.site(a.userId, site.id);
|
||||
assert.equal(view.site.build.toLevel, 1);
|
||||
assert.equal(view.you.canBuild, true);
|
||||
assert.equal(h.eg.site(b.userId, site.id).contributions, undefined, 'the ledger is for holders');
|
||||
|
||||
// bob takes the site while level 1 is being built: the level lands on the site for its NEW holder
|
||||
h.advanceTo(q.dueAt - H);
|
||||
const atk = attack(h, b, 3, { script_crew: 1300 });
|
||||
h.advanceTo(atk.arriveAt);
|
||||
assert.equal(siteOf(h, 3).holder_alliance_id, B1);
|
||||
assert.equal(siteOf(h, 3).build_to, 1, 'the build runs on');
|
||||
h.advanceTo(q.dueAt);
|
||||
row = siteOf(h, 3);
|
||||
assert.equal(row.level, 1);
|
||||
assert.equal(row.build_to, null);
|
||||
assert.equal(row.holder_alliance_id, B1);
|
||||
assert.equal(err(() => build(a2)).code, 'forbidden', 'alice is a stranger now');
|
||||
// the node raises the site's defence (level stays with the site)
|
||||
assert.ok(defenceNow(h, 3, 1) > defenceNow(h, 3, 0));
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).sites[3].level, 1);
|
||||
|
||||
// the new holder pays the next level from what is left in the stockpile
|
||||
h.db.run('UPDATE landing_sites SET fiber = 9000, hardware = 9000, capital = 9000 WHERE id = ?', site.id);
|
||||
const q2 = build(b);
|
||||
assert.equal(q2.toLevel, 2);
|
||||
assert.deepEqual(q2.cost, R.backboneCost(2));
|
||||
h.advanceTo(q2.dueAt);
|
||||
assert.equal(siteOf(h, 3).level, 2);
|
||||
assert.equal(T.notes(h, b.userId, 'backbone_level').length, 0, 'only every 10th level is announced');
|
||||
assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0);
|
||||
});
|
||||
|
||||
test('winning: level 100 makes the holder the winner, the world ends two world days later with a ranking, then it is frozen but readable', () => {
|
||||
const h = world(100, { speed: 2 });
|
||||
const a = near(h, 'alice', 4, { produce: true });
|
||||
const a2 = near(h, 'alice2', 4, { x: h.sites[4].x - 4, y: h.sites[4].y + 3 });
|
||||
const b = near(h, 'bob', 4, { x: h.sites[4].x + 4, y: h.sites[4].y, units: { script_crew: 20 } });
|
||||
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b);
|
||||
T.giveUnits(h, a.townId, { script_crew: 40 });
|
||||
h.db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 12.5, 3), (?, 40, 1)', a.opId, b.opId);
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 4', A1, a.opId);
|
||||
const site = siteOf(h, 4);
|
||||
const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id });
|
||||
assert.equal(q.toLevel, 100);
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).winner, null);
|
||||
const wonAt = q.dueAt;
|
||||
h.advanceTo(wonAt);
|
||||
const w = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId);
|
||||
assert.equal(w.winner_alliance_id, A1);
|
||||
assert.equal(w.winner_name, 'Alpha');
|
||||
assert.equal(w.won_at, wonAt);
|
||||
assert.equal(w.status, 'running', 'the world goes on for two days');
|
||||
assert.equal(w.end_at, wonAt + DAY, 'two WORLD days at speed 2 = one real day');
|
||||
assert.equal(T.notes(h, b.userId, 'backbone_won').length, 1, 'everybody hears who won');
|
||||
assert.equal(T.notes(h, a2.userId, 'backbone_level').length, 1);
|
||||
const st = h.eg.status(b.userId, h.worldId);
|
||||
assert.equal(st.winner.allianceId, A1); assert.equal(st.winner.tag, 'ALP');
|
||||
assert.equal(st.endsAt, wonAt + DAY); assert.equal(st.endedAt, null);
|
||||
assert.equal(st.phase, 'backbone_open');
|
||||
assert.equal(h.eg.results(b.userId, h.worldId).available, false);
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd' AND status = 'pending'").n, 1);
|
||||
|
||||
// still playable during the grace period; the winner is fixed even if the site is lost
|
||||
h.run('renameTown', { userId: a.userId, townId: a.townId, name: 'Still Playing' });
|
||||
assert.equal(err(() => h.run('backboneBuild', { userId: a.userId, siteId: site.id })).code, 'max_level');
|
||||
h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); // something in the queue that the end will cancel
|
||||
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 100, wantRes: 'fiber', wantAmount: 100, maxDistance: 30 }).offer; // open at the end
|
||||
h.advanceTo(w.end_at - 1);
|
||||
assert.equal(h.db.get('SELECT status FROM worlds WHERE id = ?', h.worldId).status, 'running');
|
||||
h.advanceTo(w.end_at);
|
||||
const ended = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId);
|
||||
assert.equal(ended.status, 'ended');
|
||||
assert.equal(ended.end_at, w.end_at);
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", h.worldId).n, 0, 'the world is frozen: nothing pending');
|
||||
assert.equal(T.notes(h, a.userId, 'world_ended').length, 1);
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired', 'open offers end with the world: the escrow is back in its POP');
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE status = 'open'").n, 0);
|
||||
|
||||
// the snapshot
|
||||
const res = h.eg.results(b.userId, h.worldId);
|
||||
assert.equal(res.available, true);
|
||||
assert.equal(res.status, 'ended');
|
||||
assert.equal(res.results.winner.name, 'Alpha');
|
||||
assert.equal(res.results.operators.length, 3);
|
||||
assert.deepEqual(res.results.operators.map((o) => o.rank), [1, 2, 3]);
|
||||
assert.ok(res.results.operators[0].footprint >= res.results.operators[1].footprint);
|
||||
assert.equal(res.results.alliances.length, 2);
|
||||
assert.equal(res.results.alliances[0].members + res.results.alliances[1].members, 3);
|
||||
assert.deepEqual(res.results.attackers.map((o) => o.name), ['bob', 'alice']);
|
||||
assert.deepEqual(res.results.defenders.map((o) => o.name), ['alice', 'bob']);
|
||||
assert.equal(res.results.sites.find((s) => s.index === 4).level, 100);
|
||||
const stored = JSON.parse(h.db.get('SELECT data FROM world_rankings WHERE world_id = ?', h.worldId).data);
|
||||
assert.deepEqual(stored, res.results);
|
||||
|
||||
// ended: every game command is refused with one stable code ...
|
||||
const refused = (name, args) => assert.equal(err(() => h.run(name, args)).code, 'world_ended', name);
|
||||
refused('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
|
||||
refused('renameTown', { userId: a.userId, townId: a.townId, name: 'x' });
|
||||
refused('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'scan', x: b.x, y: b.y, units: { port_scanner: 1 } });
|
||||
refused('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: a2.townId, cargo: { fiber: 1 } });
|
||||
refused('train', { userId: a.userId, townId: a.townId, unit: 'soc_analyst', count: 1 });
|
||||
refused('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 });
|
||||
refused('tradeAccept', { userId: a.userId, offerId: 1, townId: a.townId });
|
||||
refused('backboneBuild', { userId: a.userId, siteId: site.id });
|
||||
refused('backboneShip', { userId: a.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 1 } });
|
||||
refused('allianceCreate', { userId: a2.userId, worldId: h.worldId, name: 'New', tag: 'NW' });
|
||||
refused('allianceLeave', { userId: a2.userId, allianceId: A1 });
|
||||
refused('diploPropose', { userId: a.userId, allianceId: A1, targetId: B1, state: 'war' });
|
||||
refused('reportShare', { userId: a.userId, reportId: 1 });
|
||||
refused('recallMovement', { userId: a.userId, movementId: 1 });
|
||||
refused('joinWorld', { userId: a.userId, worldId: h.worldId });
|
||||
// ... except reading state and talking
|
||||
h.run('markReportRead', { userId: a.userId, all: true });
|
||||
assert.equal(h.run('messageSend', { userId: a.userId, toOperatorId: b.opId, text: 'gg' }).recipients, 1);
|
||||
// ... and everything stays readable
|
||||
assert.equal(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).world.status, 'ended');
|
||||
assert.ok(h.queries.map(a.userId, { x: 0, y: 0, r: 40 }).specials.some((s) => s.type === 'backbone'));
|
||||
assert.ok(h.mq.reports(a.userId, {}).items.length >= 0);
|
||||
assert.ok(h.queries.town(a.userId, a.townId).town.id === a.townId);
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).phase, 'ended');
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).endedAt, w.end_at);
|
||||
assert.equal(h.eg.site(a.userId, site.id).site.level, 100);
|
||||
// running it again changes nothing (idempotent)
|
||||
const snap = JSON.stringify(h.db.get('SELECT * FROM world_rankings'));
|
||||
require('../server/events/worldEnd')(Object.assign(h.ctx(), { now: w.end_at }), { id: 0, worldId: h.worldId, dueAt: w.end_at + 5, payload: {} });
|
||||
assert.equal(JSON.stringify(h.db.get('SELECT * FROM world_rankings')), snap);
|
||||
});
|
||||
|
||||
test('winner is fixed at level 100: losing the node during the grace period does not change it; a disbanded holder leaves the site to the incumbent (level stays)', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 5);
|
||||
const b = near(h, 'bob', 5, { x: h.sites[5].x + 4, y: h.sites[5].y, units: { script_crew: 4700 } });
|
||||
const A1 = alliance(h, 'Alpha', a), B1 = alliance(h, 'Bravo', b);
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, level = 99, fiber = 1e7, hardware = 1e7, capital = 1e7 WHERE idx = 5', A1, a.opId);
|
||||
const site = siteOf(h, 5);
|
||||
const q = h.run('backboneBuild', { userId: a.userId, siteId: site.id });
|
||||
h.advanceTo(q.dueAt);
|
||||
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1);
|
||||
const atk = attack(h, b, 5, { script_crew: 4700 });
|
||||
h.advanceTo(atk.arriveAt);
|
||||
assert.equal(siteOf(h, 5).holder_alliance_id, B1, 'bob took the finished node');
|
||||
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1, 'but alice\'s alliance already won');
|
||||
// the site keeps its level when its holder disbands
|
||||
A.dissolve(Object.assign(h.ctx(), { scheduler: h.scheduler }), B1, 'test');
|
||||
assert.equal(siteOf(h, 5).holder_alliance_id, null);
|
||||
assert.equal(siteOf(h, 5).level, 100);
|
||||
assert.equal(h.eg.status(a.userId, h.worldId).sites[5].holder, null);
|
||||
});
|
||||
|
||||
test('a finished node taken while nobody wins yet completes for the new holder; only one winner per world', () => {
|
||||
const h = world(100);
|
||||
const a = near(h, 'alice', 6, { units: { script_crew: 4700 } });
|
||||
const A1 = alliance(h, 'Alpha', a);
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET level = 100 WHERE idx = 6'); // finished while its holder was disbanded: nobody won
|
||||
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, null);
|
||||
const atk = attack(h, a, 6, { script_crew: 4700 });
|
||||
h.advanceTo(atk.arriveAt);
|
||||
assert.equal(h.db.get('SELECT winner_alliance_id AS w FROM worlds').w, A1);
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1);
|
||||
// a second node reaching 100 does not start a second ending
|
||||
const ctx = h.ctx();
|
||||
E.ensureSites(h.db, h.world, h.clock.now());
|
||||
h.db.run('UPDATE landing_sites SET level = 100, holder_alliance_id = ? WHERE idx = 0', A1);
|
||||
assert.equal(E.maybeWin(ctx, siteOf(h, 0), h.clock.now()), false);
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'worldEnd'").n, 1);
|
||||
});
|
||||
|
||||
test('ended worlds over HTTP: reads work, writes say world_ended; status and results routes follow their schemas', async () => {
|
||||
const { createTestServer } = require('./helpers');
|
||||
const t = await createTestServer({ contract: true });
|
||||
try {
|
||||
const a = await t.signup('alice');
|
||||
const w = t.srv.db.get('SELECT * FROM worlds');
|
||||
let r = await t.api('/worlds/' + w.id + '/status', {}, a.token);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.phase, 'running');
|
||||
assert.equal((await t.api('/worlds/999/status', {}, a.token)).status, 404);
|
||||
assert.equal((await t.api('/worlds/' + w.id + '/status')).status, 401);
|
||||
r = await t.api('/worlds/' + w.id + '/results', {}, a.token);
|
||||
assert.equal(r.body.available, false);
|
||||
// jump to the end
|
||||
t.srv.db.run("UPDATE worlds SET winner_alliance_id = NULL, winner_name = 'Win', winner_tag = 'WIN', won_at = ?, end_at = ?, start_at = ? WHERE id = ?", t.clock.now(), t.clock.now() + 1000, t.clock.now() - 101 * DAY, w.id);
|
||||
t.srv.scheduler.enqueue({ worldId: w.id, dueAt: t.clock.now() + 1000, type: 'worldEnd', payload: {} });
|
||||
t.clock.advance(1000);
|
||||
r = await t.api('/worlds/' + w.id + '/status', {}, a.token);
|
||||
assert.equal(r.body.phase, 'ended');
|
||||
assert.equal(r.body.winner.name, 'Win');
|
||||
assert.equal(r.body.sites.length, 7);
|
||||
r = await t.api('/worlds/' + w.id + '/results', {}, a.token);
|
||||
assert.equal(r.body.available, true);
|
||||
assert.equal(r.body.results.operators[0].name, 'alice');
|
||||
const build = await t.api('/towns/' + a.townId + '/build', { method: 'POST', body: { key: 'firewall' } }, a.token);
|
||||
assert.equal(build.status, 409);
|
||||
assert.equal(build.body.error.code, 'world_ended');
|
||||
for (const p of ['/me', '/map?x=0&y=0&r=5', '/reports', '/rankings/operators', '/rankings/alliances', '/rankings/battles', '/towns/' + a.townId, '/movements', '/trade/offers', '/notifications', '/map/tile?x=0&y=0']) {
|
||||
const g = await t.api(p, {}, a.token);
|
||||
assert.equal(g.status, 200, p + ' -> ' + JSON.stringify(g.body).slice(0, 200));
|
||||
}
|
||||
const post = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 10, wantRes: 'capital', wantAmount: 10, maxDistance: 5 } }, a.token);
|
||||
assert.equal(post.body.error.code, 'world_ended');
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('backbone routes over HTTP: site detail, ship, build follow their schemas and permissions', async () => {
|
||||
const { createTestServer } = require('./helpers');
|
||||
const t = await createTestServer({ contract: true });
|
||||
try {
|
||||
const lead = await t.signupPeering('lead'), mem = await t.signupPeering('mem'), out = await t.signup('outsider');
|
||||
t.setBuilding(mem.townId, 'internet_exchange', 2);
|
||||
const w = t.srv.db.get('SELECT * FROM worlds');
|
||||
assert.equal((await t.api('/backbone/1', {}, lead.token)).status, 404, 'no such site yet');
|
||||
t.srv.db.run('UPDATE worlds SET start_at = ? WHERE id = ?', t.clock.now() - 101 * DAY, w.id);
|
||||
const mk = await t.api('/alliances', { method: 'POST', body: { name: 'Backers', tag: 'BKR' } }, lead.token);
|
||||
const inv = await t.api('/alliances/' + mk.body.allianceId + '/invite', { method: 'POST', body: { operatorId: mem.operatorId } }, lead.token);
|
||||
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, mem.token);
|
||||
const world = require('../server/state').loadWorld(t.srv.db, w.id);
|
||||
E.ensureSites(t.srv.db, world, t.clock.now());
|
||||
t.srv.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = 0', mk.body.allianceId, lead.operatorId);
|
||||
const site = t.srv.db.get('SELECT * FROM landing_sites WHERE idx = 0');
|
||||
|
||||
let r = await t.api('/worlds/' + w.id + '/status', {}, out.token);
|
||||
assert.equal(r.body.phase, 'backbone_open');
|
||||
assert.equal(r.body.sites[0].holder.tag, 'BKR');
|
||||
r = await t.api('/backbone/' + site.id, {}, out.token);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.you.holder, false);
|
||||
assert.equal(r.body.contributions, undefined);
|
||||
r = await t.api('/backbone/' + site.id, {}, mem.token);
|
||||
assert.equal(r.body.you.canBuild, true);
|
||||
assert.deepEqual(r.body.contributions, []);
|
||||
|
||||
// strangers: 403 on ship and build
|
||||
assert.equal((await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: out.townId, cargo: { fiber: 5 } } }, out.token)).status, 403);
|
||||
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, out.token)).status, 403);
|
||||
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, mem.token)).body.error.code, 'not_enough_resources');
|
||||
|
||||
const ship = await t.api('/backbone/' + site.id + '/ship', { method: 'POST', body: { fromTownId: mem.townId, cargo: { fiber: 100, capital: 50 } } }, mem.token);
|
||||
assert.equal(ship.status, 201);
|
||||
assert.equal(ship.body.siteId, site.id);
|
||||
assert.equal(ship.body.toTownId, null);
|
||||
const mv = await t.api('/movements', {}, mem.token);
|
||||
assert.equal(mv.body.outgoing[0].siteId, site.id, 'the movement list says it is a shipment to a site');
|
||||
t.clock.advance(ship.body.arriveAt - t.clock.now());
|
||||
t.srv.scheduler.runDue();
|
||||
r = await t.api('/backbone/' + site.id, {}, lead.token);
|
||||
assert.deepEqual(r.body.site.pool, { fiber: 100, hardware: 0, capital: 50 });
|
||||
assert.deepEqual(r.body.contributions.map((c) => [c.name, c.fiber, c.capital]), [['mem', 100, 50]]);
|
||||
|
||||
t.srv.db.run('UPDATE landing_sites SET fiber = 4000, hardware = 4000, capital = 4000 WHERE id = ?', site.id);
|
||||
const b = await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token);
|
||||
assert.equal(b.status, 201);
|
||||
assert.equal(b.body.toLevel, 1);
|
||||
assert.equal((await t.api('/backbone/' + site.id + '/build', { method: 'POST' }, lead.token)).body.error.code, 'already_queued');
|
||||
t.clock.advance(b.body.dueAt - t.clock.now());
|
||||
t.srv.scheduler.runDue();
|
||||
r = await t.api('/worlds/' + w.id + '/status', {}, out.token);
|
||||
assert.equal(r.body.sites[0].level, 1);
|
||||
assert.equal(r.body.sites[0].build, null);
|
||||
const map = await t.api('/map?x=' + site.x + '&y=' + site.y + '&r=2', {}, out.token);
|
||||
const sp = map.body.specials.find((x) => x.type === 'backbone');
|
||||
assert.equal(sp.site.level, 1);
|
||||
assert.equal(sp.site.holder.tag, 'BKR');
|
||||
const tile = await t.api('/map/tile?x=' + site.x + '&y=' + site.y, {}, lead.token);
|
||||
assert.equal(tile.body.type, 'backbone');
|
||||
assert.equal(tile.body.backbone.mine, true);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
177
test/endgame-gaps.test.js
Normal file
177
test/endgame-gaps.test.js
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
'use strict';
|
||||
/* Gaps closed next to the end game: buildDone after exploit-kit damage, confederation sees incoming, shared reports. */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const T = require('./military-helpers');
|
||||
const { R, D, H } = T;
|
||||
|
||||
const level = (h, townId, key) => h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', townId, key).level;
|
||||
|
||||
test('buildDone: an upgrade in flight lands ONE level above whatever the building is now (exploit kits cannot be undone by it)', () => {
|
||||
const h = T.setup();
|
||||
const a = T.addOperator(h, 'alice', { infra: { firewall: 5, core_router: 10 } });
|
||||
const q = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
|
||||
assert.equal(q.toLevel, 6);
|
||||
// exploit kits hit the firewall while the upgrade is being built (siege writes the level directly)
|
||||
h.db.run("UPDATE buildings SET level = 2 WHERE town_id = ? AND key = 'firewall'", a.townId);
|
||||
h.advanceTo(q.dueAt);
|
||||
assert.equal(level(h, a.townId, 'firewall'), 3, 'the finished level adds one to the damaged building, it does not restore the queued level');
|
||||
const done = T.notes(h, a.userId, 'build_done');
|
||||
assert.equal(done[done.length - 1].level, 3, 'the notification reports the real level');
|
||||
});
|
||||
|
||||
test('buildDone: a building knocked down to 0 while its upgrade is queued comes back at level 1; an undamaged one still gets +1', () => {
|
||||
const h = T.setup();
|
||||
const a = T.addOperator(h, 'alice', { infra: { firewall: 4, noc: 5, core_router: 10 } });
|
||||
const q1 = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' }); // 4 -> 5
|
||||
const q2 = h.run('build', { userId: a.userId, townId: a.townId, key: 'noc' }); // 5 -> 6 (second slot: core router 10)
|
||||
h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key = 'firewall'", a.townId);
|
||||
h.advanceTo(Math.max(q1.dueAt, q2.dueAt));
|
||||
assert.equal(level(h, a.townId, 'firewall'), 1);
|
||||
assert.equal(level(h, a.townId, 'noc'), 6);
|
||||
});
|
||||
|
||||
test('buildDone: a brand-new infrastructure building appears at level 1 (no row yet)', () => {
|
||||
const h = T.setup();
|
||||
const a = T.addOperator(h, 'alice', { infra: { core_router: 10 } });
|
||||
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'firewall'", a.townId);
|
||||
const q = h.run('build', { userId: a.userId, townId: a.townId, key: 'firewall' });
|
||||
h.advanceTo(q.dueAt);
|
||||
assert.equal(level(h, a.townId, 'firewall'), 1);
|
||||
});
|
||||
|
||||
// ---- helpers: alliances without the HTTP layer
|
||||
const A = require('../server/alliances');
|
||||
function alliance(h, name, leader, members) {
|
||||
const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid);
|
||||
A.addMember(h.db, id, leader.opId, 'leader', h.clock.now());
|
||||
for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now());
|
||||
return id;
|
||||
}
|
||||
|
||||
test('confederation: members see each other\'s incoming movements (origin and ETA, type hidden), strangers and neutrals do not', () => {
|
||||
const h = T.setup();
|
||||
const a = T.addOperator(h, 'alice', { x: 5, y: 0 });
|
||||
const a2 = T.addOperator(h, 'alice2', { x: 5, y: 6 });
|
||||
const b = T.addOperator(h, 'bob', { x: 9, y: 0 });
|
||||
const c = T.addOperator(h, 'cat', { x: 14, y: 0, units: { script_crew: 20 } });
|
||||
const d = T.addOperator(h, 'dan', { x: 20, y: 0 });
|
||||
const X = alliance(h, 'Xray', a, [a2]), Y = alliance(h, 'Yankee', b);
|
||||
const sent = h.run('sendMovement', { userId: c.userId, fromTownId: c.townId, type: 'attack', toTownId: b.townId, units: { script_crew: 20 } });
|
||||
|
||||
// neutral: nobody but the target is told
|
||||
assert.equal(h.mq.movements(a.userId, {}).alliedIncoming.length, 0);
|
||||
assert.equal(h.mq.movements(b.userId, {}).incoming.length, 1);
|
||||
|
||||
A.setRelation(h.db, h.worldId, X, Y, 'confed', h.clock.now());
|
||||
for (const who of [a, a2]) {
|
||||
const l = h.mq.movements(who.userId, {});
|
||||
assert.equal(l.alliedIncoming.length, 1, who.name + ' sees the attack on the confederate');
|
||||
const m = l.alliedIncoming[0];
|
||||
assert.equal(m.id, sent.movementId);
|
||||
assert.equal(m.type, 'unknown');
|
||||
assert.equal(m.units, undefined);
|
||||
assert.equal(m.arriveAt, sent.arriveAt);
|
||||
assert.equal(m.from.townId, c.townId);
|
||||
assert.equal(m.to.townId, b.townId);
|
||||
assert.equal(m.toOperator.id, b.opId);
|
||||
assert.equal(l.incoming.length, 0, 'the personal incoming list is only about your own POPs');
|
||||
}
|
||||
const bl = h.mq.movements(b.userId, {});
|
||||
assert.equal(bl.incoming.length, 1, 'bob is the target himself');
|
||||
assert.equal(bl.alliedIncoming.length, 0, 'nothing is heading for his confederates');
|
||||
assert.equal(h.mq.movements(d.userId, {}).alliedIncoming.length, 0, 'a stranger sees nothing');
|
||||
assert.equal(h.mq.movements(c.userId, {}).alliedIncoming.length, 0);
|
||||
|
||||
// an attack on alice shows up for bob, but alice2's own reinforcement of alice is friendly traffic and does not
|
||||
h.db.run("UPDATE movements SET status = 'done'");
|
||||
T.giveUnits(h, a2.townId, { soc_analyst: 5 });
|
||||
T.giveUnits(h, c.townId, { script_crew: 5 });
|
||||
h.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'reinforce', toTownId: a.townId, units: { soc_analyst: 5 } });
|
||||
const atk = h.run('sendMovement', { userId: c.userId, fromTownId: c.townId, type: 'raid', toTownId: a.townId, units: { script_crew: 1 } });
|
||||
const bl2 = h.mq.movements(b.userId, {});
|
||||
assert.deepEqual(bl2.alliedIncoming.map((m) => m.id), [atk.movementId]);
|
||||
assert.equal(h.mq.movements(a.userId, {}).incoming.length, 2, 'alice herself sees both, types hidden');
|
||||
|
||||
// the confederation ends: the window closes
|
||||
A.setRelation(h.db, h.worldId, X, Y, 'neutral', h.clock.now());
|
||||
assert.equal(h.mq.movements(b.userId, {}).alliedIncoming.length, 0);
|
||||
});
|
||||
|
||||
// ---- shared report folder (HTTP, so routes, permissions and schemas are covered)
|
||||
const { createTestServer } = require('./helpers');
|
||||
const { createReport } = require('../server/military/reports');
|
||||
|
||||
test('shared reports: share, list, read, permissions, retention, unshare', async () => {
|
||||
const t = await createTestServer({ contract: true });
|
||||
try {
|
||||
const lead = await t.signupPeering('lead'), mem = await t.signupPeering('mem'), out = await t.signupPeering('outsider');
|
||||
const mk = await t.api('/alliances', { method: 'POST', body: { name: 'Folder', tag: 'FLD' } }, lead.token);
|
||||
const aid = mk.body.allianceId;
|
||||
const inv = await t.api('/alliances/' + aid + '/invite', { method: 'POST', body: { operatorId: mem.operatorId } }, lead.token);
|
||||
await t.api('/alliance-invites/' + inv.body.inviteId + '/accept', { method: 'POST' }, mem.token);
|
||||
|
||||
// two reports: one for lead, one for outsider
|
||||
const ctx = { db: t.srv.db, enqueue: (e) => t.srv.scheduler.enqueue(e), notify: () => {} };
|
||||
const now = t.clock.now();
|
||||
const rid = createReport(ctx, { worldId: 1, type: 'raid', now, summary: { s: 1 }, data: { secret: 'x' }, recipients: [{ userId: lead.userId, role: 'attacker' }] });
|
||||
const rid2 = createReport(ctx, { worldId: 1, type: 'scan', now, summary: {}, data: {}, recipients: [{ userId: out.userId, role: 'attacker' }] });
|
||||
|
||||
// sharing needs to be a recipient and an alliance member
|
||||
assert.equal((await t.api('/reports/' + rid2 + '/share', { method: 'POST' }, lead.token)).status, 404, 'not your report');
|
||||
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'POST' }, out.token)).status, 404, 'a stranger cannot even see it exists');
|
||||
const outRep = createReport(ctx, { worldId: 1, type: 'raid', now, summary: {}, data: {}, recipients: [{ userId: out.userId, role: 'attacker' }] });
|
||||
const noAll = await t.api('/reports/' + outRep + '/share', { method: 'POST' }, out.token);
|
||||
assert.equal(noAll.body.error.code, 'not_in_alliance');
|
||||
|
||||
// the folder is empty, only members read it
|
||||
assert.deepEqual((await t.api('/alliances/' + aid + '/reports', {}, mem.token)).body.items, []);
|
||||
assert.equal((await t.api('/alliances/' + aid + '/reports', {}, out.token)).status, 403);
|
||||
|
||||
// share; retention is pushed out; repeating is a no-op
|
||||
t.clock.advance(10 * 24 * 3600e3);
|
||||
const sh = await t.api('/reports/' + rid + '/share', { method: 'POST' }, lead.token);
|
||||
assert.equal(sh.status, 200);
|
||||
assert.equal(sh.body.changed, true);
|
||||
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'POST' }, lead.token)).body.changed, false);
|
||||
const exp = t.srv.db.get('SELECT expires_at FROM reports WHERE id = ?', rid).expires_at;
|
||||
assert.equal(exp, t.clock.now() + D.MILITARY.reportRetentionMs, 'shared report is kept 14 days from the share');
|
||||
|
||||
// the member reads it although they were never a participant; the stranger still cannot
|
||||
const list = await t.api('/alliances/' + aid + '/reports', {}, mem.token);
|
||||
assert.equal(list.body.items.length, 1);
|
||||
assert.equal(list.body.items[0].id, rid);
|
||||
assert.equal(list.body.items[0].sharedBy.name, 'lead');
|
||||
const one = await t.api('/alliances/' + aid + '/reports/' + rid, {}, mem.token);
|
||||
assert.equal(one.body.report.data.secret, 'x');
|
||||
assert.equal((await t.api('/alliances/' + aid + '/reports/' + rid, {}, out.token)).status, 403);
|
||||
assert.equal((await t.api('/reports/' + rid, {}, mem.token)).status, 404, 'the personal report list is unchanged: sharing is not handing out the participant role');
|
||||
|
||||
// the member cannot remove the leader's share; the leader can; the report row survives it
|
||||
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'DELETE' }, mem.token)).status, 403);
|
||||
assert.equal((await t.api('/reports/' + rid + '/share', { method: 'DELETE' }, lead.token)).body.changed, true);
|
||||
assert.equal((await t.api('/alliances/' + aid + '/reports', {}, mem.token)).body.items.length, 0);
|
||||
assert.ok(t.srv.db.get('SELECT 1 AS x FROM reports WHERE id = ?', rid));
|
||||
|
||||
// a member shares their own; deleting the report (cleanup) takes the share with it
|
||||
const mrep = createReport(ctx, { worldId: 1, type: 'raid', now: t.clock.now(), summary: {}, data: {}, recipients: [{ userId: mem.userId, role: 'defender' }] });
|
||||
assert.equal((await t.api('/reports/' + mrep + '/share', { method: 'POST' }, mem.token)).status, 200);
|
||||
assert.equal((await t.api('/reports/' + mrep + '/share', { method: 'DELETE' }, mem.token)).status, 200, 'the sharer may remove their own');
|
||||
await t.api('/reports/' + mrep + '/share', { method: 'POST' }, mem.token);
|
||||
t.srv.db.run('DELETE FROM reports WHERE id = ?', mrep);
|
||||
assert.equal(t.srv.db.get('SELECT COUNT(*) AS n FROM report_shares WHERE report_id = ?', mrep).n, 0);
|
||||
|
||||
// cursor: newest first, next page holds older ones
|
||||
const ids = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = createReport(ctx, { worldId: 1, type: 'raid', now: t.clock.now(), summary: {}, data: {}, recipients: [{ userId: lead.userId, role: 'attacker' }] });
|
||||
await t.api('/reports/' + r + '/share', { method: 'POST' }, lead.token);
|
||||
ids.push(r);
|
||||
}
|
||||
const p1 = await t.api('/alliances/' + aid + '/reports?limit=2', {}, lead.token);
|
||||
assert.deepEqual(p1.body.items.map((i) => i.id), [ids[2], ids[1]]);
|
||||
const p2 = await t.api('/alliances/' + aid + '/reports?limit=2&after=' + p1.body.next, {}, lead.token);
|
||||
assert.deepEqual(p2.body.items.map((i) => i.id), [ids[0]]);
|
||||
assert.equal(p2.body.next, null);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
128
test/endgame-rules.test.js
Normal file
128
test/endgame-rules.test.js
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
'use strict';
|
||||
/* End game and trade rules as pure functions (public/js/rules.js, data.js). */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const R = require('../public/js/rules.js');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
test('backbone sites: 7 fixed positions per (seed, radius), on plain land, spread out, never in the free centre, deterministic', () => {
|
||||
for (const [seed, radius] of [[4242, 50], [1, 50], [99, 20], [7, 150], [123456, 30]]) {
|
||||
const sites = R.backboneSites(seed, radius);
|
||||
assert.equal(sites.length, D.ENDGAME.sites, 'seed ' + seed + ' radius ' + radius);
|
||||
assert.deepEqual(sites.map((s) => s.index), [0, 1, 2, 3, 4, 5, 6]);
|
||||
for (const s of sites) {
|
||||
assert.equal(R.terrainAt(seed, radius, s.x, s.y).type, 'land');
|
||||
assert.ok(Math.abs(s.x) > 2 || Math.abs(s.y) > 2, 'not in the free centre');
|
||||
assert.ok(Math.abs(s.x) <= radius && Math.abs(s.y) <= radius);
|
||||
for (const o of sites) if (o !== s) assert.ok(R.distance(s.x, s.y, o.x, o.y) >= D.ENDGAME.siteMinSpacing, 'spacing');
|
||||
}
|
||||
assert.deepEqual(R.backboneSites(seed, radius), sites, 'same input, same answer');
|
||||
}
|
||||
assert.notDeepEqual(R.backboneSites(1, 50), R.backboneSites(2, 50), 'the seed decides');
|
||||
});
|
||||
|
||||
test('tileAt: a landing site is plain land until world day openDay, then reads backbone; old 4-argument callers see no change', () => {
|
||||
const seed = 4242, radius = 50;
|
||||
const s = R.backboneSites(seed, radius)[3];
|
||||
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y), { type: 'land' });
|
||||
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, 0), { type: 'land' });
|
||||
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, D.ENDGAME.openDay - 0.001), { type: 'land' });
|
||||
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, D.ENDGAME.openDay), { type: 'backbone', site: 3 });
|
||||
assert.deepEqual(R.tileAt(seed, radius, s.x, s.y, 500), { type: 'backbone', site: 3 });
|
||||
// every other tile is identical with and without age
|
||||
let seen = 0;
|
||||
for (let x = -radius; x <= radius; x += 1) for (let y = -radius; y <= radius; y += 3) {
|
||||
const a = R.tileAt(seed, radius, x, y), b = R.tileAt(seed, radius, x, y, 1000);
|
||||
if (b.type === 'backbone') { seen++; assert.ok(R.isBackboneSite(seed, radius, x, y)); } else assert.deepEqual(a, b);
|
||||
}
|
||||
assert.ok(seen >= 1);
|
||||
assert.equal(R.tileAt(seed, radius, radius + 1, 0, 1000).type, 'void');
|
||||
});
|
||||
|
||||
test('spawning and settling never use a landing site, not even before it shows', () => {
|
||||
const seed = 4242, radius = 50;
|
||||
const sites = R.backboneSites(seed, radius);
|
||||
const towns = [];
|
||||
for (let n = 0; n < 150; n++) {
|
||||
const p = R.pickSpawn(seed, radius, n, towns);
|
||||
if (!p) break;
|
||||
assert.ok(!sites.some((s) => s.x === p.x && s.y === p.y), 'spawn ' + n + ' on a landing site');
|
||||
towns.push(p);
|
||||
}
|
||||
assert.ok(towns.length > 100);
|
||||
const s = sites[0];
|
||||
const ok = { tileType: 'land', occupied: false, nearestOwnDist: 3, ownedCount: 1, footprint: 1e9 };
|
||||
assert.equal(R.settleCheck(ok).ok, true);
|
||||
const refused = R.settleCheck(Object.assign({ backbone: R.isBackboneSite(seed, radius, s.x, s.y) }, ok));
|
||||
assert.equal(refused.ok, false);
|
||||
assert.equal(refused.reason, 'backbone_site');
|
||||
assert.equal(R.settleCheck({ tileType: 'backbone', occupied: false, nearestOwnDist: 3, ownedCount: 1, footprint: 1e9 }).ok, false);
|
||||
});
|
||||
|
||||
test('world phase and age: running, backbone_open from day 100 / speed, ended wins over everything', () => {
|
||||
const DAY = 24 * 3600e3;
|
||||
assert.equal(R.worldAgeDays(1000, 1000, 1), 0);
|
||||
assert.equal(R.worldAgeDays(1000, 1000 - 5, 1), 0, 'never negative');
|
||||
assert.equal(R.worldAgeDays(0, 10 * DAY, 3), 30);
|
||||
assert.equal(R.worldPhase('running', 99.9), 'running');
|
||||
assert.equal(R.worldPhase('running', 100), 'backbone_open');
|
||||
assert.equal(R.worldPhase('ended', 5), 'ended');
|
||||
assert.equal(R.worldPhase('ended', 500), 'ended');
|
||||
// speed 4: day 100 of world time arrives after 25 real days
|
||||
assert.ok(R.worldAgeDays(0, 25 * DAY, 4) >= D.ENDGAME.openDay);
|
||||
});
|
||||
|
||||
test('backbone defence grows with world age and node level; cost and time curves are monotonic and far above any other building', () => {
|
||||
const seed = 4242;
|
||||
const d0 = R.backboneDefence(seed, 10, 10, 100, 0), d50 = R.backboneDefence(seed, 10, 10, 100, 50), dOld = R.backboneDefence(seed, 10, 10, 200, 0);
|
||||
assert.ok(d50 > d0 && dOld > d0);
|
||||
assert.equal(R.backboneDefence(seed, 10, 10, 100, 0), Math.round(R.incumbentDefence(seed, 10, 10, 100) * D.ENDGAME.defenceMult));
|
||||
assert.ok(d0 > 10 * R.incumbentDefence(seed, 10, 10, 100), 'heavy: well above an ordinary incumbent site');
|
||||
let prev = 0, prevT = 0, sumFiber = 0;
|
||||
for (let l = 1; l <= D.ENDGAME.maxLevel; l++) {
|
||||
const c = R.backboneCost(l), t = R.backboneTimeMs(l, 1);
|
||||
assert.ok(c.fiber > prev && t > prevT, 'level ' + l);
|
||||
prev = c.fiber; prevT = t; sumFiber += c.fiber;
|
||||
}
|
||||
assert.equal(R.backboneCost(1).fiber, D.BUILDINGS.backbone_node.cost.fiber);
|
||||
assert.ok(R.backboneCost(1).fiber > R.buildingCost('rollout_depot', 1).fiber * 10, 'level 1 already dwarfs the dearest ordinary building level 1');
|
||||
assert.ok(R.backboneCost(D.ENDGAME.maxLevel).fiber > R.buildingCost('rack_hall', 20).fiber, 'level 100 > the best ordinary building');
|
||||
assert.equal(R.backboneTimeMs(1, 4), R.backboneTimeMs(1, 1) / 4, 'world speed divides');
|
||||
assert.ok(sumFiber > 1e6, 'millions in total (a first guess, not balanced)');
|
||||
});
|
||||
|
||||
test('backbonePlan: one level at a time, paid from the pool', () => {
|
||||
const pool = (n) => ({ fiber: n, hardware: n, capital: n });
|
||||
assert.equal(R.backbonePlan({ level: 0, build: null, pool: pool(100) }, 1).code, 'not_enough_resources');
|
||||
assert.equal(R.backbonePlan({ level: 0, build: null, pool: { fiber: 4000, hardware: 4000, capital: 3999 } }, 1).code, 'not_enough_resources');
|
||||
const ok = R.backbonePlan({ level: 0, build: null, pool: pool(4000) }, 1);
|
||||
assert.equal(ok.ok, true); assert.equal(ok.toLevel, 1); assert.deepEqual(ok.cost, R.backboneCost(1));
|
||||
assert.equal(R.backbonePlan({ level: 3, build: { to: 4 }, pool: pool(1e9) }, 1).code, 'already_queued');
|
||||
assert.equal(R.backbonePlan({ level: 100, build: null, pool: pool(1e12) }, 1).code, 'max_level');
|
||||
});
|
||||
|
||||
test('trade terms: ratio band 1:2 both ways, one transport link per side, distinct resources, whole numbers', () => {
|
||||
const t = (o) => R.tradeTermsCheck(Object.assign({ giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: 10 }, o));
|
||||
assert.equal(t().ok, true);
|
||||
assert.equal(t({ giveAmount: 200, wantAmount: 100 }).ok, true);
|
||||
assert.equal(t({ giveAmount: 100, wantAmount: 200 }).ok, true);
|
||||
assert.equal(t({ giveAmount: 201, wantAmount: 100 }).code, 'trade_ratio');
|
||||
assert.equal(t({ giveAmount: 100, wantAmount: 201 }).code, 'trade_ratio');
|
||||
assert.equal(t({ giveAmount: D.TRANSPORT.capacityPerLink, wantAmount: D.TRANSPORT.capacityPerLink }).ok, true);
|
||||
assert.equal(t({ giveAmount: D.TRANSPORT.capacityPerLink + 1, wantAmount: D.TRANSPORT.capacityPerLink }).code, 'capacity_exceeded');
|
||||
assert.equal(t({ wantRes: 'fiber' }).code, 'validation_failed');
|
||||
assert.equal(t({ giveRes: 'power' }).code, 'validation_failed');
|
||||
assert.equal(t({ giveAmount: 0.5 }).code, 'validation_failed');
|
||||
assert.equal(t({ maxDistance: 0 }).code, 'validation_failed');
|
||||
assert.equal(R.tradeReach(0), 0);
|
||||
assert.equal(R.tradeReach(3), 3 * D.TRADE.reachPerLevel);
|
||||
assert.equal(R.tradeInRange(10, 10, 1), true);
|
||||
assert.equal(R.tradeInRange(10.01, 20, 1), false, "the taker's reach limits");
|
||||
assert.equal(R.tradeInRange(5, 4, 5), false, "the offer's max distance limits");
|
||||
assert.equal(R.tradeInRange(1, 50, 0), false, 'no exchange');
|
||||
});
|
||||
|
||||
test('data: the end-game level cap matches the Backbone node building', () => {
|
||||
assert.equal(D.ENDGAME.maxLevel, D.BUILDINGS.backbone_node.maxLevel);
|
||||
assert.equal(D.BUILDINGS.backbone_node.special, 'backbone');
|
||||
});
|
||||
189
test/push-game.test.js
Normal file
189
test/push-game.test.js
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
'use strict';
|
||||
/* Which hint goes to whom (server/pushHooks.js), end to end: REST commands and the event queue on a fake clock, real
|
||||
* WebSocket clients. Push is only a hint: every assertion on a hint is paired with the REST/DB truth it points at. */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { createTestServer } = require('./helpers');
|
||||
const { login, sleep } = require('./push-helpers');
|
||||
const D = require('../public/js/data.js');
|
||||
const H = D.HOUR_MS;
|
||||
|
||||
const post = (body) => ({ method: 'POST', body });
|
||||
|
||||
test('build: command hint on all devices of the owner, then town + notification when it finishes; nothing for others', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const alice = await t.signup('alice'), bob = await t.signup('bobby');
|
||||
const login2 = await t.api('/auth/login', post({ username: 'alice', password: 'correct horse battery' }));
|
||||
const a1 = await login(t.srv, alice.token), a2 = await login(t.srv, login2.body.token), b = await login(t.srv, bob.token);
|
||||
|
||||
const r = await t.api('/towns/' + alice.townId + '/build', post({ key: 'f1' }), alice.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
for (const c of [a1, a2]) await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId);
|
||||
await sleep(50);
|
||||
|
||||
for (const c of [a1, a2]) c.msgs.length = 0;
|
||||
t.clock.advance(r.body.dueAt - t.clock.now());
|
||||
t.srv.scheduler.runDue(); // the buildDone event fires
|
||||
for (const c of [a1, a2]) {
|
||||
const town = await c.waitFor((m) => m.type === 'town' && m.townId === alice.townId);
|
||||
assert.deepEqual(town, { type: 'town', townId: alice.townId });
|
||||
const n = await c.waitFor((m) => m.type === 'notification');
|
||||
assert.equal(n.kind, 'build_done');
|
||||
const row = t.srv.db.get('SELECT type FROM notifications WHERE id = ?', n.id);
|
||||
assert.equal(row.type, 'build_done', 'the id points at a real notification row');
|
||||
}
|
||||
assert.deepEqual((await b.settle(100)).filter((m) => m.type !== 'ready'), [], 'another player hears nothing');
|
||||
const poll = await t.api('/notifications', {}, alice.token);
|
||||
assert.ok(poll.body.items.some((x) => x.id === a1.msgs.find((m) => m.type === 'notification').id), 'and REST agrees');
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('train done: town + notification (train_done)', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const a = await t.signup('alice');
|
||||
t.clock.advance(73 * H);
|
||||
for (const [k, lv] of [['ops_lab', 3], ['noc', 2]]) t.srv.db.run('INSERT OR REPLACE INTO buildings (town_id, key, type, level) VALUES (?, ?, ?, ?)', a.townId, k, k, lv);
|
||||
t.srv.db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
|
||||
const c = await login(t.srv, a.token);
|
||||
const r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 5 }), a.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
await c.waitFor((m) => m.type === 'town'); // command hint
|
||||
await c.settle(50); c.msgs.length = 0;
|
||||
t.clock.set(r.body.dueAt);
|
||||
t.srv.scheduler.runDue();
|
||||
await c.waitFor((m) => m.type === 'town' && m.townId === a.townId);
|
||||
const n = await c.waitFor((m) => m.type === 'notification');
|
||||
assert.equal(n.kind, 'train_done');
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
// alice raids bobby: bobby gets 'incoming' (only him), a report lands for both
|
||||
async function raidSetup(t) {
|
||||
const a = await t.signup('alice'), b = await t.signup('bobby');
|
||||
const db = t.srv.db;
|
||||
t.clock.advance(73 * H); // beginner protection over
|
||||
for (const [k, 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, k, k, lv);
|
||||
db.run('UPDATE towns SET fiber = 5000, hardware = 5000, capital = 5000 WHERE id = ?', a.townId);
|
||||
let r = await t.api('/towns/' + a.townId + '/train', post({ unit: 'script_crew', count: 20 }), a.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
t.clock.advance(3 * H);
|
||||
t.srv.scheduler.runDue();
|
||||
return { a, b };
|
||||
}
|
||||
|
||||
test('incoming attack: defender gets incoming (+ notification), attacker does not; then report hints for both', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const { a, b } = await raidSetup(t);
|
||||
const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token);
|
||||
await sleep(30); ca.msgs.length = 0; cb.msgs.length = 0;
|
||||
|
||||
const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const inc = await cb.waitFor((m) => m.type === 'incoming');
|
||||
assert.deepEqual(inc, { type: 'incoming', townId: b.townId, arriveAt: r.body.arriveAt }, 'town and ETA only, no type, no origin');
|
||||
const note = await cb.waitFor((m) => m.type === 'notification' && m.kind === 'incoming');
|
||||
assert.ok(t.srv.db.get('SELECT 1 AS x FROM notifications WHERE id = ? AND user_id = ?', note.id, b.userId));
|
||||
const mine = await ca.settle(100);
|
||||
assert.ok(!mine.some((m) => m.type === 'incoming' || m.type === 'notification'), 'the attacker gets no warning: ' + JSON.stringify(mine));
|
||||
assert.ok(mine.some((m) => m.type === 'town' && m.townId === a.townId), 'but a town hint for the POP that sent the units');
|
||||
assert.ok(!cb.msgs.some((m) => m.type === 'town'), 'no plain town hint for the target at launch (the warning carries the ETA)');
|
||||
|
||||
ca.msgs.length = 0; cb.msgs.length = 0;
|
||||
t.clock.set(r.body.arriveAt);
|
||||
t.srv.scheduler.runDue(); // combat resolves
|
||||
const rep = t.srv.db.get('SELECT id FROM reports ORDER BY id DESC LIMIT 1');
|
||||
assert.ok(rep);
|
||||
for (const c of [ca, cb]) {
|
||||
const m = await c.waitFor((x) => x.type === 'report');
|
||||
assert.deepEqual(m, { type: 'report', id: rep.id });
|
||||
await c.waitFor((x) => x.type === 'notification' && x.kind === 'report');
|
||||
}
|
||||
await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId); // the attacked POP changed
|
||||
const view = await t.api('/reports/' + rep.id, {}, b.token);
|
||||
assert.equal(view.status, 200, 'the id in the hint is fetchable over REST');
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('recall: the target owner learns the warning is gone (town hint), the sender gets his POP hint', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const { a, b } = await raidSetup(t);
|
||||
const ca = await login(t.srv, a.token), cb = await login(t.srv, b.token);
|
||||
const r = await t.api('/movements', post({ fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 10 } }), a.token);
|
||||
await cb.waitFor((m) => m.type === 'incoming');
|
||||
await sleep(50); cb.msgs.length = 0; ca.msgs.length = 0;
|
||||
const rc = await t.api('/movements/' + r.body.movementId + '/recall', post({}), a.token);
|
||||
assert.equal(rc.status, 200, JSON.stringify(rc.body));
|
||||
await cb.waitFor((m) => m.type === 'town' && m.townId === b.townId);
|
||||
await ca.waitFor((m) => m.type === 'town' && m.townId === a.townId);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('messages and alliance invites: message hint with id, notification with kind alliance_invite', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const lead = await t.signupPeering('leader'), bob = await t.signup('bobby');
|
||||
const cl = await login(t.srv, lead.token), cb = await login(t.srv, bob.token);
|
||||
|
||||
let r = await t.api('/messages', post({ toOperatorId: bob.operatorId, text: 'hello there' }), lead.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const m = await cb.waitFor((x) => x.type === 'message');
|
||||
assert.deepEqual(m, { type: 'message', id: r.body.messageId });
|
||||
assert.equal((await cb.waitFor((x) => x.type === 'notification' && x.kind === 'message')).kind, 'message');
|
||||
assert.ok(!(await cl.settle(50)).some((x) => x.type === 'message'), 'the sender gets no message hint');
|
||||
|
||||
r = await t.api('/alliances', post({ name: 'Pushers', tag: 'PSH' }), lead.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
const inv = await t.api('/alliances/' + r.body.allianceId + '/invite', post({ operatorId: bob.operatorId }), lead.token);
|
||||
assert.equal(inv.status, 201, JSON.stringify(inv.body));
|
||||
const n = await cb.waitFor((x) => x.type === 'notification' && x.kind === 'alliance_invite');
|
||||
assert.ok(t.srv.db.get("SELECT 1 AS x FROM notifications WHERE id = ? AND type = 'alliance_invite'", n.id));
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('hints are coalesced: identical hints produced in one tick go out once, distinct ones all arrive in order', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const a = await t.signup('alice');
|
||||
const c = await login(t.srv, a.token);
|
||||
for (let i = 0; i < 50; i++) t.srv.push.toTown(a.townId, { type: 'town', townId: a.townId }); // e.g. a long catch-up
|
||||
t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' });
|
||||
t.srv.push.toUser(a.userId, { type: 'notification', id: 2, kind: 'x' });
|
||||
t.srv.push.toUser(a.userId, { type: 'notification', id: 1, kind: 'x' });
|
||||
await c.waitFor((m) => m.type === 'notification' && m.id === 2);
|
||||
await c.settle(50);
|
||||
const got = c.msgs.filter((m) => m.type !== 'ready');
|
||||
assert.deepEqual(got, [{ type: 'town', townId: a.townId }, { type: 'notification', id: 1, kind: 'x' }, { type: 'notification', id: 2, kind: 'x' }]);
|
||||
t.srv.push.toUser(999999, { type: 'town', townId: 1 }); // unknown user: silently nothing
|
||||
t.srv.push.toTown(999999, { type: 'town', townId: 999999 }); // unknown POP: silently nothing
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('rollback: a notification written by an event or command that then fails is never pushed (hints follow the commit)', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const a = await t.signup('alice');
|
||||
const c = await login(t.srv, a.token);
|
||||
const sc = t.srv.scheduler;
|
||||
sc.register('boom', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'ghost', {}); throw new Error('handler failed'); });
|
||||
sc.register('fine', (ctx, ev) => { ctx.notify(a.userId, ev.worldId, 'real', {}); });
|
||||
t.srv.commands.handlers.boomCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'ghost_cmd', {}); throw new Error('command failed'); };
|
||||
t.srv.commands.handlers.fineCmd = (ctx) => { ctx.scheduler.notify(a.userId, null, 'real_cmd', {}); return {}; };
|
||||
const worldId = t.srv.db.get('SELECT id FROM worlds').id;
|
||||
const now = t.clock.now();
|
||||
sc.enqueue({ worldId, dueAt: now + 10, type: 'boom', payload: {} });
|
||||
sc.enqueue({ worldId, dueAt: now + 20, type: 'fine', payload: {} });
|
||||
t.clock.advance(100);
|
||||
sc.runDue();
|
||||
assert.throws(() => t.srv.commands.run('boomCmd', {}), /command failed/);
|
||||
t.srv.commands.run('fineCmd', {});
|
||||
await c.waitFor((m) => m.kind === 'real_cmd');
|
||||
const kinds = (await c.settle(60)).filter((m) => m.type === 'notification').map((m) => m.kind);
|
||||
assert.deepEqual(kinds, ['real', 'real_cmd']);
|
||||
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM notifications WHERE type IN ('ghost', 'ghost_cmd')").n, 0, 'the rows rolled back too');
|
||||
assert.equal(sc.outbox.length, 0);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
56
test/push-helpers.js
Normal file
56
test/push-helpers.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
'use strict';
|
||||
/* Shared helpers of the push tests (no tests in here): a recording WebSocket client around the real `ws` package. */
|
||||
const WebSocket = require('ws');
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// Opens ws://127.0.0.1:port/ws. Resolves { ws, msgs, closed, open, waitFor(pred, ms), expectNone(ms), send(obj), auth(token) }.
|
||||
// `closed` resolves { code, reason } when the socket closes. Rejects with { status } when the upgrade is refused.
|
||||
function connect(srv, o) {
|
||||
o = o || {};
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket('ws://127.0.0.1:' + srv.port + (o.path || '/ws'), Object.assign({ headers: o.headers || {} }, o.wsOptions || {}));
|
||||
const msgs = [];
|
||||
const waiters = [];
|
||||
let closedResolve;
|
||||
const closed = new Promise((r) => { closedResolve = r; });
|
||||
const c = {
|
||||
ws, msgs, closed,
|
||||
send: (obj) => ws.send(typeof obj === 'string' ? obj : JSON.stringify(obj)),
|
||||
auth: (token) => c.send({ type: 'auth', token }),
|
||||
// first message (already received or still to come) matching pred, within ms
|
||||
waitFor(pred, ms) {
|
||||
const hit = msgs.find(pred);
|
||||
if (hit) return Promise.resolve(hit);
|
||||
return new Promise((res, rej) => {
|
||||
const t = setTimeout(() => { const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); rej(new Error('no matching message in ' + (ms || 2000) + ' ms; got ' + JSON.stringify(msgs))); }, ms || 2000);
|
||||
const w = { pred, res: (m) => { clearTimeout(t); res(m); } };
|
||||
waiters.push(w);
|
||||
});
|
||||
},
|
||||
// wait ms, then return everything received so far
|
||||
async settle(ms) { await sleep(ms === undefined ? 80 : ms); return msgs.slice(); },
|
||||
async connectAndAuth(token) { c.auth(token); return c.waitFor((m) => m.type === 'ready'); },
|
||||
};
|
||||
ws.on('message', (d) => {
|
||||
let m; try { m = JSON.parse(d.toString()); } catch (e) { m = { raw: d.toString() }; }
|
||||
msgs.push(m);
|
||||
for (let i = waiters.length - 1; i >= 0; i--) if (waiters[i].pred(m)) { const w = waiters.splice(i, 1)[0]; w.res(m); }
|
||||
});
|
||||
ws.on('close', (code, reason) => closedResolve({ code, reason: reason.toString() }));
|
||||
ws.on('unexpected-response', (req, res) => { res.resume(); reject({ status: res.statusCode }); });
|
||||
ws.on('error', (err) => { if (!/Unexpected server response/.test(err.message)) { /* closed or reset: `closed` reports it */ } });
|
||||
ws.on('open', () => resolve(c));
|
||||
});
|
||||
}
|
||||
|
||||
// Connect and authenticate in one go.
|
||||
async function login(srv, token, o) {
|
||||
const c = await connect(srv, o);
|
||||
await c.connectAndAuth(token);
|
||||
return c;
|
||||
}
|
||||
|
||||
const within = (p, ms, label) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error('timeout after ' + ms + ' ms: ' + (label || ''))), ms))]);
|
||||
|
||||
module.exports = { connect, login, sleep, within };
|
||||
193
test/push-ws.test.js
Normal file
193
test/push-ws.test.js
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
'use strict';
|
||||
/* WebSocket transport (server/push.js): auth, limits, keepalive, revocation, shutdown. Real `ws` client against
|
||||
* createServer on port 0 with the fake clock. Game hints are in push-game.test.js. */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const WebSocket = require('ws');
|
||||
const { createTestServer } = require('./helpers');
|
||||
const { connect, login, sleep, within } = require('./push-helpers');
|
||||
|
||||
test('auth: ready carries the server clock, ping gets pong, REST token works as ws token', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
t.clock.advance(12345);
|
||||
const c = await connect(t.srv);
|
||||
c.auth(u.token);
|
||||
const ready = await c.waitFor((m) => m.type === 'ready');
|
||||
assert.deepEqual(Object.keys(ready).sort(), ['serverTime', 'type']);
|
||||
assert.equal(ready.serverTime, t.clock.now());
|
||||
c.send({ type: 'ping' });
|
||||
const pong = await c.waitFor((m) => m.type === 'pong');
|
||||
assert.equal(pong.serverTime, t.clock.now());
|
||||
assert.equal(t.srv.push.stats().users, 1);
|
||||
c.ws.close();
|
||||
await c.closed;
|
||||
await sleep(20);
|
||||
assert.deepEqual(t.srv.push.stats(), { connections: 0, users: 0, ips: 0 }, 'registry is empty after close');
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('auth: bad token, first message not auth, junk first message: close 4401, never a ready', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
for (const first of [{ type: 'auth', token: 'x'.repeat(43) }, { type: 'auth' }, { type: 'auth', token: 12345 }, { type: 'ping' }, 'not json', '[1,2]', { type: 'auth', token: u.token + 'x' }]) {
|
||||
const c = await connect(t.srv);
|
||||
c.send(first);
|
||||
const r = await within(c.closed, 2000, JSON.stringify(first));
|
||||
assert.equal(r.code, 4401, JSON.stringify(first));
|
||||
assert.ok(!c.msgs.some((m) => m.type === 'ready'));
|
||||
}
|
||||
// a token in the URL is ignored: auth is the first MESSAGE only
|
||||
const c = await connect(t.srv, { path: '/ws?token=' + u.token });
|
||||
c.send({ type: 'ping' });
|
||||
assert.equal((await c.closed).code, 4401);
|
||||
await sleep(30);
|
||||
assert.equal(t.srv.push.stats().connections, 0);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('auth timeout: no message within wsAuthTimeoutMs closes 4408', async () => {
|
||||
const t = await createTestServer({ server: { wsAuthTimeoutMs: 150 } });
|
||||
try {
|
||||
const c = await connect(t.srv);
|
||||
const r = await within(c.closed, 2000);
|
||||
assert.equal(r.code, 4408);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('upgrade checks: origin, path, per-IP cap (released on close)', async () => {
|
||||
const t = await createTestServer({ server: { maxConnPerIp: 2, allowedOrigins: ['https://game.example.com'] } });
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
await assert.rejects(connect(t.srv, { headers: { Origin: 'https://evil.example' } }), { status: 403 });
|
||||
await assert.rejects(connect(t.srv, { headers: { Origin: 'null' } }), { status: 403 });
|
||||
await assert.rejects(connect(t.srv, { path: '/socket' }), { status: 404 });
|
||||
const ok1 = await login(t.srv, u.token, { headers: { Origin: 'https://game.example.com' } }); // allowlisted
|
||||
const ok2 = await login(t.srv, u.token, { headers: { Origin: 'http://127.0.0.1:' + t.srv.port } }); // same host as Host
|
||||
await assert.rejects(connect(t.srv), { status: 429 }, 'third socket from one address');
|
||||
ok1.ws.close(); await ok1.closed; await sleep(20);
|
||||
const ok3 = await login(t.srv, u.token); // no Origin: non-browser client
|
||||
assert.equal(t.srv.push.stats().connections, 2);
|
||||
ok2.ws.close(); ok3.ws.close();
|
||||
await Promise.all([ok2.closed, ok3.closed]);
|
||||
// refused requests never leaked a count
|
||||
await sleep(20);
|
||||
assert.equal(t.srv.push.stats().ips, 0);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('rate limit per socket closes 4429; the bucket refills', async () => {
|
||||
const t = await createTestServer({ server: { wsRate: 2, wsBurst: 4 } });
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
const calm = await login(t.srv, u.token);
|
||||
for (let i = 0; i < 3; i++) { calm.send({ type: 'ping' }); await sleep(600); } // 1.7 msg/s: fine
|
||||
assert.equal(calm.msgs.filter((m) => m.type === 'pong').length, 3);
|
||||
calm.ws.close();
|
||||
const c = await login(t.srv, u.token);
|
||||
for (let i = 0; i < 12; i++) c.send({ type: 'ping' }); // burst of 12 > 4 + refill
|
||||
assert.equal((await within(c.closed, 2000)).code, 4429);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('bad-message budget closes 4400; oversize payload closes 1009', async () => {
|
||||
const t = await createTestServer({ server: { wsBadBudget: 3 } });
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
const c = await login(t.srv, u.token);
|
||||
c.send({ type: 'subscribe' });
|
||||
c.send('not json');
|
||||
c.send({ type: 'auth', token: u.token }); // already authenticated: counts as bad
|
||||
assert.equal((await within(c.closed, 2000)).code, 4400);
|
||||
|
||||
const big = await login(t.srv, u.token);
|
||||
big.send(JSON.stringify({ type: 'ping', pad: 'x'.repeat(2000) }));
|
||||
assert.equal((await within(big.closed, 2000)).code, 1009);
|
||||
|
||||
const bin = await login(t.srv, u.token);
|
||||
bin.ws.send(Buffer.from([1, 2, 3])); // binary frames are bad messages too
|
||||
bin.ws.send(Buffer.from([1, 2, 3]));
|
||||
bin.ws.send(Buffer.from([1, 2, 3]));
|
||||
assert.equal((await within(bin.closed, 2000)).code, 4400);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('keepalive: a socket that never answers pings is terminated', async () => {
|
||||
const t = await createTestServer({ server: { wsPingMs: 60 } });
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
const live = await login(t.srv, u.token); // answers pings (ws default)
|
||||
const dead = await login(t.srv, u.token, { wsOptions: { autoPong: false } }); // swallows them
|
||||
const r = await within(dead.closed, 2000, 'dead socket should be dropped');
|
||||
assert.equal(r.code, 1006);
|
||||
await sleep(200);
|
||||
assert.equal(live.ws.readyState, WebSocket.OPEN, 'a healthy socket stays');
|
||||
assert.equal(t.srv.push.stats().connections, 1);
|
||||
live.ws.close();
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('revoked token and banned user are disconnected at the next ping tick; other devices stay', async () => {
|
||||
const t = await createTestServer({ server: { wsPingMs: 60 } });
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
const login2 = await t.api('/auth/login', { method: 'POST', body: { username: 'alice', password: 'correct horse battery' } });
|
||||
const phone = login2.body.token;
|
||||
const a = await login(t.srv, u.token), b = await login(t.srv, phone);
|
||||
let r = await t.api('/auth/logout', { method: 'POST' }, u.token); // revoke device 1
|
||||
assert.equal(r.status, 200);
|
||||
const res = await within(a.closed, 2000, 'revoked socket');
|
||||
assert.equal(res.code, 4401); assert.equal(res.reason, 'token_revoked');
|
||||
await sleep(150);
|
||||
assert.equal(b.ws.readyState, WebSocket.OPEN, 'the phone token is still valid');
|
||||
// and a revoked token cannot open a new socket
|
||||
const c = await connect(t.srv);
|
||||
c.auth(u.token);
|
||||
assert.equal((await within(c.closed, 2000)).code, 4401);
|
||||
// ban
|
||||
t.srv.db.run('UPDATE users SET banned = 1 WHERE id = ?', u.userId);
|
||||
assert.equal((await within(b.closed, 2000, 'banned user')).code, 4401);
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
|
||||
test('shutdown: srv.close() closes every socket with 1001 and completes promptly', async () => {
|
||||
const t = await createTestServer();
|
||||
const u = await t.signup('alice');
|
||||
const socks = [await login(t.srv, u.token), await login(t.srv, u.token), await connect(t.srv)]; // two authed, one silent
|
||||
const started = Date.now();
|
||||
await within(t.close(), 4000, 'srv.close()');
|
||||
assert.ok(Date.now() - started < 3000, 'close took ' + (Date.now() - started) + ' ms');
|
||||
for (const s of socks) assert.equal((await within(s.closed, 1000)).code, 1001);
|
||||
});
|
||||
|
||||
test('REST works fully with no socket, with an idle socket, and a failing command pushes nothing', async () => {
|
||||
const t = await createTestServer();
|
||||
try {
|
||||
const u = await t.signup('alice');
|
||||
// no socket at all: build, finish, notification row, all over REST
|
||||
let r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
|
||||
assert.equal(r.status, 201, JSON.stringify(r.body));
|
||||
t.clock.advance(r.body.dueAt - t.clock.now() + 1000);
|
||||
r = await t.api('/notifications', {}, u.token);
|
||||
assert.equal(r.status, 200);
|
||||
assert.ok(r.body.items.some((n) => n.type === 'build_done'));
|
||||
// a connected socket sees no hint for a refused command (rolled back, nothing happened)
|
||||
const c = await login(t.srv, u.token);
|
||||
r = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token);
|
||||
assert.equal(r.status, 201); // sanity: this one is valid
|
||||
await c.waitFor((m) => m.type === 'town'); // the valid build's own hint
|
||||
await c.settle(50); c.msgs.length = 0;
|
||||
const bad = await t.api('/towns/' + u.townId + '/build', { method: 'POST', body: { key: 'f1' } }, u.token); // queue/resources: refused
|
||||
assert.ok(bad.status >= 400, 'second build of the same field is refused: ' + bad.status);
|
||||
assert.deepEqual(await c.settle(100), [], 'no hint for a refused command');
|
||||
// an unauthenticated socket gets no hints either
|
||||
const idle = await connect(t.srv);
|
||||
t.clock.advance(24 * 3600e3);
|
||||
t.srv.scheduler.runDue();
|
||||
assert.deepEqual(await idle.settle(100), []);
|
||||
assert.equal(c.msgs.filter((m) => m.type === 'town').length >= 1, true, 'the authenticated one got its hint');
|
||||
idle.ws.close(); c.ws.close();
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
75
test/trade-api.test.js
Normal file
75
test/trade-api.test.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
'use strict';
|
||||
/* Trade over HTTP: routes, validation, error codes, pagination, and the declared response schemas (contract: true). */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { createTestServer } = require('./helpers');
|
||||
const D = require('../public/js/data.js');
|
||||
|
||||
test('trade API: post, list, take, mine, detail, cancel, errors', async () => {
|
||||
const t = await createTestServer({ contract: true });
|
||||
try {
|
||||
const a = await t.signup('alice'), b = await t.signup('bob'), c = await t.signup('cara');
|
||||
for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3);
|
||||
// cara has no exchange at all
|
||||
const body = (o) => Object.assign({ townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 40 }, o || {});
|
||||
|
||||
const bad = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 500, wantAmount: 200 }) }, a.token);
|
||||
assert.equal(bad.status, 409); assert.equal(bad.body.error.code, 'trade_ratio');
|
||||
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ wantRes: 'fiber' }) }, a.token)).status, 422);
|
||||
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ townId: b.townId }) }, a.token)).status, 404);
|
||||
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body() })).status, 401);
|
||||
|
||||
const made = await t.api('/trade/offers', { method: 'POST', body: body() }, a.token);
|
||||
assert.equal(made.status, 201);
|
||||
const id = made.body.offer.id;
|
||||
assert.equal(made.body.offer.give.amount, 400);
|
||||
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 100, wantAmount: 100, giveRes: 'capital' }) }, a.token)).status, 201);
|
||||
|
||||
const listB = await t.api('/trade/offers', {}, b.token);
|
||||
assert.equal(listB.status, 200);
|
||||
assert.equal(listB.body.items.length, 2);
|
||||
assert.equal(listB.body.items[0].id > listB.body.items[1].id, true, 'newest first');
|
||||
const p1 = await t.api('/trade/offers?limit=1', {}, b.token);
|
||||
assert.equal(p1.body.items.length, 1);
|
||||
const p2 = await t.api('/trade/offers?limit=1&after=' + p1.body.next, {}, b.token);
|
||||
assert.equal(p2.body.items[0].id, id);
|
||||
assert.equal(p2.body.next, null);
|
||||
assert.equal((await t.api('/trade/offers?give=capital', {}, b.token)).body.items.length, 1, 'filter by offered resource');
|
||||
assert.equal((await t.api('/trade/offers?want=capital', {}, b.token)).body.items.length, 0);
|
||||
assert.equal((await t.api('/trade/offers', {}, a.token)).body.items.length, 0, 'not your own');
|
||||
assert.equal((await t.api('/trade/offers', {}, c.token)).body.items.length, 0, 'no exchange: you see nothing');
|
||||
assert.equal((await t.api('/trade/offers?give=gold', {}, b.token)).status, 422);
|
||||
|
||||
const one = await t.api('/trade/offers/' + id, {}, c.token);
|
||||
assert.equal(one.body.offer.status, 'open', 'open offers are public inside the world');
|
||||
|
||||
const acc = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
|
||||
assert.equal(acc.status, 201);
|
||||
assert.equal(acc.body.status, 'accepted');
|
||||
assert.equal((await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token)).body.error.code, 'offer_closed');
|
||||
assert.equal((await t.api('/trade/offers/' + id, {}, c.token)).status, 404, 'closed offers are for the two parties');
|
||||
t.clock.advance(acc.body.arriveAt - t.clock.now());
|
||||
t.srv.scheduler.runDue();
|
||||
const mineA = await t.api('/trade/offers/mine', {}, a.token), mineB = await t.api('/trade/offers/mine?status=completed', {}, b.token);
|
||||
assert.equal(mineA.body.items.length, 2);
|
||||
assert.equal(mineB.body.items[0].status, 'completed');
|
||||
assert.equal(mineB.body.items[0].role, 'acceptor');
|
||||
const notes = await t.api('/notifications', {}, a.token);
|
||||
assert.ok(notes.body.items.some((n) => n.type === 'trade_completed'));
|
||||
|
||||
const other = await t.api('/trade/offers', { method: 'GET' }, b.token);
|
||||
const open = other.body.items[0];
|
||||
assert.equal((await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, b.token)).status, 404);
|
||||
const del = await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, a.token);
|
||||
assert.equal(del.status, 200);
|
||||
assert.deepEqual(del.body.returned, { resource: 'capital', amount: 100 });
|
||||
|
||||
// the Idempotency-Key makes a retried POST safe: one offer, not two
|
||||
const k = { 'idempotency-key': 'offer-retry-0001' };
|
||||
const r1 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
|
||||
const r2 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
|
||||
assert.equal(r1.body.offer.id, r2.body.offer.id);
|
||||
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE give_amount = 50").n, 1);
|
||||
void D;
|
||||
} finally { await t.close(); }
|
||||
});
|
||||
226
test/trade-flow.test.js
Normal file
226
test/trade-flow.test.js
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
'use strict';
|
||||
/* Internet exchange trade: offers, escrow, accept (two transports), cancel, expire, rules, conservation. Fake clock, in-memory db. */
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const T = require('./military-helpers');
|
||||
const { R, D, H } = T;
|
||||
|
||||
// Two traders next to each other with no production at all, so every resource that moves can be counted exactly.
|
||||
function traders(o) {
|
||||
o = o || {};
|
||||
const h = T.setup();
|
||||
const a = T.addOperator(h, 'alice', { x: 5, y: 0, infra: o.aInfra });
|
||||
const b = T.addOperator(h, 'bob', { x: 9, y: 0, infra: o.bInfra });
|
||||
for (const t of [a, b]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", t.townId);
|
||||
return { h, a, b };
|
||||
}
|
||||
const stock = (h, townId) => { const t = T.town(h, townId); return { fiber: t.fiber, hardware: t.hardware, capital: t.capital }; };
|
||||
// every unit of every resource in the world: in POPs, in open offers (escrow), on the road
|
||||
function total(h) {
|
||||
let sum = 0;
|
||||
for (const t of h.db.all('SELECT fiber, hardware, capital FROM towns')) sum += t.fiber + t.hardware + t.capital;
|
||||
for (const o of h.db.all("SELECT give_amount FROM trade_offers WHERE status = 'open'")) sum += o.give_amount;
|
||||
for (const m of h.db.all("SELECT cargo FROM movements WHERE status = 'out'")) for (const v of Object.values(JSON.parse(m.cargo))) sum += v;
|
||||
return sum;
|
||||
}
|
||||
const post = (h, who, townId, o) => h.run('tradeOffer', Object.assign({ userId: who.userId, townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }, o || {})).offer;
|
||||
const { createTradeQueries } = require('../server/tradeQueries');
|
||||
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
|
||||
|
||||
test('trade: post, escrow, accept spawns two transports, both arrive, offer completes; nothing is created or lost', () => {
|
||||
const { h, a, b } = traders();
|
||||
const before = total(h);
|
||||
const aStart = stock(h, a.townId), bStart = stock(h, b.townId);
|
||||
|
||||
const offer = post(h, a, a.townId);
|
||||
assert.equal(offer.status, 'open');
|
||||
assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400, 'the offered amount left the POP (escrow)');
|
||||
assert.equal(total(h), before, 'escrow is counted: conserved');
|
||||
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'tradeExpire' AND status = 'pending'").n, 1);
|
||||
|
||||
// bob sees it and can take it
|
||||
const tq = createTradeQueries(h);
|
||||
const list = tq.offers(b.userId, {});
|
||||
assert.equal(list.items.length, 1);
|
||||
assert.equal(list.items[0].id, offer.id);
|
||||
assert.equal(list.items[0].acceptableFrom[0].townId, b.townId);
|
||||
assert.equal(tq.offers(a.userId, {}).items.length, 0, 'your own offers are not in the market list');
|
||||
|
||||
const t0 = h.clock.now();
|
||||
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
|
||||
assert.equal(acc.status, 'accepted');
|
||||
const dist = R.distance(a.x, a.y, b.x, b.y);
|
||||
assert.equal(acc.arriveAt, t0 + R.transportMs(dist, 1), 'both legs use the transport speed');
|
||||
assert.equal(stock(h, b.townId).hardware, bStart.hardware - 300, "the acceptor's payment left at once");
|
||||
assert.equal(total(h), before, 'in flight: still conserved');
|
||||
const mvs = h.db.all("SELECT * FROM movements WHERE type = 'transport' ORDER BY id");
|
||||
assert.equal(mvs.length, 2);
|
||||
const goods = mvs.find((m) => m.id === acc.goodsMovementId), pay = mvs.find((m) => m.id === acc.paymentMovementId);
|
||||
assert.equal(goods.from_town_id, a.townId); assert.equal(goods.to_town_id, b.townId); assert.deepEqual(JSON.parse(goods.cargo), { fiber: 400 });
|
||||
assert.equal(pay.from_town_id, b.townId); assert.equal(pay.to_town_id, a.townId); assert.deepEqual(JSON.parse(pay.cargo), { hardware: 300 });
|
||||
assert.equal(T.notes(h, a.userId, 'trade_accepted').length, 1);
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'accepted');
|
||||
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled', 'an accepted offer cannot expire');
|
||||
|
||||
h.advanceTo(acc.arriveAt);
|
||||
assert.equal(h.db.get('SELECT status, legs_done FROM trade_offers WHERE id = ?', offer.id).status, 'completed');
|
||||
assert.equal(stock(h, a.townId).hardware, aStart.hardware + 300);
|
||||
assert.equal(stock(h, b.townId).fiber, bStart.fiber + 400);
|
||||
assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400);
|
||||
assert.equal(T.notes(h, a.userId, 'trade_completed').length, 1);
|
||||
assert.equal(T.notes(h, b.userId, 'trade_completed').length, 1);
|
||||
assert.equal(total(h), before, 'delivered: conserved');
|
||||
|
||||
// the carriers drive back; the links are free again afterwards
|
||||
const back = h.db.all("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
|
||||
assert.equal(back.length, 2);
|
||||
h.advance(10 * H);
|
||||
assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0);
|
||||
assert.equal(total(h), before);
|
||||
assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0);
|
||||
});
|
||||
|
||||
test('trade: terms - 1:2 ratio band, capacity, distinct resources, links, resources, ownership', () => {
|
||||
const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } });
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio');
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio');
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 501 })).code, 'capacity_exceeded');
|
||||
assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 1.5 })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, a, a.townId, { maxDistance: 0 })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, a, a.townId, { maxDistance: D.TRADE.maxDistance + 1 })).code, 'validation_failed');
|
||||
assert.equal(err(() => post(h, b, a.townId)).code, 'not_found', 'not your POP');
|
||||
assert.equal(post(h, a, a.townId, { giveAmount: 500, wantAmount: 250 }).status, 'open', 'exactly 2:1 is allowed');
|
||||
// level 1 exchange = one link, held by the open offer: no second offer and no direct transport meanwhile
|
||||
assert.equal(err(() => post(h, a, a.townId)).code, 'no_transport_link');
|
||||
assert.equal(err(() => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: 10 } })).code, 'no_transport_link');
|
||||
// a POP without an exchange cannot post
|
||||
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", b.townId);
|
||||
assert.equal(err(() => post(h, b, b.townId)).code, 'no_transport_link');
|
||||
// not enough of the offered resource
|
||||
const c = T.addOperator(h, 'cat', { x: 14, y: 0, res: 100 });
|
||||
assert.equal(err(() => post(h, c, c.townId)).code, 'not_enough_resources');
|
||||
});
|
||||
|
||||
test('trade: accept rules - own offer, closed, range, exchange, cannot afford (atomic), links', () => {
|
||||
const { h, a, b } = traders();
|
||||
const c = T.addOperator(h, 'cat', { x: 40, y: 0 }); // 35 tiles from alice
|
||||
const d = T.addOperator(h, 'dan', { x: 12, y: 0, infra: { internet_exchange: 0 } });
|
||||
h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", d.townId);
|
||||
const offer = post(h, a, a.townId, { maxDistance: 12 });
|
||||
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: a.userId, offerId: offer.id, townId: a.townId })).code, 'own_offer');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: c.userId, offerId: offer.id, townId: c.townId })).code, 'trade_out_of_range', 'beyond the offer\'s max distance');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: d.userId, offerId: offer.id, townId: d.townId })).code, 'no_transport_link', 'no Internet exchange');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: 999, townId: b.townId })).code, 'not_found');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: a.townId })).code, 'not_found', 'not your POP');
|
||||
|
||||
// reach: a level-1 exchange sees 10 tiles
|
||||
const far = T.addOperator(h, 'far', { x: 20, y: 0, infra: { internet_exchange: 1 } }); // 15 tiles from alice, within the offer's 30 below
|
||||
const wide = post(h, a, a.townId, { maxDistance: 30, giveAmount: 100, wantAmount: 100 });
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: far.userId, offerId: wide.id, townId: far.townId })).code, 'trade_out_of_range');
|
||||
const seen = createTradeQueries(h).offers(far.userId, {});
|
||||
assert.equal(seen.items.length, 0, 'out of reach: not even listed');
|
||||
assert.equal(seen.exchangeLevels[0].reach, 10);
|
||||
|
||||
// bob cannot pay: nothing changes (all or nothing)
|
||||
h.db.run('UPDATE towns SET hardware = 100 WHERE id = ?', b.townId);
|
||||
const snap = JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]);
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'not_enough_resources');
|
||||
assert.equal(JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]), snap, 'a failed accept leaves no trace');
|
||||
// no free link for bob (level 3, three running transports)
|
||||
h.db.run('UPDATE towns SET hardware = 1000 WHERE id = ?', b.townId);
|
||||
for (let i = 0; i < 3; i++) h.run('sendTransport', { userId: b.userId, fromTownId: b.townId, toTownId: c.townId, cargo: { capital: 10 } });
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'no_transport_link');
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open');
|
||||
});
|
||||
|
||||
test('trade: cancel returns the escrow, closed offers cannot be taken, strangers cannot cancel', () => {
|
||||
const { h, a, b } = traders();
|
||||
const start = stock(h, a.townId), before = total(h);
|
||||
const offer = post(h, a, a.townId);
|
||||
assert.equal(err(() => h.run('tradeCancel', { userId: b.userId, offerId: offer.id })).code, 'not_found');
|
||||
const r = h.run('tradeCancel', { userId: a.userId, offerId: offer.id });
|
||||
assert.deepEqual(r.returned, { resource: 'fiber', amount: 400 });
|
||||
assert.deepEqual(stock(h, a.townId), start);
|
||||
assert.equal(total(h), before);
|
||||
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed');
|
||||
assert.equal(err(() => h.run('tradeCancel', { userId: a.userId, offerId: offer.id })).code, 'offer_closed');
|
||||
assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0, 'the reserved link is free again');
|
||||
});
|
||||
|
||||
test('trade: an offer expires after its ttl (divided by world speed) and returns the escrow exactly once', () => {
|
||||
for (const speed of [1, 4]) {
|
||||
const h = T.setup({ speed });
|
||||
const a = T.addOperator(h, 'alice', { x: 5, y: 0 });
|
||||
h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", a.townId);
|
||||
const start = stock(h, a.townId);
|
||||
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 250, wantRes: 'fiber', wantAmount: 400, maxDistance: 20 }).offer;
|
||||
assert.equal(offer.expiresAt - h.clock.now(), D.TRADE.ttlHours * H / speed);
|
||||
h.advanceTo(offer.expiresAt - 1);
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open');
|
||||
h.advanceTo(offer.expiresAt);
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired');
|
||||
assert.deepEqual(stock(h, a.townId), start);
|
||||
assert.equal(T.notes(h, a.userId, 'trade_expired').length, 1);
|
||||
// running the handler again (idempotence) does not pay twice
|
||||
require('../server/events/tradeExpire')(Object.assign(h.ctx(), { now: offer.expiresAt }), { id: 0, worldId: h.worldId, dueAt: offer.expiresAt, payload: { offerId: offer.id } });
|
||||
assert.deepEqual(stock(h, a.townId), start);
|
||||
}
|
||||
});
|
||||
|
||||
test('trade: a delivery above the receiver\'s storage cap loses exactly the overflow (and says so); the rest is conserved', () => {
|
||||
const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000
|
||||
h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId);
|
||||
const before = total(h);
|
||||
const offer = post(h, a, a.townId);
|
||||
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
|
||||
h.advanceTo(acc.arriveAt);
|
||||
assert.equal(stock(h, b.townId).fiber, 1000);
|
||||
const arrived = T.notes(h, b.userId, 'transport_arrived')[0];
|
||||
assert.deepEqual(arrived.cargoLost, { fiber: 300 });
|
||||
assert.equal(total(h) + 300, before, 'every unit is somewhere, except the 300 that did not fit and were reported lost');
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'completed');
|
||||
});
|
||||
|
||||
test('trade: a POP that changes hands voids its open offers; the escrow stays in the POP', () => {
|
||||
const { h, a, b } = traders();
|
||||
const offer = post(h, a, a.townId);
|
||||
const before = total(h);
|
||||
const combat = require('../server/military/combat');
|
||||
const town = require('../server/state').loadTown(h.db, a.townId);
|
||||
h.db.tx(() => combat.transferTown(h.ctx(), town, { id: b.opId, name: 'bob' }, { id: a.opId, name: 'alice' }, h.clock.now()));
|
||||
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'void');
|
||||
assert.equal(T.town(h, a.townId).owner_id, b.opId);
|
||||
assert.equal(T.town(h, a.townId).fiber, 4000, "the escrow is back in the POP, now bob's");
|
||||
assert.equal(total(h), before, 'nothing created or lost');
|
||||
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed');
|
||||
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled');
|
||||
assert.equal(T.notes(h, a.userId, 'trade_void').length, 1);
|
||||
});
|
||||
|
||||
test('trade list: pages through offers that are out of reach (chunked read), cursor and filters stay right', () => {
|
||||
const saved = D.TRADE.scanChunk;
|
||||
D.TRADE.scanChunk = 2;
|
||||
try {
|
||||
const h = T.setup();
|
||||
const p = T.addOperator(h, 'poster', { x: 5, y: 0, infra: { internet_exchange: 10 } });
|
||||
const v = T.addOperator(h, 'viewer', { x: 9, y: 0 }); // 4 tiles away, exchange 3 (reach 30)
|
||||
for (const q of [p, v]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", q.townId);
|
||||
const ids = [];
|
||||
for (const [md, amt] of [[2, 10], [10, 20], [2, 30], [2, 40], [10, 50], [3, 60], [10, 70]]) ids.push(post(h, p, p.townId, { maxDistance: md, giveAmount: amt, wantAmount: amt }).id);
|
||||
const tq = createTradeQueries(h);
|
||||
const visible = [ids[1], ids[4], ids[6]]; // maxDistance >= 4
|
||||
const p1 = tq.offers(v.userId, { limit: 2 });
|
||||
assert.deepEqual(p1.items.map((o) => o.id), [visible[2], visible[1]]);
|
||||
assert.equal(p1.next, visible[1]);
|
||||
const p2 = tq.offers(v.userId, { limit: 2, after: p1.next });
|
||||
assert.deepEqual(p2.items.map((o) => o.id), [visible[0]]);
|
||||
assert.equal(p2.next, null);
|
||||
assert.equal(tq.offers(v.userId, { limit: 10 }).items.length, 3);
|
||||
assert.deepEqual(tq.offers(v.userId, { limit: 10, give: 'capital' }).items, []);
|
||||
} finally { D.TRADE.scanChunk = saved; }
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue