chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

chess.js (107052B)


      1 // @generated by Peggy 4.2.0.
      2 //
      3 // https://peggyjs.org/
      4 
      5 
      6 
      7   function rootNode(comment) {
      8   	return comment !== null ? { comment, variations: [] } : { variations: []}
      9   }
     10 
     11   function node(move, suffix, nag, comment, variations) {
     12   	const node = { move, variations };
     13 
     14     if (suffix) {
     15     	node.suffix = suffix;
     16     }
     17 
     18     if (nag) {
     19     	node.nag = nag;
     20     }
     21 
     22     if (comment !== null) {
     23     	node.comment = comment;
     24     }
     25 
     26     return node
     27   }
     28 
     29   function lineToTree(...nodes) {
     30   	const [root, ...rest] = nodes;
     31 
     32     let parent = root;
     33 
     34     for (const child of rest) {
     35     	if (child !== null) {
     36         	parent.variations = [child, ...child.variations];
     37             child.variations = [];
     38             parent = child;
     39         }
     40     }
     41 
     42   	return root
     43   }
     44 
     45   function pgn(headers, game) {
     46   	if (game.marker && game.marker.comment) {
     47     	let node = game.root;
     48         while (true) {
     49         	const next = node.variations[0];
     50             if (!next) {
     51             	node.comment = game.marker.comment;
     52             	break
     53             }
     54             node = next;
     55         }
     56     }
     57 
     58   	return {
     59     	headers,
     60         root: game.root,
     61         result: (game.marker && game.marker.result) ?? undefined
     62     }
     63   }
     64 
     65 function peg$subclass(child, parent) {
     66   function C() { this.constructor = child; }
     67   C.prototype = parent.prototype;
     68   child.prototype = new C();
     69 }
     70 
     71 function peg$SyntaxError(message, expected, found, location) {
     72   var self = Error.call(this, message);
     73   // istanbul ignore next Check is a necessary evil to support older environments
     74   if (Object.setPrototypeOf) {
     75     Object.setPrototypeOf(self, peg$SyntaxError.prototype);
     76   }
     77   self.expected = expected;
     78   self.found = found;
     79   self.location = location;
     80   self.name = "SyntaxError";
     81   return self;
     82 }
     83 
     84 peg$subclass(peg$SyntaxError, Error);
     85 
     86 function peg$padEnd(str, targetLength, padString) {
     87   padString = padString || " ";
     88   if (str.length > targetLength) { return str; }
     89   targetLength -= str.length;
     90   padString += padString.repeat(targetLength);
     91   return str + padString.slice(0, targetLength);
     92 }
     93 
     94 peg$SyntaxError.prototype.format = function(sources) {
     95   var str = "Error: " + this.message;
     96   if (this.location) {
     97     var src = null;
     98     var k;
     99     for (k = 0; k < sources.length; k++) {
    100       if (sources[k].source === this.location.source) {
    101         src = sources[k].text.split(/\r\n|\n|\r/g);
    102         break;
    103       }
    104     }
    105     var s = this.location.start;
    106     var offset_s = (this.location.source && (typeof this.location.source.offset === "function"))
    107       ? this.location.source.offset(s)
    108       : s;
    109     var loc = this.location.source + ":" + offset_s.line + ":" + offset_s.column;
    110     if (src) {
    111       var e = this.location.end;
    112       var filler = peg$padEnd("", offset_s.line.toString().length, ' ');
    113       var line = src[s.line - 1];
    114       var last = s.line === e.line ? e.column : line.length + 1;
    115       var hatLen = (last - s.column) || 1;
    116       str += "\n --> " + loc + "\n"
    117           + filler + " |\n"
    118           + offset_s.line + " | " + line + "\n"
    119           + filler + " | " + peg$padEnd("", s.column - 1, ' ')
    120           + peg$padEnd("", hatLen, "^");
    121     } else {
    122       str += "\n at " + loc;
    123     }
    124   }
    125   return str;
    126 };
    127 
    128 peg$SyntaxError.buildMessage = function(expected, found) {
    129   var DESCRIBE_EXPECTATION_FNS = {
    130     literal: function(expectation) {
    131       return "\"" + literalEscape(expectation.text) + "\"";
    132     },
    133 
    134     class: function(expectation) {
    135       var escapedParts = expectation.parts.map(function(part) {
    136         return Array.isArray(part)
    137           ? classEscape(part[0]) + "-" + classEscape(part[1])
    138           : classEscape(part);
    139       });
    140 
    141       return "[" + (expectation.inverted ? "^" : "") + escapedParts.join("") + "]";
    142     },
    143 
    144     any: function() {
    145       return "any character";
    146     },
    147 
    148     end: function() {
    149       return "end of input";
    150     },
    151 
    152     other: function(expectation) {
    153       return expectation.description;
    154     }
    155   };
    156 
    157   function hex(ch) {
    158     return ch.charCodeAt(0).toString(16).toUpperCase();
    159   }
    160 
    161   function literalEscape(s) {
    162     return s
    163       .replace(/\\/g, "\\\\")
    164       .replace(/"/g,  "\\\"")
    165       .replace(/\0/g, "\\0")
    166       .replace(/\t/g, "\\t")
    167       .replace(/\n/g, "\\n")
    168       .replace(/\r/g, "\\r")
    169       .replace(/[\x00-\x0F]/g,          function(ch) { return "\\x0" + hex(ch); })
    170       .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x"  + hex(ch); });
    171   }
    172 
    173   function classEscape(s) {
    174     return s
    175       .replace(/\\/g, "\\\\")
    176       .replace(/\]/g, "\\]")
    177       .replace(/\^/g, "\\^")
    178       .replace(/-/g,  "\\-")
    179       .replace(/\0/g, "\\0")
    180       .replace(/\t/g, "\\t")
    181       .replace(/\n/g, "\\n")
    182       .replace(/\r/g, "\\r")
    183       .replace(/[\x00-\x0F]/g,          function(ch) { return "\\x0" + hex(ch); })
    184       .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return "\\x"  + hex(ch); });
    185   }
    186 
    187   function describeExpectation(expectation) {
    188     return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
    189   }
    190 
    191   function describeExpected(expected) {
    192     var descriptions = expected.map(describeExpectation);
    193     var i, j;
    194 
    195     descriptions.sort();
    196 
    197     if (descriptions.length > 0) {
    198       for (i = 1, j = 1; i < descriptions.length; i++) {
    199         if (descriptions[i - 1] !== descriptions[i]) {
    200           descriptions[j] = descriptions[i];
    201           j++;
    202         }
    203       }
    204       descriptions.length = j;
    205     }
    206 
    207     switch (descriptions.length) {
    208       case 1:
    209         return descriptions[0];
    210 
    211       case 2:
    212         return descriptions[0] + " or " + descriptions[1];
    213 
    214       default:
    215         return descriptions.slice(0, -1).join(", ")
    216           + ", or "
    217           + descriptions[descriptions.length - 1];
    218     }
    219   }
    220 
    221   function describeFound(found) {
    222     return found ? "\"" + literalEscape(found) + "\"" : "end of input";
    223   }
    224 
    225   return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
    226 };
    227 
    228 function peg$parse(input, options) {
    229   options = options !== undefined ? options : {};
    230 
    231   var peg$FAILED = {};
    232   var peg$source = options.grammarSource;
    233 
    234   var peg$startRuleFunctions = { pgn: peg$parsepgn };
    235   var peg$startRuleFunction = peg$parsepgn;
    236 
    237   var peg$c0 = "[";
    238   var peg$c1 = "\"";
    239   var peg$c2 = "]";
    240   var peg$c3 = ".";
    241   var peg$c4 = "O-O-O";
    242   var peg$c5 = "O-O";
    243   var peg$c6 = "0-0-0";
    244   var peg$c7 = "0-0";
    245   var peg$c8 = "$";
    246   var peg$c9 = "{";
    247   var peg$c10 = "}";
    248   var peg$c11 = ";";
    249   var peg$c12 = "(";
    250   var peg$c13 = ")";
    251   var peg$c14 = "1-0";
    252   var peg$c15 = "0-1";
    253   var peg$c16 = "1/2-1/2";
    254   var peg$c17 = "*";
    255 
    256   var peg$r0 = /^[a-zA-Z]/;
    257   var peg$r1 = /^[^"]/;
    258   var peg$r2 = /^[0-9]/;
    259   var peg$r3 = /^[.]/;
    260   var peg$r4 = /^[a-zA-Z1-8\-=]/;
    261   var peg$r5 = /^[+#]/;
    262   var peg$r6 = /^[!?]/;
    263   var peg$r7 = /^[^}]/;
    264   var peg$r8 = /^[^\r\n]/;
    265   var peg$r9 = /^[ \t\r\n]/;
    266 
    267   var peg$e0 = peg$otherExpectation("tag pair");
    268   var peg$e1 = peg$literalExpectation("[", false);
    269   var peg$e2 = peg$literalExpectation("\"", false);
    270   var peg$e3 = peg$literalExpectation("]", false);
    271   var peg$e4 = peg$otherExpectation("tag name");
    272   var peg$e5 = peg$classExpectation([["a", "z"], ["A", "Z"]], false, false);
    273   var peg$e6 = peg$otherExpectation("tag value");
    274   var peg$e7 = peg$classExpectation(["\""], true, false);
    275   var peg$e8 = peg$otherExpectation("move number");
    276   var peg$e9 = peg$classExpectation([["0", "9"]], false, false);
    277   var peg$e10 = peg$literalExpectation(".", false);
    278   var peg$e11 = peg$classExpectation(["."], false, false);
    279   var peg$e12 = peg$otherExpectation("standard algebraic notation");
    280   var peg$e13 = peg$literalExpectation("O-O-O", false);
    281   var peg$e14 = peg$literalExpectation("O-O", false);
    282   var peg$e15 = peg$literalExpectation("0-0-0", false);
    283   var peg$e16 = peg$literalExpectation("0-0", false);
    284   var peg$e17 = peg$classExpectation([["a", "z"], ["A", "Z"], ["1", "8"], "-", "="], false, false);
    285   var peg$e18 = peg$classExpectation(["+", "#"], false, false);
    286   var peg$e19 = peg$otherExpectation("suffix annotation");
    287   var peg$e20 = peg$classExpectation(["!", "?"], false, false);
    288   var peg$e21 = peg$otherExpectation("NAG");
    289   var peg$e22 = peg$literalExpectation("$", false);
    290   var peg$e23 = peg$otherExpectation("brace comment");
    291   var peg$e24 = peg$literalExpectation("{", false);
    292   var peg$e25 = peg$classExpectation(["}"], true, false);
    293   var peg$e26 = peg$literalExpectation("}", false);
    294   var peg$e27 = peg$otherExpectation("rest of line comment");
    295   var peg$e28 = peg$literalExpectation(";", false);
    296   var peg$e29 = peg$classExpectation(["\r", "\n"], true, false);
    297   var peg$e30 = peg$otherExpectation("variation");
    298   var peg$e31 = peg$literalExpectation("(", false);
    299   var peg$e32 = peg$literalExpectation(")", false);
    300   var peg$e33 = peg$otherExpectation("game termination marker");
    301   var peg$e34 = peg$literalExpectation("1-0", false);
    302   var peg$e35 = peg$literalExpectation("0-1", false);
    303   var peg$e36 = peg$literalExpectation("1/2-1/2", false);
    304   var peg$e37 = peg$literalExpectation("*", false);
    305   var peg$e38 = peg$otherExpectation("whitespace");
    306   var peg$e39 = peg$classExpectation([" ", "\t", "\r", "\n"], false, false);
    307 
    308   var peg$f0 = function(headers, game) { return pgn(headers, game) };
    309   var peg$f1 = function(tagPairs) { return Object.fromEntries(tagPairs) };
    310   var peg$f2 = function(tagName, tagValue) { return [tagName, tagValue] };
    311   var peg$f3 = function(root, marker) { return { root, marker} };
    312   var peg$f4 = function(comment, moves) { return lineToTree(rootNode(comment), ...moves.flat()) };
    313   var peg$f5 = function(san, suffix, nag, comment, variations) { return node(san, suffix, nag, comment, variations) };
    314   var peg$f6 = function(nag) { return nag };
    315   var peg$f7 = function(comment) { return comment.replace(/[\r\n]+/g, " ") };
    316   var peg$f8 = function(comment) { return comment.trim() };
    317   var peg$f9 = function(line) { return line };
    318   var peg$f10 = function(result, comment) { return { result, comment } };
    319   var peg$currPos = options.peg$currPos | 0;
    320   var peg$posDetailsCache = [{ line: 1, column: 1 }];
    321   var peg$maxFailPos = peg$currPos;
    322   var peg$maxFailExpected = options.peg$maxFailExpected || [];
    323   var peg$silentFails = options.peg$silentFails | 0;
    324 
    325   var peg$result;
    326 
    327   if (options.startRule) {
    328     if (!(options.startRule in peg$startRuleFunctions)) {
    329       throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
    330     }
    331 
    332     peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
    333   }
    334 
    335   function peg$literalExpectation(text, ignoreCase) {
    336     return { type: "literal", text: text, ignoreCase: ignoreCase };
    337   }
    338 
    339   function peg$classExpectation(parts, inverted, ignoreCase) {
    340     return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase };
    341   }
    342 
    343   function peg$endExpectation() {
    344     return { type: "end" };
    345   }
    346 
    347   function peg$otherExpectation(description) {
    348     return { type: "other", description: description };
    349   }
    350 
    351   function peg$computePosDetails(pos) {
    352     var details = peg$posDetailsCache[pos];
    353     var p;
    354 
    355     if (details) {
    356       return details;
    357     } else {
    358       if (pos >= peg$posDetailsCache.length) {
    359         p = peg$posDetailsCache.length - 1;
    360       } else {
    361         p = pos;
    362         while (!peg$posDetailsCache[--p]) {}
    363       }
    364 
    365       details = peg$posDetailsCache[p];
    366       details = {
    367         line: details.line,
    368         column: details.column
    369       };
    370 
    371       while (p < pos) {
    372         if (input.charCodeAt(p) === 10) {
    373           details.line++;
    374           details.column = 1;
    375         } else {
    376           details.column++;
    377         }
    378 
    379         p++;
    380       }
    381 
    382       peg$posDetailsCache[pos] = details;
    383 
    384       return details;
    385     }
    386   }
    387 
    388   function peg$computeLocation(startPos, endPos, offset) {
    389     var startPosDetails = peg$computePosDetails(startPos);
    390     var endPosDetails = peg$computePosDetails(endPos);
    391 
    392     var res = {
    393       source: peg$source,
    394       start: {
    395         offset: startPos,
    396         line: startPosDetails.line,
    397         column: startPosDetails.column
    398       },
    399       end: {
    400         offset: endPos,
    401         line: endPosDetails.line,
    402         column: endPosDetails.column
    403       }
    404     };
    405     return res;
    406   }
    407 
    408   function peg$fail(expected) {
    409     if (peg$currPos < peg$maxFailPos) { return; }
    410 
    411     if (peg$currPos > peg$maxFailPos) {
    412       peg$maxFailPos = peg$currPos;
    413       peg$maxFailExpected = [];
    414     }
    415 
    416     peg$maxFailExpected.push(expected);
    417   }
    418 
    419   function peg$buildStructuredError(expected, found, location) {
    420     return new peg$SyntaxError(
    421       peg$SyntaxError.buildMessage(expected, found),
    422       expected,
    423       found,
    424       location
    425     );
    426   }
    427 
    428   function peg$parsepgn() {
    429     var s0, s1, s2;
    430 
    431     s0 = peg$currPos;
    432     s1 = peg$parsetagPairSection();
    433     s2 = peg$parsemoveTextSection();
    434     s0 = peg$f0(s1, s2);
    435 
    436     return s0;
    437   }
    438 
    439   function peg$parsetagPairSection() {
    440     var s0, s1, s2;
    441 
    442     s0 = peg$currPos;
    443     s1 = [];
    444     s2 = peg$parsetagPair();
    445     while (s2 !== peg$FAILED) {
    446       s1.push(s2);
    447       s2 = peg$parsetagPair();
    448     }
    449     s2 = peg$parse_();
    450     s0 = peg$f1(s1);
    451 
    452     return s0;
    453   }
    454 
    455   function peg$parsetagPair() {
    456     var s0, s2, s4, s6, s7, s8, s10;
    457 
    458     peg$silentFails++;
    459     s0 = peg$currPos;
    460     peg$parse_();
    461     if (input.charCodeAt(peg$currPos) === 91) {
    462       s2 = peg$c0;
    463       peg$currPos++;
    464     } else {
    465       s2 = peg$FAILED;
    466       if (peg$silentFails === 0) { peg$fail(peg$e1); }
    467     }
    468     if (s2 !== peg$FAILED) {
    469       peg$parse_();
    470       s4 = peg$parsetagName();
    471       if (s4 !== peg$FAILED) {
    472         peg$parse_();
    473         if (input.charCodeAt(peg$currPos) === 34) {
    474           s6 = peg$c1;
    475           peg$currPos++;
    476         } else {
    477           s6 = peg$FAILED;
    478           if (peg$silentFails === 0) { peg$fail(peg$e2); }
    479         }
    480         if (s6 !== peg$FAILED) {
    481           s7 = peg$parsetagValue();
    482           if (input.charCodeAt(peg$currPos) === 34) {
    483             s8 = peg$c1;
    484             peg$currPos++;
    485           } else {
    486             s8 = peg$FAILED;
    487             if (peg$silentFails === 0) { peg$fail(peg$e2); }
    488           }
    489           if (s8 !== peg$FAILED) {
    490             peg$parse_();
    491             if (input.charCodeAt(peg$currPos) === 93) {
    492               s10 = peg$c2;
    493               peg$currPos++;
    494             } else {
    495               s10 = peg$FAILED;
    496               if (peg$silentFails === 0) { peg$fail(peg$e3); }
    497             }
    498             if (s10 !== peg$FAILED) {
    499               s0 = peg$f2(s4, s7);
    500             } else {
    501               peg$currPos = s0;
    502               s0 = peg$FAILED;
    503             }
    504           } else {
    505             peg$currPos = s0;
    506             s0 = peg$FAILED;
    507           }
    508         } else {
    509           peg$currPos = s0;
    510           s0 = peg$FAILED;
    511         }
    512       } else {
    513         peg$currPos = s0;
    514         s0 = peg$FAILED;
    515       }
    516     } else {
    517       peg$currPos = s0;
    518       s0 = peg$FAILED;
    519     }
    520     peg$silentFails--;
    521     if (s0 === peg$FAILED) {
    522       if (peg$silentFails === 0) { peg$fail(peg$e0); }
    523     }
    524 
    525     return s0;
    526   }
    527 
    528   function peg$parsetagName() {
    529     var s0, s1, s2;
    530 
    531     peg$silentFails++;
    532     s0 = peg$currPos;
    533     s1 = [];
    534     s2 = input.charAt(peg$currPos);
    535     if (peg$r0.test(s2)) {
    536       peg$currPos++;
    537     } else {
    538       s2 = peg$FAILED;
    539       if (peg$silentFails === 0) { peg$fail(peg$e5); }
    540     }
    541     if (s2 !== peg$FAILED) {
    542       while (s2 !== peg$FAILED) {
    543         s1.push(s2);
    544         s2 = input.charAt(peg$currPos);
    545         if (peg$r0.test(s2)) {
    546           peg$currPos++;
    547         } else {
    548           s2 = peg$FAILED;
    549           if (peg$silentFails === 0) { peg$fail(peg$e5); }
    550         }
    551       }
    552     } else {
    553       s1 = peg$FAILED;
    554     }
    555     if (s1 !== peg$FAILED) {
    556       s0 = input.substring(s0, peg$currPos);
    557     } else {
    558       s0 = s1;
    559     }
    560     peg$silentFails--;
    561     if (s0 === peg$FAILED) {
    562       s1 = peg$FAILED;
    563       if (peg$silentFails === 0) { peg$fail(peg$e4); }
    564     }
    565 
    566     return s0;
    567   }
    568 
    569   function peg$parsetagValue() {
    570     var s0, s1, s2;
    571 
    572     peg$silentFails++;
    573     s0 = peg$currPos;
    574     s1 = [];
    575     s2 = input.charAt(peg$currPos);
    576     if (peg$r1.test(s2)) {
    577       peg$currPos++;
    578     } else {
    579       s2 = peg$FAILED;
    580       if (peg$silentFails === 0) { peg$fail(peg$e7); }
    581     }
    582     while (s2 !== peg$FAILED) {
    583       s1.push(s2);
    584       s2 = input.charAt(peg$currPos);
    585       if (peg$r1.test(s2)) {
    586         peg$currPos++;
    587       } else {
    588         s2 = peg$FAILED;
    589         if (peg$silentFails === 0) { peg$fail(peg$e7); }
    590       }
    591     }
    592     s0 = input.substring(s0, peg$currPos);
    593     peg$silentFails--;
    594     s1 = peg$FAILED;
    595     if (peg$silentFails === 0) { peg$fail(peg$e6); }
    596 
    597     return s0;
    598   }
    599 
    600   function peg$parsemoveTextSection() {
    601     var s0, s1, s3;
    602 
    603     s0 = peg$currPos;
    604     s1 = peg$parseline();
    605     peg$parse_();
    606     s3 = peg$parsegameTerminationMarker();
    607     if (s3 === peg$FAILED) {
    608       s3 = null;
    609     }
    610     peg$parse_();
    611     s0 = peg$f3(s1, s3);
    612 
    613     return s0;
    614   }
    615 
    616   function peg$parseline() {
    617     var s0, s1, s2, s3;
    618 
    619     s0 = peg$currPos;
    620     s1 = peg$parsecomment();
    621     if (s1 === peg$FAILED) {
    622       s1 = null;
    623     }
    624     s2 = [];
    625     s3 = peg$parsemove();
    626     while (s3 !== peg$FAILED) {
    627       s2.push(s3);
    628       s3 = peg$parsemove();
    629     }
    630     s0 = peg$f4(s1, s2);
    631 
    632     return s0;
    633   }
    634 
    635   function peg$parsemove() {
    636     var s0, s4, s5, s6, s7, s8, s9, s10;
    637 
    638     s0 = peg$currPos;
    639     peg$parse_();
    640     peg$parsemoveNumber();
    641     peg$parse_();
    642     s4 = peg$parsesan();
    643     if (s4 !== peg$FAILED) {
    644       s5 = peg$parsesuffixAnnotation();
    645       if (s5 === peg$FAILED) {
    646         s5 = null;
    647       }
    648       s6 = [];
    649       s7 = peg$parsenag();
    650       while (s7 !== peg$FAILED) {
    651         s6.push(s7);
    652         s7 = peg$parsenag();
    653       }
    654       s7 = peg$parse_();
    655       s8 = peg$parsecomment();
    656       if (s8 === peg$FAILED) {
    657         s8 = null;
    658       }
    659       s9 = [];
    660       s10 = peg$parsevariation();
    661       while (s10 !== peg$FAILED) {
    662         s9.push(s10);
    663         s10 = peg$parsevariation();
    664       }
    665       s0 = peg$f5(s4, s5, s6, s8, s9);
    666     } else {
    667       peg$currPos = s0;
    668       s0 = peg$FAILED;
    669     }
    670 
    671     return s0;
    672   }
    673 
    674   function peg$parsemoveNumber() {
    675     var s0, s1, s2, s3, s4, s5;
    676 
    677     peg$silentFails++;
    678     s0 = peg$currPos;
    679     s1 = [];
    680     s2 = input.charAt(peg$currPos);
    681     if (peg$r2.test(s2)) {
    682       peg$currPos++;
    683     } else {
    684       s2 = peg$FAILED;
    685       if (peg$silentFails === 0) { peg$fail(peg$e9); }
    686     }
    687     while (s2 !== peg$FAILED) {
    688       s1.push(s2);
    689       s2 = input.charAt(peg$currPos);
    690       if (peg$r2.test(s2)) {
    691         peg$currPos++;
    692       } else {
    693         s2 = peg$FAILED;
    694         if (peg$silentFails === 0) { peg$fail(peg$e9); }
    695       }
    696     }
    697     if (input.charCodeAt(peg$currPos) === 46) {
    698       s2 = peg$c3;
    699       peg$currPos++;
    700     } else {
    701       s2 = peg$FAILED;
    702       if (peg$silentFails === 0) { peg$fail(peg$e10); }
    703     }
    704     if (s2 !== peg$FAILED) {
    705       s3 = peg$parse_();
    706       s4 = [];
    707       s5 = input.charAt(peg$currPos);
    708       if (peg$r3.test(s5)) {
    709         peg$currPos++;
    710       } else {
    711         s5 = peg$FAILED;
    712         if (peg$silentFails === 0) { peg$fail(peg$e11); }
    713       }
    714       while (s5 !== peg$FAILED) {
    715         s4.push(s5);
    716         s5 = input.charAt(peg$currPos);
    717         if (peg$r3.test(s5)) {
    718           peg$currPos++;
    719         } else {
    720           s5 = peg$FAILED;
    721           if (peg$silentFails === 0) { peg$fail(peg$e11); }
    722         }
    723       }
    724       s1 = [s1, s2, s3, s4];
    725       s0 = s1;
    726     } else {
    727       peg$currPos = s0;
    728       s0 = peg$FAILED;
    729     }
    730     peg$silentFails--;
    731     if (s0 === peg$FAILED) {
    732       s1 = peg$FAILED;
    733       if (peg$silentFails === 0) { peg$fail(peg$e8); }
    734     }
    735 
    736     return s0;
    737   }
    738 
    739   function peg$parsesan() {
    740     var s0, s1, s2, s3, s4, s5;
    741 
    742     peg$silentFails++;
    743     s0 = peg$currPos;
    744     s1 = peg$currPos;
    745     if (input.substr(peg$currPos, 5) === peg$c4) {
    746       s2 = peg$c4;
    747       peg$currPos += 5;
    748     } else {
    749       s2 = peg$FAILED;
    750       if (peg$silentFails === 0) { peg$fail(peg$e13); }
    751     }
    752     if (s2 === peg$FAILED) {
    753       if (input.substr(peg$currPos, 3) === peg$c5) {
    754         s2 = peg$c5;
    755         peg$currPos += 3;
    756       } else {
    757         s2 = peg$FAILED;
    758         if (peg$silentFails === 0) { peg$fail(peg$e14); }
    759       }
    760       if (s2 === peg$FAILED) {
    761         if (input.substr(peg$currPos, 5) === peg$c6) {
    762           s2 = peg$c6;
    763           peg$currPos += 5;
    764         } else {
    765           s2 = peg$FAILED;
    766           if (peg$silentFails === 0) { peg$fail(peg$e15); }
    767         }
    768         if (s2 === peg$FAILED) {
    769           if (input.substr(peg$currPos, 3) === peg$c7) {
    770             s2 = peg$c7;
    771             peg$currPos += 3;
    772           } else {
    773             s2 = peg$FAILED;
    774             if (peg$silentFails === 0) { peg$fail(peg$e16); }
    775           }
    776           if (s2 === peg$FAILED) {
    777             s2 = peg$currPos;
    778             s3 = input.charAt(peg$currPos);
    779             if (peg$r0.test(s3)) {
    780               peg$currPos++;
    781             } else {
    782               s3 = peg$FAILED;
    783               if (peg$silentFails === 0) { peg$fail(peg$e5); }
    784             }
    785             if (s3 !== peg$FAILED) {
    786               s4 = [];
    787               s5 = input.charAt(peg$currPos);
    788               if (peg$r4.test(s5)) {
    789                 peg$currPos++;
    790               } else {
    791                 s5 = peg$FAILED;
    792                 if (peg$silentFails === 0) { peg$fail(peg$e17); }
    793               }
    794               if (s5 !== peg$FAILED) {
    795                 while (s5 !== peg$FAILED) {
    796                   s4.push(s5);
    797                   s5 = input.charAt(peg$currPos);
    798                   if (peg$r4.test(s5)) {
    799                     peg$currPos++;
    800                   } else {
    801                     s5 = peg$FAILED;
    802                     if (peg$silentFails === 0) { peg$fail(peg$e17); }
    803                   }
    804                 }
    805               } else {
    806                 s4 = peg$FAILED;
    807               }
    808               if (s4 !== peg$FAILED) {
    809                 s3 = [s3, s4];
    810                 s2 = s3;
    811               } else {
    812                 peg$currPos = s2;
    813                 s2 = peg$FAILED;
    814               }
    815             } else {
    816               peg$currPos = s2;
    817               s2 = peg$FAILED;
    818             }
    819           }
    820         }
    821       }
    822     }
    823     if (s2 !== peg$FAILED) {
    824       s3 = input.charAt(peg$currPos);
    825       if (peg$r5.test(s3)) {
    826         peg$currPos++;
    827       } else {
    828         s3 = peg$FAILED;
    829         if (peg$silentFails === 0) { peg$fail(peg$e18); }
    830       }
    831       if (s3 === peg$FAILED) {
    832         s3 = null;
    833       }
    834       s2 = [s2, s3];
    835       s1 = s2;
    836     } else {
    837       peg$currPos = s1;
    838       s1 = peg$FAILED;
    839     }
    840     if (s1 !== peg$FAILED) {
    841       s0 = input.substring(s0, peg$currPos);
    842     } else {
    843       s0 = s1;
    844     }
    845     peg$silentFails--;
    846     if (s0 === peg$FAILED) {
    847       s1 = peg$FAILED;
    848       if (peg$silentFails === 0) { peg$fail(peg$e12); }
    849     }
    850 
    851     return s0;
    852   }
    853 
    854   function peg$parsesuffixAnnotation() {
    855     var s0, s1, s2;
    856 
    857     peg$silentFails++;
    858     s0 = peg$currPos;
    859     s1 = [];
    860     s2 = input.charAt(peg$currPos);
    861     if (peg$r6.test(s2)) {
    862       peg$currPos++;
    863     } else {
    864       s2 = peg$FAILED;
    865       if (peg$silentFails === 0) { peg$fail(peg$e20); }
    866     }
    867     while (s2 !== peg$FAILED) {
    868       s1.push(s2);
    869       if (s1.length >= 2) {
    870         s2 = peg$FAILED;
    871       } else {
    872         s2 = input.charAt(peg$currPos);
    873         if (peg$r6.test(s2)) {
    874           peg$currPos++;
    875         } else {
    876           s2 = peg$FAILED;
    877           if (peg$silentFails === 0) { peg$fail(peg$e20); }
    878         }
    879       }
    880     }
    881     if (s1.length < 1) {
    882       peg$currPos = s0;
    883       s0 = peg$FAILED;
    884     } else {
    885       s0 = s1;
    886     }
    887     peg$silentFails--;
    888     if (s0 === peg$FAILED) {
    889       s1 = peg$FAILED;
    890       if (peg$silentFails === 0) { peg$fail(peg$e19); }
    891     }
    892 
    893     return s0;
    894   }
    895 
    896   function peg$parsenag() {
    897     var s0, s2, s3, s4, s5;
    898 
    899     peg$silentFails++;
    900     s0 = peg$currPos;
    901     peg$parse_();
    902     if (input.charCodeAt(peg$currPos) === 36) {
    903       s2 = peg$c8;
    904       peg$currPos++;
    905     } else {
    906       s2 = peg$FAILED;
    907       if (peg$silentFails === 0) { peg$fail(peg$e22); }
    908     }
    909     if (s2 !== peg$FAILED) {
    910       s3 = peg$currPos;
    911       s4 = [];
    912       s5 = input.charAt(peg$currPos);
    913       if (peg$r2.test(s5)) {
    914         peg$currPos++;
    915       } else {
    916         s5 = peg$FAILED;
    917         if (peg$silentFails === 0) { peg$fail(peg$e9); }
    918       }
    919       if (s5 !== peg$FAILED) {
    920         while (s5 !== peg$FAILED) {
    921           s4.push(s5);
    922           s5 = input.charAt(peg$currPos);
    923           if (peg$r2.test(s5)) {
    924             peg$currPos++;
    925           } else {
    926             s5 = peg$FAILED;
    927             if (peg$silentFails === 0) { peg$fail(peg$e9); }
    928           }
    929         }
    930       } else {
    931         s4 = peg$FAILED;
    932       }
    933       if (s4 !== peg$FAILED) {
    934         s3 = input.substring(s3, peg$currPos);
    935       } else {
    936         s3 = s4;
    937       }
    938       if (s3 !== peg$FAILED) {
    939         s0 = peg$f6(s3);
    940       } else {
    941         peg$currPos = s0;
    942         s0 = peg$FAILED;
    943       }
    944     } else {
    945       peg$currPos = s0;
    946       s0 = peg$FAILED;
    947     }
    948     peg$silentFails--;
    949     if (s0 === peg$FAILED) {
    950       if (peg$silentFails === 0) { peg$fail(peg$e21); }
    951     }
    952 
    953     return s0;
    954   }
    955 
    956   function peg$parsecomment() {
    957     var s0;
    958 
    959     s0 = peg$parsebraceComment();
    960     if (s0 === peg$FAILED) {
    961       s0 = peg$parserestOfLineComment();
    962     }
    963 
    964     return s0;
    965   }
    966 
    967   function peg$parsebraceComment() {
    968     var s0, s1, s2, s3, s4;
    969 
    970     peg$silentFails++;
    971     s0 = peg$currPos;
    972     if (input.charCodeAt(peg$currPos) === 123) {
    973       s1 = peg$c9;
    974       peg$currPos++;
    975     } else {
    976       s1 = peg$FAILED;
    977       if (peg$silentFails === 0) { peg$fail(peg$e24); }
    978     }
    979     if (s1 !== peg$FAILED) {
    980       s2 = peg$currPos;
    981       s3 = [];
    982       s4 = input.charAt(peg$currPos);
    983       if (peg$r7.test(s4)) {
    984         peg$currPos++;
    985       } else {
    986         s4 = peg$FAILED;
    987         if (peg$silentFails === 0) { peg$fail(peg$e25); }
    988       }
    989       while (s4 !== peg$FAILED) {
    990         s3.push(s4);
    991         s4 = input.charAt(peg$currPos);
    992         if (peg$r7.test(s4)) {
    993           peg$currPos++;
    994         } else {
    995           s4 = peg$FAILED;
    996           if (peg$silentFails === 0) { peg$fail(peg$e25); }
    997         }
    998       }
    999       s2 = input.substring(s2, peg$currPos);
   1000       if (input.charCodeAt(peg$currPos) === 125) {
   1001         s3 = peg$c10;
   1002         peg$currPos++;
   1003       } else {
   1004         s3 = peg$FAILED;
   1005         if (peg$silentFails === 0) { peg$fail(peg$e26); }
   1006       }
   1007       if (s3 !== peg$FAILED) {
   1008         s0 = peg$f7(s2);
   1009       } else {
   1010         peg$currPos = s0;
   1011         s0 = peg$FAILED;
   1012       }
   1013     } else {
   1014       peg$currPos = s0;
   1015       s0 = peg$FAILED;
   1016     }
   1017     peg$silentFails--;
   1018     if (s0 === peg$FAILED) {
   1019       s1 = peg$FAILED;
   1020       if (peg$silentFails === 0) { peg$fail(peg$e23); }
   1021     }
   1022 
   1023     return s0;
   1024   }
   1025 
   1026   function peg$parserestOfLineComment() {
   1027     var s0, s1, s2, s3, s4;
   1028 
   1029     peg$silentFails++;
   1030     s0 = peg$currPos;
   1031     if (input.charCodeAt(peg$currPos) === 59) {
   1032       s1 = peg$c11;
   1033       peg$currPos++;
   1034     } else {
   1035       s1 = peg$FAILED;
   1036       if (peg$silentFails === 0) { peg$fail(peg$e28); }
   1037     }
   1038     if (s1 !== peg$FAILED) {
   1039       s2 = peg$currPos;
   1040       s3 = [];
   1041       s4 = input.charAt(peg$currPos);
   1042       if (peg$r8.test(s4)) {
   1043         peg$currPos++;
   1044       } else {
   1045         s4 = peg$FAILED;
   1046         if (peg$silentFails === 0) { peg$fail(peg$e29); }
   1047       }
   1048       while (s4 !== peg$FAILED) {
   1049         s3.push(s4);
   1050         s4 = input.charAt(peg$currPos);
   1051         if (peg$r8.test(s4)) {
   1052           peg$currPos++;
   1053         } else {
   1054           s4 = peg$FAILED;
   1055           if (peg$silentFails === 0) { peg$fail(peg$e29); }
   1056         }
   1057       }
   1058       s2 = input.substring(s2, peg$currPos);
   1059       s0 = peg$f8(s2);
   1060     } else {
   1061       peg$currPos = s0;
   1062       s0 = peg$FAILED;
   1063     }
   1064     peg$silentFails--;
   1065     if (s0 === peg$FAILED) {
   1066       s1 = peg$FAILED;
   1067       if (peg$silentFails === 0) { peg$fail(peg$e27); }
   1068     }
   1069 
   1070     return s0;
   1071   }
   1072 
   1073   function peg$parsevariation() {
   1074     var s0, s2, s3, s5;
   1075 
   1076     peg$silentFails++;
   1077     s0 = peg$currPos;
   1078     peg$parse_();
   1079     if (input.charCodeAt(peg$currPos) === 40) {
   1080       s2 = peg$c12;
   1081       peg$currPos++;
   1082     } else {
   1083       s2 = peg$FAILED;
   1084       if (peg$silentFails === 0) { peg$fail(peg$e31); }
   1085     }
   1086     if (s2 !== peg$FAILED) {
   1087       s3 = peg$parseline();
   1088       if (s3 !== peg$FAILED) {
   1089         peg$parse_();
   1090         if (input.charCodeAt(peg$currPos) === 41) {
   1091           s5 = peg$c13;
   1092           peg$currPos++;
   1093         } else {
   1094           s5 = peg$FAILED;
   1095           if (peg$silentFails === 0) { peg$fail(peg$e32); }
   1096         }
   1097         if (s5 !== peg$FAILED) {
   1098           s0 = peg$f9(s3);
   1099         } else {
   1100           peg$currPos = s0;
   1101           s0 = peg$FAILED;
   1102         }
   1103       } else {
   1104         peg$currPos = s0;
   1105         s0 = peg$FAILED;
   1106       }
   1107     } else {
   1108       peg$currPos = s0;
   1109       s0 = peg$FAILED;
   1110     }
   1111     peg$silentFails--;
   1112     if (s0 === peg$FAILED) {
   1113       if (peg$silentFails === 0) { peg$fail(peg$e30); }
   1114     }
   1115 
   1116     return s0;
   1117   }
   1118 
   1119   function peg$parsegameTerminationMarker() {
   1120     var s0, s1, s3;
   1121 
   1122     peg$silentFails++;
   1123     s0 = peg$currPos;
   1124     if (input.substr(peg$currPos, 3) === peg$c14) {
   1125       s1 = peg$c14;
   1126       peg$currPos += 3;
   1127     } else {
   1128       s1 = peg$FAILED;
   1129       if (peg$silentFails === 0) { peg$fail(peg$e34); }
   1130     }
   1131     if (s1 === peg$FAILED) {
   1132       if (input.substr(peg$currPos, 3) === peg$c15) {
   1133         s1 = peg$c15;
   1134         peg$currPos += 3;
   1135       } else {
   1136         s1 = peg$FAILED;
   1137         if (peg$silentFails === 0) { peg$fail(peg$e35); }
   1138       }
   1139       if (s1 === peg$FAILED) {
   1140         if (input.substr(peg$currPos, 7) === peg$c16) {
   1141           s1 = peg$c16;
   1142           peg$currPos += 7;
   1143         } else {
   1144           s1 = peg$FAILED;
   1145           if (peg$silentFails === 0) { peg$fail(peg$e36); }
   1146         }
   1147         if (s1 === peg$FAILED) {
   1148           if (input.charCodeAt(peg$currPos) === 42) {
   1149             s1 = peg$c17;
   1150             peg$currPos++;
   1151           } else {
   1152             s1 = peg$FAILED;
   1153             if (peg$silentFails === 0) { peg$fail(peg$e37); }
   1154           }
   1155         }
   1156       }
   1157     }
   1158     if (s1 !== peg$FAILED) {
   1159       peg$parse_();
   1160       s3 = peg$parsecomment();
   1161       if (s3 === peg$FAILED) {
   1162         s3 = null;
   1163       }
   1164       s0 = peg$f10(s1, s3);
   1165     } else {
   1166       peg$currPos = s0;
   1167       s0 = peg$FAILED;
   1168     }
   1169     peg$silentFails--;
   1170     if (s0 === peg$FAILED) {
   1171       s1 = peg$FAILED;
   1172       if (peg$silentFails === 0) { peg$fail(peg$e33); }
   1173     }
   1174 
   1175     return s0;
   1176   }
   1177 
   1178   function peg$parse_() {
   1179     var s0, s1;
   1180 
   1181     peg$silentFails++;
   1182     s0 = [];
   1183     s1 = input.charAt(peg$currPos);
   1184     if (peg$r9.test(s1)) {
   1185       peg$currPos++;
   1186     } else {
   1187       s1 = peg$FAILED;
   1188       if (peg$silentFails === 0) { peg$fail(peg$e39); }
   1189     }
   1190     while (s1 !== peg$FAILED) {
   1191       s0.push(s1);
   1192       s1 = input.charAt(peg$currPos);
   1193       if (peg$r9.test(s1)) {
   1194         peg$currPos++;
   1195       } else {
   1196         s1 = peg$FAILED;
   1197         if (peg$silentFails === 0) { peg$fail(peg$e39); }
   1198       }
   1199     }
   1200     peg$silentFails--;
   1201     s1 = peg$FAILED;
   1202     if (peg$silentFails === 0) { peg$fail(peg$e38); }
   1203 
   1204     return s0;
   1205   }
   1206 
   1207   peg$result = peg$startRuleFunction();
   1208 
   1209   if (options.peg$library) {
   1210     return /** @type {any} */ ({
   1211       peg$result,
   1212       peg$currPos,
   1213       peg$FAILED,
   1214       peg$maxFailExpected,
   1215       peg$maxFailPos
   1216     });
   1217   }
   1218   if (peg$result !== peg$FAILED && peg$currPos === input.length) {
   1219     return peg$result;
   1220   } else {
   1221     if (peg$result !== peg$FAILED && peg$currPos < input.length) {
   1222       peg$fail(peg$endExpectation());
   1223     }
   1224 
   1225     throw peg$buildStructuredError(
   1226       peg$maxFailExpected,
   1227       peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
   1228       peg$maxFailPos < input.length
   1229         ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)
   1230         : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
   1231     );
   1232   }
   1233 }
   1234 
   1235 /**
   1236  * @license
   1237  * Copyright (c) 2025, Jeff Hlywa (jhlywa@gmail.com)
   1238  * All rights reserved.
   1239  *
   1240  * Redistribution and use in source and binary forms, with or without
   1241  * modification, are permitted provided that the following conditions are met:
   1242  *
   1243  * 1. Redistributions of source code must retain the above copyright notice,
   1244  *    this list of conditions and the following disclaimer.
   1245  * 2. Redistributions in binary form must reproduce the above copyright notice,
   1246  *    this list of conditions and the following disclaimer in the documentation
   1247  *    and/or other materials provided with the distribution.
   1248  *
   1249  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   1250  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   1251  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   1252  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   1253  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   1254  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   1255  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   1256  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   1257  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   1258  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   1259  * POSSIBILITY OF SUCH DAMAGE.
   1260  */
   1261 const MASK64 = 0xffffffffffffffffn;
   1262 function rotl(x, k) {
   1263     return ((x << k) | (x >> (64n - k))) & 0xffffffffffffffffn;
   1264 }
   1265 function wrappingMul(x, y) {
   1266     return (x * y) & MASK64;
   1267 }
   1268 // xoroshiro128**
   1269 function xoroshiro128(state) {
   1270     return function () {
   1271         let s0 = BigInt(state & MASK64);
   1272         let s1 = BigInt((state >> 64n) & MASK64);
   1273         const result = wrappingMul(rotl(wrappingMul(s0, 5n), 7n), 9n);
   1274         s1 ^= s0;
   1275         s0 = (rotl(s0, 24n) ^ s1 ^ (s1 << 16n)) & MASK64;
   1276         s1 = rotl(s1, 37n);
   1277         state = (s1 << 64n) | s0;
   1278         return result;
   1279     };
   1280 }
   1281 const rand = xoroshiro128(0xa187eb39cdcaed8f31c4b365b102e01en);
   1282 const PIECE_KEYS = Array.from({ length: 2 }, () => Array.from({ length: 6 }, () => Array.from({ length: 128 }, () => rand())));
   1283 const EP_KEYS = Array.from({ length: 8 }, () => rand());
   1284 const CASTLING_KEYS = Array.from({ length: 16 }, () => rand());
   1285 const SIDE_KEY = rand();
   1286 const WHITE = 'w';
   1287 const BLACK = 'b';
   1288 const PAWN = 'p';
   1289 const KNIGHT = 'n';
   1290 const BISHOP = 'b';
   1291 const ROOK = 'r';
   1292 const QUEEN = 'q';
   1293 const KING = 'k';
   1294 const DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
   1295 class Move {
   1296     color;
   1297     from;
   1298     to;
   1299     piece;
   1300     captured;
   1301     promotion;
   1302     /**
   1303      * @deprecated This field is deprecated and will be removed in version 2.0.0.
   1304      * Please use move descriptor functions instead: `isCapture`, `isPromotion`,
   1305      * `isEnPassant`, `isKingsideCastle`, `isQueensideCastle`, `isCastle`, and
   1306      * `isBigPawn`
   1307      */
   1308     flags;
   1309     san;
   1310     lan;
   1311     before;
   1312     after;
   1313     constructor(chess, internal) {
   1314         const { color, piece, from, to, flags, captured, promotion } = internal;
   1315         const fromAlgebraic = algebraic(from);
   1316         const toAlgebraic = algebraic(to);
   1317         this.color = color;
   1318         this.piece = piece;
   1319         this.from = fromAlgebraic;
   1320         this.to = toAlgebraic;
   1321         /*
   1322          * HACK: The chess['_method']() calls below invoke private methods in the
   1323          * Chess class to generate SAN and FEN. It's a bit of a hack, but makes the
   1324          * code cleaner elsewhere.
   1325          */
   1326         this.san = chess['_moveToSan'](internal, chess['_moves']({ legal: true }));
   1327         this.lan = fromAlgebraic + toAlgebraic;
   1328         this.before = chess.fen();
   1329         // Generate the FEN for the 'after' key
   1330         chess['_makeMove'](internal);
   1331         this.after = chess.fen();
   1332         chess['_undoMove']();
   1333         // Build the text representation of the move flags
   1334         this.flags = '';
   1335         for (const flag in BITS) {
   1336             if (BITS[flag] & flags) {
   1337                 this.flags += FLAGS[flag];
   1338             }
   1339         }
   1340         if (captured) {
   1341             this.captured = captured;
   1342         }
   1343         if (promotion) {
   1344             this.promotion = promotion;
   1345             this.lan += promotion;
   1346         }
   1347     }
   1348     isCapture() {
   1349         return this.flags.indexOf(FLAGS['CAPTURE']) > -1;
   1350     }
   1351     isPromotion() {
   1352         return this.flags.indexOf(FLAGS['PROMOTION']) > -1;
   1353     }
   1354     isEnPassant() {
   1355         return this.flags.indexOf(FLAGS['EP_CAPTURE']) > -1;
   1356     }
   1357     isKingsideCastle() {
   1358         return this.flags.indexOf(FLAGS['KSIDE_CASTLE']) > -1;
   1359     }
   1360     isQueensideCastle() {
   1361         return this.flags.indexOf(FLAGS['QSIDE_CASTLE']) > -1;
   1362     }
   1363     isBigPawn() {
   1364         return this.flags.indexOf(FLAGS['BIG_PAWN']) > -1;
   1365     }
   1366 }
   1367 const EMPTY = -1;
   1368 const FLAGS = {
   1369     NORMAL: 'n',
   1370     CAPTURE: 'c',
   1371     BIG_PAWN: 'b',
   1372     EP_CAPTURE: 'e',
   1373     PROMOTION: 'p',
   1374     KSIDE_CASTLE: 'k',
   1375     QSIDE_CASTLE: 'q',
   1376     NULL_MOVE: '-',
   1377 };
   1378 // prettier-ignore
   1379 const SQUARES = [
   1380     'a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8',
   1381     'a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7',
   1382     'a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6',
   1383     'a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5',
   1384     'a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4',
   1385     'a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3',
   1386     'a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2',
   1387     'a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1'
   1388 ];
   1389 const BITS = {
   1390     NORMAL: 1,
   1391     CAPTURE: 2,
   1392     BIG_PAWN: 4,
   1393     EP_CAPTURE: 8,
   1394     PROMOTION: 16,
   1395     KSIDE_CASTLE: 32,
   1396     QSIDE_CASTLE: 64,
   1397     NULL_MOVE: 128,
   1398 };
   1399 /* eslint-disable @typescript-eslint/naming-convention */
   1400 // these are required, according to spec
   1401 const SEVEN_TAG_ROSTER = {
   1402     Event: '?',
   1403     Site: '?',
   1404     Date: '????.??.??',
   1405     Round: '?',
   1406     White: '?',
   1407     Black: '?',
   1408     Result: '*',
   1409 };
   1410 /**
   1411  * These nulls are placeholders to fix the order of tags (as they appear in PGN spec); null values will be
   1412  * eliminated in getHeaders()
   1413  */
   1414 const SUPLEMENTAL_TAGS = {
   1415     WhiteTitle: null,
   1416     BlackTitle: null,
   1417     WhiteElo: null,
   1418     BlackElo: null,
   1419     WhiteUSCF: null,
   1420     BlackUSCF: null,
   1421     WhiteNA: null,
   1422     BlackNA: null,
   1423     WhiteType: null,
   1424     BlackType: null,
   1425     EventDate: null,
   1426     EventSponsor: null,
   1427     Section: null,
   1428     Stage: null,
   1429     Board: null,
   1430     Opening: null,
   1431     Variation: null,
   1432     SubVariation: null,
   1433     ECO: null,
   1434     NIC: null,
   1435     Time: null,
   1436     UTCTime: null,
   1437     UTCDate: null,
   1438     TimeControl: null,
   1439     SetUp: null,
   1440     FEN: null,
   1441     Termination: null,
   1442     Annotator: null,
   1443     Mode: null,
   1444     PlyCount: null,
   1445 };
   1446 const HEADER_TEMPLATE = {
   1447     ...SEVEN_TAG_ROSTER,
   1448     ...SUPLEMENTAL_TAGS,
   1449 };
   1450 /* eslint-enable @typescript-eslint/naming-convention */
   1451 /*
   1452  * NOTES ABOUT 0x88 MOVE GENERATION ALGORITHM
   1453  * ----------------------------------------------------------------------------
   1454  * From https://github.com/jhlywa/chess.js/issues/230
   1455  *
   1456  * A lot of people are confused when they first see the internal representation
   1457  * of chess.js. It uses the 0x88 Move Generation Algorithm which internally
   1458  * stores the board as an 8x16 array. This is purely for efficiency but has a
   1459  * couple of interesting benefits:
   1460  *
   1461  * 1. 0x88 offers a very inexpensive "off the board" check. Bitwise AND (&) any
   1462  *    square with 0x88, if the result is non-zero then the square is off the
   1463  *    board. For example, assuming a knight square A8 (0 in 0x88 notation),
   1464  *    there are 8 possible directions in which the knight can move. These
   1465  *    directions are relative to the 8x16 board and are stored in the
   1466  *    PIECE_OFFSETS map. One possible move is A8 - 18 (up one square, and two
   1467  *    squares to the left - which is off the board). 0 - 18 = -18 & 0x88 = 0x88
   1468  *    (because of two-complement representation of -18). The non-zero result
   1469  *    means the square is off the board and the move is illegal. Take the
   1470  *    opposite move (from A8 to C7), 0 + 18 = 18 & 0x88 = 0. A result of zero
   1471  *    means the square is on the board.
   1472  *
   1473  * 2. The relative distance (or difference) between two squares on a 8x16 board
   1474  *    is unique and can be used to inexpensively determine if a piece on a
   1475  *    square can attack any other arbitrary square. For example, let's see if a
   1476  *    pawn on E7 can attack E2. The difference between E7 (20) - E2 (100) is
   1477  *    -80. We add 119 to make the ATTACKS array index non-negative (because the
   1478  *    worst case difference is A8 - H1 = -119). The ATTACKS array contains a
   1479  *    bitmask of pieces that can attack from that distance and direction.
   1480  *    ATTACKS[-80 + 119=39] gives us 24 or 0b11000 in binary. Look at the
   1481  *    PIECE_MASKS map to determine the mask for a given piece type. In our pawn
   1482  *    example, we would check to see if 24 & 0x1 is non-zero, which it is
   1483  *    not. So, naturally, a pawn on E7 can't attack a piece on E2. However, a
   1484  *    rook can since 24 & 0x8 is non-zero. The only thing left to check is that
   1485  *    there are no blocking pieces between E7 and E2. That's where the RAYS
   1486  *    array comes in. It provides an offset (in this case 16) to add to E7 (20)
   1487  *    to check for blocking pieces. E7 (20) + 16 = E6 (36) + 16 = E5 (52) etc.
   1488  */
   1489 // prettier-ignore
   1490 // eslint-disable-next-line
   1491 const Ox88 = {
   1492     a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7,
   1493     a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23,
   1494     a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39,
   1495     a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55,
   1496     a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71,
   1497     a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87,
   1498     a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103,
   1499     a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119
   1500 };
   1501 const PAWN_OFFSETS = {
   1502     b: [16, 32, 17, 15],
   1503     w: [-16, -32, -17, -15],
   1504 };
   1505 const PIECE_OFFSETS = {
   1506     n: [-18, -33, -31, -14, 18, 33, 31, 14],
   1507     b: [-17, -15, 17, 15],
   1508     r: [-16, 1, 16, -1],
   1509     q: [-17, -16, -15, 1, 17, 16, 15, -1],
   1510     k: [-17, -16, -15, 1, 17, 16, 15, -1],
   1511 };
   1512 // prettier-ignore
   1513 const ATTACKS = [
   1514     20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 20, 0,
   1515     0, 20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 20, 0, 0,
   1516     0, 0, 20, 0, 0, 0, 0, 24, 0, 0, 0, 0, 20, 0, 0, 0,
   1517     0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 0,
   1518     0, 0, 0, 0, 20, 0, 0, 24, 0, 0, 20, 0, 0, 0, 0, 0,
   1519     0, 0, 0, 0, 0, 20, 2, 24, 2, 20, 0, 0, 0, 0, 0, 0,
   1520     0, 0, 0, 0, 0, 2, 53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
   1521     24, 24, 24, 24, 24, 24, 56, 0, 56, 24, 24, 24, 24, 24, 24, 0,
   1522     0, 0, 0, 0, 0, 2, 53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
   1523     0, 0, 0, 0, 0, 20, 2, 24, 2, 20, 0, 0, 0, 0, 0, 0,
   1524     0, 0, 0, 0, 20, 0, 0, 24, 0, 0, 20, 0, 0, 0, 0, 0,
   1525     0, 0, 0, 20, 0, 0, 0, 24, 0, 0, 0, 20, 0, 0, 0, 0,
   1526     0, 0, 20, 0, 0, 0, 0, 24, 0, 0, 0, 0, 20, 0, 0, 0,
   1527     0, 20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 20, 0, 0,
   1528     20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 20
   1529 ];
   1530 // prettier-ignore
   1531 const RAYS = [
   1532     17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0,
   1533     0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0,
   1534     0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0,
   1535     0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0,
   1536     0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0,
   1537     0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0,
   1538     0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0,
   1539     1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, 0,
   1540     0, 0, 0, 0, 0, 0, -15, -16, -17, 0, 0, 0, 0, 0, 0, 0,
   1541     0, 0, 0, 0, 0, -15, 0, -16, 0, -17, 0, 0, 0, 0, 0, 0,
   1542     0, 0, 0, 0, -15, 0, 0, -16, 0, 0, -17, 0, 0, 0, 0, 0,
   1543     0, 0, 0, -15, 0, 0, 0, -16, 0, 0, 0, -17, 0, 0, 0, 0,
   1544     0, 0, -15, 0, 0, 0, 0, -16, 0, 0, 0, 0, -17, 0, 0, 0,
   1545     0, -15, 0, 0, 0, 0, 0, -16, 0, 0, 0, 0, 0, -17, 0, 0,
   1546     -15, 0, 0, 0, 0, 0, 0, -16, 0, 0, 0, 0, 0, 0, -17
   1547 ];
   1548 const PIECE_MASKS = { p: 0x1, n: 0x2, b: 0x4, r: 0x8, q: 0x10, k: 0x20 };
   1549 const SYMBOLS = 'pnbrqkPNBRQK';
   1550 const PROMOTIONS = [KNIGHT, BISHOP, ROOK, QUEEN];
   1551 const RANK_1 = 7;
   1552 const RANK_2 = 6;
   1553 /*
   1554  * const RANK_3 = 5
   1555  * const RANK_4 = 4
   1556  * const RANK_5 = 3
   1557  * const RANK_6 = 2
   1558  */
   1559 const RANK_7 = 1;
   1560 const RANK_8 = 0;
   1561 const SIDES = {
   1562     [KING]: BITS.KSIDE_CASTLE,
   1563     [QUEEN]: BITS.QSIDE_CASTLE,
   1564 };
   1565 const ROOKS = {
   1566     w: [
   1567         { square: Ox88.a1, flag: BITS.QSIDE_CASTLE },
   1568         { square: Ox88.h1, flag: BITS.KSIDE_CASTLE },
   1569     ],
   1570     b: [
   1571         { square: Ox88.a8, flag: BITS.QSIDE_CASTLE },
   1572         { square: Ox88.h8, flag: BITS.KSIDE_CASTLE },
   1573     ],
   1574 };
   1575 const SECOND_RANK = { b: RANK_7, w: RANK_2 };
   1576 const SAN_NULLMOVE = '--';
   1577 // Extracts the zero-based rank of an 0x88 square.
   1578 function rank(square) {
   1579     return square >> 4;
   1580 }
   1581 // Extracts the zero-based file of an 0x88 square.
   1582 function file(square) {
   1583     return square & 0xf;
   1584 }
   1585 function isDigit(c) {
   1586     return '0123456789'.indexOf(c) !== -1;
   1587 }
   1588 // Converts a 0x88 square to algebraic notation.
   1589 function algebraic(square) {
   1590     const f = file(square);
   1591     const r = rank(square);
   1592     return ('abcdefgh'.substring(f, f + 1) +
   1593         '87654321'.substring(r, r + 1));
   1594 }
   1595 function swapColor(color) {
   1596     return color === WHITE ? BLACK : WHITE;
   1597 }
   1598 function validateFen(fen) {
   1599     // 1st criterion: 6 space-seperated fields?
   1600     const tokens = fen.split(/\s+/);
   1601     if (tokens.length !== 6) {
   1602         return {
   1603             ok: false,
   1604             error: 'Invalid FEN: must contain six space-delimited fields',
   1605         };
   1606     }
   1607     // 2nd criterion: move number field is a integer value > 0?
   1608     const moveNumber = parseInt(tokens[5], 10);
   1609     if (isNaN(moveNumber) || moveNumber <= 0) {
   1610         return {
   1611             ok: false,
   1612             error: 'Invalid FEN: move number must be a positive integer',
   1613         };
   1614     }
   1615     // 3rd criterion: half move counter is an integer >= 0?
   1616     const halfMoves = parseInt(tokens[4], 10);
   1617     if (isNaN(halfMoves) || halfMoves < 0) {
   1618         return {
   1619             ok: false,
   1620             error: 'Invalid FEN: half move counter number must be a non-negative integer',
   1621         };
   1622     }
   1623     // 4th criterion: 4th field is a valid e.p.-string?
   1624     if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) {
   1625         return { ok: false, error: 'Invalid FEN: en-passant square is invalid' };
   1626     }
   1627     // 5th criterion: 3th field is a valid castle-string?
   1628     if (/[^kKqQ-]/.test(tokens[2])) {
   1629         return { ok: false, error: 'Invalid FEN: castling availability is invalid' };
   1630     }
   1631     // 6th criterion: 2nd field is "w" (white) or "b" (black)?
   1632     if (!/^(w|b)$/.test(tokens[1])) {
   1633         return { ok: false, error: 'Invalid FEN: side-to-move is invalid' };
   1634     }
   1635     // 7th criterion: 1st field contains 8 rows?
   1636     const rows = tokens[0].split('/');
   1637     if (rows.length !== 8) {
   1638         return {
   1639             ok: false,
   1640             error: "Invalid FEN: piece data does not contain 8 '/'-delimited rows",
   1641         };
   1642     }
   1643     // 8th criterion: every row is valid?
   1644     for (let i = 0; i < rows.length; i++) {
   1645         // check for right sum of fields AND not two numbers in succession
   1646         let sumFields = 0;
   1647         let previousWasNumber = false;
   1648         for (let k = 0; k < rows[i].length; k++) {
   1649             if (isDigit(rows[i][k])) {
   1650                 if (previousWasNumber) {
   1651                     return {
   1652                         ok: false,
   1653                         error: 'Invalid FEN: piece data is invalid (consecutive number)',
   1654                     };
   1655                 }
   1656                 sumFields += parseInt(rows[i][k], 10);
   1657                 previousWasNumber = true;
   1658             }
   1659             else {
   1660                 if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) {
   1661                     return {
   1662                         ok: false,
   1663                         error: 'Invalid FEN: piece data is invalid (invalid piece)',
   1664                     };
   1665                 }
   1666                 sumFields += 1;
   1667                 previousWasNumber = false;
   1668             }
   1669         }
   1670         if (sumFields !== 8) {
   1671             return {
   1672                 ok: false,
   1673                 error: 'Invalid FEN: piece data is invalid (too many squares in rank)',
   1674             };
   1675         }
   1676     }
   1677     // 9th criterion: is en-passant square legal?
   1678     if ((tokens[3][1] == '3' && tokens[1] == 'w') ||
   1679         (tokens[3][1] == '6' && tokens[1] == 'b')) {
   1680         return { ok: false, error: 'Invalid FEN: illegal en-passant square' };
   1681     }
   1682     // 10th criterion: does chess position contain exact two kings?
   1683     const kings = [
   1684         { color: 'white', regex: /K/g },
   1685         { color: 'black', regex: /k/g },
   1686     ];
   1687     for (const { color, regex } of kings) {
   1688         if (!regex.test(tokens[0])) {
   1689             return { ok: false, error: `Invalid FEN: missing ${color} king` };
   1690         }
   1691         if ((tokens[0].match(regex) || []).length > 1) {
   1692             return { ok: false, error: `Invalid FEN: too many ${color} kings` };
   1693         }
   1694     }
   1695     // 11th criterion: are any pawns on the first or eighth rows?
   1696     if (Array.from(rows[0] + rows[7]).some((char) => char.toUpperCase() === 'P')) {
   1697         return {
   1698             ok: false,
   1699             error: 'Invalid FEN: some pawns are on the edge rows',
   1700         };
   1701     }
   1702     return { ok: true };
   1703 }
   1704 // this function is used to uniquely identify ambiguous moves
   1705 function getDisambiguator(move, moves) {
   1706     const from = move.from;
   1707     const to = move.to;
   1708     const piece = move.piece;
   1709     let ambiguities = 0;
   1710     let sameRank = 0;
   1711     let sameFile = 0;
   1712     for (let i = 0, len = moves.length; i < len; i++) {
   1713         const ambigFrom = moves[i].from;
   1714         const ambigTo = moves[i].to;
   1715         const ambigPiece = moves[i].piece;
   1716         /*
   1717          * if a move of the same piece type ends on the same to square, we'll need
   1718          * to add a disambiguator to the algebraic notation
   1719          */
   1720         if (piece === ambigPiece && from !== ambigFrom && to === ambigTo) {
   1721             ambiguities++;
   1722             if (rank(from) === rank(ambigFrom)) {
   1723                 sameRank++;
   1724             }
   1725             if (file(from) === file(ambigFrom)) {
   1726                 sameFile++;
   1727             }
   1728         }
   1729     }
   1730     if (ambiguities > 0) {
   1731         if (sameRank > 0 && sameFile > 0) {
   1732             /*
   1733              * if there exists a similar moving piece on the same rank and file as
   1734              * the move in question, use the square as the disambiguator
   1735              */
   1736             return algebraic(from);
   1737         }
   1738         else if (sameFile > 0) {
   1739             /*
   1740              * if the moving piece rests on the same file, use the rank symbol as the
   1741              * disambiguator
   1742              */
   1743             return algebraic(from).charAt(1);
   1744         }
   1745         else {
   1746             // else use the file symbol
   1747             return algebraic(from).charAt(0);
   1748         }
   1749     }
   1750     return '';
   1751 }
   1752 function addMove(moves, color, from, to, piece, captured = undefined, flags = BITS.NORMAL) {
   1753     const r = rank(to);
   1754     if (piece === PAWN && (r === RANK_1 || r === RANK_8)) {
   1755         for (let i = 0; i < PROMOTIONS.length; i++) {
   1756             const promotion = PROMOTIONS[i];
   1757             moves.push({
   1758                 color,
   1759                 from,
   1760                 to,
   1761                 piece,
   1762                 captured,
   1763                 promotion,
   1764                 flags: flags | BITS.PROMOTION,
   1765             });
   1766         }
   1767     }
   1768     else {
   1769         moves.push({
   1770             color,
   1771             from,
   1772             to,
   1773             piece,
   1774             captured,
   1775             flags,
   1776         });
   1777     }
   1778 }
   1779 function inferPieceType(san) {
   1780     let pieceType = san.charAt(0);
   1781     if (pieceType >= 'a' && pieceType <= 'h') {
   1782         const matches = san.match(/[a-h]\d.*[a-h]\d/);
   1783         if (matches) {
   1784             return undefined;
   1785         }
   1786         return PAWN;
   1787     }
   1788     pieceType = pieceType.toLowerCase();
   1789     if (pieceType === 'o') {
   1790         return KING;
   1791     }
   1792     return pieceType;
   1793 }
   1794 // parses all of the decorators out of a SAN string
   1795 function strippedSan(move) {
   1796     return move.replace(/=/, '').replace(/[+#]?[?!]*$/, '');
   1797 }
   1798 class Chess {
   1799     _board = new Array(128);
   1800     _turn = WHITE;
   1801     _header = {};
   1802     _kings = { w: EMPTY, b: EMPTY };
   1803     _epSquare = -1;
   1804     _halfMoves = 0;
   1805     _moveNumber = 0;
   1806     _history = [];
   1807     _comments = {};
   1808     _castling = { w: 0, b: 0 };
   1809     _hash = 0n;
   1810     // tracks number of times a position has been seen for repetition checking
   1811     _positionCount = new Map();
   1812     constructor(fen = DEFAULT_POSITION, { skipValidation = false } = {}) {
   1813         this.load(fen, { skipValidation });
   1814     }
   1815     clear({ preserveHeaders = false } = {}) {
   1816         this._board = new Array(128);
   1817         this._kings = { w: EMPTY, b: EMPTY };
   1818         this._turn = WHITE;
   1819         this._castling = { w: 0, b: 0 };
   1820         this._epSquare = EMPTY;
   1821         this._halfMoves = 0;
   1822         this._moveNumber = 1;
   1823         this._history = [];
   1824         this._comments = {};
   1825         this._header = preserveHeaders ? this._header : { ...HEADER_TEMPLATE };
   1826         this._hash = this._computeHash();
   1827         this._positionCount = new Map();
   1828         /*
   1829          * Delete the SetUp and FEN headers (if preserved), the board is empty and
   1830          * these headers don't make sense in this state. They'll get added later
   1831          * via .load() or .put()
   1832          */
   1833         this._header['SetUp'] = null;
   1834         this._header['FEN'] = null;
   1835     }
   1836     load(fen, { skipValidation = false, preserveHeaders = false } = {}) {
   1837         let tokens = fen.split(/\s+/);
   1838         // append commonly omitted fen tokens
   1839         if (tokens.length >= 2 && tokens.length < 6) {
   1840             const adjustments = ['-', '-', '0', '1'];
   1841             fen = tokens.concat(adjustments.slice(-(6 - tokens.length))).join(' ');
   1842         }
   1843         tokens = fen.split(/\s+/);
   1844         if (!skipValidation) {
   1845             const { ok, error } = validateFen(fen);
   1846             if (!ok) {
   1847                 throw new Error(error);
   1848             }
   1849         }
   1850         const position = tokens[0];
   1851         let square = 0;
   1852         this.clear({ preserveHeaders });
   1853         for (let i = 0; i < position.length; i++) {
   1854             const piece = position.charAt(i);
   1855             if (piece === '/') {
   1856                 square += 8;
   1857             }
   1858             else if (isDigit(piece)) {
   1859                 square += parseInt(piece, 10);
   1860             }
   1861             else {
   1862                 const color = piece < 'a' ? WHITE : BLACK;
   1863                 this._put({ type: piece.toLowerCase(), color }, algebraic(square));
   1864                 square++;
   1865             }
   1866         }
   1867         this._turn = tokens[1];
   1868         if (tokens[2].indexOf('K') > -1) {
   1869             this._castling.w |= BITS.KSIDE_CASTLE;
   1870         }
   1871         if (tokens[2].indexOf('Q') > -1) {
   1872             this._castling.w |= BITS.QSIDE_CASTLE;
   1873         }
   1874         if (tokens[2].indexOf('k') > -1) {
   1875             this._castling.b |= BITS.KSIDE_CASTLE;
   1876         }
   1877         if (tokens[2].indexOf('q') > -1) {
   1878             this._castling.b |= BITS.QSIDE_CASTLE;
   1879         }
   1880         this._epSquare = tokens[3] === '-' ? EMPTY : Ox88[tokens[3]];
   1881         this._halfMoves = parseInt(tokens[4], 10);
   1882         this._moveNumber = parseInt(tokens[5], 10);
   1883         this._hash = this._computeHash();
   1884         this._updateSetup(fen);
   1885         this._incPositionCount();
   1886     }
   1887     fen({ forceEnpassantSquare = false, } = {}) {
   1888         let empty = 0;
   1889         let fen = '';
   1890         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   1891             if (this._board[i]) {
   1892                 if (empty > 0) {
   1893                     fen += empty;
   1894                     empty = 0;
   1895                 }
   1896                 const { color, type: piece } = this._board[i];
   1897                 fen += color === WHITE ? piece.toUpperCase() : piece.toLowerCase();
   1898             }
   1899             else {
   1900                 empty++;
   1901             }
   1902             if ((i + 1) & 0x88) {
   1903                 if (empty > 0) {
   1904                     fen += empty;
   1905                 }
   1906                 if (i !== Ox88.h1) {
   1907                     fen += '/';
   1908                 }
   1909                 empty = 0;
   1910                 i += 8;
   1911             }
   1912         }
   1913         let castling = '';
   1914         if (this._castling[WHITE] & BITS.KSIDE_CASTLE) {
   1915             castling += 'K';
   1916         }
   1917         if (this._castling[WHITE] & BITS.QSIDE_CASTLE) {
   1918             castling += 'Q';
   1919         }
   1920         if (this._castling[BLACK] & BITS.KSIDE_CASTLE) {
   1921             castling += 'k';
   1922         }
   1923         if (this._castling[BLACK] & BITS.QSIDE_CASTLE) {
   1924             castling += 'q';
   1925         }
   1926         // do we have an empty castling flag?
   1927         castling = castling || '-';
   1928         let epSquare = '-';
   1929         /*
   1930          * only print the ep square if en passant is a valid move (pawn is present
   1931          * and ep capture is not pinned)
   1932          */
   1933         if (this._epSquare !== EMPTY) {
   1934             if (forceEnpassantSquare) {
   1935                 epSquare = algebraic(this._epSquare);
   1936             }
   1937             else {
   1938                 const bigPawnSquare = this._epSquare + (this._turn === WHITE ? 16 : -16);
   1939                 const squares = [bigPawnSquare + 1, bigPawnSquare - 1];
   1940                 for (const square of squares) {
   1941                     // is the square off the board?
   1942                     if (square & 0x88) {
   1943                         continue;
   1944                     }
   1945                     const color = this._turn;
   1946                     // is there a pawn that can capture the epSquare?
   1947                     if (this._board[square]?.color === color &&
   1948                         this._board[square]?.type === PAWN) {
   1949                         // if the pawn makes an ep capture, does it leave its king in check?
   1950                         this._makeMove({
   1951                             color,
   1952                             from: square,
   1953                             to: this._epSquare,
   1954                             piece: PAWN,
   1955                             captured: PAWN,
   1956                             flags: BITS.EP_CAPTURE,
   1957                         });
   1958                         const isLegal = !this._isKingAttacked(color);
   1959                         this._undoMove();
   1960                         // if ep is legal, break and set the ep square in the FEN output
   1961                         if (isLegal) {
   1962                             epSquare = algebraic(this._epSquare);
   1963                             break;
   1964                         }
   1965                     }
   1966                 }
   1967             }
   1968         }
   1969         return [
   1970             fen,
   1971             this._turn,
   1972             castling,
   1973             epSquare,
   1974             this._halfMoves,
   1975             this._moveNumber,
   1976         ].join(' ');
   1977     }
   1978     _pieceKey(i) {
   1979         if (!this._board[i]) {
   1980             return 0n;
   1981         }
   1982         const { color, type } = this._board[i];
   1983         const colorIndex = {
   1984             w: 0,
   1985             b: 1,
   1986         }[color];
   1987         const typeIndex = {
   1988             p: 0,
   1989             n: 1,
   1990             b: 2,
   1991             r: 3,
   1992             q: 4,
   1993             k: 5,
   1994         }[type];
   1995         return PIECE_KEYS[colorIndex][typeIndex][i];
   1996     }
   1997     _epKey() {
   1998         return this._epSquare === EMPTY ? 0n : EP_KEYS[this._epSquare & 7];
   1999     }
   2000     _castlingKey() {
   2001         const index = (this._castling.w >> 5) | (this._castling.b >> 3);
   2002         return CASTLING_KEYS[index];
   2003     }
   2004     _computeHash() {
   2005         let hash = 0n;
   2006         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   2007             // did we run off the end of the board
   2008             if (i & 0x88) {
   2009                 i += 7;
   2010                 continue;
   2011             }
   2012             if (this._board[i]) {
   2013                 hash ^= this._pieceKey(i);
   2014             }
   2015         }
   2016         hash ^= this._epKey();
   2017         hash ^= this._castlingKey();
   2018         if (this._turn === 'b') {
   2019             hash ^= SIDE_KEY;
   2020         }
   2021         return hash;
   2022     }
   2023     /*
   2024      * Called when the initial board setup is changed with put() or remove().
   2025      * modifies the SetUp and FEN properties of the header object. If the FEN
   2026      * is equal to the default position, the SetUp and FEN are deleted the setup
   2027      * is only updated if history.length is zero, ie moves haven't been made.
   2028      */
   2029     _updateSetup(fen) {
   2030         if (this._history.length > 0)
   2031             return;
   2032         if (fen !== DEFAULT_POSITION) {
   2033             this._header['SetUp'] = '1';
   2034             this._header['FEN'] = fen;
   2035         }
   2036         else {
   2037             this._header['SetUp'] = null;
   2038             this._header['FEN'] = null;
   2039         }
   2040     }
   2041     reset() {
   2042         this.load(DEFAULT_POSITION);
   2043     }
   2044     get(square) {
   2045         return this._board[Ox88[square]];
   2046     }
   2047     findPiece(piece) {
   2048         const squares = [];
   2049         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   2050             // did we run off the end of the board
   2051             if (i & 0x88) {
   2052                 i += 7;
   2053                 continue;
   2054             }
   2055             // if empty square or wrong color
   2056             if (!this._board[i] || this._board[i]?.color !== piece.color) {
   2057                 continue;
   2058             }
   2059             // check if square contains the requested piece
   2060             if (this._board[i].color === piece.color &&
   2061                 this._board[i].type === piece.type) {
   2062                 squares.push(algebraic(i));
   2063             }
   2064         }
   2065         return squares;
   2066     }
   2067     put({ type, color }, square) {
   2068         if (this._put({ type, color }, square)) {
   2069             this._updateCastlingRights();
   2070             this._updateEnPassantSquare();
   2071             this._updateSetup(this.fen());
   2072             return true;
   2073         }
   2074         return false;
   2075     }
   2076     _set(sq, piece) {
   2077         this._hash ^= this._pieceKey(sq);
   2078         this._board[sq] = piece;
   2079         this._hash ^= this._pieceKey(sq);
   2080     }
   2081     _put({ type, color }, square) {
   2082         // check for piece
   2083         if (SYMBOLS.indexOf(type.toLowerCase()) === -1) {
   2084             return false;
   2085         }
   2086         // check for valid square
   2087         if (!(square in Ox88)) {
   2088             return false;
   2089         }
   2090         const sq = Ox88[square];
   2091         // don't let the user place more than one king
   2092         if (type == KING &&
   2093             !(this._kings[color] == EMPTY || this._kings[color] == sq)) {
   2094             return false;
   2095         }
   2096         const currentPieceOnSquare = this._board[sq];
   2097         // if one of the kings will be replaced by the piece from args, set the `_kings` respective entry to `EMPTY`
   2098         if (currentPieceOnSquare && currentPieceOnSquare.type === KING) {
   2099             this._kings[currentPieceOnSquare.color] = EMPTY;
   2100         }
   2101         this._set(sq, { type: type, color: color });
   2102         if (type === KING) {
   2103             this._kings[color] = sq;
   2104         }
   2105         return true;
   2106     }
   2107     _clear(sq) {
   2108         this._hash ^= this._pieceKey(sq);
   2109         delete this._board[sq];
   2110     }
   2111     remove(square) {
   2112         const piece = this.get(square);
   2113         this._clear(Ox88[square]);
   2114         if (piece && piece.type === KING) {
   2115             this._kings[piece.color] = EMPTY;
   2116         }
   2117         this._updateCastlingRights();
   2118         this._updateEnPassantSquare();
   2119         this._updateSetup(this.fen());
   2120         return piece;
   2121     }
   2122     _updateCastlingRights() {
   2123         this._hash ^= this._castlingKey();
   2124         const whiteKingInPlace = this._board[Ox88.e1]?.type === KING &&
   2125             this._board[Ox88.e1]?.color === WHITE;
   2126         const blackKingInPlace = this._board[Ox88.e8]?.type === KING &&
   2127             this._board[Ox88.e8]?.color === BLACK;
   2128         if (!whiteKingInPlace ||
   2129             this._board[Ox88.a1]?.type !== ROOK ||
   2130             this._board[Ox88.a1]?.color !== WHITE) {
   2131             this._castling.w &= -65;
   2132         }
   2133         if (!whiteKingInPlace ||
   2134             this._board[Ox88.h1]?.type !== ROOK ||
   2135             this._board[Ox88.h1]?.color !== WHITE) {
   2136             this._castling.w &= -33;
   2137         }
   2138         if (!blackKingInPlace ||
   2139             this._board[Ox88.a8]?.type !== ROOK ||
   2140             this._board[Ox88.a8]?.color !== BLACK) {
   2141             this._castling.b &= -65;
   2142         }
   2143         if (!blackKingInPlace ||
   2144             this._board[Ox88.h8]?.type !== ROOK ||
   2145             this._board[Ox88.h8]?.color !== BLACK) {
   2146             this._castling.b &= -33;
   2147         }
   2148         this._hash ^= this._castlingKey();
   2149     }
   2150     _updateEnPassantSquare() {
   2151         if (this._epSquare === EMPTY) {
   2152             return;
   2153         }
   2154         const startSquare = this._epSquare + (this._turn === WHITE ? -16 : 16);
   2155         const currentSquare = this._epSquare + (this._turn === WHITE ? 16 : -16);
   2156         const attackers = [currentSquare + 1, currentSquare - 1];
   2157         if (this._board[startSquare] !== null ||
   2158             this._board[this._epSquare] !== null ||
   2159             this._board[currentSquare]?.color !== swapColor(this._turn) ||
   2160             this._board[currentSquare]?.type !== PAWN) {
   2161             this._hash ^= this._epKey();
   2162             this._epSquare = EMPTY;
   2163             return;
   2164         }
   2165         const canCapture = (square) => !(square & 0x88) &&
   2166             this._board[square]?.color === this._turn &&
   2167             this._board[square]?.type === PAWN;
   2168         if (!attackers.some(canCapture)) {
   2169             this._hash ^= this._epKey();
   2170             this._epSquare = EMPTY;
   2171         }
   2172     }
   2173     _attacked(color, square, verbose) {
   2174         const attackers = [];
   2175         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   2176             // did we run off the end of the board
   2177             if (i & 0x88) {
   2178                 i += 7;
   2179                 continue;
   2180             }
   2181             // if empty square or wrong color
   2182             if (this._board[i] === undefined || this._board[i].color !== color) {
   2183                 continue;
   2184             }
   2185             const piece = this._board[i];
   2186             const difference = i - square;
   2187             // skip - to/from square are the same
   2188             if (difference === 0) {
   2189                 continue;
   2190             }
   2191             const index = difference + 119;
   2192             if (ATTACKS[index] & PIECE_MASKS[piece.type]) {
   2193                 if (piece.type === PAWN) {
   2194                     if ((difference > 0 && piece.color === WHITE) ||
   2195                         (difference <= 0 && piece.color === BLACK)) {
   2196                         if (!verbose) {
   2197                             return true;
   2198                         }
   2199                         else {
   2200                             attackers.push(algebraic(i));
   2201                         }
   2202                     }
   2203                     continue;
   2204                 }
   2205                 // if the piece is a knight or a king
   2206                 if (piece.type === 'n' || piece.type === 'k') {
   2207                     if (!verbose) {
   2208                         return true;
   2209                     }
   2210                     else {
   2211                         attackers.push(algebraic(i));
   2212                         continue;
   2213                     }
   2214                 }
   2215                 const offset = RAYS[index];
   2216                 let j = i + offset;
   2217                 let blocked = false;
   2218                 while (j !== square) {
   2219                     if (this._board[j] != null) {
   2220                         blocked = true;
   2221                         break;
   2222                     }
   2223                     j += offset;
   2224                 }
   2225                 if (!blocked) {
   2226                     if (!verbose) {
   2227                         return true;
   2228                     }
   2229                     else {
   2230                         attackers.push(algebraic(i));
   2231                         continue;
   2232                     }
   2233                 }
   2234             }
   2235         }
   2236         if (verbose) {
   2237             return attackers;
   2238         }
   2239         else {
   2240             return false;
   2241         }
   2242     }
   2243     attackers(square, attackedBy) {
   2244         if (!attackedBy) {
   2245             return this._attacked(this._turn, Ox88[square], true);
   2246         }
   2247         else {
   2248             return this._attacked(attackedBy, Ox88[square], true);
   2249         }
   2250     }
   2251     _isKingAttacked(color) {
   2252         const square = this._kings[color];
   2253         return square === -1 ? false : this._attacked(swapColor(color), square);
   2254     }
   2255     hash() {
   2256         return this._hash.toString(16);
   2257     }
   2258     isAttacked(square, attackedBy) {
   2259         return this._attacked(attackedBy, Ox88[square]);
   2260     }
   2261     isCheck() {
   2262         return this._isKingAttacked(this._turn);
   2263     }
   2264     inCheck() {
   2265         return this.isCheck();
   2266     }
   2267     isCheckmate() {
   2268         return this.isCheck() && this._moves().length === 0;
   2269     }
   2270     isStalemate() {
   2271         return !this.isCheck() && this._moves().length === 0;
   2272     }
   2273     isInsufficientMaterial() {
   2274         /*
   2275          * k.b. vs k.b. (of opposite colors) with mate in 1:
   2276          * 8/8/8/8/1b6/8/B1k5/K7 b - - 0 1
   2277          *
   2278          * k.b. vs k.n. with mate in 1:
   2279          * 8/8/8/8/1n6/8/B7/K1k5 b - - 2 1
   2280          */
   2281         const pieces = {
   2282             b: 0,
   2283             n: 0,
   2284             r: 0,
   2285             q: 0,
   2286             k: 0,
   2287             p: 0,
   2288         };
   2289         const bishops = [];
   2290         let numPieces = 0;
   2291         let squareColor = 0;
   2292         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   2293             squareColor = (squareColor + 1) % 2;
   2294             if (i & 0x88) {
   2295                 i += 7;
   2296                 continue;
   2297             }
   2298             const piece = this._board[i];
   2299             if (piece) {
   2300                 pieces[piece.type] = piece.type in pieces ? pieces[piece.type] + 1 : 1;
   2301                 if (piece.type === BISHOP) {
   2302                     bishops.push(squareColor);
   2303                 }
   2304                 numPieces++;
   2305             }
   2306         }
   2307         // k vs. k
   2308         if (numPieces === 2) {
   2309             return true;
   2310         }
   2311         else if (
   2312         // k vs. kn .... or .... k vs. kb
   2313         numPieces === 3 &&
   2314             (pieces[BISHOP] === 1 || pieces[KNIGHT] === 1)) {
   2315             return true;
   2316         }
   2317         else if (numPieces === pieces[BISHOP] + 2) {
   2318             // kb vs. kb where any number of bishops are all on the same color
   2319             let sum = 0;
   2320             const len = bishops.length;
   2321             for (let i = 0; i < len; i++) {
   2322                 sum += bishops[i];
   2323             }
   2324             if (sum === 0 || sum === len) {
   2325                 return true;
   2326             }
   2327         }
   2328         return false;
   2329     }
   2330     isThreefoldRepetition() {
   2331         return this._getPositionCount(this._hash) >= 3;
   2332     }
   2333     isDrawByFiftyMoves() {
   2334         return this._halfMoves >= 100; // 50 moves per side = 100 half moves
   2335     }
   2336     isDraw() {
   2337         return (this.isDrawByFiftyMoves() ||
   2338             this.isStalemate() ||
   2339             this.isInsufficientMaterial() ||
   2340             this.isThreefoldRepetition());
   2341     }
   2342     isGameOver() {
   2343         return this.isCheckmate() || this.isDraw();
   2344     }
   2345     moves({ verbose = false, square = undefined, piece = undefined, } = {}) {
   2346         const moves = this._moves({ square, piece });
   2347         if (verbose) {
   2348             return moves.map((move) => new Move(this, move));
   2349         }
   2350         else {
   2351             return moves.map((move) => this._moveToSan(move, moves));
   2352         }
   2353     }
   2354     _moves({ legal = true, piece = undefined, square = undefined, } = {}) {
   2355         const forSquare = square ? square.toLowerCase() : undefined;
   2356         const forPiece = piece?.toLowerCase();
   2357         const moves = [];
   2358         const us = this._turn;
   2359         const them = swapColor(us);
   2360         let firstSquare = Ox88.a8;
   2361         let lastSquare = Ox88.h1;
   2362         let singleSquare = false;
   2363         // are we generating moves for a single square?
   2364         if (forSquare) {
   2365             // illegal square, return empty moves
   2366             if (!(forSquare in Ox88)) {
   2367                 return [];
   2368             }
   2369             else {
   2370                 firstSquare = lastSquare = Ox88[forSquare];
   2371                 singleSquare = true;
   2372             }
   2373         }
   2374         for (let from = firstSquare; from <= lastSquare; from++) {
   2375             // did we run off the end of the board
   2376             if (from & 0x88) {
   2377                 from += 7;
   2378                 continue;
   2379             }
   2380             // empty square or opponent, skip
   2381             if (!this._board[from] || this._board[from].color === them) {
   2382                 continue;
   2383             }
   2384             const { type } = this._board[from];
   2385             let to;
   2386             if (type === PAWN) {
   2387                 if (forPiece && forPiece !== type)
   2388                     continue;
   2389                 // single square, non-capturing
   2390                 to = from + PAWN_OFFSETS[us][0];
   2391                 if (!this._board[to]) {
   2392                     addMove(moves, us, from, to, PAWN);
   2393                     // double square
   2394                     to = from + PAWN_OFFSETS[us][1];
   2395                     if (SECOND_RANK[us] === rank(from) && !this._board[to]) {
   2396                         addMove(moves, us, from, to, PAWN, undefined, BITS.BIG_PAWN);
   2397                     }
   2398                 }
   2399                 // pawn captures
   2400                 for (let j = 2; j < 4; j++) {
   2401                     to = from + PAWN_OFFSETS[us][j];
   2402                     if (to & 0x88)
   2403                         continue;
   2404                     if (this._board[to]?.color === them) {
   2405                         addMove(moves, us, from, to, PAWN, this._board[to].type, BITS.CAPTURE);
   2406                     }
   2407                     else if (to === this._epSquare) {
   2408                         addMove(moves, us, from, to, PAWN, PAWN, BITS.EP_CAPTURE);
   2409                     }
   2410                 }
   2411             }
   2412             else {
   2413                 if (forPiece && forPiece !== type)
   2414                     continue;
   2415                 for (let j = 0, len = PIECE_OFFSETS[type].length; j < len; j++) {
   2416                     const offset = PIECE_OFFSETS[type][j];
   2417                     to = from;
   2418                     while (true) {
   2419                         to += offset;
   2420                         if (to & 0x88)
   2421                             break;
   2422                         if (!this._board[to]) {
   2423                             addMove(moves, us, from, to, type);
   2424                         }
   2425                         else {
   2426                             // own color, stop loop
   2427                             if (this._board[to].color === us)
   2428                                 break;
   2429                             addMove(moves, us, from, to, type, this._board[to].type, BITS.CAPTURE);
   2430                             break;
   2431                         }
   2432                         /* break, if knight or king */
   2433                         if (type === KNIGHT || type === KING)
   2434                             break;
   2435                     }
   2436                 }
   2437             }
   2438         }
   2439         /*
   2440          * check for castling if we're:
   2441          *   a) generating all moves, or
   2442          *   b) doing single square move generation on the king's square
   2443          */
   2444         if (forPiece === undefined || forPiece === KING) {
   2445             if (!singleSquare || lastSquare === this._kings[us]) {
   2446                 // king-side castling
   2447                 if (this._castling[us] & BITS.KSIDE_CASTLE) {
   2448                     const castlingFrom = this._kings[us];
   2449                     const castlingTo = castlingFrom + 2;
   2450                     if (!this._board[castlingFrom + 1] &&
   2451                         !this._board[castlingTo] &&
   2452                         !this._attacked(them, this._kings[us]) &&
   2453                         !this._attacked(them, castlingFrom + 1) &&
   2454                         !this._attacked(them, castlingTo)) {
   2455                         addMove(moves, us, this._kings[us], castlingTo, KING, undefined, BITS.KSIDE_CASTLE);
   2456                     }
   2457                 }
   2458                 // queen-side castling
   2459                 if (this._castling[us] & BITS.QSIDE_CASTLE) {
   2460                     const castlingFrom = this._kings[us];
   2461                     const castlingTo = castlingFrom - 2;
   2462                     if (!this._board[castlingFrom - 1] &&
   2463                         !this._board[castlingFrom - 2] &&
   2464                         !this._board[castlingFrom - 3] &&
   2465                         !this._attacked(them, this._kings[us]) &&
   2466                         !this._attacked(them, castlingFrom - 1) &&
   2467                         !this._attacked(them, castlingTo)) {
   2468                         addMove(moves, us, this._kings[us], castlingTo, KING, undefined, BITS.QSIDE_CASTLE);
   2469                     }
   2470                 }
   2471             }
   2472         }
   2473         /*
   2474          * return all pseudo-legal moves (this includes moves that allow the king
   2475          * to be captured)
   2476          */
   2477         if (!legal || this._kings[us] === -1) {
   2478             return moves;
   2479         }
   2480         // filter out illegal moves
   2481         const legalMoves = [];
   2482         for (let i = 0, len = moves.length; i < len; i++) {
   2483             this._makeMove(moves[i]);
   2484             if (!this._isKingAttacked(us)) {
   2485                 legalMoves.push(moves[i]);
   2486             }
   2487             this._undoMove();
   2488         }
   2489         return legalMoves;
   2490     }
   2491     move(move, { strict = false } = {}) {
   2492         /*
   2493          * The move function can be called with in the following parameters:
   2494          *
   2495          * .move('Nxb7')       <- argument is a case-sensitive SAN string
   2496          *
   2497          * .move({ from: 'h7', <- argument is a move object
   2498          *         to :'h8',
   2499          *         promotion: 'q' })
   2500          *
   2501          *
   2502          * An optional strict argument may be supplied to tell chess.js to
   2503          * strictly follow the SAN specification.
   2504          */
   2505         let moveObj = null;
   2506         if (typeof move === 'string') {
   2507             moveObj = this._moveFromSan(move, strict);
   2508         }
   2509         else if (move === null) {
   2510             moveObj = this._moveFromSan(SAN_NULLMOVE, strict);
   2511         }
   2512         else if (typeof move === 'object') {
   2513             const moves = this._moves();
   2514             // convert the pretty move object to an ugly move object
   2515             for (let i = 0, len = moves.length; i < len; i++) {
   2516                 if (move.from === algebraic(moves[i].from) &&
   2517                     move.to === algebraic(moves[i].to) &&
   2518                     (!('promotion' in moves[i]) || move.promotion === moves[i].promotion)) {
   2519                     moveObj = moves[i];
   2520                     break;
   2521                 }
   2522             }
   2523         }
   2524         // failed to find move
   2525         if (!moveObj) {
   2526             if (typeof move === 'string') {
   2527                 throw new Error(`Invalid move: ${move}`);
   2528             }
   2529             else {
   2530                 throw new Error(`Invalid move: ${JSON.stringify(move)}`);
   2531             }
   2532         }
   2533         //disallow null moves when in check
   2534         if (this.isCheck() && moveObj.flags & BITS.NULL_MOVE) {
   2535             throw new Error('Null move not allowed when in check');
   2536         }
   2537         /*
   2538          * need to make a copy of move because we can't generate SAN after the move
   2539          * is made
   2540          */
   2541         const prettyMove = new Move(this, moveObj);
   2542         this._makeMove(moveObj);
   2543         this._incPositionCount();
   2544         return prettyMove;
   2545     }
   2546     _push(move) {
   2547         this._history.push({
   2548             move,
   2549             kings: { b: this._kings.b, w: this._kings.w },
   2550             turn: this._turn,
   2551             castling: { b: this._castling.b, w: this._castling.w },
   2552             epSquare: this._epSquare,
   2553             halfMoves: this._halfMoves,
   2554             moveNumber: this._moveNumber,
   2555         });
   2556     }
   2557     _movePiece(from, to) {
   2558         this._hash ^= this._pieceKey(from);
   2559         this._board[to] = this._board[from];
   2560         delete this._board[from];
   2561         this._hash ^= this._pieceKey(to);
   2562     }
   2563     _makeMove(move) {
   2564         const us = this._turn;
   2565         const them = swapColor(us);
   2566         this._push(move);
   2567         if (move.flags & BITS.NULL_MOVE) {
   2568             if (us === BLACK) {
   2569                 this._moveNumber++;
   2570             }
   2571             this._halfMoves++;
   2572             this._turn = them;
   2573             this._epSquare = EMPTY;
   2574             return;
   2575         }
   2576         this._hash ^= this._epKey();
   2577         this._hash ^= this._castlingKey();
   2578         if (move.captured) {
   2579             this._hash ^= this._pieceKey(move.to);
   2580         }
   2581         this._movePiece(move.from, move.to);
   2582         // if ep capture, remove the captured pawn
   2583         if (move.flags & BITS.EP_CAPTURE) {
   2584             if (this._turn === BLACK) {
   2585                 this._clear(move.to - 16);
   2586             }
   2587             else {
   2588                 this._clear(move.to + 16);
   2589             }
   2590         }
   2591         // if pawn promotion, replace with new piece
   2592         if (move.promotion) {
   2593             this._clear(move.to);
   2594             this._set(move.to, { type: move.promotion, color: us });
   2595         }
   2596         // if we moved the king
   2597         if (this._board[move.to].type === KING) {
   2598             this._kings[us] = move.to;
   2599             // if we castled, move the rook next to the king
   2600             if (move.flags & BITS.KSIDE_CASTLE) {
   2601                 const castlingTo = move.to - 1;
   2602                 const castlingFrom = move.to + 1;
   2603                 this._movePiece(castlingFrom, castlingTo);
   2604             }
   2605             else if (move.flags & BITS.QSIDE_CASTLE) {
   2606                 const castlingTo = move.to + 1;
   2607                 const castlingFrom = move.to - 2;
   2608                 this._movePiece(castlingFrom, castlingTo);
   2609             }
   2610             // turn off castling
   2611             this._castling[us] = 0;
   2612         }
   2613         // turn off castling if we move a rook
   2614         if (this._castling[us]) {
   2615             for (let i = 0, len = ROOKS[us].length; i < len; i++) {
   2616                 if (move.from === ROOKS[us][i].square &&
   2617                     this._castling[us] & ROOKS[us][i].flag) {
   2618                     this._castling[us] ^= ROOKS[us][i].flag;
   2619                     break;
   2620                 }
   2621             }
   2622         }
   2623         // turn off castling if we capture a rook
   2624         if (this._castling[them]) {
   2625             for (let i = 0, len = ROOKS[them].length; i < len; i++) {
   2626                 if (move.to === ROOKS[them][i].square &&
   2627                     this._castling[them] & ROOKS[them][i].flag) {
   2628                     this._castling[them] ^= ROOKS[them][i].flag;
   2629                     break;
   2630                 }
   2631             }
   2632         }
   2633         this._hash ^= this._castlingKey();
   2634         // if big pawn move, update the en passant square
   2635         if (move.flags & BITS.BIG_PAWN) {
   2636             let epSquare;
   2637             if (us === BLACK) {
   2638                 epSquare = move.to - 16;
   2639             }
   2640             else {
   2641                 epSquare = move.to + 16;
   2642             }
   2643             if ((!((move.to - 1) & 0x88) &&
   2644                 this._board[move.to - 1]?.type === PAWN &&
   2645                 this._board[move.to - 1]?.color === them) ||
   2646                 (!((move.to + 1) & 0x88) &&
   2647                     this._board[move.to + 1]?.type === PAWN &&
   2648                     this._board[move.to + 1]?.color === them)) {
   2649                 this._epSquare = epSquare;
   2650                 this._hash ^= this._epKey();
   2651             }
   2652             else {
   2653                 this._epSquare = EMPTY;
   2654             }
   2655         }
   2656         else {
   2657             this._epSquare = EMPTY;
   2658         }
   2659         // reset the 50 move counter if a pawn is moved or a piece is captured
   2660         if (move.piece === PAWN) {
   2661             this._halfMoves = 0;
   2662         }
   2663         else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
   2664             this._halfMoves = 0;
   2665         }
   2666         else {
   2667             this._halfMoves++;
   2668         }
   2669         if (us === BLACK) {
   2670             this._moveNumber++;
   2671         }
   2672         this._turn = them;
   2673         this._hash ^= SIDE_KEY;
   2674     }
   2675     undo() {
   2676         const hash = this._hash;
   2677         const move = this._undoMove();
   2678         if (move) {
   2679             const prettyMove = new Move(this, move);
   2680             this._decPositionCount(hash);
   2681             return prettyMove;
   2682         }
   2683         return null;
   2684     }
   2685     _undoMove() {
   2686         const old = this._history.pop();
   2687         if (old === undefined) {
   2688             return null;
   2689         }
   2690         this._hash ^= this._epKey();
   2691         this._hash ^= this._castlingKey();
   2692         const move = old.move;
   2693         this._kings = old.kings;
   2694         this._turn = old.turn;
   2695         this._castling = old.castling;
   2696         this._epSquare = old.epSquare;
   2697         this._halfMoves = old.halfMoves;
   2698         this._moveNumber = old.moveNumber;
   2699         this._hash ^= this._epKey();
   2700         this._hash ^= this._castlingKey();
   2701         this._hash ^= SIDE_KEY;
   2702         const us = this._turn;
   2703         const them = swapColor(us);
   2704         if (move.flags & BITS.NULL_MOVE) {
   2705             return move;
   2706         }
   2707         this._movePiece(move.to, move.from);
   2708         // to undo any promotions
   2709         if (move.piece) {
   2710             this._clear(move.from);
   2711             this._set(move.from, { type: move.piece, color: us });
   2712         }
   2713         if (move.captured) {
   2714             if (move.flags & BITS.EP_CAPTURE) {
   2715                 // en passant capture
   2716                 let index;
   2717                 if (us === BLACK) {
   2718                     index = move.to - 16;
   2719                 }
   2720                 else {
   2721                     index = move.to + 16;
   2722                 }
   2723                 this._set(index, { type: PAWN, color: them });
   2724             }
   2725             else {
   2726                 // regular capture
   2727                 this._set(move.to, { type: move.captured, color: them });
   2728             }
   2729         }
   2730         if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) {
   2731             let castlingTo, castlingFrom;
   2732             if (move.flags & BITS.KSIDE_CASTLE) {
   2733                 castlingTo = move.to + 1;
   2734                 castlingFrom = move.to - 1;
   2735             }
   2736             else {
   2737                 castlingTo = move.to - 2;
   2738                 castlingFrom = move.to + 1;
   2739             }
   2740             this._movePiece(castlingFrom, castlingTo);
   2741         }
   2742         return move;
   2743     }
   2744     pgn({ newline = '\n', maxWidth = 0, } = {}) {
   2745         /*
   2746          * using the specification from http://www.chessclub.com/help/PGN-spec
   2747          * example for html usage: .pgn({ max_width: 72, newline_char: "<br />" })
   2748          */
   2749         const result = [];
   2750         let headerExists = false;
   2751         /* add the PGN header information */
   2752         for (const i in this._header) {
   2753             /*
   2754              * TODO: order of enumerated properties in header object is not
   2755              * guaranteed, see ECMA-262 spec (section 12.6.4)
   2756              *
   2757              * By using HEADER_TEMPLATE, the order of tags should be preserved; we
   2758              * do have to check for null placeholders, though, and omit them
   2759              */
   2760             const headerTag = this._header[i];
   2761             if (headerTag)
   2762                 result.push(`[${i} "${this._header[i]}"]` + newline);
   2763             headerExists = true;
   2764         }
   2765         if (headerExists && this._history.length) {
   2766             result.push(newline);
   2767         }
   2768         const appendComment = (moveString) => {
   2769             const comment = this._comments[this.fen()];
   2770             if (typeof comment !== 'undefined') {
   2771                 const delimiter = moveString.length > 0 ? ' ' : '';
   2772                 moveString = `${moveString}${delimiter}{${comment}}`;
   2773             }
   2774             return moveString;
   2775         };
   2776         // pop all of history onto reversed_history
   2777         const reversedHistory = [];
   2778         while (this._history.length > 0) {
   2779             reversedHistory.push(this._undoMove());
   2780         }
   2781         const moves = [];
   2782         let moveString = '';
   2783         // special case of a commented starting position with no moves
   2784         if (reversedHistory.length === 0) {
   2785             moves.push(appendComment(''));
   2786         }
   2787         // build the list of moves.  a move_string looks like: "3. e3 e6"
   2788         while (reversedHistory.length > 0) {
   2789             moveString = appendComment(moveString);
   2790             const move = reversedHistory.pop();
   2791             // make TypeScript stop complaining about move being undefined
   2792             if (!move) {
   2793                 break;
   2794             }
   2795             // if the position started with black to move, start PGN with #. ...
   2796             if (!this._history.length && move.color === 'b') {
   2797                 const prefix = `${this._moveNumber}. ...`;
   2798                 // is there a comment preceding the first move?
   2799                 moveString = moveString ? `${moveString} ${prefix}` : prefix;
   2800             }
   2801             else if (move.color === 'w') {
   2802                 // store the previous generated move_string if we have one
   2803                 if (moveString.length) {
   2804                     moves.push(moveString);
   2805                 }
   2806                 moveString = this._moveNumber + '.';
   2807             }
   2808             moveString =
   2809                 moveString + ' ' + this._moveToSan(move, this._moves({ legal: true }));
   2810             this._makeMove(move);
   2811         }
   2812         // are there any other leftover moves?
   2813         if (moveString.length) {
   2814             moves.push(appendComment(moveString));
   2815         }
   2816         // is there a result? (there ALWAYS has to be a result according to spec; see Seven Tag Roster)
   2817         moves.push(this._header.Result || '*');
   2818         /*
   2819          * history should be back to what it was before we started generating PGN,
   2820          * so join together moves
   2821          */
   2822         if (maxWidth === 0) {
   2823             return result.join('') + moves.join(' ');
   2824         }
   2825         // TODO (jah): huh?
   2826         const strip = function () {
   2827             if (result.length > 0 && result[result.length - 1] === ' ') {
   2828                 result.pop();
   2829                 return true;
   2830             }
   2831             return false;
   2832         };
   2833         // NB: this does not preserve comment whitespace.
   2834         const wrapComment = function (width, move) {
   2835             for (const token of move.split(' ')) {
   2836                 if (!token) {
   2837                     continue;
   2838                 }
   2839                 if (width + token.length > maxWidth) {
   2840                     while (strip()) {
   2841                         width--;
   2842                     }
   2843                     result.push(newline);
   2844                     width = 0;
   2845                 }
   2846                 result.push(token);
   2847                 width += token.length;
   2848                 result.push(' ');
   2849                 width++;
   2850             }
   2851             if (strip()) {
   2852                 width--;
   2853             }
   2854             return width;
   2855         };
   2856         // wrap the PGN output at max_width
   2857         let currentWidth = 0;
   2858         for (let i = 0; i < moves.length; i++) {
   2859             if (currentWidth + moves[i].length > maxWidth) {
   2860                 if (moves[i].includes('{')) {
   2861                     currentWidth = wrapComment(currentWidth, moves[i]);
   2862                     continue;
   2863                 }
   2864             }
   2865             // if the current move will push past max_width
   2866             if (currentWidth + moves[i].length > maxWidth && i !== 0) {
   2867                 // don't end the line with whitespace
   2868                 if (result[result.length - 1] === ' ') {
   2869                     result.pop();
   2870                 }
   2871                 result.push(newline);
   2872                 currentWidth = 0;
   2873             }
   2874             else if (i !== 0) {
   2875                 result.push(' ');
   2876                 currentWidth++;
   2877             }
   2878             result.push(moves[i]);
   2879             currentWidth += moves[i].length;
   2880         }
   2881         return result.join('');
   2882     }
   2883     /**
   2884      * @deprecated Use `setHeader` and `getHeaders` instead. This method will return null header tags (which is not what you want)
   2885      */
   2886     header(...args) {
   2887         for (let i = 0; i < args.length; i += 2) {
   2888             if (typeof args[i] === 'string' && typeof args[i + 1] === 'string') {
   2889                 this._header[args[i]] = args[i + 1];
   2890             }
   2891         }
   2892         return this._header;
   2893     }
   2894     // TODO: value validation per spec
   2895     setHeader(key, value) {
   2896         this._header[key] = value ?? SEVEN_TAG_ROSTER[key] ?? null;
   2897         return this.getHeaders();
   2898     }
   2899     removeHeader(key) {
   2900         if (key in this._header) {
   2901             this._header[key] = SEVEN_TAG_ROSTER[key] || null;
   2902             return true;
   2903         }
   2904         return false;
   2905     }
   2906     // return only non-null headers (omit placemarker nulls)
   2907     getHeaders() {
   2908         const nonNullHeaders = {};
   2909         for (const [key, value] of Object.entries(this._header)) {
   2910             if (value !== null) {
   2911                 nonNullHeaders[key] = value;
   2912             }
   2913         }
   2914         return nonNullHeaders;
   2915     }
   2916     loadPgn(pgn, { strict = false, newlineChar = '\r?\n', } = {}) {
   2917         // If newlineChar is not the default, replace all instances with \n
   2918         if (newlineChar !== '\r?\n') {
   2919             pgn = pgn.replace(new RegExp(newlineChar, 'g'), '\n');
   2920         }
   2921         const parsedPgn = peg$parse(pgn);
   2922         // Put the board in the starting position
   2923         this.reset();
   2924         // parse PGN header
   2925         const headers = parsedPgn.headers;
   2926         let fen = '';
   2927         for (const key in headers) {
   2928             // check to see user is including fen (possibly with wrong tag case)
   2929             if (key.toLowerCase() === 'fen') {
   2930                 fen = headers[key];
   2931             }
   2932             this.header(key, headers[key]);
   2933         }
   2934         /*
   2935          * the permissive parser should attempt to load a fen tag, even if it's the
   2936          * wrong case and doesn't include a corresponding [SetUp "1"] tag
   2937          */
   2938         if (!strict) {
   2939             if (fen) {
   2940                 this.load(fen, { preserveHeaders: true });
   2941             }
   2942         }
   2943         else {
   2944             /*
   2945              * strict parser - load the starting position indicated by [Setup '1']
   2946              * and [FEN position]
   2947              */
   2948             if (headers['SetUp'] === '1') {
   2949                 if (!('FEN' in headers)) {
   2950                     throw new Error('Invalid PGN: FEN tag must be supplied with SetUp tag');
   2951                 }
   2952                 // don't clear the headers when loading
   2953                 this.load(headers['FEN'], { preserveHeaders: true });
   2954             }
   2955         }
   2956         let node = parsedPgn.root;
   2957         while (node) {
   2958             if (node.move) {
   2959                 const move = this._moveFromSan(node.move, strict);
   2960                 if (move == null) {
   2961                     throw new Error(`Invalid move in PGN: ${node.move}`);
   2962                 }
   2963                 else {
   2964                     this._makeMove(move);
   2965                     this._incPositionCount();
   2966                 }
   2967             }
   2968             if (node.comment !== undefined) {
   2969                 this._comments[this.fen()] = node.comment;
   2970             }
   2971             node = node.variations[0];
   2972         }
   2973         /*
   2974          * Per section 8.2.6 of the PGN spec, the Result tag pair must match match
   2975          * the termination marker. Only do this when headers are present, but the
   2976          * result tag is missing
   2977          */
   2978         const result = parsedPgn.result;
   2979         if (result &&
   2980             Object.keys(this._header).length &&
   2981             this._header['Result'] !== result) {
   2982             this.setHeader('Result', result);
   2983         }
   2984     }
   2985     /*
   2986      * Convert a move from 0x88 coordinates to Standard Algebraic Notation
   2987      * (SAN)
   2988      *
   2989      * @param {boolean} strict Use the strict SAN parser. It will throw errors
   2990      * on overly disambiguated moves (see below):
   2991      *
   2992      * r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4
   2993      * 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned
   2994      * 4. ... Ne7 is technically the valid SAN
   2995      */
   2996     _moveToSan(move, moves) {
   2997         let output = '';
   2998         if (move.flags & BITS.KSIDE_CASTLE) {
   2999             output = 'O-O';
   3000         }
   3001         else if (move.flags & BITS.QSIDE_CASTLE) {
   3002             output = 'O-O-O';
   3003         }
   3004         else if (move.flags & BITS.NULL_MOVE) {
   3005             return SAN_NULLMOVE;
   3006         }
   3007         else {
   3008             if (move.piece !== PAWN) {
   3009                 const disambiguator = getDisambiguator(move, moves);
   3010                 output += move.piece.toUpperCase() + disambiguator;
   3011             }
   3012             if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
   3013                 if (move.piece === PAWN) {
   3014                     output += algebraic(move.from)[0];
   3015                 }
   3016                 output += 'x';
   3017             }
   3018             output += algebraic(move.to);
   3019             if (move.promotion) {
   3020                 output += '=' + move.promotion.toUpperCase();
   3021             }
   3022         }
   3023         this._makeMove(move);
   3024         if (this.isCheck()) {
   3025             if (this.isCheckmate()) {
   3026                 output += '#';
   3027             }
   3028             else {
   3029                 output += '+';
   3030             }
   3031         }
   3032         this._undoMove();
   3033         return output;
   3034     }
   3035     // convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates
   3036     _moveFromSan(move, strict = false) {
   3037         // strip off any move decorations: e.g Nf3+?! becomes Nf3
   3038         let cleanMove = strippedSan(move);
   3039         if (!strict) {
   3040             if (cleanMove === '0-0') {
   3041                 cleanMove = 'O-O';
   3042             }
   3043             else if (cleanMove === '0-0-0') {
   3044                 cleanMove = 'O-O-O';
   3045             }
   3046         }
   3047         //first implementation of null with a dummy move (black king moves from a8 to a8), maybe this can be implemented better
   3048         if (cleanMove == SAN_NULLMOVE) {
   3049             const res = {
   3050                 color: this._turn,
   3051                 from: 0,
   3052                 to: 0,
   3053                 piece: 'k',
   3054                 flags: BITS.NULL_MOVE,
   3055             };
   3056             return res;
   3057         }
   3058         let pieceType = inferPieceType(cleanMove);
   3059         let moves = this._moves({ legal: true, piece: pieceType });
   3060         // strict parser
   3061         for (let i = 0, len = moves.length; i < len; i++) {
   3062             if (cleanMove === strippedSan(this._moveToSan(moves[i], moves))) {
   3063                 return moves[i];
   3064             }
   3065         }
   3066         // the strict parser failed
   3067         if (strict) {
   3068             return null;
   3069         }
   3070         let piece = undefined;
   3071         let matches = undefined;
   3072         let from = undefined;
   3073         let to = undefined;
   3074         let promotion = undefined;
   3075         /*
   3076          * The default permissive (non-strict) parser allows the user to parse
   3077          * non-standard chess notations. This parser is only run after the strict
   3078          * Standard Algebraic Notation (SAN) parser has failed.
   3079          *
   3080          * When running the permissive parser, we'll run a regex to grab the piece, the
   3081          * to/from square, and an optional promotion piece. This regex will
   3082          * parse common non-standard notation like: Pe2-e4, Rc1c4, Qf3xf7,
   3083          * f7f8q, b1c3
   3084          *
   3085          * NOTE: Some positions and moves may be ambiguous when using the permissive
   3086          * parser. For example, in this position: 6k1/8/8/B7/8/8/8/BN4K1 w - - 0 1,
   3087          * the move b1c3 may be interpreted as Nc3 or B1c3 (a disambiguated bishop
   3088          * move). In these cases, the permissive parser will default to the most
   3089          * basic interpretation (which is b1c3 parsing to Nc3).
   3090          */
   3091         let overlyDisambiguated = false;
   3092         matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/);
   3093         if (matches) {
   3094             piece = matches[1];
   3095             from = matches[2];
   3096             to = matches[3];
   3097             promotion = matches[4];
   3098             if (from.length == 1) {
   3099                 overlyDisambiguated = true;
   3100             }
   3101         }
   3102         else {
   3103             /*
   3104              * The [a-h]?[1-8]? portion of the regex below handles moves that may be
   3105              * overly disambiguated (e.g. Nge7 is unnecessary and non-standard when
   3106              * there is one legal knight move to e7). In this case, the value of
   3107              * 'from' variable will be a rank or file, not a square.
   3108              */
   3109             matches = cleanMove.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/);
   3110             if (matches) {
   3111                 piece = matches[1];
   3112                 from = matches[2];
   3113                 to = matches[3];
   3114                 promotion = matches[4];
   3115                 if (from.length == 1) {
   3116                     overlyDisambiguated = true;
   3117                 }
   3118             }
   3119         }
   3120         pieceType = inferPieceType(cleanMove);
   3121         moves = this._moves({
   3122             legal: true,
   3123             piece: piece ? piece : pieceType,
   3124         });
   3125         if (!to) {
   3126             return null;
   3127         }
   3128         for (let i = 0, len = moves.length; i < len; i++) {
   3129             if (!from) {
   3130                 // if there is no from square, it could be just 'x' missing from a capture
   3131                 if (cleanMove ===
   3132                     strippedSan(this._moveToSan(moves[i], moves)).replace('x', '')) {
   3133                     return moves[i];
   3134                 }
   3135                 // hand-compare move properties with the results from our permissive regex
   3136             }
   3137             else if ((!piece || piece.toLowerCase() == moves[i].piece) &&
   3138                 Ox88[from] == moves[i].from &&
   3139                 Ox88[to] == moves[i].to &&
   3140                 (!promotion || promotion.toLowerCase() == moves[i].promotion)) {
   3141                 return moves[i];
   3142             }
   3143             else if (overlyDisambiguated) {
   3144                 /*
   3145                  * SPECIAL CASE: we parsed a move string that may have an unneeded
   3146                  * rank/file disambiguator (e.g. Nge7).  The 'from' variable will
   3147                  */
   3148                 const square = algebraic(moves[i].from);
   3149                 if ((!piece || piece.toLowerCase() == moves[i].piece) &&
   3150                     Ox88[to] == moves[i].to &&
   3151                     (from == square[0] || from == square[1]) &&
   3152                     (!promotion || promotion.toLowerCase() == moves[i].promotion)) {
   3153                     return moves[i];
   3154                 }
   3155             }
   3156         }
   3157         return null;
   3158     }
   3159     ascii() {
   3160         let s = '   +------------------------+\n';
   3161         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   3162             // display the rank
   3163             if (file(i) === 0) {
   3164                 s += ' ' + '87654321'[rank(i)] + ' |';
   3165             }
   3166             if (this._board[i]) {
   3167                 const piece = this._board[i].type;
   3168                 const color = this._board[i].color;
   3169                 const symbol = color === WHITE ? piece.toUpperCase() : piece.toLowerCase();
   3170                 s += ' ' + symbol + ' ';
   3171             }
   3172             else {
   3173                 s += ' . ';
   3174             }
   3175             if ((i + 1) & 0x88) {
   3176                 s += '|\n';
   3177                 i += 8;
   3178             }
   3179         }
   3180         s += '   +------------------------+\n';
   3181         s += '     a  b  c  d  e  f  g  h';
   3182         return s;
   3183     }
   3184     perft(depth) {
   3185         const moves = this._moves({ legal: false });
   3186         let nodes = 0;
   3187         const color = this._turn;
   3188         for (let i = 0, len = moves.length; i < len; i++) {
   3189             this._makeMove(moves[i]);
   3190             if (!this._isKingAttacked(color)) {
   3191                 if (depth - 1 > 0) {
   3192                     nodes += this.perft(depth - 1);
   3193                 }
   3194                 else {
   3195                     nodes++;
   3196                 }
   3197             }
   3198             this._undoMove();
   3199         }
   3200         return nodes;
   3201     }
   3202     setTurn(color) {
   3203         if (this._turn == color) {
   3204             return false;
   3205         }
   3206         this.move('--');
   3207         return true;
   3208     }
   3209     turn() {
   3210         return this._turn;
   3211     }
   3212     board() {
   3213         const output = [];
   3214         let row = [];
   3215         for (let i = Ox88.a8; i <= Ox88.h1; i++) {
   3216             if (this._board[i] == null) {
   3217                 row.push(null);
   3218             }
   3219             else {
   3220                 row.push({
   3221                     square: algebraic(i),
   3222                     type: this._board[i].type,
   3223                     color: this._board[i].color,
   3224                 });
   3225             }
   3226             if ((i + 1) & 0x88) {
   3227                 output.push(row);
   3228                 row = [];
   3229                 i += 8;
   3230             }
   3231         }
   3232         return output;
   3233     }
   3234     squareColor(square) {
   3235         if (square in Ox88) {
   3236             const sq = Ox88[square];
   3237             return (rank(sq) + file(sq)) % 2 === 0 ? 'light' : 'dark';
   3238         }
   3239         return null;
   3240     }
   3241     history({ verbose = false } = {}) {
   3242         const reversedHistory = [];
   3243         const moveHistory = [];
   3244         while (this._history.length > 0) {
   3245             reversedHistory.push(this._undoMove());
   3246         }
   3247         while (true) {
   3248             const move = reversedHistory.pop();
   3249             if (!move) {
   3250                 break;
   3251             }
   3252             if (verbose) {
   3253                 moveHistory.push(new Move(this, move));
   3254             }
   3255             else {
   3256                 moveHistory.push(this._moveToSan(move, this._moves()));
   3257             }
   3258             this._makeMove(move);
   3259         }
   3260         return moveHistory;
   3261     }
   3262     /*
   3263      * Keeps track of position occurrence counts for the purpose of repetition
   3264      * checking. Old positions are removed from the map if their counts are reduced to 0.
   3265      */
   3266     _getPositionCount(hash) {
   3267         return this._positionCount.get(hash) ?? 0;
   3268     }
   3269     _incPositionCount() {
   3270         this._positionCount.set(this._hash, (this._positionCount.get(this._hash) ?? 0) + 1);
   3271     }
   3272     _decPositionCount(hash) {
   3273         const currentCount = this._positionCount.get(hash) ?? 0;
   3274         if (currentCount === 1) {
   3275             this._positionCount.delete(hash);
   3276         }
   3277         else {
   3278             this._positionCount.set(hash, currentCount - 1);
   3279         }
   3280     }
   3281     _pruneComments() {
   3282         const reversedHistory = [];
   3283         const currentComments = {};
   3284         const copyComment = (fen) => {
   3285             if (fen in this._comments) {
   3286                 currentComments[fen] = this._comments[fen];
   3287             }
   3288         };
   3289         while (this._history.length > 0) {
   3290             reversedHistory.push(this._undoMove());
   3291         }
   3292         copyComment(this.fen());
   3293         while (true) {
   3294             const move = reversedHistory.pop();
   3295             if (!move) {
   3296                 break;
   3297             }
   3298             this._makeMove(move);
   3299             copyComment(this.fen());
   3300         }
   3301         this._comments = currentComments;
   3302     }
   3303     getComment() {
   3304         return this._comments[this.fen()];
   3305     }
   3306     setComment(comment) {
   3307         this._comments[this.fen()] = comment.replace('{', '[').replace('}', ']');
   3308     }
   3309     /**
   3310      * @deprecated Renamed to `removeComment` for consistency
   3311      */
   3312     deleteComment() {
   3313         return this.removeComment();
   3314     }
   3315     removeComment() {
   3316         const comment = this._comments[this.fen()];
   3317         delete this._comments[this.fen()];
   3318         return comment;
   3319     }
   3320     getComments() {
   3321         this._pruneComments();
   3322         return Object.keys(this._comments).map((fen) => {
   3323             return { fen: fen, comment: this._comments[fen] };
   3324         });
   3325     }
   3326     /**
   3327      * @deprecated Renamed to `removeComments` for consistency
   3328      */
   3329     deleteComments() {
   3330         return this.removeComments();
   3331     }
   3332     removeComments() {
   3333         this._pruneComments();
   3334         return Object.keys(this._comments).map((fen) => {
   3335             const comment = this._comments[fen];
   3336             delete this._comments[fen];
   3337             return { fen: fen, comment: comment };
   3338         });
   3339     }
   3340     setCastlingRights(color, rights) {
   3341         for (const side of [KING, QUEEN]) {
   3342             if (rights[side] !== undefined) {
   3343                 if (rights[side]) {
   3344                     this._castling[color] |= SIDES[side];
   3345                 }
   3346                 else {
   3347                     this._castling[color] &= ~SIDES[side];
   3348                 }
   3349             }
   3350         }
   3351         this._updateCastlingRights();
   3352         const result = this.getCastlingRights(color);
   3353         return ((rights[KING] === undefined || rights[KING] === result[KING]) &&
   3354             (rights[QUEEN] === undefined || rights[QUEEN] === result[QUEEN]));
   3355     }
   3356     getCastlingRights(color) {
   3357         return {
   3358             [KING]: (this._castling[color] & SIDES[KING]) !== 0,
   3359             [QUEEN]: (this._castling[color] & SIDES[QUEEN]) !== 0,
   3360         };
   3361     }
   3362     moveNumber() {
   3363         return this._moveNumber;
   3364     }
   3365 }
   3366 
   3367 export { BISHOP, BLACK, Chess, DEFAULT_POSITION, KING, KNIGHT, Move, PAWN, QUEEN, ROOK, SEVEN_TAG_ROSTER, SQUARES, WHITE, validateFen, xoroshiro128 };
   3368 //# sourceMappingURL=chess.js.map