@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,556 @@
1
+ // war.app web-client wire codec — the binary frames the browser client POSTs to
2
+ // https://war.app/Services?m=<name>&js=1 (as uppercase hex).
3
+ //
4
+ // Everything is little-endian. Primitives:
5
+ // bool one byte, strictly 0 or 1 (anything else is a corrupt frame)
6
+ // int16/32/64, float32/64
7
+ // string bool "present" flag, then a 7-bit varint byte length, then UTF-8
8
+ // datetime float64 milliseconds since 2000-01-01T00:00:00Z; ±3.4028235e54 are
9
+ // the "no date" (min) and "max date" sentinels, and anything at or
10
+ // beyond ±2.524556148e14 reads as one of them
11
+ // guid 16 bytes in .NET order (first three groups byte-swapped)
12
+ // list/dict int32 count (-1 = null), then the items / key-value pairs; the reader
13
+ // refuses a count above MAX_WIRE_COUNT, and one above MAX_EMPTY_ITEMS
14
+ // whose items take no bytes
15
+ //
16
+ // A frame starts with a 14-byte header: uint16 flags (protocol version, high bit
17
+ // set on replies), int32 preamble 1514664249, int32 message number, int32 method.
18
+ // Requests then carry MessageExtrasUp, an optional auth block, and the method's
19
+ // parameters. Replies carry a byte (1 → MessageExtrasDown follows), a kind byte
20
+ // (5 → a server error {code, message} follows) and the method's result.
21
+ export const PREAMBLE = 1514664249;
22
+ export const PROTOCOL_VERSION = 242;
23
+ const REPLY_FLAG = 0x8000;
24
+ /** Milliseconds from the Unix epoch to 2000-01-01T00:00:00Z, the protocol's date epoch. */
25
+ export const DATE_EPOCH_MS = Date.UTC(2000, 0, 1);
26
+ /** Written for "no date" (.NET DateTime.MinValue on the server). */
27
+ export const NO_DATE_SENTINEL = -3.4028235e54;
28
+ /** Written for the maximum date. */
29
+ const MAX_DATE_SENTINEL = 3.4028235e54;
30
+ /** Values at or beyond ± this many ms read as a sentinel. */
31
+ const DATE_SENTINEL_THRESHOLD = 2.524556148e14;
32
+ /** The decoded form of the max-date sentinel (the largest JS Date). */
33
+ export const MAX_DATE = new Date(8.64e15);
34
+ /** Envelope kind byte: a MessageExtrasDown block follows. */
35
+ const EXTRAS_PRESENT = 1;
36
+ /** Envelope kind byte: a server error follows instead of a result. */
37
+ const ERROR_KIND = 5;
38
+ /** A malformed frame, or a value that cannot be encoded. */
39
+ export class ProtocolError extends Error {
40
+ kind;
41
+ constructor(kind, message) {
42
+ super(message);
43
+ this.kind = kind;
44
+ this.name = 'ProtocolError';
45
+ }
46
+ }
47
+ /**
48
+ * The largest list or dict count a reply may announce. Counts come from the wire as int32, and the
49
+ * biggest real collections (a board's territories, a map's bonuses, a game's orders) run to a few
50
+ * thousand; a million is far past any honest reply and keeps a forged count from driving a
51
+ * multi-billion-iteration loop.
52
+ */
53
+ export const MAX_WIRE_COUNT = 1_000_000;
54
+ /**
55
+ * The longest list or dict whose items may take no bytes at all. Every real item carries at least a
56
+ * flag or a number; a count above this whose first item read nothing cannot be honest — it would
57
+ * otherwise loop and allocate `count` times from a handful of bytes. The check is per list: nested
58
+ * lists of zero-byte items still multiply (about this many items per four bytes of frame), bounded by
59
+ * the frame's size, and only an interpreted reader can read zero bytes, which the interpreter's step
60
+ * budget bounds.
61
+ */
62
+ export const MAX_EMPTY_ITEMS = 1024;
63
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
64
+ const utf8Encoder = new TextEncoder();
65
+ const GUID_ORDER = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15];
66
+ function checkInt(value, min, max, what) {
67
+ if (!Number.isInteger(value) || value < min || value > max) {
68
+ throw new ProtocolError('out-of-range', `${what} out of range: ${value}`);
69
+ }
70
+ }
71
+ export class Writer {
72
+ buf = new Uint8Array(64);
73
+ view = new DataView(this.buf.buffer);
74
+ len = 0;
75
+ ensure(n) {
76
+ if (this.len + n <= this.buf.length)
77
+ return;
78
+ let size = this.buf.length * 2;
79
+ while (size < this.len + n)
80
+ size *= 2;
81
+ const next = new Uint8Array(size);
82
+ next.set(this.buf.subarray(0, this.len));
83
+ this.buf = next;
84
+ this.view = new DataView(next.buffer);
85
+ }
86
+ get length() {
87
+ return this.len;
88
+ }
89
+ bytes() {
90
+ return this.buf.slice(0, this.len);
91
+ }
92
+ u8(value) {
93
+ checkInt(value, 0, 0xff, 'u8');
94
+ this.ensure(1);
95
+ this.buf[this.len++] = value;
96
+ return this;
97
+ }
98
+ raw(bytes) {
99
+ this.ensure(bytes.length);
100
+ this.buf.set(bytes, this.len);
101
+ this.len += bytes.length;
102
+ return this;
103
+ }
104
+ bool(value) {
105
+ return this.u8(value ? 1 : 0);
106
+ }
107
+ uint16(value) {
108
+ checkInt(value, 0, 0xffff, 'uint16');
109
+ this.ensure(2);
110
+ this.view.setUint16(this.len, value, true);
111
+ this.len += 2;
112
+ return this;
113
+ }
114
+ int16(value) {
115
+ checkInt(value, -0x8000, 0x7fff, 'int16');
116
+ this.ensure(2);
117
+ this.view.setInt16(this.len, value, true);
118
+ this.len += 2;
119
+ return this;
120
+ }
121
+ int32(value) {
122
+ checkInt(value, -0x80000000, 0x7fffffff, 'int32');
123
+ this.ensure(4);
124
+ this.view.setInt32(this.len, value, true);
125
+ this.len += 4;
126
+ return this;
127
+ }
128
+ int64(value) {
129
+ if (typeof value === 'number')
130
+ checkInt(value, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, 'int64');
131
+ const big = BigInt(value);
132
+ if (big < -(1n << 63n) || big >= 1n << 63n)
133
+ throw new ProtocolError('out-of-range', `int64 out of range: ${big}`);
134
+ this.ensure(8);
135
+ this.view.setBigInt64(this.len, big, true);
136
+ this.len += 8;
137
+ return this;
138
+ }
139
+ float32(value) {
140
+ this.ensure(4);
141
+ this.view.setFloat32(this.len, value, true);
142
+ this.len += 4;
143
+ return this;
144
+ }
145
+ float64(value) {
146
+ this.ensure(8);
147
+ this.view.setFloat64(this.len, value, true);
148
+ this.len += 8;
149
+ return this;
150
+ }
151
+ varint(value) {
152
+ checkInt(value, 0, 0xffffffff, 'varint');
153
+ let n = value;
154
+ for (;;) {
155
+ const low = n % 128;
156
+ n = Math.floor(n / 128);
157
+ this.u8(n > 0 ? low | 0x80 : low);
158
+ if (n === 0)
159
+ return this;
160
+ }
161
+ }
162
+ /** A nullable string: present flag, varint byte length, UTF-8. */
163
+ string(value) {
164
+ if (value === null)
165
+ return this.bool(false);
166
+ const encoded = utf8Encoder.encode(value);
167
+ return this.bool(true).varint(encoded.length).raw(encoded);
168
+ }
169
+ /** A datetime; null is the "no date" sentinel. */
170
+ date(value) {
171
+ if (value === null)
172
+ return this.float64(NO_DATE_SENTINEL);
173
+ const ms = value.getTime();
174
+ if (Number.isNaN(ms))
175
+ throw new ProtocolError('out-of-range', 'invalid Date');
176
+ if (ms >= MAX_DATE.getTime())
177
+ return this.float64(MAX_DATE_SENTINEL);
178
+ return this.float64(ms - DATE_EPOCH_MS);
179
+ }
180
+ /** A GUID from its 32-hex-digit form (dashes allowed), written in .NET byte order. */
181
+ guid(value) {
182
+ const hex = value.replace(/-/g, '');
183
+ if (!/^[0-9a-fA-F]{32}$/.test(hex))
184
+ throw new ProtocolError('out-of-range', `not a guid: ${value}`);
185
+ const canonical = Array.from({ length: 16 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
186
+ const out = new Uint8Array(16);
187
+ GUID_ORDER.forEach((src, i) => {
188
+ out[src] = canonical[i];
189
+ });
190
+ return this.raw(out);
191
+ }
192
+ /** A nullable list: int32 count (-1 = null), then each item. */
193
+ list(items, writeItem) {
194
+ if (items === null)
195
+ return this.int32(-1);
196
+ this.int32(items.length);
197
+ for (const item of items)
198
+ writeItem(this, item);
199
+ return this;
200
+ }
201
+ /** A nullable dict: int32 count (-1 = null), then key, value pairs. */
202
+ dict(entries, writeKey, writeValue) {
203
+ if (entries === null)
204
+ return this.int32(-1);
205
+ this.int32(entries.size);
206
+ for (const [k, v] of entries) {
207
+ writeKey(this, k);
208
+ writeValue(this, v);
209
+ }
210
+ return this;
211
+ }
212
+ }
213
+ export class Reader {
214
+ buf;
215
+ view;
216
+ pos;
217
+ constructor(buf, offset = 0) {
218
+ this.buf = buf;
219
+ this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
220
+ this.pos = offset;
221
+ }
222
+ get position() {
223
+ return this.pos;
224
+ }
225
+ get remaining() {
226
+ return this.buf.length - this.pos;
227
+ }
228
+ need(n) {
229
+ if (this.pos + n > this.buf.length) {
230
+ throw new ProtocolError('truncated', `read past end: need ${n} byte(s) at offset ${this.pos} of ${this.buf.length}`);
231
+ }
232
+ }
233
+ u8() {
234
+ this.need(1);
235
+ return this.buf[this.pos++];
236
+ }
237
+ /**
238
+ * `n` bytes. `n` often comes from the wire (a string or byte-array length), so anything but a
239
+ * non-negative integer is refused before the position moves: a negative length would rewind the
240
+ * reader and a NaN or fractional one would leave every later read misaligned.
241
+ */
242
+ raw(n) {
243
+ if (!Number.isInteger(n) || n < 0) {
244
+ throw new ProtocolError('bad-length', `bad byte count ${n} at offset ${this.pos}`);
245
+ }
246
+ this.need(n);
247
+ const out = this.buf.slice(this.pos, this.pos + n);
248
+ this.pos += n;
249
+ return out;
250
+ }
251
+ bool() {
252
+ const v = this.u8();
253
+ if (v > 1)
254
+ throw new ProtocolError('bad-bool', `bad bool ${v} at offset ${this.pos - 1}`);
255
+ return v === 1;
256
+ }
257
+ uint16() {
258
+ this.need(2);
259
+ const v = this.view.getUint16(this.pos, true);
260
+ this.pos += 2;
261
+ return v;
262
+ }
263
+ int16() {
264
+ this.need(2);
265
+ const v = this.view.getInt16(this.pos, true);
266
+ this.pos += 2;
267
+ return v;
268
+ }
269
+ int32() {
270
+ this.need(4);
271
+ const v = this.view.getInt32(this.pos, true);
272
+ this.pos += 4;
273
+ return v;
274
+ }
275
+ /** An int64 as a number (exact up to 2^53). */
276
+ int64() {
277
+ this.need(8);
278
+ const v = this.view.getBigInt64(this.pos, true);
279
+ this.pos += 8;
280
+ return Number(v);
281
+ }
282
+ float32() {
283
+ this.need(4);
284
+ const v = this.view.getFloat32(this.pos, true);
285
+ this.pos += 4;
286
+ return v;
287
+ }
288
+ float64() {
289
+ this.need(8);
290
+ const v = this.view.getFloat64(this.pos, true);
291
+ this.pos += 8;
292
+ return v;
293
+ }
294
+ varint() {
295
+ let n = 0;
296
+ let scale = 1;
297
+ for (let i = 0; i < 5; i++) {
298
+ const c = this.u8();
299
+ n += (c & 0x7f) * scale;
300
+ if (!(c & 0x80))
301
+ return n;
302
+ scale *= 128;
303
+ }
304
+ throw new ProtocolError('bad-varint', `varint longer than 5 bytes ending at offset ${this.pos}`);
305
+ }
306
+ string() {
307
+ if (!this.bool())
308
+ return null;
309
+ const start = this.pos;
310
+ const n = this.varint();
311
+ const bytes = this.raw(n);
312
+ try {
313
+ return utf8Decoder.decode(bytes);
314
+ }
315
+ catch {
316
+ throw new ProtocolError('bad-string', `invalid UTF-8 in string at offset ${start}`);
317
+ }
318
+ }
319
+ /** A datetime; the "no date" sentinel reads as null, the max sentinel as MAX_DATE. */
320
+ date() {
321
+ const ms = this.float64();
322
+ if (ms <= -DATE_SENTINEL_THRESHOLD)
323
+ return null;
324
+ if (ms >= DATE_SENTINEL_THRESHOLD)
325
+ return MAX_DATE;
326
+ return new Date(DATE_EPOCH_MS + ms);
327
+ }
328
+ /** A GUID as 32 lowercase hex digits in canonical order. */
329
+ guid() {
330
+ const b = this.raw(16);
331
+ return GUID_ORDER.map((i) => b[i].toString(16).padStart(2, '0')).join('');
332
+ }
333
+ count() {
334
+ const at = this.pos;
335
+ const n = this.int32();
336
+ if (n === -1)
337
+ return null;
338
+ if (!Number.isInteger(n) || n < 0)
339
+ throw new ProtocolError('bad-length', `bad count ${n} at offset ${at}`);
340
+ if (n > MAX_WIRE_COUNT) {
341
+ throw new ProtocolError('bad-length', `count ${n} at offset ${at} exceeds ${MAX_WIRE_COUNT}`);
342
+ }
343
+ return n;
344
+ }
345
+ /** Refuses a long collection once an item is seen to take no bytes (see MAX_EMPTY_ITEMS). */
346
+ checkItemSize(n, before, at) {
347
+ if (n > MAX_EMPTY_ITEMS && this.pos === before) {
348
+ throw new ProtocolError('bad-length', `count ${n} at offset ${at} of items that take no bytes (at most ${MAX_EMPTY_ITEMS})`);
349
+ }
350
+ }
351
+ list(readItem) {
352
+ const at = this.pos;
353
+ const n = this.count();
354
+ if (n === null)
355
+ return null;
356
+ const out = [];
357
+ for (let i = 0; i < n; i++) {
358
+ const before = this.pos;
359
+ out.push(readItem(this));
360
+ this.checkItemSize(n, before, at);
361
+ }
362
+ return out;
363
+ }
364
+ dict(readKey, readValue) {
365
+ const at = this.pos;
366
+ const n = this.count();
367
+ if (n === null)
368
+ return null;
369
+ const out = new Map();
370
+ for (let i = 0; i < n; i++) {
371
+ const before = this.pos;
372
+ const k = readKey(this);
373
+ out.set(k, readValue(this));
374
+ this.checkItemSize(n, before, at);
375
+ }
376
+ return out;
377
+ }
378
+ }
379
+ function writeHeader(w, h) {
380
+ w.uint16((h.version & 0x7fff) | (h.reply ? REPLY_FLAG : 0))
381
+ .int32(PREAMBLE)
382
+ .int32(h.msgNum)
383
+ .int32(h.method);
384
+ }
385
+ export function readHeader(r) {
386
+ const flags = r.uint16();
387
+ const preamble = r.int32();
388
+ if (preamble !== PREAMBLE) {
389
+ throw new ProtocolError('bad-preamble', `bad preamble ${preamble} (expected ${PREAMBLE})`);
390
+ }
391
+ return { version: flags & 0x7fff, reply: (flags & REPLY_FLAG) !== 0, msgNum: r.int32(), method: r.int32() };
392
+ }
393
+ const writeIntStringDict = (w, d) => {
394
+ if (d === null) {
395
+ w.bool(false);
396
+ return;
397
+ }
398
+ w.bool(true).dict(d, (ww, k) => ww.int32(k), (ww, v) => ww.string(v));
399
+ };
400
+ const readIntStringDict = (r) => r.bool()
401
+ ? r.dict((rr) => rr.int32(), (rr) => rr.string())
402
+ : null;
403
+ function writeExtrasUp(w, e) {
404
+ writeIntStringDict(w, e.dict);
405
+ w.string(e.client)
406
+ .int32(e.serverInfoVersionA)
407
+ .int32(e.serverInfoVersionB)
408
+ .date(e.fDb)
409
+ .date(e.kFa)
410
+ .int32(e.platform);
411
+ }
412
+ export function readExtrasUp(r) {
413
+ const dict = readIntStringDict(r);
414
+ return {
415
+ dict: dict === null ? null : new Map([...dict].map(([k, v]) => [k, v ?? ''])),
416
+ client: r.string(),
417
+ serverInfoVersionA: r.int32(),
418
+ serverInfoVersionB: r.int32(),
419
+ fDb: r.date(),
420
+ kFa: r.date(),
421
+ platform: r.int32(),
422
+ };
423
+ }
424
+ function optional(r, read) {
425
+ return r.bool() ? read(r) : null;
426
+ }
427
+ function writeOptional(w, value, write) {
428
+ if (value === null) {
429
+ w.bool(false);
430
+ return;
431
+ }
432
+ w.bool(true);
433
+ write(w, value);
434
+ }
435
+ function readExtrasDown(r) {
436
+ return {
437
+ cAa: readIntStringDict(r),
438
+ wca: optional(r, (rr) => rr.int32()),
439
+ c2a: r.string(),
440
+ serverInfo: optional(r, (rr) => ({
441
+ okb: rr.string(),
442
+ lbFlags: rr.string(),
443
+ serverInfoVersionA: rr.int32(),
444
+ livestream: optional(rr, (l) => ({
445
+ j7: l.string(),
446
+ jdb: l.int32(),
447
+ lr: l.date(),
448
+ zfd: l.string(),
449
+ yfd: l.string(),
450
+ })),
451
+ serverInfoVersionB: rr.int32(),
452
+ })),
453
+ j9: optional(r, (rr) => rr.dict((k) => k.int32(), (v) => optional(v, (vv) => vv.list((s) => s.string())))),
454
+ unreadMail: optional(r, (rr) => ({ cYa: rr.bool(), kFa: rr.date(), h9: rr.bool() })),
455
+ };
456
+ }
457
+ function writeExtrasDown(w, e) {
458
+ writeOptional(w, e.cAa, (ww, d) => ww.dict(d, (x, k) => x.int32(k), (x, v) => x.string(v)));
459
+ writeOptional(w, e.wca, (ww, v) => ww.int32(v));
460
+ w.string(e.c2a);
461
+ writeOptional(w, e.serverInfo, (ww, s) => {
462
+ ww.string(s.okb).string(s.lbFlags).int32(s.serverInfoVersionA);
463
+ writeOptional(ww, s.livestream, (x, l) => x.string(l.j7).int32(l.jdb).date(l.lr).string(l.zfd).string(l.yfd));
464
+ ww.int32(s.serverInfoVersionB);
465
+ });
466
+ writeOptional(w, e.j9, (ww, d) => ww.dict(d, (x, k) => x.int32(k), (x, v) => writeOptional(x, v, (y, list) => y.list(list, (z, s) => z.string(s)))));
467
+ writeOptional(w, e.unreadMail, (ww, u) => ww.bool(u.cYa).date(u.kFa).bool(u.h9));
468
+ }
469
+ // ---------------------------------------------------------------------------
470
+ // Requests
471
+ /** The auth block's type tag, as the browser client writes it before the email. */
472
+ const AUTH_TAG = 4;
473
+ export function encodeRequest(frame) {
474
+ const w = new Writer();
475
+ writeHeader(w, {
476
+ version: frame.version ?? PROTOCOL_VERSION,
477
+ reply: false,
478
+ msgNum: frame.msgNum,
479
+ method: frame.method,
480
+ });
481
+ writeExtrasUp(w, frame.extras);
482
+ if (frame.email !== null)
483
+ w.bool(true).u8(AUTH_TAG).string(frame.email);
484
+ frame.params?.(w);
485
+ return w.bytes();
486
+ }
487
+ /**
488
+ * Decode a request frame (for tests and mock servers). `hasAuth` says whether
489
+ * the method takes the auth block — the frame itself does not say.
490
+ */
491
+ export function decodeRequest(bytes, opts) {
492
+ const r = new Reader(bytes);
493
+ const header = readHeader(r);
494
+ if (header.reply)
495
+ throw new ProtocolError('not-a-reply', 'expected a request frame, got a reply');
496
+ const extras = readExtrasUp(r);
497
+ let email = null;
498
+ if (opts.hasAuth && r.bool()) {
499
+ r.u8();
500
+ email = r.string();
501
+ }
502
+ return { ...header, extras, email, body: r };
503
+ }
504
+ export function decodeReplyEnvelope(bytes) {
505
+ const r = new Reader(bytes);
506
+ const header = readHeader(r);
507
+ if (!header.reply)
508
+ throw new ProtocolError('not-a-reply', `frame for method ${header.method} is not a reply`);
509
+ const env = { version: header.version, method: header.method, msgNum: header.msgNum, body: r };
510
+ if (r.u8() === EXTRAS_PRESENT)
511
+ env.extrasDown = readExtrasDown(r);
512
+ if (r.u8() === ERROR_KIND)
513
+ env.error = { code: r.int32(), message: r.string() };
514
+ return env;
515
+ }
516
+ /** Encode a reply frame (for tests and mock servers). */
517
+ export function encodeReply(frame) {
518
+ const w = new Writer();
519
+ writeHeader(w, {
520
+ version: frame.version ?? PROTOCOL_VERSION,
521
+ reply: true,
522
+ msgNum: frame.msgNum,
523
+ method: frame.method,
524
+ });
525
+ if (frame.extrasDown) {
526
+ w.u8(EXTRAS_PRESENT);
527
+ writeExtrasDown(w, frame.extrasDown);
528
+ }
529
+ else {
530
+ w.u8(0);
531
+ }
532
+ if (frame.error) {
533
+ w.u8(ERROR_KIND).int32(frame.error.code).string(frame.error.message);
534
+ }
535
+ else {
536
+ w.u8(0);
537
+ frame.body?.(w);
538
+ }
539
+ return w.bytes();
540
+ }
541
+ /** Bytes → uppercase hex, the form the client POSTs. */
542
+ export function toHex(bytes) {
543
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0'))
544
+ .join('')
545
+ .toUpperCase();
546
+ }
547
+ export function fromHex(hex) {
548
+ const clean = hex.trim();
549
+ if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) {
550
+ throw new ProtocolError('bad-length', 'not an even-length hex string');
551
+ }
552
+ const out = new Uint8Array(clean.length / 2);
553
+ for (let i = 0; i < out.length; i++)
554
+ out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
555
+ return out;
556
+ }
@@ -0,0 +1,12 @@
1
+ // Helpers for the records the interpreter decodes (src/protocol/interp.ts). Field names in the
2
+ // bundle are minified and change between releases, so readers find a record by its registered
3
+ // type name (`$type`) and its fields by read order.
4
+ export const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
5
+ // The interpreter adds `$type` (and `$ctorError` when a constructor threw); every other key is a
6
+ // field in read order. Minified field names can start with `$` too (`$c`, `$a` live), so drop
7
+ // only those two.
8
+ const META_KEYS = new Set(['$type', '$ctorError']);
9
+ /** A decoded record's field values in read order. */
10
+ export const fields = (o) => Object.entries(o)
11
+ .filter(([k]) => !META_KEYS.has(k))
12
+ .map(([, v]) => v);