@chrischall/warapp-mcp 0.4.0 → 0.5.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/dist/chat.js CHANGED
@@ -16,9 +16,12 @@ import { parseFeedTime } from './normalize.js';
16
16
  import { asInt } from './scalars.js';
17
17
  export const GAME_DETAILS_AND_CHAT = 'warlight.shared.GameDetailsAndChat';
18
18
  export const GAME_MESSAGE = 'warlight.shared.GameMessage';
19
- /** GameMessage field positions in read order, and its whole field count. */
20
- const GM = { date: 0, sender: 1, group: 2, id: 4, text: 5, channel: 6, to: 7, turn: 9 };
21
- export const GAME_MESSAGE_FIELDS = 10;
19
+ /**
20
+ * GameMessage field positions in read order, and its whole field count (protocol 243: the shared images,
21
+ * an optional list of strings, at 5, and the reactions, an optional list of records, at 7).
22
+ */
23
+ const GM = { date: 0, sender: 1, group: 2, id: 4, images: 5, text: 6, reactions: 7, channel: 8, to: 9, turn: 11 };
24
+ export const GAME_MESSAGE_FIELDS = 12;
22
25
  /** The public channel's value (any other is a team). */
23
26
  export const PUBLIC_CHANNEL = -1;
24
27
  export const CHAT_CHANNELS = ['public', 'team', 'private', 'unknown'];
