@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.
Files changed (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,202 @@
1
+ // One web-client RPC round trip: build the frame, POST it as hex through the
2
+ // browser bridge to https://war.app/Services?m=<name>&js=1, decode the reply
3
+ // envelope, and carry the server's MessageExtrasDown values into the next
4
+ // request's MessageExtrasUp, as the real client does (docs/WEB-PROTOCOL.md).
5
+ import { McpToolError } from '@chrischall/mcp-utils';
6
+ import { readEmail } from '../config.js';
7
+ import { scrubSecrets } from '../redact.js';
8
+ import { decodeReplyEnvelope, encodeRequest, PROTOCOL_VERSION, fromHex, ProtocolError, toHex, } from './codec.js';
9
+ import { Method } from './methods.js';
10
+ /** The client version string the current web client sends. */
11
+ export const CLIENT_VERSION = 'v6.07.0.1';
12
+ /** EnumSerialization_Platform: the website. */
13
+ export const PLATFORM_WEBSITE = 15;
14
+ /**
15
+ * Server-info versions for the first request of a process, before any reply
16
+ * has supplied the real ones (the values the web client was observed sending).
17
+ */
18
+ export const INITIAL_SERVER_INFO_A = 348;
19
+ export const INITIAL_SERVER_INFO_B = 88732;
20
+ const SERVICES_URL = 'https://war.app/Services';
21
+ const CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8';
22
+ /** Methods whose frame carries no auth block. */
23
+ const NO_AUTH_METHODS = new Set([Method.GetMapDetails]);
24
+ /** Whether a method's parameters start with the auth (email) block. */
25
+ export function methodTakesAuth(methodId) {
26
+ return !NO_AUTH_METHODS.has(methodId);
27
+ }
28
+ /**
29
+ * The web client's own wording for the server error codes this server can
30
+ * meet (11, 51, 208: order commits; 33, 36, 333: chat; 254, 473, 750: joining
31
+ * an open seat; 88: any game call).
32
+ * 51 (`MustUseCard`, verified live) has no client wording; this is ours.
33
+ */
34
+ export const SERVER_ERROR_MESSAGES = {
35
+ 10: 'war.app refused the order sequence — card plays must come in turn-phase order.',
36
+ 11: 'Your orders deploy more or fewer armies than you are receiving this turn. Please verify your orders deploy the correct number.',
37
+ 51: 'You hold more cards than this game allows, so war.app requires you to play or discard one this turn.',
38
+ 33: 'Oops! This message is too long. Try breaking it into multiple smaller messages.',
39
+ 36: 'Your message was not sent because you have been sending too many messages to this game. Please try again later.',
40
+ 88: 'This game has been deleted.',
41
+ 208: 'The game has already advanced to the next turn. Please refresh.',
42
+ 333: 'This game has been archived and can no longer receive new chat.',
43
+ 254: 'Sorry, your slot was assigned to someone else by the game creator. Please ask the game creator to open up your slot.',
44
+ 473: "You don't have enough coins to join this game. Please deposit some coins and try again.",
45
+ 750: 'Sorry, the slot you joined is no longer available. Please try again with a different slot.',
46
+ };
47
+ /** The longest slice of an unmapped server message shown to the caller. */
48
+ const MAX_SERVER_MESSAGE = 200;
49
+ /** A ServerException reply (envelope kind 5). */
50
+ export class WarappServerError extends McpToolError {
51
+ code;
52
+ name = 'WarappServerError';
53
+ constructor(code, message) {
54
+ super(message, { kind: 'unknown' });
55
+ this.code = code;
56
+ }
57
+ }
58
+ /**
59
+ * #272: a failure before the request left this process (the email unread, the frame not built, the
60
+ * bridge not ready): the request was never sent, so nothing changed. {@link WarappRpc.call} marks such
61
+ * an error; a write reads it with {@link notSent} and says so, instead of calling the outcome unknown.
62
+ */
63
+ const NOT_SENT = Symbol('warapp.requestNotSent');
64
+ /** Mark `e` (made an Error when it is not one) as raised before the request was sent. */
65
+ function markNotSent(e) {
66
+ const err = e instanceof Error ? e : new Error(String(e));
67
+ err[NOT_SENT] = true;
68
+ return err;
69
+ }
70
+ /** Whether `e` was raised before the request was sent ({@link markNotSent}). */
71
+ export function notSent(e) {
72
+ return e instanceof Error && e[NOT_SENT] === true;
73
+ }
74
+ /**
75
+ * The web-client RPC channel. Hold ONE per process: message numbers count up
76
+ * per instance and the echoed extras live on it.
77
+ */
78
+ export class WarappRpc {
79
+ bridge;
80
+ email;
81
+ nextMsgNum = 1;
82
+ state = {
83
+ dict: new Map(),
84
+ client: CLIENT_VERSION,
85
+ serverInfoVersionA: INITIAL_SERVER_INFO_A,
86
+ serverInfoVersionB: INITIAL_SERVER_INFO_B,
87
+ fDb: null,
88
+ kFa: null,
89
+ platform: PLATFORM_WEBSITE,
90
+ };
91
+ constructor(opts) {
92
+ this.bridge = opts.bridge;
93
+ this.email = opts.email ?? (() => readEmail(opts.env));
94
+ }
95
+ /** A copy of the MessageExtrasUp the next request will carry. */
96
+ get extras() {
97
+ return { ...this.state, dict: this.state.dict === null ? null : new Map(this.state.dict) };
98
+ }
99
+ /**
100
+ * Send one request and return its reply envelope, `body` positioned at the
101
+ * method's result. A ServerException reply throws {@link WarappServerError}.
102
+ */
103
+ async call(methodName, methodId, writeParams) {
104
+ // Resolve the email first, so a missing one fails before anything is sent. #272: every failure
105
+ // up to the bridge's fetch is marked as one before sending (`notSent`).
106
+ let frame;
107
+ let bridge;
108
+ let email;
109
+ let msgNum;
110
+ try {
111
+ email = methodTakesAuth(methodId) ? this.email() : null;
112
+ msgNum = this.nextMsgNum++;
113
+ frame = encodeRequest({
114
+ method: methodId,
115
+ msgNum,
116
+ extras: this.extras,
117
+ email,
118
+ ...(writeParams ? { params: writeParams } : {}),
119
+ });
120
+ bridge = await this.bridge();
121
+ }
122
+ catch (e) {
123
+ throw markNotSent(e);
124
+ }
125
+ const res = await bridge.fetch({
126
+ method: 'POST',
127
+ path: `${SERVICES_URL}?m=${encodeURIComponent(methodName)}&js=1`,
128
+ headers: { 'content-type': CONTENT_TYPE },
129
+ body: toHex(frame),
130
+ });
131
+ if (res.status !== 200) {
132
+ throw new McpToolError(`war.app answered HTTP ${res.status} to ${methodName}.`, {
133
+ status: res.status,
134
+ kind: 'http',
135
+ });
136
+ }
137
+ const env = this.decode(methodName, res.body);
138
+ if (env.msgNum !== msgNum) {
139
+ throw new McpToolError(`war.app answered ${methodName} with message number ${env.msgNum}, expected ${msgNum}.`, { kind: 'unknown' });
140
+ }
141
+ if (env.version !== PROTOCOL_VERSION) {
142
+ // Every reader (the bundle's, and methods.ts) reads the layout of PROTOCOL_VERSION: a reply
143
+ // framed for another version would decode into wrong values, not an error (#131).
144
+ throw new McpToolError(`war.app answered ${methodName} in protocol version ${env.version}; this server reads version ${PROTOCOL_VERSION}.`, { kind: 'unknown', hint: 'The war.app client may have changed; this server needs an update to read it.' });
145
+ }
146
+ if (env.method !== methodId) {
147
+ throw new McpToolError(`war.app answered ${methodName} (method ${methodId}) with method ${env.method}.`, {
148
+ kind: 'unknown',
149
+ });
150
+ }
151
+ if (env.extrasDown)
152
+ this.echo(env.extrasDown);
153
+ if (env.error)
154
+ throw serverError(methodName, env.error.code, env.error.message, email);
155
+ return env;
156
+ }
157
+ decode(methodName, body) {
158
+ let bytes;
159
+ try {
160
+ bytes = fromHex(body);
161
+ }
162
+ catch {
163
+ throw new McpToolError(`war.app did not answer ${methodName} with a protocol frame. Make sure a war.app tab is open and ` +
164
+ 'signed in, then retry.', { kind: 'unknown' });
165
+ }
166
+ try {
167
+ return decodeReplyEnvelope(bytes);
168
+ }
169
+ catch (e) {
170
+ if (!(e instanceof ProtocolError))
171
+ throw e;
172
+ throw new McpToolError(`Could not decode war.app's reply to ${methodName}: ${e.message}`, {
173
+ kind: 'unknown',
174
+ cause: e,
175
+ });
176
+ }
177
+ }
178
+ /** Carry the reply's server-info versions and notification time forward. */
179
+ echo(down) {
180
+ if (down.serverInfo) {
181
+ this.state.serverInfoVersionA = down.serverInfo.serverInfoVersionA;
182
+ this.state.serverInfoVersionB = down.serverInfo.serverInfoVersionB;
183
+ }
184
+ if (down.unreadMail)
185
+ this.state.kFa = down.unreadMail.kFa;
186
+ }
187
+ }
188
+ function serverError(methodName, code, message, email) {
189
+ const known = SERVER_ERROR_MESSAGES[code];
190
+ if (known)
191
+ return new WarappServerError(code, `${known} (war.app error ${code})`);
192
+ // Unmapped: the message can be a whole server stack trace — keep its first
193
+ // line, short, with the account email scrubbed out (any letter case, raw or
194
+ // percent/form-encoded).
195
+ let detail = (message ?? '').split(/\r?\n/, 1)[0].trim();
196
+ if (email)
197
+ detail = scrubSecrets(detail, [{ value: email, anyCase: true }], '[email]');
198
+ if (detail.length > MAX_SERVER_MESSAGE)
199
+ detail = `${detail.slice(0, MAX_SERVER_MESSAGE)}…`;
200
+ const base = `war.app refused ${methodName} (server error ${code}).`;
201
+ return new WarappServerError(code, detail ? `${base} ${detail}` : base);
202
+ }
@@ -0,0 +1,393 @@
1
+ import { gameTopic } from '../protocol/methods.js';
2
+ import { CLIENT_VERSION, INITIAL_SERVER_INFO_A, INITIAL_SERVER_INFO_B, PLATFORM_WEBSITE, } from '../protocol/rpc.js';
3
+ import { DEFAULT_INITIAL_BACKOFF_MS, DEFAULT_MAX_BACKOFF_MS, parsePushFrame, SocketIoClient, subscribeFrameHex, } from './socketio.js';
4
+ import { realSetTimer } from './websocket.js';
5
+ const DEFAULT_MAX_EVENTS = 100;
6
+ const DEFAULT_IDLE_MS = 10 * 60_000;
7
+ /** Failed Subscribes in a row retried on the live session before leaving it to the next reconnect. */
8
+ export const MAX_SUBSCRIBE_RETRIES = 5;
9
+ /**
10
+ * The most games watched at once, across every open wait (each wait watches at most 20): a bound
11
+ * on what the process subscribes to and re-subscribes on every reconnect (#131).
12
+ */
13
+ export const MAX_WATCHED_GAMES = 100;
14
+ const defaultExtras = () => ({
15
+ dict: new Map(),
16
+ client: CLIENT_VERSION,
17
+ serverInfoVersionA: INITIAL_SERVER_INFO_A,
18
+ serverInfoVersionB: INITIAL_SERVER_INFO_B,
19
+ fDb: null,
20
+ kFa: null,
21
+ platform: PLATFORM_WEBSITE,
22
+ });
23
+ export class PushListener {
24
+ socket;
25
+ extras;
26
+ maxEvents;
27
+ now;
28
+ games = new Set();
29
+ /** Game ids sent in a Subscribe on the current session. */
30
+ subscribed = new Set();
31
+ /** A Subscribe being sent on the current session, by each game it carries (#148). */
32
+ sending = new Map();
33
+ /** The {@link mark} at which a Subscribe carrying each game went through on the current session. */
34
+ subscribedAt = new Map();
35
+ /** Counts Subscribes that went through: what {@link mark} reads. */
36
+ subscribes = 0;
37
+ refused = new Map();
38
+ events = [];
39
+ listeners = new Set();
40
+ reconnectListeners = new Set();
41
+ connectListeners = new Set();
42
+ connects = 0;
43
+ nextMsgNum = 1;
44
+ /** Open watches per game (a wait holds its games until it releases them). */
45
+ holds = new Map();
46
+ /** The games each Subscribe this session carried, by message number. */
47
+ sentBy = new Map();
48
+ retrying = false;
49
+ subscribeFailures = 0;
50
+ subscribeError;
51
+ /** A Subscribe failed on this session: the next one that goes through tells the connect listeners. */
52
+ resubscribeOwed = false;
53
+ cancelIdle;
54
+ opts;
55
+ sleep;
56
+ constructor(opts) {
57
+ this.opts = opts;
58
+ this.sleep =
59
+ opts.sleep ??
60
+ ((ms) => new Promise((resolve) => {
61
+ const t = setTimeout(resolve, ms);
62
+ t.unref?.();
63
+ }));
64
+ this.extras = opts.extras ?? defaultExtras;
65
+ this.maxEvents = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
66
+ this.now = opts.now ?? Date.now;
67
+ this.socket = new SocketIoClient({
68
+ transport: opts.transport,
69
+ now: this.now,
70
+ onMessage: (data) => this.onMessage(data),
71
+ onReconnect: () => {
72
+ for (const fn of this.reconnectListeners)
73
+ fn();
74
+ },
75
+ ...(opts.webSocket ? { webSocket: opts.webSocket } : {}),
76
+ ...(opts.setTimer ? { setTimer: opts.setTimer } : {}),
77
+ onConnect: async () => {
78
+ this.subscribed = new Set();
79
+ this.sending.clear();
80
+ this.subscribedAt.clear();
81
+ this.sentBy.clear();
82
+ this.subscribeFailures = 0;
83
+ this.resubscribeOwed = false;
84
+ await this.subscribePending();
85
+ const e = { reconnect: ++this.connects > 1 };
86
+ for (const fn of this.connectListeners)
87
+ fn(e);
88
+ },
89
+ ...(opts.sleep ? { sleep: opts.sleep } : {}),
90
+ ...(opts.initialBackoffMs !== undefined ? { initialBackoffMs: opts.initialBackoffMs } : {}),
91
+ ...(opts.maxBackoffMs !== undefined ? { maxBackoffMs: opts.maxBackoffMs } : {}),
92
+ });
93
+ }
94
+ /**
95
+ * Watch these games: start the socket if needed and subscribe to any not
96
+ * yet subscribed. Never throws for a socket failure — the socket keeps
97
+ * reconnecting in the background and subscribes on connect. Throws, before
98
+ * changing anything, when it would watch more than `maxGames` games at once.
99
+ * Each watch is ended by one `release` (the unwatch).
100
+ *
101
+ * Resolves true when a Subscribe for one of these games went through on the live session after
102
+ * the caller may have read them: one it sent, one another watch had in flight (it waits for that
103
+ * one), or, with `since` (the {@link mark} the caller took before it read the games), one that
104
+ * went through after that mark (#148). A push for those games before it was lost, so the caller
105
+ * re-reads them. False otherwise — subscribed here before the mark, or not connected (the connect
106
+ * subscribes and tells the connect listeners), or the Subscribe failed (its retry tells the
107
+ * connect listeners once it goes through).
108
+ */
109
+ async watch(gameIds, opts = {}) {
110
+ const max = this.opts.maxGames ?? MAX_WATCHED_GAMES;
111
+ const total = new Set([...this.games, ...gameIds]).size;
112
+ if (total > max) {
113
+ throw new Error(`Watching ${total} war.app games at once is over the limit: the push listener watches at most ${max} games. ` +
114
+ 'Wait on fewer games, or let another wait finish first.');
115
+ }
116
+ this.cancelIdle?.();
117
+ this.cancelIdle = undefined;
118
+ for (const id of gameIds) {
119
+ this.games.add(id);
120
+ this.holds.set(id, (this.holds.get(id) ?? 0) + 1);
121
+ }
122
+ this.socket.start();
123
+ if (!this.socket.connected)
124
+ return false;
125
+ // Another wait's Subscribe for one of these games may be on its way: the server has not seen it
126
+ // yet, so a push before it lands is lost to this caller too. Wait for it, then say so (#148).
127
+ const inFlight = [...new Set(gameIds.map((g) => this.sending.get(g)).filter((p) => p !== undefined))];
128
+ let sent = false;
129
+ try {
130
+ if (await this.subscribePending()) {
131
+ this.resubscribed();
132
+ sent = true;
133
+ }
134
+ }
135
+ catch (e) {
136
+ // Retried on this session (with backoff); a reconnect re-subscribes everything anyway.
137
+ this.subscribeFailed(e);
138
+ }
139
+ if (inFlight.length && (await Promise.allSettled(inFlight)).some((r) => r.status === 'fulfilled'))
140
+ sent = true;
141
+ const since = opts.since;
142
+ if (!sent && since !== undefined)
143
+ sent = gameIds.some((g) => (this.subscribedAt.get(g) ?? -Infinity) > since);
144
+ return sent;
145
+ }
146
+ /**
147
+ * End a watch (each `watch` is released once) — the unwatch. A game no watch holds any more is
148
+ * no longer watched: it is not re-subscribed on a reconnect and leaves room under the cap (#131).
149
+ * (No Unsubscribe is sent: a push for it on the current session is ignored, not recorded, #148.) When no
150
+ * watch is left, the socket stops after the idle delay unless a new watch comes first.
151
+ */
152
+ release(gameIds) {
153
+ for (const id of gameIds) {
154
+ const n = (this.holds.get(id) ?? 0) - 1;
155
+ if (n > 0)
156
+ this.holds.set(id, n);
157
+ else {
158
+ this.holds.delete(id);
159
+ this.games.delete(id);
160
+ }
161
+ }
162
+ if (this.holds.size || this.cancelIdle || !this.socket.started)
163
+ return;
164
+ const timer = this.opts.idleTimer ?? realSetTimer;
165
+ this.cancelIdle = timer(this.opts.idleMs ?? DEFAULT_IDLE_MS, () => {
166
+ this.cancelIdle = undefined;
167
+ if (this.holds.size)
168
+ return;
169
+ this.socket.stop();
170
+ // The next watch starts a new run: its first connect is not a reconnect (#131).
171
+ this.connects = 0;
172
+ this.games.clear();
173
+ this.subscribed = new Set();
174
+ this.sentBy.clear();
175
+ this.refused.clear();
176
+ this.subscribeError = undefined;
177
+ this.subscribeFailures = 0;
178
+ this.resubscribeOwed = false;
179
+ });
180
+ }
181
+ /** Stop watching games that cannot change any more (finished): they are not re-subscribed. */
182
+ forget(gameIds) {
183
+ for (const id of gameIds) {
184
+ this.games.delete(id);
185
+ this.subscribed.delete(id);
186
+ }
187
+ }
188
+ /**
189
+ * A mark to pass to {@link watch} as `since`: take it before reading the games, and `watch` says
190
+ * whether a Subscribe for one of them went through after it (another wait's, #148).
191
+ */
192
+ mark() {
193
+ return this.subscribes;
194
+ }
195
+ /** Listen for GameUpdated pushes; returns the unsubscribe. */
196
+ onUpdate(fn) {
197
+ this.listeners.add(fn);
198
+ return () => {
199
+ this.listeners.delete(fn);
200
+ };
201
+ }
202
+ /**
203
+ * Listen for reconnects (every connect after the first, once re-subscribed):
204
+ * pushes during the gap were lost, so re-read GameFeed. Returns the unsubscribe.
205
+ */
206
+ onReconnect(fn) {
207
+ this.reconnectListeners.add(fn);
208
+ return () => {
209
+ this.reconnectListeners.delete(fn);
210
+ };
211
+ }
212
+ /**
213
+ * Listen for every connect, the first included, once subscribed: a game's turn that resolved
214
+ * before its Subscribe sent no push here, so re-read GameFeed (#131). `reconnect` is false for
215
+ * the first connect of the process. Also fired, with `resubscribed: true`, when a Subscribe that
216
+ * failed on this session goes through on a retry: a turn that resolved in between sent no push
217
+ * either. Returns the unsubscribe.
218
+ */
219
+ onConnect(fn) {
220
+ this.connectListeners.add(fn);
221
+ return () => {
222
+ this.connectListeners.delete(fn);
223
+ };
224
+ }
225
+ /** The most recent events, newest first. */
226
+ recent(limit = this.maxEvents) {
227
+ return this.events.slice(-limit).reverse();
228
+ }
229
+ status() {
230
+ const s = {
231
+ started: this.socket.started,
232
+ connected: this.socket.connected,
233
+ watching: [...this.games].sort((a, b) => a - b),
234
+ refused: Object.fromEntries(this.refused),
235
+ };
236
+ const transport = this.socket.transport;
237
+ if (transport !== undefined)
238
+ s.transport = transport;
239
+ const err = this.subscribeError ?? this.socket.lastError;
240
+ if (err !== undefined)
241
+ s.lastError = err;
242
+ if (this.socket.connected) {
243
+ const pending = s.watching.filter((g) => !this.subscribed.has(g));
244
+ if (pending.length)
245
+ s.pending = pending;
246
+ }
247
+ return s;
248
+ }
249
+ stop() {
250
+ this.cancelIdle?.();
251
+ this.cancelIdle = undefined;
252
+ this.socket.stop();
253
+ this.connects = 0;
254
+ }
255
+ /** Send a Subscribe for every game not yet subscribed; true when one was sent. */
256
+ async subscribePending() {
257
+ const pending = [...this.games].filter((g) => !this.subscribed.has(g));
258
+ if (!pending.length)
259
+ return false;
260
+ for (const g of pending)
261
+ this.subscribed.add(g);
262
+ const msgNum = this.nextMsgNum++;
263
+ this.sentBy.set(msgNum, pending);
264
+ const send = this.socket.sendMessage(subscribeFrameHex(pending.map(gameTopic), msgNum, this.extras()));
265
+ for (const g of pending)
266
+ this.sending.set(g, send);
267
+ try {
268
+ await send;
269
+ }
270
+ catch (e) {
271
+ this.sentBy.delete(msgNum);
272
+ for (const g of pending)
273
+ this.subscribed.delete(g);
274
+ throw e;
275
+ }
276
+ finally {
277
+ for (const g of pending)
278
+ if (this.sending.get(g) === send)
279
+ this.sending.delete(g);
280
+ }
281
+ const at = ++this.subscribes;
282
+ for (const g of pending)
283
+ this.subscribedAt.set(g, at);
284
+ return true;
285
+ }
286
+ /**
287
+ * The retries on this session ran out with games still unsubscribed on a socket that looks
288
+ * healthy: start a new session rather than leave them unwatched until some later reconnect (#148).
289
+ * Its connect re-subscribes every game and tells the connect listeners, so waits re-read.
290
+ */
291
+ recycle() {
292
+ if (!this.socket.connected || ![...this.games].some((g) => !this.subscribed.has(g)))
293
+ return;
294
+ this.socket.recycle();
295
+ }
296
+ /** A Subscribe went through on the live session: if an earlier one failed, the games it carried may have missed a push. */
297
+ resubscribed() {
298
+ if (!this.resubscribeOwed)
299
+ return;
300
+ this.resubscribeOwed = false;
301
+ const e = { reconnect: false, resubscribed: true };
302
+ for (const fn of this.connectListeners)
303
+ fn(e);
304
+ }
305
+ /** A Subscribe failed (not sent, or refused by the server): note it and retry with backoff. */
306
+ subscribeFailed(e) {
307
+ this.subscribeError = e instanceof Error ? e.message : String(e);
308
+ this.subscribeFailures++;
309
+ this.resubscribeOwed = true;
310
+ if (this.retrying)
311
+ return;
312
+ if (this.subscribeFailures > MAX_SUBSCRIBE_RETRIES) {
313
+ this.recycle();
314
+ return;
315
+ }
316
+ this.retrying = true;
317
+ void (async () => {
318
+ try {
319
+ const initial = this.opts.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;
320
+ const max = this.opts.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
321
+ while (this.subscribeFailures <= MAX_SUBSCRIBE_RETRIES) {
322
+ await this.sleep(Math.min(max, initial * 2 ** (this.subscribeFailures - 1)));
323
+ // Not connected: the next connect subscribes every game.
324
+ if (!this.socket.connected)
325
+ return;
326
+ if (![...this.games].some((g) => !this.subscribed.has(g)))
327
+ return;
328
+ try {
329
+ if (await this.subscribePending())
330
+ this.resubscribed();
331
+ return;
332
+ }
333
+ catch (err) {
334
+ this.subscribeError = err instanceof Error ? err.message : String(err);
335
+ this.subscribeFailures++;
336
+ }
337
+ }
338
+ this.retrying = false;
339
+ this.recycle();
340
+ }
341
+ finally {
342
+ this.retrying = false;
343
+ }
344
+ })();
345
+ }
346
+ onMessage(data) {
347
+ const msg = parsePushFrame(data);
348
+ if (!msg)
349
+ return;
350
+ if (msg.kind === 'subscribe-reply') {
351
+ const games = this.sentBy.get(msg.msgNum) ?? [];
352
+ this.sentBy.delete(msg.msgNum);
353
+ if (msg.error !== undefined) {
354
+ // The Subscribe was refused as a whole: those games are not subscribed (#131).
355
+ for (const g of games)
356
+ this.subscribed.delete(g);
357
+ this.subscribeFailed(new Error(`war.app refused the push Subscribe (server error ${msg.error}).`));
358
+ return;
359
+ }
360
+ this.subscribeError = undefined;
361
+ this.subscribeFailures = 0;
362
+ for (const [topic, code] of msg.rejected)
363
+ this.refused.set(topic, code);
364
+ return;
365
+ }
366
+ if (msg.kind !== 'game-updated')
367
+ return;
368
+ // Only a game some wait watches: a push for one whose waits have ended (no Unsubscribe is sent,
369
+ // so the session still carries it) is not recorded (#148).
370
+ if (!this.games.has(msg.gameId))
371
+ return;
372
+ const update = { gameId: msg.gameId, at: new Date(this.now()).toISOString(), ...(msg.chat ? { chat: true } : {}) };
373
+ this.events.push(update);
374
+ if (this.events.length > this.maxEvents)
375
+ this.events.splice(0, this.events.length - this.maxEvents);
376
+ for (const fn of this.listeners)
377
+ fn(update);
378
+ }
379
+ }
380
+ const perTransport = new WeakMap();
381
+ /**
382
+ * The one listener for a bridge (so for the process: index.ts shares one
383
+ * bridge across connections). Built on first use; the socket starts on the
384
+ * first `watch`.
385
+ */
386
+ export function pushListenerFor(key, opts) {
387
+ let l = perTransport.get(key);
388
+ if (!l) {
389
+ l = new PushListener(opts);
390
+ perTransport.set(key, l);
391
+ }
392
+ return l;
393
+ }
@@ -0,0 +1,66 @@
1
+ // socket.io v0.9 packet helpers shared by both push transports (xhr-polling
2
+ // over the bridge, src/push/socketio.ts; the direct WebSocket,
3
+ // src/push/websocket.ts). Pure functions — no I/O.
4
+ export const SOCKET_URL = 'https://war.app/socket.io/1/';
5
+ /** Parse a handshake reply `sid:heartbeat:close:transports`; throws on anything else. */
6
+ export function parseHandshake(body) {
7
+ const parts = body.trim().split(':');
8
+ const [sid, hb, close, transports] = parts;
9
+ if (parts.length !== 4 || !sid || !/^[A-Za-z0-9_-]+$/.test(sid) || transports === undefined) {
10
+ throw new Error('war.app did not answer the socket handshake with a session.');
11
+ }
12
+ return {
13
+ sid,
14
+ heartbeatMs: (Number(hb) || 0) * 1000,
15
+ closeMs: (Number(close) || 0) * 1000,
16
+ transports: transports.split(','),
17
+ };
18
+ }
19
+ /** Split a poll body into packets (one bare packet, or the `�<len>�` framing). */
20
+ export function splitPayload(body) {
21
+ if (!body.startsWith('�'))
22
+ return body === '' ? [] : [body];
23
+ const out = [];
24
+ let i = 0;
25
+ while (i < body.length && body[i] === '�') {
26
+ const end = body.indexOf('�', i + 1);
27
+ if (end < 0)
28
+ break;
29
+ const len = Number(body.slice(i + 1, end));
30
+ if (!Number.isInteger(len) || len < 0)
31
+ break;
32
+ out.push(body.slice(end + 1, end + 1 + len));
33
+ i = end + 1 + len;
34
+ }
35
+ return out;
36
+ }
37
+ /** Parse one packet `type:id:endpoint[:data]`. */
38
+ export function parsePacket(raw) {
39
+ const type = raw.split(':', 1)[0];
40
+ switch (type) {
41
+ case '0':
42
+ return { type: 'disconnect' };
43
+ case '1':
44
+ return { type: 'connect' };
45
+ case '2':
46
+ return { type: 'heartbeat' };
47
+ case '8':
48
+ return { type: 'noop' };
49
+ case '7': {
50
+ const parts = raw.split(':');
51
+ return { type: 'error', reason: parts.slice(3).join(':') };
52
+ }
53
+ case '3': {
54
+ // Data follows the third colon.
55
+ let at = -1;
56
+ for (let n = 0; n < 3; n++) {
57
+ at = raw.indexOf(':', at + 1);
58
+ if (at < 0)
59
+ return { type: 'other', raw };
60
+ }
61
+ return { type: 'message', data: raw.slice(at + 1) };
62
+ }
63
+ default:
64
+ return { type: 'other', raw };
65
+ }
66
+ }