Repository navigation
Expand file tree
/
Copy pathuserscript.js
More file actions
3402 lines (3106 loc) · 163 KB
/
Copy pathuserscript.js
File metadata and controls
3402 lines (3106 loc) · 163 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Chess Analyzer
// @namespace http://tampermonkey.net/
// @version 3.13
// @description Chess analyzer with full Stockfish 19 NNUE, lichess (with variants) and endgame.ai support, and web-app relay
// @author Peenjeee
// @match https://www.chess.com/*
// @match https://lichess.org/*
// @match https://endgame.ai/*
// @match https://www.endgame.ai/*
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @connect localhost
// @connect chess.0xpnj.dev
// @connect cdn.jsdelivr.net
// @connect lichess.org
// ==/UserScript==
(function() {
'use strict';
const SITE = location.hostname.includes('lichess') ? 'lichess'
: location.hostname.includes('endgame') ? 'endgame'
: 'chesscom';
const EG_BOARD = '.board-container .board';
// Full-strength Stockfish 19 NNUE hosted on our own site (CORS-open).
// The loader reads its wasm location from the worker URL hash.
const REMOTE_JS = "https://chess.0xpnj.dev/stockfish-19-single.js";
const REMOTE_WASM = "https://chess.0xpnj.dev/stockfish-19-single.wasm";
// chess.com's internal engine as a fallback (chess.com pages only)
const CC_FALLBACK = "/bundles/app/js/vendor/jschessengine/stockfish.asm.1abfa10c.js";
// lichess variants run on multi-variant Stockfish 10 (GPLv3,
// github.com/lichess-org/stockfish.js): one thread and no SharedArrayBuffer,
// so it runs wherever SF19 does. Pinned on jsDelivr and checked byte for
// byte, since it runs with the page's origin.
const MV_JS = "https://cdn.jsdelivr.net/npm/stockfish.js@10.0.2/stockfish.wasm.js";
const MV_WASM = "https://cdn.jsdelivr.net/npm/stockfish.js@10.0.2/stockfish.wasm";
const MV_SHA256 = {
js: "064175042d8b72eb9fba8311b730f6f5cebcfec736494698d675dc433f3bd275",
wasm: "45816b436eb8c180acb2c5b9fda0148101f411edbfa6bf919918e0a362eafca8"
};
// Where threads are allowed (lichess game pages are cross-origin isolated)
// the variants run on the stronger Fairy-Stockfish 14 with a network per
// variant: the build lichess's own analysis uses (github.com/lichess-org/
// stockfish-web, AGPLv3; Fairy-Stockfish is GPLv3), pinned and checked the
// same way. Each network comes from lichess's asset host and is named
// after the start of its own SHA-256. Pages without threads (chess.com)
// get the same engine from the extension's offscreen document, which is
// cross-origin isolated; the userscript keeps SF10 there.
const FSF_JS = "https://cdn.jsdelivr.net/npm/@lichess-org/stockfish-web@0.5.0/fsf_14.js";
const FSF_WASM = "https://cdn.jsdelivr.net/npm/@lichess-org/stockfish-web@0.5.0/fsf_14.wasm";
const FSF_SHA256 = {
js: "d22d4e7df089b86fdcb678a795a2116d52a06e041fc91819448fc93eb3f3021f",
wasm: "e9c04dff71870770a515f1d1257aca4d7cebe2915339e9f847aebdc0c8ca74e0"
};
// lichess.org itself: lichess1.org now redirects there without the CORS
// headers a browser needs to follow it
const NNUE_URL = "https://lichess.org/assets/lifat/nnue/";
// Relay (mirrors the game to the Chess Analyzer web app via its SSE API)
const RELAY_URLS = location.hostname === 'localhost'
? ['http://localhost:5173/api/relay/']
: ['https://chess.0xpnj.dev/api/relay/'];
const RELAY_KEY = 'chessweb-relay-id';
const hasGM = typeof GM_xmlhttpRequest === 'function'
|| (typeof GM !== 'undefined' && GM && typeof GM.xmlHttpRequest === 'function');
function gmRequest(opts) {
return new Promise((resolve, reject) => {
let api = typeof GM_xmlhttpRequest === 'function' ? GM_xmlhttpRequest : GM.xmlHttpRequest;
api({
method: opts.method || 'GET',
url: opts.url,
data: opts.data,
headers: opts.headers,
responseType: opts.responseType,
onload: r => (r.status >= 200 && r.status < 300) ? resolve(r.response) : reject(new Error('HTTP ' + r.status)),
onerror: () => reject(new Error('network error')),
ontimeout: () => reject(new Error('timeout'))
});
});
}
let iv = null; // analyzer loop interval
let moves = [], ponder = "";
let currentTurn = "w";
let lastBoard = null; // board element arrows were attached to
async function fetchText(url) {
try {
let r = await fetch(url);
if (!r.ok) throw new Error('HTTP ' + r.status);
return await r.text();
} catch (e) {
if (hasGM) return gmRequest({ url });
throw e;
}
}
async function fetchBytes(url) {
try {
let r = await fetch(url);
if (!r.ok) throw new Error('HTTP ' + r.status);
return await r.arrayBuffer();
} catch (e) {
if (hasGM) return gmRequest({ url, responseType: 'arraybuffer' });
throw e;
}
}
function idbStore(mode, fn) {
return new Promise(resolve => {
try {
let open = indexedDB.open('sa-engine', 1);
open.onupgradeneeded = () => open.result.createObjectStore('files');
open.onsuccess = () => {
let tx = open.result.transaction('files', mode);
tx.onerror = () => resolve(null);
fn(tx.objectStore('files'), resolve);
};
open.onerror = () => resolve(null);
} catch (e) { resolve(null); }
});
}
let idbGet = (key) => idbStore('readonly', (st, done) => {
let g = st.get(key);
g.onsuccess = () => done(g.result || null);
g.onerror = () => done(null);
});
let idbPut = (key, buf) => idbStore('readwrite', (st, done) => {
st.put(buf, key);
st.transaction.oncomplete = () => done(true);
});
let idbDel = (key) => idbStore('readwrite', (st, done) => {
st.delete(key);
st.transaction.oncomplete = () => done(true);
});
// ------------------------------------------------------------------ board
let getVP = (b, sq) => {
let nodes = b.querySelectorAll(`.piece.${sq}`);
for (let p of nodes) {
if (p.style.display === 'none' || p.style.opacity === '0' || p.style.visibility === 'hidden') continue;
if (p.classList.contains('ghost') || p.classList.contains('hint')) continue;
return p;
}
return null;
};
function readBoardCC() {
let b = document.querySelector(".board-layout-main wc-chess-board") || document.querySelector("wc-chess-board");
if (!b) return null;
let f = "";
let lastMovedColor = null;
let highlightCount = b.querySelectorAll('.highlight').length;
let pieceMap = {};
for (let p of b.querySelectorAll('.piece')) {
if (p.style.display === 'none' || p.style.opacity === '0' || p.style.visibility === 'hidden') continue;
if (p.classList.contains('ghost') || p.classList.contains('hint')) continue;
let mSq = p.className.match(/\bsquare-(\d\d)\b/);
if (mSq) pieceMap[mSq[1]] = p;
}
for (let i = 8; i >= 1; i--) {
for (let j = 1; j <= 8; j++) {
if (j === 1 && i !== 8) f += "/";
let sqClass = `${j}${i}`;
let pNode = pieceMap[sqClass];
let m = pNode ? pNode.className.match(/\b([bw])([pbnrqk])\b/) : null;
f += m ? (m[1] === 'w' ? m[2].toUpperCase() : m[2]) : "1";
if (highlightCount === 2 && m && b.querySelector(`.highlight.square-${sqClass}`)) {
lastMovedColor = m[1];
}
}
}
if (!Object.keys(pieceMap).length) return null;
if (lastMovedColor === 'w') currentTurn = 'b';
else if (lastMovedColor === 'b') currentTurn = 'w';
else if (highlightCount === 0) currentTurn = 'w';
let castling = "";
let hp = (c, sq) => { let p = getVP(b, sq); return p && p.className.includes(c); };
if (hp('wk', 'square-51')) {
if (hp('wr', 'square-81')) castling += "K";
if (hp('wr', 'square-11')) castling += "Q";
}
if (hp('bk', 'square-58')) {
if (hp('br', 'square-88')) castling += "k";
if (hp('br', 'square-18')) castling += "q";
}
return {
board: b,
flipped: b.classList.contains("flipped"),
fen: f.replace(/1+/g, m => m.length) + " " + currentTurn + " " + (castling || "-") + " - 0 1"
};
}
// lichess variants by the key in the game's `variant-*` class. `uci` is the
// engine's name for it and `nnue` Fairy-Stockfish's network for it; the
// rest is what playableFen accepts: kings per
// side (null: any number), what a king in check means (royal: it is that
// side's turn; atomic: the same unless the kings touch; never: the board
// was misread; none: kings are ordinary pieces), and whether castling and
// white pawns on rank 1 occur. Other keys (chess960, fromPosition) stay standard.
const STANDARD = { uci: 'chess', kings: [1, 1], check: 'royal', castling: true, firstRankPawns: false };
const LI_VARIANTS = {
kingOfTheHill: { ...STANDARD, uci: 'kingofthehill', nnue: 'kingofthehill-978b86d0e6a4' },
threeCheck: { ...STANDARD, uci: '3check', nnue: '3check-cb5f517c228b' },
crazyhouse: { ...STANDARD, uci: 'crazyhouse', nnue: 'crazyhouse-8ebf84784ad2' },
atomic: { ...STANDARD, uci: 'atomic', nnue: 'atomic-2cf13ff256cc', check: 'atomic' },
horde: { ...STANDARD, uci: 'horde', nnue: 'horde-28173ddccabe', kings: [0, 1], firstRankPawns: true },
racingKings: { ...STANDARD, uci: 'racingkings', nnue: 'racingkings-636b95f085e3', check: 'never', castling: false },
antichess: { ...STANDARD, uci: 'antichess', nnue: 'antichess-dd3cbe53cd4e', kings: null, check: 'none', castling: false }
};
function readBoardLI() {
let b = document.querySelector('cg-board');
if (!b) return null;
let host = b.closest('.round__app, main.analyse');
let rules = LI_VARIANTS[host?.className.match(/\bvariant-(\w+)/)?.[1]] || STANDARD;
let wrap = b.closest('.cg-wrap') || document.querySelector('.cg-wrap');
let flipped = !!wrap && wrap.classList.contains('orientation-black');
let size = b.getBoundingClientRect().width / 8;
if (!size) return null;
// Drag state is temporary; while a piece is in flight, lichess board
// transforms do not reflect the settled position yet.
if (b.querySelector('piece.ghost') ||
b.querySelector('piece.dragging') ||
b.querySelector('piece.anim')) return null;
const TYPES = { pawn: 'p', knight: 'n', bishop: 'b', rook: 'r', queen: 'q', king: 'k' };
let sqOf = (el) => {
let m = (el.style.transform || '').match(/translate\((-?[\d.]+)px(?:,\s*(-?[\d.]+)px)?\)/);
if (!m) return null;
let col = Math.round(parseFloat(m[1]) / size), row = Math.round(parseFloat(m[2] || '0') / size);
if (col < 0 || col > 7 || row < 0 || row > 7) return null;
return flipped ? { f: 8 - col, r: row + 1 } : { f: col + 1, r: 8 - row };
};
let lastSquares = [];
b.querySelectorAll('square.last-move').forEach(sq => {
// chessground hides squares it no longer needs instead of removing them,
// and a hidden one keeps the classes of an older move or selection
if (sq.style.display === 'none') return;
let s = sqOf(sq);
if (s) lastSquares.push(s);
});
let grid = {};
let lastColor = null;
b.querySelectorAll('piece').forEach(p => {
if (p.classList.contains('ghost')) return;
let s = sqOf(p);
if (!s) return;
let color = p.classList.contains('white') ? 'w' : p.classList.contains('black') ? 'b' : null;
let type = null;
for (let k in TYPES) if (p.classList.contains(k)) { type = TYPES[k]; break; }
if (!color || !type) return;
grid[s.f + ',' + s.r] = color + type;
if (lastSquares.some(q => q.f === s.f && q.r === s.r)) lastColor = color;
});
if (Object.keys(grid).length < 2) return null;
if (lastColor === 'w') currentTurn = 'b';
else if (lastColor === 'b') currentTurn = 'w';
else {
const isPuzzle = /^\/(training|streak|storm|racer)\b/.test(location.pathname) || !!document.querySelector('main.puzzle, .puzzle__board, [class*="puzzle"], .streak, .storm, .racer');
if (isPuzzle && wrap) {
currentTurn = flipped ? 'b' : 'w';
} else {
let active = host?.querySelector('move.active');
let clock = document.querySelector('.rclock.running');
if (active) currentTurn = (active.getAttribute('p') || '').length / 2 % 2 ? 'b' : 'w';
else if (clock?.classList.contains('rclock-white')) currentTurn = 'w';
else if (clock?.classList.contains('rclock-black')) currentTurn = 'b';
else if (!lastSquares.length) currentTurn = 'w';
}
}
let f = "";
for (let r = 8; r >= 1; r--) {
if (r < 8) f += "/";
for (let c = 1; c <= 8; c++) {
let pc = grid[c + ',' + r];
f += pc ? (pc[0] === 'w' ? pc[1].toUpperCase() : pc[1]) : "1";
}
}
let castling = "";
if (rules.castling && grid['5,1'] === 'wk') {
if (grid['8,1'] === 'wr') castling += "K";
if (grid['1,1'] === 'wr') castling += "Q";
}
if (rules.castling && grid['5,8'] === 'bk') {
if (grid['8,8'] === 'br') castling += "k";
if (grid['1,8'] === 'br') castling += "q";
}
// Crazyhouse pockets sit beside the board: one piece per role, its count in data-nb
let pocket = "";
if (rules.uci === 'crazyhouse') {
host.querySelectorAll('.pocket piece').forEach(p => {
let type = Object.keys(TYPES).find(k => p.classList.contains(k));
if (!type) return;
let letter = p.classList.contains('white') ? TYPES[type].toUpperCase() : TYPES[type];
pocket += letter.repeat(+p.dataset.nb || 0);
});
pocket = "[" + pocket + "]";
}
// Three-check: each check given shows as a king icon in the giver's
// material bar; the engine wants the checks each side has left
let checks = "";
if (rules.uci === '3check') {
let given = side => host.querySelectorAll(`.material-${side} mpiece.king`).length;
let [byWhite, byBlack] = flipped ? [given('top'), given('bottom')] : [given('bottom'), given('top')];
checks = Math.max(0, 3 - byWhite) + "+" + Math.max(0, 3 - byBlack) + " ";
}
return {
board: b,
flipped,
rules,
fen: f.replace(/1+/g, m => m.length) + pocket + " " + currentTurn + " " + (castling || "-") + " - " + checks + "0 1"
};
}
// chess.com's variants server, by the slug in /variants/<slug>/game/<id>.
// The lichess ones keep lichess's rules; the rest match Fairy-Stockfish's
// variant of that name, with the Fairy-Stockfish project's own network where
// one exists (Paradigm has none). On top of the keys above: pieces maps the server's
// own piece names to FEN letters, walls turns its stones (colour 7) into
// walls, and setup waits until the setup drops are over. No Castling and
// Setup Chess are standard chess for SF19 once the board is read, and so is
// Chess960, whose castling rights come from its start position. Any other
// slug, custom rules and four-player boards included, is not supported.
const CC_VARIANTS = {
'chess960': { ...STANDARD, castling: false },
'crazyhouse': LI_VARIANTS.crazyhouse,
'3-check': LI_VARIANTS.threeCheck,
'king-of-the-hill': LI_VARIANTS.kingOfTheHill,
'atomic': LI_VARIANTS.atomic,
'giveaway': LI_VARIANTS.antichess,
'horde': LI_VARIANTS.horde,
'racing-kings': LI_VARIANTS.racingKings,
'no-castling': { ...STANDARD, castling: false },
'setup-chess': { ...STANDARD, castling: false, setup: true },
'torpedo': { ...STANDARD, uci: 'torpedo', nnue: 'torpedo-25da2c94c6cb' },
'sideways-pawns': { ...STANDARD, uci: 'pawnsideways', nnue: 'pawnsideways-68b37e5c25b0' },
// kings cannot capture there, so kings that touch give no check (as in atomic)
'petrified': { ...STANDARD, uci: 'petrified', nnue: 'petrified-fa7e5810f172', walls: true, check: 'atomic' },
'paradigm-chess30': { ...STANDARD, uci: 'paradigm', pieces: { 'Δ': 'b' } },
// the server draws a piece under its display name when it has one, else its letter
'seirawan-chess': { ...STANDARD, uci: 'seirawan', nnue: 'seirawan-432c65fe71fc', pieces: { hawk: 'h', H: 'h', seirawanElephant: 'e', E: 'e' } },
// its ferz and elephant are not the queen and bishop the check test knows
'chaturanga': { ...STANDARD, uci: 'chaturanga', nnue: 'chaturanga-1889e98f8d54', pieces: { chariot: 'r', elephant: 'b', I: 'b', F: 'q' }, check: 'none', castling: false },
// kings are captured, not mated, so a king may stand attacked
'duck-chess': { ...STANDARD, uci: 'duck', nnue: 'duck-ba21f91f5d81', check: 'none' }
};
// SF10 is lichess's build, so it plays the lichess variants; the others need Fairy-Stockfish
let sf10Plays = variant => Object.values(LI_VARIANTS).some(v => v.uci === variant);
// Seirawan: a piece still on its back-rank start square may bring a banked
// piece in on its first move. The castling letters stand for the king and
// rooks; the files of the other pieces are added while the bank holds any.
function seirawanRights(grid, castling, bank) {
let side = (color, rank, rights) => {
if (!bank[color]) return rights;
for (let [file, type] of [[2, 'n'], [3, 'b'], [4, 'q'], [6, 'b'], [7, 'n']]) {
if (grid[file + ',' + rank] === color + type) rights += String.fromCharCode((color === 'w' ? 64 : 96) + file);
}
return rights;
};
return side('w', 1, castling.replace(/[kq]/g, '')) + side('b', 8, castling.replace(/[KQ]/g, ''));
}
// The moves played so far, as SAN, from the variants server's move list.
// A duck chess turn shows where the duck went after its move ("Nf6 Θf1").
function movesCV() {
let list = document.querySelector('[class*=moves-list]')?.parentElement;
if (!list) return [];
return [...list.querySelectorAll('span')]
.filter(s => !s.children.length)
.map(s => s.textContent.trim().replace(/ Θ[a-h][1-8]$/, ''))
.filter(t => /^(@?[NBRQKP]?[a-h]?[1-8]?x?[a-h][1-8](=[NBRQ])?|O-O(-O)?)[+#]?$/.test(t));
}
// the duck chess turn last read: move count and side, duck square, placement
let duckTurn = { key: '', duckAt: -1, placement: '' };
// The variants server draws its own board: pieces are divs with data-piece
// and data-color (5 White, 6 Black, 7 stone) placed by transform in square
// units, and each banked piece is one more div off the board's edge.
function readBoardCV(relay = false) {
let b = document.querySelector('.TheBoard-layers');
let slug = location.pathname.match(/^\/variants\/([^/]+)/)?.[1] || '';
let rules = CC_VARIANTS[slug];
let idle = note => ({ board: b, flipped: false, fen: '', note });
if (!rules) return idle("Variant not supported: " + (slug || 'this board'));
if (!relay && rules.uci !== 'chess' && !sf10Plays(rules.uci) && !fsfUsable()) {
return idle((inExtension() ? "Variant engine unavailable: " : "Variant needs the extension: ") + slug);
}
let size = b.getBoundingClientRect().width / 8;
if (!size) return null;
// the bottom player box is player 0 (White) or 2 (Black)
let flipped = document.querySelector('.playerbox-bottom [data-player]')?.dataset.player === '2';
let sans = movesCV();
// Setup Chess opens with drops until both sides have spent their points
if (rules.setup && !/^[^@]/.test(sans[sans.length - 1] || '')) return idle("Waiting for the setup");
let grid = {}, pocket = { w: '', b: '' };
for (let p of b.querySelectorAll('.TheBoard-pieces .piece')) {
let m = (p.style.transform || '').match(/translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)/);
let name = p.dataset.piece || '';
// the duck (Θ, colour 7 like a stone) blocks a square the way a wall does
let type = name === 'Θ' ? '*' : rules.pieces?.[name] || (/^[PNBRQK]$/.test(name) ? name.toLowerCase() : null);
let color = type === '*' ? '*' : { 5: 'w', 6: 'b', 7: rules.walls ? '*' : null }[p.dataset.color];
if (!m || !color || !type) continue;
let col = Math.round(+m[1] / size), row = Math.round(+m[2] / size);
if (color !== '*' && (col < 0 || col > 7)) { pocket[color] += type; continue; }
if (row < 0 || row > 7 || col < 0 || col > 7) continue;
grid[(flipped ? 8 - col : col + 1) + ',' + (flipped ? row + 1 : 8 - row)] = color === '*' ? '*' : color + type;
}
if (Object.keys(grid).length < 2) return null;
// The side to move has the bright clock; when neither runs, the number
// of moves played says whose turn it is
let running = [...document.querySelectorAll('.playerbox-component')]
.find(x => /brightness\(100%\)/.test(x.querySelector('.clock-component')?.getAttribute('style') || ''));
let player = running?.querySelector('[data-player]')?.dataset.player;
let turn = player === '0' ? 'w' : player === '2' ? 'b' : sans.length % 2 ? 'b' : 'w';
let f = "";
for (let r = 8; r >= 1; r--) {
if (r < 8) f += "/";
for (let c = 1; c <= 8; c++) {
let pc = grid[c + ',' + r];
f += !pc ? "1" : pc === '*' ? '*' : pc[0] === 'w' ? pc[1].toUpperCase() : pc[1];
}
}
// A duck chess turn is a move and then the duck. In between, the board
// shows the move while the turn and the move list stand still; that is
// no position, so the turn's arrows stay up until the duck is down. A
// move that ends a turn always moves the duck.
if (rules.uci === 'duck') {
let key = sans.length + turn, duckAt = f.indexOf('*');
if (duckTurn.key === key && duckTurn.duckAt === duckAt && duckTurn.placement !== f) return null;
duckTurn = { key, duckAt, placement: f };
}
let castling = "";
if (rules.castling && grid['5,1'] === 'wk') {
if (grid['8,1'] === 'wr') castling += "K";
if (grid['1,1'] === 'wr') castling += "Q";
}
if (rules.castling && grid['5,8'] === 'bk') {
if (grid['8,8'] === 'br') castling += "k";
if (grid['1,8'] === 'br') castling += "q";
}
let banked = rules.uci === 'crazyhouse' || rules.uci === 'seirawan';
let banks = banked ? "[" + pocket.w.toUpperCase() + pocket.b + "]" : "";
if (rules.uci === 'seirawan') castling = seirawanRights(grid, castling, pocket);
// three-check: the checks each side has left, from the "+" moves in the list
let checks = "";
if (rules.uci === '3check') {
let given = side => sans.filter((s, i) => i % 2 === side && /[+#]$/.test(s)).length;
checks = Math.max(0, 3 - given(0)) + "+" + Math.max(0, 3 - given(1)) + " ";
}
return {
board: b,
flipped,
rules,
fen: f.replace(/1+/g, m => m.length) + banks + " " + turn + " " + (castling || "-") + " - " + checks + "0 1"
};
}
// Toast notification for in-game tactical alerts
function showToast(msg, bg = '#1e1b4b', border = '#6366f1', duration = 4000) {
let el = document.getElementById('sa-toast');
if (!el) {
document.body.insertAdjacentHTML('beforeend', `<div id="sa-toast" style="position:fixed;top:18px;left:50%;transform:translateX(-50%);z-index:999999;padding:10px 18px;border-radius:8px;font:600 13px system-ui,-apple-system,sans-serif;color:#fff;box-shadow:0 8px 24px rgba(0,0,0,0.5);display:none;align-items:center;gap:8px;pointer-events:none;transition:opacity 0.2s ease;"></div>`);
el = document.getElementById('sa-toast');
}
el.innerHTML = msg;
el.style.background = bg;
el.style.border = `1px solid ${border}`;
el.style.display = 'flex';
el.style.opacity = '1';
clearTimeout(el._t);
el._t = setTimeout(() => {
el.style.opacity = '0';
setTimeout(() => { el.style.display = 'none'; }, 200);
}, duration);
}
// Secret Queen: square of hidden queen from endgame.ai's game API.
// Opponent stays hidden until revealed (server-side zero knowledge).
// `revealed` array and DOM badges track both sides once revealed.
let lastEGGrid = null, lastEGFlipped = false;
// `secret` stays null until the API says whether this game is Secret Queen;
// the overlay and alerts only show once it has said yes
const SECRET_RETRY_MS = 5000;
function newSecretState(gameId) {
return { gameId, boardKey: '', ownSquare: null, revealed: [], inFlight: false, secret: null, start960: null, retryAt: 0, spectating: false, lastOppPawns: null, queenCapturedNotified: false, oppQueenFound: null };
}
let egSecret = newSecretState('');
function extractSecretQueensFromFen(fen) {
if (!fen) return { white: null, black: null };
let ranks = fen.split(' ')[0].split('/');
if (ranks.length !== 8) return { white: null, black: null };
let board = {};
for (let rIdx = 0; rIdx < 8; rIdx++) {
let rankNum = 8 - rIdx;
let colIdx = 1;
for (let ch of ranks[rIdx]) {
if (/\d/.test(ch)) {
colIdx += parseInt(ch, 10);
} else {
let sq = String.fromCharCode(colIdx + 96) + rankNum;
board[sq] = ch;
colIdx++;
}
}
}
let whiteSQ = Object.keys(board).find(sq => board[sq] === 'Q' && sq !== 'd1') || null;
let blackSQ = Object.keys(board).find(sq => board[sq] === 'q' && sq !== 'd8') || null;
return { white: whiteSQ, black: blackSQ };
}
function applySecretQueenLeak(oppSQ, oppColor, sourceTag = 'WSS MOVE') {
if (egSecret.secret !== true || !oppSQ || egSecret.oppQueenFound === oppSQ) return;
egSecret.oppQueenFound = oppSQ;
showToast(`🎯 <b>SECRET QUEEN LAWAN: ${oppSQ.toUpperCase()}!</b> (${sourceTag})`, '#581c87', '#c084fc', 12000);
if (!egSecret.revealed.some(r => r.square === oppSQ)) {
egSecret.revealed.push({ color: oppColor, square: oppSQ });
}
if (lastEGGrid) {
let k = ('abcdefgh'.indexOf(oppSQ[0]) + 1) + ',' + oppSQ[1];
if (lastEGGrid[k]) {
lastEGGrid[k] = lastEGGrid[k][0] + 'q';
}
}
let cell = document.querySelector(`.cell#${oppSQ}`);
if (cell) {
cell.style.boxShadow = 'inset 0 0 0 3px #c084fc, 0 0 15px rgba(192, 132, 252, 0.8)';
}
render(lastEGFlipped);
}
function pollEnemySecretQueen(state) {
if (state.secret !== true || !state.gameId || state.oppQueenFound || state.pollingOpp) return;
state.pollingOpp = true;
fetch('/api/games/' + encodeURIComponent(state.gameId), { cache: 'no-store' })
.then(r => r.ok ? r.json() : null)
.then(g => {
if (g && Array.isArray(g.moves) && g.moves.length > 0) {
let oppColor = lastEGFlipped ? 'w' : 'b';
// 1. Scan from moves backwards for any queen moves from pawn starting squares
for (let i = g.moves.length - 1; i >= 0; i--) {
let mStr = g.moves[i];
let mPiece = (mStr.match(/[?&]p=([^&\s]+)/) || [])[1];
let mFrom = (mStr.match(/[?&]cf=([^&\s]+)/) || [])[1];
let mFen = (mStr.match(/[?&]fen=([^&\s]+)/) || [])[1];
// Direct queen move by opponent piece
if (mPiece === 'q' + oppColor && mFrom) {
applySecretQueenLeak(mFrom, oppColor, 'OPPONENT QUEEN MOVE');
return;
}
// Check FEN for any unmasked queen
if (mFen) {
let sqs = extractSecretQueensFromFen(decodeURIComponent(mFen));
let oppSQ = oppColor === 'w' ? sqs.white : sqs.black;
if (oppSQ) {
applySecretQueenLeak(oppSQ, oppColor, 'GAME FEN LEAK');
return;
}
}
}
}
})
.catch(() => {})
.finally(() => { state.pollingOpp = false; });
}
// Endgame.ai WebSocket (SignalR) real-time sniffer & hook
if (SITE === 'endgame') {
try {
let hookScript = document.createElement('script');
hookScript.textContent = `(${function() {
if (window.__saWSHooked) return;
window.__saWSHooked = true;
const OrigWS = window.WebSocket;
const WSProxy = new Proxy(OrigWS, {
construct(target, args) {
const ws = Reflect.construct(target, args);
const url = args[0];
if (typeof url === 'string' && url.includes('gamehub')) {
console.log('%c[SA-WSS] Connected to gamehub:', 'color:#3b82f6;font-weight:bold;', url);
window.__saActiveGameHubWS = ws;
const origSend = ws.send;
ws.send = function(data) {
try {
if (typeof data === 'string') {
let frames = data.split('\x1e').filter(Boolean);
for (let frame of frames) {
let json = JSON.parse(frame);
if (json.target && (json.target.toLowerCase().includes('move') || json.target.toLowerCase().includes('play'))) {
window.__saLastMoveTarget = json.target;
console.log('%c[SA-WSS DETECTED MOVE METHOD]', 'color:#38bdf8;font-weight:bold;', json.target, json.arguments);
}
}
}
} catch(e) {}
return origSend.apply(this, arguments);
};
window.addEventListener('sa-endgame-ws-send', (e) => {
try {
const { from, to, promo } = e.detail || {};
if (!from || !to) return;
if (ws.readyState !== 1) return;
const target = window.__saLastMoveTarget || 'Move';
const moveUci = from + to + (promo ? promo.toLowerCase() : '');
const payload = JSON.stringify({
type: 1,
target: target,
arguments: [moveUci]
}) + '\x1e';
console.log('%c[SA-WSS DISPATCHING DIRECT MOVE]', 'color:#10b981;font-weight:bold;', payload);
ws.send(payload);
} catch(err) {
console.error('[SA-WSS] Move dispatch error:', err);
}
});
ws.addEventListener('message', (e) => {
if (typeof e.data === 'string') {
let frames = e.data.split('\x1e').filter(Boolean);
for (let frame of frames) {
try {
let json = JSON.parse(frame);
let str = JSON.stringify(json);
console.log('%c[SA-WSS FRAME]', 'color:#94a3b8;', json.target || json.type, json);
if (json.target === 'secretQueenRevealed' || json.target === 'secretQueenSelected' || str.includes('secretQueen') || str.includes('SecretQueen')) {
console.log('%c[SA-WSS SECRET QUEEN DATA]', 'color:#ef4444;font-weight:bold;font-size:13px;', json);
window.dispatchEvent(new CustomEvent('sa-wss-reveal', { detail: json }));
} else if (json.target === 'moved') {
console.log('%c[SA-WSS MOVE]', 'color:#10b981;', json.arguments?.[0]);
window.dispatchEvent(new CustomEvent('sa-wss-move', { detail: json.arguments?.[0] }));
}
} catch {
if (frame.includes('secretqueen') || frame.includes('SecretQueen')) {
console.log('%c[SA-WSS RAW]', 'color:#f59e0b;font-weight:bold;', frame);
}
}
}
}
});
}
return ws;
}
});
window.WebSocket = WSProxy;
}})();`;
(document.head || document.documentElement).appendChild(hookScript);
hookScript.remove();
} catch (e) {}
window.addEventListener('sa-wss-reveal', (e) => {
if (egSecret.secret !== true) return;
let data = e.detail;
if (data?.target === 'secretQueenRevealed') {
let arg = data.arguments?.[0];
if (arg?.square) {
let col = arg.color;
let sq = arg.square;
applySecretQueenLeak(sq, col, 'WSS REVEAL EVENT');
}
} else if (data?.target === 'secretQueenSelected') {
let sq = typeof data.arguments?.[0] === 'string' ? data.arguments[0] : data.arguments?.[0]?.square;
let col = data.arguments?.[0]?.color;
let oppColor = lastEGFlipped ? 'w' : 'b';
if (sq && /^[a-h][1-8]$/.test(sq)) {
if (col === oppColor || (egSecret.ownSquare && egSecret.ownSquare !== sq)) {
applySecretQueenLeak(sq, oppColor, 'WSS SELECTION EVENT');
} else {
egSecret.ownSquare = sq;
}
}
}
});
window.addEventListener('sa-wss-move', (e) => {
if (egSecret.secret !== true) return;
let moveStr = e.detail;
if (typeof moveStr !== 'string') return;
// Check if server rejected a move with secretqueen-revealed error
if (moveStr.startsWith('error:secretqueen-revealed')) {
let parts = moveStr.split(':');
let col = parts[2] || null;
let sq = parts[3] || null;
if (sq) {
applySecretQueenLeak(sq, col, 'WSS ERROR REVEAL');
return;
}
}
let mFen = (moveStr.match(/[?&]fen=([^&\s]+)/) || [])[1];
if (!mFen) return;
let sqs = extractSecretQueensFromFen(decodeURIComponent(mFen));
let oppColor = lastEGFlipped ? 'w' : 'b';
let oppSQ = oppColor === 'w' ? sqs.white : sqs.black;
if (oppSQ) {
applySecretQueenLeak(oppSQ, oppColor, 'WSS MOVE FEN');
}
});
}
function checkRevealedCaptures(revealed) {
if (!Array.isArray(revealed) || egSecret.queenCapturedNotified) return;
let oppColor = lastEGFlipped ? 'w' : 'b';
let opp = revealed.find(r => r.color === oppColor);
if (!opp || !opp.square) return;
if (lastEGGrid) {
let key = ('abcdefgh'.indexOf(opp.square[0]) + 1) + ',' + opp.square[1];
let hasQueen = Object.values(lastEGGrid).includes(oppColor + 'q');
let hasPawnAtStart = lastEGGrid[key] === oppColor + 'p';
if (!hasQueen && !hasPawnAtStart) {
egSecret.queenCapturedNotified = true;
showToast(`👑 <b>SECRET QUEEN LAWAN TERMAKAN!</b><br>Pion dari petak <b>${opp.square.toUpperCase()}</b> yang kamu makan adalah Secret Queen lawan!`, '#450a0a', '#ef4444', 9000);
} else if (opp.revealedAtMoveNumber !== null) {
showToast(`⚡ <b>SECRET QUEEN LAWAN TERUNGKAP!</b><br>Lawan menggerakkan Secret Queen dari <b>${opp.square.toUpperCase()}</b>!`, '#312e81', '#6366f1', 6000);
}
}
}
function checkSecretQueenCaptures(grid, oppColor) {
if (!grid || egSecret.secret !== true) return;
let currentOppPawns = Object.keys(grid).filter(k => grid[k] === oppColor + 'p');
if (egSecret.lastOppPawns === null) {
egSecret.lastOppPawns = currentOppPawns.length;
return;
}
if (currentOppPawns.length < egSecret.lastOppPawns) {
egSecret.lastOppPawns = currentOppPawns.length;
showToast(`⚠️ Pion lawan termakan! (Sisa ${currentOppPawns.length} calon Secret Queen)`, '#1e1b4b', '#6366f1', 3500);
if (Array.isArray(egSecret.revealed)) {
checkRevealedCaptures(egSecret.revealed);
}
}
}
// endgame.ai authenticates its API with a Bearer token kept in web storage,
// not a cookie. It is only ever sent back to endgame.ai's own API here —
// never logged and never part of the relay.
function egAccessToken() {
try {
let raw = sessionStorage.getItem('session_key') || localStorage.getItem('session_key');
let session = raw ? JSON.parse(raw) : null;
return typeof session?.access_token === 'string' ? session.access_token : null;
} catch (e) {
return null;
}
}
// The public game endpoint names the variant, and a Chess960 game's start
// position, for anyone: players, spectators and logged-out visitors.
// null: no answer yet, ask again later
function fetchEGGame(gameId) {
return fetch('/api/games/' + encodeURIComponent(gameId), { headers: { 'Accept': 'application/json' } })
.then(r => {
if (r.status === 404) return {};
return r.ok ? r.json().then(g => g || {}) : null;
});
}
// Once per game. A failed lookup is retried after a few seconds rather
// than on the next move: a finished game's board never moves.
function lookUpVariant(state) {
if (Date.now() < state.retryAt) return;
state.inFlight = true;
state.retryAt = Date.now() + SECRET_RETRY_MS;
fetchEGGame(state.gameId)
.then(g => {
if (!g || egSecret !== state) return;
state.secret = g.variant === 'SecretQueen';
state.start960 = g.variant === 'Chess960' && typeof g.startingFen === 'string' ? g.startingFen : null;
// Check if public moves array leaks secret queens
if (state.secret && Array.isArray(g.moves) && g.moves.length > 0) {
for (let mStr of g.moves) {
let mFen = (mStr.match(/[?&]fen=([^&\s]+)/) || [])[1];
if (mFen) {
let sqs = extractSecretQueensFromFen(decodeURIComponent(mFen));
let oppColor = lastEGFlipped ? 'w' : 'b';
let oppSQ = oppColor === 'w' ? sqs.white : sqs.black;
if (oppSQ) {
applySecretQueenLeak(oppSQ, oppColor, 'GAME MOVE FEN');
}
}
}
}
// overlay held back until now, board may not move again soon
if (state.secret) render(lastEGFlipped);
})
.catch(() => {})
.finally(() => { state.inFlight = false; });
}
// Your own hidden queen's square needs your login. One lookup per board
// change, whatever the answer: the square only moves when your pawn does,
// and the site refreshes an expired token (401) before the next move.
function lookUpOwnSquare(state, boardKey) {
if (!state.oppQueenFound) {
fetchEGGame(state.gameId).then(g => {
if (g && Array.isArray(g.moves) && g.moves.length > 0) {
let mFen = (g.moves[0].match(/[?&]fen=([^&\s]+)/) || [])[1];
if (mFen) {
let sqs = extractSecretQueensFromFen(decodeURIComponent(mFen));
let oppColor = lastEGFlipped ? 'w' : 'b';
let oppSQ = oppColor === 'w' ? sqs.white : sqs.black;
if (oppSQ) {
applySecretQueenLeak(oppSQ, oppColor, 'MOVE 1 FEN');
}
}
}
}).catch(() => {});
}
let token = egAccessToken();
state.inFlight = true;
state.boardKey = boardKey;
let headers = { 'x-eg-platform': 'web' };
if (token) headers['Authorization'] = 'Bearer ' + token;
fetch('/api/games/' + encodeURIComponent(state.gameId) + '/secret-queen', { headers })
.then(r => {
if (r.status === 404) return { spectating: true };
return r.ok ? r.json() : null;
})
.then(data => {
if (!data || egSecret !== state) return;
if (data.spectating) {
// not your game: no hidden square of yours to ask about
state.spectating = true;
return;
}
state.ownSquare = !data.ownRevealed && /^[a-h][1-8]$/.test(data.ownSquare || '')
? data.ownSquare
: null;
state.revealed = Array.isArray(data.revealed) ? data.revealed : [];
checkRevealedCaptures(state.revealed);
})
.catch(() => {})
.finally(() => { state.inFlight = false; });
}
function refreshOwnSecretQueen(boardKey) {
let gameId = location.pathname.match(/^\/game\/([\w-]+)/)?.[1] || '';
// new game, or board not on a game page: forget old game
if (egSecret.gameId !== gameId) egSecret = newSecretState(gameId);
if (!gameId) return;
// Poll enemy secret queen continuously on board changes until found (only if variant is SecretQueen)
if (egSecret.secret === true && !egSecret.oppQueenFound) {
pollEnemySecretQueen(egSecret);
}
if (egSecret.inFlight) return;
if (egSecret.secret === null) lookUpVariant(egSecret);
else if (egSecret.secret && !egSecret.spectating && egSecret.boardKey !== boardKey) lookUpOwnSquare(egSecret, boardKey);
}
// Other boards (home preview, a previous game) can stay mounted, so pick
// the largest one that has rendered its cells.
function findBoardEG() {
let best = null, bestArea = 0;
for (let b of document.querySelectorAll(EG_BOARD)) {
if (!b.querySelector('.cell#a1')) continue;
let r = b.getBoundingClientRect();
if (r.width * r.height > bestArea) { best = b; bestArea = r.width * r.height; }
}
return best;
}
function readBoardEG() {
let b = findBoardEG();
if (!b) return null;
let a1 = b.querySelector('.cell#a1'), h8 = b.querySelector('.cell#h8');
if (!a1 || !h8) return null;
// Flipping reverses the cell order, so a1 ends up above h8.
let flipped = a1.getBoundingClientRect().top < h8.getBoundingClientRect().top;
let grid = {};
let lastColor = null;
b.querySelectorAll('.cell').forEach(cell => {
let sq = cell.id.match(/^([a-h])([1-8])$/);
let p = cell.querySelector('.piece');
if (!sq || !p) return;
let m = p.className.match(/\bpiece\s+([pnbrqk])([wb])\b/);
if (!m) return;
let type = (egSecret.secret === true && cell.querySelector('.secret-queen-badge')) ? 'q' : m[1];
grid[('abcdefgh'.indexOf(sq[1]) + 1) + ',' + sq[2]] = m[2] + type;
if (cell.classList.contains('lastMove')) lastColor = m[2];
});
// A half-rendered board without both kings will crash the engine.
let pieces = Object.values(grid);
if (pieces.filter(p => p === 'wk').length !== 1 || pieces.filter(p => p === 'bk').length !== 1) return null;
refreshOwnSecretQueen(Object.entries(grid).sort().join(';'));
if (egSecret.secret === true) {
let own = egSecret.ownSquare;
if (own) {
let key = ('abcdefgh'.indexOf(own[0]) + 1) + ',' + own[1];
if (grid[key] && grid[key][1] === 'p') grid[key] = grid[key][0] + 'q';
}
if (egSecret.oppQueenFound) {
let oppSQ = egSecret.oppQueenFound;
let oppColor = flipped ? 'w' : 'b';
let key = ('abcdefgh'.indexOf(oppSQ[0]) + 1) + ',' + oppSQ[1];
if (grid[key] && grid[key][1] === 'p') {
grid[key] = oppColor + 'q';
}
}
if (Array.isArray(egSecret.revealed)) {
egSecret.revealed.forEach(r => {
if (r?.square && /^[a-h][1-8]$/.test(r.square)) {
let key = ('abcdefgh'.indexOf(r.square[0]) + 1) + ',' + r.square[1];
if (grid[key] && grid[key][1] === 'p' && (!r.color || grid[key][0] === r.color)) {
grid[key] = grid[key][0] + 'q';
}
}
});
}
checkSecretQueenCaptures(grid, flipped ? 'w' : 'b');
}
let lastMoveSquares = b.querySelectorAll('.cell.lastMove');
if (lastColor === 'w') currentTurn = 'b';
else if (lastColor === 'b') currentTurn = 'w';
else if (!lastMoveSquares.length) currentTurn = 'w';
else {
// Fallback for mid-game if lastColor was null: detect active clock
const clocks = document.querySelectorAll('[class*="clock"], [class*="timer"]');
let activeSide = null;
clocks.forEach(clk => {
const style = clk.getAttribute('style') || '';
const cls = clk.className || '';
const isActive = cls.includes('active') || cls.includes('running') || cls.includes('purple') || style.includes('background');
if (isActive) {
const r = clk.getBoundingClientRect();
const bRect = b.getBoundingClientRect();
const isBottom = r.top > (bRect.top + bRect.height / 2);
activeSide = isBottom ? (flipped ? 'b' : 'w') : (flipped ? 'w' : 'b');
}
});
if (activeSide) currentTurn = activeSide;
}
let f = "";
for (let r = 8; r >= 1; r--) {
if (r < 8) f += "/";
for (let c = 1; c <= 8; c++) {
let pc = grid[c + ',' + r];
f += pc ? (pc[0] === 'w' ? pc[1].toUpperCase() : pc[1]) : "1";
}
}
let castling = "";
if (grid['5,1'] === 'wk') {
if (grid['8,1'] === 'wr') castling += "K";
if (grid['1,1'] === 'wr') castling += "Q";
}
if (grid['5,8'] === 'bk') {
if (grid['8,8'] === 'br') castling += "k";
if (grid['1,8'] === 'br') castling += "q";
}
return {
board: b,
flipped,
fen: f.replace(/1+/g, m => m.length) + " " + currentTurn + " " + (castling || "-") + " - 0 1"
};
}
// chess.com's variants server has its own board; everywhere else on chess.com it is wc-chess-board
let readBoardChesscom = relay => document.querySelector('.TheBoard-layers') ? readBoardCV(relay) : readBoardCC();
let readBoard = { lichess: readBoardLI, endgame: readBoardEG, chesscom: readBoardChesscom }[SITE];
// ----------------------------------------------------------------- arrows