gigachess 0.2.1

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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +183 -0
  3. package/dist/attacks.d.ts +40 -0
  4. package/dist/attacks.d.ts.map +1 -0
  5. package/dist/attacks.js +389 -0
  6. package/dist/bishopMagicBlob.d.ts +2 -0
  7. package/dist/bishopMagicBlob.d.ts.map +1 -0
  8. package/dist/bishopMagicBlob.js +11 -0
  9. package/dist/board.d.ts +73 -0
  10. package/dist/board.d.ts.map +1 -0
  11. package/dist/board.js +237 -0
  12. package/dist/chess.d.ts +215 -0
  13. package/dist/chess.d.ts.map +1 -0
  14. package/dist/chess.js +1453 -0
  15. package/dist/chess960.d.ts +10 -0
  16. package/dist/chess960.d.ts.map +1 -0
  17. package/dist/chess960.js +18 -0
  18. package/dist/chessops/board.d.ts +49 -0
  19. package/dist/chessops/board.d.ts.map +1 -0
  20. package/dist/chessops/board.js +138 -0
  21. package/dist/chessops/chess.d.ts +104 -0
  22. package/dist/chessops/chess.d.ts.map +1 -0
  23. package/dist/chessops/chess.js +435 -0
  24. package/dist/chessops/compat.d.ts +19 -0
  25. package/dist/chessops/compat.d.ts.map +1 -0
  26. package/dist/chessops/compat.js +25 -0
  27. package/dist/chessops/convert.d.ts +42 -0
  28. package/dist/chessops/convert.d.ts.map +1 -0
  29. package/dist/chessops/convert.js +114 -0
  30. package/dist/chessops/debug.d.ts +17 -0
  31. package/dist/chessops/debug.d.ts.map +1 -0
  32. package/dist/chessops/debug.js +67 -0
  33. package/dist/chessops/fen.d.ts +28 -0
  34. package/dist/chessops/fen.d.ts.map +1 -0
  35. package/dist/chessops/fen.js +74 -0
  36. package/dist/chessops/fenInternal.d.ts +15 -0
  37. package/dist/chessops/fenInternal.d.ts.map +1 -0
  38. package/dist/chessops/fenInternal.js +42 -0
  39. package/dist/chessops/index.d.ts +12 -0
  40. package/dist/chessops/index.d.ts.map +1 -0
  41. package/dist/chessops/index.js +17 -0
  42. package/dist/chessops/san.d.ts +7 -0
  43. package/dist/chessops/san.d.ts.map +1 -0
  44. package/dist/chessops/san.js +33 -0
  45. package/dist/chessops/setup.d.ts +64 -0
  46. package/dist/chessops/setup.d.ts.map +1 -0
  47. package/dist/chessops/setup.js +158 -0
  48. package/dist/chessops/squareSet.d.ts +48 -0
  49. package/dist/chessops/squareSet.d.ts.map +1 -0
  50. package/dist/chessops/squareSet.js +192 -0
  51. package/dist/chessops/transform.d.ts +12 -0
  52. package/dist/chessops/transform.d.ts.map +1 -0
  53. package/dist/chessops/transform.js +53 -0
  54. package/dist/chessops/types.d.ts +47 -0
  55. package/dist/chessops/types.d.ts.map +1 -0
  56. package/dist/chessops/types.js +12 -0
  57. package/dist/chessops/util.d.ts +19 -0
  58. package/dist/chessops/util.d.ts.map +1 -0
  59. package/dist/chessops/util.js +52 -0
  60. package/dist/chesstree.d.ts +143 -0
  61. package/dist/chesstree.d.ts.map +1 -0
  62. package/dist/chesstree.js +514 -0
  63. package/dist/core.d.ts +10 -0
  64. package/dist/core.d.ts.map +1 -0
  65. package/dist/core.js +11 -0
  66. package/dist/fen.d.ts +10 -0
  67. package/dist/fen.d.ts.map +1 -0
  68. package/dist/fen.js +600 -0
  69. package/dist/index.d.ts +17 -0
  70. package/dist/index.d.ts.map +1 -0
  71. package/dist/index.js +22 -0
  72. package/dist/packedMove.d.ts +31 -0
  73. package/dist/packedMove.d.ts.map +1 -0
  74. package/dist/packedMove.js +88 -0
  75. package/dist/pgn.d.ts +24 -0
  76. package/dist/pgn.d.ts.map +1 -0
  77. package/dist/pgn.js +361 -0
  78. package/dist/rookMagicBlob.d.ts +2 -0
  79. package/dist/rookMagicBlob.d.ts.map +1 -0
  80. package/dist/rookMagicBlob.js +11 -0
  81. package/dist/san.d.ts +6 -0
  82. package/dist/san.d.ts.map +1 -0
  83. package/dist/san.js +484 -0
  84. package/dist/squareSet.d.ts +48 -0
  85. package/dist/squareSet.d.ts.map +1 -0
  86. package/dist/squareSet.js +154 -0
  87. package/dist/types.d.ts +147 -0
  88. package/dist/types.d.ts.map +1 -0
  89. package/dist/types.js +88 -0
  90. package/dist/util.d.ts +11 -0
  91. package/dist/util.d.ts.map +1 -0
  92. package/dist/util.js +59 -0
  93. package/dist/zobrist.d.ts +45 -0
  94. package/dist/zobrist.d.ts.map +1 -0
  95. package/dist/zobrist.js +271 -0
  96. package/dist/zobristBlob.d.ts +2 -0
  97. package/dist/zobristBlob.d.ts.map +1 -0
  98. package/dist/zobristBlob.js +11 -0
  99. package/package.json +135 -0
