jev-chess 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/ARCHITECTURE.md +148 -0
  2. package/README.md +109 -0
  3. package/dist/chessEngine.d.ts +36 -0
  4. package/dist/chessEngine.d.ts.map +1 -0
  5. package/dist/chessEngine.js +173 -0
  6. package/dist/chessEngine.js.map +1 -0
  7. package/dist/classicMatches.d.ts +50 -0
  8. package/dist/classicMatches.d.ts.map +1 -0
  9. package/dist/classicMatches.js +223 -0
  10. package/dist/classicMatches.js.map +1 -0
  11. package/dist/demo.d.ts +2 -0
  12. package/dist/demo.d.ts.map +1 -0
  13. package/dist/demo.js +142 -0
  14. package/dist/demo.js.map +1 -0
  15. package/dist/gameReviewer.d.ts +11 -0
  16. package/dist/gameReviewer.d.ts.map +1 -0
  17. package/dist/gameReviewer.js +89 -0
  18. package/dist/gameReviewer.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +9 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/moveEvaluator.d.ts +11 -0
  24. package/dist/moveEvaluator.d.ts.map +1 -0
  25. package/dist/moveEvaluator.js +103 -0
  26. package/dist/moveEvaluator.js.map +1 -0
  27. package/dist/moveResolver.d.ts +15 -0
  28. package/dist/moveResolver.d.ts.map +1 -0
  29. package/dist/moveResolver.js +97 -0
  30. package/dist/moveResolver.js.map +1 -0
  31. package/dist/personaEngine.d.ts +15 -0
  32. package/dist/personaEngine.d.ts.map +1 -0
  33. package/dist/personaEngine.js +151 -0
  34. package/dist/personaEngine.js.map +1 -0
  35. package/dist/server.d.ts +2 -0
  36. package/dist/server.d.ts.map +1 -0
  37. package/dist/server.js +1490 -0
  38. package/dist/server.js.map +1 -0
  39. package/dist/typeSafeClient.d.ts +13 -0
  40. package/dist/typeSafeClient.d.ts.map +1 -0
  41. package/dist/typeSafeClient.js +336 -0
  42. package/dist/typeSafeClient.js.map +1 -0
  43. package/dist/types.d.ts +100 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +5 -0
  46. package/dist/types.js.map +1 -0
  47. package/dist/web/main.d.ts +2 -0
  48. package/dist/web/main.d.ts.map +1 -0
  49. package/dist/web/main.js +620 -0
  50. package/dist/web/main.js.map +1 -0
  51. package/package.json +35 -0
  52. package/public/app.js +45 -0
  53. package/public/index.html +790 -0
  54. package/src/chessEngine.ts +191 -0
  55. package/src/classicMatches.ts +291 -0
  56. package/src/demo.ts +160 -0
  57. package/src/gameReviewer.ts +113 -0
  58. package/src/index.ts +8 -0
  59. package/src/moveEvaluator.ts +122 -0
  60. package/src/moveResolver.ts +120 -0
  61. package/src/personaEngine.ts +193 -0
  62. package/src/server.ts +1509 -0
  63. package/src/typeSafeClient.ts +321 -0
  64. package/src/types.ts +118 -0
  65. package/src/web/main.ts +615 -0
  66. package/tests/chess.test.ts +206 -0
  67. package/tsconfig.json +21 -0
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "jev-chess",
3
+ "version": "1.0.0",
4
+ "description": "Designing Chess Moves and Games with TypeSafe AI (System One / Jev)",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "build:web": "esbuild src/web/main.ts --bundle --minify --format=iife --outfile=public/app.js",
10
+ "test": "vitest run",
11
+ "demo": "tsx src/demo.ts",
12
+ "serve": "tsx src/server.ts",
13
+ "typecheck": "tsc --noEmit"
14
+ },
15
+ "keywords": [
16
+ "typesafe-ai",
17
+ "jev",
18
+ "chess",
19
+ "system-one",
20
+ "composite-scoring",
21
+ "intent-routing"
22
+ ],
23
+ "author": "Antigravity Pair Programmer",
24
+ "license": "MIT",
25
+ "dependencies": {
26
+ "@typesafe-ai/sdk": "^0.6.0",
27
+ "chess.js": "^1.4.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^26.6.2",
31
+ "tsx": "^4.23.13",
32
+ "typescript": "^7.0.2",
33
+ "vitest": "^4.1.11"
34
+ }
35
+ }
package/public/app.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";(()=>{function wn(s){return s!==null?{comment:s,variations:[]}:{variations:[]}}function xn(s,e,t,n,i){let r={move:s,variations:i};return e&&(r.suffix=e),t&&(r.nag=t),n!==null&&(r.comment=n),r}function Sn(...s){let[e,...t]=s,n=e;for(let i of t)i!==null&&(n.variations=[i,...i.variations],i.variations=[],n=i);return e}function kn(s,e){if(e.marker&&e.marker.comment){let t=e.root;for(;;){let n=t.variations[0];if(!n){t.comment=e.marker.comment;break}t=n}}return{headers:s,root:e.root,result:(e.marker&&e.marker.result)??void 0}}function Cn(s,e){function t(){this.constructor=s}t.prototype=e.prototype,s.prototype=new t}function ge(s,e,t,n){var i=Error.call(this,s);return Object.setPrototypeOf&&Object.setPrototypeOf(i,ge.prototype),i.expected=e,i.found=t,i.location=n,i.name="SyntaxError",i}Cn(ge,Error);function Xe(s,e,t){return t=t||" ",s.length>e?s:(e-=s.length,t+=t.repeat(e),s+t.slice(0,e))}ge.prototype.format=function(s){var e="Error: "+this.message;if(this.location){var t=null,n;for(n=0;n<s.length;n++)if(s[n].source===this.location.source){t=s[n].text.split(/\r\n|\n|\r/g);break}var i=this.location.start,r=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(i):i,a=this.location.source+":"+r.line+":"+r.column;if(t){var o=this.location.end,l=Xe("",r.line.toString().length," "),f=t[i.line-1],m=i.line===o.line?o.column:f.length+1,g=m-i.column||1;e+=`
2
+ --> `+a+`
3
+ `+l+` |
4
+ `+r.line+" | "+f+`
5
+ `+l+" | "+Xe("",i.column-1," ")+Xe("",g,"^")}else e+=`
6
+ at `+a}return e};ge.buildMessage=function(s,e){var t={literal:function(f){return'"'+i(f.text)+'"'},class:function(f){var m=f.parts.map(function(g){return Array.isArray(g)?r(g[0])+"-"+r(g[1]):r(g)});return"["+(f.inverted?"^":"")+m.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(f){return f.description}};function n(f){return f.charCodeAt(0).toString(16).toUpperCase()}function i(f){return f.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(m){return"\\x0"+n(m)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(m){return"\\x"+n(m)})}function r(f){return f.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(m){return"\\x0"+n(m)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(m){return"\\x"+n(m)})}function a(f){return t[f.type](f)}function o(f){var m=f.map(a),g,p;if(m.sort(),m.length>0){for(g=1,p=1;g<m.length;g++)m[g-1]!==m[g]&&(m[p]=m[g],p++);m.length=p}switch(m.length){case 1:return m[0];case 2:return m[0]+" or "+m[1];default:return m.slice(0,-1).join(", ")+", or "+m[m.length-1]}}function l(f){return f?'"'+i(f)+'"':"end of input"}return"Expected "+o(s)+" but "+l(e)+" found."};function Mn(s,e){e=e!==void 0?e:{};var t={},n=e.grammarSource,i={pgn:Lt},r=Lt,a="[",o='"',l="]",f=".",m="O-O-O",g="O-O",p="0-0-0",v="0-0",x="$",_="{",M="}",Q=";",U="(",X=")",A="1-0",H="0-1",C="1/2-1/2",bs="*",Ve=/^[a-zA-Z]/,_t=/^[^"]/,Me=/^[0-9]/,bt=/^[.]/,Et=/^[a-zA-Z1-8\-=]/,Es=/^[+#]/,wt=/^[!?]/,xt=/^[^}]/,St=/^[^\r\n]/,kt=/^[ \t\r\n]/,ws=G("tag pair"),xs=B("[",!1),Ct=B('"',!1),Ss=B("]",!1),ks=G("tag name"),Je=V([["a","z"],["A","Z"]],!1,!1),Cs=G("tag value"),Mt=V(['"'],!0,!1),Ms=G("move number"),Ae=V([["0","9"]],!1,!1),As=B(".",!1),At=V(["."],!1,!1),Ts=G("standard algebraic notation"),Is=B("O-O-O",!1),Ps=B("O-O",!1),$s=B("0-0-0",!1),Ns=B("0-0",!1),Tt=V([["a","z"],["A","Z"],["1","8"],"-","="],!1,!1),Bs=V(["+","#"],!1,!1),Rs=G("suffix annotation"),It=V(["!","?"],!1,!1),Ls=G("NAG"),Os=B("$",!1),Ks=G("brace comment"),qs=B("{",!1),Pt=V(["}"],!0,!1),Fs=B("}",!1),Ds=G("rest of line comment"),Qs=B(";",!1),$t=V(["\r",`
7
+ `],!0,!1),Us=G("variation"),Hs=B("(",!1),js=B(")",!1),Ws=G("game termination marker"),Gs=B("1-0",!1),Ys=B("0-1",!1),Vs=B("1/2-1/2",!1),Js=B("*",!1),zs=G("whitespace"),Nt=V([" "," ","\r",`
8
+ `],!1,!1),Xs=function(c,h){return kn(c,h)},Zs=function(c){return Object.fromEntries(c)},en=function(c,h){return[c,h]},tn=function(c,h){return{root:c,marker:h}},sn=function(c,h){return Sn(wn(c),...h.flat())},nn=function(c,h,d,E,w){return xn(c,h,d,E,w)},rn=function(c){return c},on=function(c){return c.replace(/[\r\n]+/g," ")},an=function(c){return c.trim()},cn=function(c){return c},ln=function(c,h){return{result:c,comment:h}},u=e.peg$currPos|0,pe=[{line:1,column:1}],Y=u,Te=e.peg$maxFailExpected||[],y=e.peg$silentFails|0,ye;if(e.startRule){if(!(e.startRule in i))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');r=i[e.startRule]}function B(c,h){return{type:"literal",text:c,ignoreCase:h}}function V(c,h,d){return{type:"class",parts:c,inverted:h,ignoreCase:d}}function fn(){return{type:"end"}}function G(c){return{type:"other",description:c}}function Bt(c){var h=pe[c],d;if(h)return h;if(c>=pe.length)d=pe.length-1;else for(d=c;!pe[--d];);for(h=pe[d],h={line:h.line,column:h.column};d<c;)s.charCodeAt(d)===10?(h.line++,h.column=1):h.column++,d++;return pe[c]=h,h}function Rt(c,h,d){var E=Bt(c),w=Bt(h),T={source:n,start:{offset:c,line:E.line,column:E.column},end:{offset:h,line:w.line,column:w.column}};return T}function b(c){u<Y||(u>Y&&(Y=u,Te=[]),Te.push(c))}function un(c,h,d){return new ge(ge.buildMessage(c,h),c,h,d)}function Lt(){var c,h,d;return c=u,h=hn(),d=mn(),c=Xs(h,d),c}function hn(){var c,h,d;for(c=u,h=[],d=Ot();d!==t;)h.push(d),d=Ot();return d=F(),c=Zs(h),c}function Ot(){var c,h,d,E,w,T,ce;return y++,c=u,F(),s.charCodeAt(u)===91?(h=a,u++):(h=t,y===0&&b(xs)),h!==t?(F(),d=dn(),d!==t?(F(),s.charCodeAt(u)===34?(E=o,u++):(E=t,y===0&&b(Ct)),E!==t?(w=pn(),s.charCodeAt(u)===34?(T=o,u++):(T=t,y===0&&b(Ct)),T!==t?(F(),s.charCodeAt(u)===93?(ce=l,u++):(ce=t,y===0&&b(Ss)),ce!==t?c=en(d,w):(u=c,c=t)):(u=c,c=t)):(u=c,c=t)):(u=c,c=t)):(u=c,c=t),y--,c===t&&y===0&&b(ws),c}function dn(){var c,h,d;if(y++,c=u,h=[],d=s.charAt(u),Ve.test(d)?u++:(d=t,y===0&&b(Je)),d!==t)for(;d!==t;)h.push(d),d=s.charAt(u),Ve.test(d)?u++:(d=t,y===0&&b(Je));else h=t;return h!==t?c=s.substring(c,u):c=h,y--,c===t&&(h=t,y===0&&b(ks)),c}function pn(){var c,h,d;for(y++,c=u,h=[],d=s.charAt(u),_t.test(d)?u++:(d=t,y===0&&b(Mt));d!==t;)h.push(d),d=s.charAt(u),_t.test(d)?u++:(d=t,y===0&&b(Mt));return c=s.substring(c,u),y--,h=t,y===0&&b(Cs),c}function mn(){var c,h,d;return c=u,h=Kt(),F(),d=En(),d===t&&(d=null),F(),c=tn(h,d),c}function Kt(){var c,h,d,E;for(c=u,h=ze(),h===t&&(h=null),d=[],E=qt();E!==t;)d.push(E),E=qt();return c=sn(h,d),c}function qt(){var c,h,d,E,w,T,ce,Ie;if(c=u,F(),gn(),F(),h=vn(),h!==t){for(d=yn(),d===t&&(d=null),E=[],w=Ft();w!==t;)E.push(w),w=Ft();for(w=F(),T=ze(),T===t&&(T=null),ce=[],Ie=Dt();Ie!==t;)ce.push(Ie),Ie=Dt();c=nn(h,d,E,T,ce)}else u=c,c=t;return c}function gn(){var c,h,d,E,w,T;for(y++,c=u,h=[],d=s.charAt(u),Me.test(d)?u++:(d=t,y===0&&b(Ae));d!==t;)h.push(d),d=s.charAt(u),Me.test(d)?u++:(d=t,y===0&&b(Ae));if(s.charCodeAt(u)===46?(d=f,u++):(d=t,y===0&&b(As)),d!==t){for(E=F(),w=[],T=s.charAt(u),bt.test(T)?u++:(T=t,y===0&&b(At));T!==t;)w.push(T),T=s.charAt(u),bt.test(T)?u++:(T=t,y===0&&b(At));h=[h,d,E,w],c=h}else u=c,c=t;return y--,c===t&&(h=t,y===0&&b(Ms)),c}function vn(){var c,h,d,E,w,T;if(y++,c=u,h=u,s.substr(u,5)===m?(d=m,u+=5):(d=t,y===0&&b(Is)),d===t&&(s.substr(u,3)===g?(d=g,u+=3):(d=t,y===0&&b(Ps)),d===t&&(s.substr(u,5)===p?(d=p,u+=5):(d=t,y===0&&b($s)),d===t&&(s.substr(u,3)===v?(d=v,u+=3):(d=t,y===0&&b(Ns)),d===t))))if(d=u,E=s.charAt(u),Ve.test(E)?u++:(E=t,y===0&&b(Je)),E!==t){if(w=[],T=s.charAt(u),Et.test(T)?u++:(T=t,y===0&&b(Tt)),T!==t)for(;T!==t;)w.push(T),T=s.charAt(u),Et.test(T)?u++:(T=t,y===0&&b(Tt));else w=t;w!==t?(E=[E,w],d=E):(u=d,d=t)}else u=d,d=t;return d!==t?(E=s.charAt(u),Es.test(E)?u++:(E=t,y===0&&b(Bs)),E===t&&(E=null),d=[d,E],h=d):(u=h,h=t),h!==t?c=s.substring(c,u):c=h,y--,c===t&&(h=t,y===0&&b(Ts)),c}function yn(){var c,h,d;for(y++,c=u,h=[],d=s.charAt(u),wt.test(d)?u++:(d=t,y===0&&b(It));d!==t;)h.push(d),h.length>=2?d=t:(d=s.charAt(u),wt.test(d)?u++:(d=t,y===0&&b(It)));return h.length<1?(u=c,c=t):c=h,y--,c===t&&(h=t,y===0&&b(Rs)),c}function Ft(){var c,h,d,E,w;if(y++,c=u,F(),s.charCodeAt(u)===36?(h=x,u++):(h=t,y===0&&b(Os)),h!==t){if(d=u,E=[],w=s.charAt(u),Me.test(w)?u++:(w=t,y===0&&b(Ae)),w!==t)for(;w!==t;)E.push(w),w=s.charAt(u),Me.test(w)?u++:(w=t,y===0&&b(Ae));else E=t;E!==t?d=s.substring(d,u):d=E,d!==t?c=rn(d):(u=c,c=t)}else u=c,c=t;return y--,c===t&&y===0&&b(Ls),c}function ze(){var c;return c=_n(),c===t&&(c=bn()),c}function _n(){var c,h,d,E,w;if(y++,c=u,s.charCodeAt(u)===123?(h=_,u++):(h=t,y===0&&b(qs)),h!==t){for(d=u,E=[],w=s.charAt(u),xt.test(w)?u++:(w=t,y===0&&b(Pt));w!==t;)E.push(w),w=s.charAt(u),xt.test(w)?u++:(w=t,y===0&&b(Pt));d=s.substring(d,u),s.charCodeAt(u)===125?(E=M,u++):(E=t,y===0&&b(Fs)),E!==t?c=on(d):(u=c,c=t)}else u=c,c=t;return y--,c===t&&(h=t,y===0&&b(Ks)),c}function bn(){var c,h,d,E,w;if(y++,c=u,s.charCodeAt(u)===59?(h=Q,u++):(h=t,y===0&&b(Qs)),h!==t){for(d=u,E=[],w=s.charAt(u),St.test(w)?u++:(w=t,y===0&&b($t));w!==t;)E.push(w),w=s.charAt(u),St.test(w)?u++:(w=t,y===0&&b($t));d=s.substring(d,u),c=an(d)}else u=c,c=t;return y--,c===t&&(h=t,y===0&&b(Ds)),c}function Dt(){var c,h,d,E;return y++,c=u,F(),s.charCodeAt(u)===40?(h=U,u++):(h=t,y===0&&b(Hs)),h!==t?(d=Kt(),d!==t?(F(),s.charCodeAt(u)===41?(E=X,u++):(E=t,y===0&&b(js)),E!==t?c=cn(d):(u=c,c=t)):(u=c,c=t)):(u=c,c=t),y--,c===t&&y===0&&b(Us),c}function En(){var c,h,d;return y++,c=u,s.substr(u,3)===A?(h=A,u+=3):(h=t,y===0&&b(Gs)),h===t&&(s.substr(u,3)===H?(h=H,u+=3):(h=t,y===0&&b(Ys)),h===t&&(s.substr(u,7)===C?(h=C,u+=7):(h=t,y===0&&b(Vs)),h===t&&(s.charCodeAt(u)===42?(h=bs,u++):(h=t,y===0&&b(Js))))),h!==t?(F(),d=ze(),d===t&&(d=null),c=ln(h,d)):(u=c,c=t),y--,c===t&&(h=t,y===0&&b(Ws)),c}function F(){var c,h;for(y++,c=[],h=s.charAt(u),kt.test(h)?u++:(h=t,y===0&&b(Nt));h!==t;)c.push(h),h=s.charAt(u),kt.test(h)?u++:(h=t,y===0&&b(Nt));return y--,h=t,y===0&&b(zs),c}if(ye=r(),e.peg$library)return{peg$result:ye,peg$currPos:u,peg$FAILED:t,peg$maxFailExpected:Te,peg$maxFailPos:Y};if(ye!==t&&u===s.length)return ye;throw ye!==t&&u<s.length&&b(fn()),un(Te,Y<s.length?s.charAt(Y):null,Y<s.length?Rt(Y,Y+1):Rt(Y,Y))}var $e=0xffffffffffffffffn;function Ze(s,e){return(s<<e|s>>64n-e)&0xffffffffffffffffn}function Qt(s,e){return s*e&$e}function An(s){return function(){let e=BigInt(s&$e),t=BigInt(s>>64n&$e),n=Qt(Ze(Qt(e,5n),7n),9n);return t^=e,e=(Ze(e,24n)^t^t<<16n)&$e,t=Ze(t,37n),s=t<<64n|e,n}}var Re=An(0xa187eb39cdcaed8f31c4b365b102e01en),Tn=Array.from({length:2},()=>Array.from({length:6},()=>Array.from({length:128},()=>Re()))),In=Array.from({length:8},()=>Re()),Pn=Array.from({length:16},()=>Re()),et=Re(),K="w",j="b",$="p",rt="n",Ne="b",be="r",ne="q",N="k",tt="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",me=class{color;from;to;piece;captured;promotion;flags;san;lan;before;after;constructor(e,t){let{color:n,piece:i,from:r,to:a,flags:o,captured:l,promotion:f}=t,m=R(r),g=R(a);this.color=n,this.piece=i,this.from=m,this.to=g,this.san=e._moveToSan(t,e._moves({legal:!0})),this.lan=m+g,this.before=e.fen(),e._makeMove(t),this.after=e.fen(),e._undoMove(),this.flags="";for(let p in k)k[p]&o&&(this.flags+=le[p]);l&&(this.captured=l),f&&(this.promotion=f,this.lan+=f)}isCapture(){return this.flags.indexOf(le.CAPTURE)>-1}isPromotion(){return this.flags.indexOf(le.PROMOTION)>-1}isEnPassant(){return this.flags.indexOf(le.EP_CAPTURE)>-1}isKingsideCastle(){return this.flags.indexOf(le.KSIDE_CASTLE)>-1}isQueensideCastle(){return this.flags.indexOf(le.QSIDE_CASTLE)>-1}isBigPawn(){return this.flags.indexOf(le.BIG_PAWN)>-1}},O=-1,le={NORMAL:"n",CAPTURE:"c",BIG_PAWN:"b",EP_CAPTURE:"e",PROMOTION:"p",KSIDE_CASTLE:"k",QSIDE_CASTLE:"q",NULL_MOVE:"-"};var k={NORMAL:1,CAPTURE:2,BIG_PAWN:4,EP_CAPTURE:8,PROMOTION:16,KSIDE_CASTLE:32,QSIDE_CASTLE:64,NULL_MOVE:128},ot={Event:"?",Site:"?",Date:"????.??.??",Round:"?",White:"?",Black:"?",Result:"*"},$n={WhiteTitle:null,BlackTitle:null,WhiteElo:null,BlackElo:null,WhiteUSCF:null,BlackUSCF:null,WhiteNA:null,BlackNA:null,WhiteType:null,BlackType:null,EventDate:null,EventSponsor:null,Section:null,Stage:null,Board:null,Opening:null,Variation:null,SubVariation:null,ECO:null,NIC:null,Time:null,UTCTime:null,UTCDate:null,TimeControl:null,SetUp:null,FEN:null,Termination:null,Annotator:null,Mode:null,PlyCount:null},Nn={...ot,...$n},S={a8:0,b8:1,c8:2,d8:3,e8:4,f8:5,g8:6,h8:7,a7:16,b7:17,c7:18,d7:19,e7:20,f7:21,g7:22,h7:23,a6:32,b6:33,c6:34,d6:35,e6:36,f6:37,g6:38,h6:39,a5:48,b5:49,c5:50,d5:51,e5:52,f5:53,g5:54,h5:55,a4:64,b4:65,c4:66,d4:67,e4:68,f4:69,g4:70,h4:71,a3:80,b3:81,c3:82,d3:83,e3:84,f3:85,g3:86,h3:87,a2:96,b2:97,c2:98,d2:99,e2:100,f2:101,g2:102,h2:103,a1:112,b1:113,c1:114,d1:115,e1:116,f1:117,g1:118,h1:119},st={b:[16,32,17,15],w:[-16,-32,-17,-15]},Ut={n:[-18,-33,-31,-14,18,33,31,14],b:[-17,-15,17,15],r:[-16,1,16,-1],q:[-17,-16,-15,1,17,16,15,-1],k:[-17,-16,-15,1,17,16,15,-1]},Bn=[20,0,0,0,0,0,0,24,0,0,0,0,0,0,20,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,24,24,24,24,24,24,56,0,56,24,24,24,24,24,24,0,0,0,0,0,0,2,53,56,53,2,0,0,0,0,0,0,0,0,0,0,0,20,2,24,2,20,0,0,0,0,0,0,0,0,0,0,20,0,0,24,0,0,20,0,0,0,0,0,0,0,0,20,0,0,0,24,0,0,0,20,0,0,0,0,0,0,20,0,0,0,0,24,0,0,0,0,20,0,0,0,0,20,0,0,0,0,0,24,0,0,0,0,0,20,0,0,20,0,0,0,0,0,0,24,0,0,0,0,0,0,20],Rn=[17,0,0,0,0,0,0,16,0,0,0,0,0,0,15,0,0,17,0,0,0,0,0,16,0,0,0,0,0,15,0,0,0,0,17,0,0,0,0,16,0,0,0,0,15,0,0,0,0,0,0,17,0,0,0,16,0,0,0,15,0,0,0,0,0,0,0,0,17,0,0,16,0,0,15,0,0,0,0,0,0,0,0,0,0,17,0,16,0,15,0,0,0,0,0,0,0,0,0,0,0,0,17,16,15,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,-15,-16,-17,0,0,0,0,0,0,0,0,0,0,0,0,-15,0,-16,0,-17,0,0,0,0,0,0,0,0,0,0,-15,0,0,-16,0,0,-17,0,0,0,0,0,0,0,0,-15,0,0,0,-16,0,0,0,-17,0,0,0,0,0,0,-15,0,0,0,0,-16,0,0,0,0,-17,0,0,0,0,-15,0,0,0,0,0,-16,0,0,0,0,0,-17,0,0,-15,0,0,0,0,0,0,-16,0,0,0,0,0,0,-17],Ln={p:1,n:2,b:4,r:8,q:16,k:32},On="pnbrqkPNBRQK",Ht=[rt,Ne,be,ne],Kn=7,qn=6,Fn=1,Dn=0,Pe={[N]:k.KSIDE_CASTLE,[ne]:k.QSIDE_CASTLE},te={w:[{square:S.a1,flag:k.QSIDE_CASTLE},{square:S.h1,flag:k.KSIDE_CASTLE}],b:[{square:S.a8,flag:k.QSIDE_CASTLE},{square:S.h8,flag:k.KSIDE_CASTLE}]},Qn={b:Fn,w:qn},nt="--";function fe(s){return s>>4}function Ee(s){return s&15}function Wt(s){return"0123456789".indexOf(s)!==-1}function R(s){let e=Ee(s),t=fe(s);return"abcdefgh".substring(e,e+1)+"87654321".substring(t,t+1)}function _e(s){return s===K?j:K}function Un(s){let e=s.split(/\s+/);if(e.length!==6)return{ok:!1,error:"Invalid FEN: must contain six space-delimited fields"};let t=parseInt(e[5],10);if(isNaN(t)||t<=0)return{ok:!1,error:"Invalid FEN: move number must be a positive integer"};let n=parseInt(e[4],10);if(isNaN(n)||n<0)return{ok:!1,error:"Invalid FEN: half move counter number must be a non-negative integer"};if(!/^(-|[abcdefgh][36])$/.test(e[3]))return{ok:!1,error:"Invalid FEN: en-passant square is invalid"};if(/[^kKqQ-]/.test(e[2]))return{ok:!1,error:"Invalid FEN: castling availability is invalid"};if(!/^(w|b)$/.test(e[1]))return{ok:!1,error:"Invalid FEN: side-to-move is invalid"};let i=e[0].split("/");if(i.length!==8)return{ok:!1,error:"Invalid FEN: piece data does not contain 8 '/'-delimited rows"};for(let a=0;a<i.length;a++){let o=0,l=!1;for(let f=0;f<i[a].length;f++)if(Wt(i[a][f])){if(l)return{ok:!1,error:"Invalid FEN: piece data is invalid (consecutive number)"};o+=parseInt(i[a][f],10),l=!0}else{if(!/^[prnbqkPRNBQK]$/.test(i[a][f]))return{ok:!1,error:"Invalid FEN: piece data is invalid (invalid piece)"};o+=1,l=!1}if(o!==8)return{ok:!1,error:"Invalid FEN: piece data is invalid (too many squares in rank)"}}if(e[3][1]=="3"&&e[1]=="w"||e[3][1]=="6"&&e[1]=="b")return{ok:!1,error:"Invalid FEN: illegal en-passant square"};let r=[{color:"white",regex:/K/g},{color:"black",regex:/k/g}];for(let{color:a,regex:o}of r){if(!o.test(e[0]))return{ok:!1,error:`Invalid FEN: missing ${a} king`};if((e[0].match(o)||[]).length>1)return{ok:!1,error:`Invalid FEN: too many ${a} kings`}}return Array.from(i[0]+i[7]).some(a=>a.toUpperCase()==="P")?{ok:!1,error:"Invalid FEN: some pawns are on the edge rows"}:{ok:!0}}function Hn(s,e){let t=s.from,n=s.to,i=s.piece,r=0,a=0,o=0;for(let l=0,f=e.length;l<f;l++){let m=e[l].from,g=e[l].to,p=e[l].piece;i===p&&t!==m&&n===g&&(r++,fe(t)===fe(m)&&a++,Ee(t)===Ee(m)&&o++)}return r>0?a>0&&o>0?R(t):o>0?R(t).charAt(1):R(t).charAt(0):""}function se(s,e,t,n,i,r=void 0,a=k.NORMAL){let o=fe(n);if(i===$&&(o===Kn||o===Dn))for(let l=0;l<Ht.length;l++){let f=Ht[l];s.push({color:e,from:t,to:n,piece:i,captured:r,promotion:f,flags:a|k.PROMOTION})}else s.push({color:e,from:t,to:n,piece:i,captured:r,flags:a})}function jt(s){let e=s.charAt(0);return e>="a"&&e<="h"?s.match(/[a-h]\d.*[a-h]\d/)?void 0:$:(e=e.toLowerCase(),e==="o"?N:e)}function it(s){return s.replace(/=/,"").replace(/[+#]?[?!]*$/,"")}var Be=class{_board=new Array(128);_turn=K;_header={};_kings={w:O,b:O};_epSquare=-1;_halfMoves=0;_moveNumber=0;_history=[];_comments={};_castling={w:0,b:0};_hash=0n;_positionCount=new Map;constructor(e=tt,{skipValidation:t=!1}={}){this.load(e,{skipValidation:t})}clear({preserveHeaders:e=!1}={}){this._board=new Array(128),this._kings={w:O,b:O},this._turn=K,this._castling={w:0,b:0},this._epSquare=O,this._halfMoves=0,this._moveNumber=1,this._history=[],this._comments={},this._header=e?this._header:{...Nn},this._hash=this._computeHash(),this._positionCount=new Map,this._header.SetUp=null,this._header.FEN=null}load(e,{skipValidation:t=!1,preserveHeaders:n=!1}={}){let i=e.split(/\s+/);if(i.length>=2&&i.length<6){let o=["-","-","0","1"];e=i.concat(o.slice(-(6-i.length))).join(" ")}if(i=e.split(/\s+/),!t){let{ok:o,error:l}=Un(e);if(!o)throw new Error(l)}let r=i[0],a=0;this.clear({preserveHeaders:n});for(let o=0;o<r.length;o++){let l=r.charAt(o);if(l==="/")a+=8;else if(Wt(l))a+=parseInt(l,10);else{let f=l<"a"?K:j;this._put({type:l.toLowerCase(),color:f},R(a)),a++}}this._turn=i[1],i[2].indexOf("K")>-1&&(this._castling.w|=k.KSIDE_CASTLE),i[2].indexOf("Q")>-1&&(this._castling.w|=k.QSIDE_CASTLE),i[2].indexOf("k")>-1&&(this._castling.b|=k.KSIDE_CASTLE),i[2].indexOf("q")>-1&&(this._castling.b|=k.QSIDE_CASTLE),this._epSquare=i[3]==="-"?O:S[i[3]],this._halfMoves=parseInt(i[4],10),this._moveNumber=parseInt(i[5],10),this._hash=this._computeHash(),this._updateSetup(e),this._incPositionCount()}fen({forceEnpassantSquare:e=!1}={}){let t=0,n="";for(let a=S.a8;a<=S.h1;a++){if(this._board[a]){t>0&&(n+=t,t=0);let{color:o,type:l}=this._board[a];n+=o===K?l.toUpperCase():l.toLowerCase()}else t++;a+1&136&&(t>0&&(n+=t),a!==S.h1&&(n+="/"),t=0,a+=8)}let i="";this._castling[K]&k.KSIDE_CASTLE&&(i+="K"),this._castling[K]&k.QSIDE_CASTLE&&(i+="Q"),this._castling[j]&k.KSIDE_CASTLE&&(i+="k"),this._castling[j]&k.QSIDE_CASTLE&&(i+="q"),i=i||"-";let r="-";if(this._epSquare!==O)if(e)r=R(this._epSquare);else{let a=this._epSquare+(this._turn===K?16:-16),o=[a+1,a-1];for(let l of o){if(l&136)continue;let f=this._turn;if(this._board[l]?.color===f&&this._board[l]?.type===$){this._makeMove({color:f,from:l,to:this._epSquare,piece:$,captured:$,flags:k.EP_CAPTURE});let m=!this._isKingAttacked(f);if(this._undoMove(),m){r=R(this._epSquare);break}}}}return[n,this._turn,i,r,this._halfMoves,this._moveNumber].join(" ")}_pieceKey(e){if(!this._board[e])return 0n;let{color:t,type:n}=this._board[e],i={w:0,b:1}[t],r={p:0,n:1,b:2,r:3,q:4,k:5}[n];return Tn[i][r][e]}_epKey(){return this._epSquare===O?0n:In[this._epSquare&7]}_castlingKey(){let e=this._castling.w>>5|this._castling.b>>3;return Pn[e]}_computeHash(){let e=0n;for(let t=S.a8;t<=S.h1;t++){if(t&136){t+=7;continue}this._board[t]&&(e^=this._pieceKey(t))}return e^=this._epKey(),e^=this._castlingKey(),this._turn==="b"&&(e^=et),e}_updateSetup(e){this._history.length>0||(e!==tt?(this._header.SetUp="1",this._header.FEN=e):(this._header.SetUp=null,this._header.FEN=null))}reset(){this.load(tt)}get(e){return this._board[S[e]]}findPiece(e){let t=[];for(let n=S.a8;n<=S.h1;n++){if(n&136){n+=7;continue}!this._board[n]||this._board[n]?.color!==e.color||this._board[n].color===e.color&&this._board[n].type===e.type&&t.push(R(n))}return t}put({type:e,color:t},n){return this._put({type:e,color:t},n)?(this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),!0):!1}_set(e,t){this._hash^=this._pieceKey(e),this._board[e]=t,this._hash^=this._pieceKey(e)}_put({type:e,color:t},n){if(On.indexOf(e.toLowerCase())===-1||!(n in S))return!1;let i=S[n];if(e==N&&!(this._kings[t]==O||this._kings[t]==i))return!1;let r=this._board[i];return r&&r.type===N&&(this._kings[r.color]=O),this._set(i,{type:e,color:t}),e===N&&(this._kings[t]=i),!0}_clear(e){this._hash^=this._pieceKey(e),delete this._board[e]}remove(e){let t=this.get(e);return this._clear(S[e]),t&&t.type===N&&(this._kings[t.color]=O),this._updateCastlingRights(),this._updateEnPassantSquare(),this._updateSetup(this.fen()),t}_updateCastlingRights(){this._hash^=this._castlingKey();let e=this._board[S.e1]?.type===N&&this._board[S.e1]?.color===K,t=this._board[S.e8]?.type===N&&this._board[S.e8]?.color===j;(!e||this._board[S.a1]?.type!==be||this._board[S.a1]?.color!==K)&&(this._castling.w&=-65),(!e||this._board[S.h1]?.type!==be||this._board[S.h1]?.color!==K)&&(this._castling.w&=-33),(!t||this._board[S.a8]?.type!==be||this._board[S.a8]?.color!==j)&&(this._castling.b&=-65),(!t||this._board[S.h8]?.type!==be||this._board[S.h8]?.color!==j)&&(this._castling.b&=-33),this._hash^=this._castlingKey()}_updateEnPassantSquare(){if(this._epSquare===O)return;let e=this._epSquare+(this._turn===K?-16:16),t=this._epSquare+(this._turn===K?16:-16),n=[t+1,t-1];if(this._board[e]!==null||this._board[this._epSquare]!==null||this._board[t]?.color!==_e(this._turn)||this._board[t]?.type!==$){this._hash^=this._epKey(),this._epSquare=O;return}let i=r=>!(r&136)&&this._board[r]?.color===this._turn&&this._board[r]?.type===$;n.some(i)||(this._hash^=this._epKey(),this._epSquare=O)}_attacked(e,t,n){let i=[];for(let r=S.a8;r<=S.h1;r++){if(r&136){r+=7;continue}if(this._board[r]===void 0||this._board[r].color!==e)continue;let a=this._board[r],o=r-t;if(o===0)continue;let l=o+119;if(Bn[l]&Ln[a.type]){if(a.type===$){if(o>0&&a.color===K||o<=0&&a.color===j)if(n)i.push(R(r));else return!0;continue}if(a.type==="n"||a.type==="k")if(n){i.push(R(r));continue}else return!0;let f=Rn[l],m=r+f,g=!1;for(;m!==t;){if(this._board[m]!=null){g=!0;break}m+=f}if(!g)if(n){i.push(R(r));continue}else return!0}}return n?i:!1}attackers(e,t){return t?this._attacked(t,S[e],!0):this._attacked(this._turn,S[e],!0)}_isKingAttacked(e){let t=this._kings[e];return t===-1?!1:this._attacked(_e(e),t)}hash(){return this._hash.toString(16)}isAttacked(e,t){return this._attacked(t,S[e])}isCheck(){return this._isKingAttacked(this._turn)}inCheck(){return this.isCheck()}isCheckmate(){return this.isCheck()&&this._moves().length===0}isStalemate(){return!this.isCheck()&&this._moves().length===0}isInsufficientMaterial(){let e={b:0,n:0,r:0,q:0,k:0,p:0},t=[],n=0,i=0;for(let r=S.a8;r<=S.h1;r++){if(i=(i+1)%2,r&136){r+=7;continue}let a=this._board[r];a&&(e[a.type]=a.type in e?e[a.type]+1:1,a.type===Ne&&t.push(i),n++)}if(n===2)return!0;if(n===3&&(e[Ne]===1||e[rt]===1))return!0;if(n===e[Ne]+2){let r=0,a=t.length;for(let o=0;o<a;o++)r+=t[o];if(r===0||r===a)return!0}return!1}isThreefoldRepetition(){return this._getPositionCount(this._hash)>=3}isDrawByFiftyMoves(){return this._halfMoves>=100}isDraw(){return this.isDrawByFiftyMoves()||this.isStalemate()||this.isInsufficientMaterial()||this.isThreefoldRepetition()}isGameOver(){return this.isCheckmate()||this.isDraw()}moves({verbose:e=!1,square:t=void 0,piece:n=void 0}={}){let i=this._moves({square:t,piece:n});return e?i.map(r=>new me(this,r)):i.map(r=>this._moveToSan(r,i))}_moves({legal:e=!0,piece:t=void 0,square:n=void 0}={}){let i=n?n.toLowerCase():void 0,r=t?.toLowerCase(),a=[],o=this._turn,l=_e(o),f=S.a8,m=S.h1,g=!1;if(i)if(i in S)f=m=S[i],g=!0;else return[];for(let v=f;v<=m;v++){if(v&136){v+=7;continue}if(!this._board[v]||this._board[v].color===l)continue;let{type:x}=this._board[v],_;if(x===$){if(r&&r!==x)continue;_=v+st[o][0],this._board[_]||(se(a,o,v,_,$),_=v+st[o][1],Qn[o]===fe(v)&&!this._board[_]&&se(a,o,v,_,$,void 0,k.BIG_PAWN));for(let M=2;M<4;M++)_=v+st[o][M],!(_&136)&&(this._board[_]?.color===l?se(a,o,v,_,$,this._board[_].type,k.CAPTURE):_===this._epSquare&&se(a,o,v,_,$,$,k.EP_CAPTURE))}else{if(r&&r!==x)continue;for(let M=0,Q=Ut[x].length;M<Q;M++){let U=Ut[x][M];for(_=v;_+=U,!(_&136);){if(!this._board[_])se(a,o,v,_,x);else{if(this._board[_].color===o)break;se(a,o,v,_,x,this._board[_].type,k.CAPTURE);break}if(x===rt||x===N)break}}}}if((r===void 0||r===N)&&(!g||m===this._kings[o])){if(this._castling[o]&k.KSIDE_CASTLE){let v=this._kings[o],x=v+2;!this._board[v+1]&&!this._board[x]&&!this._attacked(l,this._kings[o])&&!this._attacked(l,v+1)&&!this._attacked(l,x)&&se(a,o,this._kings[o],x,N,void 0,k.KSIDE_CASTLE)}if(this._castling[o]&k.QSIDE_CASTLE){let v=this._kings[o],x=v-2;!this._board[v-1]&&!this._board[v-2]&&!this._board[v-3]&&!this._attacked(l,this._kings[o])&&!this._attacked(l,v-1)&&!this._attacked(l,x)&&se(a,o,this._kings[o],x,N,void 0,k.QSIDE_CASTLE)}}if(!e||this._kings[o]===-1)return a;let p=[];for(let v=0,x=a.length;v<x;v++)this._makeMove(a[v]),this._isKingAttacked(o)||p.push(a[v]),this._undoMove();return p}move(e,{strict:t=!1}={}){let n=null;if(typeof e=="string")n=this._moveFromSan(e,t);else if(e===null)n=this._moveFromSan(nt,t);else if(typeof e=="object"){let r=this._moves();for(let a=0,o=r.length;a<o;a++)if(e.from===R(r[a].from)&&e.to===R(r[a].to)&&(!("promotion"in r[a])||e.promotion===r[a].promotion)){n=r[a];break}}if(!n)throw typeof e=="string"?new Error(`Invalid move: ${e}`):new Error(`Invalid move: ${JSON.stringify(e)}`);if(this.isCheck()&&n.flags&k.NULL_MOVE)throw new Error("Null move not allowed when in check");let i=new me(this,n);return this._makeMove(n),this._incPositionCount(),i}_push(e){this._history.push({move:e,kings:{b:this._kings.b,w:this._kings.w},turn:this._turn,castling:{b:this._castling.b,w:this._castling.w},epSquare:this._epSquare,halfMoves:this._halfMoves,moveNumber:this._moveNumber})}_movePiece(e,t){this._hash^=this._pieceKey(e),this._board[t]=this._board[e],delete this._board[e],this._hash^=this._pieceKey(t)}_makeMove(e){let t=this._turn,n=_e(t);if(this._push(e),e.flags&k.NULL_MOVE){t===j&&this._moveNumber++,this._halfMoves++,this._turn=n,this._epSquare=O;return}if(this._hash^=this._epKey(),this._hash^=this._castlingKey(),e.captured&&(this._hash^=this._pieceKey(e.to)),this._movePiece(e.from,e.to),e.flags&k.EP_CAPTURE&&(this._turn===j?this._clear(e.to-16):this._clear(e.to+16)),e.promotion&&(this._clear(e.to),this._set(e.to,{type:e.promotion,color:t})),this._board[e.to].type===N){if(this._kings[t]=e.to,e.flags&k.KSIDE_CASTLE){let i=e.to-1,r=e.to+1;this._movePiece(r,i)}else if(e.flags&k.QSIDE_CASTLE){let i=e.to+1,r=e.to-2;this._movePiece(r,i)}this._castling[t]=0}if(this._castling[t]){for(let i=0,r=te[t].length;i<r;i++)if(e.from===te[t][i].square&&this._castling[t]&te[t][i].flag){this._castling[t]^=te[t][i].flag;break}}if(this._castling[n]){for(let i=0,r=te[n].length;i<r;i++)if(e.to===te[n][i].square&&this._castling[n]&te[n][i].flag){this._castling[n]^=te[n][i].flag;break}}if(this._hash^=this._castlingKey(),e.flags&k.BIG_PAWN){let i;t===j?i=e.to-16:i=e.to+16,!(e.to-1&136)&&this._board[e.to-1]?.type===$&&this._board[e.to-1]?.color===n||!(e.to+1&136)&&this._board[e.to+1]?.type===$&&this._board[e.to+1]?.color===n?(this._epSquare=i,this._hash^=this._epKey()):this._epSquare=O}else this._epSquare=O;e.piece===$?this._halfMoves=0:e.flags&(k.CAPTURE|k.EP_CAPTURE)?this._halfMoves=0:this._halfMoves++,t===j&&this._moveNumber++,this._turn=n,this._hash^=et}undo(){let e=this._hash,t=this._undoMove();if(t){let n=new me(this,t);return this._decPositionCount(e),n}return null}_undoMove(){let e=this._history.pop();if(e===void 0)return null;this._hash^=this._epKey(),this._hash^=this._castlingKey();let t=e.move;this._kings=e.kings,this._turn=e.turn,this._castling=e.castling,this._epSquare=e.epSquare,this._halfMoves=e.halfMoves,this._moveNumber=e.moveNumber,this._hash^=this._epKey(),this._hash^=this._castlingKey(),this._hash^=et;let n=this._turn,i=_e(n);if(t.flags&k.NULL_MOVE)return t;if(this._movePiece(t.to,t.from),t.piece&&(this._clear(t.from),this._set(t.from,{type:t.piece,color:n})),t.captured)if(t.flags&k.EP_CAPTURE){let r;n===j?r=t.to-16:r=t.to+16,this._set(r,{type:$,color:i})}else this._set(t.to,{type:t.captured,color:i});if(t.flags&(k.KSIDE_CASTLE|k.QSIDE_CASTLE)){let r,a;t.flags&k.KSIDE_CASTLE?(r=t.to+1,a=t.to-1):(r=t.to-2,a=t.to+1),this._movePiece(a,r)}return t}pgn({newline:e=`
9
+ `,maxWidth:t=0}={}){let n=[],i=!1;for(let p in this._header)this._header[p]&&n.push(`[${p} "${this._header[p]}"]`+e),i=!0;i&&this._history.length&&n.push(e);let r=p=>{let v=this._comments[this.fen()];if(typeof v<"u"){let x=p.length>0?" ":"";p=`${p}${x}{${v}}`}return p},a=[];for(;this._history.length>0;)a.push(this._undoMove());let o=[],l="";for(a.length===0&&o.push(r(""));a.length>0;){l=r(l);let p=a.pop();if(!p)break;if(!this._history.length&&p.color==="b"){let v=`${this._moveNumber}. ...`;l=l?`${l} ${v}`:v}else p.color==="w"&&(l.length&&o.push(l),l=this._moveNumber+".");l=l+" "+this._moveToSan(p,this._moves({legal:!0})),this._makeMove(p)}if(l.length&&o.push(r(l)),o.push(this._header.Result||"*"),t===0)return n.join("")+o.join(" ");let f=function(){return n.length>0&&n[n.length-1]===" "?(n.pop(),!0):!1},m=function(p,v){for(let x of v.split(" "))if(x){if(p+x.length>t){for(;f();)p--;n.push(e),p=0}n.push(x),p+=x.length,n.push(" "),p++}return f()&&p--,p},g=0;for(let p=0;p<o.length;p++){if(g+o[p].length>t&&o[p].includes("{")){g=m(g,o[p]);continue}g+o[p].length>t&&p!==0?(n[n.length-1]===" "&&n.pop(),n.push(e),g=0):p!==0&&(n.push(" "),g++),n.push(o[p]),g+=o[p].length}return n.join("")}header(...e){for(let t=0;t<e.length;t+=2)typeof e[t]=="string"&&typeof e[t+1]=="string"&&(this._header[e[t]]=e[t+1]);return this._header}setHeader(e,t){return this._header[e]=t??ot[e]??null,this.getHeaders()}removeHeader(e){return e in this._header?(this._header[e]=ot[e]||null,!0):!1}getHeaders(){let e={};for(let[t,n]of Object.entries(this._header))n!==null&&(e[t]=n);return e}loadPgn(e,{strict:t=!1,newlineChar:n=`\r?
10
+ `}={}){n!==`\r?
11
+ `&&(e=e.replace(new RegExp(n,"g"),`
12
+ `));let i=Mn(e);this.reset();let r=i.headers,a="";for(let f in r)f.toLowerCase()==="fen"&&(a=r[f]),this.header(f,r[f]);if(!t)a&&this.load(a,{preserveHeaders:!0});else if(r.SetUp==="1"){if(!("FEN"in r))throw new Error("Invalid PGN: FEN tag must be supplied with SetUp tag");this.load(r.FEN,{preserveHeaders:!0})}let o=i.root;for(;o;){if(o.move){let f=this._moveFromSan(o.move,t);if(f==null)throw new Error(`Invalid move in PGN: ${o.move}`);this._makeMove(f),this._incPositionCount()}o.comment!==void 0&&(this._comments[this.fen()]=o.comment),o=o.variations[0]}let l=i.result;l&&Object.keys(this._header).length&&this._header.Result!==l&&this.setHeader("Result",l)}_moveToSan(e,t){let n="";if(e.flags&k.KSIDE_CASTLE)n="O-O";else if(e.flags&k.QSIDE_CASTLE)n="O-O-O";else{if(e.flags&k.NULL_MOVE)return nt;if(e.piece!==$){let i=Hn(e,t);n+=e.piece.toUpperCase()+i}e.flags&(k.CAPTURE|k.EP_CAPTURE)&&(e.piece===$&&(n+=R(e.from)[0]),n+="x"),n+=R(e.to),e.promotion&&(n+="="+e.promotion.toUpperCase())}return this._makeMove(e),this.isCheck()&&(this.isCheckmate()?n+="#":n+="+"),this._undoMove(),n}_moveFromSan(e,t=!1){let n=it(e);if(t||(n==="0-0"?n="O-O":n==="0-0-0"&&(n="O-O-O")),n==nt)return{color:this._turn,from:0,to:0,piece:"k",flags:k.NULL_MOVE};let i=jt(n),r=this._moves({legal:!0,piece:i});for(let p=0,v=r.length;p<v;p++)if(n===it(this._moveToSan(r[p],r)))return r[p];if(t)return null;let a,o,l,f,m,g=!1;if(o=n.match(/([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/),o?(a=o[1],l=o[2],f=o[3],m=o[4],l.length==1&&(g=!0)):(o=n.match(/([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/),o&&(a=o[1],l=o[2],f=o[3],m=o[4],l.length==1&&(g=!0))),i=jt(n),r=this._moves({legal:!0,piece:a||i}),!f)return null;for(let p=0,v=r.length;p<v;p++)if(l){if((!a||a.toLowerCase()==r[p].piece)&&S[l]==r[p].from&&S[f]==r[p].to&&(!m||m.toLowerCase()==r[p].promotion))return r[p];if(g){let x=R(r[p].from);if((!a||a.toLowerCase()==r[p].piece)&&S[f]==r[p].to&&(l==x[0]||l==x[1])&&(!m||m.toLowerCase()==r[p].promotion))return r[p]}}else if(n===it(this._moveToSan(r[p],r)).replace("x",""))return r[p];return null}ascii(){let e=` +------------------------+
13
+ `;for(let t=S.a8;t<=S.h1;t++){if(Ee(t)===0&&(e+=" "+"87654321"[fe(t)]+" |"),this._board[t]){let n=this._board[t].type,r=this._board[t].color===K?n.toUpperCase():n.toLowerCase();e+=" "+r+" "}else e+=" . ";t+1&136&&(e+=`|
14
+ `,t+=8)}return e+=` +------------------------+
15
+ `,e+=" a b c d e f g h",e}perft(e){let t=this._moves({legal:!1}),n=0,i=this._turn;for(let r=0,a=t.length;r<a;r++)this._makeMove(t[r]),this._isKingAttacked(i)||(e-1>0?n+=this.perft(e-1):n++),this._undoMove();return n}setTurn(e){return this._turn==e?!1:(this.move("--"),!0)}turn(){return this._turn}board(){let e=[],t=[];for(let n=S.a8;n<=S.h1;n++)this._board[n]==null?t.push(null):t.push({square:R(n),type:this._board[n].type,color:this._board[n].color}),n+1&136&&(e.push(t),t=[],n+=8);return e}squareColor(e){if(e in S){let t=S[e];return(fe(t)+Ee(t))%2===0?"light":"dark"}return null}history({verbose:e=!1}={}){let t=[],n=[];for(;this._history.length>0;)t.push(this._undoMove());for(;;){let i=t.pop();if(!i)break;e?n.push(new me(this,i)):n.push(this._moveToSan(i,this._moves())),this._makeMove(i)}return n}_getPositionCount(e){return this._positionCount.get(e)??0}_incPositionCount(){this._positionCount.set(this._hash,(this._positionCount.get(this._hash)??0)+1)}_decPositionCount(e){let t=this._positionCount.get(e)??0;t===1?this._positionCount.delete(e):this._positionCount.set(e,t-1)}_pruneComments(){let e=[],t={},n=i=>{i in this._comments&&(t[i]=this._comments[i])};for(;this._history.length>0;)e.push(this._undoMove());for(n(this.fen());;){let i=e.pop();if(!i)break;this._makeMove(i),n(this.fen())}this._comments=t}getComment(){return this._comments[this.fen()]}setComment(e){this._comments[this.fen()]=e.replace("{","[").replace("}","]")}deleteComment(){return this.removeComment()}removeComment(){let e=this._comments[this.fen()];return delete this._comments[this.fen()],e}getComments(){return this._pruneComments(),Object.keys(this._comments).map(e=>({fen:e,comment:this._comments[e]}))}deleteComments(){return this.removeComments()}removeComments(){return this._pruneComments(),Object.keys(this._comments).map(e=>{let t=this._comments[e];return delete this._comments[e],{fen:e,comment:t}})}setCastlingRights(e,t){for(let i of[N,ne])t[i]!==void 0&&(t[i]?this._castling[e]|=Pe[i]:this._castling[e]&=~Pe[i]);this._updateCastlingRights();let n=this.getCastlingRights(e);return(t[N]===void 0||t[N]===n[N])&&(t[ne]===void 0||t[ne]===n[ne])}getCastlingRights(e){return{[N]:(this._castling[e]&Pe[N])!==0,[ne]:(this._castling[e]&Pe[ne])!==0}}moveNumber(){return this._moveNumber}};var Gt={p:"pawn",n:"knight",b:"bishop",r:"rook",q:"queen",k:"king"},jn={p:1,n:3,b:3,r:5,q:9,k:0},Le=class{chess;constructor(e){this.chess=new Be(e)}reset(){this.chess.reset()}load(e){try{return this.chess.load(e),!0}catch{return!1}}fen(){return this.chess.fen()}turn(){return this.chess.turn()==="w"?"white":"black"}isCheck(){return this.chess.inCheck()}isGameOver(){return this.chess.isGameOver()}history(){return this.chess.history()}getAnnotatedMoves(){return this.chess.moves({verbose:!0}).map(t=>{let n=Gt[t.piece]??t.piece,i=t.san==="O-O"||t.san==="O-O-O",r=!!t.captured,a=t.captured?Gt[t.captured]:void 0,o=`${n} moves from ${t.from} to ${t.to}`;return i?o=t.san==="O-O"?"Kingside castle":"Queenside castle":r&&(o=`${n} on ${t.from} captures ${a} on ${t.to}`),t.san.includes("+")?o+=" with check":t.san.includes("#")&&(o+=" with checkmate!"),{san:t.san,from:t.from,to:t.to,piece:n,color:t.color==="w"?"white":"black",isCapture:r,capturedPiece:a,isCheck:t.san.includes("+")||t.san.includes("#"),isCastling:i,description:o}})}getMaterialBalance(){let e=this.chess.board(),t=0,n=0;for(let a of e)for(let o of a){if(!o)continue;let l=jn[o.type];o.color==="w"?t+=l:n+=l}let i=t-n,r="Material is exactly equal";return i>0?r=`White is up +${i} point${i>1?"s":""}`:i<0&&(r=`Black is up +${Math.abs(i)} point${Math.abs(i)>1?"s":""}`),{whiteScore:t,blackScore:n,diff:i,description:r}}getGamePhase(){let e=this.chess.board(),t=0,n=0;for(let r of e)for(let a of r)a&&a.type!=="p"&&a.type!=="k"&&(t++,a.type==="q"&&n++);return this.chess.history().length<16&&t>=12?"opening":t<=6||n===0?"endgame":"middlegame"}getBoardContext(){let e=this.chess.history(),t=e.slice(-6);return{fen:this.chess.fen(),turn:this.turn(),moveNumber:Math.floor(e.length/2)+1,inCheck:this.isCheck(),materialBalance:this.getMaterialBalance(),gamePhase:this.getGamePhase(),recentHistory:t,candidateMoves:this.getAnnotatedMoves()}}makeMove(e){let t=this.getAnnotatedMoves().find(n=>n.san===e||`${n.from}${n.to}`===e);return t?(this.chess.move(t.san),t):null}};var ut=s=>s.get("x-typesafe-request-id")??void 0,Wn=class ss extends Promise{#e;#n;#t;constructor(e,t){super(n=>n(void 0)),this.#e=e,this.#n=t}asResponse(){return this.#e}async withResponse(){let[e,t]=await Promise.all([this.#s(),this.#e]);return{data:e,response:t,requestId:ut(t.headers)}}map(e){return new ss(this.#e,()=>this.#s().then(e))}#s(){return this.#t??=this.#e.then(this.#n),this.#t}then(e,t){return this.#s().then(e,t)}catch(e){return this.#s().catch(e)}finally(e){return this.#s().finally(e)}},ve={apiKey:"TYPESAFE_API_KEY",baseURL:"TYPESAFE_BASE_URL",defaultModel:"TYPESAFE_DEFAULT_MODEL",logLevel:"TYPESAFE_LOG_LEVEL"},ns=s=>{if(!(typeof process>"u"||!process.env))return process.env[s]?.trim()||void 0},at=(s,e)=>s??ns(e),Gn=(s,e)=>Array.from({length:e-s},(t,n)=>s+n),Fe={maxRetries:2,backoffInitialMs:500,backoffMaxMs:5e3,backoffJitter:.25,httpStatuses:new Set([408,429,...Gn(500,600)]),respectRetryAfter:!0,maxRetryAfterMs:6e4,apiConnectionError:!0,apiTimeoutError:!0};Fe.maxRetries;var Yn=(s,e=Fe)=>e.httpStatuses.has(s),is=(s,e=Date.now())=>{let t=Number(s.get("retry-after-ms"));if(s.has("retry-after-ms")&&Number.isFinite(t)&&t>=0)return t;let n=s.get("retry-after");if(n===null)return;let i=Number(n);if(Number.isFinite(i))return i>=0?i*1e3:void 0;let r=Date.parse(n);if(!Number.isNaN(r))return Math.max(0,r-e)},Vn=(s,e,t=Fe,n=Math.random)=>{if(t.respectRetryAfter&&e!==void 0){let r=is(e);if(r!==void 0&&r<=t.maxRetryAfterMs)return r}let i=Math.min(t.backoffInitialMs*2**s,t.backoffMaxMs);return Math.round(i*(1-n()*t.backoffJitter))},Jn=(s,e)=>new Promise((t,n)=>{if(e?.aborted)return n(e.reason);let i=()=>{clearTimeout(r),n(e?.reason)},r=setTimeout(()=>{e?.removeEventListener("abort",i),t()},s);e?.addEventListener("abort",i,{once:!0})}),L=class extends Error{constructor(s,e){super(s,e),this.name=new.target.name}},qe=s=>typeof s=="object"&&s!==null,zn=s=>{if(typeof s=="string")return s||void 0;if(!qe(s))return;let{error:e,message:t,detail:n}=s;if(typeof e=="string")return e;if(qe(e)&&typeof e.message=="string")return e.message;if(typeof t=="string")return t;if(typeof n=="string")return n;if(qe(n)&&typeof n.message=="string")return n.message;if(Array.isArray(n))return Xn(n)},Xn=s=>{let e=s.flatMap(t=>{if(!qe(t)||typeof t.msg!="string")return[];let n=Array.isArray(t.loc)?t.loc.filter(i=>i!=="body").join("."):"";return[n?`${n}: ${t.msg}`:t.msg]});return e.length>0?e.join("; "):void 0},Yt=200,ie=class ft extends L{status;headers;body;requestId;constructor(e,t,n,i){super(i??ft.describe(e,t)),this.status=e,this.body=t,this.headers=n,this.requestId=ut(n)}static describe(e,t){let n=zn(t);if(n)return`${e} ${n}`;if(t===void 0)return`${e} status code (no body)`;let i=typeof t=="string"?t:JSON.stringify(t);return`${e} ${i.length>Yt?`${i.slice(0,Yt)}\u2026`:i}`}static fromResponse(e,t,n){return e===400?new Zn(e,t,n):e===401?new ei(e,t,n):e===403?new ti(e,t,n):e===404?new si(e,t,n):e===422?new ni(e,t,n):e===429?new ii(e,t,n):e>=500?new ri(e,t,n):new ft(e,t,n)}},Zn=class extends ie{},ei=class extends ie{},ti=class extends ie{},si=class extends ie{},ni=class extends ie{},ii=class extends ie{retryAfterMs=is(this.headers)},ri=class extends ie{},ht=class extends L{constructor(s="Connection error.",e){super(s,e)}},rs=class extends ht{timeoutMs;constructor(s,e){super(`Request timed out after ${s}ms.`,e),this.timeoutMs=s}},ct=class extends L{constructor(s="Request was aborted.",e){super(s,e)}},os=["debug","info","warn","error","off"],oi="warn",ai=s=>os.includes(s),Vt=(s,e)=>{if(ai(s))return s;throw new L(`Invalid log level "${s}" from ${e}. Expected one of: ${os.join(", ")}.`)},Oe="[typesafe-sdk]",ci={debug:(s,...e)=>console.debug(`${Oe} ${s}`,...e),info:(s,...e)=>console.info(`${Oe} ${s}`,...e),warn:(s,...e)=>console.warn(`${Oe} ${s}`,...e),error:(s,...e)=>console.error(`${Oe} ${s}`,...e)},Jt={debug:0,info:1,warn:2,error:3,off:4},Ke=()=>{},li=(s,e)=>{let t=n=>Jt[n]>=Jt[e];return{debug:t("debug")?(n,...i)=>s.debug(n,...i):Ke,info:t("info")?(n,...i)=>s.info(n,...i):Ke,warn:t("warn")?(n,...i)=>s.warn(n,...i):Ke,error:t("error")?(n,...i)=>s.error(n,...i):Ke}},fi=new Set(["authorization","proxy-authorization","x-api-key"]),ui=new Set(["cookie","set-cookie"]),hi=s=>{let[e,t]=s.includes(" ")?s.split(/\s+/,2):[void 0,s],n=t&&t.length>8?t.slice(-4):"";return`${e?`${e} `:""}***${n}`},di=(s,e)=>{let t=s.toLowerCase();return fi.has(t)?hi(e):ui.has(t)?"***":e},pi=s=>Object.fromEntries(Object.entries(s).map(([e,t])=>[e,di(e,t)])),re=(s=null,e)=>({type:"noul",instructions:s,criteria:e}),J=(s,e)=>{if(!Array.isArray(e))throw new L("Score criteria must be a list of descriptions indexed by score from zero, not a map.");return{type:"score",instructions:s,criteria:e}},ue=(s,e)=>{if(Array.isArray(e))throw new L("Choice criteria must be a map of labels to descriptions, not a list.");return{type:"choice",instructions:s,criteria:e}},mi=s=>{if(Object.keys(s).length===0)throw new L("At least one question is required.");for(let[e,t]of Object.entries(s))if(t.type==="score"){if(!Array.isArray(t.criteria))throw new L(`Score question "${e}" has criteria that are not a list; score criteria must be a list of descriptions indexed by score from zero.`);if(t.criteria.length<2)throw new L(`Score question "${e}" has ${t.criteria.length} criteria; at least two scores are required.`)}},gi=class{#e;constructor(s){this.#e=s}list(s={}){return this.#e.request("GET","/v1/models",s).map(vi)}},vi=s=>{if(Array.isArray(s?.models))return s.models;throw new L("Unexpected response shape from GET /v1/models; expected { models: [...] }.")},D=globalThis,as=()=>typeof D.window<"u"&&typeof D.window.document<"u"&&typeof D.navigator<"u",yi=()=>{let s=D.process?.platform&&D.process?.arch?` (${D.process.platform}; ${D.process.arch})`:"";return D.Bun?.version?`bun/${D.Bun.version}${s}`:D.Deno?.version?.deno?`deno/${D.Deno.version.deno}${s}`:D.EdgeRuntime!==void 0?"vercel-edge":D.navigator?.userAgent==="Cloudflare-Workers"?"cloudflare-workers":D.process?.versions?.node?`node/${D.process.versions.node}${s}`:as()?"browser":"unknown"},zt="0.6.0",_i=()=>{throw new L(`No API key was provided. Pass \`apiKey\` to the TypeSafeClient constructor or set the ${ve.apiKey} environment variable.`)},bi=()=>{throw new L("No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.")},Ei=()=>{throw new L("TypeSafeClient is running in a browser, which would expose your API key to anyone using the page. Call the API from a server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.")},wi=(s,e)=>globalThis.fetch(s,e),xi=(s,e)=>{if(!Number.isInteger(e)||e<0)throw new L(`\`${s}\` must be a non-negative integer, got ${String(e)}.`);return e},Xt=(s,e)=>{if(!Number.isFinite(e)||e<=0)throw new L(`\`${s}\` must be a positive number of milliseconds, got ${String(e)}.`);return e},lt=(s,e)=>{if(!Number.isFinite(e)||e<0)throw new L(`\`${s}\` must be a non-negative number of milliseconds, got ${String(e)}.`);return e},Si=(s,e)=>{if(!Number.isFinite(e)||e<0||e>1)throw new L(`\`${s}\` must be between 0 and 1, got ${String(e)}.`);return e},ki=(s,e)=>{for(let t of e)if(!Number.isInteger(t)||t<100||t>999)throw new L(`\`${s}\` must contain HTTP status codes, got ${String(t)}.`);return e},Zt=(s,e)=>{let t=e??{};return{maxRetries:t.maxRetries===void 0?s.maxRetries:xi("retry.maxRetries",t.maxRetries),backoffInitialMs:t.backoffInitialMs===void 0?s.backoffInitialMs:lt("retry.backoffInitialMs",t.backoffInitialMs),backoffMaxMs:t.backoffMaxMs===void 0?s.backoffMaxMs:lt("retry.backoffMaxMs",t.backoffMaxMs),backoffJitter:t.backoffJitter===void 0?s.backoffJitter:Si("retry.backoffJitter",t.backoffJitter),httpStatuses:new Set(t.httpStatuses===void 0?s.httpStatuses:ki("retry.httpStatuses",t.httpStatuses)),respectRetryAfter:t.respectRetryAfter??s.respectRetryAfter,maxRetryAfterMs:t.maxRetryAfterMs===void 0?s.maxRetryAfterMs:lt("retry.maxRetryAfterMs",t.maxRetryAfterMs),apiConnectionError:t.apiConnectionError??s.apiConnectionError,apiTimeoutError:t.apiTimeoutError??s.apiTimeoutError}},Ci=(s,e)=>s instanceof rs?e.apiTimeoutError:s instanceof ht?e.apiConnectionError:!1,Mi=s=>{if(s!==void 0)return Vt(s,"the `logLevel` option");let e=ns(ve.logLevel);return e!==void 0?Vt(e,ve.logLevel):oi},Ai=s=>s.replace(/\/+$/,""),es=(...s)=>{let e=new Map;for(let t of s)for(let[n,i]of Object.entries(t))i===void 0?e.delete(n.toLowerCase()):e.set(n.toLowerCase(),[n,i]);return Object.fromEntries(e.values())},Ti=async(s,e)=>{let t=s.clone().body?.getReader();if(!t)return;let n=()=>{t.cancel(e.reason).catch(()=>{}),s.body?.cancel(e.reason).catch(()=>{})};e.addEventListener("abort",n,{once:!0});try{for(e.aborted&&n(),e.throwIfAborted();!(await t.read()).done;)e.throwIfAborted();e.throwIfAborted()}finally{e.removeEventListener("abort",n),t.releaseLock()}},Ii=yi(),cs=class{#e;baseURL;defaultModel;logLevel;logger;retry;timeout;defaultHeaders;fetch;models;#n=0;constructor(s={}){as()&&!s.dangerouslyAllowBrowser&&Ei(),this.#e=at(s.apiKey,ve.apiKey)??_i(),this.baseURL=Ai(at(s.baseURL,ve.baseURL)??"https://api.typesafe.ai"),this.defaultModel=at(s.defaultModel,ve.defaultModel)??"jev-latest",this.logLevel=Mi(s.logLevel),this.logger=li(s.logger??ci,this.logLevel),this.retry=Zt(Fe,s.retry),this.timeout=Xt("timeout",s.timeout??1e4),this.defaultHeaders={...s.defaultHeaders},s.fetch===void 0&&typeof globalThis.fetch!="function"&&bi(),this.fetch=s.fetch??wi;let e={request:(t,n,i)=>this.#t(t,n,i),defaultModel:this.defaultModel};this.models=new gi(e)}systemOne(s,e={}){mi(s.questions);let t={...s,model:s.model??this.defaultModel};return this.#t("POST","/v1/systemone",{...e,body:t})}#t(s,e,t={}){let n={method:s,path:e,body:t.body,headers:es(this.defaultHeaders,t.headers??{}),signal:t.signal,timeout:t.timeout===void 0?this.timeout:Xt("timeout",t.timeout),retry:Zt(this.retry,t.retry)},i=`#${++this.#n} ${s} ${e}`;return new Wn(this.fetchWithRetries(i,n),async r=>{let a=await ts(r);return this.logger.debug(`${i} <- body`,a),a})}async fetchWithRetries(s,e){let t=`${this.baseURL}${e.path}`,n=es(e.headers,{Authorization:`Bearer ${this.#e}`,Accept:"application/json","User-Agent":`typesafe-sdk/${zt}`,"X-TypeSafe-SDK":`typesafe-sdk/${zt}`,"X-TypeSafe-Runtime":Ii,"Content-Type":e.body===void 0?void 0:"application/json","X-TypeSafe-Retry-Count":void 0}),i=e.body===void 0?void 0:JSON.stringify(e.body);for(let r=0;;r++){let a=e.retry.maxRetries-r,o=r===0?n:{...n,"X-TypeSafe-Retry-Count":String(r)};this.logger.debug(`${s} -> ${t}`,{headers:pi(o),body:e.body});let l=Date.now(),f;try{f=await this.attempt(s,t,{method:e.method,headers:o,body:i},e)}catch(v){if(v instanceof ct||a<=0||!Ci(v,e.retry))throw v;await this.backOff(s,r,a,v.message,void 0,e);continue}let m=ut(f.headers);if(this.logger.info(`${s} <- ${f.status} in ${Date.now()-l}ms${m?` (request ${m})`:""}`),f.ok)return f;let g=await ts(f);this.logger.debug(`${s} <- error body`,g);let p=ie.fromResponse(f.status,g,f.headers);if(a<=0||!Yn(f.status,e.retry))throw p;await this.backOff(s,r,a,`${f.status}`,f.headers,e)}}async attempt(s,e,t,{signal:n,timeout:i}){let r=new AbortController,a=()=>r.abort(n?.reason);n?.aborted&&a(),n?.addEventListener("abort",a,{once:!0});let o=!1,l=setTimeout(()=>{o=!0,r.abort()},i),f=Date.now(),m=()=>`${Date.now()-f}ms`;try{let g=await this.fetch(e,{...t,signal:r.signal});return await Ti(g,r.signal),g}catch(g){throw n?.aborted?(this.logger.info(`${s} aborted by caller after ${m()}`),new ct(void 0,{cause:g})):o?(this.logger.info(`${s} timed out after ${m()}`),new rs(i,{cause:g})):(this.logger.info(`${s} connection error after ${m()}`,g),new ht(g instanceof Error?`Connection error: ${g.message}`:void 0,{cause:g}))}finally{clearTimeout(l),n?.removeEventListener("abort",a)}}async backOff(s,e,t,n,i,{retry:r,signal:a}){let o=Vn(e,i,r),l=e+1,f=e+t;this.logger.info(`${s} retrying in ${o}ms (retry ${l}/${f}) after ${n}`);try{await Jn(o,a)}catch(m){throw this.logger.info(`${s} aborted by caller while waiting to retry`),new ct(void 0,{cause:m})}}},ts=async s=>{let e=await s.text();if(e.length!==0){if((s.headers.get("content-type")??"").includes("application/json"))try{return JSON.parse(e)}catch{return e}try{return JSON.parse(e)}catch{return e}}};var De=class{isLive=!1;async systemOne(e){let t={},n=typeof e.state=="string"?e.state:JSON.stringify(e.state);for(let[i,r]of Object.entries(e.questions))if(r){if(r.type==="noul"){let a=.5,o=`${n} ${JSON.stringify(r.instructions)}`.toLowerCase(),l=e.state?.evaluated_move,f=l?.san??(o.includes("san")?o:"");o.includes("king")||o.includes("attack")?f.includes("#")?a=.99:f.includes("+")||l?.is_check?a=.91:f.includes("f7")||f.includes("h7")||f.includes("g7")||f.includes("f2")?a=.84:l?.is_capture||f.includes("x")?a=.68:f.includes("o-o")||f.includes("castle")?a=.05:a=.28:o.includes("psychological")||o.includes("pressure")||o.includes("provocative")?f.includes("#")?a=.99:f.includes("+")||l?.is_check?a=.88:l?.is_capture||f.includes("x")?a=.81:f.includes("d4")||f.includes("e4")||f.includes("c4")||f.includes("f4")?a=.65:f.includes("o-o")?a=.22:a=.35:o.includes("decisive_sacrifice")||o.includes("sacrifice")?a=.94:o.includes("blunder")||o.includes("risk")?a=o.includes("??")?.92:.24:o.includes("material")&&(a=l?.is_capture||f.includes("x")?.88:.22),t[i]={type:"noul",noul:Math.round(a*100)/100}}else if(r.type==="choice"){let a=r.criteria??{},o=Object.keys(a),l="none",f={},m=typeof e.state=="object"&&e.state!==null&&"user_intent"in e.state?String(e.state.user_intent).toLowerCase():n.toLowerCase(),g=e.state?.evaluated_move,p=g?.san??"",v=g?.is_capture??p.includes("x"),x=g?.is_check??p.includes("+"),_=g?.is_castling??(p.includes("O-O")||p.includes("o-o")),M=0;for(let X of o){if(X==="none")continue;let A=0,H=(a[X]??"").toLowerCase(),C=X.toLowerCase();m.includes("knight")&&(H.includes("knight")||C.startsWith("n"))&&(A+=10),m.includes("bishop")&&(H.includes("bishop")||C.startsWith("b"))&&(A+=10),(m.includes("queen's pawn")||m.includes("d-pawn"))&&(m.includes("two square")&&(C==="d4"||H.includes("d2 to d4"))?A+=20:(C==="d3"||H.includes("d2 to d3"))&&(A+=15)),(m.includes("king's pawn")||m.includes("e-pawn"))&&(m.includes("two square")&&(C==="e4"||H.includes("e2 to e4"))?A+=20:(C==="e3"||H.includes("e2 to e3"))&&(A+=15)),m.includes("castle")&&(H.includes("castle")||C.includes("o-o"))&&(A+=25),m.includes("center")&&(C==="d4"||C==="e4"||C==="nf3"||C==="nc3")&&(A+=6),m.includes("attack")&&(H.includes("captures")||C==="nf3")&&(A+=5),(n.includes("strategic_theme")||H.includes("pawn")||H.includes("develop"))&&(_&&C==="prophylaxis"?A+=40:x&&(C==="tactical_strike"||C==="king_hunt")?A+=38:v&&(C==="tactical_strike"||C==="simplification")?A+=36:p.startsWith("d")||p.startsWith("e")||p.startsWith("c")||p.startsWith("f")?C==="pawn_break"&&(A+=35):p.startsWith("N")||p.startsWith("B")||p.startsWith("R")||p.startsWith("Q")?C==="piece_activation"&&(A+=35):C==="prophylaxis"&&(A+=20)),(n.includes("match_meta")||n.includes("immortal")||n.includes("century"))&&((n.includes("immortal-game")||n.includes("anderssen"))&&C==="romantic_swashbuckler"||(n.includes("opera")||n.includes("morphy"))&&C==="dynamic_initiative"||(n.includes("century")||n.includes("fischer"))&&C==="dynamic_initiative"||n.includes("kasparov")&&C==="tactical_firestorm"||n.includes("tal")&&C==="tactical_firestorm"?A+=60:(C==="romantic_swashbuckler"||C==="tactical_firestorm")&&(A+=20)),(n.includes("??")||n.includes("blunder"))&&(C==="king_safety_negligence"&&(A+=40),C==="tactical_blindness"&&(A+=25)),A>M&&(M=A,l=X)}M===0&&(l=o.includes("none")?"none":o[0]??"none");let U=l==="none"?.25:.91;for(let X of o){let A=X===l?U:(1-U)/Math.max(1,o.length-1);f[X]=Math.round(A*100)/100}t[i]={type:"choice",choice:l,confidence:U,probabilities:f}}else if(r.type==="score"){let a=r.criteria??[],o=a.length,l=`${n} ${JSON.stringify(r.instructions)}`.toLowerCase(),f=1,m=e.state?.evaluated_move,g=(m?.san??(l.includes("san")?l:"")).toLowerCase(),p=m?.is_capture??g.includes("x"),v=m?.is_check??g.includes("+"),x=m?.is_castling??(g.includes("o-o")||g.includes("castle"));l.includes("brilliance")?f=2.9:l.includes("overall sharpness")||l.includes("volatility")?f=2.8:l.includes("aggress")||l.includes("sharp")?g.includes("#")||g.includes("bxf7")||g.includes("rxd4")||g.includes("be6")?f=2.9:v?f=2.6:p?f=2.2:g.startsWith("d4")||g.startsWith("e4")||g.startsWith("c4")||g.startsWith("f4")?f=1.7:x?f=.4:g.startsWith("n")||g.startsWith("b")?f=.9:f=.6:l.includes("prophyl")?x?f=2.9:g.startsWith("a3")||g.startsWith("h3")||g.startsWith("c3")||g.startsWith("d3")?f=2.3:v||p?f=.4:f=1.2:l.includes("complex")||l.includes("tension")?g.includes("#")||g.includes("bxf7")||g.includes("??")?f=2.9:v||p?f=2.2:x?f=.5:g.startsWith("d")||g.startsWith("e")?f=1.5:f=1:l.includes("difficult")?f=l.includes("??")?2.8:.6:f=1.2,f=Math.max(0,Math.min(o-1,f));let _={};for(let M=0;M<o;M++){let Q=Math.abs(M-f);_[M.toString()]=Math.round(Math.exp(-Q*1.5)*100)/100}t[i]={type:"score",score:Math.round(f*10)/10,confidence:.91,legend:Object.fromEntries(a.map((M,Q)=>[Q.toString(),M])),probabilities:_}}}return{model:"jev-latest (offline-simulated)",answers:t,usage:{input_tokens:280,output_tokens:45}}}},Qe=class{isLive=!0;client;constructor(e){this.client=new cs({apiKey:e})}async systemOne(e){return this.client.systemOne(e)}},he=null;function fs(){return typeof process<"u"&&process?.env?.TYPESAFE_API_KEY?process.env.TYPESAFE_API_KEY:typeof window<"u"&&typeof window.localStorage<"u"?window.localStorage.getItem("TYPESAFE_API_KEY"):null}function ls(s){typeof process<"u"&&process?.env&&(s?process.env.TYPESAFE_API_KEY=s:delete process.env.TYPESAFE_API_KEY),typeof window<"u"&&typeof window.localStorage<"u"&&(s?window.localStorage.setItem("TYPESAFE_API_KEY",s):window.localStorage.removeItem("TYPESAFE_API_KEY"))}function dt(s){if(s&&s.trim().length>0){let e=s.trim();return ls(e),he=new Qe(e),!0}else return ls(null),he=new De,!1}function us(){let s=Z(),e=fs();return s.isLive&&e?{isLive:!0,maskedKey:e.length>8?`${e.slice(0,4)}...${e.slice(-4)}`:"ts_\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"}:{isLive:!1}}function Z(){if(he)return he;let s=fs();return s&&s.trim().length>0?he=new Qe(s):he=new De,he}var Ue=class{get client(){return Z()}async resolveIntent(e,t,n=.55){let i=e.getAnnotatedMoves();if(i.length===0)return{query:t,matchedMove:null,san:"none",confidence:1,probabilities:{},clarificationNeeded:!1,alternativeCandidates:[]};let r=i.find(_=>_.san.toLowerCase()===t.trim().toLowerCase()||`${_.from}${_.to}`.toLowerCase()===t.trim().toLowerCase());if(r)return{query:t,matchedMove:r,san:r.san,confidence:1,probabilities:{[r.san]:1},clarificationNeeded:!1,alternativeCandidates:[]};let a={};for(let _ of i)a[_.san]=_.description;a.none="No legal candidate move matches what the player requested";let o={user_intent:t,board:{turn:e.turn(),in_check:e.isCheck(),fen:e.fen()},legal_moves:i.map(_=>({san:_.san,description:_.description}))},f=(await this.client.systemOne({state:o,questions:{matched_move:ue("Which legal chess move in `legal_moves` best fulfills the player's command in `user_intent`?",a)}})).answers.matched_move,m=f.choice,g=f.confidence,p=f.probabilities,v=Object.entries(p).filter(([_])=>_!=="none"&&_!==m).sort((_,M)=>M[1]-_[1]).map(([_])=>_);if(m==="none"||g<n)return{query:t,matchedMove:null,san:m,confidence:g,probabilities:p,clarificationNeeded:!0,alternativeCandidates:v.slice(0,3)};let x=i.find(_=>_.san===m)??null;return{query:t,matchedMove:x,san:m,confidence:g,probabilities:p,clarificationNeeded:!1,alternativeCandidates:v.slice(0,2)}}};var pt=["Quiet, solid, or prophylactic maneuver with minimal immediate confrontation","Normal central development or positional consolidation","Sharp or provocative move with direct tactical tension","High-risk sacrifice or explosive tactical clash"],Pi={pawn_break:"Advances a pawn to challenge or dissolve opponent pawn structure",piece_activation:"Develops or repositions a piece to an active central or attacking square",prophylaxis:"Prevents opponent's plan, stabilizes position, or secures king safety",tactical_strike:"Direct capture, check, fork, pin, or tactic to win material or mate",king_hunt:"Advances pieces or pawns directly against the enemy king",simplification:"Trades pieces to consolidate advantage or clarify position"},He=class{get client(){return Z()}async evaluateMove(e,t){let n=e.getBoardContext(),i={evaluated_move:{san:t.san,description:t.description,is_capture:t.isCapture,is_check:t.isCheck,piece:t.piece},board_context:{fen:n.fen,turn:n.turn,game_phase:n.gamePhase,material:n.materialBalance.description,recent_history:n.recentHistory}},r=await this.client.systemOne({state:i,questions:{tactical_sharpness:J("How sharp, tactical, or double-edged is the move `evaluated_move.san` in this position?",pt),strategic_theme:ue("Which primary strategic or tactical theme best characterizes `evaluated_move.san`?",Pi),king_attack:re("Does `evaluated_move.san` initiate or advance a direct attack against the enemy king?"),psychological_pressure:re("Is `evaluated_move.san` a provocative or high-pressure move that challenges the opponent mentally?")}}),a=r.answers.tactical_sharpness,o=r.answers.strategic_theme,l=r.answers.king_attack,f=r.answers.psychological_pressure,m=a.score,g=pt[Math.min(pt.length-1,Math.round(m))]??"Standard move",p="Standard Move";return m>=2.2?p="Sharp Tactical Clash":l.noul>=.7?p="King Assault Initiated":o.choice==="prophylaxis"?p="Prophylactic Squeeze":o.choice==="pawn_break"?p="Central Pawn Break":o.choice==="simplification"?p="Positional Simplification":m<=.6?p="Calm Positional Maneuver":p="Piece Activation",{san:t.san,tacticalSharpness:{score:m,level:g,confidence:a.confidence},strategicTheme:{theme:o.choice,confidence:o.confidence},kingAttackRisk:{probability:l.noul},psychologicalPressure:{probability:f.noul},commentaryBadge:p}}};var $i={tal:{id:"tal",name:"Mikhail Tal",title:"The Magician from Riga",quote:"You must take your opponent into a deep dark forest where 2+2=5, and the path leading out is only wide enough for one.",weights:{aggression:.45,prophylaxis:-.15,complexity:.5,materialGreed:-.2}},petrosian:{id:"petrosian",name:"Tigran Petrosian",title:"Iron Tigran",quote:"Nothing can be done against me; my position is so solid.",weights:{aggression:.05,prophylaxis:.65,complexity:-.3,materialGreed:.2}},capablanca:{id:"capablanca",name:"Jos\xE9 Ra\xFAl Capablanca",title:"The Chess Machine",quote:"A master plays simple chess, puts pieces where they belong, and simplifies into a clean endgame.",weights:{aggression:.2,prophylaxis:.35,complexity:-.4,materialGreed:.45}},coffeehouse:{id:"coffeehouse",name:"Coffeehouse Gambiteer",title:"Romantic Hustler",quote:"Checks are free, pawn storms are mandatory, and danger lurks on every rank.",weights:{aggression:.55,prophylaxis:-.35,complexity:.4,materialGreed:-.1}}},Ni=["Passive retreat, backward consolidation, or defensive block","Neutral developing maneuver or quiet regrouping","Forward thrust, central pressure, or active threat creation","Direct sacrifice, attack on the king, or fierce tactical challenge"],Bi=["Completely ignores king safety and opponent counterplay","Standard move with ordinary tactical exposure","Solid, patient reinforcement of weaknesses or squares","Deep prophylactic suppression of opponent counter-ideas"],Ri=["Clarifies position, forces trades, or liquidates tension","Steady, orderly position with clear structural goals","Introduces sharp asymmetry, unbalances, and multiple branches","Maximum chaos: highly volatile tactical minefield"],je=class{get client(){return Z()}async selectMove(e,t,n=5){let i=$i[t],r=e.getAnnotatedMoves();if(r.length===0)throw new Error("No legal moves available in current position.");let a=r.filter(v=>v.isCheck||v.isCapture),o=r.filter(v=>!v.isCheck&&!v.isCapture),l=[];a.length>0&&l.push(...a.slice(0,2)),o.length>0&&l.push(...o.slice(0,Math.max(2,n-l.length)));let f=l.slice(0,n),m=[];for(let v of f){let x={candidate_move:{san:v.san,description:v.description,is_capture:v.isCapture,is_check:v.isCheck},board:{turn:e.turn(),fen:e.fen(),material:e.getMaterialBalance().description}},_=await this.client.systemOne({state:x,questions:{aggression:J("How aggressive and attacking is `candidate_move.san`?",Ni),prophylaxis:J("How well does `candidate_move.san` ensure safety and stifle opponent counterplay?",Bi),complexity:J("How much tactical tension and complexity does `candidate_move.san` inject into the board?",Ri),material_greed:re("Is the move `candidate_move.san` primarily motivated by winning or defending material?")}}),M={aggression:_.answers.aggression.score,prophylaxis:_.answers.prophylaxis.score,complexity:_.answers.complexity.score,materialGreed:_.answers.material_greed.noul},Q=i.weights.aggression*M.aggression+i.weights.prophylaxis*M.prophylaxis+i.weights.complexity*M.complexity+i.weights.materialGreed*M.materialGreed;m.push({move:v,compositeScore:Math.round(Q*1e3)/1e3,dimensionScores:M})}m.sort((v,x)=>x.compositeScore-v.compositeScore);let g=m[0],p=`${i.name} (${i.title}) selected ${g.move.san} with composite score ${g.compositeScore} (Aggression: ${g.dimensionScores.aggression.toFixed(1)}, Prophylaxis: ${g.dimensionScores.prophylaxis.toFixed(1)}, Complexity: ${g.dimensionScores.complexity.toFixed(1)}, Greed: ${g.dimensionScores.materialGreed.toFixed(2)}).`;return{persona:i,selectedMove:g.move,rankedCandidates:m,rationale:p}}};var we=[{id:"immortal-game",title:"The Immortal Game",white:"Adolf Anderssen",black:"Lionel Kieseritzky",year:1851,event:"London (Casual match during 1st International Tournament)",result:"1-0",eco:"C33",opening:"King's Gambit Accepted",description:"Anderssen gave up both rooks and a bishop, followed by his queen, delivering checkmate with his three remaining minor pieces.",keyMoveIndex:38,moves:["e4","e5","f4","exf4","Bc4","Qh4+","Kf1","b5","Bxb5","Nf6","Nf3","Qh6","d3","Nh5","Nh4","Qg5","Nf5","c6","g4","Nf6","Rg1","cxb5","h4","Qg6","h5","Qg5","Qf3","Ng8","Bxf4","Qf6","Nc3","Bc5","Nd5","Qxb2","Bd6","Bxg1","e5","Qxa1+","Ke2","Na6","Nxg7+","Kd8","Qf6+","Nxf6","Be7#"]},{id:"opera-game",title:"The Opera Game",white:"Paul Morphy",black:"Duke of Brunswick & Count Isouard",year:1858,event:"Paris Opera House (Norma intermission)",result:"1-0",eco:"C41",opening:"Philidor Defense",description:"Morphy's quintessential demonstration of rapid development, open lines, and deflection queen sacrifice ending in checkmate with rook and bishop.",keyMoveIndex:30,moves:["e4","e5","Nf3","d6","d4","Bg4","dxe5","Bxf3","Qxf3","dxe5","Bc4","Nf6","Qb3","Qe7","Nc3","c6","Bg5","b5","Nxb5","cxb5","Bxb5+","Nbd7","O-O-O","Rd8","Rxd7","Rxd7","Rd1","Qe6","Bxd7+","Nxd7","Qb8+","Nxb8","Rd8#"]},{id:"game-of-the-century",title:"Game of the Century",white:"Donald Byrne",black:"Bobby Fischer (age 13)",year:1956,event:"Rosenwald Memorial Tournament, New York",result:"0-1",eco:"D92",opening:"Gr\xFCnfeld Defence, 5.Bf4",description:"A 13-year-old Bobby Fischer sacrifices his queen on move 17 (Be6!!) to unleash an unstoppable windmill attack with bishop and knight.",keyMoveIndex:33,moves:["Nf3","Nf6","c4","g6","Nc3","Bg7","d4","O-O","Bf4","d5","Qb3","dxc4","Qxc4","c6","e4","Nbd7","Rd1","Nb6","Qc5","Bg4","Bg5","Na4","Qa3","Nxc3","bxc3","Nxe4","Bxe7","Qb6","Bc4","Nxc3","Bc5","Rfe8+","Kf1","Be6","Bxb6","Bxc4+","Kg1","Ne2+","Kf1","Nxd4+","Kg1","Ne2+","Kf1","Nc3+","Kg1","axb6","Qb4","Ra4","Qxb6","Nxd1","h3","Rxa2","Kh2","Nxf2","Re1","Rxe1","Qd8+","Bf8","Nxe1","Bd5","Nf3","Ne4","Qb8","b5","h4","h5","Ne5","Kg7","Kg1","Bc5+","Kf1","Ng3+","Ke1","Bb4+","Kd1","Bb3+","Kc1","Ne2+","Kb1","Nc3+","Kc1","Rc2#"]},{id:"kasparov-immortal",title:"Kasparov's Immortal",white:"Garry Kasparov",black:"Veselin Topalov",year:1999,event:"Hoogovens Group A, Wijk aan Zee",result:"1-0",eco:"B07",opening:"Pirc Defense",description:"Kasparov sacrifices his rook on d4 (24. Rxd4!!) initiating a spectacular 15-move king hunt that drove the black king across the entire board.",keyMoveIndex:46,moves:["e4","d6","d4","Nf6","Nc3","g6","Be3","Bg7","Qd2","c6","f3","b5","Nge2","Nbd7","Bh6","Bxh6","Qxh6","Bb7","a3","e5","O-O-O","Qe7","Kb1","a6","Nc1","O-O-O","Nb3","exd4","Rxd4","c5","Rd1","Nb6","g3","Kb8","Na5","Ba8","Bh3","d5","Qf4+","Ka7","Rhe1","d4","Nd5","Nbxd5","exd5","Qd6","Rxd4","cxd4","Re7+","Kb6","Qxd4+","Kxa5","b4+","Ka4","Qc3","Qxd5","Ra7","Bb7","Rxb7","Qc4","Qxf6","Kxa3","Qxa6+","Kxb4","c3+","Kxc3","Qa1+","Kd2","Qb2+","Kd1","Bf1","Rd2","Rd7+","Rxd7","Bxc4","bxc4","Qxh8","Rd3","Qa8","c3","Qa4+","Ke1","f4","f5","Kc1","Rd2","Qa7"]},{id:"tal-larsen-1965",title:"Tal's Wild Central Sacrifice",white:"Mikhail Tal",black:"Bent Larsen",year:1965,event:"Candidates Semifinal, Bled, Match Game 10",result:"1-0",eco:"B57",opening:"Sicilian Defense, Richter-Rauzer",description:"Tal's famous intuitive piece sacrifice 16. Nxd5!! blowing open the center against Larsen's uncastled king to clinch the match.",keyMoveIndex:30,moves:["e4","c5","Nf3","Nc6","d4","cxd4","Nxd4","e6","Nc3","d6","Be3","Nf6","f4","Be7","Qf3","O-O","O-O-O","Qc7","Ndb5","Qb8","g4","a6","Nd4","Nxd4","Bxd4","b5","g5","Nd7","Bd3","b4","Nd5","exd5","exd5","f5","Rde1","Rf7","h4","Bb7","Bxf5","Rxf5","Rxe7","Ne5","Qe4","Qf8","fxe5","Rf4","Qe3","Rf3","Qe2","Qxe7","Qxf3","dxe5","Re1","Rd8","Rxe5","Qd6","Qf4","Rf8","Qe4","Bc8","b3","a5","h5","Bd7","h6"]}],Li={romantic_swashbuckler:"Cascading material sacrifices culminating in a forced mating net",dynamic_initiative:"Relentless piece tempo and coordinated piece pressure dominating passive defenders",positional_squeeze:"Prophylactic clamp, suffocating opponent counterplay before technical breakthrough",tactical_firestorm:"Sharp double-edged complications with king chases and critical calculate-or-die tactics"},mt=["Standard technical victory with routine exchanges","Well-played competitive game with solid tactical execution","Brilliant game featuring deep calculation and attractive piece play","Immortal artistic masterpiece that redefined chess literature"],gt=["Solid and quiet; long positional maneuvering behind closed pawns","Balanced fighting contest with strategic tension","Very sharp; frequent piece contact, king exposure, and tactical threats","Wild tactical hurricane; mutual piece sacrifices and all-out monarch assault"],We=class{get client(){return Z()}async classifyMatch(e){let t=e.moves[e.keyMoveIndex]??e.moves[e.moves.length-1]??"e4",n=Math.floor(e.keyMoveIndex/2)+1,i={match_meta:{id:e.id,title:e.title,white:e.white,black:e.black,year:e.year,eco:e.eco,opening:e.opening,result:e.result,total_moves:e.moves.length},turning_point:{move_number:n,san:t,description:e.description},moves_sample:e.moves.slice(0,30)},r=await this.client.systemOne({state:i,questions:{archetype:ue("Which historical chess archetype best classifies `match_meta.title`?",Li),brilliance:J("Rate the aesthetic and instructive brilliance of this classic match:",mt),sharpness:J("Rate the overall tactical sharpness and volatility of this game:",gt),decisive_sacrifice:re("Does this match feature a sound, decisive piece or queen sacrifice for the initiative?")}}),a=r.answers.archetype.choice,o=r.answers.brilliance.score,l=r.answers.sharpness.score,f=r.answers.decisive_sacrifice.noul>=.6,m=0,g=0;for(let U of e.moves)U.includes("+")||U.includes("x")||U.includes("#")?m++:U.toLowerCase()[0]>="a"&&U.toLowerCase()[0]<="h"&&!U.includes("O")&&g++;let p=Math.max(1,e.moves.length),v=Math.round(m/p*100),x=Math.round(g/p*100),_=Math.max(10,100-v-x),M=Math.round(_*.35),Q=`${e.title} (${e.year}) is a classic ${a.replace(/_/g," ")}. `;return o>=2.3?Q+="Widely celebrated as one of the finest artistic achievements in the history of the game.":Q+="A deeply instructive showcase of classical principles and aggressive tactical conversion.",{matchId:e.id,title:e.title,archetype:a.replace(/_/g," ").toUpperCase(),aestheticBrilliance:{score:o,level:mt[Math.min(mt.length-1,Math.round(o))]??"Masterpiece",confidence:r.answers.brilliance.confidence},overallSharpness:{score:l,level:gt[Math.min(gt.length-1,Math.round(l))]??"Sharp"},hasDecisiveSacrifice:f,turningPoint:{moveNumber:n,san:t,annotation:e.description},strategicBreakdown:{tacticalStrikesPct:v,pawnBreaksPct:x,prophylaxisPct:M,pieceActivationPct:_},verdict:Q}}};var Oi={p:"\u265F",n:"\u265E",b:"\u265D",r:"\u265C",q:"\u265B",k:"\u265A",P:"\u2659",N:"\u2658",B:"\u2657",R:"\u2656",Q:"\u2655",K:"\u2654"},q=new Le,Ki=new Ue,ds=new He,qi=new je,Fi=new We,oe=null,Ge=[],z="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",ps="tal",Se=null,ke=null,I=null,W=0,xe=null;function de(s){let e=document.getElementById("board");if(!e)return;e.innerHTML="";let[t,n]=s.split(" "),i=document.getElementById("turnDot"),r=document.getElementById("turnLabel");i&&r&&(n==="w"?(i.className="turn-dot white",r.innerText="White to move"):(i.className="turn-dot black",r.innerText="Black to move"));let a=(t??"").split("/");for(let o=0;o<8;o++){let l=0,f=a[o]??"";for(let m of f)if(isNaN(Number(m)))hs(o,l,m),l++;else for(let g=0;g<parseInt(m,10);g++)hs(o,l,null),l++}}function hs(s,e,t){let n=["a","b","c","d","e","f","g","h"],i=["8","7","6","5","4","3","2","1"],r=n[e]+i[s],a=(s+e)%2===0,o=document.createElement("div");if(o.className="square "+(a?"light":"dark"),o.dataset.sq=r,r===oe&&o.classList.add("selected"),r===Se&&o.classList.add("last-from"),r===ke&&o.classList.add("last-to"),oe&&Ge.some(f=>f.from===oe&&f.to===r)&&o.classList.add("target"),e===0){let l=document.createElement("span");l.className="coord-label coord-rank",l.innerText=i[s]??"",o.appendChild(l)}if(s===7){let l=document.createElement("span");l.className="coord-label coord-file",l.innerText=n[e]??"",o.appendChild(l)}if(t){let l=document.createElement("span");l.innerText=Oi[t]||t,o.appendChild(l)}o.onclick=()=>Qi(r),document.getElementById("board")?.appendChild(o)}function Ce(){Ge=q.getAnnotatedMoves();let s=q.getMaterialBalance(),e=document.getElementById("materialBalance");e&&(e.innerText=s.description||"Equal"),Di(q.history())}function Di(s){let e=document.getElementById("historyList");if(e){if(!s||s.length===0){e.innerHTML='<span style="color: #666;">No moves played yet</span>';return}e.innerHTML=s.map((t,n)=>`<span class="history-item">${n%2===0?Math.floor(n/2+1)+". ":""}${t}</span>`).join(" "),e.scrollTop=e.scrollHeight}}async function Qi(s){if(oe){let t=Ge.find(n=>n.from===oe&&n.to===s);if(t){await Ye(t.san),oe=null;return}}oe=Ge.some(t=>t.from===s)?s:null,de(z)}async function Ye(s){let e=q.makeMove(s);if(e){Se=e.from,ke=e.to,z=q.fen(),de(z),Ce();let t=await ds.evaluateMove(q,e);ms(t)}}function Ui(s){return s?s.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "):"--"}function ms(s){if(!s)return;let e=document.getElementById("lastMoveBadge");e&&(e.innerText=s.commentaryBadge||"Move Evaluated");let t=document.getElementById("mSharp");t&&(t.innerText=s.tacticalSharpness.score.toFixed(1));let n=document.getElementById("mSharpBar");n&&(n.style.width=Math.min(100,s.tacticalSharpness.score/3*100)+"%");let i=document.getElementById("mTheme");i&&(i.innerText=Ui(s.strategicTheme.theme));let r=document.getElementById("mThemeConf");r&&(r.innerText="Confidence: "+(s.strategicTheme.confidence*100).toFixed(0)+"%");let a=document.getElementById("mKing");a&&(a.innerText=(s.kingAttackRisk.probability*100).toFixed(0)+"%");let o=document.getElementById("mKingBar");o&&(o.style.width=s.kingAttackRisk.probability*100+"%");let l=document.getElementById("mPressure");l&&(l.innerText=(s.psychologicalPressure.probability*100).toFixed(0)+"%");let f=document.getElementById("mPressureBar");f&&(f.style.width=s.psychologicalPressure.probability*100+"%")}function gs(){let s=document.getElementById("lastMoveBadge");s&&(s.innerText="Waiting for move...");let e=document.getElementById("mSharp");e&&(e.innerText="--");let t=document.getElementById("mSharpBar");t&&(t.style.width="0%");let n=document.getElementById("mTheme");n&&(n.innerText="--");let i=document.getElementById("mThemeConf");i&&(i.innerText="Confidence: --");let r=document.getElementById("mKing");r&&(r.innerText="--");let a=document.getElementById("mKingBar");a&&(a.style.width="0%");let o=document.getElementById("mPressure");o&&(o.innerText="--");let l=document.getElementById("mPressureBar");l&&(l.style.width="0%")}async function vs(){let s=document.getElementById("nlInput");if(!s)return;let e=s.value.trim();if(!e)return;let t=document.getElementById("resolutionResult"),n=document.getElementById("resText"),i=document.getElementById("resConf");t&&(t.style.display="flex"),n&&(n.innerText="Resolving intent via TypeSafe Choice..."),i&&(i.innerText="");let r=await Ki.resolveIntent(q,e);r.matchedMove?(n&&(n.innerText="Matched: "+r.matchedMove.san+" ("+r.matchedMove.description+")"),i&&(i.innerText=(r.confidence*100).toFixed(1)+"% confidence"),s.value="",await Ye(r.matchedMove.san)):(n&&(n.innerText="Ambiguous: "+(r.alternativeCandidates?.join(", ")||"No legal match")),i&&(i.innerText="Low confidence ("+(r.confidence*100).toFixed(1)+"%)"))}function Hi(s){let e=document.getElementById("nlInput");e&&(e.value=s,vs())}function ji(s,e){ps=s,document.querySelectorAll(".persona-card").forEach(t=>t.classList.remove("active")),e.classList.add("active")}async function Wi(){let s=document.getElementById("personaRationale");s&&(s.innerText="Evaluating candidates with TypeSafe Composite Scoring...");try{let e=await qi.selectMove(q,ps);s&&(s.innerText=e.rationale),await Ye(e.selectedMove.san)}catch(e){s&&(s.innerText=e?.message||"Unable to make persona move.")}}function Gi(){ee(),q.reset(),z=q.fen(),Se=null,ke=null,oe=null;let s=document.getElementById("resolutionResult");s&&(s.style.display="none"),de(z),Ce(),gs()}function Yi(){ee(),q.chess.undo(),z=q.fen(),de(z),Ce()}function Vi(){let s=document.getElementById("matchSelect");s&&(s.innerHTML=we.map(e=>`<option value="${e.id}">${e.title} (${e.year}) \u2014 ${e.white} vs ${e.black}</option>`).join(""),we.length>0&&ys(we[0].id))}function Ji(s){s&&ys(s)}function ys(s){if(ee(),I=we.find(f=>f.id===s)||null,!I)return;let e=document.getElementById("matchMetaBox");e&&(e.style.display="block");let t=document.getElementById("matchPlayers");t&&(t.innerText=`${I.white} vs ${I.black}`);let n=document.getElementById("matchYearEvent");n&&(n.innerText=`${I.year} \xB7 ${I.event}`);let i=document.getElementById("matchDesc");i&&(i.innerText=I.description);let r=document.getElementById("matchEco");r&&(r.innerText=I.eco);let a=document.getElementById("matchOpening");a&&(a.innerText=I.opening);let o=document.getElementById("matchResult");o&&(o.innerText=I.result),ae(0);let l=document.getElementById("classificationCard");l&&(l.style.display="none")}async function ae(s){if(!I)return;let e=Math.max(0,Math.min(I.moves.length,s));W=e;let t=document.getElementById("replayMoveLabel");t&&(t.innerText=`Move ${W} / ${I.moves.length}`);let n=W/Math.max(1,I.moves.length)*100,i=document.getElementById("replayProgressBar");i&&(i.style.width=n+"%");let r=document.getElementById("replayTurnLabel");if(r)if(W===0)r.innerText="Starting Position";else{let o=I.moves[W-1],l=Math.floor((W-1)/2)+1,f=(W-1)%2===0?"White":"Black";r.innerText=`${l}${f==="White"?".":"..."} ${o}`}q.reset();let a=null;for(let o=0;o<e;o++){let l=q.makeMove(I.moves[o]);o===e-1&&(a=l)}if(z=q.fen(),a?(Se=a.from,ke=a.to):(Se=null,ke=null),Ce(),de(z),a){let o=await ds.evaluateMove(q,a);ms(o)}else gs()}function zi(){ee(),ae(0)}function Xi(){ee(),W>0&&ae(W-1)}function _s(){I&&W<I.moves.length&&ae(W+1)}function Zi(){ee(),I&&ae(I.moves.length)}function er(){ee(),I&&ae(I.keyMoveIndex)}function tr(){if(xe)ee();else{if(!I)return;W>=I.moves.length&&ae(0);let s=document.getElementById("autoPlayBtn");s&&(s.innerText="Pause"),xe=setInterval(()=>{I&&W<I.moves.length?_s():ee()},1200)}}function ee(){if(xe){clearInterval(xe),xe=null;let s=document.getElementById("autoPlayBtn");s&&(s.innerText="Auto Play")}}async function sr(){if(!I)return;let s=document.getElementById("classifyBtn");s&&(s.innerText="Classifying with System One...",s.disabled=!0);try{let e=await Fi.classifyMatch(I),t=document.getElementById("classificationCard");t&&(t.style.display="flex");let n=document.getElementById("classArchetype");n&&(n.innerText=e.archetype);let i=document.getElementById("classSacrifice");i&&(i.innerText=e.hasDecisiveSacrifice?"Decisive Sacrifice Confirmed":"No Decisive Sacrifice");let r=document.getElementById("classBrillianceScore");r&&(r.innerText=e.aestheticBrilliance.score.toFixed(1)+" / 3.0");let a=document.getElementById("classBrillianceLevel");a&&(a.innerText=e.aestheticBrilliance.level);let o=document.getElementById("classSharpnessScore");o&&(o.innerText=e.overallSharpness.score.toFixed(1)+" / 3.0");let l=document.getElementById("classSharpnessLevel");l&&(l.innerText=e.overallSharpness.level);let f=document.getElementById("classTurningMove");f&&(f.innerText=e.turningPoint.san);let m=document.getElementById("classTurningNum");m&&(m.innerText=`Move ${e.turningPoint.moveNumber}`);let g=document.getElementById("bdTactical");g&&(g.innerText=e.strategicBreakdown.tacticalStrikesPct+"%");let p=document.getElementById("bdPawn");p&&(p.innerText=e.strategicBreakdown.pawnBreaksPct+"%");let v=document.getElementById("bdPiece");v&&(v.innerText=e.strategicBreakdown.pieceActivationPct+"%");let x=document.getElementById("bdProphyl");x&&(x.innerText=e.strategicBreakdown.prophylaxisPct+"%");let _=document.getElementById("classVerdict");_&&(_.innerText=e.verdict)}catch(e){console.error("Failed to classify match",e)}finally{s&&(s.innerText="Classify Match with System One",s.disabled=!1)}}function vt(){let s=us(),e=document.getElementById("backendBadge"),t=document.getElementById("backendStatusDot"),n=document.getElementById("backendStatusText"),i=document.getElementById("keyBtnLabel");s.isLive?(e&&(e.className="badge-status"),t&&(t.className="status-dot live"),n&&(n.innerText="Live API (jev-latest)"),i&&(i.innerText=s.maskedKey||"Live Key")):(e&&(e.className="badge-status badge-sim"),t&&(t.className="status-dot sim"),n&&(n.innerText="Simulation Mode (jev-latest calibrated)"),i&&(i.innerText="API Key"))}function nr(){let s=document.getElementById("keyModal");s&&(s.style.display="flex");let e=document.getElementById("modalStatus");e&&(e.innerText="")}function yt(){let s=document.getElementById("keyModal");s&&(s.style.display="none")}function ir(){let s=document.getElementById("keyInput"),e=document.getElementById("toggleVisibilityBtn");if(!s||!e)return;let t=s.type==="password";s.type=t?"text":"password",e.innerText=t?"Hide":"Show"}function rr(){let s=document.getElementById("keyInput");if(!s)return;let e=s.value.trim(),t=document.getElementById("modalStatus");if(!e){t&&(t.innerHTML='<span style="color: var(--danger)">Please enter a valid API key.</span>');return}dt(e),t&&(t.innerHTML='<span style="color: var(--success)">Successfully connected to live jev-latest model.</span>'),s.value="",vt(),setTimeout(yt,1e3)}function or(){dt(null);let s=document.getElementById("modalStatus");s&&(s.innerHTML='<span style="color: var(--warning)">Switched back to calibrated simulation mode.</span>'),vt(),setTimeout(yt,800)}var P=window;P.renderBoard=de;P.playMove=Ye;P.resolveAndPlayMove=vs;P.setChip=Hi;P.selectPersona=ji;P.makePersonaMove=Wi;P.resetGame=Gi;P.undoMove=Yi;P.onMatchSelectChange=Ji;P.goToReplayMove=ae;P.stepFirst=zi;P.stepPrev=Xi;P.stepNext=_s;P.stepLast=Zi;P.jumpToTurningPoint=er;P.toggleAutoPlay=tr;P.classifyCurrentMatch=sr;P.openKeyModal=nr;P.closeKeyModal=yt;P.toggleKeyVisibility=ir;P.saveApiKey=rr;P.clearApiKey=or;window.addEventListener("DOMContentLoaded",()=>{de(z),Ce(),vt(),Vi()});})();
16
+ /*! Bundled license information:
17
+
18
+ chess.js/dist/esm/chess.js:
19
+ (**
20
+ * @license
21
+ * Copyright (c) 2025, Jeff Hlywa (jhlywa@gmail.com)
22
+ * All rights reserved.
23
+ *
24
+ * Redistribution and use in source and binary forms, with or without
25
+ * modification, are permitted provided that the following conditions are met:
26
+ *
27
+ * 1. Redistributions of source code must retain the above copyright notice,
28
+ * this list of conditions and the following disclaimer.
29
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
30
+ * this list of conditions and the following disclaimer in the documentation
31
+ * and/or other materials provided with the distribution.
32
+ *
33
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
34
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
37
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
38
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
39
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
40
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
41
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
43
+ * POSSIBILITY OF SUCH DAMAGE.
44
+ *)
45
+ */