@@ -39,8 +42,13 @@ function webLine(m) {
39
42
  const channel = f[GM.channel];
40
43
  const to = f[GM.to];
41
44
  const turn = f[GM.turn];
45
+ const images = f[GM.images];
46
+ const reactions = f[GM.reactions];
42
47
  if (!(date === null || date instanceof Date) || !optInt(sender) || !optInt(group) || !optInt(to) || !optInt(turn))
43
48
  return undefined;
49
+ // Not reported, but checked: a field of another type here means the layout is not 243's.
50
+ if (!(images === null || Array.isArray(images)) || !(reactions === null || Array.isArray(reactions)))
51
+ return undefined;
44
52
  if (!(id === null || typeof id === 'string' || isInt(id)) || typeof text !== 'string' || !isInt(channel))
45
53
  return undefined;
46
54
  const line = { sender, text, turn, channel: 'unknown' };
package/dist/my-games.js CHANGED
@@ -26,7 +26,7 @@ export const gameStateName = (code) => GAME_STATE_NAMES[code] ?? String(code);
26
26
  const GAME_WAITING = 2;
27
27
  const GAME_PLAYING = 3;
28
28
  const GAME_DISTRIBUTING = 5;
29
- const GAME_FINISHED = 4;
29
+ export const GAME_FINISHED = 4;
30
30
  const PLAYER_PLAYING = 2;
31
31
  /** GameInfo field positions in read order, and its whole field count (src/open-games.ts reads the same record). */
32
32
  const GI = { gameId: 7, name: 13, lastTurn: 14, players: 16, state: 22 };
@@ -24,7 +24,8 @@ import { createHash, randomBytes } from 'node:crypto';
24
24
  import { chmod, mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
25
25
  import { join } from 'node:path';
26
26
  import { withPathLock } from '../path-lock.js';
27
- import { BundleInterpreter, parseBundle, READER_HELPERS, REQUIRED_HELPERS, } from './interp.js';
27
+ import { PROTOCOL_VERSION } from './codec.js';
28
+ import { BundleInterpreter, parseBundle, } from './interp.js';
28
29
  /** A page that loads the game client (the homepage does not). */
29
30
  const DEFAULT_PAGE_URL = 'https://war.app/MultiPlayer';
30
31
  /** The only host the bundle is downloaded from (exactly this host: no subdomain, no port). */
@@ -107,6 +108,17 @@ export class WarappBundle {
107
108
  constructor(src, version, opts = {}) {
108
109
  this.version = version;
109
110
  this.interp = new BundleInterpreter(parseBundle(src), opts);
111
+ // Every request is framed in this server's protocol, and war.app answers in the protocol a request
112
+ // declares, so the replies are in PROTOCOL_VERSION's layout: a client whose readers default to another
113
+ // protocol would read them in its own layout. Such a build (a newer release, or an old stand-in) is
114
+ // refused here, like a client whose helpers cannot be checked (docs/CLIENT-RELEASES.md).
115
+ const protocol = this.interp.bundleProtocol;
116
+ if (opts.version === undefined && protocol !== undefined && protocol !== PROTOCOL_VERSION) {
117
+ throw new BundleError('protocol-mismatch', `war.app's client bundle ${version} speaks protocol ${protocol}, and this server speaks ${PROTOCOL_VERSION}; ` +
118
+ 'its readers would read the replies in the wrong layout, so it is not used. ' +
119
+ (protocol > PROTOCOL_VERSION ? 'The client changed and this server needs an update.' : 'It is an older client.'));
120
+ }
121
+ this.protocol = protocol;
110
122
  // The built-in reader helpers are pinned to one client release while the bundle floats:
111
123
  // refuse a bundle whose own helpers read differently, rather than decode it wrongly (#131).
112
124
  this.dialectCheck = this.interp.verifyDialect();
@@ -116,7 +128,7 @@ export class WarappBundle {
116
128
  }
117
129
  // The count, flag and byte helpers decode every army count, fog flag and unit count: one this
118
130
  // check cannot verify could be a swapped same-width read, which no later check catches (#148).
119
- const unverifiedRequired = REQUIRED_HELPERS.map((n) => `${READER_HELPERS}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
131
+ const unverifiedRequired = this.interp.requiredHelpers.map((n) => `${this.interp.helperClass}.${n}`).filter((k) => this.dialectCheck.unverified.includes(k));
120
132
  if (unverifiedRequired.length) {
121
133
  throw new BundleError('dialect-unverified', `war.app's client bundle ${version} defines ${unverifiedRequired.join(', ')} in a way this server cannot check ` +
122
134
  `(${unverifiedRequired.map((k) => this.dialectCheck.reasons?.[k] ?? 'unverified').join('; ')}); those read every ` +
@@ -125,6 +137,12 @@ export class WarappBundle {
125
137
  }
126
138
  /** The built-in reader helpers checked against this bundle's own definitions at load. */
127
139
  dialectCheck;
140
+ /** The protocol version the bundle's readers default to, when it can be read from the bundle. */
141
+ protocol;
142
+ /** The reader names were derived from this bundle (false: the built-in v6.07 names). */
143
+ get derivedDialect() {
144
+ return this.interp.derived;
145
+ }
128
146
  /** What this bundle's decoding rests on, for the tools to show (#148). */
129
147
  report() {
130
148
  const { verified, unverified, reasons } = this.dialectCheck;
@@ -157,15 +175,15 @@ export class WarappBundle {
157
175
  }
158
176
  }
159
177
  /**
160
- * The client release the built-in readers (src/protocol/interp.ts `DEFAULT_DIALECT`) and every
161
- * hand-written encoder are written for: client v6.07, protocol 242. war.app's CDN still serves it by
162
- * version, byte for byte, and war.app still answers a protocol-242 request in 242's layout. So when
163
- * the current client is refused (2026-11-17: 639304451701341657 renamed every reader on protocol
164
- * 243), this one stands in and decodes those replies exactly. Only bytes with this digest are used.
178
+ * The pinned known-good client: v6.08.0.2, protocol 243, the release every hand-written encoder and
179
+ * reader of this server is written for (#340). It stands in for a current client refused at load when
180
+ * no recorded build does, only with this digest. war.app's CDN ignores `?v=` and serves the current
181
+ * build, so it can be downloaded by version only while Cloudflare still caches that URL
182
+ * (docs/CLIENT-RELEASES.md): the copy kept in the data dir is what a stand-in really rests on.
165
183
  */
166
184
  export const KNOWN_GOOD_BUNDLE = {
167
- version: '639294131571648437',
168
- digest: 'dec5cf174f6affb9e4c08802534cf8c6c6496eff977847aaf1497535e3371404',
185
+ version: '639304508939095333',
186
+ digest: '3c55e2d08681d05661eb350b3d72d02f25729130bb78dc9c5d3b1febd73febd1',
169
187
  };
170
188
  /** The CDN URL of a client release, by version (the location {@link discoverBundleUrl} pins). */
171
189
  const bundleUrlOf = (version) => `https://${BUNDLE_HOST}${BUNDLE_PATH}?v=${version}`;
@@ -325,7 +343,7 @@ async function readVerified(file, digest) {
325
343
  return null;
326
344
  }
327
345
  /** Whether `e` is the load-time refusal of a client this server cannot read (#131, #148). */
328
- const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified');
346
+ const isDialectRefusal = (e) => e instanceof BundleError && (e.kind === 'dialect-mismatch' || e.kind === 'dialect-unverified' || e.kind === 'protocol-mismatch');
329
347
  /** Write `src` into the cache as `name` (`0700` directories, an atomic `0600` file). */
330
348
  async function cacheBundle(dataDir, dir, name, src) {
331
349
  await ensurePrivateDir(dataDir);
@@ -19,7 +19,7 @@
19
19
  // parameters. Replies carry a byte (1 → MessageExtrasDown follows), a kind byte
20
20
  // (5 → a server error {code, message} follows) and the method's result.
21
21
  export const PREAMBLE = 1514664249;
22
- export const PROTOCOL_VERSION = 242;
22
+ export const PROTOCOL_VERSION = 243;
23
23
  const REPLY_FLAG = 0x8000;
24
24
  /** Milliseconds from the Unix epoch to 2000-01-01T00:00:00Z, the protocol's date epoch. */
25
25
  export const DATE_EPOCH_MS = Date.UTC(2000, 0, 1);
@@ -0,0 +1,371 @@
1
+ // Deriving the reader dialect from the client bundle itself.
2
+ //
3
+ // Every war.app client build re-minifies the code, hotfix builds included (docs/CLIENT-RELEASES.md),
4
+ // so the names the bundle's readers call — the BinaryReader's methods (`a.Tg()`), the Serializer's
5
+ // helpers (`P.Ya(a)`), the Enumerable helpers, the nullable wrapper classes — change with every
6
+ // build while what they do does not. Rather than pin one build's names, this module finds them by
7
+ // structure:
8
+ //
9
+ // - the wrapper and helper CLASSES by their registered type names (`W["warlight.shared.Serializer"]=P`),
10
+ // which the minifier keeps;
11
+ // - the haxe.io.Input methods by what they do (readByte throws its own name; readInt32 reads four
12
+ // bytes and shifts by 24; readInt16 sign-extends at 32768; …);
13
+ // - the BinaryReader methods by the Input method they call (or the varint/raw/string shapes);
14
+ // - the static helpers by their canonical form: the function's tokens with every name renamed to
15
+ // its order of first appearance, except reader-method names (replaced by their role) and class
16
+ // vars (replaced by their registered type name). Two builds' helpers that do the same thing have
17
+ // the same canonical form, whatever the minifier called them.
18
+ //
19
+ // Nothing here runs bundle code: it reads source text. The result is only names → roles; the
20
+ // interpreter attaches its built-in natives to them and `verifyDialect` still probes the bundle's
21
+ // own definitions against those natives, so a wrong derivation is refused at load, never decoded
22
+ // through. A bundle this module cannot read in full gets `null`, and the interpreter falls back to
23
+ // its built-in (v6.07) names.
24
+ import { parseExpressionAt } from 'acorn';
25
+ /** Registered type names of the classes the dialect lives on. */
26
+ const INPUT_TYPE = 'haxe.io.Input';
27
+ const READER_TYPE = 'system.io.BinaryReader';
28
+ const SERIALIZER_TYPE = 'warlight.shared.Serializer';
29
+ const UTILITY_TYPE = 'warlight.shared.SharedUtility';
30
+ const PUMP_TYPE = 'warlight.shared.MessagePump';
31
+ const ENUMERABLE_TYPE = 'system.linq.Enumerable';
32
+ /** The wrapper classes `new X(v)` reads as `v` (v6.07: Z, Yb, uc, dc, oc, ec, fc). */
33
+ export const WRAPPER_TYPES = [
34
+ 'system.Nullable_Int',
35
+ 'system.Nullable',
36
+ 'system.Nullable_Float',
37
+ 'system.Nullable_Bool',
38
+ 'system.CsRef',
39
+ 'system.TimeSpan',
40
+ 'system.DateTime',
41
+ ];
42
+ /** The longest function source this module canonicalizes (the helpers are a few hundred characters). */
43
+ const MAX_FN_SOURCE = 4000;
44
+ /** The reader roles a derivation must find, or it is not used. */
45
+ const REQUIRED_READER_ROLES = ['bool', 'int32', 'u8', 'string', 'float64', 'float32', 'uint16', 'raw', 'varint'];
46
+ /** The Serializer roles a derivation must find (every one the v6.07 dialect had). */
47
+ const REQUIRED_STATIC_ROLES = [
48
+ 'int32',
49
+ 'string',
50
+ 'bool',
51
+ 'u8',
52
+ 'float32',
53
+ 'float64',
54
+ 'timespan',
55
+ 'date',
56
+ 'guid',
57
+ 'uint16',
58
+ 'bytes',
59
+ 'list',
60
+ 'dict',
61
+ ];
62
+ const KEYWORDS = new Set('var let const function return if else for while do break continue new null true false this typeof instanceof in of throw try catch finally switch case default void delete'.split(' '));
63
+ const TOKEN = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[A-Za-z_$][\w$]*|\d+(?:\.\d+)?(?:[eE][-+]?\d+)?|>>>=?|===|!==|<<=|>>=|[=!<>]=|&&|\|\||\+\+|--|<<|>>|[-+*/%&|^]=|\S/g;
64
+ /**
65
+ * A function's canonical form: its tokens, with keywords, literals and punctuation kept, a member
66
+ * name that is a known reader method replaced by `@<role>`, an identifier that is a registered class
67
+ * var replaced by `@T:<type name>`, and every other name by `#<n>`, its order of first appearance.
68
+ */
69
+ export function canonicalize(src, roleOf, typeOf) {
70
+ const names = new Map();
71
+ const out = [];
72
+ let prev = '';
73
+ for (const t of src.match(TOKEN) ?? []) {
74
+ const c = t[0];
75
+ const isName = /[A-Za-z_$]/.test(c);
76
+ if (!isName || KEYWORDS.has(t))
77
+ out.push(t);
78
+ else if (prev === '.' && roleOf(t) !== undefined)
79
+ out.push(`@${roleOf(t)}`);
80
+ else if (prev !== '.' && typeOf(t) !== undefined)
81
+ out.push(`@T:${typeOf(t)}`);
82
+ else {
83
+ let n = names.get(t);
84
+ if (n === undefined) {
85
+ n = `#${names.size}`;
86
+ names.set(t, n);
87
+ }
88
+ out.push(n);
89
+ }
90
+ prev = t;
91
+ }
92
+ return out.join(' ');
93
+ }
94
+ /**
95
+ * The Serializer helpers of client v6.07.0.1 in canonical form (generated from that bundle with this
96
+ * module's own reader roles), by role. 6.08.0.1 and 6.08.0.2 give the same forms.
97
+ */
98
+ export const SERIALIZER_TEMPLATES = {
99
+ 'function ( #0 ) { return #0 . @int32 ( ) }': 'int32',
100
+ 'function ( #0 ) { return #0 . @bool ( ) ? #0 . @string ( ) : null }': 'string',
101
+ 'function ( #0 ) { return #0 . @bool ( ) }': 'bool',
102
+ 'function ( #0 ) { return #0 . @u8 ( ) }': 'u8',
103
+ 'function ( #0 ) { return #0 . @float32 ( ) }': 'float32',
104
+ 'function ( #0 ) { return #0 . @float64 ( ) }': 'float64',
105
+ 'function ( #0 ) { return #0 . @uint16 ( ) }': 'uint16',
106
+ 'function ( #0 ) { #0 = #0 . @float64 ( ) ; return - 922336666814565 >= #0 ? @T:system.TimeSpan . #1 : 922336666814565 <= #0 ? @T:system.TimeSpan . #2 : new @T:system.TimeSpan ( #0 ) }': 'timespan',
107
+ 'function ( #0 ) { var #1 = #0 . @int32 ( ) ; return - 1 == #1 ? null : #0 . @raw ( #1 ) }': 'bytes',
108
+ 'function ( #0 , #1 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #2 = [ ] , #3 = 0 ; #3 < #0 ; ) #2 . #4 ( #1 ( ) ) , ++ #3 ; return #2 }': 'list',
109
+ 'function ( #0 , #1 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #2 = [ ] , #3 = 0 ; #3 < #0 ; ) #2 [ #3 ] = #1 ( ) , ++ #3 ; return #2 }': 'list',
110
+ 'function ( #0 , #1 , #2 ) { #0 = #0 . @int32 ( ) ; if ( - 1 == #0 ) return null ; for ( var #3 = new @T:system.collections.generic.Dictionary ( #0 ) , #4 = 0 ; #4 < #0 ; ) { var #5 = #1 ( ) ; @T:warlight.shared.Assert . #6 ( ! #3 . #7 ( #5 ) , "Dupe keys deserialized" ) ; #3 . #8 ( #5 , #2 ( ) ) ; ++ #4 } return #3 }': 'dict',
111
+ };
112
+ /** The date and guid helpers call a SharedUtility reader: matched by that helper's shape (see `utilityRole`). */
113
+ const UTILITY_CALL = 'function ( #0 ) { return @T:warlight.shared.SharedUtility . #1 ( #0 ) }';
114
+ /** v6.07's `P.uL`: a list into a client collection class (`new Je`), whose type name varies. */
115
+ const COLLECTION_LIST = /^function \( #0 , #1 \) \{ #0 = #0 \. @int32 \( \) ; if \( - 1 == #0 \) return null ; for \( var #2 = new (?:#\d+|@T:[\w.$]+) , #3 = 0 ; #3 < #0 ; \) #2 \. #\d+ \( #1 \( \) \) , \+\+ #3 ; return #2 \}$/;
116
+ /** SharedUtility's ParseLongSafe and TryGetValue-or-default (`O.fA`, `O.Fy`): identity in the built-in dialect. */
117
+ const UTILITY_IDENTITY_MARK = '"ParseLongSafe(null)"';
118
+ const UTILITY_TRY_GET = /^function \( #0 , #1 , #2 \) \{ var #3 = new @T:system\.CsRef \( null \) ; return #0 \. #4 \( #1 , #3 \) \? #3 \. #5 : #2 \}$/;
119
+ /** MessagePump's identity (`za.rc`). */
120
+ const IDENTITY = 'function ( #0 ) { return #0 }';
121
+ /** Enumerable's Select and ToArray (`E.Za`, `E.Sa`). */
122
+ const SELECT = 'function ( #0 , #1 ) { for ( var #2 = [ ] , #3 = 0 ; #3 < #0 . #4 ; ) { var #5 = #0 [ #3 ] ; ++ #3 ; #2 . #6 ( #1 ( #5 ) ) } return #2 }';
123
+ const TO_ARRAY = 'function ( #0 ) { for ( var #1 = [ ] , #2 = 0 ; #2 < #0 . #3 ; ) { var #4 = #0 [ #2 ] ; ++ #2 ; #1 . #5 ( #4 ) } return #1 }';
124
+ /** The source of the function expression starting at `at`, or undefined when it does not parse or is too long. */
125
+ function functionAt(src, at) {
126
+ try {
127
+ const end = Math.min(src.length, at + MAX_FN_SOURCE);
128
+ const node = parseExpressionAt(src.slice(0, end), at, { ecmaVersion: 'latest' });
129
+ if (node.type !== 'FunctionExpression')
130
+ return undefined;
131
+ return src.slice(at, node.end);
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ const esc = (s) => s.replace(/\$/g, '\\$');
138
+ /** `cls.name=function…` statics of a class: name → source (the first definition of each name). */
139
+ function staticsOf(src, cls) {
140
+ const out = new Map();
141
+ for (const m of src.matchAll(new RegExp(`(?<![\\w$.])${esc(cls)}\\.([\\w$]+)\\s*=\\s*(?=function\\b)`, 'g'))) {
142
+ if (out.has(m[1]))
143
+ continue;
144
+ const fn = functionAt(src, m.index + m[0].length);
145
+ if (fn)
146
+ out.set(m[1], fn);
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * The function-valued properties of `cls.prototype={…}` (or `cls.prototype=Fa(base.prototype,{…})`),
152
+ * name → source. Only the first prototype assignment of the class is read.
153
+ */
154
+ function prototypeOf(src, cls) {
155
+ const out = new Map();
156
+ const m = new RegExp(`(?<![\\w$.])${esc(cls)}\\.prototype\\s*=\\s*`).exec(src);
157
+ if (!m)
158
+ return out;
159
+ let at = m.index + m[0].length;
160
+ if (src[at] !== '{') {
161
+ // `Fa(base.prototype,{` — the object literal is the second argument.
162
+ const brace = src.indexOf('{', at);
163
+ if (brace < 0 || brace - at > 200)
164
+ return out;
165
+ at = brace;
166
+ }
167
+ let obj;
168
+ try {
169
+ obj = parseExpressionAt(src, at, { ecmaVersion: 'latest' });
170
+ }
171
+ catch {
172
+ return out;
173
+ }
174
+ if (obj.type !== 'ObjectExpression')
175
+ return out;
176
+ for (const p of obj.properties ?? []) {
177
+ if (p.type !== 'Property' || p.key.type !== 'Identifier' || !p.key.name)
178
+ continue;
179
+ if (p.value.type !== 'FunctionExpression' || p.value.end - p.value.start > MAX_FN_SOURCE)
180
+ continue;
181
+ out.set(p.key.name, src.slice(p.value.start, p.value.end));
182
+ }
183
+ return out;
184
+ }
185
+ /** Classify haxe.io.Input's methods by what they do. */
186
+ function inputRoles(methods) {
187
+ const roles = new Map();
188
+ let readByte;
189
+ for (const [name, fn] of methods) {
190
+ if (/methodName\s*:\s*"readByte"/.test(fn))
191
+ readByte = name;
192
+ }
193
+ if (!readByte)
194
+ return roles;
195
+ roles.set(readByte, 'readByte');
196
+ const calls = (fn, name) => fn.split(`this.${name}(`).length - 1;
197
+ let readInt32;
198
+ for (const [name, fn] of methods) {
199
+ if (name === readByte)
200
+ continue;
201
+ const bytes = calls(fn, readByte);
202
+ if (bytes === 4 && fn.includes('<<24')) {
203
+ readInt32 = name;
204
+ roles.set(name, 'readInt32');
205
+ }
206
+ else if (bytes === 2 && fn.includes('32768'))
207
+ roles.set(name, 'readInt16');
208
+ else if (bytes === 2)
209
+ roles.set(name, 'readUInt16');
210
+ }
211
+ if (readInt32) {
212
+ for (const [name, fn] of methods) {
213
+ if (roles.has(name))
214
+ continue;
215
+ const ints = calls(fn, readInt32);
216
+ if (ints === 2)
217
+ roles.set(name, 'readDouble');
218
+ else if (ints === 1)
219
+ roles.set(name, 'readFloat');
220
+ }
221
+ }
222
+ return roles;
223
+ }
224
+ const FROM_INPUT = {
225
+ readByte: 'u8',
226
+ readInt32: 'int32',
227
+ readInt16: 'int16',
228
+ readUInt16: 'uint16',
229
+ readFloat: 'float32',
230
+ readDouble: 'float64',
231
+ };
232
+ /** Classify the BinaryReader's methods by the Input method they call, or their own shape. */
233
+ function readerRoles(methods, input) {
234
+ const roles = new Map();
235
+ for (const [name, fn] of methods) {
236
+ if (fn.includes('"Bad format"') && /&127\)<</.test(fn))
237
+ roles.set(name, 'varint');
238
+ else if (/new [\w$]+\(new ArrayBuffer\(/.test(fn))
239
+ roles.set(name, 'raw');
240
+ else if (fn.includes('4294967296'))
241
+ continue; // the int64 read: no built-in
242
+ else {
243
+ const bool = /return\s*0\s*!=\s*this\.[\w$]+\.([\w$]+)\(\)/.exec(fn);
244
+ if (bool && input.get(bool[1]) === 'readByte') {
245
+ roles.set(name, 'bool');
246
+ continue;
247
+ }
248
+ const direct = /return\s+this\.[\w$]+\.([\w$]+)\(\)/.exec(fn);
249
+ const r = direct ? input.get(direct[1]) : undefined;
250
+ if (r)
251
+ roles.set(name, FROM_INPUT[r]);
252
+ }
253
+ }
254
+ // Self calls (`bc:function(){try{return this.JIb()}…}`) and the string read (varint then raw).
255
+ for (let pass = 0; pass < 3; pass++) {
256
+ for (const [name, fn] of methods) {
257
+ if (roles.has(name))
258
+ continue;
259
+ const own = [...fn.matchAll(/this\.([\w$]+)\(/g)].map((m) => m[1]).filter((n) => methods.has(n));
260
+ const ownRoles = own.map((n) => roles.get(n));
261
+ if (ownRoles.includes('varint') && ownRoles.includes('raw'))
262
+ roles.set(name, 'string');
263
+ else if (own.length === 1 && ownRoles[0] && /^function\(\)\{try\{return this\.[\w$]+\(\)\}/.test(fn))
264
+ roles.set(name, ownRoles[0]);
265
+ }
266
+ }
267
+ return roles;
268
+ }
269
+ /** The protocol version most of the bundle's readers default to (`null==d&&(d=243)`). */
270
+ export function bundleProtocol(src) {
271
+ const counts = new Map();
272
+ for (const m of src.matchAll(/null==([a-z])&&\(\1=(\d{3})\)/g)) {
273
+ const v = Number(m[2]);
274
+ counts.set(v, (counts.get(v) ?? 0) + 1);
275
+ }
276
+ let best;
277
+ let n = 0;
278
+ for (const [v, c] of counts) {
279
+ if (c > n) {
280
+ best = v;
281
+ n = c;
282
+ }
283
+ }
284
+ return n >= 3 ? best : undefined;
285
+ }
286
+ /**
287
+ * Derive the dialect from a bundle, or `null` when any required class or role cannot be found (the
288
+ * interpreter then uses its built-in names).
289
+ */
290
+ export function deriveDialect(bundle) {
291
+ const { src, typeNameOf, varOf } = bundle;
292
+ const inputVar = varOf.get(INPUT_TYPE);
293
+ const readerVar = varOf.get(READER_TYPE);
294
+ const serializer = varOf.get(SERIALIZER_TYPE);
295
+ if (!inputVar || !readerVar || !serializer)
296
+ return null;
297
+ const input = inputRoles(prototypeOf(src, inputVar));
298
+ const reader = readerRoles(prototypeOf(src, readerVar), input);
299
+ const readerMethods = {};
300
+ for (const [n, r] of reader)
301
+ readerMethods[n] = r;
302
+ const found = new Set(reader.values());
303
+ if (!REQUIRED_READER_ROLES.every((r) => found.has(r)))
304
+ return null;
305
+ const roleOf = (n) => reader.get(n);
306
+ const typeOf = (n) => typeNameOf.get(n);
307
+ const canon = (fn) => canonicalize(fn, roleOf, typeOf);
308
+ const statics = {};
309
+ const put = (cls, name, role) => {
310
+ (statics[cls] ??= {})[name] = role;
311
+ };
312
+ // The SharedUtility date and guid readers (P.Td → O.N3c, P.tL → O.Q3c): told apart by what they read.
313
+ const utility = varOf.get(UTILITY_TYPE);
314
+ const utilityStatics = utility ? staticsOf(src, utility) : new Map();
315
+ const utilityRole = (name) => {
316
+ const fn = utilityStatics.get(name);
317
+ if (!fn)
318
+ return undefined;
319
+ // A guid is 16 raw bytes; a date is one float64.
320
+ if (/@raw \( 16 \)/.test(canon(fn)) || /\(16\)/.test(fn))
321
+ return 'guid';
322
+ if (canon(fn).includes('@float64'))
323
+ return 'date';
324
+ return undefined;
325
+ };
326
+ for (const [name, fn] of staticsOf(src, serializer)) {
327
+ const c = canon(fn);
328
+ const role = SERIALIZER_TEMPLATES[c];
329
+ if (role)
330
+ put(serializer, name, role);
331
+ else if (COLLECTION_LIST.test(c))
332
+ put(serializer, name, 'list');
333
+ else if (c === UTILITY_CALL) {
334
+ const callee = /return [\w$]+\.([\w$]+)\(/.exec(fn)?.[1];
335
+ const r = callee ? utilityRole(callee) : undefined;
336
+ if (r)
337
+ put(serializer, name, r);
338
+ }
339
+ }
340
+ const roles = new Set(Object.values(statics[serializer] ?? {}));
341
+ if (!REQUIRED_STATIC_ROLES.every((r) => roles.has(r)))
342
+ return null;
343
+ if (utility) {
344
+ for (const [name, fn] of utilityStatics) {
345
+ if (fn.includes(UTILITY_IDENTITY_MARK) || UTILITY_TRY_GET.test(canon(fn)))
346
+ put(utility, name, 'identity');
347
+ }
348
+ }
349
+ const pump = varOf.get(PUMP_TYPE);
350
+ if (pump) {
351
+ for (const [name, fn] of staticsOf(src, pump))
352
+ if (canon(fn) === IDENTITY)
353
+ put(pump, name, 'identity');
354
+ }
355
+ const enumerable = varOf.get(ENUMERABLE_TYPE);
356
+ if (enumerable) {
357
+ for (const [name, fn] of staticsOf(src, enumerable)) {
358
+ if (name === 'Range')
359
+ put(enumerable, name, 'range');
360
+ else {
361
+ const c = canon(fn);
362
+ if (c === SELECT)
363
+ put(enumerable, name, 'select');
364
+ else if (c === TO_ARRAY)
365
+ put(enumerable, name, 'toArray');
366
+ }
367
+ }
368
+ }
369
+ const wrappers = WRAPPER_TYPES.map((t) => varOf.get(t)).filter((v) => v !== undefined);
370
+ return { readerMethods, statics, wrappers, serializer, protocol: bundleProtocol(src) };
371
+ }