package/dist/fen.js ADDED
@@ -0,0 +1,600 @@
1
+ // src/fen.ts — parseFen / makeFen with six-field validation per purechess-rules
2
+ // Clean-room from spec tables + FIDE notes, no G P L, no english hard-coded strings beyond codes
3
+ import * as board from "./board.js";
4
+ import * as sq from "./squareSet.js";
5
+ import { Color, Role, Err, Ok } from "./types.js";
6
+ import { squareFile, squareRank, squareName } from "./util.js";
7
+ import * as attacks from "./attacks.js";
8
+ import { zobristTablesLoaded, calculateZobrist } from "./zobrist.js";
9
+ // helpers to create CastlingRights
10
+ function makeCastling(whiteSet, blackSet) {
11
+ const whiteKing = whiteSet.has(7);
12
+ const whiteQueen = whiteSet.has(0);
13
+ const blackKing = blackSet.has(63);
14
+ const blackQueen = blackSet.has(56);
15
+ return {
16
+ white: new Set(whiteSet),
17
+ black: new Set(blackSet),
18
+ whiteKing,
19
+ whiteQueen,
20
+ blackKing,
21
+ blackQueen,
22
+ };
23
+ }
24
+ function roleFromChar(ch) {
25
+ const lower = ch.toLowerCase();
26
+ let role;
27
+ if (lower === "p")
28
+ role = Role.Pawn;
29
+ else if (lower === "n")
30
+ role = Role.Knight;
31
+ else if (lower === "b")
32
+ role = Role.Bishop;
33
+ else if (lower === "r")
34
+ role = Role.Rook;
35
+ else if (lower === "q")
36
+ role = Role.Queen;
37
+ else if (lower === "k")
38
+ role = Role.King;
39
+ else
40
+ return undefined;
41
+ const color = ch === lower ? Color.Black : Color.White;
42
+ return { role: role, color };
43
+ }
44
+ function charFromPiece(color, role) {
45
+ let ch;
46
+ switch (role) {
47
+ case Role.Pawn:
48
+ ch = "p";
49
+ break;
50
+ case Role.Knight:
51
+ ch = "n";
52
+ break;
53
+ case Role.Bishop:
54
+ ch = "b";
55
+ break;
56
+ case Role.Rook:
57
+ ch = "r";
58
+ break;
59
+ case Role.Queen:
60
+ ch = "q";
61
+ break;
62
+ case Role.King:
63
+ ch = "k";
64
+ break;
65
+ default: ch = "?";
66
+ }
67
+ return color === Color.White ? ch.toUpperCase() : ch;
68
+ }
69
+ /** Whitespace predicate for the single-pass FEN scanner (space, \t, \n, \v, \f, \r). */
70
+ function isFenSpace(c) {
71
+ return c === 32 || (c >= 9 && c <= 13);
72
+ }
73
+ /** Digits-only integer parse over fen[s..e); NaN when empty or non-digit. */
74
+ function parseFenCount(fen, s, e) {
75
+ if (s >= e)
76
+ return NaN;
77
+ let v = 0;
78
+ for (let k = s; k < e; k++) {
79
+ const c = fen.charCodeAt(k);
80
+ if (c < 48 || c > 57)
81
+ return NaN;
82
+ v = v * 10 + (c - 48);
83
+ }
84
+ return v;
85
+ }
86
+ export function parseFen(fen, opts) {
87
+ // ----- single-pass field tokenization (zero regex, zero split arrays) -----
88
+ // Fields are whitespace-separated; 1..6 fields are accepted (missing fields
89
+ // default to w/-/-/0/1; more than 6 is rejected) — baseline-compatible
90
+ // field tolerance required for parse-agreement parity on corpora like
91
+ // wac_150.epd whose FENs carry only four fields.
92
+ const n = fen.length;
93
+ const fs = [];
94
+ const fe = [];
95
+ {
96
+ let pos = 0;
97
+ for (;;) {
98
+ while (pos < n && isFenSpace(fen.charCodeAt(pos)))
99
+ pos++;
100
+ if (pos >= n)
101
+ break;
102
+ const s = pos;
103
+ while (pos < n && !isFenSpace(fen.charCodeAt(pos)))
104
+ pos++;
105
+ fs.push(s);
106
+ fe.push(pos);
107
+ }
108
+ }
109
+ const fieldCount = fs.length;
110
+ if (fieldCount < 1 || fieldCount > 6) {
111
+ return Err({ code: "fen/invalidFen" });
112
+ }
113
+ // ----- piece placement -----
114
+ // Single-pass build into a locally-owned scratch board (FP policy:
115
+ // clone→mutate-clone) — ONE final immutable copy instead of the old
116
+ // per-piece `setPiece`. The scanner walks the raw string with charCodeAt:
117
+ // '/' drops a rank, '1'..'8' skips empty squares, anything else must be a
118
+ // piece letter (color = uppercase ⇒ white).
119
+ const scratch = board.newScratchBoard();
120
+ let r = 7;
121
+ let file = 0;
122
+ for (let k = fs[0]; k < fe[0]; k++) {
123
+ const c = fen.charCodeAt(k);
124
+ if (c === 47) {
125
+ // '/': next rank down
126
+ if (file !== 8 || r === 0)
127
+ return Err({ code: "fen/invalidPiecePlacement" });
128
+ r--;
129
+ file = 0;
130
+ continue;
131
+ }
132
+ if (c >= 49 && c <= 56) {
133
+ // '1'..'8': consecutive empty squares
134
+ file += c - 48;
135
+ if (file > 8)
136
+ return Err({ code: "fen/invalidPiecePlacement" });
137
+ continue;
138
+ }
139
+ if (file >= 8)
140
+ return Err({ code: "fen/invalidPiecePlacement" });
141
+ // inline role/color decode (no per-piece object allocation)
142
+ let role;
143
+ switch (c | 32) {
144
+ case 112:
145
+ role = Role.Pawn;
146
+ break; // p
147
+ case 110:
148
+ role = Role.Knight;
149
+ break; // n
150
+ case 98:
151
+ role = Role.Bishop;
152
+ break; // b
153
+ case 114:
154
+ role = Role.Rook;
155
+ break; // r
156
+ case 113:
157
+ role = Role.Queen;
158
+ break; // q
159
+ case 107:
160
+ role = Role.King;
161
+ break; // k
162
+ default: return Err({ code: "fen/invalidPiecePlacement" });
163
+ }
164
+ const color = c >= 97 ? Color.Black : Color.White; // lowercase ⇒ black
165
+ const sqIdx = r * 8 + file;
166
+ board.putPieceInPlace(scratch, sqIdx, { color, role });
167
+ file++;
168
+ }
169
+ if (file !== 8 || r !== 0)
170
+ return Err({ code: "fen/invalidPiecePlacement" });
171
+ const curBoard = board.cloneBoard(scratch);
172
+ // ----- active color -----
173
+ let turn;
174
+ if (fieldCount < 2) {
175
+ turn = Color.White;
176
+ }
177
+ else if (fe[1] - fs[1] === 1) {
178
+ const c = fen.charCodeAt(fs[1]);
179
+ if (c === 119)
180
+ turn = Color.White; // 'w'
181
+ else if (c === 98)
182
+ turn = Color.Black; // 'b'
183
+ else
184
+ return Err({ code: "fen/invalidActiveColor" });
185
+ }
186
+ else {
187
+ return Err({ code: "fen/invalidActiveColor" });
188
+ }
189
+ // ----- castling -----
190
+ let whiteSet = new Set();
191
+ let blackSet = new Set();
192
+ const castlingStart = fieldCount > 2 ? fs[2] : -1;
193
+ const castlingIsDash = castlingStart === -1 || (fe[2] - fs[2] === 1 && fen.charCodeAt(fs[2]) === 45);
194
+ if (!castlingIsDash) {
195
+ // validate characters
196
+ const chess960 = !!opts?.chess960;
197
+ // Find king squares for Shredder mapping if needed
198
+ let wk, bk;
199
+ if (chess960) {
200
+ wk = board.kingSquare(curBoard, Color.White);
201
+ bk = board.kingSquare(curBoard, Color.Black);
202
+ }
203
+ // collect chars (index scan over field 2)
204
+ for (let k = castlingStart; k < fe[2]; k++) {
205
+ const ch = fen[k];
206
+ if (!chess960) {
207
+ if (ch !== "K" && ch !== "Q" && ch !== "k" && ch !== "q") {
208
+ return Err({ code: "fen/invalidCastling" });
209
+ }
210
+ if (ch === "K")
211
+ whiteSet.add(7);
212
+ else if (ch === "Q")
213
+ whiteSet.add(0);
214
+ else if (ch === "k")
215
+ blackSet.add(63);
216
+ else if (ch === "q")
217
+ blackSet.add(56);
218
+ }
219
+ else {
220
+ // chess960 tolerant
221
+ if (ch === "K") {
222
+ // Shredder king-side white: find rook > king file
223
+ if (wk === undefined)
224
+ return Err({ code: "fen/invalidCastling" });
225
+ const kf = squareFile(wk);
226
+ // find white rooks on rank 1
227
+ let best;
228
+ for (let f = 7; f > kf; f--) {
229
+ const sqIdx = f; // rank 0
230
+ const p = board.pieceAt(curBoard, sqIdx);
231
+ if (p && p.color === Color.White && p.role === Role.Rook) {
232
+ best = sqIdx;
233
+ break;
234
+ }
235
+ // if no rook found, still add H1 as fallback for standard
236
+ }
237
+ if (best !== undefined)
238
+ whiteSet.add(best);
239
+ else
240
+ whiteSet.add(7); // fallback to H1
241
+ }
242
+ else if (ch === "Q") {
243
+ if (wk === undefined)
244
+ return Err({ code: "fen/invalidCastling" });
245
+ const kf = squareFile(wk);
246
+ let best;
247
+ for (let f = kf - 1; f >= 0; f--) {
248
+ const sqIdx = f;
249
+ const p = board.pieceAt(curBoard, sqIdx);
250
+ if (p && p.color === Color.White && p.role === Role.Rook) {
251
+ best = sqIdx;
252
+ break;
253
+ }
254
+ }
255
+ if (best !== undefined)
256
+ whiteSet.add(best);
257
+ else
258
+ whiteSet.add(0);
259
+ }
260
+ else if (ch === "k") {
261
+ if (bk === undefined)
262
+ return Err({ code: "fen/invalidCastling" });
263
+ const kf = squareFile(bk);
264
+ let best;
265
+ for (let f = 7; f > kf; f--) {
266
+ const sqIdx = 56 + f;
267
+ const p = board.pieceAt(curBoard, sqIdx);
268
+ if (p && p.color === Color.Black && p.role === Role.Rook) {
269
+ best = sqIdx;
270
+ break;
271
+ }
272
+ }
273
+ if (best !== undefined)
274
+ blackSet.add(best);
275
+ else
276
+ blackSet.add(63);
277
+ }
278
+ else if (ch === "q") {
279
+ if (bk === undefined)
280
+ return Err({ code: "fen/invalidCastling" });
281
+ const kf = squareFile(bk);
282
+ let best;
283
+ for (let f = kf - 1; f >= 0; f--) {
284
+ const sqIdx = 56 + f;
285
+ const p = board.pieceAt(curBoard, sqIdx);
286
+ if (p && p.color === Color.Black && p.role === Role.Rook) {
287
+ best = sqIdx;
288
+ break;
289
+ }
290
+ }
291
+ if (best !== undefined)
292
+ blackSet.add(best);
293
+ else
294
+ blackSet.add(56);
295
+ }
296
+ else if (ch >= "A" && ch <= "H") {
297
+ const file = ch.charCodeAt(0) - 65;
298
+ const sqIdx = file; // rank 0
299
+ whiteSet.add(sqIdx);
300
+ }
301
+ else if (ch >= "a" && ch <= "h") {
302
+ const file = ch.charCodeAt(0) - 97;
303
+ const sqIdx = 56 + file;
304
+ blackSet.add(sqIdx);
305
+ }
306
+ else {
307
+ return Err({ code: "fen/invalidCastling" });
308
+ }
309
+ }
310
+ }
311
+ // duplicate check not needed; Set handles
312
+ // For non-960, ensure no duplicate file letters etc already handled
313
+ }
314
+ const castling = makeCastling(whiteSet, blackSet);
315
+ // ----- en passant -----
316
+ // Structural validation (square name + rank for the side to move) stays
317
+ // unconditional per purechess-rules. The capturability check moves behind
318
+ // `strict` (design D3): real-world corpora (lichess FENs after any double
319
+ // push) and turbochess's own makeFen output contain unreachable ep squares,
320
+ // and baseline accepts them — rejecting them broke round-trip for ~4.7% of
321
+ // real-game positions.
322
+ let epSquare = null;
323
+ const epIsDash = fieldCount < 4 || (fe[3] - fs[3] === 1 && fen.charCodeAt(fs[3]) === 45);
324
+ if (!epIsDash) {
325
+ // index-based square parse (replaces parseSquare on a substring)
326
+ if (fe[3] - fs[3] !== 2)
327
+ return Err({ code: "fen/invalidEnPassant" });
328
+ const ef = fen.charCodeAt(fs[3]) - 97; // file a..h
329
+ const er = fen.charCodeAt(fs[3] + 1) - 49; // rank 1..8
330
+ if (ef < 0 || ef > 7 || er < 0 || er > 7)
331
+ return Err({ code: "fen/invalidEnPassant" });
332
+ const sqIdx = (er << 3) | ef;
333
+ const rank = squareRank(sqIdx);
334
+ // must be rank 6 for white to move (index 5) or rank 3 for black to move (index 2)
335
+ if (turn === Color.White && rank !== 5)
336
+ return Err({ code: "fen/enPassantUncapturable" });
337
+ if (turn === Color.Black && rank !== 2)
338
+ return Err({ code: "fen/enPassantUncapturable" });
339
+ epSquare = sqIdx;
340
+ if (opts?.strict) {
341
+ // FIDE-strict mode restores the previous behavior: a pawn of the side
342
+ // to move must be able to capture on the ep square.
343
+ const file = squareFile(sqIdx);
344
+ let capturable = false;
345
+ // For white to move, ep rank 5, capturing pawns are on rank 4 (index 4) adjacent file
346
+ // For black to move, ep rank 2, capturing pawns on rank 3 (index 3) adjacent
347
+ const pawnRank = turn === Color.White ? 4 : 3;
348
+ for (const df of [-1, 1]) {
349
+ const pf = file + df;
350
+ if (pf < 0 || pf >= 8)
351
+ continue;
352
+ const pawnSq = pawnRank * 8 + pf;
353
+ const p = board.pieceAt(curBoard, pawnSq);
354
+ if (p && p.color === turn && p.role === Role.Pawn)
355
+ capturable = true;
356
+ }
357
+ if (!capturable)
358
+ return Err({ code: "fen/enPassantNotCapturable" });
359
+ }
360
+ }
361
+ // ----- halfmove -----
362
+ const half = fieldCount > 4 ? parseFenCount(fen, fs[4], fe[4]) : 0;
363
+ if (!Number.isInteger(half) || half < 0 || half > 150)
364
+ return Err({ code: "fen/invalidHalfmove" });
365
+ // ----- fullmove -----
366
+ const full = fieldCount > 5 ? parseFenCount(fen, fs[5], fe[5]) : 1;
367
+ if (!Number.isInteger(full) || full < 1)
368
+ return Err({ code: "fen/invalidFullmove" });
369
+ // ----- validations per purechess-rules -----
370
+ // pawn on back rank
371
+ for (let f = 0; f < 8; f++) {
372
+ const sq1 = f; // rank 1
373
+ const sq8 = 56 + f; // rank 8
374
+ const p1 = board.pieceAt(curBoard, sq1);
375
+ const p8 = board.pieceAt(curBoard, sq8);
376
+ if (p1 && p1.role === Role.Pawn)
377
+ return Err({ code: "fen/pawnOnBackRank" });
378
+ if (p8 && p8.role === Role.Pawn)
379
+ return Err({ code: "fen/pawnOnBackRank" });
380
+ }
381
+ // kings count
382
+ const whiteKings = sq.popcnt(sq.and(curBoard.white, curBoard.king));
383
+ const blackKings = sq.popcnt(sq.and(curBoard.black, curBoard.king));
384
+ const totalKings = sq.popcnt(curBoard.king);
385
+ if (totalKings !== 2 || whiteKings !== 1 || blackKings !== 1) {
386
+ return Err({ code: "fen/kingsCount" });
387
+ }
388
+ // kings adjacent
389
+ const wkSq = board.kingSquare(curBoard, Color.White);
390
+ const bkSq = board.kingSquare(curBoard, Color.Black);
391
+ if (wkSq !== undefined && bkSq !== undefined) {
392
+ const wAtt = attacks.kingAttacks(wkSq);
393
+ if (sq.has(wAtt, bkSq))
394
+ return Err({ code: "fen/kingsAdjacent" });
395
+ }
396
+ // oppositeCheck: side not to move king attacked
397
+ if (wkSq !== undefined && bkSq !== undefined) {
398
+ const whiteAttacked = attacks.isAttacked(curBoard, wkSq, Color.Black);
399
+ const blackAttacked = attacks.isAttacked(curBoard, bkSq, Color.White);
400
+ // illegal if both in check
401
+ if (whiteAttacked && blackAttacked)
402
+ return Err({ code: "fen/oppositeCheck" });
403
+ // illegal if opponent king is in check (side not to move)
404
+ if (turn === Color.White && blackAttacked)
405
+ return Err({ code: "fen/oppositeCheck" });
406
+ if (turn === Color.Black && whiteAttacked)
407
+ return Err({ code: "fen/oppositeCheck" });
408
+ }
409
+ // castling validation extra: if not chess960 and castling rights refer to missing rook/king not on original? For now skip strict
410
+ const setup = {
411
+ board: curBoard,
412
+ turn,
413
+ castling,
414
+ epSquare,
415
+ halfmoves: half,
416
+ fullmoves: full,
417
+ halfmove: half,
418
+ fullmove: full,
419
+ };
420
+ // Seed the initial Zobrist key when the Polyglot tables are already loaded
421
+ // (lazy-loading contract — see src/zobrist.ts); makeMove then maintains it
422
+ // incrementally in O(1). Positions parsed before loading carry no key.
423
+ if (zobristTablesLoaded()) {
424
+ const zk = calculateZobrist(setup);
425
+ setup.zobristLo = zk.lo;
426
+ setup.zobristHi = zk.hi;
427
+ }
428
+ return Ok(setup);
429
+ }
430
+ export function makeFen(setup, opts) {
431
+ const boardVal = setup.board;
432
+ // piece placement
433
+ let placement = "";
434
+ for (let r = 7; r >= 0; r--) {
435
+ let empty = 0;
436
+ let rankStr = "";
437
+ for (let f = 0; f < 8; f++) {
438
+ const sqIdx = r * 8 + f;
439
+ // occupancy + role/color via direct bit tests (no per-square pieceAt
440
+ // allocation — task 5.1)
441
+ if (!sq.has(boardVal.occupied, sqIdx)) {
442
+ empty++;
443
+ }
444
+ else {
445
+ if (empty > 0) {
446
+ rankStr += String(empty);
447
+ empty = 0;
448
+ }
449
+ const isWhite = sq.has(boardVal.white, sqIdx);
450
+ let ch;
451
+ if (sq.has(boardVal.pawn, sqIdx))
452
+ ch = isWhite ? "P" : "p";
453
+ else if (sq.has(boardVal.knight, sqIdx))
454
+ ch = isWhite ? "N" : "n";
455
+ else if (sq.has(boardVal.bishop, sqIdx))
456
+ ch = isWhite ? "B" : "b";
457
+ else if (sq.has(boardVal.rook, sqIdx))
458
+ ch = isWhite ? "R" : "r";
459
+ else if (sq.has(boardVal.queen, sqIdx))
460
+ ch = isWhite ? "Q" : "q";
461
+ else
462
+ ch = isWhite ? "K" : "k";
463
+ rankStr += ch;
464
+ }
465
+ }
466
+ if (empty > 0)
467
+ rankStr += String(empty);
468
+ placement += rankStr;
469
+ if (r > 0)
470
+ placement += "/";
471
+ }
472
+ const active = setup.turn === Color.White ? "w" : "b";
473
+ // castling
474
+ let castlingStr = "";
475
+ const chess960 = !!opts?.chess960;
476
+ const shredder = !!opts?.shredder;
477
+ const whiteSet = setup.castling.white;
478
+ const blackSet = setup.castling.black;
479
+ const hasWhite = whiteSet.size > 0;
480
+ const hasBlack = blackSet.size > 0;
481
+ if (!hasWhite && !hasBlack) {
482
+ castlingStr = "-";
483
+ }
484
+ else {
485
+ if (!chess960) {
486
+ // standard KQkq
487
+ if (whiteSet.has(7))
488
+ castlingStr += "K";
489
+ if (whiteSet.has(0))
490
+ castlingStr += "Q";
491
+ if (blackSet.has(63))
492
+ castlingStr += "k";
493
+ if (blackSet.has(56))
494
+ castlingStr += "q";
495
+ if (castlingStr === "")
496
+ castlingStr = "-";
497
+ }
498
+ else {
499
+ if (shredder) {
500
+ // Shredder: emit KQkq if rooks on standard squares else fallback to file letters
501
+ let emitted = false;
502
+ const canShredderWhiteK = whiteSet.has(7);
503
+ const canShredderWhiteQ = whiteSet.has(0);
504
+ const canShredderBlackK = blackSet.has(63);
505
+ const canShredderBlackQ = blackSet.has(56);
506
+ const isStandard = (canShredderWhiteK || canShredderWhiteQ || canShredderBlackK || canShredderBlackQ) &&
507
+ [...whiteSet].every(s => s === 7 || s === 0) &&
508
+ [...blackSet].every(s => s === 63 || s === 56);
509
+ if (isStandard) {
510
+ if (canShredderWhiteK)
511
+ castlingStr += "K";
512
+ if (canShredderWhiteQ)
513
+ castlingStr += "Q";
514
+ if (canShredderBlackK)
515
+ castlingStr += "k";
516
+ if (canShredderBlackQ)
517
+ castlingStr += "q";
518
+ emitted = true;
519
+ }
520
+ if (!emitted) {
521
+ // fallback to X-FEN
522
+ castlingStr = makeXFenString(setup);
523
+ }
524
+ if (castlingStr === "")
525
+ castlingStr = "-";
526
+ }
527
+ else {
528
+ castlingStr = makeXFenString(setup);
529
+ if (castlingStr === "")
530
+ castlingStr = "-";
531
+ }
532
+ }
533
+ }
534
+ const epStr = setup.epSquare === null || setup.epSquare === undefined ? "-" : squareName(setup.epSquare);
535
+ const half = String(setup.halfmoves ?? setup.halfmove ?? 0);
536
+ const full = String(setup.fullmoves ?? setup.fullmove ?? 1);
537
+ return `${placement} ${active} ${castlingStr} ${epStr} ${half} ${full}`;
538
+ }
539
+ function makeXFenString(setup) {
540
+ const boardVal = setup.board;
541
+ const wk = board.kingSquare(boardVal, Color.White);
542
+ const bk = board.kingSquare(boardVal, Color.Black);
543
+ let out = "";
544
+ // white: need to order king-side then queen-side
545
+ if (setup.castling.white.size > 0) {
546
+ let files = [];
547
+ for (const sqIdx of setup.castling.white)
548
+ files.push({ sq: sqIdx, file: squareFile(sqIdx) });
549
+ if (wk !== undefined) {
550
+ const kf = squareFile(wk);
551
+ // sort: king-side (file > kf) first then queen-side
552
+ const right = files.filter(x => x.file > kf).sort((a, b) => a.file - b.file);
553
+ const left = files.filter(x => x.file < kf).sort((a, b) => b.file - a.file); // maybe closest first?
554
+ // For standard, right = [7], left=[0] => H A
555
+ // For generic, we emit right files then left files
556
+ for (const r of right)
557
+ out += String.fromCharCode(65 + r.file);
558
+ for (const l of left)
559
+ out += String.fromCharCode(65 + l.file);
560
+ // if king not between? fallback sorted
561
+ if (right.length + left.length !== files.length) {
562
+ // some rook on same file as king? shouldn't happen
563
+ for (const f of files)
564
+ if (!right.includes(f) && !left.includes(f))
565
+ out += String.fromCharCode(65 + f.file);
566
+ }
567
+ }
568
+ else {
569
+ files.sort((a, b) => a.file - b.file);
570
+ for (const f of files)
571
+ out += String.fromCharCode(65 + f.file);
572
+ }
573
+ }
574
+ // black
575
+ if (setup.castling.black.size > 0) {
576
+ let files = [];
577
+ for (const sqIdx of setup.castling.black)
578
+ files.push({ sq: sqIdx, file: squareFile(sqIdx) });
579
+ if (bk !== undefined) {
580
+ const kf = squareFile(bk);
581
+ const right = files.filter(x => x.file > kf).sort((a, b) => a.file - b.file);
582
+ const left = files.filter(x => x.file < kf).sort((a, b) => b.file - a.file);
583
+ for (const r of right)
584
+ out += String.fromCharCode(97 + r.file);
585
+ for (const l of left)
586
+ out += String.fromCharCode(97 + l.file);
587
+ if (right.length + left.length !== files.length) {
588
+ for (const f of files)
589
+ if (!right.includes(f) && !left.includes(f))
590
+ out += String.fromCharCode(97 + f.file);
591
+ }
592
+ }
593
+ else {
594
+ files.sort((a, b) => a.file - b.file);
595
+ for (const f of files)
596
+ out += String.fromCharCode(97 + f.file);
597
+ }
598
+ }
599
+ return out;
600
+ }
@@ -0,0 +1,17 @@
1
+ export * from "./squareSet.js";
2
+ export * from "./board.js";
3
+ export * from "./types.js";
4
+ export * from "./util.js";
5
+ export * from "./fen.js";
6
+ export * from "./san.js";
7
+ export * from "./pgn.js";
8
+ export * from "./chess960.js";
9
+ export * from "./zobrist.js";
10
+ export * from "./packedMove.js";
11
+ export { knightAttacks, kingAttacks, pawnAttacks, bishopAttacks, rookAttacks, queenAttacks, ensureMagicTablesLoaded, magicTablesLoaded, ray, between, isAttacked, } from "./attacks.js";
12
+ export { kingAttackers } from "./attacks.js";
13
+ export { dests, allDests, detectCastling, isCheck, isCheckmate, isStalemate, isInsufficientMaterial, isFiftyMoveDraw, isSeventyFiveMoveDraw, isThreefoldRepetition, isLegal, perft, makeMove, play, INITIAL_FEN, } from "./chess.js";
14
+ export type { CastlingPlan } from "./chess.js";
15
+ export { pgnImport, buildTree, build, pgnExport, TreeWrapperImpl, } from "./chesstree.js";
16
+ export type { TreeWrapper, TreeNode, Path, Comment, Glyph, Clock, Shape, Eval as TreeEval, Game, Player, AnalyseData, } from "./chesstree.js";
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAGhC,OAAO,EACL,aAAa,EACb,WAAW,EACX,WAAW,EACX,aAAa,EACb,WAAW,EACX,YAAY,EACZ,uBAAuB,EACvB,iBAAiB,EACjB,GAAG,EACH,OAAO,EACP,UAAU,GACX,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C,OAAO,EACL,KAAK,EACL,QAAQ,EACR,cAAc,EACd,OAAO,EACP,WAAW,EACX,WAAW,EACX,sBAAsB,EACtB,eAAe,EACf,qBAAqB,EACrB,qBAAqB,EACrB,OAAO,EACP,KAAK,EACL,QAAQ,EACR,IAAI,EACJ,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,EACL,SAAS,EACT,SAAS,EACT,KAAK,EACL,SAAS,EACT,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EACV,WAAW,EACX,QAAQ,EACR,IAAI,EACJ,OAAO,EACP,KAAK,EACL,KAAK,EACL,KAAK,EACL,IAAI,IAAI,QAAQ,EAChB,IAAI,EACJ,MAAM,EACN,WAAW,GACZ,MAAM,gBAAgB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ // src/index.ts — turbochess full entry (MIT): the Unified Super API
2
+ // Re-exports all turbochess modules per spec (formerly purechess, ADR-015)
3
+ // and defines the root Unified `Chess` class (design D1): the ergonomic
4
+ // chess.js-superset core class extended with native tree navigation
5
+ // (`toTree`/`loadTree`), so `turbochess/core` stays free of PGN/tree code.
6
+ export * from "./squareSet.js";
7
+ export * from "./board.js";
8
+ export * from "./types.js";
9
+ export * from "./util.js";
10
+ export * from "./fen.js";
11
+ export * from "./san.js";
12
+ export * from "./pgn.js";
13
+ export * from "./chess960.js";
14
+ export * from "./zobrist.js";
15
+ export * from "./packedMove.js";
16
+ // attacks: explicit to avoid duplicate kingAttackers with chess
17
+ export { knightAttacks, kingAttacks, pawnAttacks, bishopAttacks, rookAttacks, queenAttacks, ensureMagicTablesLoaded, magicTablesLoaded, ray, between, isAttacked, } from "./attacks.js";
18
+ export { kingAttackers } from "./attacks.js";
19
+ // chess core (avoid duplicate Position and kingAttackers)
20
+ export { dests, allDests, detectCastling, isCheck, isCheckmate, isStalemate, isInsufficientMaterial, isFiftyMoveDraw, isSeventyFiveMoveDraw, isThreefoldRepetition, isLegal, perft, makeMove, play, INITIAL_FEN, } from "./chess.js";
21
+ // chesstree integration (tree shapes + analysis API, folded into the root)
22
+ export { pgnImport, buildTree, build, pgnExport, TreeWrapperImpl, } from "./chesstree.js";
@@ -0,0 +1,31 @@
1
+ import { Role } from "./types.js";
2
+ import type { Move } from "./types.js";
3
+ export type PackedMove = {
4
+ from: number;
5
+ to: number;
6
+ /** promotion code (0 = none, 1 = N, 2 = B, 3 = R, 4 = Q) */
7
+ promo: number;
8
+ };
9
+ /** moves2 promotion codes (NOT the Role enum — spec-mandated encoding). */
10
+ export declare const PROMO_NONE = 0;
11
+ export declare const PROMO_KNIGHT = 1;
12
+ export declare const PROMO_BISHOP = 2;
13
+ export declare const PROMO_ROOK = 3;
14
+ export declare const PROMO_QUEEN = 4;
15
+ /** Packs from/to/promo into one 16-bit word. */
16
+ export declare function packMove(from: number, to: number, promo?: number): number;
17
+ /** Unpacks a 16-bit word into its from/to/promo fields. */
18
+ export declare function unpackMove(word: number): PackedMove;
19
+ /** Role enum → moves2 promotion code. */
20
+ export declare function roleToPromoCode(role: Role): number;
21
+ /** moves2 promotion code → Role enum (undefined for PROMO_NONE). */
22
+ export declare function promoCodeToRole(code: number): Role | undefined;
23
+ /** Packs a Move into its 16-bit word (promotion flags are honored). */
24
+ export declare function packOf(move: Move): number;
25
+ /** Expands a 16-bit word into an engine Move (no legality interpretation). */
26
+ export declare function unpackToMove(word: number): Move;
27
+ /** Packs a move list into a flat Uint16Array (moves2 stream). */
28
+ export declare function movesToPacked(moves: readonly Move[]): Uint16Array;
29
+ /** Expands a moves2 stream (Uint16Array, or little-endian Uint8Array) into engine Moves. */
30
+ export declare function packedToMoves(buffer: Uint16Array | Uint8Array): Move[];
31
+ //# sourceMappingURL=packedMove.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"packedMove.d.ts","sourceRoot":"","sources":["../src/packedMove.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,MAAM,MAAM,UAAU,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,4DAA4D;IAC5D,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,UAAU,IAAI,CAAC;AAC5B,eAAO,MAAM,YAAY,IAAI,CAAC;AAC9B,eAAO,MAAM,YAAY,IAAI,CAAC;AAC9B,eAAO,MAAM,UAAU,IAAI,CAAC;AAC5B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,gDAAgD;AAChD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,GAAE,MAAmB,GAAG,MAAM,CAErF;AAED,2DAA2D;AAC3D,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAOnD;AAED,yCAAyC;AACzC,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAQlD;AAED,oEAAoE;AACpE,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAQ9D;AAED,uEAAuE;AACvE,wBAAgB,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAGzC;AAED,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAW/C;AAED,iEAAiE;AACjE,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,WAAW,CAIjE;AAED,4FAA4F;AAC5F,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,GAAG,UAAU,GAAG,IAAI,EAAE,CAatE"}