@lichess-org/pgn-viewer 2.5.1 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/demo/lichess-pgn-viewer.js +353 -240
- package/dist/config.d.ts +1 -1
- package/dist/interfaces.d.ts +2 -2
- package/dist/lichess-pgn-viewer.min.js +4 -4
- package/dist/pgnViewer.d.ts +2 -2
- package/dist/pgnViewer.js +1 -1
- package/dist/pgnViewer.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/view/accessibleBoard.js +3 -3
- package/dist/view/accessibleBoard.js.map +1 -1
- package/dist/view/main.d.ts +1 -1
- package/dist/view/main.js +1 -1
- package/dist/view/main.js.map +1 -1
- package/dist/view/util.d.ts +1 -1
- package/package.json +8 -4
- package/src/interfaces.ts +2 -2
- package/src/pgnViewer.ts +3 -3
- package/src/view/accessibleBoard.ts +3 -3
- package/src/view/main.ts +2 -2
- package/src/view/util.ts +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ee=["a","b","c","d","e","f","g","h"],nt=["1","2","3","4","5","6","7","8"];var F=["white","black"],U=["pawn","knight","bishop","rook","queen","king"],zn=["a","h"],oe=e=>"role"in e;var g=e=>e!==void 0,M=e=>e==="white"?"black":"white",J=e=>e>>3,L=e=>e&7,rt=(e,t)=>0<=e&&e<8&&0<=t&&t<8?e+8*t:void 0,se=e=>{switch(e){case"pawn":return"p";case"knight":return"n";case"bishop":return"b";case"rook":return"r";case"queen":return"q";case"king":return"k"}};function Ae(e){switch(e.toLowerCase()){case"p":return"pawn";case"n":return"knight";case"b":return"bishop";case"r":return"rook";case"q":return"queen";case"k":return"king";default:return}}function he(e){if(e.length===2)return rt(e.charCodeAt(0)-97,e.charCodeAt(1)-49)}var j=e=>Ee[L(e)]+nt[J(e)];var zt=e=>oe(e)?`${se(e.role).toUpperCase()}@${j(e.to)}`:j(e.from)+j(e.to)+(e.promotion?se(e.promotion):""),Ke=(e,t)=>e==="white"?t==="a"?2:6:t==="a"?58:62,it=(e,t)=>e==="white"?t==="a"?3:5:t==="a"?59:61;var Vn=e=>(e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),Math.imul(e+(e>>>4)&252645135,16843009)>>24),Vt=e=>(e=e>>>8&16711935|(e&16711935)<<8,e>>>16&65535|(e&65535)<<16),Fn=e=>(e=e>>>1&1431655765|(e&1431655765)<<1,e=e>>>2&858993459|(e&858993459)<<2,e=e>>>4&252645135|(e&252645135)<<4,Vt(e)),u=class e{constructor(t,n){this.lo=t|0,this.hi=n|0}static fromSquare(t){return t>=32?new e(0,1<<t-32):new e(1<<t,0)}static fromRank(t){return new e(255,0).shl64(8*t)}static fromFile(t){return new e(16843009<<t,16843009<<t)}static empty(){return new e(0,0)}static full(){return new e(4294967295,4294967295)}static corners(){return new e(129,2164260864)}static center(){return new e(402653184,24)}static backranks(){return new e(255,4278190080)}static backrank(t){return t==="white"?new e(255,0):new e(0,4278190080)}static lightSquares(){return new e(1437226410,1437226410)}static darkSquares(){return new e(2857740885,2857740885)}complement(){return new e(~this.lo,~this.hi)}xor(t){return new e(this.lo^t.lo,this.hi^t.hi)}union(t){return new e(this.lo|t.lo,this.hi|t.hi)}intersect(t){return new e(this.lo&t.lo,this.hi&t.hi)}diff(t){return new e(this.lo&~t.lo,this.hi&~t.hi)}intersects(t){return this.intersect(t).nonEmpty()}isDisjoint(t){return this.intersect(t).isEmpty()}supersetOf(t){return t.diff(this).isEmpty()}subsetOf(t){return this.diff(t).isEmpty()}shr64(t){return t>=64?e.empty():t>=32?new e(this.hi>>>t-32,0):t>0?new e(this.lo>>>t^this.hi<<32-t,this.hi>>>t):this}shl64(t){return t>=64?e.empty():t>=32?new e(0,this.lo<<t-32):t>0?new e(this.lo<<t,this.hi<<t^this.lo>>>32-t):this}bswap64(){return new e(Vt(this.hi),Vt(this.lo))}rbit64(){return new e(Fn(this.hi),Fn(this.lo))}minus64(t){let n=this.lo-t.lo,r=(n&t.lo&1)+(t.lo>>>1)+(n>>>1)>>>31;return new e(n,this.hi-(t.hi+r))}equals(t){return this.lo===t.lo&&this.hi===t.hi}size(){return Vn(this.lo)+Vn(this.hi)}isEmpty(){return this.lo===0&&this.hi===0}nonEmpty(){return this.lo!==0||this.hi!==0}has(t){return(t>=32?this.hi&1<<t-32:this.lo&1<<t)!==0}set(t,n){return n?this.with(t):this.without(t)}with(t){return t>=32?new e(this.lo,this.hi|1<<t-32):new e(this.lo|1<<t,this.hi)}without(t){return t>=32?new e(this.lo,this.hi&~(1<<t-32)):new e(this.lo&~(1<<t),this.hi)}toggle(t){return t>=32?new e(this.lo,this.hi^1<<t-32):new e(this.lo^1<<t,this.hi)}last(){if(this.hi!==0)return 63-Math.clz32(this.hi);if(this.lo!==0)return 31-Math.clz32(this.lo)}first(){if(this.lo!==0)return 31-Math.clz32(this.lo&-this.lo);if(this.hi!==0)return 63-Math.clz32(this.hi&-this.hi)}withoutFirst(){return this.lo!==0?new e(this.lo&this.lo-1,this.hi):new e(0,this.hi&this.hi-1)}moreThanOne(){return this.hi!==0&&this.lo!==0||(this.lo&this.lo-1)!==0||(this.hi&this.hi-1)!==0}singleSquare(){return this.moreThanOne()?void 0:this.last()}*[Symbol.iterator](){let t=this.lo,n=this.hi;for(;t!==0;){let r=31-Math.clz32(t&-t);t^=1<<r,yield r}for(;n!==0;){let r=31-Math.clz32(n&-n);n^=1<<r,yield 32+r}}*reversed(){let t=this.lo,n=this.hi;for(;n!==0;){let r=31-Math.clz32(n);n^=1<<r,yield 32+r}for(;t!==0;){let r=31-Math.clz32(t);t^=1<<r,yield r}}};var ot=(e,t)=>{let n=u.empty();for(let r of t){let i=e+r;0<=i&&i<64&&Math.abs(L(e)-L(i))<=2&&(n=n.with(i))}return n},be=e=>{let t=[];for(let n=0;n<64;n++)t[n]=e(n);return t},qi=be(e=>ot(e,[-9,-8,-7,-1,1,7,8,9])),Di=be(e=>ot(e,[-17,-15,-10,-6,6,10,15,17])),Li={white:be(e=>ot(e,[7,9])),black:be(e=>ot(e,[-7,-9]))},ae=e=>qi[e],qe=e=>Di[e],we=(e,t)=>Li[e][t],Ft=be(e=>u.fromFile(L(e)).without(e)),Ht=be(e=>u.fromRank(J(e)).without(e)),Gt=be(e=>{let t=new u(134480385,2151686160),n=8*(J(e)-L(e));return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),Wt=be(e=>{let t=new u(270549120,16909320),n=8*(J(e)+L(e)-7);return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),Ut=(e,t,n)=>{let r=n.intersect(t),i=r.bswap64();return r=r.minus64(e),i=i.minus64(e.bswap64()),r.xor(i.bswap64()).intersect(t)},Bi=(e,t)=>Ut(u.fromSquare(e),Ft[e],t),Ii=(e,t)=>{let n=Ht[e],r=t.intersect(n),i=r.rbit64();return r=r.minus64(u.fromSquare(e)),i=i.minus64(u.fromSquare(63-e)),r.xor(i.rbit64()).intersect(n)},ve=(e,t)=>{let n=u.fromSquare(e);return Ut(n,Gt[e],t).xor(Ut(n,Wt[e],t))},ye=(e,t)=>Bi(e,t).xor(Ii(e,t)),$e=(e,t)=>ve(e,t).xor(ye(e,t)),st=(e,t,n)=>{switch(e.role){case"pawn":return we(e.color,t);case"knight":return qe(t);case"bishop":return ve(t,n);case"rook":return ye(t,n);case"queen":return $e(t,n);case"king":return ae(t)}},jt=(e,t)=>{let n=u.fromSquare(t);return Ht[e].intersects(n)?Ht[e].with(e):Wt[e].intersects(n)?Wt[e].with(e):Gt[e].intersects(n)?Gt[e].with(e):Ft[e].intersects(n)?Ft[e].with(e):u.empty()},xe=(e,t)=>jt(e,t).intersect(u.full().shl64(e).xor(u.full().shl64(t))).withoutFirst();var de=class e{constructor(){}static default(){let t=new e;return t.reset(),t}reset(){this.occupied=new u(65535,4294901760),this.promoted=u.empty(),this.white=new u(65535,0),this.black=new u(0,4294901760),this.pawn=new u(65280,16711680),this.knight=new u(66,1107296256),this.bishop=new u(36,603979776),this.rook=new u(129,2164260864),this.queen=new u(8,134217728),this.king=new u(16,268435456)}static empty(){let t=new e;return t.clear(),t}clear(){this.occupied=u.empty(),this.promoted=u.empty();for(let t of F)this[t]=u.empty();for(let t of U)this[t]=u.empty()}clone(){let t=new e;t.occupied=this.occupied,t.promoted=this.promoted;for(let n of F)t[n]=this[n];for(let n of U)t[n]=this[n];return t}getColor(t){if(this.white.has(t))return"white";if(this.black.has(t))return"black"}getRole(t){for(let n of U)if(this[n].has(t))return n}get(t){let n=this.getColor(t);if(!n)return;let r=this.getRole(t),i=this.promoted.has(t);return{color:n,role:r,promoted:i}}take(t){let n=this.get(t);return n&&(this.occupied=this.occupied.without(t),this[n.color]=this[n.color].without(t),this[n.role]=this[n.role].without(t),n.promoted&&(this.promoted=this.promoted.without(t))),n}set(t,n){let r=this.take(t);return this.occupied=this.occupied.with(t),this[n.color]=this[n.color].with(t),this[n.role]=this[n.role].with(t),n.promoted&&(this.promoted=this.promoted.with(t)),r}has(t){return this.occupied.has(t)}*[Symbol.iterator](){for(let t of this.occupied)yield[t,this.get(t)]}pieces(t,n){return this[t].intersect(this[n])}rooksAndQueens(){return this.rook.union(this.queen)}bishopsAndQueens(){return this.bishop.union(this.queen)}steppers(){return this.knight.union(this.pawn).union(this.king)}sliders(){return this.bishop.union(this.rook).union(this.queen)}kingOf(t){return this.pieces(t,"king").singleSquare()}};var fe=class e{constructor(){}static empty(){let t=new e;for(let n of U)t[n]=0;return t}static fromBoard(t,n){let r=new e;for(let i of U)r[i]=t.pieces(n,i).size();return r}clone(){let t=new e;for(let n of U)t[n]=this[n];return t}equals(t){return U.every(n=>this[n]===t[n])}add(t){let n=new e;for(let r of U)n[r]=this[r]+t[r];return n}subtract(t){let n=new e;for(let r of U)n[r]=this[r]-t[r];return n}nonEmpty(){return U.some(t=>this[t]>0)}isEmpty(){return!this.nonEmpty()}hasPawns(){return this.pawn>0}hasNonPawns(){return this.knight>0||this.bishop>0||this.rook>0||this.queen>0||this.king>0}size(){return this.pawn+this.knight+this.bishop+this.rook+this.queen+this.king}},_e=class e{constructor(t,n){this.white=t,this.black=n}static empty(){return new e(fe.empty(),fe.empty())}static fromBoard(t){return new e(fe.fromBoard(t,"white"),fe.fromBoard(t,"black"))}clone(){return new e(this.white.clone(),this.black.clone())}equals(t){return this.white.equals(t.white)&&this.black.equals(t.black)}add(t){return new e(this.white.add(t.white),this.black.add(t.black))}subtract(t){return new e(this.white.subtract(t.white),this.black.subtract(t.black))}count(t){return this.white[t]+this.black[t]}size(){return this.white.size()+this.black.size()}isEmpty(){return this.white.isEmpty()&&this.black.isEmpty()}nonEmpty(){return!this.isEmpty()}hasPawns(){return this.white.hasPawns()||this.black.hasPawns()}hasNonPawns(){return this.white.hasNonPawns()||this.black.hasNonPawns()}},Se=class e{constructor(t,n){this.white=t,this.black=n}static default(){return new e(3,3)}clone(){return new e(this.white,this.black)}equals(t){return this.white===t.white&&this.black===t.black}};var at=class{unwrap(t,n){let r=this._chain(i=>m.ok(t?t(i):i),i=>n?m.ok(n(i)):m.err(i));if(r.isErr)throw r.error;return r.value}map(t,n){return this._chain(r=>m.ok(t(r)),r=>m.err(n?n(r):r))}chain(t,n){return this._chain(t,n??(r=>m.err(r)))}},Yt=class extends at{constructor(t){super(),this.value=t,this.isOk=!0,this.isErr=!1}_chain(t,n){return t(this.value)}},Zt=class extends at{constructor(t){super(),this.error=t,this.isOk=!1,this.isErr=!0}_chain(t,n){return n(this.error)}},m;(function(e){function t(i){return new Yt(i)}e.ok=t;function n(i){return new Zt(i||new Error)}e.err=n;function r(i){if(Array.isArray(i)){let a=[];for(let l=0;l<i.length;l++){let c=i[l];if(c.isErr)return c;a.push(c.value)}return e.ok(a)}let o={},s=Object.keys(i);for(let a=0;a<s.length;a++){let l=i[s[a]];if(l.isErr)return l;o[s[a]]=l.value}return e.ok(o)}e.all=r})(m||(m={}));var q;(function(e){e.Empty="ERR_EMPTY",e.OppositeCheck="ERR_OPPOSITE_CHECK",e.PawnsOnBackrank="ERR_PAWNS_ON_BACKRANK",e.Kings="ERR_KINGS",e.Variant="ERR_VARIANT"})(q||(q={}));var D=class extends Error{},Ki=(e,t,n,r)=>n[t].intersect(ye(e,r).intersect(n.rooksAndQueens()).union(ve(e,r).intersect(n.bishopsAndQueens())).union(qe(e).intersect(n.knight)).union(ae(e).intersect(n.king)).union(we(M(t),e).intersect(n.pawn))),ce=class e{constructor(){}static default(){let t=new e;return t.castlingRights=u.corners(),t.rook={white:{a:0,h:7},black:{a:56,h:63}},t.path={white:{a:new u(14,0),h:new u(96,0)},black:{a:new u(0,234881024),h:new u(0,1610612736)}},t}static empty(){let t=new e;return t.castlingRights=u.empty(),t.rook={white:{a:void 0,h:void 0},black:{a:void 0,h:void 0}},t.path={white:{a:u.empty(),h:u.empty()},black:{a:u.empty(),h:u.empty()}},t}clone(){let t=new e;return t.castlingRights=this.castlingRights,t.rook={white:{a:this.rook.white.a,h:this.rook.white.h},black:{a:this.rook.black.a,h:this.rook.black.h}},t.path={white:{a:this.path.white.a,h:this.path.white.h},black:{a:this.path.black.a,h:this.path.black.h}},t}add(t,n,r,i){let o=Ke(t,n),s=it(t,n);this.castlingRights=this.castlingRights.with(i),this.rook[t][n]=i,this.path[t][n]=xe(i,s).with(s).union(xe(r,o).with(o)).without(r).without(i)}static fromSetup(t){let n=e.empty(),r=t.castlingRights.intersect(t.board.rook);for(let i of F){let o=u.backrank(i),s=t.board.kingOf(i);if(!g(s)||!o.has(s))continue;let a=r.intersect(t.board[i]).intersect(o),l=a.first();g(l)&&l<s&&n.add(i,"a",s,l);let c=a.last();g(c)&&s<c&&n.add(i,"h",s,c)}return n}discardRook(t){if(this.castlingRights.has(t)){this.castlingRights=this.castlingRights.without(t);for(let n of F)for(let r of zn)this.rook[n][r]===t&&(this.rook[n][r]=void 0)}}discardColor(t){this.castlingRights=this.castlingRights.diff(u.backrank(t)),this.rook[t].a=void 0,this.rook[t].h=void 0}},ee=class{constructor(t){this.rules=t}reset(){this.board=de.default(),this.pockets=void 0,this.turn="white",this.castles=ce.default(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){this.board=t.board.clone(),this.board.promoted=u.empty(),this.pockets=void 0,this.turn=t.turn,this.castles=ce.fromSetup(t),this.epSquare=$i(this,t.epSquare),this.remainingChecks=void 0,this.halfmoves=t.halfmoves,this.fullmoves=t.fullmoves}kingAttackers(t,n,r){return Ki(t,n,this.board,r)}playCaptureAt(t,n){this.halfmoves=0,n.role==="rook"&&this.castles.discardRook(t),this.pockets&&this.pockets[M(n.color)][n.promoted?"pawn":n.role]++}ctx(){let t=this.isVariantEnd(),n=this.board.kingOf(this.turn);if(!g(n))return{king:n,blockers:u.empty(),checkers:u.empty(),variantEnd:t,mustCapture:!1};let r=ye(n,u.empty()).intersect(this.board.rooksAndQueens()).union(ve(n,u.empty()).intersect(this.board.bishopsAndQueens())).intersect(this.board[M(this.turn)]),i=u.empty();for(let s of r){let a=xe(n,s).intersect(this.board.occupied);a.moreThanOne()||(i=i.union(a))}let o=this.kingAttackers(n,M(this.turn),this.board.occupied);return{king:n,blockers:i,checkers:o,variantEnd:t,mustCapture:!1}}clone(){var t,n;let r=new this.constructor;return r.board=this.board.clone(),r.pockets=(t=this.pockets)===null||t===void 0?void 0:t.clone(),r.turn=this.turn,r.castles=this.castles.clone(),r.epSquare=this.epSquare,r.remainingChecks=(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),r.halfmoves=this.halfmoves,r.fullmoves=this.fullmoves,r}validate(){if(this.board.occupied.isEmpty())return m.err(new D(q.Empty));if(this.board.king.size()!==2)return m.err(new D(q.Kings));if(!g(this.board.kingOf(this.turn)))return m.err(new D(q.Kings));let t=this.board.kingOf(M(this.turn));return g(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?m.err(new D(q.OppositeCheck)):u.backranks().intersects(this.board.pawn)?m.err(new D(q.PawnsOnBackrank)):m.ok(void 0):m.err(new D(q.Kings))}dropDests(t){return u.empty()}dests(t,n){if(n=n||this.ctx(),n.variantEnd)return u.empty();let r=this.board.get(t);if(!r||r.color!==this.turn)return u.empty();let i,o;if(r.role==="pawn"){i=we(this.turn,t).intersect(this.board[M(this.turn)]);let s=this.turn==="white"?8:-8,a=t+s;if(0<=a&&a<64&&!this.board.occupied.has(a)){i=i.with(a);let l=this.turn==="white"?t<16:t>=48,c=a+s;l&&!this.board.occupied.has(c)&&(i=i.with(c))}g(this.epSquare)&&Vi(this,t,n)&&(o=u.fromSquare(this.epSquare))}else r.role==="bishop"?i=ve(t,this.board.occupied):r.role==="knight"?i=qe(t):r.role==="rook"?i=ye(t,this.board.occupied):r.role==="queen"?i=$e(t,this.board.occupied):i=ae(t);if(i=i.diff(this.board[this.turn]),g(n.king)){if(r.role==="king"){let s=this.board.occupied.without(t);for(let a of i)this.kingAttackers(a,M(this.turn),s).nonEmpty()&&(i=i.without(a));return i.union(ct(this,"a",n)).union(ct(this,"h",n))}if(n.checkers.nonEmpty()){let s=n.checkers.singleSquare();if(!g(s))return u.empty();i=i.intersect(xe(s,n.king).with(s))}n.blockers.has(t)&&(i=i.intersect(jt(t,n.king)))}return o&&(i=i.union(o)),i}isVariantEnd(){return!1}variantOutcome(t){}hasInsufficientMaterial(t){return this.board[t].intersect(this.board.pawn.union(this.board.rooksAndQueens())).nonEmpty()?!1:this.board[t].intersects(this.board.knight)?this.board[t].size()<=2&&this.board[M(t)].diff(this.board.king).diff(this.board.queen).isEmpty():this.board[t].intersects(this.board.bishop)?(!this.board.bishop.intersects(u.darkSquares())||!this.board.bishop.intersects(u.lightSquares()))&&this.board.pawn.isEmpty()&&this.board.knight.isEmpty():!0}toSetup(){var t,n;return{board:this.board.clone(),pockets:(t=this.pockets)===null||t===void 0?void 0:t.clone(),turn:this.turn,castlingRights:this.castles.castlingRights,epSquare:zi(this),remainingChecks:(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),halfmoves:Math.min(this.halfmoves,150),fullmoves:Math.min(Math.max(this.fullmoves,1),9999)}}isInsufficientMaterial(){return F.every(t=>this.hasInsufficientMaterial(t))}hasDests(t){t=t||this.ctx();for(let n of this.board[this.turn])if(this.dests(n,t).nonEmpty())return!0;return this.dropDests(t).nonEmpty()}isLegal(t,n){if(oe(t))return!this.pockets||this.pockets[this.turn][t.role]<=0||t.role==="pawn"&&u.backranks().has(t.to)?!1:this.dropDests(n).has(t.to);{if(t.promotion==="pawn"||t.promotion==="king"&&this.rules!=="antichess"||!!t.promotion!==(this.board.pawn.has(t.from)&&u.backranks().has(t.to)))return!1;let r=this.dests(t.from,n);return r.has(t.to)||r.has(Hn(this,t).to)}}isCheck(){let t=this.board.kingOf(this.turn);return g(t)&&this.kingAttackers(t,M(this.turn),this.board.occupied).nonEmpty()}isEnd(t){return(t?t.variantEnd:this.isVariantEnd())?!0:this.isInsufficientMaterial()||!this.hasDests(t)}isCheckmate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.nonEmpty()&&!this.hasDests(t)}isStalemate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.isEmpty()&&!this.hasDests(t)}outcome(t){let n=this.variantOutcome(t);return n||(t=t||this.ctx(),this.isCheckmate(t)?{winner:M(this.turn)}:this.isInsufficientMaterial()||this.isStalemate(t)?{winner:void 0}:void 0)}allDests(t){t=t||this.ctx();let n=new Map;if(t.variantEnd)return n;for(let r of this.board[this.turn])n.set(r,this.dests(r,t));return n}play(t){let n=this.turn,r=this.epSquare,i=Qt(this,t);if(this.epSquare=void 0,this.halfmoves+=1,n==="black"&&(this.fullmoves+=1),this.turn=M(n),oe(t))this.board.set(t.to,{role:t.role,color:n}),this.pockets&&this.pockets[n][t.role]--,t.role==="pawn"&&(this.halfmoves=0);else{let o=this.board.take(t.from);if(!o)return;let s;if(o.role==="pawn"){this.halfmoves=0,t.to===r&&(s=this.board.take(t.to+(n==="white"?-8:8)));let a=t.from-t.to;Math.abs(a)===16&&8<=t.from&&t.from<=55&&(this.epSquare=t.from+t.to>>1),t.promotion&&(o.role=t.promotion,o.promoted=!!this.pockets)}else if(o.role==="rook")this.castles.discardRook(t.from);else if(o.role==="king"){if(i){let a=this.castles.rook[n][i];if(g(a)){let l=this.board.take(a);this.board.set(Ke(n,i),o),l&&this.board.set(it(n,i),l)}}this.castles.discardColor(n)}if(!i){let a=this.board.set(t.to,o)||s;a&&this.playCaptureAt(t.to,a)}}this.remainingChecks&&this.isCheck()&&(this.remainingChecks[n]=Math.max(this.remainingChecks[n]-1,0))}},ze=class extends ee{constructor(){super("chess")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}},$i=(e,t)=>{if(!g(t))return;let n=e.turn==="white"?5:2,r=e.turn==="white"?8:-8;if(J(t)!==n||e.board.occupied.has(t+r))return;let i=t-r;if(!(!e.board.pawn.has(i)||!e.board[M(e.turn)].has(i)))return t},zi=e=>{if(!g(e.epSquare))return;let t=e.ctx(),r=e.board.pieces(e.turn,"pawn").intersect(we(M(e.turn),e.epSquare));for(let i of r)if(e.dests(i,t).has(e.epSquare))return e.epSquare},Vi=(e,t,n)=>{if(!g(e.epSquare)||!we(e.turn,t).has(e.epSquare))return!1;if(!g(n.king))return!0;let r=e.turn==="white"?8:-8,i=e.epSquare-r;return e.kingAttackers(n.king,M(e.turn),e.board.occupied.toggle(t).toggle(i).with(e.epSquare)).without(i).isEmpty()},ct=(e,t,n)=>{if(!g(n.king)||n.checkers.nonEmpty())return u.empty();let r=e.castles.rook[e.turn][t];if(!g(r))return u.empty();if(e.castles.path[e.turn][t].intersects(e.board.occupied))return u.empty();let i=Ke(e.turn,t),o=xe(n.king,i),s=e.board.occupied.without(n.king);for(let c of o)if(e.kingAttackers(c,M(e.turn),s).nonEmpty())return u.empty();let a=it(e.turn,t),l=e.board.occupied.toggle(n.king).toggle(r).toggle(a);return e.kingAttackers(i,M(e.turn),l).nonEmpty()?u.empty():u.fromSquare(r)},lt=(e,t,n)=>{if(n.variantEnd)return u.empty();let r=e.board.get(t);if(!r||r.color!==e.turn)return u.empty();let i=st(r,t,e.board.occupied);if(r.role==="pawn"){let o=e.board[M(e.turn)];g(e.epSquare)&&(o=o.with(e.epSquare)),i=i.intersect(o);let s=e.turn==="white"?8:-8,a=t+s;if(0<=a&&a<64&&!e.board.occupied.has(a)){i=i.with(a);let l=e.turn==="white"?t<16:t>=48,c=a+s;l&&!e.board.occupied.has(c)&&(i=i.with(c))}return i}else i=i.diff(e.board[e.turn]);return t===n.king?i.union(ct(e,"a",n)).union(ct(e,"h",n)):i};var Qt=(e,t)=>{if(oe(t))return;let n=t.to-t.from;if(!(Math.abs(n)!==2&&!e.board[e.turn].has(t.to))&&e.board.king.has(t.from))return n>0?"h":"a"},Hn=(e,t)=>{let n=Qt(e,t);if(!n)return t;let r=e.castles.rook[e.turn][n];return{from:t.from,to:g(r)?r:t.to}};var Gn=e=>oe(e)?String.fromCharCode(35+e.to,139+["queen","rook","bishop","knight","pawn"].indexOf(e.role)):String.fromCharCode(35+e.from,e.promotion?99+8*["queen","rook","bishop","knight","king"].indexOf(e.promotion)+L(e.to):35+e.to);var Hi="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",Gi=Hi+" w KQkq -",Na=Gi+" 0 1",Wi="8/8/8/8/8/8/8/8",Ui=Wi+" w - -",Ta=Ui+" 0 1",$;(function(e){e.Fen="ERR_FEN",e.Board="ERR_BOARD",e.Pockets="ERR_POCKETS",e.Turn="ERR_TURN",e.Castling="ERR_CASTLING",e.EpSquare="ERR_EP_SQUARE",e.RemainingChecks="ERR_REMAINING_CHECKS",e.Halfmoves="ERR_HALFMOVES",e.Fullmoves="ERR_FULLMOVES"})($||($={}));var z=class extends Error{},ji=(e,t,n)=>{let r=e.indexOf(t);for(;n-- >0&&r!==-1;)r=e.indexOf(t,r+t.length);return r},De=e=>/^\d{1,4}$/.test(e)?parseInt(e,10):void 0,Yn=e=>{let t=Ae(e);return t&&{role:t,color:e.toLowerCase()===e?"black":"white"}},Xt=e=>{let t=de.empty(),n=7,r=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="/"&&r===8)r=0,n--;else{let s=parseInt(o,10);if(s>0)r+=s;else{if(r>=8||n<0)return m.err(new z($.Board));let a=r+n*8,l=Yn(o);if(!l)return m.err(new z($.Board));e[i+1]==="~"&&(l.promoted=!0,i++),t.set(a,l),r++}}}return n!==0||r!==8?m.err(new z($.Board)):m.ok(t)},Wn=e=>{if(e.length>64)return m.err(new z($.Pockets));let t=_e.empty();for(let n of e){let r=Yn(n);if(!r)return m.err(new z($.Pockets));t[r.color][r.role]++}return m.ok(t)},Yi=(e,t)=>{let n=u.empty();if(t==="-")return m.ok(n);for(let r of t){let i=r.toLowerCase(),o=r===i?"black":"white",s=o==="white"?0:7;if("a"<=i&&i<="h")n=n.with(rt(i.charCodeAt(0)-97,s));else if(i==="k"||i==="q"){let a=e[o].intersect(u.backrank(o)).intersect(e.rook.union(e.king)),l=i==="k"?a.last():a.first();n=n.with(g(l)&&e.rook.has(l)?l:rt(i==="k"?7:0,s))}else return m.err(new z($.Castling))}return F.some(r=>u.backrank(r).intersect(n).size()>2)?m.err(new z($.Castling)):m.ok(n)},Un=e=>{let t=e.split("+");if(t.length===3&&t[0]===""){let n=De(t[1]),r=De(t[2]);return!g(n)||n>3||!g(r)||r>3?m.err(new z($.RemainingChecks)):m.ok(new Se(3-n,3-r))}else if(t.length===2){let n=De(t[0]),r=De(t[1]);return!g(n)||n>3||!g(r)||r>3?m.err(new z($.RemainingChecks)):m.ok(new Se(n,r))}else return m.err(new z($.RemainingChecks))},Zn=e=>{let t=e.split(/[\s_]+/),n=t.shift(),r,i=m.ok(void 0);if(n.endsWith("]")){let a=n.indexOf("[");if(a===-1)return m.err(new z($.Fen));r=Xt(n.slice(0,a)),i=Wn(n.slice(a+1,-1))}else{let a=ji(n,"/",7);a===-1?r=Xt(n):(r=Xt(n.slice(0,a)),i=Wn(n.slice(a+1)))}let o,s=t.shift();if(!g(s)||s==="w")o="white";else if(s==="b")o="black";else return m.err(new z($.Turn));return r.chain(a=>{let l=t.shift(),c=g(l)?Yi(a,l):m.ok(u.empty()),p=t.shift(),f;if(g(p)&&p!=="-"&&(f=he(p),!g(f)))return m.err(new z($.EpSquare));let C=t.shift(),k;g(C)&&C.includes("+")&&(k=Un(C),C=t.shift());let h=g(C)?De(C):0;if(!g(h))return m.err(new z($.Halfmoves));let d=t.shift(),w=g(d)?De(d):1;if(!g(w))return m.err(new z($.Fullmoves));let b=t.shift(),y=m.ok(void 0);if(g(b)){if(g(k))return m.err(new z($.RemainingChecks));y=Un(b)}else g(k)&&(y=k);return t.length>0?m.err(new z($.Fen)):i.chain(E=>c.chain(x=>y.map(P=>({board:a,pockets:E,turn:o,castlingRights:x,remainingChecks:P,epSquare:f,halfmoves:h,fullmoves:Math.max(1,w)}))))})};var Zi=e=>{let t=se(e.role);return e.color==="white"&&(t=t.toUpperCase()),e.promoted&&(t+="~"),t},Qi=e=>{let t="",n=0;for(let r=7;r>=0;r--)for(let i=0;i<8;i++){let o=i+r*8,s=e.get(o);s?(n>0&&(t+=n,n=0),t+=Zi(s)):n++,i===7&&(n>0&&(t+=n,n=0),r!==0&&(t+="/"))}return t},jn=e=>U.map(t=>se(t).repeat(e[t])).join(""),Xi=e=>jn(e.white).toUpperCase()+jn(e.black),Ji=(e,t)=>{let n="";for(let r of F){let i=u.backrank(r),o=e.kingOf(r);g(o)&&!i.has(o)&&(o=void 0);let s=e.pieces(r,"rook").intersect(i);for(let a of t.intersect(i).reversed())if(a===s.first()&&g(o)&&a<o)n+=r==="white"?"Q":"q";else if(a===s.last()&&g(o)&&o<a)n+=r==="white"?"K":"k";else{let l=Ee[L(a)];n+=r==="white"?l.toUpperCase():l}}return n||"-"},eo=e=>`${e.white}+${e.black}`,ut=(e,t)=>[Qi(e.board)+(e.pockets?`[${Xi(e.pockets)}]`:""),e.turn[0],Ji(e.board,e.castlingRights),g(e.epSquare)?j(e.epSquare):"-",...e.remainingChecks?[eo(e.remainingChecks)]:[],...t?.epd?[]:[Math.max(0,Math.min(e.halfmoves,9999)),Math.max(1,Math.min(e.fullmoves,9999))]].join(" ");var no=(e,t)=>{let n="";if(oe(t))t.role!=="pawn"&&(n=se(t.role).toUpperCase()),n+="@"+j(t.to);else{let r=e.board.getRole(t.from);if(!r)return"--";if(r==="king"&&(e.board[e.turn].has(t.to)||Math.abs(t.to-t.from)===2))n=t.to>t.from?"O-O":"O-O-O";else{let i=e.board.occupied.has(t.to)||r==="pawn"&&L(t.from)!==L(t.to);if(r!=="pawn"){n=se(r).toUpperCase();let o;if(r==="king"?o=ae(t.to).intersect(e.board.king):r==="queen"?o=$e(t.to,e.board.occupied).intersect(e.board.queen):r==="rook"?o=ye(t.to,e.board.occupied).intersect(e.board.rook):r==="bishop"?o=ve(t.to,e.board.occupied).intersect(e.board.bishop):o=qe(t.to).intersect(e.board.knight),o=o.intersect(e.board[e.turn]).without(t.from),o.nonEmpty()){let s=e.ctx();for(let a of o)e.dests(a,s).has(t.to)||(o=o.without(a));if(o.nonEmpty()){let a=!1,l=o.intersects(u.fromRank(J(t.from)));o.intersects(u.fromFile(L(t.from)))?a=!0:l=!0,l&&(n+=Ee[L(t.from)]),a&&(n+=nt[J(t.from)])}}}else i&&(n=Ee[L(t.from)]);i&&(n+="x"),n+=j(t.to),t.promotion&&(n+="="+se(t.promotion).toUpperCase())}}return n},Qn=(e,t)=>{var n;let r=no(e,t);return e.play(t),!((n=e.outcome())===null||n===void 0)&&n.winner?r+"#":e.isCheck()?r+"+":r};var Xn=(e,t)=>{let n=e.ctx(),r=t.match(/^([NBRQK])?([a-h])?([1-8])?[-x]?([a-h][1-8])(?:=?([nbrqkNBRQK]))?[+#]?$/);if(!r){let p;if(t==="O-O"||t==="O-O+"||t==="O-O#"?p="h":(t==="O-O-O"||t==="O-O-O+"||t==="O-O-O#")&&(p="a"),p){let k=e.castles.rook[e.turn][p];return!g(n.king)||!g(k)||!e.dests(n.king,n).has(k)?void 0:{from:n.king,to:k}}let f=t.match(/^([pnbrqkPNBRQK])?@([a-h][1-8])[+#]?$/);if(!f)return;let C={role:f[1]?Ae(f[1]):"pawn",to:he(f[2])};return e.isLegal(C,n)?C:void 0}let i=r[1]?Ae(r[1]):"pawn",o=he(r[4]),s=r[5]?Ae(r[5]):void 0;if(!!s!==(i==="pawn"&&u.backranks().has(o))||s==="king"&&e.rules!=="antichess")return;let a=e.board.pieces(e.turn,i);i==="pawn"&&!r[2]?a=a.intersect(u.fromFile(L(o))):r[2]&&(a=a.intersect(u.fromFile(r[2].charCodeAt(0)-97))),r[3]&&(a=a.intersect(u.fromRank(r[3].charCodeAt(0)-49)));let l=i==="pawn"?u.fromFile(L(o)):u.empty();a=a.intersect(l.union(st({color:M(e.turn),role:i},o,e.board.occupied)));let c;for(let p of a)if(e.dests(p,n).has(o)){if(g(c))return;c=p}if(g(c))return{from:c,to:o,promotion:s}};var ht=class extends ee{constructor(){super("crazyhouse")}reset(){super.reset(),this.pockets=_e.empty()}setupUnchecked(t){super.setupUnchecked(t),this.board.promoted=t.board.promoted.intersect(t.board.occupied).diff(t.board.king).diff(t.board.pawn),this.pockets=t.pockets?t.pockets.clone():_e.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}validate(){return super.validate().chain(t=>{var n,r;return!((n=this.pockets)===null||n===void 0)&&n.count("king")?m.err(new D(q.Kings)):(((r=this.pockets)===null||r===void 0?void 0:r.size())||0)+this.board.occupied.size()>64?m.err(new D(q.Variant)):m.ok(void 0)})}hasInsufficientMaterial(t){return this.pockets?this.board.occupied.size()+this.pockets.size()<=3&&this.board.pawn.isEmpty()&&this.board.promoted.isEmpty()&&this.board.rooksAndQueens().isEmpty()&&this.pockets.count("pawn")<=0&&this.pockets.count("rook")<=0&&this.pockets.count("queen")<=0:super.hasInsufficientMaterial(t)}dropDests(t){var n,r;let i=this.board.occupied.complement().intersect(!((n=this.pockets)===null||n===void 0)&&n[this.turn].hasNonPawns()?u.full():!((r=this.pockets)===null||r===void 0)&&r[this.turn].hasPawns()?u.backranks().complement():u.empty());if(t=t||this.ctx(),g(t.king)&&t.checkers.nonEmpty()){let o=t.checkers.singleSquare();return g(o)?i.intersect(xe(o,t.king)):u.empty()}else return i}},dt=class extends ee{constructor(){super("atomic")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return m.err(new D(q.Empty));if(this.board.king.size()>2)return m.err(new D(q.Kings));let t=this.board.kingOf(M(this.turn));return g(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?m.err(new D(q.OppositeCheck)):u.backranks().intersects(this.board.pawn)?m.err(new D(q.PawnsOnBackrank)):m.ok(void 0):m.err(new D(q.Kings))}kingAttackers(t,n,r){let i=this.board.pieces(n,"king");return i.isEmpty()||ae(t).intersects(i)?u.empty():super.kingAttackers(t,n,r)}playCaptureAt(t,n){super.playCaptureAt(t,n),this.board.take(t);for(let r of ae(t).intersect(this.board.occupied).diff(this.board.pawn)){let i=this.board.take(r);i?.role==="rook"&&this.castles.discardRook(r),i?.role==="king"&&this.castles.discardColor(i.color)}}hasInsufficientMaterial(t){if(this.board.pieces(M(t),"king").isEmpty())return!1;if(this.board[t].diff(this.board.king).isEmpty())return!0;if(this.board[M(t)].diff(this.board.king).nonEmpty()){if(this.board.occupied.equals(this.board.bishop.union(this.board.king))){if(!this.board.bishop.intersect(this.board.white).intersects(u.darkSquares()))return!this.board.bishop.intersect(this.board.black).intersects(u.lightSquares());if(!this.board.bishop.intersect(this.board.white).intersects(u.lightSquares()))return!this.board.bishop.intersect(this.board.black).intersects(u.darkSquares())}return!1}return this.board.queen.nonEmpty()||this.board.pawn.nonEmpty()?!1:this.board.knight.union(this.board.bishop).union(this.board.rook).size()===1?!0:this.board.occupied.equals(this.board.knight.union(this.board.king))?this.board.knight.size()<=2:!1}dests(t,n){n=n||this.ctx();let r=u.empty();for(let i of lt(this,t,n)){let o=this.clone();o.play({from:t,to:i});let s=o.board.kingOf(this.turn);g(s)&&(!g(o.board.kingOf(o.turn))||o.kingAttackers(s,o.turn,o.board.occupied).isEmpty())&&(r=r.with(i))}return r}isVariantEnd(){return!!this.variantOutcome()}variantOutcome(t){for(let n of F)if(this.board.pieces(n,"king").isEmpty())return{winner:M(n)}}},ft=class extends ee{constructor(){super("antichess")}reset(){super.reset(),this.castles=ce.empty()}setupUnchecked(t){super.setupUnchecked(t),this.castles=ce.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}validate(){return this.board.occupied.isEmpty()?m.err(new D(q.Empty)):u.backranks().intersects(this.board.pawn)?m.err(new D(q.PawnsOnBackrank)):m.ok(void 0)}kingAttackers(t,n,r){return u.empty()}ctx(){let t=super.ctx();if(g(this.epSquare)&&we(M(this.turn),this.epSquare).intersects(this.board.pieces(this.turn,"pawn")))return t.mustCapture=!0,t;let n=this.board[M(this.turn)];for(let r of this.board[this.turn])if(lt(this,r,t).intersects(n))return t.mustCapture=!0,t;return t}dests(t,n){n=n||this.ctx();let r=lt(this,t,n),i=this.board[M(this.turn)];return r.intersect(n.mustCapture?g(this.epSquare)&&this.board.getRole(t)==="pawn"?i.with(this.epSquare):i:u.full())}hasInsufficientMaterial(t){if(this.board[t].isEmpty())return!1;if(this.board[M(t)].isEmpty())return!0;if(this.board.occupied.equals(this.board.bishop)){let n=this.board[t].intersects(u.lightSquares()),r=this.board[t].intersects(u.darkSquares()),i=this.board[M(t)].isDisjoint(u.lightSquares()),o=this.board[M(t)].isDisjoint(u.darkSquares());return n&&i||r&&o}return this.board.occupied.equals(this.board.knight)&&this.board.occupied.size()===2?this.board.white.intersects(u.lightSquares())!==this.board.black.intersects(u.darkSquares())!=(this.turn===t):!1}isVariantEnd(){return this.board[this.turn].isEmpty()}variantOutcome(t){if(t=t||this.ctx(),t.variantEnd||this.isStalemate(t))return{winner:this.turn}}},pt=class extends ee{constructor(){super("kingofthehill")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}hasInsufficientMaterial(t){return!1}isVariantEnd(){return this.board.king.intersects(u.center())}variantOutcome(t){for(let n of F)if(this.board.pieces(n,"king").intersects(u.center()))return{winner:n}}},mt=class extends ee{constructor(){super("3check")}reset(){super.reset(),this.remainingChecks=Se.default()}setupUnchecked(t){var n;super.setupUnchecked(t),this.remainingChecks=((n=t.remainingChecks)===null||n===void 0?void 0:n.clone())||Se.default()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}hasInsufficientMaterial(t){return this.board.pieces(t,"king").equals(this.board[t])}isVariantEnd(){return!!this.remainingChecks&&(this.remainingChecks.white<=0||this.remainingChecks.black<=0)}variantOutcome(t){if(this.remainingChecks){for(let n of F)if(this.remainingChecks[n]<=0)return{winner:n}}}},io=()=>{let e=de.empty();return e.occupied=new u(65535,0),e.promoted=u.empty(),e.white=new u(61680,0),e.black=new u(3855,0),e.pawn=u.empty(),e.knight=new u(6168,0),e.bishop=new u(9252,0),e.rook=new u(16962,0),e.queen=new u(129,0),e.king=new u(33024,0),e},gt=class extends ee{constructor(){super("racingkings")}reset(){this.board=io(),this.pockets=void 0,this.turn="white",this.castles=ce.empty(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){super.setupUnchecked(t),this.castles=ce.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}validate(){return this.isCheck()||this.board.pawn.nonEmpty()?m.err(new D(q.Variant)):super.validate()}dests(t,n){if(n=n||this.ctx(),t===n.king)return super.dests(t,n);let r=u.empty();for(let i of super.dests(t,n)){let o={from:t,to:i},s=this.clone();s.play(o),s.isCheck()||(r=r.with(i))}return r}hasInsufficientMaterial(t){return!1}isVariantEnd(){let t=u.fromRank(7),n=this.board.king.intersect(t);if(n.isEmpty())return!1;if(this.turn==="white"||n.intersects(this.board.black))return!0;let r=this.board.kingOf("black");if(g(r)){let i=this.board.occupied.without(r);for(let o of ae(r).intersect(t).diff(this.board.black))if(this.kingAttackers(o,"white",i).isEmpty())return!1}return!0}variantOutcome(t){if(t?!t.variantEnd:!this.isVariantEnd())return;let n=u.fromRank(7),r=this.board.pieces("black","king").intersects(n),i=this.board.pieces("white","king").intersects(n);return r&&!i?{winner:"black"}:i&&!r?{winner:"white"}:{winner:void 0}}},oo=()=>{let e=de.empty();return e.occupied=new u(4294967295,4294901862),e.promoted=u.empty(),e.white=new u(4294967295,102),e.black=new u(0,4294901760),e.pawn=new u(4294967295,16711782),e.knight=new u(0,1107296256),e.bishop=new u(0,603979776),e.rook=new u(0,2164260864),e.queen=new u(0,134217728),e.king=new u(0,268435456),e},kt=class extends ee{constructor(){super("horde")}reset(){this.board=oo(),this.pockets=void 0,this.turn="white",this.castles=ce.default(),this.castles.discardColor("white"),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return m.err(new D(q.Empty));if(this.board.king.size()!==1)return m.err(new D(q.Kings));let t=this.board.kingOf(M(this.turn));if(g(t)&&this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty())return m.err(new D(q.OppositeCheck));for(let n of F){let r=this.board.pieces(n,"king").isEmpty()?u.backrank(M(n)):u.backranks();if(this.board.pieces(n,"pawn").intersects(r))return m.err(new D(q.PawnsOnBackrank))}return m.ok(void 0)}hasInsufficientMaterial(t){if(this.board.pieces(t,"king").nonEmpty())return!1;let n=k=>k==="light"?"dark":"light",r=k=>k==="light"?u.lightSquares():u.darkSquares(),i=k=>{let h=this.board.pieces(k,"bishop");return h.intersects(u.darkSquares())&&h.intersects(u.lightSquares())},o=fe.fromBoard(this.board,t),s=k=>r(k).intersect(this.board.pieces(t,"bishop")).size(),a=s("light")>=1?"light":"dark",l=o.pawn+o.knight+o.rook+o.queen+Math.min(s("dark"),2)+Math.min(s("light"),2),c=fe.fromBoard(this.board,M(t)),p=k=>r(k).intersect(this.board.pieces(M(t),"bishop")).size(),f=c.size(),C=k=>f-k;if(l===0)return!0;if(l>=4||(o.pawn>=1||o.queen>=1)&&l>=2||o.rook>=1&&l>=2&&!(l===2&&o.rook===1&&o.bishop===1&&C(p(a))===1))return!1;if(l===1){if(f===1)return!0;if(o.queen===1)return!(c.pawn>=1||c.rook>=1||p("light")>=2||p("dark")>=2);if(o.pawn===1){let k=this.board.pieces(t,"pawn").last(),h=this.clone();h.board.set(k,{color:t,role:"queen"});let d=this.clone();return d.board.set(k,{color:t,role:"knight"}),h.hasInsufficientMaterial(t)&&d.hasInsufficientMaterial(t)}else{if(o.rook===1)return!(c.pawn>=2||c.rook>=1&&c.pawn>=1||c.rook>=1&&c.knight>=1||c.pawn>=1&&c.knight>=1);if(o.bishop===1)return!(p(n(a))>=2||p(n(a))>=1&&c.pawn>=1||c.pawn>=2);if(o.knight===1)return!(f>=4&&(c.knight>=2||c.pawn>=2||c.rook>=1&&c.knight>=1||c.rook>=1&&c.bishop>=1||c.knight>=1&&c.bishop>=1||c.rook>=1&&c.pawn>=1||c.knight>=1&&c.pawn>=1||c.bishop>=1&&c.pawn>=1||i(M(t))&&c.pawn>=1)&&(p("dark")<2||C(p("dark"))>=3)&&(p("light")<2||C(p("light"))>=3))}}else{if(l===2)return f===1?!0:o.knight===2?c.pawn+c.bishop+c.knight<1:i(t)?!(c.pawn>=1||c.bishop>=1||c.knight>=1&&c.rook+c.queen>=1):o.bishop>=1&&o.knight>=1?!(c.pawn>=1||p(n(a))>=1||C(p(a))>=3):!(c.pawn>=1&&p(n(a))>=1||c.pawn>=1&&c.knight>=1||p(n(a))>=1&&c.knight>=1||p(n(a))>=2||c.knight>=2||c.pawn>=2);if(l===3)return o.knight===2&&o.bishop===1||o.knight===3||i(t)?!1:f===1}return!0}isVariantEnd(){return this.board.white.isEmpty()||this.board.black.isEmpty()}variantOutcome(t){if(this.board.white.isEmpty())return{winner:"black"};if(this.board.black.isEmpty())return{winner:"white"}}},Jn=e=>{switch(e){case"chess":return ze.default();case"antichess":return ft.default();case"atomic":return dt.default();case"horde":return kt.default();case"racingkings":return gt.default();case"kingofthehill":return pt.default();case"3check":return mt.default();case"crazyhouse":return ht.default()}},er=(e,t)=>{switch(e){case"chess":return ze.fromSetup(t);case"antichess":return ft.fromSetup(t);case"atomic":return dt.fromSetup(t);case"horde":return kt.fromSetup(t);case"racingkings":return gt.fromSetup(t);case"kingofthehill":return pt.fromSetup(t);case"3check":return mt.fromSetup(t);case"crazyhouse":return ht.fromSetup(t)}};var ao=(e=rn)=>({headers:e(),moves:new Ve}),Ve=class{constructor(){this.children=[]}*mainlineNodes(){let t=this;for(;t.children.length;){let n=t.children[0];yield n,t=n}}*mainline(){for(let t of this.mainlineNodes())yield t.data}end(){let t=this;for(;t.children.length;)t=t.children[0];return t}},bt=class extends Ve{constructor(t){super(),this.data=t}};var nr=(e,t,n)=>{let r=new Ve,i=[{before:e,after:r,ctx:t}],o;for(;o=i.pop();)for(let s=0;s<o.before.children.length;s++){let a=s<o.before.children.length-1?o.ctx.clone():o.ctx,l=o.before.children[s],c=n(a,l.data,s);if(g(c)){let p=new bt(c);o.after.children.push(p),i.push({before:l,after:p,ctx:a})}}return r};var co=e=>e?e.winner==="white"?"1-0":e.winner==="black"?"0-1":"1/2-1/2":"*",lo=e=>e==="1-0"||e==="1\u20130"||e==="1\u20140"?{winner:"white"}:e==="0-1"||e==="0\u20131"||e==="0\u20141"?{winner:"black"}:e==="1/2-1/2"||e==="1/2\u20131/2"||e==="1/2\u20141/2"?{winner:void 0}:void 0;var rn=()=>new Map([["Event","?"],["Site","?"],["Date","????.??.??"],["Round","?"],["White","?"],["Black","?"],["Result","*"]]);var tr="\uFEFF",Jt=e=>/^\s*$/.test(e),en=e=>e.startsWith("%"),tn=class extends Error{},nn=class{constructor(t,n=rn,r=1e6){this.emitGame=t,this.initHeaders=n,this.maxBudget=r,this.lineBuf=[],this.resetGame(),this.state=0}resetGame(){this.budget=this.maxBudget,this.found=!1,this.state=1,this.game=ao(this.initHeaders),this.stack=[{parent:this.game.moves,root:!0}],this.commentBuf=[]}consumeBudget(t){if(this.budget-=t,this.budget<0)throw new tn("ERR_PGN_BUDGET")}parse(t,n){if(!(this.budget<0))try{let r=0;for(;;){let i=t.indexOf(`
|
|
2
|
-
`,
|
|
3
|
-
`);this.commentBuf=[],r.node?((t=r.node.data).comments||(t.comments=[]),r.node.data.comments.push(i)):r.root?((n=this.game).comments||(n.comments=[]),this.game.comments.push(i)):(r.startingComments||(r.startingComments=[]),r.startingComments.push(i))}emit(t){if(this.state===4&&this.handleComment(),t)return this.emitGame(this.game,t);this.found&&this.emitGame(this.game,void 0),this.resetGame()}},on=(e,t=rn)=>{let n=[];return new nn(r=>n.push(r),t,NaN).parse(e),n},uo=e=>{switch((e||"chess").toLowerCase()){case"chess":case"chess960":case"chess 960":case"standard":case"from position":case"classical":case"normal":case"fischerandom":case"fischerrandom":case"fischer random":case"wild/0":case"wild/1":case"wild/2":case"wild/3":case"wild/4":case"wild/5":case"wild/6":case"wild/7":case"wild/8":case"wild/8a":return"chess";case"crazyhouse":case"crazy house":case"house":case"zh":return"crazyhouse";case"king of the hill":case"koth":case"kingofthehill":return"kingofthehill";case"three-check":case"three check":case"threecheck":case"three check chess":case"3-check":case"3 check":case"3check":return"3check";case"antichess":case"anti chess":case"anti":return"antichess";case"atomic":case"atom":case"atomic chess":return"atomic";case"horde":case"horde chess":return"horde";case"racing kings":case"racingkings":case"racing":case"race":return"racingkings";default:return}};var rr=e=>{let t=uo(e.get("Variant"));if(!t)return m.err(new D(q.Variant));let n=e.get("FEN");return n?Zn(n).chain(r=>er(t,r)):m.ok(Jn(t))};function ho(e){switch(e){case"G":return"green";case"R":return"red";case"Y":return"yellow";case"B":return"blue";default:return}}var fo=e=>{let t=ho(e.slice(0,1)),n=he(e.slice(1,3)),r=he(e.slice(3,5));if(!(!t||!g(n))){if(e.length===3)return{color:t,from:n,to:n};if(e.length===5&&g(r))return{color:t,from:n,to:r}}};var ir=e=>{let t,n,r,i=[];return{text:e.replace(/\s?\[%(emt|clk)\s(\d{1,5}):(\d{1,2}):(\d{1,2}(?:\.\d{0,3})?)\]\s?/g,(s,a,l,c,p)=>{let f=parseInt(l,10)*3600+parseInt(c,10)*60+parseFloat(p);return a==="emt"?t=f:a==="clk"&&(n=f)," "}).replace(/\s?\[%(?:csl|cal)\s([RGYB][a-h][1-8](?:[a-h][1-8])?(?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)*)\]\s?/g,(s,a)=>{for(let l of a.split(","))i.push(fo(l));return" "}).replace(/\s?\[%eval\s(?:#([+-]?\d{1,5})|([+-]?(?:\d{1,5}|\d{0,5}\.\d{1,2})))(?:,(\d{1,5}))?\]\s?/g,(s,a,l,c)=>{let p=c&&parseInt(c,10);return r=a?{mate:parseInt(a,10),depth:p}:{pawns:parseFloat(l),depth:p}," "}).trim(),shapes:i,emt:t,clock:n,evaluation:r}};var mo=e=>ko[e];function sn(e){return(t,...n)=>{let r=e&&e(t)||mo(t);return go(r??t,n)}}var go=(e,t)=>{let n=e;return t.forEach((r,i)=>{n=n.replace(`%${i+1}$s`,r),n=n.replace("%s",r)}),n},ko={flipTheBoard:"Flip the board",analysisBoard:"Analysis board",practiceWithComputer:"Practice with computer",getPgn:"Get PGN",download:"Download",viewOnLichess:"View on Lichess",viewOnSite:"View on site",menu:"Menu","aria.first":"Go to first move","aria.prev":"Go to previous move","aria.next":"Go to next move","aria.last":"Go to last move","aria.gameMoves":"Game moves","aria.gameResult":"Game result","aria.variation":"Variation","aria.navigationControls":"Game navigation controls","aria.viewProfileOnLichess":"View %s's profile on Lichess","aria.chessGameBetween":"Chess game between %1$s, whites, and %2$s, blacks. %3$s","aria.gameInProgress":"Game in progress","aria.whitesWin":"Whites win","aria.blacksWin":"Blacks win","aria.draw":"Draw","aria.unknownPlayer":"Unknown player","aria.rated":"rated %s","aria.move":"Move %1$s, %2$s, %3$s","aria.white":"white","aria.black":"black","aria.remaining":"%s remaining","aria.linkOpensInNewTab":"%s, link, opens in new tab","aria.accessibleChessboard":"Accessible chessboard","aria.piece.king":"king","aria.piece.queen":"queen","aria.piece.rook":"rook","aria.piece.bishop":"bishop","aria.piece.knight":"knight","aria.piece.pawn":"pawn","aria.empty":"empty","san.takes":"takes","san.check":"check","san.checkmate":"checkmate","san.promotesTo":"promotes to","san.droppedOn":"dropped on","san.longCastling":"long castling","san.shortCastling":"short castling"};var or=["white","black"];var le=["a","b","c","d","e","f","g","h"],Ce=["1","2","3","4","5","6","7","8"];var wt=[...Ce].reverse(),vt=Array.prototype.concat(...le.map(e=>Ce.map(t=>e+t))),H=e=>vt[8*e[0]+e[1]],T=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],ar=e=>{if(e)return e[1]==="@"?[e.slice(2,4)]:[e.slice(0,2),e.slice(2,4)]},yt=vt.map(T);function cr(e){let t,n=()=>(t===void 0&&(t=e()),t);return n.clear=()=>{t=void 0},n}var lr=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;let t=performance.now()-e;return e=void 0,t}}},xt=e=>e==="white"?"black":"white",Pe=(e,t)=>{let n=e[0]-t[0],r=e[1]-t[1];return n*n+r*r},Fe=(e,t)=>e.role===t.role&&e.color===t.color,Me=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],Z=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},an=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},He=(e,t)=>{e.style.visibility=t?"visible":"hidden"},ue=e=>{var t;if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(!((t=e.targetTouches)===null||t===void 0)&&t[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},St=e=>e.button===2,Q=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};function Ct(e,t,n){let r=T(e);return t||(r[0]=7-r[0],r[1]=7-r[1]),[n.left+n.width*r[0]/8+n.width/16,n.top+n.height*(7-r[1])/8+n.height/16]}var te=class e{constructor(t){this.path=t;this.size=()=>this.path.length/2;this.head=()=>this.path.slice(0,2);this.tail=()=>new e(this.path.slice(2));this.init=()=>new e(this.path.slice(0,-2));this.last=()=>this.path.slice(-2);this.empty=()=>this.path=="";this.contains=t=>this.path.startsWith(t.path);this.isChildOf=t=>this.init()===t;this.append=t=>new e(this.path+t);this.equals=t=>this.path==t.path}static{this.root=new e("")}};var Pt=class{constructor(t,n,r,i){this.initial=t;this.moves=n;this.players=r;this.metadata=i;this.nodeAt=t=>ur(this.moves,t);this.dataAt=t=>{let n=this.nodeAt(t);return n?wo(n)?n.data:this.initial:void 0};this.title=()=>this.players.white.name?[this.players.white.title,this.players.white.name,"vs",this.players.black.title,this.players.black.name].filter(t=>t&&!!t.trim()).join("_").replace(" ","-"):"lichess-pgn-viewer";this.pathAtMainlinePly=t=>t==0?te.root:this.mainline[Math.max(0,Math.min(this.mainline.length-1,t=="last"?9999:t-1))]?.path||te.root;this.hasPlayerName=()=>!!(this.players.white?.name||this.players.black?.name);this.mainline=Array.from(this.moves.mainline())}},bo=(e,t)=>e.children.find(n=>n.data.path.last()==t),ur=(e,t)=>{if(t.empty())return e;let n=bo(e,t.head());return n?ur(n,t.tail()):void 0},wo=e=>"data"in e,Mt=e=>"uci"in e;var cn=class e{constructor(t,n,r){this.pos=t;this.path=n;this.clocks=r;this.clone=()=>new e(this.pos.clone(),this.path,{...this.clocks})}},ln=e=>{let t=e.map(ir),n=r=>r.reduce((i,o)=>typeof o==null?i:o,void 0);return{texts:t.map(r=>r.text).filter(r=>!!r),shapes:t.flatMap(r=>r.shapes),clock:n(t.map(r=>r.clock)),emt:n(t.map(r=>r.emt))}},hr=(e,t=!1)=>{let n=on(e)[0]||on("*")[0],r=rr(n.headers).unwrap(),i=ut(r.toSetup()),o=ln(n.comments||[]),s=new Map(Array.from(n.headers,([f,C])=>[f.toLowerCase(),C])),a=So(s,t),l={fen:i,turn:r.turn,check:r.isCheck(),pos:r.clone(),comments:o.texts,shapes:o.shapes,clocks:{white:a.timeControl?.initial||o.clock,black:a.timeControl?.initial||o.clock}},c=vo(r,n.moves,a),p=xo(s,a);return new Pt(l,c,p,a)},vo=(e,t,n)=>nr(t,new cn(e,te.root,{}),(r,i,o)=>{let s=Xn(r.pos,i.san);if(!s)return;let a=Gn(s),l=r.path.append(a),c=Qn(r.pos,s);r.path=l;let p=r.pos.toSetup(),f=ln(i.comments||[]),C=ln(i.startingComments||[]),k=[...f.shapes,...C.shapes],h=(p.fullmoves-1)*2+(r.pos.turn==="white"?0:1),d=r.clocks=yo(r.clocks,r.pos.turn,f.clock);return h<2&&n.timeControl&&(d={white:n.timeControl.initial,black:n.timeControl.initial,...d}),{path:l,ply:h,move:s,san:c,uci:zt(s),fen:ut(r.pos.toSetup()),turn:r.pos.turn,check:r.pos.isCheck(),comments:f.texts,startingComments:C.texts,nags:i.nags||[],shapes:k,clocks:d,emt:f.emt}}),yo=(e,t,n)=>t=="white"?{...e,black:n}:{...e,white:n};function xo(e,t){let n=(i,o)=>{let s=e.get(`${i}${o}`);return s=="?"||s==""?void 0:s},r=i=>{let o=n(i,"");return{name:o,title:n(i,"title"),rating:parseInt(n(i,"elo")||"")||void 0,isLichessUser:t.isLichess&&!!o?.match(/^[a-z0-9][a-z0-9_-]{0,28}[a-z0-9]$/i)}};return{white:r("white"),black:r("black")}}function So(e,t){let n=e.get("chapterurl")||e.get("gameurl")||e.get("source")||e.get("site"),r=e.get("timecontrol")?.split("+").map(s=>parseInt(s)),i=r&&r[0]?{initial:r[0],increment:r[1]||0}:void 0,o=e.get("orientation");return{externalLink:n&&n.match(/^https?:\/\//)?n:void 0,isLichess:!!(t&&n?.startsWith(t)),timeControl:i,orientation:o==="white"||o==="black"?o:void 0,result:e.get("result")}}var We=class{constructor(t,n){this.opts=t;this.redraw=n;this.flipped=!1;this.pane="board";this.autoScrollRequested=!1;this.curNode=()=>this.game.nodeAt(this.path)||this.game.moves;this.curData=()=>this.game.dataAt(this.path)||this.game.initial;this.goTo=(t,n=!0)=>{let r=t=="first"?te.root:t=="prev"?this.path.init():t=="next"?this.game.nodeAt(this.path)?.children[0]?.data.path:this.game.pathAtMainlinePly("last");this.toPath(r||this.path,n)};this.canGoTo=t=>t=="prev"||t=="first"?!this.path.empty():!!this.curNode().children[0];this.toPath=(t,n=!0)=>{this.path=t,this.pane="board",this.autoScrollRequested=!0,this.redrawGround(),this.redraw(),n&&this.focus()};this.focus=()=>this.div?.focus();this.toggleMenu=()=>{this.pane=this.pane=="board"?"menu":"board",this.redraw(),this.pane=="board"&&setTimeout(()=>this.menuButton?.focus(),0)};this.togglePgn=()=>{this.pane=this.pane=="pgn"?"board":"pgn",this.redraw()};this.orientation=()=>{let t=this.opts.orientation||"white";return this.flipped?M(t):t};this.flip=()=>{this.flipped=!this.flipped,this.pane="board",this.redrawGround(),this.redraw()};this.cgState=()=>{let t=this.curData(),n=Mt(t)?ar(t.uci):this.opts.chessground?.lastMove;return{fen:t.fen,orientation:this.orientation(),check:t.check,lastMove:n,turnColor:t.turn}};this.analysisUrl=()=>this.game.metadata.isLichess&&this.game.metadata.externalLink||`https://lichess.org/analysis/${this.curData().fen.replace(" ","_")}?color=${this.orientation()}`;this.practiceUrl=()=>`${this.analysisUrl()}#practice`;this.setGround=t=>{this.ground=t,this.redrawGround()};this.redrawGround=()=>this.withGround(t=>{t.set(this.cgState()),t.setShapes(this.curData().shapes.map(n=>({orig:j(n.from),dest:j(n.to),brush:n.color})))});this.withGround=t=>this.ground&&t(this.ground);this.game=hr(t.pgn,t.lichess),t.orientation=t.orientation||this.game.metadata.orientation,this.translate=sn(t.translate),this.path=this.game.pathAtMainlinePly(t.initialPly)}};var Ne=(e,t)=>Math.abs(e-t),Co=e=>(t,n,r,i)=>Ne(t,r)<2&&(e==="white"?i===n+1||n<=1&&i===n+2&&t===r:i===n-1||n>=6&&i===n-2&&t===r),un=(e,t,n,r)=>{let i=Ne(e,n),o=Ne(t,r);return i===1&&o===2||i===2&&o===1},dr=(e,t,n,r)=>Ne(e,n)===Ne(t,r),fr=(e,t,n,r)=>e===n||t===r,hn=(e,t,n,r)=>dr(e,t,n,r)||fr(e,t,n,r),Po=(e,t,n)=>(r,i,o,s)=>Ne(r,o)<2&&Ne(i,s)<2||n&&i===s&&i===(e==="white"?0:7)&&(r===4&&(o===2&&t.includes(0)||o===6&&t.includes(7))||t.includes(o));function Mo(e,t){let n=t==="white"?"1":"8",r=[];for(let[i,o]of e)i[1]===n&&o.color===t&&o.role==="rook"&&r.push(T(i)[0]);return r}function dn(e,t,n){let r=e.get(t);if(!r)return[];let i=T(t),o=r.role,s=o==="pawn"?Co(r.color):o==="knight"?un:o==="bishop"?dr:o==="rook"?fr:o==="queen"?hn:Po(r.color,Mo(e,r.color),n);return yt.filter(a=>(i[0]!==a[0]||i[1]!==a[1])&&s(i[0],i[1],a[0],a[1])).map(H)}function W(e,...t){e&&setTimeout(()=>e(...t),1)}function pr(e){e.orientation=xt(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function mr(e,t){for(let[n,r]of t)r?e.pieces.set(n,r):e.pieces.delete(n)}function gr(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(let[n,r]of e.pieces)r.role==="king"&&r.color===t&&(e.check=n)}function Eo(e,t,n,r){re(e),e.premovable.current=[t,n],W(e.premovable.events.set,t,n,r)}function ne(e){e.premovable.current&&(e.premovable.current=void 0,W(e.premovable.events.unset))}function Ao(e,t,n){ne(e),e.predroppable.current={role:t,key:n},W(e.predroppable.events.set,t,n)}function re(e){let t=e.predroppable;t.current&&(t.current=void 0,W(t.events.unset))}function _o(e,t,n){if(!e.autoCastle)return!1;let r=e.pieces.get(t);if(!r||r.role!=="king")return!1;let i=T(t),o=T(n);if(i[1]!==0&&i[1]!==7||i[1]!==o[1])return!1;i[0]===4&&!e.pieces.has(n)&&(o[0]===6?n=H([7,o[1]]):o[0]===2&&(n=H([0,o[1]])));let s=e.pieces.get(n);return!s||s.color!==r.color||s.role!=="rook"?!1:(e.pieces.delete(t),e.pieces.delete(n),i[0]<o[0]?(e.pieces.set(H([6,o[1]]),r),e.pieces.set(H([5,o[1]]),s)):(e.pieces.set(H([2,o[1]]),r),e.pieces.set(H([3,o[1]]),s)),!0)}function fn(e,t,n){let r=e.pieces.get(t),i=e.pieces.get(n);if(t===n||!r)return!1;let o=i&&i.color!==r.color?i:void 0;return n===e.selected&&G(e),W(e.events.move,t,n,o),_o(e,t,n)||(e.pieces.set(n,r),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,W(e.events.change),o||!0}function Et(e,t,n,r){if(e.pieces.has(n))if(r)e.pieces.delete(n);else return!1;return W(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,W(e.events.change),e.movable.dests=void 0,e.turnColor=xt(e.turnColor),!0}function kr(e,t,n){let r=fn(e,t,n);return r&&(e.movable.dests=void 0,e.turnColor=xt(e.turnColor),e.animation.current=void 0),r}function pn(e,t,n){if(_t(e,t,n)){let r=kr(e,t,n);if(r){let i=e.hold.stop();G(e);let o={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:i};return r!==!0&&(o.captured=r),W(e.movable.events.after,t,n,o),!0}}else if(To(e,t,n))return Eo(e,t,n,{ctrlKey:e.stats.ctrlKey}),G(e),!0;return G(e),!1}function At(e,t,n,r){let i=e.pieces.get(t);i&&(No(e,t,n)||r)?(e.pieces.delete(t),Et(e,i,n,r),W(e.movable.events.afterNewPiece,i.role,n,{premove:!1,predrop:!1})):i&&Ro(e,t,n)?Ao(e,i.role,n):(ne(e),re(e)),e.pieces.delete(t),G(e)}function Ue(e,t,n){if(W(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){G(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&pn(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(br(e,t)||gn(e,t))&&(mn(e,t),e.hold.start())}function mn(e,t){e.selected=t,gn(e,t)?e.premovable.customDests||(e.premovable.dests=dn(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function G(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function br(e,t){let n=e.pieces.get(t);return!!n&&(e.movable.color==="both"||e.movable.color===n.color&&e.turnColor===n.color)}var _t=(e,t,n)=>{var r,i;return t!==n&&br(e,t)&&(e.movable.free||!!(!((i=(r=e.movable.dests)===null||r===void 0?void 0:r.get(t))===null||i===void 0)&&i.includes(n)))};function No(e,t,n){let r=e.pieces.get(t);return!!r&&(t===n||!e.pieces.has(n))&&(e.movable.color==="both"||e.movable.color===r.color&&e.turnColor===r.color)}function gn(e,t){let n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function To(e,t,n){var r,i;let o=(i=(r=e.premovable.customDests)===null||r===void 0?void 0:r.get(t))!==null&&i!==void 0?i:dn(e.pieces,t,e.premovable.castle);return t!==n&&gn(e,t)&&o.includes(n)}function Ro(e,t,n){let r=e.pieces.get(t),i=e.pieces.get(n);return!!r&&(!i||i.color!==e.movable.color)&&e.predroppable.enabled&&(r.role!=="pawn"||n[1]!=="1"&&n[1]!=="8")&&e.movable.color===r.color&&e.turnColor!==r.color}function wr(e,t){let n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color==="both"||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function vr(e){let t=e.premovable.current;if(!t)return!1;let n=t[0],r=t[1],i=!1;if(_t(e,n,r)){let o=kr(e,n,r);if(o){let s={premove:!0};o!==!0&&(s.captured=o),W(e.movable.events.after,n,r,s),i=!0}}return ne(e),i}function yr(e,t){let n=e.predroppable.current,r=!1;if(!n)return!1;if(t(n)){let i={role:n.role,color:e.movable.color};Et(e,i,n.key)&&(W(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),r=!0)}return re(e),r}function je(e){ne(e),re(e),G(e)}function kn(e){e.movable.color=e.movable.dests=e.animation.current=void 0,je(e)}function ie(e,t,n){let r=Math.floor(8*(e[0]-n.left)/n.width);t||(r=7-r);let i=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(i=7-i),r>=0&&r<8&&i>=0&&i<8?H([r,i]):void 0}function xr(e,t,n,r){let i=T(e),o=yt.filter(c=>hn(i[0],i[1],c[0],c[1])||un(i[0],i[1],c[0],c[1])),a=o.map(c=>Ct(H(c),n,r)).map(c=>Pe(t,c)),[,l]=a.reduce((c,p,f)=>c[0]<p?c:[p,f],[a[0],0]);return H(o[l])}var B=e=>e.orientation==="white";var wn="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",Oo={p:"pawn",r:"rook",n:"knight",b:"bishop",q:"queen",k:"king"},qo={pawn:"p",rook:"r",knight:"n",bishop:"b",queen:"q",king:"k"};function Le(e){e==="start"&&(e=wn);let t=new Map,n=7,r=0;for(let i of e)switch(i){case" ":case"[":return t;case"/":if(--n,n<0)return t;r=0;break;case"~":{let o=t.get(H([r-1,n]));o&&(o.promoted=!0);break}default:{let o=i.charCodeAt(0);if(o<57)r+=o-48;else{let s=i.toLowerCase();t.set(H([r,n]),{role:Oo[s],color:i===s?"black":"white"}),++r}}}return t}function Sr(e){return wt.map(t=>le.map(n=>{let r=e.get(n+t);if(r){let i=qo[r.role];return r.color==="white"&&(i=i.toUpperCase()),r.promoted&&(i+="~"),i}else return"1"}).join("")).join("/").replace(/1{2,}/g,t=>t.length.toString())}function vn(e,t){t.animation&&(yn(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function Nt(e,t){var n,r,i;if(!((n=t.movable)===null||n===void 0)&&n.dests&&(e.movable.dests=void 0),!((r=t.drawable)===null||r===void 0)&&r.autoShapes&&(e.drawable.autoShapes=[]),yn(e,t),t.fen&&(e.pieces=Le(t.fen),e.drawable.shapes=((i=t.drawable)===null||i===void 0?void 0:i.shapes)||[]),"check"in t&&gr(e,t.check||!1),"lastMove"in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&mn(e,e.selected),vn(e,t),!e.movable.rookCastle&&e.movable.dests){let o=e.movable.color==="white"?"1":"8",s="e"+o,a=e.movable.dests.get(s),l=e.pieces.get(s);if(!a||!l||l.role!=="king")return;e.movable.dests.set(s,a.filter(c=>!(c==="a"+o&&a.includes("c"+o))&&!(c==="h"+o&&a.includes("g"+o))))}}function yn(e,t){for(let n in t)n==="__proto__"||n==="constructor"||!Object.prototype.hasOwnProperty.call(t,n)||(Object.prototype.hasOwnProperty.call(e,n)&&Cr(e[n])&&Cr(t[n])?yn(e[n],t[n]):e[n]=t[n])}function Cr(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var pe=(e,t)=>t.animation.enabled?Io(e,t):me(e,t);function me(e,t){let n=e(t);return t.dom.redraw(),n}var xn=(e,t)=>({key:e,pos:T(e),piece:t}),Lo=(e,t)=>t.sort((n,r)=>Pe(e.pos,n.pos)-Pe(e.pos,r.pos))[0];function Bo(e,t){let n=new Map,r=[],i=new Map,o=[],s=[],a=new Map,l,c,p;for(let[f,C]of e)a.set(f,xn(f,C));for(let f of vt)l=t.pieces.get(f),c=a.get(f),l?c?Fe(l,c.piece)||(o.push(c),s.push(xn(f,l))):s.push(xn(f,l)):c&&o.push(c);for(let f of s)c=Lo(f,o.filter(C=>Fe(f.piece,C.piece))),c&&(p=[c.pos[0]-f.pos[0],c.pos[1]-f.pos[1]],n.set(f.key,p.concat(p)),r.push(c.key));for(let f of o)r.includes(f.key)||i.set(f.key,f.piece);return{anims:n,fadings:i}}function Pr(e,t){let n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}let r=1-(t-n.start)*n.frequency;if(r<=0)e.animation.current=void 0,e.dom.redrawNow();else{let i=Ko(r);for(let o of n.plan.anims.values())o[2]=o[0]*i,o[3]=o[1]*i;e.dom.redrawNow(!0),requestAnimationFrame((o=performance.now())=>Pr(e,o))}}function Io(e,t){let n=new Map(t.pieces),r=e(t),i=Bo(n,t);if(i.anims.size||i.fadings.size){let o=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:i},o||Pr(t,performance.now())}else t.dom.redraw();return r}var Ko=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1;var $o=["green","red","blue","yellow"];function Mr(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?G(e):je(e);let n=ue(t),r=ie(n,B(e),e.dom.bounds());r&&(e.drawable.current={orig:r,pos:n,brush:zo(t),snapToValidMove:e.drawable.defaultSnapToValidMove},Er(e))}function Er(e){requestAnimationFrame(()=>{let t=e.drawable.current;if(t){let n=ie(t.pos,B(e),e.dom.bounds());n||(t.snapToValidMove=!1);let r=t.snapToValidMove?xr(t.orig,t.pos,B(e),e.dom.bounds()):n;r!==t.mouseSq&&(t.mouseSq=r,t.dest=r!==t.orig?r:void 0,e.dom.redrawNow()),Er(e)}})}function Ar(e,t){e.drawable.current&&(e.drawable.current.pos=ue(t))}function _r(e){let t=e.drawable.current;t&&(t.mouseSq&&Vo(e.drawable,t),Sn(e))}function Sn(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}function Nr(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),Tr(e.drawable))}function zo(e){var t;let n=(e.shiftKey||e.ctrlKey)&&St(e),r=e.altKey||e.metaKey||((t=e.getModifierState)===null||t===void 0?void 0:t.call(e,"AltGraph"));return $o[(n?1:0)+(r?2:0)]}function Vo(e,t){let n=i=>i.orig===t.orig&&i.dest===t.dest,r=e.shapes.find(n);r&&(e.shapes=e.shapes.filter(i=>!n(i))),(!r||r.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),Tr(e)}function Tr(e){e.onChange&&e.onChange(e.shapes)}function Rr(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;let n=e.dom.bounds(),r=ue(t),i=ie(r,B(e),n);if(!i)return;let o=e.pieces.get(i),s=e.selected;if(!s&&e.drawable.enabled&&(e.drawable.eraseOnClick||!o||o.color!==e.turnColor)&&Nr(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||o||s||Ho(e,r)))t.preventDefault();else if(t.touches)return;let a=!!e.premovable.current,l=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&_t(e,e.selected,i)?pe(f=>Ue(f,i),e):Ue(e,i);let c=e.selected===i,p=Br(e,i);if(o&&p&&c&&wr(e,i)){e.draggable.current={orig:i,piece:o,origPos:r,pos:r,started:e.draggable.autoDistance&&e.stats.dragged,element:p,previouslySelected:s,originTarget:t.target,keyHasChanged:!1},p.cgDragging=!0,p.classList.add("dragging");let f=e.dom.elements.ghost;f&&(f.className=`ghost ${o.color} ${o.role}`,Z(f,Me(n)(T(i),B(e))),He(f,!0)),Cn(e)}else a&&ne(e),l&&re(e);e.dom.redraw()}function Ho(e,t){let n=B(e),r=e.dom.bounds(),i=Math.pow(r.width/8,2);for(let o of e.pieces.keys()){let s=Ct(o,n,r);if(Pe(s,t)<=i)return!0}return!1}function Or(e,t,n,r){e.pieces.set("a0",t),e.dom.redraw();let o=ue(n);e.draggable.current={orig:"a0",piece:t,origPos:o,pos:o,started:!0,element:()=>Br(e,"a0"),originTarget:n.target,newPiece:!0,force:!!r,keyHasChanged:!1},Cn(e)}function Cn(e){requestAnimationFrame(()=>{var t;let n=e.draggable.current;if(!n)return;!((t=e.animation.current)===null||t===void 0)&&t.plan.anims.has(n.orig)&&(e.animation.current=void 0);let r=e.pieces.get(n.orig);if(!r||!Fe(r,n.piece))Te(e);else if(!n.started&&Pe(n.pos,n.origPos)>=Math.pow(e.draggable.distance,2)&&(n.started=!0),n.started){if(typeof n.element=="function"){let o=n.element();if(!o)return;o.cgDragging=!0,o.classList.add("dragging"),n.element=o}let i=e.dom.bounds();Z(n.element,[n.pos[0]-i.left-i.width/16,n.pos[1]-i.top-i.height/16]),n.keyHasChanged||(n.keyHasChanged=n.orig!==ie(n.pos,B(e),i))}Cn(e)})}function qr(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=ue(t))}function Dr(e,t){let n=e.draggable.current;if(!n)return;if(t.type==="touchend"&&t.cancelable!==!1&&t.preventDefault(),t.type==="touchend"&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}ne(e),re(e);let r=ue(t)||n.pos,i=ie(r,B(e),e.dom.bounds());i&&n.started&&n.orig!==i?n.newPiece?At(e,n.orig,i,n.force):(e.stats.ctrlKey=t.ctrlKey,pn(e,n.orig,i)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!i&&(e.pieces.delete(n.orig),W(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===i||!i)?G(e):e.selectable.enabled||G(e),Lr(e),e.draggable.current=void 0,e.dom.redraw()}function Te(e){let t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,G(e),Lr(e),e.dom.redraw())}function Lr(e){let t=e.dom.elements;t.ghost&&He(t.ghost,!1)}function Br(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName==="PIECE")return n;n=n.nextSibling}}function Kr(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{Ir(e,2),setTimeout(()=>Ir(e,void 0),120)},120)}function Ir(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function $r(e,t){function n(){pr(e),t()}return{set(r){r.orientation&&r.orientation!==e.orientation&&n(),vn(e,r),(r.fen?pe:me)(i=>Nt(i,r),e)},state:e,getFen:()=>Sr(e.pieces),toggleOrientation:n,setPieces(r){pe(i=>mr(i,r),e)},selectSquare(r,i){r?pe(o=>Ue(o,r,i),e):e.selected&&(G(e),e.dom.redraw())},move(r,i){pe(o=>fn(o,r,i),e)},newPiece(r,i){pe(o=>Et(o,r,i),e)},playPremove(){if(e.premovable.current){if(pe(vr,e))return!0;e.dom.redraw()}return!1},playPredrop(r){if(e.predroppable.current){let i=yr(e,r);return e.dom.redraw(),i}return!1},cancelPremove(){me(ne,e)},cancelPredrop(){me(re,e)},cancelMove(){me(r=>{je(r),Te(r)},e)},stop(){me(r=>{kn(r),Te(r)},e)},explode(r){Kr(e,r)},setAutoShapes(r){me(i=>i.drawable.autoShapes=r,e)},setShapes(r){me(i=>i.drawable.shapes=r,e)},getKeyAtDomPos(r){return ie(r,B(e),e.dom.bounds())},redrawAll:t,dragNewPiece(r,i,o){Or(e,r,i,o)},destroy(){kn(e),e.dom.unbind&&e.dom.unbind(),e.dom.destroyed=!0}}}function zr(){return{pieces:Le(wn),orientation:"white",turnColor:"white",coordinates:!0,coordinatesOnSquares:!1,ranksPosition:"right",autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:"both",showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!("ontouchstart"in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:"g",color:"#15781B",opacity:1,lineWidth:10},red:{key:"r",color:"#882020",opacity:1,lineWidth:10},blue:{key:"b",color:"#003088",opacity:1,lineWidth:10},yellow:{key:"y",color:"#e68f00",opacity:1,lineWidth:10},paleBlue:{key:"pb",color:"#003088",opacity:.4,lineWidth:15},paleGreen:{key:"pg",color:"#15781B",opacity:.4,lineWidth:15},paleRed:{key:"pr",color:"#882020",opacity:.4,lineWidth:15},paleGrey:{key:"pgr",color:"#4a4a4a",opacity:.35,lineWidth:15},purple:{key:"purple",color:"#68217a",opacity:.65,lineWidth:10},pink:{key:"pink",color:"#ee2080",opacity:.5,lineWidth:10},white:{key:"white",color:"white",opacity:1,lineWidth:10}},prevSvgHash:""},hold:lr()}}var Vr={hilitePrimary:{key:"hilitePrimary",color:"#3291ff",opacity:1,lineWidth:1},hiliteWhite:{key:"hiliteWhite",color:"#ffffff",opacity:1,lineWidth:1}};function Gr(){let e=I("defs"),t=V(I("filter"),{id:"cg-filter-blur"});return t.appendChild(V(I("feGaussianBlur"),{stdDeviation:"0.019"})),e.appendChild(t),e}function Wr(e,t,n){var r;let i=e.drawable,o=i.current,s=o&&o.mouseSq?o:void 0,a=new Map,l=e.dom.bounds(),c=i.autoShapes.filter(k=>!k.piece);for(let k of i.shapes.concat(c).concat(s?[s]:[])){if(!k.dest)continue;let h=(r=a.get(k.dest))!==null&&r!==void 0?r:new Set,d=Ot(Rt(T(k.orig),e.orientation),l),w=Ot(Rt(T(k.dest),e.orientation),l);h.add(Mn(d,w)),a.set(k.dest,h)}let p=i.shapes.concat(c).map(k=>({shape:k,current:!1,hash:Fr(k,Pn(k.dest,a),!1,l)}));s&&p.push({shape:s,current:!0,hash:Fr(s,Pn(s.dest,a),!0,l)});let f=p.map(k=>k.hash).join(";");if(f===e.drawable.prevSvgHash)return;e.drawable.prevSvgHash=f;let C=t.querySelector("defs");Wo(i,p,C),Uo(p,t.querySelector("g"),n.querySelector("g"),k=>Zo(e,k,i.brushes,a,l))}function Wo(e,t,n){var r;let i=new Map,o;for(let l of t.filter(c=>c.shape.dest&&c.shape.brush))o=Ur(e.brushes[l.shape.brush],l.shape.modifiers),!((r=l.shape.modifiers)===null||r===void 0)&&r.hilite&&i.set(Tt(o).key,Tt(o)),i.set(o.key,o);let s=new Set,a=n.firstElementChild;for(;a;)s.add(a.getAttribute("cgKey")),a=a.nextElementSibling;for(let[l,c]of i.entries())s.has(l)||n.appendChild(Jo(c))}function Uo(e,t,n,r){let i=new Map;for(let o of e)i.set(o.hash,!1);for(let o of[t,n]){let s=[],a=o.firstElementChild,l;for(;a;)l=a.getAttribute("cgHash"),i.has(l)?i.set(l,!0):s.push(a),a=a.nextElementSibling;for(let c of s)o.removeChild(c)}for(let o of e.filter(s=>!i.get(s.hash)))for(let s of r(o))s.isCustom?n.appendChild(s.el):t.appendChild(s.el)}function Fr({orig:e,dest:t,brush:n,piece:r,modifiers:i,customSvg:o,label:s},a,l,c){var p,f;return[c.width,c.height,l,e,t,n,a&&"-",r&&jo(r),i&&Yo(i),o&&`custom-${Hr(o.html)},${(f=(p=o.center)===null||p===void 0?void 0:p[0])!==null&&f!==void 0?f:"o"}`,s&&`label-${Hr(s.text)}`].filter(C=>C).join(",")}function jo(e){return[e.color,e.role,e.scale].filter(t=>t).join(",")}function Yo(e){return[e.lineWidth,e.hilite&&"*"].filter(t=>t).join(",")}function Hr(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function Zo(e,{shape:t,current:n,hash:r},i,o,s){var a,l;let c=Ot(Rt(T(t.orig),e.orientation),s),p=t.dest?Ot(Rt(T(t.dest),e.orientation),s):c,f=t.brush&&Ur(i[t.brush],t.modifiers),C=o.get(t.dest),k=[];if(f){let h=V(I("g"),{cgHash:r});k.push({el:h}),c[0]!==p[0]||c[1]!==p[1]?h.appendChild(Xo(t,f,c,p,n,Pn(t.dest,o))):h.appendChild(Qo(i[t.brush],c,n,s))}if(t.label){let h=t.label;(a=h.fill)!==null&&a!==void 0||(h.fill=t.brush&&i[t.brush].color);let d=t.brush?void 0:"tr";k.push({el:es(h,r,c,p,C,d),isCustom:!0})}if(t.customSvg){let h=(l=t.customSvg.center)!==null&&l!==void 0?l:"orig",[d,w]=h==="label"?Yr(c,p,C).map(y=>y-.5):h==="dest"?p:c,b=V(I("g"),{transform:`translate(${d},${w})`,cgHash:r});b.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,k.push({el:b,isCustom:!0})}return k}function Qo(e,t,n,r){let i=ts(),o=(r.width+r.height)/(4*Math.max(r.width,r.height));return V(I("circle"),{stroke:e.color,"stroke-width":i[n?0:1],fill:"none",opacity:jr(e,n),cx:t[0],cy:t[1],r:o-i[1]/2})}function Tt(e){return["#ffffff","#fff","white"].includes(e.color)?Vr.hilitePrimary:Vr.hiliteWhite}function Xo(e,t,n,r,i,o){var s;function a(p){var f;let C=rs(o&&!i),k=r[0]-n[0],h=r[1]-n[1],d=Math.atan2(h,k),w=Math.cos(d)*C,b=Math.sin(d)*C;return V(I("line"),{stroke:p?Tt(t).color:t.color,"stroke-width":ns(t,i)+(p?.04:0),"stroke-linecap":"round","marker-end":`url(#arrowhead-${p?Tt(t).key:t.key})`,opacity:!((f=e.modifiers)===null||f===void 0)&&f.hilite?1:jr(t,i),x1:n[0],y1:n[1],x2:r[0]-w,y2:r[1]-b})}if(!(!((s=e.modifiers)===null||s===void 0)&&s.hilite))return a(!1);let l=I("g"),c=V(I("g"),{filter:"url(#cg-filter-blur)"});return c.appendChild(is(n,r)),c.appendChild(a(!0)),l.appendChild(c),l.appendChild(a(!1)),l}function Jo(e){let t=V(I("marker"),{id:"arrowhead-"+e.key,orient:"auto",overflow:"visible",markerWidth:4,markerHeight:4,refX:e.key.startsWith("hilite")?1.86:2.05,refY:2});return t.appendChild(V(I("path"),{d:"M0,0 V4 L3,2 Z",fill:e.color})),t.setAttribute("cgKey",e.key),t}function es(e,t,n,r,i,o){var s;let l=.4*.75**e.text.length,c=Yr(n,r,i),p=o==="tr"?.4:0,f=V(I("g"),{transform:`translate(${c[0]+p},${c[1]-p})`,cgHash:t});f.appendChild(V(I("circle"),{r:.4/2,"fill-opacity":o?1:.8,"stroke-opacity":o?1:.7,"stroke-width":.03,fill:(s=e.fill)!==null&&s!==void 0?s:"#666",stroke:"white"}));let C=V(I("text"),{"font-size":l,"font-family":"Noto Sans","text-anchor":"middle",fill:"white",y:.13*.75**e.text.length});return C.innerHTML=e.text,f.appendChild(C),f}function Rt(e,t){return t==="white"?e:[7-e[0],7-e[1]]}function Pn(e,t){return(e&&t.has(e)&&t.get(e).size>1)===!0}function I(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function V(e,t){for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function Ur(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(n=>n).join("")}:e}function ts(){return[3/64,4/64]}function ns(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function jr(e,t){return(e.opacity||1)*(t?.9:1)}function rs(e){return(e?20:10)/64}function Ot(e,t){let n=Math.min(1,t.width/t.height),r=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*r]}function is(e,t){let n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return V(I("rect"),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:"none",stroke:"none"})}function Mn(e,t,n=!0){let r=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(r*8/Math.PI)+16)%16:r}function os(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((n,r)=>n+r*r,0))}function Yr(e,t,n){let r=os(e,t),i=Mn(e,t,!1);if(n&&(r-=33/64,n.size>1)){r-=10/64;let o=Mn(e,t);(n.has((o+1)%16)||n.has((o+15)%16))&&o&1&&(r-=.4)}return[e[0]-Math.cos(i)*r,e[1]-Math.sin(i)*r].map(o=>o+.5)}function Zr(e,t){e.innerHTML="",e.classList.add("cg-wrap");for(let l of or)e.classList.toggle("orientation-"+l,t.orientation===l);e.classList.toggle("manipulable",!t.viewOnly);let n=Q("cg-container");e.appendChild(n);let r=Q("cg-board");n.appendChild(r);let i,o,s;if(t.drawable.visible&&(i=V(I("svg"),{class:"cg-shapes",viewBox:"-4 -4 8 8",preserveAspectRatio:"xMidYMid slice"}),i.appendChild(Gr()),i.appendChild(I("g")),o=V(I("svg"),{class:"cg-custom-svgs",viewBox:"-3.5 -3.5 8 8",preserveAspectRatio:"xMidYMid slice"}),o.appendChild(I("g")),s=Q("cg-auto-pieces"),n.appendChild(i),n.appendChild(o),n.appendChild(s)),t.coordinates){let l=t.orientation==="black"?" black":"",c=t.ranksPosition==="left"?" left":"";if(t.coordinatesOnSquares){let p=t.orientation==="white"?f=>f+1:f=>8-f;le.forEach((f,C)=>n.appendChild(En(Ce.map(k=>f+k),"squares rank"+p(C)+l+c)))}else n.appendChild(En(Ce,"ranks"+l+c)),n.appendChild(En(le,"files"+l))}let a;return t.draggable.enabled&&t.draggable.showGhost&&(a=Q("piece","ghost"),He(a,!1),n.appendChild(a)),{board:r,container:n,wrap:e,ghost:a,svg:i,customSvg:o,autoPieces:s}}function En(e,t){let n=Q("coords",t),r;for(let i of e)r=Q("coord"),r.textContent=i,n.appendChild(r);return n}function Qr(e,t){if(!e.dropmode.active)return;ne(e),re(e);let n=e.dropmode.piece;if(n){e.pieces.set("a0",n);let r=ue(t),i=r&&ie(r,B(e),e.dom.bounds());i&&At(e,"a0",i)}e.dom.redraw()}function Jr(e,t){let n=e.dom.elements.board;if("ResizeObserver"in window&&new ResizeObserver(t).observe(e.dom.elements.wrap),(e.disableContextMenu||e.drawable.enabled)&&n.addEventListener("contextmenu",i=>i.preventDefault()),e.viewOnly)return;let r=as(e);n.addEventListener("touchstart",r,{passive:!1}),n.addEventListener("mousedown",r,{passive:!1})}function ei(e,t){let n=[];if("ResizeObserver"in window||n.push(Ye(document.body,"chessground.resize",t)),!e.viewOnly){let r=Xr(e,qr,Ar),i=Xr(e,Dr,_r);for(let s of["touchmove","mousemove"])n.push(Ye(document,s,r));for(let s of["touchend","mouseup"])n.push(Ye(document,s,i));let o=()=>e.dom.bounds.clear();n.push(Ye(document,"scroll",o,{capture:!0,passive:!0})),n.push(Ye(window,"resize",o,{passive:!0}))}return()=>n.forEach(r=>r())}function Ye(e,t,n,r){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n,r)}var as=e=>t=>{e.draggable.current?Te(e):e.drawable.current?Sn(e):t.shiftKey||St(t)?e.drawable.enabled&&Mr(e,t):e.viewOnly||(e.dropmode.active?Qr(e,t):Rr(e,t))},Xr=(e,t,n)=>r=>{e.drawable.current?e.drawable.enabled&&n(e,r):e.viewOnly||t(e,r)};function ni(e){let t=B(e),n=Me(e.dom.bounds()),r=e.dom.elements.board,i=e.pieces,o=e.animation.current,s=o?o.plan.anims:new Map,a=o?o.plan.fadings:new Map,l=e.draggable.current,c=ls(e),p=new Set,f=new Set,C=new Map,k=new Map,h,d,w,b,y,E,x,P,A,_;for(d=r.firstChild;d;){if(h=d.cgKey,ii(d))if(w=i.get(h),y=s.get(h),E=a.get(h),b=d.cgPiece,d.cgDragging&&(!l||l.orig!==h)&&(d.classList.remove("dragging"),Z(d,n(T(h),t)),d.cgDragging=!1),!E&&d.cgFading&&(d.cgFading=!1,d.classList.remove("fading")),w){if(y&&d.cgAnimating&&b===Ze(w)){let v=T(h);v[0]+=y[2],v[1]+=y[3],d.classList.add("anim"),Z(d,n(v,t))}else d.cgAnimating&&(d.cgAnimating=!1,d.classList.remove("anim"),Z(d,n(T(h),t)),e.addPieceZIndex&&(d.style.zIndex=An(T(h),t)));b===Ze(w)&&(!E||!d.cgFading)?p.add(h):E&&b===Ze(E)?(d.classList.add("fading"),d.cgFading=!0):_n(C,b,d)}else _n(C,b,d);else if(oi(d)){let v=d.className;c.get(h)===v?f.add(h):_n(k,v,d)}d=d.nextSibling}for(let[v,R]of c)if(!f.has(v)){A=k.get(R),_=A&&A.pop();let O=n(T(v),t);if(_)_.cgKey=v,Z(_,O);else{let N=Q("square",R);N.cgKey=v,Z(N,O),r.insertBefore(N,r.firstChild)}}for(let[v,R]of i)if(y=s.get(v),!p.has(v))if(x=C.get(Ze(R)),P=x&&x.pop(),P){P.cgKey=v,P.cgFading&&(P.classList.remove("fading"),P.cgFading=!1);let O=T(v);e.addPieceZIndex&&(P.style.zIndex=An(O,t)),y&&(P.cgAnimating=!0,P.classList.add("anim"),O[0]+=y[2],O[1]+=y[3]),Z(P,n(O,t))}else{let O=Ze(R),N=Q("piece",O),K=T(v);N.cgPiece=O,N.cgKey=v,y&&(N.cgAnimating=!0,K[0]+=y[2],K[1]+=y[3]),Z(N,n(K,t)),e.addPieceZIndex&&(N.style.zIndex=An(K,t)),r.appendChild(N)}for(let v of C.values())ti(e,v);for(let v of k.values())ti(e,v)}function ri(e){let t=B(e),n=Me(e.dom.bounds()),r=e.dom.elements.board.firstChild;for(;r;)(ii(r)&&!r.cgAnimating||oi(r))&&Z(r,n(T(r.cgKey),t)),r=r.nextSibling}function Nn(e){var t,n;let r=e.dom.elements.wrap.getBoundingClientRect(),i=e.dom.elements.container,o=r.height/r.width,s=Math.floor(r.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,a=s*o;i.style.width=s+"px",i.style.height=a+"px",e.dom.bounds.clear(),(t=e.addDimensionsCssVarsTo)===null||t===void 0||t.style.setProperty("---cg-width",s+"px"),(n=e.addDimensionsCssVarsTo)===null||n===void 0||n.style.setProperty("---cg-height",a+"px")}var ii=e=>e.tagName==="PIECE",oi=e=>e.tagName==="SQUARE";function ti(e,t){for(let n of t)e.dom.elements.board.removeChild(n)}function An(e,t){let r=e[1];return`${t?10-r:3+r}`}var Ze=e=>`${e.color} ${e.role}`;function ls(e){var t,n,r;let i=new Map;if(e.lastMove&&e.highlight.lastMove)for(let a of e.lastMove)ge(i,a,"last-move");if(e.check&&e.highlight.check&&ge(i,e.check,"check"),e.selected&&(ge(i,e.selected,"selected"),e.movable.showDests)){let a=(t=e.movable.dests)===null||t===void 0?void 0:t.get(e.selected);if(a)for(let c of a)ge(i,c,"move-dest"+(e.pieces.has(c)?" oc":""));let l=(r=(n=e.premovable.customDests)===null||n===void 0?void 0:n.get(e.selected))!==null&&r!==void 0?r:e.premovable.dests;if(l)for(let c of l)ge(i,c,"premove-dest"+(e.pieces.has(c)?" oc":""))}let o=e.premovable.current;if(o)for(let a of o)ge(i,a,"current-premove");else e.predroppable.current&&ge(i,e.predroppable.current.key,"current-premove");let s=e.exploding;if(s)for(let a of s.keys)ge(i,a,"exploding"+s.stage);return e.highlight.custom&&e.highlight.custom.forEach((a,l)=>{ge(i,l,a)}),i}function ge(e,t,n){let r=e.get(t);r?e.set(t,`${r} ${n}`):e.set(t,n)}function _n(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function si(e,t,n){let r=new Map,i=[];for(let a of e)r.set(a.hash,!1);let o=t.firstElementChild,s;for(;o;)s=o.getAttribute("cgHash"),r.has(s)?r.set(s,!0):i.push(o),o=o.nextElementSibling;for(let a of i)t.removeChild(a);for(let a of e)r.get(a.hash)||t.appendChild(n(a))}function ai(e,t){let r=e.drawable.autoShapes.filter(i=>i.piece).map(i=>({shape:i,hash:hs(i),current:!1}));si(r,t,i=>us(e,i,e.dom.bounds()))}function ci(e){var t;let n=B(e),r=Me(e.dom.bounds()),i=(t=e.dom.elements.autoPieces)===null||t===void 0?void 0:t.firstChild;for(;i;)an(i,r(T(i.cgKey),n),i.cgScale),i=i.nextSibling}function us(e,{shape:t,hash:n},r){var i,o,s;let a=t.orig,l=(i=t.piece)===null||i===void 0?void 0:i.role,c=(o=t.piece)===null||o===void 0?void 0:o.color,p=(s=t.piece)===null||s===void 0?void 0:s.scale,f=Q("piece",`${l} ${c}`);return f.setAttribute("cgHash",n),f.cgKey=a,f.cgScale=p,an(f,Me(r)(T(a),B(e)),p),f}var hs=e=>{var t,n,r;return[e.orig,(t=e.piece)===null||t===void 0?void 0:t.role,(n=e.piece)===null||n===void 0?void 0:n.color,(r=e.piece)===null||r===void 0?void 0:r.scale].join(",")};function li(e,t){let n=zr();Nt(n,t||{});function r(){let i="dom"in n?n.dom.unbind:void 0,o=Zr(e,n),s=cr(()=>o.board.getBoundingClientRect()),a=p=>{ni(c),o.autoPieces&&ai(c,o.autoPieces),!p&&o.svg&&Wr(c,o.svg,o.customSvg)},l=()=>{Nn(c),ri(c),o.autoPieces&&ci(c)},c=n;return c.dom={elements:o,bounds:s,redraw:fs(a),redrawNow:a,unbind:i},c.drawable.prevSvgHash="",Nn(c),a(!1),Jr(c,l),i||(c.dom.unbind=ei(c,l)),c.events.insert&&c.events.insert(o),c}return $r(r(),r)}function fs(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}function ps(e,t){return document.createElement(e,t)}function ms(e,t,n){return document.createElementNS(e,t,n)}function gs(){return Re(document.createDocumentFragment())}function ks(e){return document.createTextNode(e)}function bs(e){return document.createComment(e)}function ws(e,t,n){if(ke(e)){let r=e;for(;r&&ke(r);)r=Re(r).parent;e=r??e}ke(t)&&(t=Re(t,e)),n&&ke(n)&&(n=Re(n).firstChildNode),e.insertBefore(t,n)}function vs(e,t){e.removeChild(t)}function ys(e,t){ke(t)&&(t=Re(t,e)),e.appendChild(t)}function ui(e){if(ke(e)){for(;e&&ke(e);)e=Re(e).parent;return e??null}return e.parentNode}function xs(e){var t;if(ke(e)){let n=Re(e),r=ui(n);if(r&&n.lastChildNode){let i=Array.from(r.childNodes),o=i.indexOf(n.lastChildNode);return(t=i[o+1])!==null&&t!==void 0?t:null}return null}return e.nextSibling}function Ss(e){return e.tagName}function Cs(e,t){e.textContent=t}function Ps(e){return e.textContent}function Ms(e){return e.nodeType===1}function Es(e){return e.nodeType===3}function As(e){return e.nodeType===8}function ke(e){return e.nodeType===11}function Re(e,t){var n,r,i;let o=e;return(n=o.parent)!==null&&n!==void 0||(o.parent=t??null),(r=o.firstChildNode)!==null&&r!==void 0||(o.firstChildNode=e.firstChild),(i=o.lastChildNode)!==null&&i!==void 0||(o.lastChildNode=e.lastChild),o}var hi={createElement:ps,createElementNS:ms,createTextNode:ks,createDocumentFragment:gs,createComment:bs,insertBefore:ws,removeChild:vs,appendChild:ys,parentNode:ui,nextSibling:xs,tagName:Ss,setTextContent:Cs,getTextContent:Ps,isElement:Ms,isText:Es,isComment:As,isDocumentFragment:ke};function Oe(e,t,n,r,i){let o=t===void 0?void 0:t.key;return{sel:e,data:t,children:n,text:r,elm:i,key:o}}var Qe=Array.isArray;function Be(e){return typeof e=="string"||typeof e=="number"||e instanceof String||e instanceof Number}function Tn(e){return e===void 0}function Y(e){return e!==void 0}var Rn=Oe("",{},[],void 0,void 0);function Xe(e,t){var n,r;let i=e.key===t.key,o=((n=e.data)===null||n===void 0?void 0:n.is)===((r=t.data)===null||r===void 0?void 0:r.is),s=e.sel===t.sel,a=!e.sel&&e.sel===t.sel?typeof e.text==typeof t.text:!0;return s&&i&&o&&a}function _s(){throw new Error("The document fragment is not supported on this platform.")}function Ns(e,t){return e.isElement(t)}function Ts(e,t){return e.isDocumentFragment(t)}function Rs(e,t,n){var r;let i={};for(let o=t;o<=n;++o){let s=(r=e[o])===null||r===void 0?void 0:r.key;s!==void 0&&(i[s]=o)}return i}var Os=["create","update","remove","destroy","pre","post"];function On(e,t,n){let r={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},i=t!==void 0?t:hi;for(let h of Os)for(let d of e){let w=d[h];w!==void 0&&r[h].push(w)}function o(h){let d=h.id?"#"+h.id:"",w=h.getAttribute("class"),b=w?"."+w.split(" ").join("."):"";return Oe(i.tagName(h).toLowerCase()+d+b,{},[],void 0,h)}function s(h){return Oe(void 0,{},[],void 0,h)}function a(h,d){return function(){if(--d===0){let b=i.parentNode(h);i.removeChild(b,h)}}}function l(h,d){var w,b,y,E;let x,P=h.data;if(P!==void 0){let v=(w=P.hook)===null||w===void 0?void 0:w.init;Y(v)&&(v(h),P=h.data)}let A=h.children,_=h.sel;if(_==="!")Tn(h.text)&&(h.text=""),h.elm=i.createComment(h.text);else if(_!==void 0){let v=_.indexOf("#"),R=_.indexOf(".",v),O=v>0?v:_.length,N=R>0?R:_.length,K=v!==-1||R!==-1?_.slice(0,Math.min(O,N)):_,X=h.elm=Y(P)&&Y(x=P.ns)?i.createElementNS(x,K,P):i.createElement(K,P);for(O<N&&X.setAttribute("id",_.slice(O+1,N)),R>0&&X.setAttribute("class",_.slice(N+1).replace(/\./g," ")),x=0;x<r.create.length;++x)r.create[x](Rn,h);if(Qe(A))for(x=0;x<A.length;++x){let $n=A[x];$n!=null&&i.appendChild(X,l($n,d))}else Be(h.text)&&i.appendChild(X,i.createTextNode(h.text));let tt=h.data.hook;Y(tt)&&((b=tt.create)===null||b===void 0||b.call(tt,Rn,h),tt.insert&&d.push(h))}else if(!((y=n?.experimental)===null||y===void 0)&&y.fragments&&h.children){for(h.elm=((E=i.createDocumentFragment)!==null&&E!==void 0?E:_s)(),x=0;x<r.create.length;++x)r.create[x](Rn,h);for(x=0;x<h.children.length;++x){let v=h.children[x];v!=null&&i.appendChild(h.elm,l(v,d))}}else h.elm=i.createTextNode(h.text);return h.elm}function c(h,d,w,b,y,E){for(;b<=y;++b){let x=w[b];x!=null&&i.insertBefore(h,l(x,E),d)}}function p(h){var d,w;let b=h.data;if(b!==void 0){(w=(d=b?.hook)===null||d===void 0?void 0:d.destroy)===null||w===void 0||w.call(d,h);for(let y=0;y<r.destroy.length;++y)r.destroy[y](h);if(h.children!==void 0)for(let y=0;y<h.children.length;++y){let E=h.children[y];E!=null&&typeof E!="string"&&p(E)}}}function f(h,d,w,b){for(var y,E;w<=b;++w){let x,P,A=d[w];if(A!=null)if(Y(A.sel)){p(A),x=r.remove.length+1,P=a(A.elm,x);for(let v=0;v<r.remove.length;++v)r.remove[v](A,P);let _=(E=(y=A?.data)===null||y===void 0?void 0:y.hook)===null||E===void 0?void 0:E.remove;Y(_)?_(A,P):P()}else A.children?(p(A),f(h,A.children,0,A.children.length-1)):i.removeChild(h,A.elm)}}function C(h,d,w,b){let y=0,E=0,x=d.length-1,P=d[0],A=d[x],_=w.length-1,v=w[0],R=w[_],O,N,K,X;for(;y<=x&&E<=_;)P==null?P=d[++y]:A==null?A=d[--x]:v==null?v=w[++E]:R==null?R=w[--_]:Xe(P,v)?(k(P,v,b),P=d[++y],v=w[++E]):Xe(A,R)?(k(A,R,b),A=d[--x],R=w[--_]):Xe(P,R)?(k(P,R,b),i.insertBefore(h,P.elm,i.nextSibling(A.elm)),P=d[++y],R=w[--_]):Xe(A,v)?(k(A,v,b),i.insertBefore(h,A.elm,P.elm),A=d[--x],v=w[++E]):(O===void 0&&(O=Rs(d,y,x)),N=O[v.key],Tn(N)?i.insertBefore(h,l(v,b),P.elm):(K=d[N],K.sel!==v.sel?i.insertBefore(h,l(v,b),P.elm):(k(K,v,b),d[N]=void 0,i.insertBefore(h,K.elm,P.elm))),v=w[++E]);E<=_&&(X=w[_+1]==null?null:w[_+1].elm,c(h,X,w,E,_,b)),y<=x&&f(h,d,y,x)}function k(h,d,w){var b,y,E,x,P,A,_,v;let R=(b=d.data)===null||b===void 0?void 0:b.hook;(y=R?.prepatch)===null||y===void 0||y.call(R,h,d);let O=d.elm=h.elm;if(h===d)return;if(d.data!==void 0||Y(d.text)&&d.text!==h.text){(E=d.data)!==null&&E!==void 0||(d.data={}),(x=h.data)!==null&&x!==void 0||(h.data={});for(let X=0;X<r.update.length;++X)r.update[X](h,d);(_=(A=(P=d.data)===null||P===void 0?void 0:P.hook)===null||A===void 0?void 0:A.update)===null||_===void 0||_.call(A,h,d)}let N=h.children,K=d.children;Tn(d.text)?Y(N)&&Y(K)?N!==K&&C(O,N,K,w):Y(K)?(Y(h.text)&&i.setTextContent(O,""),c(O,null,K,0,K.length-1,w)):Y(N)?f(O,N,0,N.length-1):Y(h.text)&&i.setTextContent(O,""):h.text!==d.text&&(Y(N)&&f(O,N,0,N.length-1),i.setTextContent(O,d.text)),(v=R?.postpatch)===null||v===void 0||v.call(R,h,d)}return function(d,w){let b,y,E,x=[];for(b=0;b<r.pre.length;++b)r.pre[b]();for(Ns(i,d)?d=o(d):Ts(i,d)&&(d=s(d)),Xe(d,w)?k(d,w,x):(y=d.elm,E=i.parentNode(y),l(w,x),E!==null&&(i.insertBefore(E,w.elm,i.nextSibling(y)),f(E,[d],0,0))),b=0;b<x.length;++b)x[b].data.hook.insert(x[b]);for(b=0;b<r.post.length;++b)r.post[b]();return w}}function fi(e,t,n){if(e.ns="http://www.w3.org/2000/svg",n!=="foreignObject"&&t!==void 0)for(let r=0;r<t.length;++r){let i=t[r];if(typeof i=="string")continue;let o=i.data;o!==void 0&&fi(o,i.children,i.sel)}}function S(e,t,n){let r={},i,o,s;if(n!==void 0?(t!==null&&(r=t),Qe(n)?i=n:Be(n)?o=n.toString():n&&n.sel&&(i=[n])):t!=null&&(Qe(t)?i=t:Be(t)?o=t.toString():t&&t.sel?i=[t]:r=t),i!==void 0)for(s=0;s<i.length;++s)Be(i[s])&&(i[s]=Oe(void 0,void 0,void 0,i[s],void 0));return e[0]==="s"&&e[1]==="v"&&e[2]==="g"&&(e.length===3||e[3]==="."||e[3]==="#")&&fi(r,i,e),Oe(e,r,i,o,void 0)}var qs="http://www.w3.org/1999/xlink",Ds="http://www.w3.org/XML/1998/namespace";function pi(e,t){let n,r=t.elm,i=e.data.attrs,o=t.data.attrs;if(!(!i&&!o)&&i!==o){i=i||{},o=o||{};for(n in o){let s=o[n];i[n]!==s&&(s===!0?r.setAttribute(n,""):s===!1?r.removeAttribute(n):n.charCodeAt(0)!==120?r.setAttribute(n,s):n.charCodeAt(3)===58?r.setAttributeNS(Ds,n,s):n.charCodeAt(5)===58?r.setAttributeNS(qs,n,s):r.setAttribute(n,s))}for(n in i)n in o||r.removeAttribute(n)}}var qn={create:pi,update:pi};function mi(e,t){let n,r,i=t.elm,o=e.data.class,s=t.data.class;if(!(!o&&!s)&&o!==s){o=o||{},s=s||{};for(r in o)o[r]&&!Object.prototype.hasOwnProperty.call(s,r)&&i.classList.remove(r);for(r in s)n=s[r],n!==o[r]&&i.classList[n?"add":"remove"](r)}}var Dn={create:mi,update:mi};var gi=e=>{let t=Ln[e];return t?S("nag",{attrs:{title:t.name}},t.symbol):void 0},Ln={1:{symbol:"!",name:"Good move"},2:{symbol:"?",name:"Mistake"},3:{symbol:"!!",name:"Brilliant move"},4:{symbol:"??",name:"Blunder"},5:{symbol:"!?",name:"Interesting move"},6:{symbol:"?!",name:"Dubious move"},7:{symbol:"\u25A1",name:"Only move"},22:{symbol:"\u2A00",name:"Zugzwang"},10:{symbol:"=",name:"Equal position"},13:{symbol:"\u221E",name:"Unclear position"},14:{symbol:"\u2A72",name:"White is slightly better"},15:{symbol:"\u2A71",name:"Black is slightly better"},16:{symbol:"\xB1",name:"White is better"},17:{symbol:"\u2213",name:"Black is better"},18:{symbol:"+\u2212",name:"White is winning"},19:{symbol:"-+",name:"Black is winning"},146:{symbol:"N",name:"Novelty"},32:{symbol:"\u2191\u2191",name:"Development"},36:{symbol:"\u2191",name:"Initiative"},40:{symbol:"\u2192",name:"Attack"},132:{symbol:"\u21C6",name:"Counterplay"},138:{symbol:"\u2295",name:"Time trouble"},44:{symbol:"=\u221E",name:"With compensation"},140:{symbol:"\u2206",name:"With the idea"}};function bi(e,t,n){for(let r of["touchstart","mousedown"])e.addEventListener(r,i=>{t(i),i.preventDefault(),n&&n()},{passive:!1})}var Bn=(e,t,n,r=!0)=>Ie(i=>i.addEventListener(e,o=>{let s=t(o);return s===!1&&o.preventDefault(),n?.(),s},{passive:r}));function Ie(e){return{insert:t=>e(t.elm)}}var Je=e=>{if(!e&&e!==0)return["-"];let t=new Date(e*1e3),n=":",r=ki(t.getUTCMinutes())+n+ki(t.getUTCSeconds());return e>=3600?[Math.floor(e/3600)+n+r]:[r]},ki=e=>(e<10?"0":"")+e,wi=(e,t,n,r)=>{let i=`${t.toUpperCase()}${n}`;if(!r)return`${i} ${e("aria.empty")}`;let o=e(`aria.piece.${r.role}`);return`${i} ${e(`aria.${r.color}`)} ${o}`},qt=(e,t,n)=>{let r=n?Ls(e,n):e;if(t&&t.length>0){let i=t.map(o=>Ln[o]?.name).filter(o=>o).join(", ");i&&(r+=`, ${i}`)}return r},Ls=(e,t)=>e.split("").map(n=>{if(n==="x")return t("san.takes");if(n==="+")return t("san.check");if(n==="#")return t("san.checkmate");if(n==="=")return t("san.promotesTo");if(n==="@")return t("san.droppedOn");let r=n.charCodeAt(0);return r>48&&r<58?n:r>96&&r<105?n.toUpperCase():n==="K"?t("aria.piece.king"):n==="Q"?t("aria.piece.queen"):n==="R"?t("aria.piece.rook"):n==="B"?t("aria.piece.bishop"):n==="N"?t("aria.piece.knight"):n==="O"?"O":n}).join(" ").replace("O - O - O",t("san.longCastling")).replace("O - O",t("san.shortCastling"));function vi(e){let t=0;return n=>{t+=n.deltaY*(n.deltaMode?40:1),Math.abs(t)>=4?(e(n,!0),t=0):e(n,!1)}}function yi(e,t){let n=()=>{e(),r=Math.max(100,r-r/15),i=setTimeout(n,r)},r=350,i=setTimeout(n,500);e();let o=t.type=="touchstart"?"touchend":"mouseup";document.addEventListener(o,()=>clearTimeout(i),{once:!0})}var Bs=e=>e.altKey||e.ctrlKey||e.shiftKey||e.metaKey||document.activeElement instanceof HTMLInputElement||document.activeElement instanceof HTMLTextAreaElement,xi=e=>t=>{Bs(t)||(t.key=="ArrowLeft"?e.goTo("prev"):t.key=="ArrowRight"?e.goTo("next"):t.key=="f"&&e.flip())};var Si=e=>S("div.lpv__menu.lpv__pane",{attrs:{role:"menu","aria-label":e.translate("menu")??"Menu"},hook:{insert:t=>{let n=t.elm;n.querySelector('[role="menuitem"]')?.focus(),Ks(e,n)}}},[S("button.lpv__menu__entry.lpv__menu__flip.lpv__fbt",{attrs:{role:"menuitem"},hook:Bn("click",e.flip)},e.translate("flipTheBoard")),e.opts.menu.analysisBoard?.enabled?S("a.lpv__menu__entry.lpv__menu__analysis.lpv__fbt",{attrs:{role:"menuitem",href:e.analysisUrl(),target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",e.translate("analysisBoard"))}},e.translate("analysisBoard")):void 0,e.opts.menu.practiceWithComputer?.enabled?S("a.lpv__menu__entry.lpv__menu__practice.lpv__fbt",{attrs:{role:"menuitem",href:e.practiceUrl(),target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",e.translate("practiceWithComputer"))}},e.translate("practiceWithComputer")):void 0,e.opts.menu.getPgn.enabled?S("button.lpv__menu__entry.lpv__menu__pgn.lpv__fbt",{attrs:{role:"menuitem"},hook:Bn("click",e.togglePgn)},e.translate("getPgn")):void 0,Is(e)]),Is=e=>{let t=e.game.metadata.externalLink,n=e.translate(e.game.metadata.isLichess?"viewOnLichess":"viewOnSite");return t&&S("a.lpv__menu__entry.lpv__fbt",{attrs:{role:"menuitem",href:t,target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",n)}},n)},Ci=e=>S("div.lpv__controls",{attrs:{role:"navigation","aria-label":e.translate("aria.navigationControls")}},[e.pane=="board"?void 0:Dt(e,"first","step-backward"),Dt(e,"prev","left-open"),S("button.lpv__fbt.lpv__controls__menu.lpv__icon",{class:{active:e.pane!="board","lpv__icon-ellipsis-vert":e.pane=="board"},hook:{insert:t=>{let n=t.elm;n.addEventListener("click",e.toggleMenu),e.menuButton=n}},attrs:{"aria-label":e.translate("menu"),"aria-expanded":String(e.pane==="menu"),"aria-haspopup":"menu"}},e.pane=="board"?void 0:"X"),Dt(e,"next","right-open"),e.pane=="board"?void 0:Dt(e,"last","step-forward")]),Dt=(e,t,n)=>{let r=e.pane=="board"&&!e.canGoTo(t);return S(`button.lpv__controls__goto.lpv__controls__goto--${t}.lpv__fbt.lpv__icon.lpv__icon-${n}`,{class:{disabled:r},hook:Ie(i=>bi(i,o=>yi(()=>e.goTo(t),o))),attrs:{"aria-label":e.translate(`aria.${t}`),"aria-disabled":String(r),disabled:r}})},Ks=(e,t)=>{let n=r=>{switch(r.key){case"Enter":case" ":r.preventDefault(),document.activeElement?.click();break;case"Escape":r.preventDefault(),e.toggleMenu();break}};t.addEventListener("keydown",n)};var et={"aria-hidden":!0},Lt={role:"presentation","aria-hidden":"true"},Pi=e=>{let t=e.curData();if(!Mt(t))return"";let n=Math.ceil(t.ply/2),r=t.ply%2===1?"white":"black",i=t.san,o=e.translate("aria.move",n.toString(),e.translate(`aria.${r}`),qt(i,t.nags,e.translate)),s=t.clocks&&t.clocks[r==="white"?"white":"black"];if(s!==void 0&&e.opts.showClocks){let l=Je(s).join("");l!=="-"&&(o+=", "+e.translate("aria.remaining",l))}let a=t.comments.join(" ").trim();return a&&(o+=`. ${a}`),o},Mi=e=>{let t=e.game,n=a=>{let l=a.name||e.translate("aria.unknownPlayer");return a.title&&(l=`${a.title} ${l}`),a.rating&&(l=`${l}, ${e.translate("aria.rated",a.rating.toString())}`),l},r=a=>!a||a==="*"?e.translate("aria.gameInProgress"):a==="1-0"?e.translate("aria.whitesWin"):a==="0-1"?e.translate("aria.blacksWin"):a==="1/2-1/2"?e.translate("aria.draw"):a,i=n(t.players.white),o=n(t.players.black),s=r(t.metadata.result);return e.translate("aria.chessGameBetween",i,o,s)};var Ai=e=>S("div.lpv__side",[S("div.lpv__moves",{attrs:{role:"complementary","aria-label":e.translate("aria.gameMoves")},hook:{insert:t=>{let n=t.elm;e.path.empty()||Ei(e,n),n.addEventListener("click",r=>{let i=r.target.getAttribute("data-path");i&&e.toPath(new te(i))},{passive:!0})},postpatch:(t,n)=>{e.autoScrollRequested&&(Ei(e,n.elm),e.autoScrollRequested=!1)}}},[...e.game.initial.comments.map(It),...Fs(e),...$s(e)])]),$s=e=>{let t=e.game.metadata.result;return t&&t!="*"?[S("comment.result",{attrs:{role:"note","aria-label":e.translate("aria.gameResult")}},e.game.metadata.result)]:[]},In=()=>S("button.move.empty",{attrs:{"aria-hidden":"true",disabled:!0}},"..."),Kn=e=>S("index",{attrs:Lt},`${e}.`),It=e=>S("comment",{attrs:{role:"note"}},e),zs=()=>S("paren.open",{attrs:et},"("),Vs=()=>S("paren.close",{attrs:et},")"),Bt=e=>Math.floor((e.ply-1)/2)+1,Fs=e=>{let t=Gs(e),n=[],r,i=e.game.moves.children.slice(1);for(e.game.initial.pos.turn=="black"&&e.game.mainline[0]&&n.push(Kn(e.game.initial.pos.fullmoves),In());r=(r||e.game.moves).children[0];){let o=r.data,s=o.ply%2==1;s&&n.push(Kn(Bt(o))),n.push(t(o));let a=s&&(i.length||o.comments.length)&&r.children.length;a&&n.push(In()),o.comments.forEach(l=>n.push(It(l))),i.forEach(l=>n.push(Hs(e.translate,t,l))),a&&n.push(Kn(Bt(o)),In()),i=r.children.slice(1)}return n},Hs=(e,t,n)=>S("variation",{attrs:{role:"group","aria-label":e("aria.variation")}},[...n.data.startingComments.map(It),..._i(t,n)]),_i=(e,t)=>{let n=[],r=[];t.data.ply%2==0&&n.push(S("index",{attrs:Lt},[Bt(t.data),"..."]));do{let i=t.data;i.ply%2==1&&n.push(S("index",{attrs:Lt},[Bt(i),"."])),n.push(e(i)),i.comments.forEach(o=>n.push(It(o))),r.forEach(o=>{n=[...n,zs(),..._i(e,o),Vs()]}),r=t.children.slice(1),t=t.children[0]}while(t);return n},Gs=e=>t=>S("button.move",{class:{current:e.path.equals(t.path),ancestor:e.path.contains(t.path),good:t.nags.includes(1),mistake:t.nags.includes(2),brilliant:t.nags.includes(3),blunder:t.nags.includes(4),interesting:t.nags.includes(5),inaccuracy:t.nags.includes(6)},attrs:{"data-path":t.path.path,role:"button","aria-label":e.translate("aria.move",Math.ceil(t.ply/2).toString(),e.translate(`aria.${t.ply%2===1?"white":"black"}`),qt(t.san,t.nags,e.translate))}},[t.san,...t.nags.map(gi)]),Ei=(e,t)=>{let n=t.querySelector(".current");if(!n){t.scrollTop=e.path.empty()?0:99999;return}t.scrollTop=n.offsetTop-t.offsetHeight/2+n.offsetHeight};function Kt(e,t){let n=t=="bottom"?e.orientation():M(e.orientation()),r=e.game.players[n],i=[r.title?S("span.lpv__player__title",r.title):void 0,S("span.lpv__player__name",r.name),r.rating?S("span.lpv__player__rating",["(",r.rating,")"]):void 0];return S(`div.lpv__player.lpv__player--${t}`,[r.isLichessUser&&r.name?S("a.lpv__player__person.ulpt.user-link",{attrs:{href:`${e.opts.lichess}/@/${r.name}`,"aria-label":e.translate("aria.viewProfileOnLichess",r.name)}},i):S("span.lpv__player__person",i),e.opts.showClocks?Ws(e,n):void 0])}var Ws=(e,t)=>{let n=e.curData(),r=n.clocks&&n.clocks[t];return typeof r==null?void 0:S("div.lpv__player__clock",{class:{active:t==n.turn},attrs:{role:"timer","aria-label":Je(r).join("")}},Je(r))};var Ni=e=>{let t=e.flipped;return S("div.lpv__sr-only",{attrs:{role:"grid","aria-label":e.translate("aria.accessibleChessboard"),"aria-hidden":"false"}},Us(e,t))},Us=(e,t)=>{let n=e.ground?.state.pieces||Le(e.curData().fen),r=t?Ce:wt,i=t?[...le].reverse():le;return r.map(o=>S("div",{attrs:{role:"row"}},i.map(s=>{let a=`${s}${o}`,l=n.get(a);return js(e.translate,s,o,l)})))},js=(e,t,n,r)=>{let i=wi(e,t,n,r);return S("span",{attrs:{role:"gridcell","aria-label":i}},i)};function $t(e){let t=e.opts,n=`lpv.lpv--moves-${t.showMoves}.lpv--controls-${t.showControls}${t.classes?"."+t.classes.replace(" ","."):""}`,r=t.showPlayers=="auto"?e.game.hasPlayerName():t.showPlayers;return S(`div.${n}`,{class:{"lpv--menu":e.pane!="board","lpv--players":r},attrs:{role:"region",tabindex:0,"aria-label":Mi(e)},hook:Ie(i=>{e.setGround(li(i.querySelector(".cg-wrap"),Qs(e,i))),t.keyboardToMove&&i.addEventListener("keydown",xi(e))})},[S("div.lpv__sr-only",{attrs:{"aria-live":"polite","aria-atomic":"true"}},Pi(e)),Ni(e),r?Kt(e,"top"):void 0,Ys(e),r?Kt(e,"bottom"):void 0,t.showControls?Ci(e):void 0,t.showMoves?Ai(e):void 0,e.pane=="menu"?Si(e):e.pane=="pgn"?Zs(e):void 0])}var Ys=e=>S("div.lpv__board",{attrs:et,hook:Ie(t=>{t.addEventListener("click",e.focus),e.opts.scrollToMove&&!("ontouchstart"in window)&&t.addEventListener("wheel",vi((n,r)=>{n.preventDefault(),n.deltaY>0&&r?e.goTo("next",!1):n.deltaY<0&&r&&e.goTo("prev",!1)}))})},S("div.cg-wrap")),Zs=e=>{let t=new Blob([e.opts.pgn],{type:"text/plain"});return S("div.lpv__pgn.lpv__pane",[S("a.lpv__pgn__download.lpv__fbt",{attrs:{href:window.URL.createObjectURL(t),download:e.opts.menu.getPgn.fileName||`${e.game.title()}.pgn`}},e.translate("download")),S("textarea.lpv__pgn__text",e.opts.pgn)])},Qs=(e,t)=>({viewOnly:!e.opts.drawArrows,addDimensionsCssVarsTo:t,drawable:{enabled:e.opts.drawArrows,visible:!0},disableContextMenu:e.opts.drawArrows,...e.opts.chessground||{},movable:{free:!1},draggable:{enabled:!1},selectable:{enabled:!1},...e.cgState()});var Xs={pgn:"*",fen:void 0,showPlayers:"auto",showClocks:!0,showMoves:"auto",showControls:!0,scrollToMove:!0,keyboardToMove:!0,orientation:void 0,initialPly:0,chessground:{},drawArrows:!0,menu:{getPgn:{enabled:!0,fileName:void 0},practiceWithComputer:{enabled:!0},analysisBoard:{enabled:!0}},lichess:"https://lichess.org",classes:void 0};function Ri(e,t){let n={...Xs};return Oi(n,t),n.fen&&(n.pgn=`[FEN "${n.fen}"]
|
|
4
|
-
${
|
|
1
|
+
var _e=["a","b","c","d","e","f","g","h"],lt=["1","2","3","4","5","6","7","8"];var V=["white","black"],W=["pawn","knight","bishop","rook","queen","king"],tn=["a","h"],se=e=>"role"in e;var b=e=>e!==void 0,M=e=>e==="white"?"black":"white",J=e=>e>>3,B=e=>e&7,ut=(e,t)=>0<=e&&e<8&&0<=t&&t<8?e+8*t:void 0,ae=e=>{switch(e){case"pawn":return"p";case"knight":return"n";case"bishop":return"b";case"rook":return"r";case"queen":return"q";case"king":return"k"}};function qe(e){switch(e.toLowerCase()){case"p":return"pawn";case"n":return"knight";case"b":return"bishop";case"r":return"rook";case"q":return"queen";case"k":return"king";default:return}}function de(e){if(e.length===2)return ut(e.charCodeAt(0)-97,e.charCodeAt(1)-49)}var U=e=>_e[B(e)]+lt[J(e)];var Zt=e=>se(e)?`${ae(e.role).toUpperCase()}@${U(e.to)}`:U(e.from)+U(e.to)+(e.promotion?ae(e.promotion):""),Ve=(e,t)=>e==="white"?t==="a"?2:6:t==="a"?58:62,ht=(e,t)=>e==="white"?t==="a"?3:5:t==="a"?59:61;var rn=e=>(e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),Math.imul(e+(e>>>4)&252645135,16843009)>>24),Qt=e=>(e=e>>>8&16711935|(e&16711935)<<8,e>>>16&65535|(e&65535)<<16),nn=e=>(e=e>>>1&1431655765|(e&1431655765)<<1,e=e>>>2&858993459|(e&858993459)<<2,e=e>>>4&252645135|(e&252645135)<<4,Qt(e)),u=class e{constructor(t,r){this.lo=t|0,this.hi=r|0}static fromSquare(t){return t>=32?new e(0,1<<t-32):new e(1<<t,0)}static fromRank(t){return new e(255,0).shl64(8*t)}static fromFile(t){return new e(16843009<<t,16843009<<t)}static empty(){return new e(0,0)}static full(){return new e(4294967295,4294967295)}static corners(){return new e(129,2164260864)}static center(){return new e(402653184,24)}static backranks(){return new e(255,4278190080)}static backrank(t){return t==="white"?new e(255,0):new e(0,4278190080)}static lightSquares(){return new e(1437226410,1437226410)}static darkSquares(){return new e(2857740885,2857740885)}complement(){return new e(~this.lo,~this.hi)}xor(t){return new e(this.lo^t.lo,this.hi^t.hi)}union(t){return new e(this.lo|t.lo,this.hi|t.hi)}intersect(t){return new e(this.lo&t.lo,this.hi&t.hi)}diff(t){return new e(this.lo&~t.lo,this.hi&~t.hi)}intersects(t){return this.intersect(t).nonEmpty()}isDisjoint(t){return this.intersect(t).isEmpty()}supersetOf(t){return t.diff(this).isEmpty()}subsetOf(t){return this.diff(t).isEmpty()}shr64(t){return t>=64?e.empty():t>=32?new e(this.hi>>>t-32,0):t>0?new e(this.lo>>>t^this.hi<<32-t,this.hi>>>t):this}shl64(t){return t>=64?e.empty():t>=32?new e(0,this.lo<<t-32):t>0?new e(this.lo<<t,this.hi<<t^this.lo>>>32-t):this}bswap64(){return new e(Qt(this.hi),Qt(this.lo))}rbit64(){return new e(nn(this.hi),nn(this.lo))}minus64(t){let r=this.lo-t.lo,n=(r&t.lo&1)+(t.lo>>>1)+(r>>>1)>>>31;return new e(r,this.hi-(t.hi+n))}equals(t){return this.lo===t.lo&&this.hi===t.hi}size(){return rn(this.lo)+rn(this.hi)}isEmpty(){return this.lo===0&&this.hi===0}nonEmpty(){return this.lo!==0||this.hi!==0}has(t){return(t>=32?this.hi&1<<t-32:this.lo&1<<t)!==0}set(t,r){return r?this.with(t):this.without(t)}with(t){return t>=32?new e(this.lo,this.hi|1<<t-32):new e(this.lo|1<<t,this.hi)}without(t){return t>=32?new e(this.lo,this.hi&~(1<<t-32)):new e(this.lo&~(1<<t),this.hi)}toggle(t){return t>=32?new e(this.lo,this.hi^1<<t-32):new e(this.lo^1<<t,this.hi)}last(){if(this.hi!==0)return 63-Math.clz32(this.hi);if(this.lo!==0)return 31-Math.clz32(this.lo)}first(){if(this.lo!==0)return 31-Math.clz32(this.lo&-this.lo);if(this.hi!==0)return 63-Math.clz32(this.hi&-this.hi)}withoutFirst(){return this.lo!==0?new e(this.lo&this.lo-1,this.hi):new e(0,this.hi&this.hi-1)}moreThanOne(){return this.hi!==0&&this.lo!==0||(this.lo&this.lo-1)!==0||(this.hi&this.hi-1)!==0}singleSquare(){return this.moreThanOne()?void 0:this.last()}*[Symbol.iterator](){let t=this.lo,r=this.hi;for(;t!==0;){let n=31-Math.clz32(t&-t);t^=1<<n,yield n}for(;r!==0;){let n=31-Math.clz32(r&-r);r^=1<<n,yield 32+n}}*reversed(){let t=this.lo,r=this.hi;for(;r!==0;){let n=31-Math.clz32(r);r^=1<<n,yield 32+n}for(;t!==0;){let n=31-Math.clz32(t);t^=1<<n,yield n}}};var dt=(e,t)=>{let r=u.empty();for(let n of t){let i=e+n;0<=i&&i<64&&Math.abs(B(e)-B(i))<=2&&(r=r.with(i))}return r},we=e=>{let t=[];for(let r=0;r<64;r++)t[r]=e(r);return t},eo=we(e=>dt(e,[-9,-8,-7,-1,1,7,8,9])),to=we(e=>dt(e,[-17,-15,-10,-6,6,10,15,17])),ro={white:we(e=>dt(e,[7,9])),black:we(e=>dt(e,[-7,-9]))},ce=e=>eo[e],Be=e=>to[e],ve=(e,t)=>ro[e][t],Xt=we(e=>u.fromFile(B(e)).without(e)),Jt=we(e=>u.fromRank(J(e)).without(e)),er=we(e=>{let t=new u(134480385,2151686160),r=8*(J(e)-B(e));return(r>=0?t.shl64(r):t.shr64(-r)).without(e)}),tr=we(e=>{let t=new u(270549120,16909320),r=8*(J(e)+B(e)-7);return(r>=0?t.shl64(r):t.shr64(-r)).without(e)}),rr=(e,t,r)=>{let n=r.intersect(t),i=n.bswap64();return n=n.minus64(e),i=i.minus64(e.bswap64()),n.xor(i.bswap64()).intersect(t)},no=(e,t)=>rr(u.fromSquare(e),Xt[e],t),io=(e,t)=>{let r=Jt[e],n=t.intersect(r),i=n.rbit64();return n=n.minus64(u.fromSquare(e)),i=i.minus64(u.fromSquare(63-e)),n.xor(i.rbit64()).intersect(r)},ye=(e,t)=>{let r=u.fromSquare(e);return rr(r,er[e],t).xor(rr(r,tr[e],t))},xe=(e,t)=>no(e,t).xor(io(e,t)),He=(e,t)=>ye(e,t).xor(xe(e,t)),pt=(e,t,r)=>{switch(e.role){case"pawn":return ve(e.color,t);case"knight":return Be(t);case"bishop":return ye(t,r);case"rook":return xe(t,r);case"queen":return He(t,r);case"king":return ce(t)}},nr=(e,t)=>{let r=u.fromSquare(t);return Jt[e].intersects(r)?Jt[e].with(e):tr[e].intersects(r)?tr[e].with(e):er[e].intersects(r)?er[e].with(e):Xt[e].intersects(r)?Xt[e].with(e):u.empty()},Ce=(e,t)=>nr(e,t).intersect(u.full().shl64(e).xor(u.full().shl64(t))).withoutFirst();var pe=class e{constructor(){}static default(){let t=new e;return t.reset(),t}reset(){this.occupied=new u(65535,4294901760),this.promoted=u.empty(),this.white=new u(65535,0),this.black=new u(0,4294901760),this.pawn=new u(65280,16711680),this.knight=new u(66,1107296256),this.bishop=new u(36,603979776),this.rook=new u(129,2164260864),this.queen=new u(8,134217728),this.king=new u(16,268435456)}static empty(){let t=new e;return t.clear(),t}clear(){this.occupied=u.empty(),this.promoted=u.empty();for(let t of V)this[t]=u.empty();for(let t of W)this[t]=u.empty()}clone(){let t=new e;t.occupied=this.occupied,t.promoted=this.promoted;for(let r of V)t[r]=this[r];for(let r of W)t[r]=this[r];return t}getColor(t){if(this.white.has(t))return"white";if(this.black.has(t))return"black"}getRole(t){for(let r of W)if(this[r].has(t))return r}get(t){let r=this.getColor(t);if(!r)return;let n=this.getRole(t),i=this.promoted.has(t);return{color:r,role:n,promoted:i}}take(t){let r=this.get(t);return r&&(this.occupied=this.occupied.without(t),this[r.color]=this[r.color].without(t),this[r.role]=this[r.role].without(t),r.promoted&&(this.promoted=this.promoted.without(t))),r}set(t,r){let n=this.take(t);return this.occupied=this.occupied.with(t),this[r.color]=this[r.color].with(t),this[r.role]=this[r.role].with(t),r.promoted&&(this.promoted=this.promoted.with(t)),n}has(t){return this.occupied.has(t)}*[Symbol.iterator](){for(let t of this.occupied)yield[t,this.get(t)]}pieces(t,r){return this[t].intersect(this[r])}rooksAndQueens(){return this.rook.union(this.queen)}bishopsAndQueens(){return this.bishop.union(this.queen)}steppers(){return this.knight.union(this.pawn).union(this.king)}sliders(){return this.bishop.union(this.rook).union(this.queen)}kingOf(t){return this.pieces(t,"king").singleSquare()}};var fe=class e{constructor(){}static empty(){let t=new e;for(let r of W)t[r]=0;return t}static fromBoard(t,r){let n=new e;for(let i of W)n[i]=t.pieces(r,i).size();return n}clone(){let t=new e;for(let r of W)t[r]=this[r];return t}equals(t){return W.every(r=>this[r]===t[r])}add(t){let r=new e;for(let n of W)r[n]=this[n]+t[n];return r}subtract(t){let r=new e;for(let n of W)r[n]=this[n]-t[n];return r}nonEmpty(){return W.some(t=>this[t]>0)}isEmpty(){return!this.nonEmpty()}hasPawns(){return this.pawn>0}hasNonPawns(){return this.knight>0||this.bishop>0||this.rook>0||this.queen>0||this.king>0}size(){return this.pawn+this.knight+this.bishop+this.rook+this.queen+this.king}},Ne=class e{constructor(t,r){this.white=t,this.black=r}static empty(){return new e(fe.empty(),fe.empty())}static fromBoard(t){return new e(fe.fromBoard(t,"white"),fe.fromBoard(t,"black"))}clone(){return new e(this.white.clone(),this.black.clone())}equals(t){return this.white.equals(t.white)&&this.black.equals(t.black)}add(t){return new e(this.white.add(t.white),this.black.add(t.black))}subtract(t){return new e(this.white.subtract(t.white),this.black.subtract(t.black))}count(t){return this.white[t]+this.black[t]}size(){return this.white.size()+this.black.size()}isEmpty(){return this.white.isEmpty()&&this.black.isEmpty()}nonEmpty(){return!this.isEmpty()}hasPawns(){return this.white.hasPawns()||this.black.hasPawns()}hasNonPawns(){return this.white.hasNonPawns()||this.black.hasNonPawns()}},Se=class e{constructor(t,r){this.white=t,this.black=r}static default(){return new e(3,3)}clone(){return new e(this.white,this.black)}equals(t){return this.white===t.white&&this.black===t.black}};var ft=class{unwrap(t,r){let n=this._chain(i=>k.ok(t?t(i):i),i=>r?k.ok(r(i)):k.err(i));if(n.isErr)throw n.error;return n.value}map(t,r){return this._chain(n=>k.ok(t(n)),n=>k.err(r?r(n):n))}chain(t,r){return this._chain(t,r??(n=>k.err(n)))}},ir=class extends ft{constructor(t){super(),this.value=t,this.isOk=!0,this.isErr=!1}_chain(t,r){return t(this.value)}},or=class extends ft{constructor(t){super(),this.error=t,this.isOk=!1,this.isErr=!0}_chain(t,r){return r(this.error)}},k;(function(e){function t(i){return new ir(i)}e.ok=t;function r(i){return new or(i||new Error)}e.err=r;function n(i){if(Array.isArray(i)){let a=[];for(let l=0;l<i.length;l++){let c=i[l];if(c.isErr)return c;a.push(c.value)}return e.ok(a)}let o={},s=Object.keys(i);for(let a=0;a<s.length;a++){let l=i[s[a]];if(l.isErr)return l;o[s[a]]=l.value}return e.ok(o)}e.all=n})(k||(k={}));var O;(function(e){e.Empty="ERR_EMPTY",e.OppositeCheck="ERR_OPPOSITE_CHECK",e.PawnsOnBackrank="ERR_PAWNS_ON_BACKRANK",e.Kings="ERR_KINGS",e.Variant="ERR_VARIANT"})(O||(O={}));var D=class extends Error{},oo=(e,t,r,n)=>r[t].intersect(xe(e,n).intersect(r.rooksAndQueens()).union(ye(e,n).intersect(r.bishopsAndQueens())).union(Be(e).intersect(r.knight)).union(ce(e).intersect(r.king)).union(ve(M(t),e).intersect(r.pawn))),le=class e{constructor(){}static default(){let t=new e;return t.castlingRights=u.corners(),t.rook={white:{a:0,h:7},black:{a:56,h:63}},t.path={white:{a:new u(14,0),h:new u(96,0)},black:{a:new u(0,234881024),h:new u(0,1610612736)}},t}static empty(){let t=new e;return t.castlingRights=u.empty(),t.rook={white:{a:void 0,h:void 0},black:{a:void 0,h:void 0}},t.path={white:{a:u.empty(),h:u.empty()},black:{a:u.empty(),h:u.empty()}},t}clone(){let t=new e;return t.castlingRights=this.castlingRights,t.rook={white:{a:this.rook.white.a,h:this.rook.white.h},black:{a:this.rook.black.a,h:this.rook.black.h}},t.path={white:{a:this.path.white.a,h:this.path.white.h},black:{a:this.path.black.a,h:this.path.black.h}},t}add(t,r,n,i){let o=Ve(t,r),s=ht(t,r);this.castlingRights=this.castlingRights.with(i),this.rook[t][r]=i,this.path[t][r]=Ce(i,s).with(s).union(Ce(n,o).with(o)).without(n).without(i)}static fromSetup(t){let r=e.empty(),n=t.castlingRights.intersect(t.board.rook);for(let i of V){let o=u.backrank(i),s=t.board.kingOf(i);if(!b(s)||!o.has(s))continue;let a=n.intersect(t.board[i]).intersect(o),l=a.first();b(l)&&l<s&&r.add(i,"a",s,l);let c=a.last();b(c)&&s<c&&r.add(i,"h",s,c)}return r}discardRook(t){if(this.castlingRights.has(t)){this.castlingRights=this.castlingRights.without(t);for(let r of V)for(let n of tn)this.rook[r][n]===t&&(this.rook[r][n]=void 0)}}discardColor(t){this.castlingRights=this.castlingRights.diff(u.backrank(t)),this.rook[t].a=void 0,this.rook[t].h=void 0}},ee=class{constructor(t){this.rules=t}reset(){this.board=pe.default(),this.pockets=void 0,this.turn="white",this.castles=le.default(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){this.board=t.board.clone(),this.board.promoted=u.empty(),this.pockets=void 0,this.turn=t.turn,this.castles=le.fromSetup(t),this.epSquare=so(this,t.epSquare),this.remainingChecks=void 0,this.halfmoves=t.halfmoves,this.fullmoves=t.fullmoves}kingAttackers(t,r,n){return oo(t,r,this.board,n)}playCaptureAt(t,r){this.halfmoves=0,r.role==="rook"&&this.castles.discardRook(t),this.pockets&&this.pockets[M(r.color)][r.promoted?"pawn":r.role]++}ctx(){let t=this.isVariantEnd(),r=this.board.kingOf(this.turn);if(!b(r))return{king:r,blockers:u.empty(),checkers:u.empty(),variantEnd:t,mustCapture:!1};let n=xe(r,u.empty()).intersect(this.board.rooksAndQueens()).union(ye(r,u.empty()).intersect(this.board.bishopsAndQueens())).intersect(this.board[M(this.turn)]),i=u.empty();for(let s of n){let a=Ce(r,s).intersect(this.board.occupied);a.moreThanOne()||(i=i.union(a))}let o=this.kingAttackers(r,M(this.turn),this.board.occupied);return{king:r,blockers:i,checkers:o,variantEnd:t,mustCapture:!1}}clone(){var t,r;let n=new this.constructor;return n.board=this.board.clone(),n.pockets=(t=this.pockets)===null||t===void 0?void 0:t.clone(),n.turn=this.turn,n.castles=this.castles.clone(),n.epSquare=this.epSquare,n.remainingChecks=(r=this.remainingChecks)===null||r===void 0?void 0:r.clone(),n.halfmoves=this.halfmoves,n.fullmoves=this.fullmoves,n}validate(){if(this.board.occupied.isEmpty())return k.err(new D(O.Empty));if(this.board.king.size()!==2)return k.err(new D(O.Kings));if(!b(this.board.kingOf(this.turn)))return k.err(new D(O.Kings));let t=this.board.kingOf(M(this.turn));return b(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?k.err(new D(O.OppositeCheck)):u.backranks().intersects(this.board.pawn)?k.err(new D(O.PawnsOnBackrank)):k.ok(void 0):k.err(new D(O.Kings))}dropDests(t){return u.empty()}dests(t,r){if(r=r||this.ctx(),r.variantEnd)return u.empty();let n=this.board.get(t);if(!n||n.color!==this.turn)return u.empty();let i,o;if(n.role==="pawn"){i=ve(this.turn,t).intersect(this.board[M(this.turn)]);let s=this.turn==="white"?8:-8,a=t+s;if(0<=a&&a<64&&!this.board.occupied.has(a)){i=i.with(a);let l=this.turn==="white"?t<16:t>=48,c=a+s;l&&!this.board.occupied.has(c)&&(i=i.with(c))}b(this.epSquare)&&co(this,t,r)&&(o=u.fromSquare(this.epSquare))}else n.role==="bishop"?i=ye(t,this.board.occupied):n.role==="knight"?i=Be(t):n.role==="rook"?i=xe(t,this.board.occupied):n.role==="queen"?i=He(t,this.board.occupied):i=ce(t);if(i=i.diff(this.board[this.turn]),b(r.king)){if(n.role==="king"){let s=this.board.occupied.without(t);for(let a of i)this.kingAttackers(a,M(this.turn),s).nonEmpty()&&(i=i.without(a));return i.union(mt(this,"a",r)).union(mt(this,"h",r))}if(r.checkers.nonEmpty()){let s=r.checkers.singleSquare();if(!b(s))return u.empty();i=i.intersect(Ce(s,r.king).with(s))}r.blockers.has(t)&&(i=i.intersect(nr(t,r.king)))}return o&&(i=i.union(o)),i}isVariantEnd(){return!1}variantOutcome(t){}hasInsufficientMaterial(t){return this.board[t].intersect(this.board.pawn.union(this.board.rooksAndQueens())).nonEmpty()?!1:this.board[t].intersects(this.board.knight)?this.board[t].size()<=2&&this.board[M(t)].diff(this.board.king).diff(this.board.queen).isEmpty():this.board[t].intersects(this.board.bishop)?(!this.board.bishop.intersects(u.darkSquares())||!this.board.bishop.intersects(u.lightSquares()))&&this.board.pawn.isEmpty()&&this.board.knight.isEmpty():!0}toSetup(){var t,r;return{board:this.board.clone(),pockets:(t=this.pockets)===null||t===void 0?void 0:t.clone(),turn:this.turn,castlingRights:this.castles.castlingRights,epSquare:ao(this),remainingChecks:(r=this.remainingChecks)===null||r===void 0?void 0:r.clone(),halfmoves:Math.min(this.halfmoves,150),fullmoves:Math.min(Math.max(this.fullmoves,1),9999)}}isInsufficientMaterial(){return V.every(t=>this.hasInsufficientMaterial(t))}hasDests(t){t=t||this.ctx();for(let r of this.board[this.turn])if(this.dests(r,t).nonEmpty())return!0;return this.dropDests(t).nonEmpty()}isLegal(t,r){if(se(t))return!this.pockets||this.pockets[this.turn][t.role]<=0||t.role==="pawn"&&u.backranks().has(t.to)?!1:this.dropDests(r).has(t.to);{if(t.promotion==="pawn"||t.promotion==="king"&&this.rules!=="antichess"||!!t.promotion!==(this.board.pawn.has(t.from)&&u.backranks().has(t.to)))return!1;let n=this.dests(t.from,r);return n.has(t.to)||n.has(on(this,t).to)}}isCheck(){let t=this.board.kingOf(this.turn);return b(t)&&this.kingAttackers(t,M(this.turn),this.board.occupied).nonEmpty()}isEnd(t){return(t?t.variantEnd:this.isVariantEnd())?!0:this.isInsufficientMaterial()||!this.hasDests(t)}isCheckmate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.nonEmpty()&&!this.hasDests(t)}isStalemate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.isEmpty()&&!this.hasDests(t)}outcome(t){let r=this.variantOutcome(t);return r||(t=t||this.ctx(),this.isCheckmate(t)?{winner:M(this.turn)}:this.isInsufficientMaterial()||this.isStalemate(t)?{winner:void 0}:void 0)}allDests(t){t=t||this.ctx();let r=new Map;if(t.variantEnd)return r;for(let n of this.board[this.turn])r.set(n,this.dests(n,t));return r}play(t){let r=this.turn,n=this.epSquare,i=sr(this,t);if(this.epSquare=void 0,this.halfmoves+=1,r==="black"&&(this.fullmoves+=1),this.turn=M(r),se(t))this.board.set(t.to,{role:t.role,color:r}),this.pockets&&this.pockets[r][t.role]--,t.role==="pawn"&&(this.halfmoves=0);else{let o=this.board.take(t.from);if(!o)return;let s;if(o.role==="pawn"){this.halfmoves=0,t.to===n&&(s=this.board.take(t.to+(r==="white"?-8:8)));let a=t.from-t.to;Math.abs(a)===16&&8<=t.from&&t.from<=55&&(this.epSquare=t.from+t.to>>1),t.promotion&&(o.role=t.promotion,o.promoted=!!this.pockets)}else if(o.role==="rook")this.castles.discardRook(t.from);else if(o.role==="king"){if(i){let a=this.castles.rook[r][i];if(b(a)){let l=this.board.take(a);this.board.set(Ve(r,i),o),l&&this.board.set(ht(r,i),l)}}this.castles.discardColor(r)}if(!i){let a=this.board.set(t.to,o)||s;a&&this.playCaptureAt(t.to,a)}}this.remainingChecks&&this.isCheck()&&(this.remainingChecks[r]=Math.max(this.remainingChecks[r]-1,0))}},Ge=class extends ee{constructor(){super("chess")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}},so=(e,t)=>{if(!b(t))return;let r=e.turn==="white"?5:2,n=e.turn==="white"?8:-8;if(J(t)!==r||e.board.occupied.has(t+n))return;let i=t-n;if(!(!e.board.pawn.has(i)||!e.board[M(e.turn)].has(i)))return t},ao=e=>{if(!b(e.epSquare))return;let t=e.ctx(),n=e.board.pieces(e.turn,"pawn").intersect(ve(M(e.turn),e.epSquare));for(let i of n)if(e.dests(i,t).has(e.epSquare))return e.epSquare},co=(e,t,r)=>{if(!b(e.epSquare)||!ve(e.turn,t).has(e.epSquare))return!1;if(!b(r.king))return!0;let n=e.turn==="white"?8:-8,i=e.epSquare-n;return e.kingAttackers(r.king,M(e.turn),e.board.occupied.toggle(t).toggle(i).with(e.epSquare)).without(i).isEmpty()},mt=(e,t,r)=>{if(!b(r.king)||r.checkers.nonEmpty())return u.empty();let n=e.castles.rook[e.turn][t];if(!b(n))return u.empty();if(e.castles.path[e.turn][t].intersects(e.board.occupied))return u.empty();let i=Ve(e.turn,t),o=Ce(r.king,i),s=e.board.occupied.without(r.king);for(let c of o)if(e.kingAttackers(c,M(e.turn),s).nonEmpty())return u.empty();let a=ht(e.turn,t),l=e.board.occupied.toggle(r.king).toggle(n).toggle(a);return e.kingAttackers(i,M(e.turn),l).nonEmpty()?u.empty():u.fromSquare(n)},gt=(e,t,r)=>{if(r.variantEnd)return u.empty();let n=e.board.get(t);if(!n||n.color!==e.turn)return u.empty();let i=pt(n,t,e.board.occupied);if(n.role==="pawn"){let o=e.board[M(e.turn)];b(e.epSquare)&&(o=o.with(e.epSquare)),i=i.intersect(o);let s=e.turn==="white"?8:-8,a=t+s;if(0<=a&&a<64&&!e.board.occupied.has(a)){i=i.with(a);let l=e.turn==="white"?t<16:t>=48,c=a+s;l&&!e.board.occupied.has(c)&&(i=i.with(c))}return i}else i=i.diff(e.board[e.turn]);return t===r.king?i.union(mt(e,"a",r)).union(mt(e,"h",r)):i};var sr=(e,t)=>{if(se(t))return;let r=t.to-t.from;if(!(Math.abs(r)!==2&&!e.board[e.turn].has(t.to))&&e.board.king.has(t.from))return r>0?"h":"a"},on=(e,t)=>{let r=sr(e,t);if(!r)return t;let n=e.castles.rook[e.turn][r];return{from:t.from,to:b(n)?n:t.to}};var sn=e=>se(e)?String.fromCharCode(35+e.to,139+["queen","rook","bishop","knight","pawn"].indexOf(e.role)):String.fromCharCode(35+e.from,e.promotion?99+8*["queen","rook","bishop","knight","king"].indexOf(e.promotion)+B(e.to):35+e.to);var uo="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",ho=uo+" w KQkq -",ic=ho+" 0 1",po="8/8/8/8/8/8/8/8",fo=po+" w - -",oc=fo+" 0 1",K;(function(e){e.Fen="ERR_FEN",e.Board="ERR_BOARD",e.Pockets="ERR_POCKETS",e.Turn="ERR_TURN",e.Castling="ERR_CASTLING",e.EpSquare="ERR_EP_SQUARE",e.RemainingChecks="ERR_REMAINING_CHECKS",e.Halfmoves="ERR_HALFMOVES",e.Fullmoves="ERR_FULLMOVES"})(K||(K={}));var F=class extends Error{},mo=(e,t,r)=>{let n=e.indexOf(t);for(;r-- >0&&n!==-1;)n=e.indexOf(t,n+t.length);return n},Le=e=>/^\d{1,4}$/.test(e)?parseInt(e,10):void 0,un=e=>{let t=qe(e);return t&&{role:t,color:e.toLowerCase()===e?"black":"white"}},ar=e=>{let t=pe.empty(),r=7,n=0;for(let i=0;i<e.length;i++){let o=e[i];if(o==="/"&&n===8)n=0,r--;else{let s=parseInt(o,10);if(s>0)n+=s;else{if(n>=8||r<0)return k.err(new F(K.Board));let a=n+r*8,l=un(o);if(!l)return k.err(new F(K.Board));e[i+1]==="~"&&(l.promoted=!0,i++),t.set(a,l),n++}}}return r!==0||n!==8?k.err(new F(K.Board)):k.ok(t)},an=e=>{if(e.length>64)return k.err(new F(K.Pockets));let t=Ne.empty();for(let r of e){let n=un(r);if(!n)return k.err(new F(K.Pockets));t[n.color][n.role]++}return k.ok(t)},go=(e,t)=>{let r=u.empty();if(t==="-")return k.ok(r);for(let n of t){let i=n.toLowerCase(),o=n===i?"black":"white",s=o==="white"?0:7;if("a"<=i&&i<="h")r=r.with(ut(i.charCodeAt(0)-97,s));else if(i==="k"||i==="q"){let a=e[o].intersect(u.backrank(o)).intersect(e.rook.union(e.king)),l=i==="k"?a.last():a.first();r=r.with(b(l)&&e.rook.has(l)?l:ut(i==="k"?7:0,s))}else return k.err(new F(K.Castling))}return V.some(n=>u.backrank(n).intersect(r).size()>2)?k.err(new F(K.Castling)):k.ok(r)},cn=e=>{let t=e.split("+");if(t.length===3&&t[0]===""){let r=Le(t[1]),n=Le(t[2]);return!b(r)||r>3||!b(n)||n>3?k.err(new F(K.RemainingChecks)):k.ok(new Se(3-r,3-n))}else if(t.length===2){let r=Le(t[0]),n=Le(t[1]);return!b(r)||r>3||!b(n)||n>3?k.err(new F(K.RemainingChecks)):k.ok(new Se(r,n))}else return k.err(new F(K.RemainingChecks))},hn=e=>{let t=e.split(/[\s_]+/),r=t.shift(),n,i=k.ok(void 0);if(r.endsWith("]")){let a=r.indexOf("[");if(a===-1)return k.err(new F(K.Fen));n=ar(r.slice(0,a)),i=an(r.slice(a+1,-1))}else{let a=mo(r,"/",7);a===-1?n=ar(r):(n=ar(r.slice(0,a)),i=an(r.slice(a+1)))}let o,s=t.shift();if(!b(s)||s==="w")o="white";else if(s==="b")o="black";else return k.err(new F(K.Turn));return n.chain(a=>{let l=t.shift(),c=b(l)?go(a,l):k.ok(u.empty()),h=t.shift(),f;if(b(h)&&h!=="-"&&(f=de(h),!b(f)))return k.err(new F(K.EpSquare));let g=t.shift(),m;b(g)&&g.includes("+")&&(m=cn(g),g=t.shift());let d=b(g)?Le(g):0;if(!b(d))return k.err(new F(K.Halfmoves));let p=t.shift(),v=b(p)?Le(p):1;if(!b(v))return k.err(new F(K.Fullmoves));let w=t.shift(),x=k.ok(void 0);if(b(w)){if(b(m))return k.err(new F(K.RemainingChecks));x=cn(w)}else b(m)&&(x=m);return t.length>0?k.err(new F(K.Fen)):i.chain(A=>c.chain(C=>x.map(P=>({board:a,pockets:A,turn:o,castlingRights:C,remainingChecks:P,epSquare:f,halfmoves:d,fullmoves:Math.max(1,v)}))))})};var ko=e=>{let t=ae(e.role);return e.color==="white"&&(t=t.toUpperCase()),e.promoted&&(t+="~"),t},bo=e=>{let t="",r=0;for(let n=7;n>=0;n--)for(let i=0;i<8;i++){let o=i+n*8,s=e.get(o);s?(r>0&&(t+=r,r=0),t+=ko(s)):r++,i===7&&(r>0&&(t+=r,r=0),n!==0&&(t+="/"))}return t},ln=e=>W.map(t=>ae(t).repeat(e[t])).join(""),wo=e=>ln(e.white).toUpperCase()+ln(e.black),vo=(e,t)=>{let r="";for(let n of V){let i=u.backrank(n),o=e.kingOf(n);b(o)&&!i.has(o)&&(o=void 0);let s=e.pieces(n,"rook").intersect(i);for(let a of t.intersect(i).reversed())if(a===s.first()&&b(o)&&a<o)r+=n==="white"?"Q":"q";else if(a===s.last()&&b(o)&&o<a)r+=n==="white"?"K":"k";else{let l=_e[B(a)];r+=n==="white"?l.toUpperCase():l}}return r||"-"},yo=e=>`${e.white}+${e.black}`,kt=(e,t)=>[bo(e.board)+(e.pockets?`[${wo(e.pockets)}]`:""),e.turn[0],vo(e.board,e.castlingRights),b(e.epSquare)?U(e.epSquare):"-",...e.remainingChecks?[yo(e.remainingChecks)]:[],...t?.epd?[]:[Math.max(0,Math.min(e.halfmoves,9999)),Math.max(1,Math.min(e.fullmoves,9999))]].join(" ");var Co=(e,t)=>{let r="";if(se(t))t.role!=="pawn"&&(r=ae(t.role).toUpperCase()),r+="@"+U(t.to);else{let n=e.board.getRole(t.from);if(!n)return"--";if(n==="king"&&(e.board[e.turn].has(t.to)||Math.abs(t.to-t.from)===2))r=t.to>t.from?"O-O":"O-O-O";else{let i=e.board.occupied.has(t.to)||n==="pawn"&&B(t.from)!==B(t.to);if(n!=="pawn"){r=ae(n).toUpperCase();let o;if(n==="king"?o=ce(t.to).intersect(e.board.king):n==="queen"?o=He(t.to,e.board.occupied).intersect(e.board.queen):n==="rook"?o=xe(t.to,e.board.occupied).intersect(e.board.rook):n==="bishop"?o=ye(t.to,e.board.occupied).intersect(e.board.bishop):o=Be(t.to).intersect(e.board.knight),o=o.intersect(e.board[e.turn]).without(t.from),o.nonEmpty()){let s=e.ctx();for(let a of o)e.dests(a,s).has(t.to)||(o=o.without(a));if(o.nonEmpty()){let a=!1,l=o.intersects(u.fromRank(J(t.from)));o.intersects(u.fromFile(B(t.from)))?a=!0:l=!0,l&&(r+=_e[B(t.from)]),a&&(r+=lt[J(t.from)])}}}else i&&(r=_e[B(t.from)]);i&&(r+="x"),r+=U(t.to),t.promotion&&(r+="="+ae(t.promotion).toUpperCase())}}return r},dn=(e,t)=>{var r;let n=Co(e,t);return e.play(t),!((r=e.outcome())===null||r===void 0)&&r.winner?n+"#":e.isCheck()?n+"+":n};var pn=(e,t)=>{let r=e.ctx(),n=t.match(/^([NBRQK])?([a-h])?([1-8])?[-x]?([a-h][1-8])(?:=?([nbrqkNBRQK]))?[+#]?$/);if(!n){let h;if(t==="O-O"||t==="O-O+"||t==="O-O#"?h="h":(t==="O-O-O"||t==="O-O-O+"||t==="O-O-O#")&&(h="a"),h){let m=e.castles.rook[e.turn][h];return!b(r.king)||!b(m)||!e.dests(r.king,r).has(m)?void 0:{from:r.king,to:m}}let f=t.match(/^([pnbrqkPNBRQK])?@([a-h][1-8])[+#]?$/);if(!f)return;let g={role:f[1]?qe(f[1]):"pawn",to:de(f[2])};return e.isLegal(g,r)?g:void 0}let i=n[1]?qe(n[1]):"pawn",o=de(n[4]),s=n[5]?qe(n[5]):void 0;if(!!s!==(i==="pawn"&&u.backranks().has(o))||s==="king"&&e.rules!=="antichess")return;let a=e.board.pieces(e.turn,i);i==="pawn"&&!n[2]?a=a.intersect(u.fromFile(B(o))):n[2]&&(a=a.intersect(u.fromFile(n[2].charCodeAt(0)-97))),n[3]&&(a=a.intersect(u.fromRank(n[3].charCodeAt(0)-49)));let l=i==="pawn"?u.fromFile(B(o)):u.empty();a=a.intersect(l.union(pt({color:M(e.turn),role:i},o,e.board.occupied)));let c;for(let h of a)if(e.dests(h,r).has(o)){if(b(c))return;c=h}if(b(c))return{from:c,to:o,promotion:s}};var bt=class extends ee{constructor(){super("crazyhouse")}reset(){super.reset(),this.pockets=Ne.empty()}setupUnchecked(t){super.setupUnchecked(t),this.board.promoted=t.board.promoted.intersect(t.board.occupied).diff(t.board.king).diff(t.board.pawn),this.pockets=t.pockets?t.pockets.clone():Ne.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}validate(){return super.validate().chain(t=>{var r,n;return!((r=this.pockets)===null||r===void 0)&&r.count("king")?k.err(new D(O.Kings)):(((n=this.pockets)===null||n===void 0?void 0:n.size())||0)+this.board.occupied.size()>64?k.err(new D(O.Variant)):k.ok(void 0)})}hasInsufficientMaterial(t){return this.pockets?this.board.occupied.size()+this.pockets.size()<=3&&this.board.pawn.isEmpty()&&this.board.promoted.isEmpty()&&this.board.rooksAndQueens().isEmpty()&&this.pockets.count("pawn")<=0&&this.pockets.count("rook")<=0&&this.pockets.count("queen")<=0:super.hasInsufficientMaterial(t)}dropDests(t){var r,n;let i=this.board.occupied.complement().intersect(!((r=this.pockets)===null||r===void 0)&&r[this.turn].hasNonPawns()?u.full():!((n=this.pockets)===null||n===void 0)&&n[this.turn].hasPawns()?u.backranks().complement():u.empty());if(t=t||this.ctx(),b(t.king)&&t.checkers.nonEmpty()){let o=t.checkers.singleSquare();return b(o)?i.intersect(Ce(o,t.king)):u.empty()}else return i}},wt=class extends ee{constructor(){super("atomic")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return k.err(new D(O.Empty));if(this.board.king.size()>2)return k.err(new D(O.Kings));let t=this.board.kingOf(M(this.turn));return b(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?k.err(new D(O.OppositeCheck)):u.backranks().intersects(this.board.pawn)?k.err(new D(O.PawnsOnBackrank)):k.ok(void 0):k.err(new D(O.Kings))}kingAttackers(t,r,n){let i=this.board.pieces(r,"king");return i.isEmpty()||ce(t).intersects(i)?u.empty():super.kingAttackers(t,r,n)}playCaptureAt(t,r){super.playCaptureAt(t,r),this.board.take(t);for(let n of ce(t).intersect(this.board.occupied).diff(this.board.pawn)){let i=this.board.take(n);i?.role==="rook"&&this.castles.discardRook(n),i?.role==="king"&&this.castles.discardColor(i.color)}}hasInsufficientMaterial(t){if(this.board.pieces(M(t),"king").isEmpty())return!1;if(this.board[t].diff(this.board.king).isEmpty())return!0;if(this.board[M(t)].diff(this.board.king).nonEmpty()){if(this.board.occupied.equals(this.board.bishop.union(this.board.king))){if(!this.board.bishop.intersect(this.board.white).intersects(u.darkSquares()))return!this.board.bishop.intersect(this.board.black).intersects(u.lightSquares());if(!this.board.bishop.intersect(this.board.white).intersects(u.lightSquares()))return!this.board.bishop.intersect(this.board.black).intersects(u.darkSquares())}return!1}return this.board.queen.nonEmpty()||this.board.pawn.nonEmpty()?!1:this.board.knight.union(this.board.bishop).union(this.board.rook).size()===1?!0:this.board.occupied.equals(this.board.knight.union(this.board.king))?this.board.knight.size()<=2:!1}dests(t,r){r=r||this.ctx();let n=u.empty();for(let i of gt(this,t,r)){let o=this.clone();o.play({from:t,to:i});let s=o.board.kingOf(this.turn);b(s)&&(!b(o.board.kingOf(o.turn))||o.kingAttackers(s,o.turn,o.board.occupied).isEmpty())&&(n=n.with(i))}return n}isVariantEnd(){return!!this.variantOutcome()}variantOutcome(t){for(let r of V)if(this.board.pieces(r,"king").isEmpty())return{winner:M(r)}}},vt=class extends ee{constructor(){super("antichess")}reset(){super.reset(),this.castles=le.empty()}setupUnchecked(t){super.setupUnchecked(t),this.castles=le.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}validate(){return this.board.occupied.isEmpty()?k.err(new D(O.Empty)):u.backranks().intersects(this.board.pawn)?k.err(new D(O.PawnsOnBackrank)):k.ok(void 0)}kingAttackers(t,r,n){return u.empty()}ctx(){let t=super.ctx();if(b(this.epSquare)&&ve(M(this.turn),this.epSquare).intersects(this.board.pieces(this.turn,"pawn")))return t.mustCapture=!0,t;let r=this.board[M(this.turn)];for(let n of this.board[this.turn])if(gt(this,n,t).intersects(r))return t.mustCapture=!0,t;return t}dests(t,r){r=r||this.ctx();let n=gt(this,t,r),i=this.board[M(this.turn)];return n.intersect(r.mustCapture?b(this.epSquare)&&this.board.getRole(t)==="pawn"?i.with(this.epSquare):i:u.full())}hasInsufficientMaterial(t){if(this.board[t].isEmpty())return!1;if(this.board[M(t)].isEmpty())return!0;if(this.board.occupied.equals(this.board.bishop)){let r=this.board[t].intersects(u.lightSquares()),n=this.board[t].intersects(u.darkSquares()),i=this.board[M(t)].isDisjoint(u.lightSquares()),o=this.board[M(t)].isDisjoint(u.darkSquares());return r&&i||n&&o}return this.board.occupied.equals(this.board.knight)&&this.board.occupied.size()===2?this.board.white.intersects(u.lightSquares())!==this.board.black.intersects(u.darkSquares())!=(this.turn===t):!1}isVariantEnd(){return this.board[this.turn].isEmpty()}variantOutcome(t){if(t=t||this.ctx(),t.variantEnd||this.isStalemate(t))return{winner:this.turn}}},yt=class extends ee{constructor(){super("kingofthehill")}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}hasInsufficientMaterial(t){return!1}isVariantEnd(){return this.board.king.intersects(u.center())}variantOutcome(t){for(let r of V)if(this.board.pieces(r,"king").intersects(u.center()))return{winner:r}}},xt=class extends ee{constructor(){super("3check")}reset(){super.reset(),this.remainingChecks=Se.default()}setupUnchecked(t){var r;super.setupUnchecked(t),this.remainingChecks=((r=t.remainingChecks)===null||r===void 0?void 0:r.clone())||Se.default()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}hasInsufficientMaterial(t){return this.board.pieces(t,"king").equals(this.board[t])}isVariantEnd(){return!!this.remainingChecks&&(this.remainingChecks.white<=0||this.remainingChecks.black<=0)}variantOutcome(t){if(this.remainingChecks){for(let r of V)if(this.remainingChecks[r]<=0)return{winner:r}}}},Po=()=>{let e=pe.empty();return e.occupied=new u(65535,0),e.promoted=u.empty(),e.white=new u(61680,0),e.black=new u(3855,0),e.pawn=u.empty(),e.knight=new u(6168,0),e.bishop=new u(9252,0),e.rook=new u(16962,0),e.queen=new u(129,0),e.king=new u(33024,0),e},Ct=class extends ee{constructor(){super("racingkings")}reset(){this.board=Po(),this.pockets=void 0,this.turn="white",this.castles=le.empty(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){super.setupUnchecked(t),this.castles=le.empty()}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}validate(){return this.isCheck()||this.board.pawn.nonEmpty()?k.err(new D(O.Variant)):super.validate()}dests(t,r){if(r=r||this.ctx(),t===r.king)return super.dests(t,r);let n=u.empty();for(let i of super.dests(t,r)){let o={from:t,to:i},s=this.clone();s.play(o),s.isCheck()||(n=n.with(i))}return n}hasInsufficientMaterial(t){return!1}isVariantEnd(){let t=u.fromRank(7),r=this.board.king.intersect(t);if(r.isEmpty())return!1;if(this.turn==="white"||r.intersects(this.board.black))return!0;let n=this.board.kingOf("black");if(b(n)){let i=this.board.occupied.without(n);for(let o of ce(n).intersect(t).diff(this.board.black))if(this.kingAttackers(o,"white",i).isEmpty())return!1}return!0}variantOutcome(t){if(t?!t.variantEnd:!this.isVariantEnd())return;let r=u.fromRank(7),n=this.board.pieces("black","king").intersects(r),i=this.board.pieces("white","king").intersects(r);return n&&!i?{winner:"black"}:i&&!n?{winner:"white"}:{winner:void 0}}},Mo=()=>{let e=pe.empty();return e.occupied=new u(4294967295,4294901862),e.promoted=u.empty(),e.white=new u(4294967295,102),e.black=new u(0,4294901760),e.pawn=new u(4294967295,16711782),e.knight=new u(0,1107296256),e.bishop=new u(0,603979776),e.rook=new u(0,2164260864),e.queen=new u(0,134217728),e.king=new u(0,268435456),e},St=class extends ee{constructor(){super("horde")}reset(){this.board=Mo(),this.pockets=void 0,this.turn="white",this.castles=le.default(),this.castles.discardColor("white"),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}static default(){let t=new this;return t.reset(),t}static fromSetup(t){let r=new this;return r.setupUnchecked(t),r.validate().map(n=>r)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return k.err(new D(O.Empty));if(this.board.king.size()!==1)return k.err(new D(O.Kings));let t=this.board.kingOf(M(this.turn));if(b(t)&&this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty())return k.err(new D(O.OppositeCheck));for(let r of V){let n=this.board.pieces(r,"king").isEmpty()?u.backrank(M(r)):u.backranks();if(this.board.pieces(r,"pawn").intersects(n))return k.err(new D(O.PawnsOnBackrank))}return k.ok(void 0)}hasInsufficientMaterial(t){if(this.board.pieces(t,"king").nonEmpty())return!1;let r=m=>m==="light"?"dark":"light",n=m=>m==="light"?u.lightSquares():u.darkSquares(),i=m=>{let d=this.board.pieces(m,"bishop");return d.intersects(u.darkSquares())&&d.intersects(u.lightSquares())},o=fe.fromBoard(this.board,t),s=m=>n(m).intersect(this.board.pieces(t,"bishop")).size(),a=s("light")>=1?"light":"dark",l=o.pawn+o.knight+o.rook+o.queen+Math.min(s("dark"),2)+Math.min(s("light"),2),c=fe.fromBoard(this.board,M(t)),h=m=>n(m).intersect(this.board.pieces(M(t),"bishop")).size(),f=c.size(),g=m=>f-m;if(l===0)return!0;if(l>=4||(o.pawn>=1||o.queen>=1)&&l>=2||o.rook>=1&&l>=2&&!(l===2&&o.rook===1&&o.bishop===1&&g(h(a))===1))return!1;if(l===1){if(f===1)return!0;if(o.queen===1)return!(c.pawn>=1||c.rook>=1||h("light")>=2||h("dark")>=2);if(o.pawn===1){let m=this.board.pieces(t,"pawn").last(),d=this.clone();d.board.set(m,{color:t,role:"queen"});let p=this.clone();return p.board.set(m,{color:t,role:"knight"}),d.hasInsufficientMaterial(t)&&p.hasInsufficientMaterial(t)}else{if(o.rook===1)return!(c.pawn>=2||c.rook>=1&&c.pawn>=1||c.rook>=1&&c.knight>=1||c.pawn>=1&&c.knight>=1);if(o.bishop===1)return!(h(r(a))>=2||h(r(a))>=1&&c.pawn>=1||c.pawn>=2);if(o.knight===1)return!(f>=4&&(c.knight>=2||c.pawn>=2||c.rook>=1&&c.knight>=1||c.rook>=1&&c.bishop>=1||c.knight>=1&&c.bishop>=1||c.rook>=1&&c.pawn>=1||c.knight>=1&&c.pawn>=1||c.bishop>=1&&c.pawn>=1||i(M(t))&&c.pawn>=1)&&(h("dark")<2||g(h("dark"))>=3)&&(h("light")<2||g(h("light"))>=3))}}else{if(l===2)return f===1?!0:o.knight===2?c.pawn+c.bishop+c.knight<1:i(t)?!(c.pawn>=1||c.bishop>=1||c.knight>=1&&c.rook+c.queen>=1):o.bishop>=1&&o.knight>=1?!(c.pawn>=1||h(r(a))>=1||g(h(a))>=3):!(c.pawn>=1&&h(r(a))>=1||c.pawn>=1&&c.knight>=1||h(r(a))>=1&&c.knight>=1||h(r(a))>=2||c.knight>=2||c.pawn>=2);if(l===3)return o.knight===2&&o.bishop===1||o.knight===3||i(t)?!1:f===1}return!0}isVariantEnd(){return this.board.white.isEmpty()||this.board.black.isEmpty()}variantOutcome(t){if(this.board.white.isEmpty())return{winner:"black"};if(this.board.black.isEmpty())return{winner:"white"}}},fn=e=>{switch(e){case"chess":return Ge.default();case"antichess":return vt.default();case"atomic":return wt.default();case"horde":return St.default();case"racingkings":return Ct.default();case"kingofthehill":return yt.default();case"3check":return xt.default();case"crazyhouse":return bt.default()}},mn=(e,t)=>{switch(e){case"chess":return Ge.fromSetup(t);case"antichess":return vt.fromSetup(t);case"atomic":return wt.fromSetup(t);case"horde":return St.fromSetup(t);case"racingkings":return Ct.fromSetup(t);case"kingofthehill":return yt.fromSetup(t);case"3check":return xt.fromSetup(t);case"crazyhouse":return bt.fromSetup(t)}};var Ao=(e=dr)=>({headers:e(),moves:new We}),We=class{constructor(){this.children=[]}*mainlineNodes(){let t=this;for(;t.children.length;){let r=t.children[0];yield r,t=r}}*mainline(){for(let t of this.mainlineNodes())yield t.data}end(){let t=this;for(;t.children.length;)t=t.children[0];return t}},Pt=class extends We{constructor(t){super(),this.data=t}};var kn=(e,t,r)=>{let n=new We,i=[{before:e,after:n,ctx:t}],o;for(;o=i.pop();)for(let s=0;s<o.before.children.length;s++){let a=s<o.before.children.length-1?o.ctx.clone():o.ctx,l=o.before.children[s],c=r(a,l.data,s);if(b(c)){let h=new Pt(c);o.after.children.push(h),i.push({before:l,after:h,ctx:a})}}return n};var _o=e=>e?e.winner==="white"?"1-0":e.winner==="black"?"0-1":"1/2-1/2":"*",qo=e=>e==="1-0"||e==="1\u20130"||e==="1\u20140"?{winner:"white"}:e==="0-1"||e==="0\u20131"||e==="0\u20141"?{winner:"black"}:e==="1/2-1/2"||e==="1/2\u20131/2"||e==="1/2\u20141/2"?{winner:void 0}:void 0;var dr=()=>new Map([["Event","?"],["Site","?"],["Date","????.??.??"],["Round","?"],["White","?"],["Black","?"],["Result","*"]]);var gn="\uFEFF",cr=e=>/^\s*$/.test(e),lr=e=>e.startsWith("%"),ur=class extends Error{},hr=class{constructor(t,r=dr,n=1e6){this.emitGame=t,this.initHeaders=r,this.maxBudget=n,this.lineBuf=[],this.resetGame(),this.state=0}resetGame(){this.budget=this.maxBudget,this.found=!1,this.state=1,this.game=Ao(this.initHeaders),this.stack=[{parent:this.game.moves,root:!0}],this.commentBuf=[]}consumeBudget(t){if(this.budget-=t,this.budget<0)throw new ur("ERR_PGN_BUDGET")}parse(t,r){if(!(this.budget<0))try{let n=0;for(;;){let i=t.indexOf(`
|
|
2
|
+
`,n);if(i===-1)break;let o=i>n&&t[i-1]==="\r"?i-1:i;this.consumeBudget(i-n),this.lineBuf.push(t.slice(n,o)),n=i+1,this.handleLine()}this.consumeBudget(t.length-n),this.lineBuf.push(t.slice(n)),r?.stream||(this.handleLine(),this.emit(void 0))}catch(n){this.emit(n)}}handleLine(){let t=!0,r=this.lineBuf.join("");this.lineBuf=[];e:for(;;)switch(this.state){case 0:r.startsWith(gn)&&(r=r.slice(gn.length)),this.state=1;case 1:if(cr(r)||lr(r))return;this.found=!0,this.state=2;case 2:{if(lr(r))return;let n=!0;for(;n;)n=!1,r=r.replace(/^\s*\[([A-Za-z0-9][A-Za-z0-9_+#=:-]*)\s+"((?:[^"\\]|\\"|\\\\)*)"\]/,(i,o,s)=>(this.consumeBudget(200),this.handleHeader(o,s.replace(/\\"/g,'"').replace(/\\\\/g,"\\")),n=!0,t=!1,""));if(cr(r))return;this.state=3}case 3:{if(t){if(lr(r))return;if(cr(r))return this.emit(void 0)}let n=/(?:[NBKRQ]?[a-h]?[1-8]?[-x]?[a-h][1-8](?:=?[nbrqkNBRQK])?|[pnbrqkPNBRQK]?@[a-h][1-8]|[O0o][-–—][O0o](?:[-–—][O0o])?)[+#]?|--|Z0|0000|@@@@|{|;|\$\d{1,4}|[?!]{1,2}|\(|\)|\*|1[-–—]0|0[-–—]1|1\/2[-–—]1\/2/g,i;for(;i=n.exec(r);){let o=this.stack[this.stack.length-1],s=i[0];if(s===";")return;if(s.startsWith("$"))this.handleNag(parseInt(s.slice(1),10));else if(s==="!")this.handleNag(1);else if(s==="?")this.handleNag(2);else if(s==="!!")this.handleNag(3);else if(s==="??")this.handleNag(4);else if(s==="!?")this.handleNag(5);else if(s==="?!")this.handleNag(6);else if(s==="1-0"||s==="1\u20130"||s==="1\u20140"||s==="0-1"||s==="0\u20131"||s==="0\u20141"||s==="1/2-1/2"||s==="1/2\u20131/2"||s==="1/2\u20141/2"||s==="*")this.stack.length===1&&s!=="*"&&this.handleHeader("Result",s);else if(s==="(")this.consumeBudget(100),this.stack.push({parent:o.parent,root:!1});else if(s===")")this.stack.length>1&&this.stack.pop();else if(s==="{"){let a=n.lastIndex,l=r[a]===" "?a+1:a;r=r.slice(l),this.state=4;continue e}else this.consumeBudget(100),s.startsWith("O")||s.startsWith("0")||s.startsWith("o")?s=s.replace(/[0o]/g,"O").replace(/[–—]/g,"-"):(s==="Z0"||s==="0000"||s==="@@@@")&&(s="--"),o.node&&(o.parent=o.node),o.node=new Pt({san:s,startingComments:o.startingComments}),o.startingComments=void 0,o.root=!1,o.parent.children.push(o.node)}return}case 4:{let n=r.indexOf("}");if(n===-1){this.commentBuf.push(r);return}else{let i=n>0&&r[n-1]===" "?n-1:n;this.commentBuf.push(r.slice(0,i)),this.handleComment(),r=r.slice(n),this.state=3,t=!1}}}}handleHeader(t,r){this.game.headers.set(t,t==="Result"?_o(qo(r)):r)}handleNag(t){var r;this.consumeBudget(50);let n=this.stack[this.stack.length-1];n.node&&((r=n.node.data).nags||(r.nags=[]),n.node.data.nags.push(t))}handleComment(){var t,r;this.consumeBudget(100);let n=this.stack[this.stack.length-1],i=this.commentBuf.join(`
|
|
3
|
+
`);this.commentBuf=[],n.node?((t=n.node.data).comments||(t.comments=[]),n.node.data.comments.push(i)):n.root?((r=this.game).comments||(r.comments=[]),this.game.comments.push(i)):(n.startingComments||(n.startingComments=[]),n.startingComments.push(i))}emit(t){if(this.state===4&&this.handleComment(),t)return this.emitGame(this.game,t);this.found&&this.emitGame(this.game,void 0),this.resetGame()}},pr=(e,t=dr)=>{let r=[];return new hr(n=>r.push(n),t,NaN).parse(e),r},No=e=>{switch((e||"chess").toLowerCase()){case"chess":case"chess960":case"chess 960":case"standard":case"from position":case"classical":case"normal":case"fischerandom":case"fischerrandom":case"fischer random":case"wild/0":case"wild/1":case"wild/2":case"wild/3":case"wild/4":case"wild/5":case"wild/6":case"wild/7":case"wild/8":case"wild/8a":return"chess";case"crazyhouse":case"crazy house":case"house":case"zh":return"crazyhouse";case"king of the hill":case"koth":case"kingofthehill":return"kingofthehill";case"three-check":case"three check":case"threecheck":case"three check chess":case"3-check":case"3 check":case"3check":return"3check";case"antichess":case"anti chess":case"anti":return"antichess";case"atomic":case"atom":case"atomic chess":return"atomic";case"horde":case"horde chess":return"horde";case"racing kings":case"racingkings":case"racing":case"race":return"racingkings";default:return}};var bn=e=>{let t=No(e.get("Variant"));if(!t)return k.err(new D(O.Variant));let r=e.get("FEN");return r?hn(r).chain(n=>mn(t,n)):k.ok(fn(t))};function To(e){switch(e){case"G":return"green";case"R":return"red";case"Y":return"yellow";case"B":return"blue";default:return}}var Ro=e=>{let t=To(e.slice(0,1)),r=de(e.slice(1,3)),n=de(e.slice(3,5));if(!(!t||!b(r))){if(e.length===3)return{color:t,from:r,to:r};if(e.length===5&&b(n))return{color:t,from:r,to:n}}};var wn=e=>{let t,r,n,i=[];return{text:e.replace(/\s?\[%(emt|clk)\s(\d{1,5}):(\d{1,2}):(\d{1,2}(?:\.\d{0,3})?)\]\s?/g,(s,a,l,c,h)=>{let f=parseInt(l,10)*3600+parseInt(c,10)*60+parseFloat(h);return a==="emt"?t=f:a==="clk"&&(r=f)," "}).replace(/\s?\[%(?:csl|cal)\s([RGYB][a-h][1-8](?:[a-h][1-8])?(?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)*)\]\s?/g,(s,a)=>{for(let l of a.split(","))i.push(Ro(l));return" "}).replace(/\s?\[%eval\s(?:#([+-]?\d{1,5})|([+-]?(?:\d{1,5}|\d{0,5}\.\d{1,2})))(?:,(\d{1,5}))?\]\s?/g,(s,a,l,c)=>{let h=c&&parseInt(c,10);return n=a?{mate:parseInt(a,10),depth:h}:{pawns:parseFloat(l),depth:h}," "}).trim(),shapes:i,emt:t,clock:r,evaluation:n}};var Do=e=>Lo[e];function fr(e){return(t,...r)=>{let n=e&&e(t)||Do(t);return Bo(n??t,r)}}var Bo=(e,t)=>{let r=e;return t.forEach((n,i)=>{r=r.replace(`%${i+1}$s`,n),r=r.replace("%s",n)}),r},Lo={flipTheBoard:"Flip the board",analysisBoard:"Analysis board",practiceWithComputer:"Practice with computer",getPgn:"Get PGN",download:"Download",viewOnLichess:"View on Lichess",viewOnSite:"View on site",menu:"Menu","aria.first":"Go to first move","aria.prev":"Go to previous move","aria.next":"Go to next move","aria.last":"Go to last move","aria.gameMoves":"Game moves","aria.gameResult":"Game result","aria.variation":"Variation","aria.navigationControls":"Game navigation controls","aria.viewProfileOnLichess":"View %s's profile on Lichess","aria.chessGameBetween":"Chess game between %1$s, whites, and %2$s, blacks. %3$s","aria.gameInProgress":"Game in progress","aria.whitesWin":"Whites win","aria.blacksWin":"Blacks win","aria.draw":"Draw","aria.unknownPlayer":"Unknown player","aria.rated":"rated %s","aria.move":"Move %1$s, %2$s, %3$s","aria.white":"white","aria.black":"black","aria.remaining":"%s remaining","aria.linkOpensInNewTab":"%s, link, opens in new tab","aria.accessibleChessboard":"Accessible chessboard","aria.piece.king":"king","aria.piece.queen":"queen","aria.piece.rook":"rook","aria.piece.bishop":"bishop","aria.piece.knight":"knight","aria.piece.pawn":"pawn","aria.empty":"empty","san.takes":"takes","san.check":"check","san.checkmate":"checkmate","san.promotesTo":"promotes to","san.droppedOn":"dropped on","san.longCastling":"long castling","san.shortCastling":"short castling"};var vn=["white","black"];var ue=["a","b","c","d","e","f","g","h"],Pe=["1","2","3","4","5","6","7","8"];var Mt=[...Pe].reverse(),Ue=ue.flatMap(e=>Pe.map(t=>e+t)),Y=e=>e.every(t=>t>=0&&t<=7)?Ue[8*e[0]+e[1]]:void 0,Me=e=>Y(e),E=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],xn=e=>{if(e)return e[1]==="@"?[e.slice(2,4)]:[e.slice(0,2),e.slice(2,4)]},mr=Ue.map(E),Cn=Ue.map((e,t)=>({key:e,pos:mr[t]}));function gr(e){let t,r=()=>(t===void 0&&(t=e()),t);return r.clear=()=>{t=void 0},r}var Sn=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;let t=performance.now()-e;return e=void 0,t}}},Ie=e=>e==="white"?"black":"white",Ee=(e,t)=>(e[0]-t[0])**2+(e[1]-t[1])**2,Te=(e,t)=>e.role===t.role&&e.color===t.color,Pn=(e,t)=>e[0]===t[0]&&e[1]===t[1],Ae=e=>(t,r)=>[(r?t[0]:7-t[0])*e.width/8,(r?7-t[1]:t[1])*e.height/8],Z=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},kr=(e,t,r=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${r})`},je=(e,t)=>{e.style.visibility=t?"visible":"hidden"},he=e=>{if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(e.targetTouches?.[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},Io=gr(()=>!("ontouchstart"in window)&&["macintosh","firefox"].every(e=>navigator.userAgent.toLowerCase().includes(e))),Et=e=>e.button===2&&!(e.ctrlKey&&Io()),Q=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r};function At(e,t,r){let n=E(e);return t||(n[0]=7-n[0],n[1]=7-n[1]),[r.left+r.width*n[0]/8+r.width/16,r.top+r.height*(7-n[1])/8+r.height/16]}var te=(e,t)=>Math.abs(e-t),Ye=(e,t,r,n)=>te(e,r)*te(t,n)===2,_t=(e,t,r,n)=>e===r!=(t===n),qt=(e,t,r,n)=>te(e,r)===te(t,n)&&e!==r,Nt=(e,t,r,n)=>_t(e,t,r,n)||qt(e,t,r,n),br=(e,t,r,n)=>Math.max(te(e,r),te(t,n))===1,wr=(e,t,r,n,i)=>te(e,r)===1&&n===t+(i?1:-1),vr=(e,t,r,n,i)=>{let o=i?1:-1;return e===r&&(n===t+o||n===t+2*o&&(i?t<=1:t>=6))},Ze=(e,t,r,n)=>{let i=r-e,o=n-t;if(i&&o&&Math.abs(i)!==Math.abs(o))return[];let s=Math.sign(i),a=Math.sign(o),l=[],c=e+s,h=t+a;for(;c!==r||h!==n;)l.push([c,h]),c+=s,h+=a;return l.map(Y).filter(f=>f!==void 0)},Mn=e=>{let t=E(e),r=[];return t[0]>0&&r.push([t[0]-1,t[1]]),t[0]<7&&r.push([t[0]+1,t[1]]),r.map(Y).filter(n=>n!==void 0)},Qe=(e,t)=>{let r=E(e);return r[1]+=t,Y(r)};var re=class e{constructor(t){this.path=t;this.size=()=>this.path.length/2;this.head=()=>this.path.slice(0,2);this.tail=()=>new e(this.path.slice(2));this.init=()=>new e(this.path.slice(0,-2));this.last=()=>this.path.slice(-2);this.empty=()=>this.path=="";this.contains=t=>this.path.startsWith(t.path);this.isChildOf=t=>this.init()===t;this.append=t=>new e(this.path+t);this.equals=t=>this.path==t.path}static{this.root=new e("")}};var Tt=class{constructor(t,r,n,i){this.initial=t;this.moves=r;this.players=n;this.metadata=i;this.nodeAt=t=>En(this.moves,t);this.dataAt=t=>{let r=this.nodeAt(t);return r?Fo(r)?r.data:this.initial:void 0};this.title=()=>this.players.white.name?[this.players.white.title,this.players.white.name,"vs",this.players.black.title,this.players.black.name].filter(t=>t&&!!t.trim()).join("_").replace(" ","-"):"lichess-pgn-viewer";this.pathAtMainlinePly=t=>t==0?re.root:this.mainline[Math.max(0,Math.min(this.mainline.length-1,t=="last"?9999:t-1))]?.path||re.root;this.hasPlayerName=()=>!!(this.players.white?.name||this.players.black?.name);this.mainline=Array.from(this.moves.mainline())}},Ko=(e,t)=>e.children.find(r=>r.data.path.last()==t),En=(e,t)=>{if(t.empty())return e;let r=Ko(e,t.head());return r?En(r,t.tail()):void 0},Fo=e=>"data"in e,Rt=e=>"uci"in e;var yr=class e{constructor(t,r,n){this.pos=t;this.path=r;this.clocks=n;this.clone=()=>new e(this.pos.clone(),this.path,{...this.clocks})}},xr=e=>{let t=e.map(wn),r=n=>n.reduce((i,o)=>typeof o==null?i:o,void 0);return{texts:t.map(n=>n.text).filter(n=>!!n),shapes:t.flatMap(n=>n.shapes),clock:r(t.map(n=>n.clock)),emt:r(t.map(n=>n.emt))}},An=(e,t=!1)=>{let r=pr(e)[0]||pr("*")[0],n=bn(r.headers).unwrap(),i=kt(n.toSetup()),o=xr(r.comments||[]),s=new Map(Array.from(r.headers,([f,g])=>[f.toLowerCase(),g])),a=Ho(s,t),l={fen:i,turn:n.turn,check:n.isCheck(),pos:n.clone(),comments:o.texts,shapes:o.shapes,clocks:{white:a.timeControl?.initial||o.clock,black:a.timeControl?.initial||o.clock}},c=$o(n,r.moves,a),h=Vo(s,a);return new Tt(l,c,h,a)},$o=(e,t,r)=>kn(t,new yr(e,re.root,{}),(n,i,o)=>{let s=pn(n.pos,i.san);if(!s)return;let a=sn(s),l=n.path.append(a),c=dn(n.pos,s);n.path=l;let h=n.pos.toSetup(),f=xr(i.comments||[]),g=xr(i.startingComments||[]),m=[...f.shapes,...g.shapes],d=(h.fullmoves-1)*2+(n.pos.turn==="white"?0:1),p=n.clocks=zo(n.clocks,n.pos.turn,f.clock);return d<2&&r.timeControl&&(p={white:r.timeControl.initial,black:r.timeControl.initial,...p}),{path:l,ply:d,move:s,san:c,uci:Zt(s),fen:kt(n.pos.toSetup()),turn:n.pos.turn,check:n.pos.isCheck(),comments:f.texts,startingComments:g.texts,nags:i.nags||[],shapes:m,clocks:p,emt:f.emt}}),zo=(e,t,r)=>t=="white"?{...e,black:r}:{...e,white:r};function Vo(e,t){let r=(i,o)=>{let s=e.get(`${i}${o}`);return s=="?"||s==""?void 0:s},n=i=>{let o=r(i,"");return{name:o,title:r(i,"title"),rating:parseInt(r(i,"elo")||"")||void 0,isLichessUser:t.isLichess&&!!o?.match(/^[a-z0-9][a-z0-9_-]{0,28}[a-z0-9]$/i)}};return{white:n("white"),black:n("black")}}function Ho(e,t){let r=e.get("chapterurl")||e.get("gameurl")||e.get("source")||e.get("site"),n=e.get("timecontrol")?.split("+").map(s=>parseInt(s)),i=n&&n[0]?{initial:n[0],increment:n[1]||0}:void 0,o=e.get("orientation");return{externalLink:r&&r.match(/^https?:\/\//)?r:void 0,isLichess:!!(t&&r?.startsWith(t)),timeControl:i,orientation:o==="white"||o==="black"?o:void 0,result:e.get("result")}}var Je=class{constructor(t,r){this.opts=t;this.redraw=r;this.flipped=!1;this.pane="board";this.autoScrollRequested=!1;this.curNode=()=>this.game.nodeAt(this.path)||this.game.moves;this.curData=()=>this.game.dataAt(this.path)||this.game.initial;this.goTo=(t,r=!0)=>{let n=t=="first"?re.root:t=="prev"?this.path.init():t=="next"?this.game.nodeAt(this.path)?.children[0]?.data.path:this.game.pathAtMainlinePly("last");this.toPath(n||this.path,r)};this.canGoTo=t=>t=="prev"||t=="first"?!this.path.empty():!!this.curNode().children[0];this.toPath=(t,r=!0)=>{this.path=t,this.pane="board",this.autoScrollRequested=!0,this.redrawGround(),this.redraw(),r&&this.focus()};this.focus=()=>this.div?.focus();this.toggleMenu=()=>{this.pane=this.pane=="board"?"menu":"board",this.redraw(),this.pane=="board"&&setTimeout(()=>this.menuButton?.focus(),0)};this.togglePgn=()=>{this.pane=this.pane=="pgn"?"board":"pgn",this.redraw()};this.orientation=()=>{let t=this.opts.orientation||"white";return this.flipped?M(t):t};this.flip=()=>{this.flipped=!this.flipped,this.pane="board",this.redrawGround(),this.redraw()};this.cgState=()=>{let t=this.curData(),r=Rt(t)?xn(t.uci):this.opts.chessground?.lastMove;return{fen:t.fen,orientation:this.orientation(),check:t.check,lastMove:r,turnColor:t.turn}};this.analysisUrl=()=>this.game.metadata.isLichess&&this.game.metadata.externalLink||`https://lichess.org/analysis/${this.curData().fen.replace(" ","_")}?color=${this.orientation()}`;this.practiceUrl=()=>`${this.analysisUrl()}#practice`;this.setGround=t=>{this.ground=t,this.redrawGround()};this.redrawGround=()=>this.withGround(t=>{t.set(this.cgState()),t.setShapes(this.curData().shapes.map(r=>({orig:U(r.from),dest:U(r.to),brush:r.color})))});this.withGround=t=>this.ground&&t(this.ground);this.game=An(t.pgn,t.lichess),t.orientation=t.orientation||this.game.metadata.orientation,this.translate=fr(t.translate),this.path=this.game.pathAtMainlinePly(t.initialPly)}};var Ke=e=>e.friendlies.has(e.dest.key),Go=e=>e.enemies.has(e.dest.key),_n=(e,t,r)=>Ze(...e,...t).some(n=>r.has(n)),qn=(e,t,r)=>{let n=r.enemies.get(e);if(n?.role!=="pawn")return!1;let i=n.color==="white"?1:-1,o=E(e),s=E(t);return vr(...o,...s,n.color==="white")&&!_n(o,[s[0],s[1]+i],r.allPieces)},Wo=(e,t,r)=>{let n=r.enemies.get(e);return n?.role==="pawn"&&wr(...E(e),...E(t),n.color==="white")&&(r.friendlies.has(t)||Dt(Qe(t,n.color==="white"?-1:1),r.friendlies,r.enemies,r.lastMove))},Uo=e=>[...e.enemies.keys()].some(t=>qn(t,e.dest.key,e)),Cr=(e,t)=>{let r=e.dest.pos;return[...e.enemies].some(([n,i])=>{let o=E(n);return!t?.includes(i.role)&&(i.role==="pawn"&&wr(...o,...r,i.color==="white")||i.role==="knight"&&Ye(...o,...r)||i.role==="bishop"&&qt(...o,...r)||i.role==="rook"&&_t(...o,...r)||i.role==="queen"&&Nt(...o,...r)||i.role==="king"&&br(...o,...r))&&(!["bishop","rook","queen"].includes(i.role)||!_n(o,r,e.allPieces))})},Ot=e=>Ke(e)&&(Dt(e.dest.key,e.friendlies,e.enemies,e.lastMove)||Cr(e)),Dt=(e,t,r,n)=>{if(!e||n&&e!==n[1])return!1;let i=E(e),o=t.get(e);return o?.role==="pawn"&&i[1]===(o.color==="white"?3:4)&&(!n||te(E(n[0])[1],i[1])===2)&&[1,-1].some(s=>{let a=Y([i[0]+s,i[1]]);return!!a&&r.get(a)?.role==="pawn"})},jo=(e,t)=>{if(e.unrestrictedPremoves)return!0;let r=Ze(...e.orig.pos,...e.dest.pos);t&&r.push(e.dest.key);let n=r.filter(s=>e.friendlies.has(s));if(!n.length)return!0;let i=n[0],o=Qe(i,e.color==="white"?-1:1);return n.length===1&&Dt(i,e.friendlies,e.enemies,e.lastMove)&&!!o&&!r.includes(o)},Yo=(e,t)=>{if(e.unrestrictedPremoves)return!0;let r=Ze(...e.orig.pos,...e.dest.pos);t&&r.push(e.dest.key);let n=r.filter(h=>e.enemies.has(h));if(n.length>1)return!1;if(!n.length)return!0;let i=n[0],o=e.enemies.get(i);if(!o||o.role!=="pawn")return!0;let s=o.color==="white"?1:-1,a=Qe(i,s),l=a?[...Mn(a).filter(h=>Wo(i,h,e)),...[a,Qe(a,s)].filter(h=>!!h).filter(h=>qn(i,h,e))]:[],c=[...r,e.orig.key];return l.some(h=>!c.includes(h))},Sr=(e,t)=>jo(e,t)&&Yo(e,t),Zo=e=>{let t=e.color==="white"?1:-1;return te(e.orig.pos[0],e.dest.pos[0])>1?!1:te(e.orig.pos[0],e.dest.pos[0])?e.dest.pos[1]!==e.orig.pos[1]+t?!1:e.unrestrictedPremoves||Go(e)?!0:Ke(e)?Cr(e):Uo(e)||Dt(Y([e.dest.pos[0],e.dest.pos[1]+t]),e.friendlies,e.enemies,e.lastMove)||Cr(e,["pawn"]):vr(...e.orig.pos,...e.dest.pos,e.color==="white")&&Sr(e,!0)},Qo=e=>Ye(...e.orig.pos,...e.dest.pos)&&(e.unrestrictedPremoves||!Ke(e)||Ot(e)),Nn=e=>qt(...e.orig.pos,...e.dest.pos)&&Sr(e,!1)&&(e.unrestrictedPremoves||!Ke(e)||Ot(e)),Tn=e=>_t(...e.orig.pos,...e.dest.pos)&&Sr(e,!1)&&(e.unrestrictedPremoves||!Ke(e)||Ot(e)),Xo=e=>Nn(e)||Tn(e),Jo=e=>br(...e.orig.pos,...e.dest.pos)&&(e.unrestrictedPremoves||!Ke(e)||Ot(e))||e.canCastle&&e.orig.pos[1]===e.dest.pos[1]&&e.orig.pos[1]===(e.color==="white"?0:7)&&(e.orig.pos[0]===4&&(e.dest.pos[0]===2&&e.rookFilesFriendlies.includes(0)||e.dest.pos[0]===6&&e.rookFilesFriendlies.includes(7))||e.rookFilesFriendlies.includes(e.dest.pos[0]))&&(e.unrestrictedPremoves||Ze(...e.orig.pos,e.dest.pos[0]>e.orig.pos[0]?7:1,e.dest.pos[1]).map(t=>e.allPieces.get(t)).every(t=>!t||Te(t,{role:"rook",color:e.color}))),es={pawn:Zo,knight:Qo,bishop:Nn,rook:Tn,queen:Xo,king:Jo};function Pr(e,t){let r=e.pieces,n=e.premovable.castle,i=!!e.premovable.unrestrictedPremoves,o=r.get(t);if(!o||o.color===e.turnColor)return[];let s=o.color,a=new Map([...r].filter(([g,m])=>m.color===s)),l=new Map([...r].filter(([g,m])=>m.color===Ie(s))),c={key:t,pos:E(t)},h=g=>es[o.role](g)&&e.premovable.additionalPremoveRequirements(g),f={orig:c,role:o.role,allPieces:r,friendlies:a,enemies:l,unrestrictedPremoves:i,color:s,canCastle:n,rookFilesFriendlies:Array.from(r).filter(([g,m])=>g[1]===(s==="white"?"1":"8")&&m.color===s&&m.role==="rook").map(([g])=>E(g)[0]),lastMove:e.lastMove};return Cn.filter(g=>h({...f,dest:g})).map(g=>g.key)}function G(e,...t){e&&setTimeout(()=>e(...t),1)}function Rn(e){e.orientation=Ie(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function On(e,t){for(let[r,n]of t)n?e.pieces.set(r,n):e.pieces.delete(r)}function Dn(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(let[r,n]of e.pieces)n.role==="king"&&n.color===t&&(e.check=r)}function ts(e,t,r,n){ie(e),e.premovable.current=[t,r],G(e.premovable.events.set,t,r,n)}function ne(e){e.premovable.current&&(e.premovable.current=void 0,G(e.premovable.events.unset))}function rs(e,t,r){ne(e),e.predroppable.current={role:t,key:r},G(e.predroppable.events.set,t,r)}function ie(e){let t=e.predroppable;t.current&&(t.current=void 0,G(t.events.unset))}function ns(e,t,r){if(!e.autoCastle)return!1;let n=e.pieces.get(t);if(!n||n.role!=="king")return!1;let i=E(t),o=E(r);if(i[1]!==0&&i[1]!==7||i[1]!==o[1])return!1;i[0]===4&&!e.pieces.has(r)&&(o[0]===6?r=Me([7,o[1]]):o[0]===2&&(r=Me([0,o[1]])));let s=e.pieces.get(r);return!s||s.color!==n.color||s.role!=="rook"?!1:(e.pieces.delete(t),e.pieces.delete(r),i[0]<o[0]?(e.pieces.set(Me([6,o[1]]),n),e.pieces.set(Me([5,o[1]]),s)):(e.pieces.set(Me([2,o[1]]),n),e.pieces.set(Me([3,o[1]]),s)),!0)}function Mr(e,t,r){let n=e.pieces.get(t),i=e.pieces.get(r);if(t===r||!n)return!1;let o=i&&i.color!==n.color?i:void 0;return r===e.selected&&H(e),G(e.events.move,t,r,o),ns(e,t,r)||(e.pieces.set(r,n),e.pieces.delete(t)),e.lastMove=[t,r],e.check=void 0,G(e.events.change),o||!0}function Bt(e,t,r,n){if(e.pieces.has(r))if(n)e.pieces.delete(r);else return!1;return G(e.events.dropNewPiece,t,r),e.pieces.set(r,t),e.lastMove=[r],e.check=void 0,G(e.events.change),e.movable.dests=void 0,e.turnColor=Ie(e.turnColor),!0}function Bn(e,t,r){let n=Mr(e,t,r);return n&&(e.movable.dests=void 0,e.turnColor=Ie(e.turnColor),e.animation.current=void 0),n}function Er(e,t,r){if(It(e,t,r)){let n=Bn(e,t,r);if(n){let i=e.hold.stop();H(e);let o={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:i};return n!==!0&&(o.captured=n),G(e.movable.events.after,t,r,o),!0}}else if(os(e,t,r))return ts(e,t,r,{ctrlKey:e.stats.ctrlKey}),H(e),!0;return H(e),!1}function Lt(e,t,r,n){let i=e.pieces.get(t);i&&(is(e,t,r)||n)?(e.pieces.delete(t),Bt(e,i,r,n),G(e.movable.events.afterNewPiece,i.role,r,{premove:!1,predrop:!1})):i&&ss(e,t,r)?rs(e,i.role,r):(ne(e),ie(e)),e.pieces.delete(t),H(e)}function et(e,t,r){if(G(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){H(e),e.hold.cancel();return}else if((e.selectable.enabled||r)&&e.selected!==t&&Er(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(Ln(e,t)||_r(e,t))&&(Ar(e,t),e.hold.start())}function Ar(e,t){e.selected=t,_r(e,t)?e.premovable.customDests||(e.premovable.dests=Pr(e,t)):e.premovable.dests=void 0}function H(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function Ln(e,t){let r=e.pieces.get(t);return!!r&&(e.movable.color==="both"||e.movable.color===r.color&&e.turnColor===r.color)}var It=(e,t,r)=>t!==r&&Ln(e,t)&&(e.movable.free||!!e.movable.dests?.get(t)?.includes(r));function is(e,t,r){let n=e.pieces.get(t);return!!n&&(t===r||!e.pieces.has(r))&&(e.movable.color==="both"||e.movable.color===n.color&&e.turnColor===n.color)}function _r(e,t){let r=e.pieces.get(t);return!!r&&e.premovable.enabled&&e.movable.color===r.color&&e.turnColor!==r.color}var os=(e,t,r)=>t!==r&&_r(e,t)&&(e.premovable.customDests?.get(t)??Pr(e,t)).includes(r);function ss(e,t,r){let n=e.pieces.get(t),i=e.pieces.get(r);return!!n&&(!i||i.color!==e.movable.color)&&e.predroppable.enabled&&(n.role!=="pawn"||r[1]!=="1"&&r[1]!=="8")&&e.movable.color===n.color&&e.turnColor!==n.color}function In(e,t){let r=e.pieces.get(t);return!!r&&e.draggable.enabled&&(e.movable.color==="both"||e.movable.color===r.color&&(e.turnColor===r.color||e.premovable.enabled))}function Kn(e){let t=e.premovable.current;if(!t)return!1;let r=t[0],n=t[1],i=!1;if(It(e,r,n)){let o=Bn(e,r,n);if(o){let s={premove:!0};o!==!0&&(s.captured=o),G(e.movable.events.after,r,n,s),i=!0}}return ne(e),i}function Fn(e,t){let r=e.predroppable.current,n=!1;if(!r)return!1;if(t(r)){let i={role:r.role,color:e.movable.color};Bt(e,i,r.key)&&(G(e.movable.events.afterNewPiece,r.role,r.key,{premove:!1,predrop:!0}),n=!0)}return ie(e),n}function tt(e){ne(e),ie(e),H(e)}function qr(e){e.movable.color=e.movable.dests=e.animation.current=void 0,tt(e)}function oe(e,t,r){let n=Math.floor(8*(e[0]-r.left)/r.width);t||(n=7-n);let i=7-Math.floor(8*(e[1]-r.top)/r.height);return t||(i=7-i),n>=0&&n<8&&i>=0&&i<8?Y([n,i]):void 0}function $n(e,t,r,n){let i=E(e),o=mr.filter(c=>Pn(i,c)||Nt(i[0],i[1],c[0],c[1])||Ye(i[0],i[1],c[0],c[1])),a=o.map(c=>At(Me(c),r,n)).map(c=>Ee(t,c)),[,l]=a.reduce((c,h,f)=>c[0]<h?c:[h,f],[a[0],0]);return Y(o[l])}var L=e=>e.orientation==="white";var Tr="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",as={p:"pawn",r:"rook",n:"knight",b:"bishop",q:"queen",k:"king"},cs={pawn:"p",rook:"r",knight:"n",bishop:"b",queen:"q",king:"k"};function Fe(e){e==="start"&&(e=Tr);let t=new Map,r=7,n=0;for(let i of e)switch(i){case" ":case"[":return t;case"/":if(--r,r<0)return t;n=0;break;case"~":{let o=Y([n-1,r]),s=o&&t.get(o);s&&(s.promoted=!0);break}default:{let o=i.charCodeAt(0);if(o<57)n+=o-48;else{let s=i.toLowerCase(),a=Y([n,r]);a&&t.set(a,{role:as[s],color:i===s?"black":"white"}),++n}}}return t}function zn(e){return Mt.map(t=>ue.map(r=>{let n=e.get(r+t);if(n){let i=cs[n.role];return n.color==="white"&&(i=i.toUpperCase()),n.promoted&&(i+="~"),i}else return"1"}).join("")).join("/").replace(/1{2,}/g,t=>t.length.toString())}function Rr(e,t){t.animation&&(Or(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function Kt(e,t){if(t.movable?.dests&&(e.movable.dests=void 0),t.drawable?.autoShapes&&(e.drawable.autoShapes=[]),Or(e,t),t.fen&&(e.pieces=Fe(t.fen),e.drawable.shapes=t.drawable?.shapes||[]),"check"in t&&Dn(e,t.check||!1),"lastMove"in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&Ar(e,e.selected),Rr(e,t),!e.movable.rookCastle&&e.movable.dests){let r=e.movable.color==="white"?"1":"8",n="e"+r,i=e.movable.dests.get(n),o=e.pieces.get(n);if(!i||!o||o.role!=="king")return;e.movable.dests.set(n,i.filter(s=>!(s==="a"+r&&i.includes("c"+r))&&!(s==="h"+r&&i.includes("g"+r))))}}function Or(e,t){for(let r in t)r==="__proto__"||r==="constructor"||!Object.prototype.hasOwnProperty.call(t,r)||(Object.prototype.hasOwnProperty.call(e,r)&&Vn(e[r])&&Vn(t[r])?Or(e[r],t[r]):e[r]=t[r])}function Vn(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var me=(e,t)=>t.animation.enabled?ds(e,t):ge(e,t);function ge(e,t){let r=e(t);return t.dom.redraw(),r}var Dr=(e,t)=>({key:e,pos:E(e),piece:t}),us=(e,t)=>t.sort((r,n)=>Ee(e.pos,r.pos)-Ee(e.pos,n.pos))[0];function hs(e,t){let r=new Map,n=[],i=new Map,o=[],s=[],a=new Map,l,c,h;for(let[f,g]of e)a.set(f,Dr(f,g));for(let f of Ue)l=t.pieces.get(f),c=a.get(f),l?c?Te(l,c.piece)||(o.push(c),s.push(Dr(f,l))):s.push(Dr(f,l)):c&&o.push(c);for(let f of s)c=us(f,o.filter(g=>Te(f.piece,g.piece))),c&&(h=[c.pos[0]-f.pos[0],c.pos[1]-f.pos[1]],r.set(f.key,h.concat(h)),n.push(c.key));for(let f of o)n.includes(f.key)||i.set(f.key,f.piece);return{anims:r,fadings:i}}function Hn(e,t){let r=e.animation.current;if(r===void 0){e.dom.destroyed||e.dom.redrawNow();return}let n=1-(t-r.start)*r.frequency;if(n<=0)e.animation.current=void 0,e.dom.redrawNow();else{let i=ps(n);for(let o of r.plan.anims.values())o[2]=o[0]*i,o[3]=o[1]*i;e.dom.redrawNow(!0),requestAnimationFrame((o=performance.now())=>Hn(e,o))}}function ds(e,t){let r=new Map(t.pieces),n=e(t),i=hs(r,t);if(i.anims.size||i.fadings.size){let o=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:i},o||Hn(t,performance.now())}else t.dom.redraw();return n}var ps=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1;var fs=["green","red","blue","yellow"];function Gn(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?H(e):tt(e);let r=he(t),n=oe(r,L(e),e.dom.bounds());n&&(e.drawable.current={orig:n,pos:r,brush:ms(t),snapToValidMove:e.drawable.defaultSnapToValidMove},Wn(e))}function Wn(e){requestAnimationFrame(()=>{let t=e.drawable.current;if(t){let r=oe(t.pos,L(e),e.dom.bounds());r||(t.snapToValidMove=!1);let n=t.snapToValidMove?$n(t.orig,t.pos,L(e),e.dom.bounds()):r;n!==t.mouseSq&&(t.mouseSq=n,t.dest=n!==t.orig?n:void 0,e.dom.redrawNow()),Wn(e)}})}function Un(e,t){e.drawable.current&&(e.drawable.current.pos=he(t))}function jn(e){let t=e.drawable.current;t&&(t.mouseSq&&gs(e.drawable,t),Br(e))}function Br(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}function Yn(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),Zn(e.drawable))}var Ft=(e,t)=>e.orig===t.orig&&e.dest===t.dest,Lr=(e,t)=>e.brush===t.brush;function ms(e){let t=(e.shiftKey||e.ctrlKey)&&Et(e),r=e.altKey||e.metaKey||e.getModifierState?.("AltGraph");return fs[(t?1:0)+(r?2:0)]}function gs(e,t){let r=e.shapes.find(n=>Ft(n,t));r&&(e.shapes=e.shapes.filter(n=>!Ft(n,t))),(!r||!Lr(r,t))&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),Zn(e)}function Zn(e){e.onChange&&e.onChange(e.shapes)}function Qn(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;let r=e.dom.bounds(),n=he(t),i=oe(n,L(e),r);if(!i)return;let o=e.pieces.get(i),s=e.selected;if(!s&&e.drawable.enabled&&(e.drawable.eraseOnMovablePieceClick||!o||o.color!==e.turnColor)&&Yn(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||o||s||bs(e,n)))t.preventDefault();else if(t.touches)return;let a=!!e.premovable.current,l=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&It(e,e.selected,i)?me(f=>et(f,i),e):et(e,i);let c=e.selected===i,h=ri(e,i);if(o&&h&&c&&In(e,i)){e.draggable.current={orig:i,piece:o,origPos:n,pos:n,started:e.draggable.autoDistance&&e.stats.dragged,element:h,previouslySelected:s,originTarget:t.target,keyHasChanged:!1},h.cgDragging=!0,h.classList.add("dragging");let f=e.dom.elements.ghost;f&&(f.className=`ghost ${o.color} ${o.role}`,Z(f,Ae(r)(E(i),L(e))),je(f,!0)),Ir(e)}else a&&ne(e),l&&ie(e);e.dom.redraw()}function bs(e,t){let r=L(e),n=e.dom.bounds(),i=Math.pow(e.touchIgnoreRadius*n.width/16,2)*2;for(let o of e.pieces.keys()){let s=At(o,r,n);if(Ee(s,t)<=i)return!0}return!1}function Xn(e,t,r,n){e.pieces.set("a0",t),e.dom.redraw();let o=he(r);e.draggable.current={orig:"a0",piece:t,origPos:o,pos:o,started:!0,element:()=>ri(e,"a0"),originTarget:r.target,newPiece:!0,force:!!n,keyHasChanged:!1},Ir(e)}function Ir(e){requestAnimationFrame(()=>{let t=e.draggable.current;if(!t)return;e.animation.current?.plan.anims.has(t.orig)&&(e.animation.current=void 0);let r=e.pieces.get(t.orig);if(!r||!Te(r,t.piece))Re(e);else if(!t.started&&Ee(t.pos,t.origPos)>=Math.pow(e.draggable.distance,2)&&(t.started=!0),t.started){if(typeof t.element=="function"){let i=t.element();if(!i)return;i.cgDragging=!0,i.classList.add("dragging"),t.element=i}let n=e.dom.bounds();Z(t.element,[t.pos[0]-n.left-n.width/16,t.pos[1]-n.top-n.height/16]),t.keyHasChanged||(t.keyHasChanged=t.orig!==oe(t.pos,L(e),n))}Ir(e)})}function Jn(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=he(t))}function ei(e,t){let r=e.draggable.current;if(!r)return;if(t.type==="touchend"&&t.cancelable!==!1&&t.preventDefault(),t.type==="touchend"&&r.originTarget!==t.target&&!r.newPiece){e.draggable.current=void 0;return}ne(e),ie(e);let n=he(t)||r.pos,i=oe(n,L(e),e.dom.bounds());i&&r.started&&r.orig!==i?r.newPiece?Lt(e,r.orig,i,r.force):(e.stats.ctrlKey=t.ctrlKey,Er(e,r.orig,i)&&(e.stats.dragged=!0)):r.newPiece?e.pieces.delete(r.orig):e.draggable.deleteOnDropOff&&!i&&(e.pieces.delete(r.orig),G(e.events.change)),(r.orig===r.previouslySelected||r.keyHasChanged)&&(r.orig===i||!i)?H(e):e.selectable.enabled||H(e),ti(e),e.draggable.current=void 0,e.dom.redraw()}function Re(e){let t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,H(e),ti(e),e.dom.redraw())}function ti(e){let t=e.dom.elements;t.ghost&&je(t.ghost,!1)}function ri(e,t){let r=e.dom.elements.board.firstChild;for(;r;){if(r.cgKey===t&&r.tagName==="PIECE")return r;r=r.nextSibling}}function ii(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{ni(e,2),setTimeout(()=>ni(e,void 0),120)},120)}function ni(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function oi(e,t){function r(){Rn(e),t()}return{set(n){n.orientation&&n.orientation!==e.orientation&&r(),Rr(e,n),(n.fen?me:ge)(i=>Kt(i,n),e)},state:e,getFen:()=>zn(e.pieces),toggleOrientation:r,setPieces(n){me(i=>On(i,n),e)},selectSquare(n,i){n?me(o=>et(o,n,i),e):e.selected&&(H(e),e.dom.redraw())},move(n,i){me(o=>Mr(o,n,i),e)},newPiece(n,i){me(o=>Bt(o,n,i),e)},playPremove(){if(e.premovable.current){if(me(Kn,e))return!0;e.dom.redraw()}return!1},playPredrop(n){if(e.predroppable.current){let i=Fn(e,n);return e.dom.redraw(),i}return!1},cancelPremove(){ge(ne,e)},cancelPredrop(){ge(ie,e)},cancelMove(){ge(n=>{tt(n),Re(n)},e)},stop(){ge(n=>{qr(n),Re(n)},e)},explode(n){ii(e,n)},setAutoShapes(n){ge(i=>i.drawable.autoShapes=n,e)},setShapes(n){ge(i=>i.drawable.shapes=n.slice(),e)},getKeyAtDomPos(n){return oe(n,L(e),e.dom.bounds())},redrawAll:t,dragNewPiece(n,i,o){Xn(e,n,i,o)},destroy(){qr(e),e.dom.unbind&&e.dom.unbind(),e.dom.destroyed=!0}}}function si(){return{pieces:Fe(Tr),orientation:"white",turnColor:"white",coordinates:!0,coordinatesOnSquares:!1,ranksPosition:"right",autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,touchIgnoreRadius:1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:"both",showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,additionalPremoveRequirements:e=>!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!("ontouchstart"in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnMovablePieceClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:"g",color:"#15781B",opacity:1,lineWidth:10},red:{key:"r",color:"#882020",opacity:1,lineWidth:10},blue:{key:"b",color:"#003088",opacity:1,lineWidth:10},yellow:{key:"y",color:"#e68f00",opacity:1,lineWidth:10},paleBlue:{key:"pb",color:"#003088",opacity:.4,lineWidth:15},paleGreen:{key:"pg",color:"#15781B",opacity:.4,lineWidth:15},paleRed:{key:"pr",color:"#882020",opacity:.4,lineWidth:15},paleGrey:{key:"pgr",color:"#4a4a4a",opacity:.35,lineWidth:15},purple:{key:"purple",color:"#68217a",opacity:.65,lineWidth:10},pink:{key:"pink",color:"#ee2080",opacity:.5,lineWidth:10},white:{key:"white",color:"white",opacity:1,lineWidth:10},paleWhite:{key:"pwhite",color:"white",opacity:.6,lineWidth:10}},prevSvgHash:""},hold:Sn()}}function li(){let e=$("defs"),t=z($("filter"),{id:"cg-filter-blur"});return t.appendChild(z($("feGaussianBlur"),{stdDeviation:"0.013"})),e.appendChild(t),e}function ui(e,t){let r=e.drawable,n=r.current,i=n&&n.mouseSq?n:void 0,o=new Map,s=e.dom.bounds(),a=r.autoShapes.filter(f=>!f.piece);for(let f of r.shapes.concat(a).concat(i?[i]:[])){if(!f.dest)continue;let g=o.get(f.dest)??new Set,m=zt($t(E(f.orig),e.orientation),s),d=zt($t(E(f.dest),e.orientation),s);g.add(Fr(m,d)),o.set(f.dest,g)}let l=[],c=i?r.shapes.findIndex(f=>Ft(f,i)&&Lr(f,i)):-1;for(let[f,g]of r.shapes.concat(a).entries()){let m=c!==-1&&c===f;l.push({shape:g,current:!1,pendingErase:m,hash:ai(g,Kr(g.dest,o),!1,s,m)})}i&&c===-1&&l.push({shape:i,current:!0,hash:ai(i,Kr(i.dest,o),!0,s,!1),pendingErase:!1});let h=l.map(f=>f.hash).join(";");h!==e.drawable.prevSvgHash&&(e.drawable.prevSvgHash=h,vs(r,l,t),ys(l,t,f=>Ss(e,f,r.brushes,o,s)))}function vs(e,t,r){for(let n of[r.shapes,r.shapesBelow]){let i=n.querySelector("defs"),o=t.filter(c=>n===r.shapesBelow==!!c.shape.below),s=new Map;for(let c of o.filter(h=>h.shape.dest&&h.shape.brush)){let h=hi(e.brushes[c.shape.brush],c.shape.modifiers),{key:f,color:g}=di(c.shape);f&&g&&s.set(f,{key:f,color:g,opacity:1,lineWidth:1}),s.set(h.key,h)}let a=new Set,l=i.firstElementChild;for(;l;)a.add(l.getAttribute("cgKey")),l=l.nextElementSibling;for(let[c,h]of s.entries())a.has(c)||i.appendChild(Es(h))}}function ys(e,t,r){for(let[n,i]of[[t.shapes,t.custom],[t.shapesBelow,t.customBelow]]){let[o,s]=[n,i].map(c=>c.querySelector("g")),a=e.filter(c=>n===t.shapesBelow==!!c.shape.below),l=new Map;for(let c of a)l.set(c.hash,!1);for(let c of[o,s]){let h=[],f=c.firstElementChild,g;for(;f;)g=f.getAttribute("cgHash"),l.has(g)?l.set(g,!0):h.push(f),f=f.nextElementSibling;for(let m of h)c.removeChild(m)}for(let c of a.filter(h=>!l.get(h.hash)))for(let h of r(c))h.isCustom?s.appendChild(h.el):o.appendChild(h.el)}}function ai({orig:e,dest:t,brush:r,piece:n,modifiers:i,customSvg:o,label:s,below:a},l,c,h,f){return[h.width,h.height,c,f&&"pendingErase",e,t,r,l&&"-",n&&xs(n),i&&Cs(i),o&&`custom-${ci(o.html)},${o.center?.[0]??"o"}`,s&&`label-${ci(s.text)}`,a&&"below"].filter(g=>g).join(",")}function xs(e){return[e.color,e.role,e.scale].filter(t=>t).join(",")}function Cs(e){return[e.lineWidth,e.hilite].filter(t=>t).join(",")}function ci(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)>>>0;return t.toString()}function Ss(e,{shape:t,current:r,pendingErase:n,hash:i},o,s,a){let l=zt($t(E(t.orig),e.orientation),a),c=t.dest?zt($t(E(t.dest),e.orientation),a):l,h=t.brush&&hi(o[t.brush],t.modifiers),f=s.get(t.dest),g=[];if(h){let m=z($("g"),{cgHash:i});g.push({el:m}),l[0]!==c[0]||l[1]!==c[1]?m.appendChild(Ms(t,h,l,c,r,Kr(t.dest,s),n)):m.appendChild(Ps(o[t.brush],l,r,a,n))}if(t.label){let m=t.label;m.fill??(m.fill=t.brush&&o[t.brush].color);let d=t.brush?void 0:"tr";g.push({el:As(m,i,l,c,f,d),isCustom:!0})}if(t.customSvg){let m=t.customSvg.center??"orig",[d,p]=m==="label"?fi(l,c,f).map(w=>w-.5):m==="dest"?c:l,v=z($("g"),{transform:`translate(${d},${p})`,cgHash:i});v.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,g.push({el:v,isCustom:!0})}return g}function Ps(e,t,r,n,i){let o=_s(),s=(n.width+n.height)/(4*Math.max(n.width,n.height));return z($("circle"),{stroke:e.color,"stroke-width":o[r?0:1],fill:"none",opacity:pi(e,r,i),cx:t[0],cy:t[1],r:s-o[1]/2})}function Ms(e,t,r,n,i,o,s){function a(h){let f=Ns(o&&!i),g=n[0]-r[0],m=n[1]-r[1],d=Math.atan2(m,g),p=Math.cos(d)*f,v=Math.sin(d)*f,w=di(e);return z($("line"),{stroke:h?w.color:t.color,"stroke-width":qs(t,i)*(h?1.14:1),"stroke-linecap":"round","marker-end":`url(#arrowhead-${h?w.key:t.key})`,opacity:e.modifiers?.hilite&&!s?1:pi(t,i,s),x1:r[0],y1:r[1],x2:n[0]-p,y2:n[1]-v})}if(!e.modifiers?.hilite)return a(!1);let l=z($("g"),{opacity:t.opacity}),c=z($("g"),{filter:"url(#cg-filter-blur)"});return c.appendChild(Ts(r,n)),c.appendChild(a(!0)),l.appendChild(c),l.appendChild(a(!1)),l}function Es(e){let t=z($("marker"),{id:"arrowhead-"+e.key,orient:"auto",overflow:"visible",markerWidth:4,markerHeight:4,refX:e.key.startsWith("hilite")?1.86:2.05,refY:2});return t.appendChild(z($("path"),{d:"M0,0 V4 L3,2 Z",fill:e.color})),t.setAttribute("cgKey",e.key),t}function As(e,t,r,n,i,o){let a=.4*.75**e.text.length,l=fi(r,n,i),c=o==="tr"?.4:0,h=z($("g"),{transform:`translate(${l[0]+c},${l[1]-c})`,cgHash:t});h.appendChild(z($("circle"),{r:.4/2,"fill-opacity":o?1:.8,"stroke-opacity":o?1:.7,"stroke-width":.03,fill:e.fill??"#666",stroke:"white"}));let f=z($("text"),{"font-size":a,"font-family":"Noto Sans","text-anchor":"middle",fill:"white",y:.13*.75**e.text.length});return f.innerHTML=e.text,h.appendChild(f),h}function $t(e,t){return t==="white"?e:[7-e[0],7-e[1]]}function Kr(e,t){return(e&&t.has(e)&&t.get(e).size>1)===!0}function $(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function z(e,t){for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.setAttribute(r,t[r]);return e}function hi(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(r=>r).join("")}:e}function _s(){return[3/64,4/64]}function qs(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function di(e){let t=e.modifiers?.hilite;return{key:t&&`hilite-${t.replace("#","")}`,color:t}}function pi(e,t,r){return(e.opacity||1)*(r?.6:t?.9:1)}function Ns(e){return(e?20:10)/64}function zt(e,t){let r=Math.min(1,t.width/t.height),n=Math.min(1,t.height/t.width);return[(e[0]-3.5)*r,(3.5-e[1])*n]}function Ts(e,t){let r={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return z($("rect"),{x:r.from[0],y:r.from[1],width:r.to[0]-r.from[0],height:r.to[1]-r.from[1],fill:"none",stroke:"none"})}function Fr(e,t,r=!0){let n=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return r?(Math.round(n*8/Math.PI)+16)%16:n}function Rs(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((r,n)=>r+n*n,0))}function fi(e,t,r){let n=Rs(e,t),i=Fr(e,t,!1);if(r&&(n-=33/64,r.size>1)){n-=10/64;let o=Fr(e,t);(r.has((o+1)%16)||r.has((o+15)%16))&&o&1&&(n-=.4)}return[e[0]-Math.cos(i)*n,e[1]-Math.sin(i)*n].map(o=>o+.5)}function gi(e,t){e.innerHTML="",e.classList.add("cg-wrap");for(let h of vn)e.classList.toggle("orientation-"+h,t.orientation===h);e.classList.toggle("manipulable",!t.viewOnly);let r=Q("cg-container");e.appendChild(r);let n=Q("cg-board");r.appendChild(n);let i,o,s,a,l;if(t.drawable.visible&&([i,o]=["cg-shapes-below","cg-shapes"].map(h=>mi(h,!0)),[s,a]=["cg-custom-below","cg-custom-svgs"].map(h=>mi(h,!1)),l=Q("cg-auto-pieces"),r.appendChild(i),r.appendChild(s),r.appendChild(o),r.appendChild(a),r.appendChild(l)),t.coordinates){let h=t.orientation==="black"?" black":"",f=t.ranksPosition==="left"?" left":"";if(t.coordinatesOnSquares){let g=t.orientation==="white"?m=>m+1:m=>8-m;ue.forEach((m,d)=>r.appendChild($r(Pe.map(p=>m+p),"squares rank"+g(d)+h+f)))}else r.appendChild($r(Pe,"ranks"+h+f)),r.appendChild($r(ue,"files"+h))}let c;return t.draggable.enabled&&t.draggable.showGhost&&(c=Q("piece","ghost"),je(c,!1),r.appendChild(c)),{board:n,container:r,wrap:e,ghost:c,shapes:o,shapesBelow:i,custom:a,customBelow:s,autoPieces:l}}function mi(e,t){let r=z($("svg"),{class:e,viewBox:t?"-4 -4 8 8":"-3.5 -3.5 8 8",preserveAspectRatio:"xMidYMid slice"});return t&&r.appendChild(li()),r.appendChild($("g")),r}function $r(e,t){let r=Q("coords",t),n;for(let i of e)n=Q("coord"),n.textContent=i,r.appendChild(n);return r}function ki(e,t){if(!e.dropmode.active)return;ne(e),ie(e);let r=e.dropmode.piece;if(r){e.pieces.set("a0",r);let n=he(t),i=n&&oe(n,L(e),e.dom.bounds());i&&Lt(e,"a0",i)}e.dom.redraw()}function wi(e,t){let r=e.dom.elements.board;if("ResizeObserver"in window&&new ResizeObserver(t).observe(e.dom.elements.wrap),(e.disableContextMenu||e.drawable.enabled)&&r.addEventListener("contextmenu",i=>i.preventDefault()),e.viewOnly)return;let n=Ds(e);r.addEventListener("touchstart",n,{passive:!1}),r.addEventListener("mousedown",n,{passive:!1})}function vi(e,t){let r=[];if("ResizeObserver"in window||r.push(rt(document.body,"chessground.resize",t)),!e.viewOnly){let n=bi(e,Jn,Un),i=bi(e,ei,jn);for(let s of["touchmove","mousemove"])r.push(rt(document,s,n));for(let s of["touchend","mouseup"])r.push(rt(document,s,i));let o=()=>e.dom.bounds.clear();r.push(rt(document,"scroll",o,{capture:!0,passive:!0})),r.push(rt(window,"resize",o,{passive:!0}))}return()=>r.forEach(n=>n())}function rt(e,t,r,n){return e.addEventListener(t,r,n),()=>e.removeEventListener(t,r,n)}var Ds=e=>t=>{e.draggable.current?Re(e):e.drawable.current?Br(e):t.shiftKey||Et(t)?e.drawable.enabled&&Gn(e,t):e.viewOnly||(e.dropmode.active?ki(e,t):Qn(e,t))},bi=(e,t,r)=>n=>{e.drawable.current?e.drawable.enabled&&r(e,n):e.viewOnly||t(e,n)};function xi(e){let t=L(e),r=Ae(e.dom.bounds()),n=e.dom.elements.board,i=e.pieces,o=e.animation.current,s=o?o.plan.anims:new Map,a=o?o.plan.fadings:new Map,l=e.draggable.current,c=Ls(e),h=new Set,f=new Set,g=new Map,m=new Map,d,p,v,w,x,A,C,P,_,q;for(p=n.firstChild;p;){if(d=p.cgKey,Si(p))if(v=i.get(d),x=s.get(d),A=a.get(d),w=p.cgPiece,p.cgDragging&&(!l||l.orig!==d)&&(p.classList.remove("dragging"),Z(p,r(E(d),t)),p.cgDragging=!1),!A&&p.cgFading&&(p.cgFading=!1,p.classList.remove("fading")),v){if(x&&p.cgAnimating&&w===nt(v)){let y=E(d);y[0]+=x[2],y[1]+=x[3],p.classList.add("anim"),Z(p,r(y,t))}else p.cgAnimating&&(p.cgAnimating=!1,p.classList.remove("anim"),Z(p,r(E(d),t)),e.addPieceZIndex&&(p.style.zIndex=zr(E(d),t)));w===nt(v)&&(!A||!p.cgFading)?h.add(d):A&&w===nt(A)?(p.classList.add("fading"),p.cgFading=!0):Vr(g,w,p)}else Vr(g,w,p);else if(Pi(p)){let y=p.className;c.get(d)===y?f.add(d):Vr(m,y,p)}p=p.nextSibling}for(let[y,T]of c)if(!f.has(y)){_=m.get(T),q=_&&_.pop();let R=r(E(y),t);if(q)q.cgKey=y,Z(q,R);else{let N=Q("square",T);N.cgKey=y,Z(N,R),n.insertBefore(N,n.firstChild)}}for(let[y,T]of i)if(x=s.get(y),!h.has(y))if(C=g.get(nt(T)),P=C&&C.pop(),P){P.cgKey=y,P.cgFading&&(P.classList.remove("fading"),P.cgFading=!1);let R=E(y);e.addPieceZIndex&&(P.style.zIndex=zr(R,t)),x&&(P.cgAnimating=!0,P.classList.add("anim"),R[0]+=x[2],R[1]+=x[3]),Z(P,r(R,t))}else{let R=nt(T),N=Q("piece",R),I=E(y);N.cgPiece=R,N.cgKey=y,x&&(N.cgAnimating=!0,I[0]+=x[2],I[1]+=x[3]),Z(N,r(I,t)),e.addPieceZIndex&&(N.style.zIndex=zr(I,t)),n.appendChild(N)}for(let y of g.values())yi(e,y);for(let y of m.values())yi(e,y)}function Ci(e){let t=L(e),r=Ae(e.dom.bounds()),n=e.dom.elements.board.firstChild;for(;n;)(Si(n)&&!n.cgAnimating||Pi(n))&&Z(n,r(E(n.cgKey),t)),n=n.nextSibling}function Hr(e){let t=e.dom.elements.wrap.getBoundingClientRect(),r=e.dom.elements.container,n=t.height/t.width,i=Math.floor(t.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,o=i*n;r.style.width=i+"px",r.style.height=o+"px",e.dom.bounds.clear(),e.addDimensionsCssVarsTo?.style.setProperty("---cg-width",i+"px"),e.addDimensionsCssVarsTo?.style.setProperty("---cg-height",o+"px")}var Si=e=>e.tagName==="PIECE",Pi=e=>e.tagName==="SQUARE";function yi(e,t){for(let r of t)e.dom.elements.board.removeChild(r)}function zr(e,t){let n=e[1];return`${t?10-n:3+n}`}var nt=e=>`${e.color} ${e.role}`;function Ls(e){let t=new Map;if(e.lastMove&&e.highlight.lastMove)for(let i of e.lastMove)ke(t,i,"last-move");if(e.check&&e.highlight.check&&ke(t,e.check,"check"),e.selected&&(ke(t,e.selected,"selected"),e.movable.showDests)){let i=e.movable.dests?.get(e.selected);if(i)for(let s of i)ke(t,s,"move-dest"+(e.pieces.has(s)?" oc":""));let o=e.premovable.customDests?.get(e.selected)??e.premovable.dests;if(o)for(let s of o)ke(t,s,"premove-dest"+(e.pieces.has(s)?" oc":""))}let r=e.premovable.current;if(r)for(let i of r)ke(t,i,"current-premove");else e.predroppable.current&&ke(t,e.predroppable.current.key,"current-premove");let n=e.exploding;if(n)for(let i of n.keys)ke(t,i,"exploding"+n.stage);return e.highlight.custom&&e.highlight.custom.forEach((i,o)=>{ke(t,o,i)}),t}function ke(e,t,r){let n=e.get(t);n?e.set(t,`${n} ${r}`):e.set(t,r)}function Vr(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Mi(e,t,r){let n=new Map,i=[];for(let a of e)n.set(a.hash,!1);let o=t.firstElementChild,s;for(;o;)s=o.getAttribute("cgHash"),n.has(s)?n.set(s,!0):i.push(o),o=o.nextElementSibling;for(let a of i)t.removeChild(a);for(let a of e)n.get(a.hash)||t.appendChild(r(a))}function Ei(e,t){let n=e.drawable.autoShapes.filter(i=>i.piece).map(i=>({shape:i,hash:Ks(i),current:!1,pendingErase:!1}));Mi(n,t,i=>Is(e,i,e.dom.bounds()))}function Ai(e){let t=L(e),r=Ae(e.dom.bounds()),n=e.dom.elements.autoPieces?.firstChild;for(;n;)kr(n,r(E(n.cgKey),t),n.cgScale),n=n.nextSibling}function Is(e,{shape:t,hash:r},n){let i=t.orig,o=t.piece?.role,s=t.piece?.color,a=t.piece?.scale,l=Q("piece",`${o} ${s}`);return l.setAttribute("cgHash",r),l.cgKey=i,l.cgScale=a,kr(l,Ae(n)(E(i),L(e)),a),l}var Ks=e=>[e.orig,e.piece?.role,e.piece?.color,e.piece?.scale].join(",");function _i(e,t){let r=si();Kt(r,t||{});function n(){let i="dom"in r?r.dom.unbind:void 0,o=gi(e,r),s=gr(()=>o.board.getBoundingClientRect()),a=h=>{xi(c),o.autoPieces&&Ei(c,o.autoPieces),!h&&o.shapes&&ui(c,o)},l=()=>{Hr(c),Ci(c),o.autoPieces&&Ai(c)},c=r;return c.dom={elements:o,bounds:s,redraw:$s(a),redrawNow:a,unbind:i},c.drawable.prevSvgHash="",Hr(c),a(!1),wi(c,l),i||(c.dom.unbind=vi(c,l)),c.events.insert&&c.events.insert(o),c}return oi(n(),n)}function $s(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}function zs(e,t){return document.createElement(e,t)}function Vs(e,t,r){return document.createElementNS(e,t,r)}function Hs(){return Oe(document.createDocumentFragment())}function Gs(e){return document.createTextNode(e)}function Ws(e){return document.createComment(e)}function Us(e,t,r){if(be(e)){let n=e;for(;n&&be(n);)n=Oe(n).parent;e=n??e}be(t)&&(t=Oe(t,e)),r&&be(r)&&(r=Oe(r).firstChildNode),e.insertBefore(t,r)}function js(e,t){e.removeChild(t)}function Ys(e,t){be(t)&&(t=Oe(t,e)),e.appendChild(t)}function qi(e){if(be(e)){for(;e&&be(e);)e=Oe(e).parent;return e??null}return e.parentNode}function Zs(e){var t;if(be(e)){let r=Oe(e),n=qi(r);if(n&&r.lastChildNode){let i=Array.from(n.childNodes),o=i.indexOf(r.lastChildNode);return(t=i[o+1])!==null&&t!==void 0?t:null}return null}return e.nextSibling}function Qs(e){return e.tagName}function Xs(e,t){e.textContent=t}function Js(e){return e.textContent}function ea(e){return e.nodeType===1}function ta(e){return e.nodeType===3}function ra(e){return e.nodeType===8}function be(e){return e.nodeType===11}function Oe(e,t){var r,n,i;let o=e;return(r=o.parent)!==null&&r!==void 0||(o.parent=t??null),(n=o.firstChildNode)!==null&&n!==void 0||(o.firstChildNode=e.firstChild),(i=o.lastChildNode)!==null&&i!==void 0||(o.lastChildNode=e.lastChild),o}var Ni={createElement:zs,createElementNS:Vs,createTextNode:Gs,createDocumentFragment:Hs,createComment:Ws,insertBefore:Us,removeChild:js,appendChild:Ys,parentNode:qi,nextSibling:Zs,tagName:Qs,setTextContent:Xs,getTextContent:Js,isElement:ea,isText:ta,isComment:ra,isDocumentFragment:be};function De(e,t,r,n,i){let o=t===void 0?void 0:t.key;return{sel:e,data:t,children:r,text:n,elm:i,key:o}}var it=Array.isArray;function $e(e){return typeof e=="string"||typeof e=="number"||e instanceof String||e instanceof Number}function Gr(e){return e===void 0}function j(e){return e!==void 0}var Wr=De("",{},[],void 0,void 0);function ot(e,t){var r,n;let i=e.key===t.key,o=((r=e.data)===null||r===void 0?void 0:r.is)===((n=t.data)===null||n===void 0?void 0:n.is),s=e.sel===t.sel,a=!e.sel&&e.sel===t.sel?typeof e.text==typeof t.text:!0;return s&&i&&o&&a}function na(){throw new Error("The document fragment is not supported on this platform.")}function ia(e,t){return e.isElement(t)}function oa(e,t){return e.isDocumentFragment(t)}function sa(e,t,r){var n;let i={};for(let o=t;o<=r;++o){let s=(n=e[o])===null||n===void 0?void 0:n.key;s!==void 0&&(i[s]=o)}return i}var aa=["create","update","remove","destroy","pre","post"];function Ur(e,t,r){let n={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},i=t!==void 0?t:Ni;for(let d of aa)for(let p of e){let v=p[d];v!==void 0&&n[d].push(v)}function o(d){let p=d.id?"#"+d.id:"",v=d.getAttribute("class"),w=v?"."+v.split(" ").join("."):"";return De(i.tagName(d).toLowerCase()+p+w,{},[],void 0,d)}function s(d){return De(void 0,{},[],void 0,d)}function a(d,p){return function(){if(--p===0){let w=i.parentNode(d);i.removeChild(w,d)}}}function l(d,p){var v,w,x,A;let C,P=d.data;if(P!==void 0){let y=(v=P.hook)===null||v===void 0?void 0:v.init;j(y)&&(y(d),P=d.data)}let _=d.children,q=d.sel;if(q==="!")Gr(d.text)&&(d.text=""),d.elm=i.createComment(d.text);else if(q!==void 0){let y=q.indexOf("#"),T=q.indexOf(".",y),R=y>0?y:q.length,N=T>0?T:q.length,I=y!==-1||T!==-1?q.slice(0,Math.min(R,N)):q,X=d.elm=j(P)&&j(C=P.ns)?i.createElementNS(C,I,P):i.createElement(I,P);for(R<N&&X.setAttribute("id",q.slice(R+1,N)),T>0&&X.setAttribute("class",q.slice(N+1).replace(/\./g," ")),C=0;C<n.create.length;++C)n.create[C](Wr,d);if(it(_))for(C=0;C<_.length;++C){let en=_[C];en!=null&&i.appendChild(X,l(en,p))}else $e(d.text)&&i.appendChild(X,i.createTextNode(d.text));let ct=d.data.hook;j(ct)&&((w=ct.create)===null||w===void 0||w.call(ct,Wr,d),ct.insert&&p.push(d))}else if(!((x=r?.experimental)===null||x===void 0)&&x.fragments&&d.children){for(d.elm=((A=i.createDocumentFragment)!==null&&A!==void 0?A:na)(),C=0;C<n.create.length;++C)n.create[C](Wr,d);for(C=0;C<d.children.length;++C){let y=d.children[C];y!=null&&i.appendChild(d.elm,l(y,p))}}else d.elm=i.createTextNode(d.text);return d.elm}function c(d,p,v,w,x,A){for(;w<=x;++w){let C=v[w];C!=null&&i.insertBefore(d,l(C,A),p)}}function h(d){var p,v;let w=d.data;if(w!==void 0){(v=(p=w?.hook)===null||p===void 0?void 0:p.destroy)===null||v===void 0||v.call(p,d);for(let x=0;x<n.destroy.length;++x)n.destroy[x](d);if(d.children!==void 0)for(let x=0;x<d.children.length;++x){let A=d.children[x];A!=null&&typeof A!="string"&&h(A)}}}function f(d,p,v,w){for(var x,A;v<=w;++v){let C,P,_=p[v];if(_!=null)if(j(_.sel)){h(_),C=n.remove.length+1,P=a(_.elm,C);for(let y=0;y<n.remove.length;++y)n.remove[y](_,P);let q=(A=(x=_?.data)===null||x===void 0?void 0:x.hook)===null||A===void 0?void 0:A.remove;j(q)?q(_,P):P()}else _.children?(h(_),f(d,_.children,0,_.children.length-1)):i.removeChild(d,_.elm)}}function g(d,p,v,w){let x=0,A=0,C=p.length-1,P=p[0],_=p[C],q=v.length-1,y=v[0],T=v[q],R,N,I,X;for(;x<=C&&A<=q;)P==null?P=p[++x]:_==null?_=p[--C]:y==null?y=v[++A]:T==null?T=v[--q]:ot(P,y)?(m(P,y,w),P=p[++x],y=v[++A]):ot(_,T)?(m(_,T,w),_=p[--C],T=v[--q]):ot(P,T)?(m(P,T,w),i.insertBefore(d,P.elm,i.nextSibling(_.elm)),P=p[++x],T=v[--q]):ot(_,y)?(m(_,y,w),i.insertBefore(d,_.elm,P.elm),_=p[--C],y=v[++A]):(R===void 0&&(R=sa(p,x,C)),N=R[y.key],Gr(N)?i.insertBefore(d,l(y,w),P.elm):(I=p[N],I.sel!==y.sel?i.insertBefore(d,l(y,w),P.elm):(m(I,y,w),p[N]=void 0,i.insertBefore(d,I.elm,P.elm))),y=v[++A]);A<=q&&(X=v[q+1]==null?null:v[q+1].elm,c(d,X,v,A,q,w)),x<=C&&f(d,p,x,C)}function m(d,p,v){var w,x,A,C,P,_,q,y;let T=(w=p.data)===null||w===void 0?void 0:w.hook;(x=T?.prepatch)===null||x===void 0||x.call(T,d,p);let R=p.elm=d.elm;if(d===p)return;if(p.data!==void 0||j(p.text)&&p.text!==d.text){(A=p.data)!==null&&A!==void 0||(p.data={}),(C=d.data)!==null&&C!==void 0||(d.data={});for(let X=0;X<n.update.length;++X)n.update[X](d,p);(q=(_=(P=p.data)===null||P===void 0?void 0:P.hook)===null||_===void 0?void 0:_.update)===null||q===void 0||q.call(_,d,p)}let N=d.children,I=p.children;Gr(p.text)?j(N)&&j(I)?N!==I&&g(R,N,I,v):j(I)?(j(d.text)&&i.setTextContent(R,""),c(R,null,I,0,I.length-1,v)):j(N)?f(R,N,0,N.length-1):j(d.text)&&i.setTextContent(R,""):d.text!==p.text&&(j(N)&&f(R,N,0,N.length-1),i.setTextContent(R,p.text)),(y=T?.postpatch)===null||y===void 0||y.call(T,d,p)}return function(p,v){let w,x,A,C=[];for(w=0;w<n.pre.length;++w)n.pre[w]();for(ia(i,p)?p=o(p):oa(i,p)&&(p=s(p)),ot(p,v)?m(p,v,C):(x=p.elm,A=i.parentNode(x),l(v,C),A!==null&&(i.insertBefore(A,v.elm,i.nextSibling(x)),f(A,[p],0,0))),w=0;w<C.length;++w)C[w].data.hook.insert(C[w]);for(w=0;w<n.post.length;++w)n.post[w]();return v}}function Ri(e,t,r){if(e.ns="http://www.w3.org/2000/svg",r!=="foreignObject"&&t!==void 0)for(let n=0;n<t.length;++n){let i=t[n];if(typeof i=="string")continue;let o=i.data;o!==void 0&&Ri(o,i.children,i.sel)}}function S(e,t,r){let n={},i,o,s;if(r!==void 0?(t!==null&&(n=t),it(r)?i=r:$e(r)?o=r.toString():r&&r.sel&&(i=[r])):t!=null&&(it(t)?i=t:$e(t)?o=t.toString():t&&t.sel?i=[t]:n=t),i!==void 0)for(s=0;s<i.length;++s)$e(i[s])&&(i[s]=De(void 0,void 0,void 0,i[s],void 0));return e[0]==="s"&&e[1]==="v"&&e[2]==="g"&&(e.length===3||e[3]==="."||e[3]==="#")&&Ri(n,i,e),De(e,n,i,o,void 0)}var ca="http://www.w3.org/1999/xlink",la="http://www.w3.org/XML/1998/namespace";function Oi(e,t){let r,n=t.elm,i=e.data.attrs,o=t.data.attrs;if(!(!i&&!o)&&i!==o){i=i||{},o=o||{};for(r in o){let s=o[r];i[r]!==s&&(s===!0?n.setAttribute(r,""):s===!1?n.removeAttribute(r):r.charCodeAt(0)!==120?n.setAttribute(r,s):r.charCodeAt(3)===58?n.setAttributeNS(la,r,s):r.charCodeAt(5)===58?n.setAttributeNS(ca,r,s):n.setAttribute(r,s))}for(r in i)r in o||n.removeAttribute(r)}}var jr={create:Oi,update:Oi};function Di(e,t){let r,n,i=t.elm,o=e.data.class,s=t.data.class;if(!(!o&&!s)&&o!==s){o=o||{},s=s||{};for(n in o)o[n]&&!Object.prototype.hasOwnProperty.call(s,n)&&i.classList.remove(n);for(n in s)r=s[n],r!==o[n]&&i.classList[r?"add":"remove"](n)}}var Yr={create:Di,update:Di};var Bi=e=>{let t=Zr[e];return t?S("nag",{attrs:{title:t.name}},t.symbol):void 0},Zr={1:{symbol:"!",name:"Good move"},2:{symbol:"?",name:"Mistake"},3:{symbol:"!!",name:"Brilliant move"},4:{symbol:"??",name:"Blunder"},5:{symbol:"!?",name:"Interesting move"},6:{symbol:"?!",name:"Dubious move"},7:{symbol:"\u25A1",name:"Only move"},22:{symbol:"\u2A00",name:"Zugzwang"},10:{symbol:"=",name:"Equal position"},13:{symbol:"\u221E",name:"Unclear position"},14:{symbol:"\u2A72",name:"White is slightly better"},15:{symbol:"\u2A71",name:"Black is slightly better"},16:{symbol:"\xB1",name:"White is better"},17:{symbol:"\u2213",name:"Black is better"},18:{symbol:"+\u2212",name:"White is winning"},19:{symbol:"-+",name:"Black is winning"},146:{symbol:"N",name:"Novelty"},32:{symbol:"\u2191\u2191",name:"Development"},36:{symbol:"\u2191",name:"Initiative"},40:{symbol:"\u2192",name:"Attack"},132:{symbol:"\u21C6",name:"Counterplay"},138:{symbol:"\u2295",name:"Time trouble"},44:{symbol:"=\u221E",name:"With compensation"},140:{symbol:"\u2206",name:"With the idea"}};function Ii(e,t,r){for(let n of["touchstart","mousedown"])e.addEventListener(n,i=>{t(i),i.preventDefault(),r&&r()},{passive:!1})}var Qr=(e,t,r,n=!0)=>ze(i=>i.addEventListener(e,o=>{let s=t(o);return s===!1&&o.preventDefault(),r?.(),s},{passive:n}));function ze(e){return{insert:t=>e(t.elm)}}var st=e=>{if(!e&&e!==0)return["-"];let t=new Date(e*1e3),r=":",n=Li(t.getUTCMinutes())+r+Li(t.getUTCSeconds());return e>=3600?[Math.floor(e/3600)+r+n]:[n]},Li=e=>(e<10?"0":"")+e,Ki=(e,t,r,n)=>{let i=`${t.toUpperCase()}${r}`;if(!n)return`${i} ${e("aria.empty")}`;let o=e(`aria.piece.${n.role}`);return`${i} ${e(`aria.${n.color}`)} ${o}`},Vt=(e,t,r)=>{let n=r?ua(e,r):e;if(t&&t.length>0){let i=t.map(o=>Zr[o]?.name).filter(o=>o).join(", ");i&&(n+=`, ${i}`)}return n},ua=(e,t)=>e.split("").map(r=>{if(r==="x")return t("san.takes");if(r==="+")return t("san.check");if(r==="#")return t("san.checkmate");if(r==="=")return t("san.promotesTo");if(r==="@")return t("san.droppedOn");let n=r.charCodeAt(0);return n>48&&n<58?r:n>96&&n<105?r.toUpperCase():r==="K"?t("aria.piece.king"):r==="Q"?t("aria.piece.queen"):r==="R"?t("aria.piece.rook"):r==="B"?t("aria.piece.bishop"):r==="N"?t("aria.piece.knight"):r==="O"?"O":r}).join(" ").replace("O - O - O",t("san.longCastling")).replace("O - O",t("san.shortCastling"));function Fi(e){let t=0;return r=>{t+=r.deltaY*(r.deltaMode?40:1),Math.abs(t)>=4?(e(r,!0),t=0):e(r,!1)}}function $i(e,t){let r=()=>{e(),n=Math.max(100,n-n/15),i=setTimeout(r,n)},n=350,i=setTimeout(r,500);e();let o=t.type=="touchstart"?"touchend":"mouseup";document.addEventListener(o,()=>clearTimeout(i),{once:!0})}var ha=e=>e.altKey||e.ctrlKey||e.shiftKey||e.metaKey||document.activeElement instanceof HTMLInputElement||document.activeElement instanceof HTMLTextAreaElement,zi=e=>t=>{ha(t)||(t.key=="ArrowLeft"?e.goTo("prev"):t.key=="ArrowRight"?e.goTo("next"):t.key=="f"&&e.flip())};var Vi=e=>S("div.lpv__menu.lpv__pane",{attrs:{role:"menu","aria-label":e.translate("menu")??"Menu"},hook:{insert:t=>{let r=t.elm;r.querySelector('[role="menuitem"]')?.focus(),pa(e,r)}}},[S("button.lpv__menu__entry.lpv__menu__flip.lpv__fbt",{attrs:{role:"menuitem"},hook:Qr("click",e.flip)},e.translate("flipTheBoard")),e.opts.menu.analysisBoard?.enabled?S("a.lpv__menu__entry.lpv__menu__analysis.lpv__fbt",{attrs:{role:"menuitem",href:e.analysisUrl(),target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",e.translate("analysisBoard"))}},e.translate("analysisBoard")):void 0,e.opts.menu.practiceWithComputer?.enabled?S("a.lpv__menu__entry.lpv__menu__practice.lpv__fbt",{attrs:{role:"menuitem",href:e.practiceUrl(),target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",e.translate("practiceWithComputer"))}},e.translate("practiceWithComputer")):void 0,e.opts.menu.getPgn.enabled?S("button.lpv__menu__entry.lpv__menu__pgn.lpv__fbt",{attrs:{role:"menuitem"},hook:Qr("click",e.togglePgn)},e.translate("getPgn")):void 0,da(e)]),da=e=>{let t=e.game.metadata.externalLink,r=e.translate(e.game.metadata.isLichess?"viewOnLichess":"viewOnSite");return t&&S("a.lpv__menu__entry.lpv__fbt",{attrs:{role:"menuitem",href:t,target:"_blank","aria-label":e.translate("aria.linkOpensInNewTab",r)}},r)},Hi=e=>S("div.lpv__controls",{attrs:{role:"navigation","aria-label":e.translate("aria.navigationControls")}},[e.pane=="board"?void 0:Ht(e,"first","step-backward"),Ht(e,"prev","left-open"),S("button.lpv__fbt.lpv__controls__menu.lpv__icon",{class:{active:e.pane!="board","lpv__icon-ellipsis-vert":e.pane=="board"},hook:{insert:t=>{let r=t.elm;r.addEventListener("click",e.toggleMenu),e.menuButton=r}},attrs:{"aria-label":e.translate("menu"),"aria-expanded":String(e.pane==="menu"),"aria-haspopup":"menu"}},e.pane=="board"?void 0:"X"),Ht(e,"next","right-open"),e.pane=="board"?void 0:Ht(e,"last","step-forward")]),Ht=(e,t,r)=>{let n=e.pane=="board"&&!e.canGoTo(t);return S(`button.lpv__controls__goto.lpv__controls__goto--${t}.lpv__fbt.lpv__icon.lpv__icon-${r}`,{class:{disabled:n},hook:ze(i=>Ii(i,o=>$i(()=>e.goTo(t),o))),attrs:{"aria-label":e.translate(`aria.${t}`),"aria-disabled":String(n),disabled:n}})},pa=(e,t)=>{let r=n=>{switch(n.key){case"Enter":case" ":n.preventDefault(),document.activeElement?.click();break;case"Escape":n.preventDefault(),e.toggleMenu();break}};t.addEventListener("keydown",r)};var at={"aria-hidden":!0},Gt={role:"presentation","aria-hidden":"true"},Gi=e=>{let t=e.curData();if(!Rt(t))return"";let r=Math.ceil(t.ply/2),n=t.ply%2===1?"white":"black",i=t.san,o=e.translate("aria.move",r.toString(),e.translate(`aria.${n}`),Vt(i,t.nags,e.translate)),s=t.clocks&&t.clocks[n==="white"?"white":"black"];if(s!==void 0&&e.opts.showClocks){let l=st(s).join("");l!=="-"&&(o+=", "+e.translate("aria.remaining",l))}let a=t.comments.join(" ").trim();return a&&(o+=`. ${a}`),o},Wi=e=>{let t=e.game,r=a=>{let l=a.name||e.translate("aria.unknownPlayer");return a.title&&(l=`${a.title} ${l}`),a.rating&&(l=`${l}, ${e.translate("aria.rated",a.rating.toString())}`),l},n=a=>!a||a==="*"?e.translate("aria.gameInProgress"):a==="1-0"?e.translate("aria.whitesWin"):a==="0-1"?e.translate("aria.blacksWin"):a==="1/2-1/2"?e.translate("aria.draw"):a,i=r(t.players.white),o=r(t.players.black),s=n(t.metadata.result);return e.translate("aria.chessGameBetween",i,o,s)};var ji=e=>S("div.lpv__side",[S("div.lpv__moves",{attrs:{role:"complementary","aria-label":e.translate("aria.gameMoves")},hook:{insert:t=>{let r=t.elm;e.path.empty()||Ui(e,r),r.addEventListener("click",n=>{let i=n.target.getAttribute("data-path");i&&e.toPath(new re(i))},{passive:!0})},postpatch:(t,r)=>{e.autoScrollRequested&&(Ui(e,r.elm),e.autoScrollRequested=!1)}}},[...e.game.initial.comments.map(Ut),...ka(e),...fa(e)])]),fa=e=>{let t=e.game.metadata.result;return t&&t!="*"?[S("comment.result",{attrs:{role:"note","aria-label":e.translate("aria.gameResult")}},e.game.metadata.result)]:[]},Xr=()=>S("button.move.empty",{attrs:{"aria-hidden":"true",disabled:!0}},"..."),Jr=e=>S("index",{attrs:Gt},`${e}.`),Ut=e=>S("comment",{attrs:{role:"note"}},e),ma=()=>S("paren.open",{attrs:at},"("),ga=()=>S("paren.close",{attrs:at},")"),Wt=e=>Math.floor((e.ply-1)/2)+1,ka=e=>{let t=wa(e),r=[],n,i=e.game.moves.children.slice(1);for(e.game.initial.pos.turn=="black"&&e.game.mainline[0]&&r.push(Jr(e.game.initial.pos.fullmoves),Xr());n=(n||e.game.moves).children[0];){let o=n.data,s=o.ply%2==1;s&&r.push(Jr(Wt(o))),r.push(t(o));let a=s&&(i.length||o.comments.length)&&n.children.length;a&&r.push(Xr()),o.comments.forEach(l=>r.push(Ut(l))),i.forEach(l=>r.push(ba(e.translate,t,l))),a&&r.push(Jr(Wt(o)),Xr()),i=n.children.slice(1)}return r},ba=(e,t,r)=>S("variation",{attrs:{role:"group","aria-label":e("aria.variation")}},[...r.data.startingComments.map(Ut),...Yi(t,r)]),Yi=(e,t)=>{let r=[],n=[];t.data.ply%2==0&&r.push(S("index",{attrs:Gt},[Wt(t.data),"..."]));do{let i=t.data;i.ply%2==1&&r.push(S("index",{attrs:Gt},[Wt(i),"."])),r.push(e(i)),i.comments.forEach(o=>r.push(Ut(o))),n.forEach(o=>{r=[...r,ma(),...Yi(e,o),ga()]}),n=t.children.slice(1),t=t.children[0]}while(t);return r},wa=e=>t=>S("button.move",{class:{current:e.path.equals(t.path),ancestor:e.path.contains(t.path),good:t.nags.includes(1),mistake:t.nags.includes(2),brilliant:t.nags.includes(3),blunder:t.nags.includes(4),interesting:t.nags.includes(5),inaccuracy:t.nags.includes(6)},attrs:{"data-path":t.path.path,role:"button","aria-label":e.translate("aria.move",Math.ceil(t.ply/2).toString(),e.translate(`aria.${t.ply%2===1?"white":"black"}`),Vt(t.san,t.nags,e.translate))}},[t.san,...t.nags.map(Bi)]),Ui=(e,t)=>{let r=t.querySelector(".current");if(!r){t.scrollTop=e.path.empty()?0:99999;return}t.scrollTop=r.offsetTop-t.offsetHeight/2+r.offsetHeight};function jt(e,t){let r=t=="bottom"?e.orientation():M(e.orientation()),n=e.game.players[r],i=[n.title?S("span.lpv__player__title",n.title):void 0,S("span.lpv__player__name",n.name),n.rating?S("span.lpv__player__rating",["(",n.rating,")"]):void 0];return S(`div.lpv__player.lpv__player--${t}`,[n.isLichessUser&&n.name?S("a.lpv__player__person.ulpt.user-link",{attrs:{href:`${e.opts.lichess}/@/${n.name}`,"aria-label":e.translate("aria.viewProfileOnLichess",n.name)}},i):S("span.lpv__player__person",i),e.opts.showClocks?va(e,r):void 0])}var va=(e,t)=>{let r=e.curData(),n=r.clocks&&r.clocks[t];return typeof n==null?void 0:S("div.lpv__player__clock",{class:{active:t==r.turn},attrs:{role:"timer","aria-label":st(n).join("")}},st(n))};var Zi=e=>{let t=e.flipped;return S("div.lpv__sr-only",{attrs:{role:"grid","aria-label":e.translate("aria.accessibleChessboard"),"aria-hidden":"false"}},ya(e,t))},ya=(e,t)=>{let r=e.ground?.state.pieces||Fe(e.curData().fen),n=t?Pe:Mt,i=t?[...ue].reverse():ue;return n.map(o=>S("div",{attrs:{role:"row"}},i.map(s=>{let a=`${s}${o}`,l=r.get(a);return xa(e.translate,s,o,l)})))},xa=(e,t,r,n)=>{let i=Ki(e,t,r,n);return S("span",{attrs:{role:"gridcell","aria-label":i}},i)};function Yt(e){let t=e.opts,r=`lpv.lpv--moves-${t.showMoves}.lpv--controls-${t.showControls}${t.classes?"."+t.classes.replace(" ","."):""}`,n=t.showPlayers=="auto"?e.game.hasPlayerName():t.showPlayers;return S(`div.${r}`,{class:{"lpv--menu":e.pane!="board","lpv--players":n},attrs:{role:"region",tabindex:0,"aria-label":Wi(e)},hook:ze(i=>{e.setGround(_i(i.querySelector(".cg-wrap"),Pa(e,i))),t.keyboardToMove&&i.addEventListener("keydown",zi(e))})},[S("div.lpv__sr-only",{attrs:{"aria-live":"polite","aria-atomic":"true"}},Gi(e)),Zi(e),n?jt(e,"top"):void 0,Ca(e),n?jt(e,"bottom"):void 0,t.showControls?Hi(e):void 0,t.showMoves?ji(e):void 0,e.pane=="menu"?Vi(e):e.pane=="pgn"?Sa(e):void 0])}var Ca=e=>S("div.lpv__board",{attrs:at,hook:ze(t=>{t.addEventListener("click",e.focus),e.opts.scrollToMove&&!("ontouchstart"in window)&&t.addEventListener("wheel",Fi((r,n)=>{r.preventDefault(),r.deltaY>0&&n?e.goTo("next",!1):r.deltaY<0&&n&&e.goTo("prev",!1)}))})},S("div.cg-wrap")),Sa=e=>{let t=new Blob([e.opts.pgn],{type:"text/plain"});return S("div.lpv__pgn.lpv__pane",[S("a.lpv__pgn__download.lpv__fbt",{attrs:{href:window.URL.createObjectURL(t),download:e.opts.menu.getPgn.fileName||`${e.game.title()}.pgn`}},e.translate("download")),S("textarea.lpv__pgn__text",e.opts.pgn)])},Pa=(e,t)=>({viewOnly:!e.opts.drawArrows,addDimensionsCssVarsTo:t,drawable:{enabled:e.opts.drawArrows,visible:!0},disableContextMenu:e.opts.drawArrows,...e.opts.chessground||{},movable:{free:!1},draggable:{enabled:!1},selectable:{enabled:!1},...e.cgState()});var Ma={pgn:"*",fen:void 0,showPlayers:"auto",showClocks:!0,showMoves:"auto",showControls:!0,scrollToMove:!0,keyboardToMove:!0,orientation:void 0,initialPly:0,chessground:{},drawArrows:!0,menu:{getPgn:{enabled:!0,fileName:void 0},practiceWithComputer:{enabled:!0},analysisBoard:{enabled:!0}},lichess:"https://lichess.org",classes:void 0};function Xi(e,t){let r={...Ma};return Ji(r,t),r.fen&&(r.pgn=`[FEN "${r.fen}"]
|
|
4
|
+
${r.pgn}`),r.classes||(r.classes=e.className),r}function Ji(e,t){for(let r in t)typeof t[r]<"u"&&(Qi(e[r])&&Qi(t[r])?Ji(e[r],t[r]):e[r]=t[r])}function Qi(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ea(e,t){let r=Ur([Yr,jr]),n=Xi(e,t),i=new Je(n,a),o=Yt(i);e.innerHTML="";let s=r(e,o);i.div=s.elm;function a(){s=r(s,Yt(i))}return i}export{Ea as default};
|
package/dist/pgnViewer.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Api as CgApi } from 'chessground/api';
|
|
1
|
+
import { Api as CgApi } from '@lichess-org/chessground/api';
|
|
2
2
|
import { GoTo, InitialOrMove, Opts, Translate } from './interfaces';
|
|
3
|
-
import { Config as CgConfig } from 'chessground/config';
|
|
3
|
+
import { Config as CgConfig } from '@lichess-org/chessground/config';
|
|
4
4
|
import { Path } from './path';
|
|
5
5
|
import { AnyNode, Game } from './game';
|
|
6
6
|
export default class PgnViewer {
|