gigachess 0.5.0 → 0.7.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 (107) hide show
  1. package/README.md +142 -54
  2. package/dist/attacks.d.ts +18 -7
  3. package/dist/attacks.d.ts.map +1 -1
  4. package/dist/attacks.js +197 -89
  5. package/dist/bishopSplit32Blob.d.ts +2 -0
  6. package/dist/bishopSplit32Blob.d.ts.map +1 -0
  7. package/dist/bishopSplit32Blob.js +2 -0
  8. package/dist/castling.d.ts +2 -0
  9. package/dist/castling.d.ts.map +1 -1
  10. package/dist/castling.js +27 -12
  11. package/dist/chess960.d.ts +2 -9
  12. package/dist/chess960.d.ts.map +1 -1
  13. package/dist/chess960.js +2 -18
  14. package/dist/chessjs.d.ts +1 -1
  15. package/dist/chessjs.d.ts.map +1 -1
  16. package/dist/chessjs.js +1 -1
  17. package/dist/chessops/board.d.ts +1 -1
  18. package/dist/chessops/board.d.ts.map +1 -1
  19. package/dist/chessops/board.js +1 -1
  20. package/dist/chessops/chess.d.ts +6 -10
  21. package/dist/chessops/chess.d.ts.map +1 -1
  22. package/dist/chessops/chess.js +73 -97
  23. package/dist/chessops/convert.d.ts +1 -1
  24. package/dist/chessops/convert.d.ts.map +1 -1
  25. package/dist/chessops/convert.js +1 -1
  26. package/dist/chessops/debug.d.ts.map +1 -1
  27. package/dist/chessops/debug.js +7 -0
  28. package/dist/chessops/fen.d.ts.map +1 -1
  29. package/dist/chessops/fen.js +13 -2
  30. package/dist/chessops/fenInternal.d.ts +1 -1
  31. package/dist/chessops/fenInternal.d.ts.map +1 -1
  32. package/dist/chessops/fenInternal.js +1 -1
  33. package/dist/chessops/nativeBridge.d.ts +14 -0
  34. package/dist/chessops/nativeBridge.d.ts.map +1 -0
  35. package/dist/chessops/nativeBridge.js +87 -0
  36. package/dist/chessops/san.d.ts.map +1 -1
  37. package/dist/chessops/san.js +12 -10
  38. package/dist/chesstree.d.ts.map +1 -1
  39. package/dist/chesstree.js +23 -62
  40. package/dist/core.d.ts +6 -8
  41. package/dist/core.d.ts.map +1 -1
  42. package/dist/core.js +5 -10
  43. package/dist/fast/bishopSplit32Blob-NOHWZEWR.js +1 -0
  44. package/dist/fast/index.js +1 -0
  45. package/dist/fast/rookSplit32Blob-C3ANUNTJ.js +1 -0
  46. package/dist/fast/zobristBlob-HIMMLZLJ.js +1 -0
  47. package/dist/fast.d.ts +2 -0
  48. package/dist/fast.d.ts.map +1 -0
  49. package/dist/fast.js +2 -0
  50. package/dist/index.d.ts +1 -14
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +2 -19
  53. package/dist/native96.d.ts +16 -0
  54. package/dist/native96.d.ts.map +1 -0
  55. package/dist/native96.js +6 -0
  56. package/dist/nativeBoard96.d.ts +118 -0
  57. package/dist/nativeBoard96.d.ts.map +1 -0
  58. package/dist/nativeBoard96.js +1077 -0
  59. package/dist/nativeChess.d.ts +97 -0
  60. package/dist/nativeChess.d.ts.map +1 -0
  61. package/dist/nativeChess.js +201 -0
  62. package/dist/nativeMovegen96.d.ts +2 -0
  63. package/dist/nativeMovegen96.d.ts.map +1 -0
  64. package/dist/nativeMovegen96.js +282 -0
  65. package/dist/nativePublicTypes.d.ts +3 -0
  66. package/dist/nativePublicTypes.d.ts.map +1 -0
  67. package/dist/nativePublicTypes.js +1 -0
  68. package/dist/perftCompact.d.ts +10 -0
  69. package/dist/perftCompact.d.ts.map +1 -0
  70. package/dist/perftCompact.js +420 -0
  71. package/dist/pgn.d.ts +2 -3
  72. package/dist/pgn.d.ts.map +1 -1
  73. package/dist/pgn.js +2 -5
  74. package/dist/rookSplit32Blob.d.ts +2 -0
  75. package/dist/rookSplit32Blob.d.ts.map +1 -0
  76. package/dist/rookSplit32Blob.js +2 -0
  77. package/dist/setupBoard.d.ts +54 -0
  78. package/dist/setupBoard.d.ts.map +1 -0
  79. package/dist/setupBoard.js +249 -0
  80. package/dist/{fen.d.ts → setupFen.d.ts} +1 -1
  81. package/dist/setupFen.d.ts.map +1 -0
  82. package/dist/{fen.js → setupFen.js} +140 -125
  83. package/dist/squareSet.d.ts +2 -0
  84. package/dist/squareSet.d.ts.map +1 -1
  85. package/dist/squareSet.js +6 -1
  86. package/dist/types.d.ts +1 -1
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/zobrist.d.ts +2 -2
  89. package/dist/zobrist.d.ts.map +1 -1
  90. package/dist/zobrist.js +17 -15
  91. package/package.json +18 -6
  92. package/dist/bishopMagicBlob.d.ts +0 -2
  93. package/dist/bishopMagicBlob.d.ts.map +0 -1
  94. package/dist/bishopMagicBlob.js +0 -11
  95. package/dist/board.d.ts +0 -216
  96. package/dist/board.d.ts.map +0 -1
  97. package/dist/board.js +0 -1088
  98. package/dist/chess.d.ts +0 -252
  99. package/dist/chess.d.ts.map +0 -1
  100. package/dist/chess.js +0 -1930
  101. package/dist/fen.d.ts.map +0 -1
  102. package/dist/rookMagicBlob.d.ts +0 -2
  103. package/dist/rookMagicBlob.d.ts.map +0 -1
  104. package/dist/rookMagicBlob.js +0 -11
  105. package/dist/san.d.ts +0 -38
  106. package/dist/san.d.ts.map +0 -1
  107. package/dist/san.js +0 -549
