@chrischall/warapp-mcp 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +211 -9
- package/dist/analysis/accept-surrender.js +56 -0
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/calibrate.js +239 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/finished-game.js +136 -0
- package/dist/analysis/game-lessons.js +217 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +179 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +552 -0
- package/dist/analysis/opponents.js +1253 -0
- package/dist/analysis/outlook.js +695 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1405 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +1001 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2927 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +584 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1112 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +121082 -36148
- package/dist/calibration-source.js +75 -0
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +265 -0
- package/dist/client.js +439 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/finished-store.js +357 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/lessons-store.js +356 -0
- package/dist/live.js +287 -0
- package/dist/map-details.js +127 -0
- package/dist/map-stats.js +160 -0
- package/dist/map-store.js +242 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +218 -0
- package/dist/normalize.js +443 -0
- package/dist/notifications.js +143 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +165 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +231 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +727 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +615 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +227 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +291 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2223 -0
- package/dist/surrender-pending.js +126 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/accept-surrender.js +311 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +158 -0
- package/dist/tools/chat-read-mark.js +179 -0
- package/dist/tools/chat.js +525 -0
- package/dist/tools/check-plan.js +689 -0
- package/dist/tools/commander-check.js +103 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/end-of-game.js +384 -0
- package/dist/tools/game.js +151 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +152 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-details.js +88 -0
- package/dist/tools/map-stats.js +130 -0
- package/dist/tools/map.js +141 -0
- package/dist/tools/my-games.js +193 -0
- package/dist/tools/notifications.js +484 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +163 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/past-games.js +94 -0
- package/dist/tools/picks.js +305 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +445 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +257 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender-pending.js +74 -0
- package/dist/tools/surrender.js +247 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +178 -0
- package/dist/tools/turn.js +2825 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +300 -0
- package/dist/tools/write-kit.js +164 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +577 -0
- package/dist/version.js +4 -0
- package/manifest.json +194 -4
- package/mint.yaml +106 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +1096 -21
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { normalizeSettings } from './normalize.js';
|
|
2
|
+
import { anonymousHistoryOfRecord, finishedPath, historyOfRecord, listFinishedRecords, readFinishedRecord } from './finished-store.js';
|
|
3
|
+
import { readStoredMap } from './map-store.js';
|
|
4
|
+
import { playerRecordSalt } from './player-record-store.js';
|
|
5
|
+
import { gamesDir, loadReplay } from './replay.js';
|
|
6
|
+
import { readdir } from 'node:fs/promises';
|
|
7
|
+
const count = (o, k) => {
|
|
8
|
+
o[k] = (o[k] ?? 0) + 1;
|
|
9
|
+
};
|
|
10
|
+
async function settingsRecordIds(dir) {
|
|
11
|
+
const names = await readdir(gamesDir(dir)).catch(() => []);
|
|
12
|
+
return names
|
|
13
|
+
.filter((n) => /^\d+\.json$/.test(n))
|
|
14
|
+
.map((n) => Number(n.slice(0, -5)))
|
|
15
|
+
.sort((a, b) => a - b);
|
|
16
|
+
}
|
|
17
|
+
/** Every finished game the data directory can score, and what it cannot. Never throws. */
|
|
18
|
+
export async function calibrationSources(dir) {
|
|
19
|
+
const out = { inputs: [], statuses: {}, skipped: {} };
|
|
20
|
+
const salt = await playerRecordSalt(dir).catch(() => undefined);
|
|
21
|
+
// The settings records by the record path they would match.
|
|
22
|
+
const byPath = new Map();
|
|
23
|
+
for (const id of await settingsRecordIds(dir)) {
|
|
24
|
+
const replay = await loadReplay(dir, id);
|
|
25
|
+
if (!salt || !replay || replay.playerId === undefined) {
|
|
26
|
+
count(out.statuses, 'missing');
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
byPath.set(finishedPath(dir, salt, replay.playerId, id), replay);
|
|
30
|
+
}
|
|
31
|
+
const paths = salt ? await listFinishedRecords(dir) : [];
|
|
32
|
+
const seen = new Set();
|
|
33
|
+
for (const path of paths) {
|
|
34
|
+
seen.add(path);
|
|
35
|
+
const rec = await readFinishedRecord(path);
|
|
36
|
+
if (typeof rec === 'string') {
|
|
37
|
+
count(out.statuses, rec);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
count(out.statuses, rec.status);
|
|
41
|
+
if (rec.status !== 'captured')
|
|
42
|
+
continue;
|
|
43
|
+
const replay = byPath.get(path);
|
|
44
|
+
const matched = replay ? historyOfRecord(rec, salt, [replay.playerId, ...replay.game.players.map((p) => p.id)]) : undefined;
|
|
45
|
+
const history = matched && typeof matched === 'object' ? matched : anonymousHistoryOfRecord(rec);
|
|
46
|
+
if (typeof history === 'string') {
|
|
47
|
+
count(out.skipped, 'captured-without-boards');
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const fromReplay = matched !== undefined && typeof matched === 'object';
|
|
51
|
+
const settings = fromReplay ? replay.settings : rec.settings ? normalizeSettings(rec.settings) : undefined;
|
|
52
|
+
if (!settings) {
|
|
53
|
+
count(out.skipped, 'no-settings');
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const mapId = rec.mapId ?? settings.mapId;
|
|
57
|
+
const map = (fromReplay ? replay.map : undefined) ?? (mapId !== undefined ? await readStoredMap(dir, mapId, { maxAgeMs: Number.POSITIVE_INFINITY }) : undefined);
|
|
58
|
+
if (!map) {
|
|
59
|
+
count(out.skipped, 'no-map');
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const cached = fromReplay && replay.playerId === history.me
|
|
63
|
+
? replay.boards.map((b) => {
|
|
64
|
+
const o = replay.orders.get(b.turn);
|
|
65
|
+
return { turn: b.turn, board: b.board, ...(o ? { orders: o } : {}) };
|
|
66
|
+
})
|
|
67
|
+
: [];
|
|
68
|
+
out.inputs.push({ source: fromReplay ? 'settings-record' : 'record-only', history, settings, map, cached });
|
|
69
|
+
}
|
|
70
|
+
// A settings record whose game has no record: its pass has not run (or the record was pruned).
|
|
71
|
+
for (const path of byPath.keys())
|
|
72
|
+
if (!seen.has(path))
|
|
73
|
+
count(out.statuses, 'missing');
|
|
74
|
+
return out;
|
|
75
|
+
}
|
package/dist/cards.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// Cards: the type table, my hand read from the live board, the game's card
|
|
2
|
+
// rules from GameFeed settings, and which cards the planner plays.
|
|
3
|
+
//
|
|
4
|
+
// VERIFIED 2026-11-12 (docs/PLAN-CARDS-PUSH.md): the hand is a dict GUID →
|
|
5
|
+
// card instance (`warlight.shared.ReinforcementCardInstance { guid, type,
|
|
6
|
+
// armies }`, `warlight.shared.NoParameterCardInstance { guid, type }`) under the
|
|
7
|
+
// player entry keyed by the in-game id. Field names are minified, so instances
|
|
8
|
+
// are found by type name and their fields by kind and read order, and the
|
|
9
|
+
// reader stays loose: an unexpected shape yields fewer cards, never an error.
|
|
10
|
+
import { currentStanding } from './live.js';
|
|
11
|
+
import { fields, isObj } from './protocol/decoded.js';
|
|
12
|
+
import { asInt } from './scalars.js';
|
|
13
|
+
/** Card type ids (the client's registry). */
|
|
14
|
+
export const CARD_TYPES = {
|
|
15
|
+
1: 'Reinforcement',
|
|
16
|
+
2: 'Spy',
|
|
17
|
+
3: 'Emergency Blockade',
|
|
18
|
+
4: 'Order Priority',
|
|
19
|
+
5: 'Order Delay',
|
|
20
|
+
6: 'Airlift',
|
|
21
|
+
7: 'Gift',
|
|
22
|
+
8: 'Diplomacy',
|
|
23
|
+
9: 'Sanctions',
|
|
24
|
+
10: 'Reconnaissance',
|
|
25
|
+
11: 'Surveillance',
|
|
26
|
+
12: 'Blockade',
|
|
27
|
+
13: 'Bomb',
|
|
28
|
+
};
|
|
29
|
+
export const CARD_REINFORCEMENT = 1;
|
|
30
|
+
export const CARD_ORDER_PRIORITY = 4;
|
|
31
|
+
export const CARD_ORDER_DELAY = 5;
|
|
32
|
+
export const CARD_BLOCKADE = 12;
|
|
33
|
+
/** A card type's display name; `Card <id>` for an unknown id. */
|
|
34
|
+
export const cardTypeName = (type) => CARD_TYPES[type] ?? `Card ${type}`;
|
|
35
|
+
const squash = (s) => s.toLowerCase().replace(/[^a-z]/g, '').replace(/card$/, '');
|
|
36
|
+
const BY_NAME = new Map(Object.entries(CARD_TYPES).map(([id, name]) => [squash(name), Number(id)]));
|
|
37
|
+
/** A card type id from its name (any case, spaces optional, a trailing "card" ignored). */
|
|
38
|
+
export function cardTypeByName(name) {
|
|
39
|
+
return BY_NAME.get(squash(name));
|
|
40
|
+
}
|
|
41
|
+
const GUID_RE = /^[0-9a-f]{32}$/;
|
|
42
|
+
/** A GUID as 32 lowercase hex digits (dashes and braces dropped), or `undefined`. */
|
|
43
|
+
export function normalizeGuid(v) {
|
|
44
|
+
if (typeof v !== 'string')
|
|
45
|
+
return undefined;
|
|
46
|
+
const hex = v.replace(/[-{}]/g, '').toLowerCase();
|
|
47
|
+
return GUID_RE.test(hex) ? hex : undefined;
|
|
48
|
+
}
|
|
49
|
+
const CARD_INSTANCE = /CardInstance$/;
|
|
50
|
+
const MAX_DEPTH = 32;
|
|
51
|
+
function cardOf(o, key) {
|
|
52
|
+
const values = fields(o);
|
|
53
|
+
const id = values.map(normalizeGuid).find((g) => g !== undefined) ?? normalizeGuid(key);
|
|
54
|
+
const ints = values.filter((v) => typeof v === 'number' && Number.isInteger(v));
|
|
55
|
+
// The card-instance base reader sets `Gb` (the card type) last among the integer fields; a
|
|
56
|
+
// ReinforcementCardInstance prepends `tc` (its armies) in its subclass. So the TYPE is the last
|
|
57
|
+
// integer and the Reinforcement armies are the first — never read the type from `ints[0]`, which
|
|
58
|
+
// is `tc` for a Reinforcement card and collides with Order Delay's type id (5).
|
|
59
|
+
const type = ints[ints.length - 1];
|
|
60
|
+
if (id === undefined || type === undefined)
|
|
61
|
+
return undefined;
|
|
62
|
+
const card = { id, type, name: cardTypeName(type) };
|
|
63
|
+
if (type === CARD_REINFORCEMENT && ints.length >= 2)
|
|
64
|
+
card.armies = ints[0];
|
|
65
|
+
return card;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* My hand from a decoded LatestGameInfo: every card instance in its CURRENT
|
|
69
|
+
* GameStanding (`currentStanding`, the same object the board is read from) under
|
|
70
|
+
* the player entry keyed by `myInGameId` (or under no player key at all).
|
|
71
|
+
*
|
|
72
|
+
* VERIFIED 2026-11-12 (#20): only the current standing is the hand. The pending
|
|
73
|
+
* orders, the last GameTurn (its receive/play-card orders) and the previous
|
|
74
|
+
* standing still carry instances already played — playing one is refused with
|
|
75
|
+
* error 50 `CardInstanceUnavailable` — so they are never walked. Empty when there
|
|
76
|
+
* is no standing or it carries no cards; never throws.
|
|
77
|
+
*
|
|
78
|
+
* A team shares one hand and one card limit (the wiki's Team Games). Given several in-game
|
|
79
|
+
* ids (mine and my teammates'), the hand is every card under any of them, each GUID once.
|
|
80
|
+
* UNVERIFIED live (#163): how war.app keys a team's hand — under each player, under one, or
|
|
81
|
+
* repeated under all — has not been seen on a team board. So each card of a team hand carries the
|
|
82
|
+
* id it was read under (`owner`): the first id given (mine) when it is under that one at all.
|
|
83
|
+
*/
|
|
84
|
+
export function readHand(info, myInGameId) {
|
|
85
|
+
const ids = typeof myInGameId === 'number' ? [myInGameId] : [...myInGameId];
|
|
86
|
+
const owners = new Set(ids);
|
|
87
|
+
const team = owners.size > 1;
|
|
88
|
+
const out = [];
|
|
89
|
+
const seen = new Map();
|
|
90
|
+
const walk = (v, owner, key, depth) => {
|
|
91
|
+
if (depth > MAX_DEPTH)
|
|
92
|
+
return;
|
|
93
|
+
if (Array.isArray(v)) {
|
|
94
|
+
for (const item of v) {
|
|
95
|
+
if (Array.isArray(item) && item.length === 2 && (typeof item[0] === 'number' || typeof item[0] === 'string')) {
|
|
96
|
+
walk(item[1], typeof item[0] === 'number' ? item[0] : owner, item[0], depth + 1);
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
walk(item, owner, undefined, depth + 1);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!isObj(v))
|
|
105
|
+
return;
|
|
106
|
+
if (typeof v.$type === 'string' && CARD_INSTANCE.test(v.$type)) {
|
|
107
|
+
if (owner !== undefined && !owners.has(owner))
|
|
108
|
+
return;
|
|
109
|
+
const card = cardOf(v, key);
|
|
110
|
+
if (!card)
|
|
111
|
+
return;
|
|
112
|
+
const known = seen.get(card.id);
|
|
113
|
+
if (known) {
|
|
114
|
+
if (team && owner === ids[0])
|
|
115
|
+
known.owner = owner;
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (team && owner !== undefined)
|
|
119
|
+
card.owner = owner;
|
|
120
|
+
seen.set(card.id, card);
|
|
121
|
+
out.push(card);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
for (const [k, f] of Object.entries(v))
|
|
125
|
+
if (k !== '$type')
|
|
126
|
+
walk(f, owner, undefined, depth + 1);
|
|
127
|
+
};
|
|
128
|
+
const standing = currentStanding(info);
|
|
129
|
+
if (standing)
|
|
130
|
+
walk(standing, undefined, undefined, 0);
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Whether my hand can be read at all: the current standing carries a player entry keyed by
|
|
135
|
+
* `myInGameId` (a `[id, value]` pair). Without one, {@link readHand}'s empty hand means "unknown",
|
|
136
|
+
* not "no cards" (#130). Unverified live: assumes war.app sends every player's entry, as the
|
|
137
|
+
* synthetic shape does. Given several ids (a team's hand, as {@link readHand} takes them), an
|
|
138
|
+
* entry under any of them will do.
|
|
139
|
+
*/
|
|
140
|
+
export function handReadable(info, myInGameId) {
|
|
141
|
+
const owners = new Set(typeof myInGameId === 'number' ? [myInGameId] : myInGameId);
|
|
142
|
+
let found = false;
|
|
143
|
+
const walk = (v, depth) => {
|
|
144
|
+
if (found || depth > MAX_DEPTH)
|
|
145
|
+
return;
|
|
146
|
+
if (Array.isArray(v)) {
|
|
147
|
+
if (v.length === 2 && typeof v[0] === 'number' && owners.has(v[0]) && v[1] !== null && typeof v[1] === 'object') {
|
|
148
|
+
found = true;
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
for (const item of v)
|
|
152
|
+
walk(item, depth + 1);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (!isObj(v))
|
|
156
|
+
return;
|
|
157
|
+
for (const [k, f] of Object.entries(v))
|
|
158
|
+
if (k !== '$type')
|
|
159
|
+
walk(f, depth + 1);
|
|
160
|
+
};
|
|
161
|
+
const standing = currentStanding(info);
|
|
162
|
+
if (standing)
|
|
163
|
+
walk(standing, 0);
|
|
164
|
+
return found;
|
|
165
|
+
}
|
|
166
|
+
export function cardRules(settings) {
|
|
167
|
+
const rules = { inPlay: [] };
|
|
168
|
+
if (!settings)
|
|
169
|
+
return rules;
|
|
170
|
+
const raw = settings.raw;
|
|
171
|
+
const max = asInt(raw.MaxCardsHold);
|
|
172
|
+
if (max !== undefined)
|
|
173
|
+
rules.maxCardsHold = max;
|
|
174
|
+
const per = asInt(raw.NumberOfCardsToReceiveEachTurn);
|
|
175
|
+
if (per !== undefined)
|
|
176
|
+
rules.cardsPerTurn = per;
|
|
177
|
+
const r = raw.ReinforcementCard;
|
|
178
|
+
if (isObj(r)) {
|
|
179
|
+
const armies = asInt(r.FixedArmies);
|
|
180
|
+
if (armies !== undefined)
|
|
181
|
+
rules.reinforcementArmies = armies;
|
|
182
|
+
}
|
|
183
|
+
for (const name of settings.cards) {
|
|
184
|
+
const type = cardTypeByName(name);
|
|
185
|
+
rules.inPlay.push(type !== undefined ? cardTypeName(type) : name);
|
|
186
|
+
}
|
|
187
|
+
return rules;
|
|
188
|
+
}
|
|
189
|
+
/** Armies a Reinforcement card adds: its own count, else the game's setting. */
|
|
190
|
+
export function reinforcementArmies(card, rules) {
|
|
191
|
+
return card.armies ?? rules.reinforcementArmies;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* How many cards must leave the hand this turn (played or discarded) for war.app to
|
|
195
|
+
* accept the orders: the whole cards held beyond `maxCardsHold`; 0 without a known limit.
|
|
196
|
+
*
|
|
197
|
+
* VERIFIED 2026-11-12 (#20): live, a turn with no card play was accepted at 4/4 whole
|
|
198
|
+
* cards and refused (error 51) at 5/4; the client bundle's `GameValidateOrders` removes
|
|
199
|
+
* every played or discarded instance from a copy of the hand and refuses while what is
|
|
200
|
+
* left is still `> MaxCardsHold`. So the limit is strictly "over", and each card over it
|
|
201
|
+
* needs its own play or discard. Counts only the real hand (see `readHand`).
|
|
202
|
+
*/
|
|
203
|
+
export const cardsToShed = (hand, rules) => rules.maxCardsHold !== undefined && rules.maxCardsHold > 0 ? Math.max(0, hand.length - rules.maxCardsHold) : 0;
|
|
204
|
+
/** Whether war.app requires a card play or discard this turn (error 51 otherwise): the hand is over the limit. */
|
|
205
|
+
export const playRequired = (hand, rules) => cardsToShed(hand, rules) > 0;
|
|
206
|
+
/**
|
|
207
|
+
* How much a card is worth keeping, for choosing a discard (lowest goes first). A heuristic
|
|
208
|
+
* (#163): every ranking read keeps the timing and combat cards longest — Order Delay (an unplayed
|
|
209
|
+
* one is a threat in itself), Order Priority, Emergency Blockade, Bomb and Airlift — and the
|
|
210
|
+
* information cards go first. Order Priority sits below Order Delay because one that must go is
|
|
211
|
+
* played, not thrown away. Reinforcement is kept only when its armies are unknown (or, in a team
|
|
212
|
+
* game, when it is not auto-played) and is the last resort. {@link keepValue} adjusts it per game.
|
|
213
|
+
*/
|
|
214
|
+
const KEEP_VALUE = {
|
|
215
|
+
2: 1, // Spy
|
|
216
|
+
10: 2, // Reconnaissance
|
|
217
|
+
11: 3, // Surveillance
|
|
218
|
+
7: 4, // Gift
|
|
219
|
+
8: 5, // Diplomacy
|
|
220
|
+
9: 6, // Sanctions
|
|
221
|
+
12: 7, // Blockade
|
|
222
|
+
6: 8, // Airlift
|
|
223
|
+
13: 9, // Bomb
|
|
224
|
+
3: 10, // Emergency Blockade
|
|
225
|
+
4: 11, // Order Priority
|
|
226
|
+
5: 12, // Order Delay
|
|
227
|
+
1: 13, // Reinforcement
|
|
228
|
+
};
|
|
229
|
+
const INFORMATION_CARDS = new Set([2, 10, 11]);
|
|
230
|
+
const ONE_V_ONE_CHEAP = new Set([7, 8]); // Gift, Diplomacy
|
|
231
|
+
/** Whether a card is mine to play: not read under a teammate's id (V8 unverified). */
|
|
232
|
+
export const isMyCard = (c, me) => me === undefined || c.owner === undefined || c.owner === me;
|
|
233
|
+
/**
|
|
234
|
+
* A card's keep value in this game: the information cards (Spy, Reconnaissance, Surveillance)
|
|
235
|
+
* are worth nothing without fog; Gift and Diplomacy are worth little in a 1v1 (there is no third
|
|
236
|
+
* player to buy off or to set against the opponent), below the information cards.
|
|
237
|
+
*/
|
|
238
|
+
function keepValue(c, game = {}) {
|
|
239
|
+
if (game.fog === 'NoFog' && INFORMATION_CARDS.has(c.type))
|
|
240
|
+
return -2;
|
|
241
|
+
if (game.players === 2 && !game.team && ONE_V_ONE_CHEAP.has(c.type))
|
|
242
|
+
return 0;
|
|
243
|
+
return KEEP_VALUE[c.type] ?? 5;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* The cards the planner plays. Outside a team game, every Reinforcement card (it only adds
|
|
247
|
+
* armies) — said to be a default, since holding one is a choice. In a team game (#163) the team
|
|
248
|
+
* shares one hand, so a Reinforcement is played only when cards must be shed (one per card over
|
|
249
|
+
* the limit, before any discard). Over the hold limit, with plays still short of what must leave
|
|
250
|
+
* the hand, the lowest-value cards in this game ({@link keepValue}) leave it: discarded, except an
|
|
251
|
+
* Order Priority, which is played (my first order goes first; one at most, a second is
|
|
252
|
+
* discarded). Order Delay, Blockade and the targeted cards are never auto-played.
|
|
253
|
+
*/
|
|
254
|
+
export function chooseCardPlays(hand, rules, game = {}) {
|
|
255
|
+
const shed = cardsToShed(hand, rules);
|
|
256
|
+
const plays = [];
|
|
257
|
+
const discards = [];
|
|
258
|
+
const warnings = [];
|
|
259
|
+
let extraArmies = 0;
|
|
260
|
+
let heldForTeam = 0;
|
|
261
|
+
const mineOnly = game.team ? game.me : undefined;
|
|
262
|
+
for (const c of hand) {
|
|
263
|
+
if (c.type !== CARD_REINFORCEMENT || !isMyCard(c, mineOnly))
|
|
264
|
+
continue;
|
|
265
|
+
const armies = reinforcementArmies(c, rules);
|
|
266
|
+
if (armies === undefined) {
|
|
267
|
+
warnings.push(`Not playing Reinforcement card ${c.id}: the armies it adds are unknown.`);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (game.team && plays.length >= shed) {
|
|
271
|
+
heldForTeam++;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
plays.push(c);
|
|
275
|
+
extraArmies += armies;
|
|
276
|
+
}
|
|
277
|
+
if (heldForTeam) {
|
|
278
|
+
warnings.push(`Holding ${heldForTeam === 1 ? 'a Reinforcement card' : `${heldForTeam} Reinforcement cards`}: in a team game the team shares one hand, ` +
|
|
279
|
+
'so a teammate may need it more. Play it yourself (warapp_submit_turn) if the team agrees.');
|
|
280
|
+
}
|
|
281
|
+
const defaults = plays.length - Math.min(plays.length, shed);
|
|
282
|
+
if (!game.team && defaults > 0) {
|
|
283
|
+
warnings.push(`Playing ${defaults === 1 ? 'the Reinforcement card' : `${defaults} Reinforcement cards`} by default (+${extraArmies} armies this turn): ` +
|
|
284
|
+
'holding one is a choice — with no enemy in sight, or so the opponent undercounts your income — and the card keeps.');
|
|
285
|
+
}
|
|
286
|
+
if (plays.length < shed) {
|
|
287
|
+
const used = new Set(plays.map((c) => c.id));
|
|
288
|
+
const rest = hand.filter((c) => !used.has(c.id) && isMyCard(c, mineOnly));
|
|
289
|
+
// A stable sort: equal-value cards go in hand order. The lowest-value cards leave the hand; an
|
|
290
|
+
// Order Priority that must go anyway is played rather than discarded.
|
|
291
|
+
const byValue = rest
|
|
292
|
+
.map((c, i) => ({ c, i }))
|
|
293
|
+
.sort((a, b) => keepValue(a.c, game) - keepValue(b.c, game) || a.i - b.i);
|
|
294
|
+
// At most one Order Priority is played: a second adds nothing over the first, and whether
|
|
295
|
+
// war.app takes two plays of it in one turn is unverified, so the rest are discarded.
|
|
296
|
+
const playOne = (c) => c.type === CARD_ORDER_PRIORITY && !plays.some((p) => p.type === CARD_ORDER_PRIORITY);
|
|
297
|
+
const short = shed - plays.length;
|
|
298
|
+
for (const { c } of byValue.slice(0, short))
|
|
299
|
+
(playOne(c) ? plays : discards).push(c);
|
|
300
|
+
const theirs = short - Math.min(short, byValue.length);
|
|
301
|
+
if (theirs > 0) {
|
|
302
|
+
warnings.push(`${theirs} more card${theirs === 1 ? '' : 's'} must leave the team's hand from your teammates' cards: ` +
|
|
303
|
+
'ask them to play or discard (whether you can play a card read under a teammate is not yet verified).');
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const forced = plays.filter((c) => c.type === CARD_ORDER_PRIORITY);
|
|
307
|
+
if (forced.length) {
|
|
308
|
+
warnings.push(`You hold ${hand.length} cards (the limit is ${rules.maxCardsHold}), so ${shed} must be played or discarded this ` +
|
|
309
|
+
`turn. Playing Order Priority because it is the card that must go (a play costs nothing a discard would keep), ` +
|
|
310
|
+
'whatever the plan advises for it.');
|
|
311
|
+
}
|
|
312
|
+
if (discards.length) {
|
|
313
|
+
warnings.push(`You hold ${hand.length} cards (the limit is ${rules.maxCardsHold}), so ${shed} must be played or discarded this ` +
|
|
314
|
+
`turn. Discarding ${discards.map((c) => c.name).join(', ')}, the cards worth least in this game (the timing and ` +
|
|
315
|
+
'combat cards — Order Delay, Order Priority, Emergency Blockade, Bomb, Airlift — are kept longest). Swap in a card play if you prefer.');
|
|
316
|
+
}
|
|
317
|
+
return { required: shed > 0, plays, discards, extraArmies, warnings };
|
|
318
|
+
}
|
|
319
|
+
/** Whether the chosen plays spend an Order Priority card anyway (the hand is over the limit and it must go). */
|
|
320
|
+
export function playsOrderPriority(choice) {
|
|
321
|
+
return choice.plays.some((c) => c.type === CARD_ORDER_PRIORITY);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Whether I can play an Order Priority card this turn: one is in my hand and the chosen
|
|
325
|
+
* card plays do not discard it (the planner advises it for a commander strike, #61).
|
|
326
|
+
*/
|
|
327
|
+
export function holdsOrderPriority(hand, choice) {
|
|
328
|
+
const discarded = new Set(choice.discards.map((c) => c.id));
|
|
329
|
+
return hand.some((c) => c.type === CARD_ORDER_PRIORITY && !discarded.has(c.id));
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* The Order Priority card to add to the chosen plays when the plan advises one (a withdrawal
|
|
333
|
+
* or a commander strike), so the orders carry it: one in my hand the choice neither discards
|
|
334
|
+
* nor already plays. `undefined` when the choice already plays one, or none is left to play.
|
|
335
|
+
*/
|
|
336
|
+
export function advisedOrderPriority(hand, choice) {
|
|
337
|
+
if (choice.plays.some((c) => c.type === CARD_ORDER_PRIORITY))
|
|
338
|
+
return undefined;
|
|
339
|
+
const discarded = new Set(choice.discards.map((c) => c.id));
|
|
340
|
+
return hand.find((c) => c.type === CARD_ORDER_PRIORITY && !discarded.has(c.id));
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* The Order Delay to play, and where: when the schedule (#127) puts an attack last because the
|
|
344
|
+
* opponent can answer it first (`moveSlots` `last`) and I hold an Order Delay the choice neither
|
|
345
|
+
* plays nor discards, the card goes above every order that is not urgent — after the protected
|
|
346
|
+
* and early orders (withdrawals, transfers into a threatened border), before the rest — as the
|
|
347
|
+
* sources and the developer's own bot play it. `undefined` otherwise. The planner never plays it:
|
|
348
|
+
* warapp_submit_turn writes the card after every move (its only live-verified position), where it
|
|
349
|
+
* delays nothing, unless the card order carries `before` (#186) — a placement unverified live, so
|
|
350
|
+
* the advice stays advice until one commit verifies it.
|
|
351
|
+
*/
|
|
352
|
+
export function adviseOrderDelay(hand, choice, moves, moveSlots) {
|
|
353
|
+
if (!moveSlots)
|
|
354
|
+
return undefined;
|
|
355
|
+
const gone = new Set([...choice.plays, ...choice.discards].map((c) => c.id));
|
|
356
|
+
const card = hand.find((c) => c.type === CARD_ORDER_DELAY && !gone.has(c.id));
|
|
357
|
+
if (!card)
|
|
358
|
+
return undefined;
|
|
359
|
+
const attacks = moves.flatMap((m, i) => (m.kind === 'attack' && moveSlots[i] === 'last' ? [i + 1] : []));
|
|
360
|
+
if (!attacks.length)
|
|
361
|
+
return undefined;
|
|
362
|
+
const firstCalm = moveSlots.findIndex((s) => s !== 'protected' && s !== 'early');
|
|
363
|
+
const before = firstCalm < 0 ? moves.length + 1 : firstCalm + 1;
|
|
364
|
+
return { card, before, attacks };
|
|
365
|
+
}
|
|
366
|
+
/** Card types whose ActiveCard expires at the beginning of the next turn (the bundle's `CardGame*` overrides). */
|
|
367
|
+
const EXPIRES_AT_NEXT_TURN = new Set([2, 10, 11]); // Spy, Reconnaissance, Surveillance
|
|
368
|
+
/** The client's play-order class suffixes (`GameOrderPlayCard<X>`) that are not the card's name. */
|
|
369
|
+
const ORDER_CARD = { Abandon: 'Emergency Blockade' };
|
|
370
|
+
const PLAY_ORDER = /GameOrderPlayCard([A-Za-z]+)$/;
|
|
371
|
+
const ACTIVE_CARD = /\.ActiveCard$/;
|
|
372
|
+
const intsOf = (o) => Object.entries(o)
|
|
373
|
+
.filter(([k, v]) => k !== '$type' && typeof v === 'number' && Number.isInteger(v))
|
|
374
|
+
.map(([, v]) => v);
|
|
375
|
+
function activeCardOf(o) {
|
|
376
|
+
const order = Object.values(o).find((v) => isObj(v) && typeof v.$type === 'string' && PLAY_ORDER.test(v.$type));
|
|
377
|
+
if (!order)
|
|
378
|
+
return undefined;
|
|
379
|
+
const kind = PLAY_ORDER.exec(order.$type)[1];
|
|
380
|
+
const type = cardTypeByName(kind);
|
|
381
|
+
const card = ORDER_CARD[kind] ?? (type !== undefined ? cardTypeName(type) : kind);
|
|
382
|
+
const ints = intsOf(order);
|
|
383
|
+
const out = { card };
|
|
384
|
+
// The order's own fields are read before the base's card GUID and player: Diplomacy's two
|
|
385
|
+
// players, Sanctions' target, then the player who played it (the last integer).
|
|
386
|
+
if (kind === 'Diplomacy' && ints.length >= 3)
|
|
387
|
+
out.players = [ints[0], ints[1]];
|
|
388
|
+
if (kind === 'Sanctions' && ints.length >= 2)
|
|
389
|
+
out.target = ints[0];
|
|
390
|
+
if (ints.length)
|
|
391
|
+
out.playedBy = ints[ints.length - 1];
|
|
392
|
+
const expires = intsOf(o)[0];
|
|
393
|
+
if (expires !== undefined) {
|
|
394
|
+
out.expiresAfterTurn = expires;
|
|
395
|
+
out.untilTurn = type !== undefined && EXPIRES_AT_NEXT_TURN.has(type) ? expires : expires + 1;
|
|
396
|
+
}
|
|
397
|
+
return out;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* The cards in effect, from a decoded LatestGameInfo's CURRENT GameStanding (its `ActiveCards`:
|
|
401
|
+
* each a `warlight.shared.ActiveCard { Card, ExpiresAfterTurn }`, the card being the play order
|
|
402
|
+
* that started it). Fields are minified, so they are found by type name and read order (read from
|
|
403
|
+
* the client bundle). Loose: an unexpected shape yields fewer entries, never an error.
|
|
404
|
+
*
|
|
405
|
+
* UNVERIFIED live (#163): the reader follows the client bundle's ActiveCard and play-order
|
|
406
|
+
* readers, but no live board carrying an active card has been decoded yet, and whether a fogged
|
|
407
|
+
* player sees the cards played on others (card plays can be fogged) is not known.
|
|
408
|
+
*/
|
|
409
|
+
export function readActiveCards(info) {
|
|
410
|
+
const out = [];
|
|
411
|
+
const walk = (v, depth) => {
|
|
412
|
+
if (depth > MAX_DEPTH)
|
|
413
|
+
return;
|
|
414
|
+
if (Array.isArray(v)) {
|
|
415
|
+
for (const item of v)
|
|
416
|
+
walk(item, depth + 1);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
if (!isObj(v))
|
|
420
|
+
return;
|
|
421
|
+
if (typeof v.$type === 'string' && ACTIVE_CARD.test(v.$type)) {
|
|
422
|
+
const card = activeCardOf(v);
|
|
423
|
+
if (card)
|
|
424
|
+
out.push(card);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
for (const [k, f] of Object.entries(v))
|
|
428
|
+
if (k !== '$type')
|
|
429
|
+
walk(f, depth + 1);
|
|
430
|
+
};
|
|
431
|
+
const standing = currentStanding(info);
|
|
432
|
+
if (standing)
|
|
433
|
+
walk(standing, 0);
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// The chat cursor: per game, per channel, how many messages were marked seen and the time of the
|
|
2
|
+
// newest one, so "new since" survives a restart. Local only, at `<dataDir>/chat/<gameId>.json`, and
|
|
3
|
+
// name-free: counts and times, never a message's text, sender or name (docs/PLAN-TEAMS.md, part A).
|
|
4
|
+
// Keyed to the account (its GameFeed id) that marked it. Best effort: the store never throws.
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { CHAT_CHANNELS } from './chat.js';
|
|
9
|
+
export const chatCursorPath = (dir, gameId) => join(dir, 'chat', `${gameId}.json`);
|
|
10
|
+
const byChannel = (lines, channel) => lines.map((l, i) => [l, i]).filter(([l]) => l.channel === channel);
|
|
11
|
+
/**
|
|
12
|
+
* Which messages are new (parallel to `lines`, oldest first). With no cursor for a channel, all of it
|
|
13
|
+
* is. With the times of every message on the channel and a time in the cursor: what came after the
|
|
14
|
+
* newest message seen (one sharing its millisecond counts past the `atLast` seen there), so a list
|
|
15
|
+
* that dropped its oldest messages still finds the new ones. Otherwise by count: the messages past
|
|
16
|
+
* the number seen (a list that shrank then has nothing new). My own messages are never new. A message
|
|
17
|
+
* is judged against its channel's own mark and the whole-chat mark (`all`): seen by either, it is not
|
|
18
|
+
* new, so a whole-chat mark from one source clears what the other source shows. A public, team or
|
|
19
|
+
* private message is judged against `all` only by time (`all` with a time, and every message on the
|
|
20
|
+
* channel timed): a count taken over another source's list says nothing about one channel's.
|
|
21
|
+
*/
|
|
22
|
+
export function markNew(lines, cursor) {
|
|
23
|
+
const out = lines.map((l) => !l.mine);
|
|
24
|
+
if (!cursor)
|
|
25
|
+
return out;
|
|
26
|
+
for (const channel of CHAT_CHANNELS) {
|
|
27
|
+
const mine = byChannel(lines, channel);
|
|
28
|
+
const timed = mine.every(([l]) => l.timeMs !== undefined);
|
|
29
|
+
const whole = channel === 'unknown' || (timed && cursor.all?.lastTimeMs !== undefined) ? cursor.all : undefined;
|
|
30
|
+
const marks = [whole, cursor.channels[channel]].filter((c) => c !== undefined);
|
|
31
|
+
if (!marks.length)
|
|
32
|
+
continue;
|
|
33
|
+
const fresh = marks.map((c) => freshAgainst(mine.map(([l]) => l), c));
|
|
34
|
+
mine.forEach(([l, i], k) => {
|
|
35
|
+
out[i] = !l.mine && fresh.every((f) => f[k]);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
/** Which of one channel's messages (oldest first) came after the mark `c`. */
|
|
41
|
+
function freshAgainst(on, c) {
|
|
42
|
+
const timed = c.lastTimeMs !== undefined && on.every((l) => l.timeMs !== undefined);
|
|
43
|
+
let atLast = 0;
|
|
44
|
+
return on.map((l, k) => {
|
|
45
|
+
if (!timed)
|
|
46
|
+
return k >= c.seen;
|
|
47
|
+
const t = l.timeMs;
|
|
48
|
+
if (t === c.lastTimeMs)
|
|
49
|
+
return ++atLast > (c.atLast ?? 1);
|
|
50
|
+
return t > c.lastTimeMs;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The cursor with `channels` marked seen as `lines` stand (every message on them, mine included).
|
|
55
|
+
* `namesChannels: false` is a source that names no channel (GameFeed: every message `unknown`): it
|
|
56
|
+
* records only `unknown` and, when every channel is named, the whole chat, never a public, team or
|
|
57
|
+
* private mark (one of `{ seen: 0 }` would make that channel's whole history new on the next web read).
|
|
58
|
+
*/
|
|
59
|
+
export function advanceCursor(cursor, lines, channels, opts = {}) {
|
|
60
|
+
const next = { ...cursor, channels: { ...cursor.channels } };
|
|
61
|
+
for (const channel of markedChannels(channels, opts))
|
|
62
|
+
next.channels[channel] = seenOf(byChannel(lines, channel).map(([l]) => l));
|
|
63
|
+
if (CHAT_CHANNELS.every((c) => channels.includes(c)))
|
|
64
|
+
next.all = seenOf(lines);
|
|
65
|
+
return next;
|
|
66
|
+
}
|
|
67
|
+
/** The channels a mark of `channels` records: only `unknown` from a source that names none. */
|
|
68
|
+
export const markedChannels = (channels, opts = {}) => opts.namesChannels === false ? channels.filter((c) => c === 'unknown') : [...channels];
|
|
69
|
+
function seenOf(on) {
|
|
70
|
+
const c = { seen: on.length };
|
|
71
|
+
if (on.length && on.every((l) => l.timeMs !== undefined)) {
|
|
72
|
+
const last = Math.max(...on.map((l) => l.timeMs));
|
|
73
|
+
c.lastTimeMs = last;
|
|
74
|
+
c.atLast = on.filter((l) => l.timeMs === last).length;
|
|
75
|
+
}
|
|
76
|
+
return c;
|
|
77
|
+
}
|
|
78
|
+
/** New messages per channel; `unknown` only when there is one. */
|
|
79
|
+
export function unreadCounts(lines, fresh) {
|
|
80
|
+
const n = (channel) => lines.filter((l, i) => l.channel === channel && fresh[i]).length;
|
|
81
|
+
const unknown = n('unknown');
|
|
82
|
+
return { public: n('public'), team: n('team'), private: n('private'), ...(unknown ? { unknown } : {}) };
|
|
83
|
+
}
|
|
84
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
85
|
+
const count = (v) => typeof v === 'number' && Number.isInteger(v) && v >= 0;
|
|
86
|
+
function channelOf(v) {
|
|
87
|
+
if (!isRec(v) || !count(v.seen))
|
|
88
|
+
return undefined;
|
|
89
|
+
const c = { seen: v.seen };
|
|
90
|
+
if (typeof v.lastTimeMs === 'number' && Number.isFinite(v.lastTimeMs)) {
|
|
91
|
+
c.lastTimeMs = v.lastTimeMs;
|
|
92
|
+
if (count(v.atLast))
|
|
93
|
+
c.atLast = v.atLast;
|
|
94
|
+
}
|
|
95
|
+
return c;
|
|
96
|
+
}
|
|
97
|
+
/** The cursor of `gameId` as `playerId` marked it; `undefined` when absent, another account's, or unusable. */
|
|
98
|
+
export async function readChatCursor(dir, gameId, playerId) {
|
|
99
|
+
try {
|
|
100
|
+
const c = JSON.parse(await readFile(chatCursorPath(dir, gameId), 'utf8'));
|
|
101
|
+
if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !isRec(c.channels))
|
|
102
|
+
return undefined;
|
|
103
|
+
const channels = {};
|
|
104
|
+
for (const ch of CHAT_CHANNELS) {
|
|
105
|
+
const v = channelOf(c.channels[ch]);
|
|
106
|
+
if (v)
|
|
107
|
+
channels[ch] = v;
|
|
108
|
+
}
|
|
109
|
+
const all = channelOf(c.all);
|
|
110
|
+
return { gameId, playerId, channels, ...(all ? { all } : {}) };
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Write the cursor (mode 0600, atomically); `true` when written. Best effort. */
|
|
117
|
+
export async function writeChatCursor(dir, cursor) {
|
|
118
|
+
try {
|
|
119
|
+
const path = chatCursorPath(dir, cursor.gameId);
|
|
120
|
+
await mkdir(join(dir, 'chat'), { recursive: true, mode: 0o700 });
|
|
121
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
122
|
+
try {
|
|
123
|
+
await writeFile(tmp, JSON.stringify(cursor), { mode: 0o600 });
|
|
124
|
+
await rename(tmp, path);
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
await rm(tmp, { force: true }).catch(() => undefined);
|
|
128
|
+
throw e;
|
|
129
|
+
}
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|