package/dist/san.js DELETED
@@ -1,549 +0,0 @@
1
- // src/san.ts — parseSan/makeSan, parseUci/makeUci per purechess-rules
2
- // Clean-room from spec tables + FIDE notes, no G P L
3
- import * as sq from "./squareSet.js";
4
- import * as board from "./board.js";
5
- import * as chess from "./chess.js";
6
- import * as attacks from "./attacks.js";
7
- import { Color, Role } from "./types.js";
8
- import { Err, Ok } from "./types.js";
9
- import { squareFile, squareRank, parseSquare, squareName } from "./util.js";
10
- import { isNullMove, nullMove, NULL_MOVE_SAN, NULL_MOVE_UCI } from "./packedMove.js";
11
- const ROLE_SAN = ["", "N", "B", "R", "Q", "K"];
12
- const roleToSanChar = (role) => ROLE_SAN[role] ?? "";
13
- /**
14
- * The null move is a first-class pass, not a placeholder alias: the only SAN
15
- * tokens that denote one are `--` (the canonical rendering) and `Z0` (the
16
- * moves2/FEN pass token). `null`, `pass` and every other spelling are rejected
17
- * by `parseSan`.
18
- */
19
- export const NULL_MOVE_SANS = [NULL_MOVE_SAN, "Z0"];
20
- const NULL_MOVE_SAN_SET = new Set(NULL_MOVE_SANS);
21
- /** True when `san` is one of the two accepted null-move tokens. */
22
- export function isNullMoveSan(san) {
23
- return NULL_MOVE_SAN_SET.has(san);
24
- }
25
- const SAN_ROLES = { K: Role.King, Q: Role.Queen, R: Role.Rook, B: Role.Bishop, N: Role.Knight };
26
- const sanCharToRole = (ch) => SAN_ROLES[ch];
27
- const promoCharToRole = (ch) => SAN_ROLES[ch.toUpperCase()];
28
- function normalizeCastlingSan(s) {
29
- // tolerant 0-0 -> O-O
30
- return s.replace(/0-0-0/g, "O-O-O").replace(/0-0/g, "O-O");
31
- }
32
- // ---------- makeSan ----------
33
- export function makeSan(move, pos) {
34
- // A pass renders as exactly `--` and returns here: it is never suffixed with
35
- // `+` or `#` (a pass can neither give nor answer check), and it has no
36
- // origin square for the castling/disambiguation paths below.
37
- if (isNullMove(move))
38
- return NULL_MOVE_SAN;
39
- // Castling — detected via the shared detectCastling path (design D2) so a
40
- // canonical castling move given in the representation's encoding renders
41
- // O-O/O-O-O, never "Kg1"/"Kxh1" (measured defect: makeSan({4,6}, kiwipete)
42
- // returned "Kg1"). The isCastling flag is kept as a fallback for moves
43
- // produced by genLegalMoves under either representation. The role/rights
44
- // pre-check keeps the hot SAN path free of detectCastling calls.
45
- let castling = null;
46
- const movingPiece = board.pieceAt(pos.board, move.from);
47
- if (movingPiece && movingPiece.role === Role.King && (pos.castling.white.size > 0 || pos.castling.black.size > 0)) {
48
- castling = chess.detectCastling(pos, move.from, move.to);
49
- }
50
- if (castling || move.isCastling) {
51
- const isKingSide = castling ? castling.side === "king" : move.to === 6 || move.to === 62;
52
- let base = isKingSide ? "O-O" : "O-O-O";
53
- // add check suffix
54
- const next = chess.makeMove(pos, move);
55
- if (chess.isCheck(next)) {
56
- if (chess.isCheckmate(next))
57
- base += "#";
58
- else
59
- base += "+";
60
- }
61
- return base;
62
- }
63
- const piece = board.pieceAt(pos.board, move.from);
64
- if (!piece)
65
- return "";
66
- const toName = squareName(move.to);
67
- const isCapture = (() => {
68
- const target = board.pieceAt(pos.board, move.to);
69
- if (target && target.color !== pos.turn)
70
- return true;
71
- if (move.isEnPassant)
72
- return true;
73
- // en-passant capture onto the empty ep square (baseline output parity):
74
- // a pawn moving DIAGONALLY onto the ep square is a capture even when the
75
- // caller did not set the isEnPassant flag (external move objects). A
76
- // straight push to the ep square remains a quiet move.
77
- if (piece.role === Role.Pawn &&
78
- pos.epSquare !== null &&
79
- move.to === pos.epSquare &&
80
- squareFile(move.from) !== squareFile(move.to)) {
81
- return true;
82
- }
83
- return false;
84
- })();
85
- const destRank = squareRank(move.to);
86
- const isPromotion = !!move.isPromotion || (piece.role === Role.Pawn && (destRank === 7 || destRank === 0));
87
- // Piece letter
88
- let san = "";
89
- if (piece.role !== Role.Pawn) {
90
- san += roleToSanChar(piece.role);
91
- }
92
- else if (isCapture) {
93
- // pawn capture needs file of from
94
- san += String.fromCharCode(97 + squareFile(move.from));
95
- }
96
- // Disambiguation for non-pawn (and pawn capture already handled)
97
- if (piece.role !== Role.Pawn) {
98
- // Find other pieces of same role/color that can legally move to same destination
99
- const candidates = [];
100
- const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
101
- let attackers;
102
- switch (piece.role) {
103
- case Role.Knight:
104
- attackers = sq.and(attacks.knightAttacks(move.to), sq.and(own, pos.board.knight));
105
- break;
106
- case Role.Bishop:
107
- attackers = sq.and(attacks.bishopAttacks(move.to, pos.board.occupied), sq.and(own, pos.board.bishop));
108
- break;
109
- case Role.Rook:
110
- attackers = sq.and(attacks.rookAttacks(move.to, pos.board.occupied), sq.and(own, pos.board.rook));
111
- break;
112
- case Role.Queen:
113
- attackers = sq.and(attacks.queenAttacks(move.to, pos.board.occupied), sq.and(own, pos.board.queen));
114
- break;
115
- case Role.King:
116
- attackers = sq.and(attacks.kingAttacks(move.to), sq.and(own, pos.board.king));
117
- break;
118
- default:
119
- attackers = sq.EMPTY;
120
- break;
121
- }
122
- const otherAttackers = sq.minus(attackers, sq.singleton(move.from));
123
- if (!sq.isEmpty(otherAttackers)) {
124
- const ctx = chess.analyzeCheckContext(pos);
125
- for (const sqIdx of sq.iter(otherAttackers)) {
126
- const cand = board.pieceAt(pos.board, sqIdx);
127
- if (!cand)
128
- continue;
129
- const d = chess.destsFast(pos, sqIdx, cand, ctx);
130
- if (sq.has(d, move.to))
131
- candidates.push(sqIdx);
132
- }
133
- }
134
- // Include moving piece itself, total candidates +1 = all that can reach dest
135
- // If there is any other candidate, need disambiguation
136
- if (candidates.length > 0) {
137
- // Determine minimal disambiguation
138
- const movingFile = squareFile(move.from);
139
- const movingRank = squareRank(move.from);
140
- let needFile = false;
141
- let needRank = false;
142
- // Check if file alone distinguishes
143
- let fileUnique = true;
144
- for (const c of candidates) {
145
- if (squareFile(c) === movingFile) {
146
- fileUnique = false;
147
- break;
148
- }
149
- }
150
- if (fileUnique) {
151
- san += String.fromCharCode(97 + movingFile);
152
- }
153
- else {
154
- // file not unique, check rank
155
- let rankUnique = true;
156
- for (const c of candidates) {
157
- if (squareRank(c) === movingRank) {
158
- rankUnique = false;
159
- break;
160
- }
161
- }
162
- if (rankUnique) {
163
- san += String.fromCharCode(49 + movingRank);
164
- }
165
- else {
166
- san += String.fromCharCode(97 + movingFile) + String.fromCharCode(49 + movingRank);
167
- }
168
- }
169
- }
170
- }
171
- // Capture
172
- if (isCapture) {
173
- // For pawn, we already added file, need 'x'
174
- // For pieces, disambiguation already in san, now add 'x'
175
- san += "x";
176
- }
177
- // Destination
178
- // For pawn capture we already have file preceding 'x', need dest; for non-pawn we need dest after optional disamb and 'x'
179
- // Our san currently for pawn capture is like "e" + "x" => "ex", then dest
180
- // For non-pawn, san is piece char + disamb + 'x' if capture, then dest
181
- // So append dest
182
- // But for non-pawn capture case, we already have piece+disamb, now need to ensure we haven't duplicated file for pawn
183
- // For pawn non-capture, san is "" currently, just dest
184
- // For pawn capture, san is "ex" already, need dest
185
- // For pieces, san currently is piece+disamb (+x if capture) => need dest
186
- // However for pieces, if we added disamb file/rank, san already has it, so just add dest
187
- // Implementation above for pieces: san = piece char + disamb (file or rank or both) . For pawn capture, san = file + 'x' ? Wait we added file for pawn at start, then for disamb we skip for pawn, then capture adds 'x'. So for pawn capture "exd5": piece pawn => san initially "e" (file), then disamb skipped, then isCapture adds "x" => "ex", then dest "d5" => "exd5" correct.
188
- // For pawn non-capture "e4": san "" initially, no disamb, no capture, just dest "e4"
189
- // For piece "Nbd2": piece N, candidates determine file unique => san = "N" + "b" => "Nb", no capture, then dest "d2" => "Nbd2"
190
- // For "Qh4e1": piece Q, disamb "h4", san="Qh4", dest "e1" => "Qh4e1"
191
- san += toName;
192
- // Promotion
193
- if (isPromotion) {
194
- const promo = move.promotion ?? Role.Queen;
195
- san += "=" + roleToSanChar(promo);
196
- }
197
- // Check / mate suffix
198
- const next = chess.makeMove(pos, move);
199
- if (chess.isCheck(next)) {
200
- if (chess.isCheckmate(next))
201
- san += "#";
202
- else
203
- san += "+";
204
- }
205
- return san;
206
- }
207
- // ---------- parseSan ----------
208
- export function parseSan(san, pos) {
209
- return parseSanDetailed(san, pos).result;
210
- }
211
- /**
212
- * `parseSan` with the matching moves retained.
213
- *
214
- * A multi-match parse ends in `san/ambiguous` and `parseSan` throws the matches
215
- * away, so a caller can report *that* the input was ambiguous but never *what*
216
- * it could have meant. `candidates` carries that list so a UI can name the
217
- * disambiguated spellings instead of guessing (BlindBase ADR-042, report #11).
218
- *
219
- * `result` is exactly what `parseSan` returns for the same input; this exists so
220
- * the two cannot drift, not as a second parse path.
221
- */
222
- export function parseSanDetailed(san, pos) {
223
- const traced = parseSanTraced(san, pos);
224
- const candidates = traced.candidates;
225
- if (candidates === null) {
226
- // Rejected before any move could match — nothing to disambiguate.
227
- return { result: traced.result, candidates: null };
228
- }
229
- if (candidates.length === 0) {
230
- return { result: Err({ code: "san/noLegalMove" }), candidates };
231
- }
232
- if (candidates.length > 1) {
233
- return { result: Err({ code: "san/ambiguous" }), candidates };
234
- }
235
- return { result: Ok(candidates[0]), candidates };
236
- }
237
- /**
238
- * Every legal move `san` could denote, or the error when it names none.
239
- *
240
- * The counterpart to `parseSan` for callers that must react to ambiguity rather
241
- * than accept it: `length === 1` means resolved, `length > 1` means the caller
242
- * should ask which of these it meant.
243
- */
244
- export function parseSanCandidates(san, pos) {
245
- const { result, candidates } = parseSanDetailed(san, pos);
246
- if (candidates === null || candidates.length === 0) {
247
- return result.ok ? Ok([result.value]) : Err(result.error);
248
- }
249
- return Ok(candidates);
250
- }
251
- /**
252
- * The parse body, keeping the collected candidates.
253
- *
254
- * Every early refusal before candidate collection returns `candidates: null`,
255
- * which is what distinguishes "this string is not a SAN at all" from "this SAN
256
- * is ambiguous" — a distinction `parseSan`'s single error channel previously
257
- * lost.
258
- */
259
- function parseSanTraced(san, pos) {
260
- // A refusal raised before any move could match: nothing to disambiguate, which
261
- // is what separates "not a SAN at all" from "an ambiguous SAN".
262
- const fail = (code) => ({ result: Err({ code }), candidates: null });
263
- const orig = san;
264
- let s = normalizeCastlingSan(san.trim());
265
- // Null move (pass) — exactly `--` or `Z0`, matched BEFORE any check-suffix
266
- // handling so a suffixed spelling (`--+`) is not silently accepted. A pass is
267
- // legal iff the side to move is not in check; the test is computed fresh from
268
- // the attack tables, never from the cached `checkers` bitboard.
269
- if (isNullMoveSan(s)) {
270
- if (!chess.isNullMoveLegal(pos))
271
- return fail("san/illegal");
272
- return { result: Ok(nullMove()), candidates: [nullMove()] };
273
- }
274
- // Handle check suffix for later, but keep for validation
275
- let checkSuffix = "";
276
- if (s.endsWith("+") || s.endsWith("#")) {
277
- checkSuffix = s.slice(-1);
278
- s = s.slice(0, -1);
279
- }
280
- // Castling
281
- if (s === "O-O" || s === "O-O-O") {
282
- const isKingSide = s === "O-O";
283
- const kingSq = board.kingSquare(pos.board, pos.turn);
284
- if (kingSq === undefined)
285
- return fail("san/noKing");
286
- // Find if castling is legal via dests. The generated dest is the
287
- // representation's castling square: normalized landing (6/2/62/58) or the
288
- // right's rook square (baseline/960 form). Both are accepted.
289
- const d = chess.dests(pos, kingSq);
290
- const normDest = pos.turn === Color.White ? (isKingSide ? 6 : 2) : (isKingSide ? 62 : 58);
291
- let dest;
292
- if (sq.has(d, normDest)) {
293
- dest = normDest;
294
- }
295
- else {
296
- const rights = pos.turn === Color.White ? pos.castling.white : pos.castling.black;
297
- for (const rs of rights) {
298
- const rookIsKingSide = squareFile(rs) > squareFile(kingSq);
299
- if (rookIsKingSide === isKingSide && sq.has(d, rs)) {
300
- dest = rs;
301
- break;
302
- }
303
- }
304
- }
305
- if (dest === undefined)
306
- return fail("san/illegal");
307
- const move = { from: kingSq, to: dest, isCastling: true, isEnPassant: false, isPromotion: false, promotion: null };
308
- // Optionally validate check suffix matches actual
309
- // We ignore mismatch for parsing tolerance, but we could validate
310
- // If checkSuffix present, we could verify after play, but not required to error
311
- return { result: Ok(move), candidates: [move] };
312
- }
313
- // Promotion handling
314
- let promotion = undefined;
315
- const eqIdx = s.indexOf("=");
316
- if (eqIdx !== -1) {
317
- const promoChar = s[eqIdx + 1];
318
- if (!promoChar)
319
- return fail("san/invalidPromotion");
320
- const role = promoCharToRole(promoChar);
321
- if (role === undefined)
322
- return fail("san/invalidPromotion");
323
- promotion = role;
324
- s = s.slice(0, eqIdx);
325
- }
326
- // Destination
327
- if (s.length < 2)
328
- return fail("san/invalidSan");
329
- const toStr = s.slice(-2);
330
- const to = parseSquare(toStr);
331
- if (to === undefined)
332
- return fail("san/invalidSquare");
333
- let rest = s.slice(0, -2);
334
- // Capture
335
- let isCapture = false;
336
- if (rest.endsWith("x")) {
337
- isCapture = true;
338
- rest = rest.slice(0, -1);
339
- }
340
- // Piece
341
- let pieceRole = null; // null means pawn
342
- if (rest.length > 0 && "KQRBN".includes(rest[0])) {
343
- const ch = rest[0];
344
- pieceRole = sanCharToRole(ch);
345
- rest = rest.slice(1);
346
- }
347
- else {
348
- pieceRole = Role.Pawn;
349
- }
350
- // Disambiguation remaining
351
- let disambFile = null;
352
- let disambRank = null;
353
- if (rest.length === 1) {
354
- const ch = rest[0];
355
- if (ch >= "a" && ch <= "h")
356
- disambFile = ch;
357
- else if (ch >= "1" && ch <= "8")
358
- disambRank = ch;
359
- else
360
- return fail("san/invalidSan");
361
- }
362
- else if (rest.length === 2) {
363
- if (rest[0] >= "a" && rest[0] <= "h" && rest[1] >= "1" && rest[1] <= "8") {
364
- disambFile = rest[0];
365
- disambRank = rest[1];
366
- }
367
- else
368
- return fail("san/invalidSan");
369
- }
370
- else if (rest.length > 2) {
371
- return fail("san/invalidSan");
372
- }
373
- // For pawn, pieceRole is pawn, but rest may be file for capture (like "e" in exd5)
374
- // Our disamb handling already captured that: for "exd5", rest after removing piece (none) and capture, rest = "e" => disambFile = 'e' . Good.
375
- // For pawn push "e4", rest = "" => no disamb.
376
- // Targeted reverse attacker lookup
377
- const us = pos.turn;
378
- const own = us === Color.White ? pos.board.white : pos.board.black;
379
- const candidateFroms = [];
380
- if (pieceRole === Role.Pawn) {
381
- // 1. Pawn pushes
382
- const pushFrom = us === Color.White ? to - 8 : to + 8;
383
- if (pushFrom >= 0 && pushFrom < 64 && !board.pieceAt(pos.board, to)) {
384
- const p = board.pieceAt(pos.board, pushFrom);
385
- if (p && p.color === us && p.role === Role.Pawn)
386
- candidateFroms.push(pushFrom);
387
- }
388
- if (us === Color.White && squareRank(to) === 3) {
389
- const dblFrom = to - 16;
390
- if (!board.pieceAt(pos.board, to) && !board.pieceAt(pos.board, to - 8)) {
391
- const p = board.pieceAt(pos.board, dblFrom);
392
- if (p && p.color === us && p.role === Role.Pawn)
393
- candidateFroms.push(dblFrom);
394
- }
395
- }
396
- else if (us === Color.Black && squareRank(to) === 4) {
397
- const dblFrom = to + 16;
398
- if (!board.pieceAt(pos.board, to) && !board.pieceAt(pos.board, to + 8)) {
399
- const p = board.pieceAt(pos.board, dblFrom);
400
- if (p && p.color === us && p.role === Role.Pawn)
401
- candidateFroms.push(dblFrom);
402
- }
403
- }
404
- // 2. Pawn diagonal attacks (normal captures or en-passant)
405
- const pAtt = attacks.pawnAttacks(us === Color.White ? Color.Black : Color.White, to);
406
- const pawnCaps = sq.and(pAtt, sq.and(own, pos.board.pawn));
407
- for (const sqIdx of sq.iter(pawnCaps)) {
408
- candidateFroms.push(sqIdx);
409
- }
410
- }
411
- else {
412
- let attackers;
413
- switch (pieceRole) {
414
- case Role.Knight:
415
- attackers = sq.and(attacks.knightAttacks(to), sq.and(own, pos.board.knight));
416
- break;
417
- case Role.Bishop:
418
- attackers = sq.and(attacks.bishopAttacks(to, pos.board.occupied), sq.and(own, pos.board.bishop));
419
- break;
420
- case Role.Rook:
421
- attackers = sq.and(attacks.rookAttacks(to, pos.board.occupied), sq.and(own, pos.board.rook));
422
- break;
423
- case Role.Queen:
424
- attackers = sq.and(attacks.queenAttacks(to, pos.board.occupied), sq.and(own, pos.board.queen));
425
- break;
426
- case Role.King:
427
- attackers = sq.and(attacks.kingAttacks(to), sq.and(own, pos.board.king));
428
- break;
429
- default:
430
- attackers = sq.EMPTY;
431
- break;
432
- }
433
- for (const sqIdx of sq.iter(attackers)) {
434
- candidateFroms.push(sqIdx);
435
- }
436
- }
437
- // Disambiguation filtering
438
- let filteredFroms = candidateFroms;
439
- if (disambFile !== null) {
440
- const reqFile = disambFile.charCodeAt(0) - 97;
441
- filteredFroms = filteredFroms.filter(f => squareFile(f) === reqFile);
442
- }
443
- if (disambRank !== null) {
444
- const reqRank = disambRank.charCodeAt(0) - 49;
445
- filteredFroms = filteredFroms.filter(f => squareRank(f) === reqRank);
446
- }
447
- if (filteredFroms.length === 0)
448
- return fail("san/noLegalMove");
449
- // Legality filtering with single shared check context
450
- const ctx = chess.analyzeCheckContext(pos);
451
- const candidates = [];
452
- const destRank = squareRank(to);
453
- for (const from of filteredFroms) {
454
- const fromPiece = board.pieceAt(pos.board, from);
455
- if (!fromPiece)
456
- continue;
457
- const isPromo = fromPiece.role === Role.Pawn && (destRank === 0 || destRank === 7);
458
- if (isPromo && promotion === undefined)
459
- continue;
460
- if (!isPromo && promotion !== undefined)
461
- continue;
462
- const d = chess.destsFast(pos, from, fromPiece, ctx);
463
- if (!sq.has(d, to))
464
- continue;
465
- let isEnPassant = false;
466
- if (fromPiece.role === Role.Pawn && pos.epSquare !== null && to === pos.epSquare) {
467
- const fileDiff = Math.abs(squareFile(to) - squareFile(from));
468
- const dir = fromPiece.color === Color.White ? 1 : -1;
469
- if (fileDiff === 1 && destRank - squareRank(from) === dir)
470
- isEnPassant = true;
471
- }
472
- candidates.push({
473
- from,
474
- to,
475
- promotion: isPromo ? (promotion ?? Role.Queen) : null,
476
- isPromotion: isPromo,
477
- isEnPassant,
478
- isCastling: false,
479
- });
480
- }
481
- if (candidates.length === 0)
482
- return { result: Err({ code: "san/noLegalMove" }), candidates };
483
- if (candidates.length > 1)
484
- return { result: Err({ code: "san/ambiguous" }), candidates };
485
- return { result: Ok(candidates[0]), candidates };
486
- }
487
- // ---------- UCI ----------
488
- export function parseUci(uci) {
489
- const s = uci.trim();
490
- // The null move is the `0000` token (its own 4-char spelling, not a square
491
- // pair). Parsing is position-free; the legality of a pass is judged by the
492
- // validating entry points (isLegal / parseSan / makeMove).
493
- if (s === NULL_MOVE_UCI)
494
- return Ok(nullMove());
495
- if (s.length < 4 || s.length > 5)
496
- return Err({ code: "uci/invalidUci" });
497
- const fromStr = s.slice(0, 2);
498
- const toStr = s.slice(2, 4);
499
- const from = parseSquare(fromStr);
500
- const to = parseSquare(toStr);
501
- if (from === undefined || to === undefined)
502
- return Err({ code: "uci/invalidSquare" });
503
- let promotion = null;
504
- let isPromotion = false;
505
- if (s.length === 5) {
506
- const promoChar = s[4];
507
- const role = promoCharToRole(promoChar);
508
- if (!role)
509
- return Err({ code: "uci/invalidPromotion" });
510
- promotion = role;
511
- isPromotion = true;
512
- }
513
- // Determine if this is castling via king move? For UCI, castling is e1g1 or e1h1 etc. We need to detect if this is king move and castling rights? But we don't have Position here to validate. parseUci as per spec is pure without position: it just parses squares and promotion. However spec says parseUci handles e1g1 and e1h1 both as castling in 960. But without position, we can't know. So we just return Move with from,to,promotion and set isCastling false initially; caller can interpret via position's dests/isLegal.
514
- // But we can set isCastling heuristically: if from is king start and to is G1/C1 or rook square? We don't have board. We'll just return move and let chess.isLegal handle normalization.
515
- // For now, set isCastling false, and let makeMove handle 960 normalization
516
- const move = { from, to, promotion, isPromotion, isEnPassant: false, isCastling: false };
517
- // Also need to detect promotion case where to square is back rank and promotion missing? That's SAN concern, not UCI: UCI must have promotion char if pawn to back rank, but we can allow without and still return move with null promotion? Spec says e7e8q and e7e8Q both promotion queen. We'll handle.
518
- return Ok(move);
519
- }
520
- export function makeUci(move) {
521
- // A pass renders as `0000` (the 16-bit sentinel's 4-char spelling) and
522
- // returns here — it has no origin/destination square.
523
- if (isNullMove(move))
524
- return NULL_MOVE_UCI;
525
- const from = squareName(move.from);
526
- const to = squareName(move.to);
527
- let promo = "";
528
- if (move.promotion !== null && move.promotion !== undefined) {
529
- switch (move.promotion) {
530
- case Role.Queen:
531
- promo = "q";
532
- break;
533
- case Role.Rook:
534
- promo = "r";
535
- break;
536
- case Role.Bishop:
537
- promo = "b";
538
- break;
539
- case Role.Knight:
540
- promo = "n";
541
- break;
542
- default: promo = "";
543
- }
544
- }
545
- else if (move.isPromotion && move.promotion) {
546
- // same
547
- }
548
- return from + to + promo;
549
- }