@konoui/mjimage 0.0.61 → 0.1.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.
package/dist/index.cjs CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var Hs=Object.defineProperty;var Ws=(n,t,e)=>t in n?Hs(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var _=(n,t,e)=>Ws(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Fe="MS Gothic, sans-serif",nt={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Ie={WIDTH:125,HEIGHT:27.5},Bn={BASE:40},q=",",p={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},y={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},b={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},A={E:"1w",S:"2w",W:"3w",N:"4w"},k={E1:"1w1",E2:"1w2",E3:"1w3",E4:"1w4",S1:"2w1",S2:"2w2",S3:"2w3",S4:"2w4",W1:"3w1",W2:"3w2",W3:"3w3",W4:"3w4",N1:"4w1",N2:"4w2",N3:"4w3",N4:"4w4"},fe={[A.E]:"東",[A.S]:"南",[A.W]:"西",[A.N]:"北"},Ge={[k.E1]:"東1局",[k.E2]:"東2局",[k.E3]:"東3局",[k.E4]:"東4局",[k.S1]:"南1局",[k.S2]:"南2局",[k.S3]:"南3局",[k.S4]:"南4局",[k.W1]:"西1局",[k.W2]:"西2局",[k.W3]:"西3局",[k.W4]:"西4局",[k.N1]:"北1局",[k.N2]:"北2局",[k.N3]:"北3局",[k.N4]:"北4局"};function S(n,t){if(!n)throw new Error(t)}class Bs{constructor(t="東",e="2"){_(this,"ctx",null);_(this,"strText");_(this,"numText");_(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),S(this.ctx,"context is null"));const s=this.ctx;s.font=e;const r=s.measureText(t);let i=r.width,o=r.actualBoundingBoxAscent+r.actualBoundingBoxDescent;return[i,o]});_(this,"measureFontContext",(t,e)=>{const s={family:t,size:e},r=`${s.size}px ${s.family}`,[i,o]=this.measure(this.strText,r),[a,c]=this.measure(this.numText,r);return{font:{family:t,size:e},textWidth:i,textHeight:o,numWidth:a,numHeight:c}});_(this,"measureTableFontContext",t=>{const e=this.measureFontContext(Fe,Bn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class Ds{constructor(t){_(this,"input");_(this,"position");_(this,"nextPosition");_(this,"char");_(this,"eof","\0");this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Xt=(n,t)=>{if(n.t==t.t){if(C(n)&&C(t)){if(n.has(y.RED))return-1;if(t.has(y.RED))return 1}return n.n-t.n}const e={[p.M]:1,[p.P]:2,[p.S]:3,[p.Z]:4,[p.BACK]:5};return e[n.t]-e[t.t]},Ks=(n,t)=>{const e={[y.HORIZONTAL]:1,[y.TSUMO]:2,[y.RON]:3,[y.DORA]:4,[y.COLOR_GRAYSCALE]:5,[y.RED]:6};return e[n]-e[t]},Dn=n=>{const t=[];n.forEach((s,r)=>{s.has(y.HORIZONTAL)&&t.push(r)});const e=n.filter(s=>!s.has(y.HORIZONTAL)).sort(Xt);return t.forEach(s=>{e.splice(s,0,n[s])}),e};function C(n){return n.isNum()&&n.n==5}function Ls(n){for(const t of Object.values(p))if(t==n)return[t,!0];return[p.BACK,!1]}class w{constructor(t,e,s=[]){this.t=t,this.n=e,this.ops=s}static from(t){const e=new W(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===p.BACK?this.t:`${[...this.ops].sort(Ks).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,s=(t==null?void 0:t.n)??this.n,r=t!=null&&t.removeAll?[]:this.ops.filter(o=>Array.isArray(t==null?void 0:t.remove)?!t.remove.includes(o):(t==null?void 0:t.remove)!=o),i=new Set([...r]);return t!=null&&t.add&&(Array.isArray(t.add)?t.add.forEach(o=>i.add(o)):i.add(t.add)),new w(e,s,Array.from(i))}has(t){return this.ops.includes(t)}isNum(){return this.t==p.M||this.t==p.P||this.t==p.S}equals(t){return t.t==p.BACK&&this.t==p.BACK?!0:this.t==t.t&&this.n==t.n}}class T{constructor(t,e){_(this,"_tiles");_(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Dn(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Xt);return}}static from(t){const e=new W(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=T.from(t.tiles),s=e.type;if(!(t.type==b.PAIR||t.type==b.ISOLATED||t.type==b.THREE||t.type==b.RUN)&&s!=t.type)throw new Error(`input type is ${t.type} but got is ${s}: ${t.tiles}`);return oe(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){return[b.PON.toString(),b.CHI.toString(),b.DAI_KAN.toString(),b.SHO_KAN.toString(),b.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t==null?void 0:t.replace,s=[...this.tiles];return e&&(s[e.idx]=e.tile),oe(s,this._type)}}const _t=n=>{let t="";for(const e of n){if(e.t==p.BACK)return n.join("");t+=e.toString().slice(0,-1)}return`${t}${n[0].t}`},Ze=n=>{let t=n[0].t,e="";for(const r of n){const i=r.t,o=i==p.BACK?r.toString():r.toString().slice(0,-1);i!=t&&t!=p.BACK&&(e+=t),t=i,e+=o}const s=n.at(-1);return s.t!=p.BACK&&(e+=s.t),e};class Z extends T{constructor(t){super(t,b.CHI)}static from(t){return T.deserialize({tiles:t,type:b.CHI})}toString(){return _t(this.tiles)}}class V extends T{constructor(t){super(t,b.PON)}static from(t){return T.deserialize({tiles:t,type:b.PON})}toString(){return _t(this.tiles)}}class R extends T{constructor(t){const e=t.filter(r=>r.t!=p.BACK),s=e[0];if(e.length<t.length){if(C(s)){const r=new w(s.t,5);super([r.clone({add:y.RED}),r,r,r],b.AN_KAN);return}super([s,s,s,s],b.AN_KAN);return}super(t,b.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:y.RED}),e=C(t)?t.clone({add:y.RED}):t;return[new w(p.BACK,0),e,t,new w(p.BACK,0)]}static from(t){return T.deserialize({tiles:t,type:b.AN_KAN})}toString(){return Ze(this.tilesWithBack)}}class Y extends T{constructor(t){super(t,b.DAI_KAN)}static from(t){return T.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return _t(this.tiles)}}class D extends T{constructor(t){super(t,b.SHO_KAN)}static from(t){return T.deserialize({tiles:t,type:b.SHO_KAN})}static fromPon(t,e){const s=t.tiles.findIndex(i=>i.has(y.HORIZONTAL)),r=[...t.tiles];return r.splice(s,0,e.clone({add:y.HORIZONTAL})),new D(r)}toString(){return _t(this.tiles)}}class H extends T{constructor(t,e){super([t,e],b.PAIR)}toString(){return _t(this.tiles)}static from(t){return T.deserialize({tiles:t,type:b.PAIR})}}class z extends T{constructor(t){super(t,b.THREE)}static from(t){return T.deserialize({tiles:t,type:b.THREE})}toString(){return _t(this.tiles)}}class Q extends T{constructor(t){super(t,b.RUN)}static from(t){return T.deserialize({tiles:t,type:b.RUN})}toString(){return _t(this.tiles)}}class Ve extends T{constructor(t){super([t],b.ISOLATED)}static from(t){return T.deserialize({tiles:t,type:b.ISOLATED})}toString(){return this.tiles[0].toString()}}class kt extends T{constructor(t){super(t,b.HAND)}static from(t){return T.deserialize({tiles:t,type:b.HAND})}toString(){return Ze(this.tiles)}}class Je extends T{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Ze(this.tiles)}}const oe=(n,t)=>{switch(t){case b.CHI:return new Z([n[0],n[1],n[2]]);case b.PON:return new V([n[0],n[1],n[2]]);case b.AN_KAN:return new R(n);case b.DAI_KAN:return new Y(n);case b.SHO_KAN:return new D(n);case b.THREE:return new z(n);case b.RUN:return new Q(n);case b.PAIR:return new H(n[0],n[1]);case b.ISOLATED:return new Ve(n[0]);case b.HAND:return new kt(n);default:return new Je(n,t)}};class W{constructor(t){_(this,"maxInputLength",600);this.input=t,this.input=t.replace(/\s/g,"")}parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=q)}tileSeparators(){const t=new Ds(this.input),e=[];let s=[];for(this.validate(this.input);;){t.skipWhitespace();const r=t.char;if(r===t.eof)break;if(r==q){e.push(q),t.readChar();continue}const[i,o]=bn(r,s);if(o){if(i==p.BACK){e.push(new w(i,0)),t.readChar();continue}e.push(...js(s,i)),s=[],t.readChar();continue}else{const[a,c]=Us(t);if(c){s.push(a),t.readChar();continue}const[l,u]=Kn(r);if(!u)throw new Error(`encounter unexpected number. n: ${l}, current: ${r}, input: ${t.input}`);s.push({n:l})}t.readChar()}if(s.length>0)throw new Error(`remaining values ${s.toString()}`);return e}makeBlocks(t){let e=[];const s=[];if(t.length==0)return s;for(const o of t){if(o==q){const a=wn(e),c=oe(e,a);s.push(c),e=[];continue}e.push(o)}const r=wn(e),i=oe(e,r);return s.push(i),e=[],s}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[s,r]=bn(e,[new w(p.BACK,1)]);if(!r)throw new Error(`last character: ${e} is not type value: ${t}`)}}function wn(n){if(n.length===0)return b.UNKNOWN;if(n.length===1)return n[0].has(y.DORA)?b.IMAGE_DORA:n[0].has(y.TSUMO)?b.TSUMO:b.HAND;const t=n.every(i=>i.equals(n[0])),e=n.filter(i=>i.has(y.HORIZONTAL)).length,s=n.filter(i=>i.has(y.TSUMO)||i.has(y.DORA)).length,r=n.filter(i=>i.t==p.BACK).length;if(s>0)return b.UNKNOWN;if(e==0&&r==0)return b.HAND;if(n.length===3&&r===0)return t?b.PON:e==1&&zs(n)?b.CHI:b.IMAGE_DISCARD;if(n.length==4&&r==2)return b.AN_KAN;if(n.length==4&&t){if(e==1)return b.DAI_KAN;if(e==2)return b.SHO_KAN}return e==1||s==0?b.IMAGE_DISCARD:b.UNKNOWN}function zs(n){const t=[...n].sort(Xt);if(t.some(s=>t[0].t!=s.t))return!1;const e=t.map(s=>s.n);for(let s=0;s<e.length-1;s++)if(e[s]!=e[s+1]-1)return!1;return!0}function js(n,t){return n.map(e=>{const s=new w(t,e.n,e.ops);return s.isNum()&&s.n==0?s.clone({n:5,add:y.RED}):s})}function bn(n,t){const[e,s]=Ls(n);if(s)return[e,!0];if((n==="w"||n==="d")&&t.length>0){for(let i=0;i<t.length;i++){const o=t[i];n==="d"&&(t[i].n=o.n+4)}return[p.Z,!0]}return[p.BACK,!1]}function Kn(n){const t=Number(n),e=0<=t&&t<=9;return[t,e]}function Us(n){const t=Object.values(y);if(!t.includes(n.char))return[new w(p.BACK,0),!1];const e=[];for(let s=0;s<4;s++){const r=n.peekCharN(s);if(t.includes(r))e.push(r);else{const[i,o]=Kn(r);if(!o)break;for(const c of e)n.readChar();const a=new w(p.BACK,i,e);if(a.has(y.RED)&&a.n!=5)throw new Error(`found ${y.RED} but number is not 5: ${i}`);if(a.has(y.DORA)&&a.has(y.TSUMO))throw new Error(`unable to specify both ${y.DORA} and ${y.TSUMO}`);return[a,!0]}}return[new w(p.BACK,0),!1]}function $(n,t=!1){const e={[A.E]:n,[A.S]:n,[A.W]:n,[A.N]:n};if(t)for(let s of Object.values(A))e[s]=structuredClone(n);return e}const Gt=n=>{let t=n.substring(0,2),e=Number(n.substring(2,3));return e==4?(e=1,t=gt(t)):e++,`${t}${e}`},Fs=n=>Gt(Gt(Gt(n))),gt=n=>{let t=Number(n.toString()[0]);return t=t%4+1,`${t}w`},pe=n=>{let t=Number(n.toString()[0]);const e=[1,4,3,2],s=e.indexOf(t);return`${e[(s+1)%e.length]}w`},Oe=(n,t,e)=>{const s=Math.abs(Number(n[0])-Number(t[0]));return S(s==1||s==2||s==3),e==b.PON?s==3?0:s==2?1:2:s==3?0:s==1?3:2};function _n(n){return typeof n>"u"}function ke(n,t=0){return{a:1,c:0,e:n,b:0,d:1,f:t}}function Xe(...n){n=Array.isArray(n[0])?n[0]:n;const t=(e,s)=>({a:e.a*s.a+e.c*s.b,c:e.a*s.c+e.c*s.d,e:e.a*s.e+e.c*s.f+e.e,b:e.b*s.a+e.d*s.b,d:e.b*s.c+e.d*s.d,f:e.b*s.e+e.d*s.f+e.f});switch(n.length){case 0:throw new Error("no matrices provided");case 1:return n[0];case 2:return t(n[0],n[1]);default:{const[e,s,...r]=n,i=t(e,s);return Xe(i,...r)}}}function Gs(...n){return Xe(...n)}const{cos:Zs,sin:Vs,PI:Js}=Math;function Xs(n,t,e){const s=Zs(n),r=Vs(n),i={a:s,c:-r,e:0,b:r,d:s,f:0};return _n(t)||_n(e)?i:Xe([ke(t,e),i,ke(-t,-e)])}function Ys(n,t=void 0,e=void 0){return Xs(n*Js/180,t,e)}function qs(n){return Qs(n)}function Qs(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}function tr(n,t){function e(){this.constructor=n}e.prototype=t.prototype,n.prototype=new e}function ge(n,t,e,s){var r=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(r,ge.prototype),r.expected=t,r.found=e,r.location=s,r.name="SyntaxError",r}tr(ge,Error);function be(n,t,e){return e=e||" ",n.length>t?n:(t-=n.length,e+=e.repeat(t),n+e.slice(0,t))}ge.prototype.format=function(n){var t="Error: "+this.message;if(this.location){var e=null,s;for(s=0;s<n.length;s++)if(n[s].source===this.location.source){e=n[s].text.split(/\r\n|\n|\r/g);break}var r=this.location.start,i=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(r):r,o=this.location.source+":"+i.line+":"+i.column;if(e){var a=this.location.end,c=be("",i.line.toString().length," "),l=e[r.line-1],u=r.line===a.line?a.column:l.length+1,h=u-r.column||1;t+=`
1
+ "use strict";var Ws=Object.defineProperty;var Bs=(n,t,e)=>t in n?Ws(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var E=(n,t,e)=>Bs(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ge="MS Gothic, sans-serif",it={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},ke={WIDTH:125,HEIGHT:27.5},Dn={BASE:40},et=",",p={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},y={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},_={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},A={E:"1w",S:"2w",W:"3w",N:"4w"},C={E1:"1w1",E2:"1w2",E3:"1w3",E4:"1w4",S1:"2w1",S2:"2w2",S3:"2w3",S4:"2w4",W1:"3w1",W2:"3w2",W3:"3w3",W4:"3w4",N1:"4w1",N2:"4w2",N3:"4w3",N4:"4w4"},ge={[A.E]:"東",[A.S]:"南",[A.W]:"西",[A.N]:"北"},Ze={[C.E1]:"東1局",[C.E2]:"東2局",[C.E3]:"東3局",[C.E4]:"東4局",[C.S1]:"南1局",[C.S2]:"南2局",[C.S3]:"南3局",[C.S4]:"南4局",[C.W1]:"西1局",[C.W2]:"西2局",[C.W3]:"西3局",[C.W4]:"西4局",[C.N1]:"北1局",[C.N2]:"北2局",[C.N3]:"北3局",[C.N4]:"北4局"};function I(n,t){if(!n)throw new Error(t)}class Ds{constructor(t="東",e="2"){E(this,"ctx",null);E(this,"strText");E(this,"numText");E(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),I(this.ctx,"context is null"));const s=this.ctx;s.font=e;const r=s.measureText(t);let i=r.width,o=r.actualBoundingBoxAscent+r.actualBoundingBoxDescent;return[i,o]});E(this,"measureFontContext",(t,e)=>{const s={family:t,size:e},r=`${s.size}px ${s.family}`,[i,o]=this.measure(this.strText,r),[a,c]=this.measure(this.numText,r);return{font:{family:t,size:e},textWidth:i,textHeight:o,numWidth:a,numHeight:c}});E(this,"measureTableFontContext",t=>{const e=this.measureFontContext(Ge,Dn.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class Ks{constructor(t){E(this,"input");E(this,"position");E(this,"nextPosition");E(this,"char");E(this,"eof","\0");this.input=t,this.position=0,this.nextPosition=0,this.char=this.readChar()}readChar(){return this.nextPosition>=this.input.length?(this.char=this.eof,this.char):(this.char=this.input[this.nextPosition],this.position=this.nextPosition,this.nextPosition++,this.char)}peekChar(){return this.nextPosition>=this.input.length?this.eof:this.input[this.nextPosition]}peekCharN(t){if(t<0)throw new Error("arg must be positive value");return this.position+t>=this.input.length?this.eof:this.input[this.position+t]}prevChar(){return this.position>=this.input.length?this.eof:this.position>0?this.input[this.position-1]:this.eof}skipWhitespace(){for(;this.isWhitespace(this.char);)this.readChar()}isWhitespace(t){return/\s/.test(t)}}const Xt=(n,t)=>{if(n.t==t.t){if(x(n)&&x(t)){if(n.has(y.RED))return-1;if(t.has(y.RED))return 1}return n.n-t.n}const e={[p.M]:1,[p.P]:2,[p.S]:3,[p.Z]:4,[p.BACK]:5};return e[n.t]-e[t.t]},Ls=(n,t)=>{const e={[y.HORIZONTAL]:1,[y.TSUMO]:2,[y.RON]:3,[y.DORA]:4,[y.COLOR_GRAYSCALE]:5,[y.RED]:6};return e[n]-e[t]},Kn=n=>{const t=[];n.forEach((s,r)=>{s.has(y.HORIZONTAL)&&t.push(r)});const e=n.filter(s=>!s.has(y.HORIZONTAL)).sort(Xt);return t.forEach(s=>{e.splice(s,0,n[s])}),e};function x(n){return n.isNum()&&n.n==5}function zs(n){for(const t of Object.values(p))if(t==n)return[t,!0];return[p.BACK,!1]}class w{constructor(t,e,s=[]){this.t=t,this.n=e,this.ops=s}static from(t){const e=new B(t).tiles();if(e.length!=1)throw new Error(`input is not a single tile ${t}`);return e[0]}toString(){return this.t===p.BACK?this.t:`${[...this.ops].sort(Ls).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,s=(t==null?void 0:t.n)??this.n,r=t!=null&&t.removeAll?[]:this.ops.filter(o=>Array.isArray(t==null?void 0:t.remove)?!t.remove.includes(o):(t==null?void 0:t.remove)!=o),i=new Set([...r]);return t!=null&&t.add&&(Array.isArray(t.add)?t.add.forEach(o=>i.add(o)):i.add(t.add)),new w(e,s,Array.from(i))}has(t){return this.ops.includes(t)}isNum(){return this.t==p.M||this.t==p.P||this.t==p.S}equals(t){return t.t==p.BACK&&this.t==p.BACK?!0:this.t==t.t&&this.n==t.n}}class O{constructor(t,e){E(this,"_tiles");E(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Kn(this._tiles);return}if(this._type!=_.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Xt);return}}static from(t){const e=new B(t).parse();if(e.length!=1)throw new Error(`block must be 1: ${t}`);return e[0]}static deserialize(t){const e=O.from(t.tiles),s=e.type;if(!(t.type==_.PAIR||t.type==_.ISOLATED||t.type==_.THREE||t.type==_.RUN)&&s!=t.type)throw new Error(`input type is ${t.type} but got is ${s}: ${t.tiles}`);return ae(e.tiles,t.type)}serialize(){return{tiles:this.toString(),type:this.type}}toJSON(){return this.serialize()}get type(){return this._type}get tiles(){return this._tiles}is(t){return this._type==t}isCalled(){return[_.PON.toString(),_.CHI.toString(),_.DAI_KAN.toString(),_.SHO_KAN.toString(),_.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t==null?void 0:t.replace,s=[...this.tiles];return e&&(s[e.idx]=e.tile),ae(s,this._type)}}const Nt=n=>{let t="";for(const e of n){if(e.t==p.BACK)return n.join("");t+=e.toString().slice(0,-1)}return`${t}${n[0].t}`},Ve=n=>{let t=n[0].t,e="";for(const r of n){const i=r.t,o=i==p.BACK?r.toString():r.toString().slice(0,-1);i!=t&&t!=p.BACK&&(e+=t),t=i,e+=o}const s=n.at(-1);return s.t!=p.BACK&&(e+=s.t),e};class J extends O{constructor(t){super(t,_.CHI)}static from(t){return O.deserialize({tiles:t,type:_.CHI})}toString(){return Nt(this.tiles)}}class Y extends O{constructor(t){super(t,_.PON)}static from(t){return O.deserialize({tiles:t,type:_.PON})}toString(){return Nt(this.tiles)}}class M extends O{constructor(t){const e=t.filter(r=>r.t!=p.BACK),s=e[0];if(e.length<t.length){if(x(s)){const r=new w(s.t,5);super([r.clone({add:y.RED}),r,r,r],_.AN_KAN);return}super([s,s,s,s],_.AN_KAN);return}super(t,_.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:y.RED}),e=x(t)?t.clone({add:y.RED}):t;return[new w(p.BACK,0),e,t,new w(p.BACK,0)]}static from(t){return O.deserialize({tiles:t,type:_.AN_KAN})}toString(){return Ve(this.tilesWithBack)}}class Q extends O{constructor(t){super(t,_.DAI_KAN)}static from(t){return O.deserialize({tiles:t,type:_.DAI_KAN})}toString(){return Nt(this.tiles)}}class K extends O{constructor(t){super(t,_.SHO_KAN)}static from(t){return O.deserialize({tiles:t,type:_.SHO_KAN})}static fromPon(t,e){const s=t.tiles.findIndex(i=>i.has(y.HORIZONTAL)),r=[...t.tiles];return r.splice(s,0,e.clone({add:y.HORIZONTAL})),new K(r)}toString(){return Nt(this.tiles)}}class W extends O{constructor(t,e){super([t,e],_.PAIR)}toString(){return Nt(this.tiles)}static from(t){return O.deserialize({tiles:t,type:_.PAIR})}}class U extends O{constructor(t){super(t,_.THREE)}static from(t){return O.deserialize({tiles:t,type:_.THREE})}toString(){return Nt(this.tiles)}}class nt extends O{constructor(t){super(t,_.RUN)}static from(t){return O.deserialize({tiles:t,type:_.RUN})}toString(){return Nt(this.tiles)}}class Je extends O{constructor(t){super([t],_.ISOLATED)}static from(t){return O.deserialize({tiles:t,type:_.ISOLATED})}toString(){return this.tiles[0].toString()}}class Ct extends O{constructor(t){super(t,_.HAND)}static from(t){return O.deserialize({tiles:t,type:_.HAND})}toString(){return Ve(this.tiles)}}class Ye extends O{constructor(t,e){super(t,e)}toString(){return this.is(_.IMAGE_DISCARD)?this.tiles.join(""):Ve(this.tiles)}}const ae=(n,t)=>{switch(t){case _.CHI:return new J([n[0],n[1],n[2]]);case _.PON:return new Y([n[0],n[1],n[2]]);case _.AN_KAN:return new M(n);case _.DAI_KAN:return new Q(n);case _.SHO_KAN:return new K(n);case _.THREE:return new U(n);case _.RUN:return new nt(n);case _.PAIR:return new W(n[0],n[1]);case _.ISOLATED:return new Je(n[0]);case _.HAND:return new Ct(n);default:return new Ye(n,t)}};class B{constructor(t){E(this,"maxInputLength",600);this.input=t,this.input=t.replace(/\s/g,"")}parse(){const t=this.tileSeparators();return this.makeBlocks(t)}tiles(){return this.tileSeparators().filter(t=>t!=et)}tileSeparators(){const t=new Ks(this.input),e=[];let s=[];for(this.validate(this.input);;){t.skipWhitespace();const r=t.char;if(r===t.eof)break;if(r==et){e.push(et),t.readChar();continue}const[i,o]=En(r,s);if(o){if(i==p.BACK){e.push(new w(i,0)),t.readChar();continue}e.push(...Us(s,i)),s=[],t.readChar();continue}else{const[a,c]=Fs(t);if(c){s.push(a),t.readChar();continue}const[l,h]=Ln(r);if(!h)throw new Error(`encounter unexpected number. n: ${l}, current: ${r}, input: ${t.input}`);s.push({n:l})}t.readChar()}if(s.length>0)throw new Error(`remaining values ${s.toString()}`);return e}makeBlocks(t){let e=[];const s=[];if(t.length==0)return s;for(const o of t){if(o==et){const a=_n(e),c=ae(e,a);s.push(c),e=[];continue}e.push(o)}const r=_n(e),i=ae(e,r);return s.push(i),e=[],s}validate(t){if(t.length==0)return;if(t.length>this.maxInputLength)throw new Error(`exceeded maximum input length(${t.length})`);const e=t.charAt(t.length-1),[s,r]=En(e,[new w(p.BACK,1)]);if(!r)throw new Error(`last character: ${e} is not type value: ${t}`)}}function _n(n){if(n.length===0)return _.UNKNOWN;if(n.length===1)return n[0].has(y.DORA)?_.IMAGE_DORA:n[0].has(y.TSUMO)?_.TSUMO:_.HAND;const t=n.every(i=>i.equals(n[0])),e=n.filter(i=>i.has(y.HORIZONTAL)).length,s=n.filter(i=>i.has(y.TSUMO)||i.has(y.DORA)).length,r=n.filter(i=>i.t==p.BACK).length;if(s>0)return _.UNKNOWN;if(e==0&&r==0)return _.HAND;if(n.length===3&&r===0)return t?_.PON:e==1&&js(n)?_.CHI:_.IMAGE_DISCARD;if(n.length==4&&r==2)return _.AN_KAN;if(n.length==4&&t){if(e==1)return _.DAI_KAN;if(e==2)return _.SHO_KAN}return e==1||s==0?_.IMAGE_DISCARD:_.UNKNOWN}function js(n){const t=[...n].sort(Xt);if(t.some(s=>t[0].t!=s.t))return!1;const e=t.map(s=>s.n);for(let s=0;s<e.length-1;s++)if(e[s]!=e[s+1]-1)return!1;return!0}function Us(n,t){return n.map(e=>{const s=new w(t,e.n,e.ops);return s.isNum()&&s.n==0?s.clone({n:5,add:y.RED}):s})}function En(n,t){const[e,s]=zs(n);if(s)return[e,!0];if((n==="w"||n==="d")&&t.length>0){for(let i=0;i<t.length;i++){const o=t[i];n==="d"&&(t[i].n=o.n+4)}return[p.Z,!0]}return[p.BACK,!1]}function Ln(n){const t=Number(n),e=0<=t&&t<=9;return[t,e]}function Fs(n){const t=Object.values(y);if(!t.includes(n.char))return[new w(p.BACK,0),!1];const e=[];for(let s=0;s<4;s++){const r=n.peekCharN(s);if(t.includes(r))e.push(r);else{const[i,o]=Ln(r);if(!o)break;for(const c of e)n.readChar();const a=new w(p.BACK,i,e);if(a.has(y.RED)&&a.n!=5)throw new Error(`found ${y.RED} but number is not 5: ${i}`);if(a.has(y.DORA)&&a.has(y.TSUMO))throw new Error(`unable to specify both ${y.DORA} and ${y.TSUMO}`);return[a,!0]}}return[new w(p.BACK,0),!1]}function P(n,t=!1){const e={[A.E]:n,[A.S]:n,[A.W]:n,[A.N]:n};if(t)for(let s of Object.values(A))e[s]=structuredClone(n);return e}const Zt=n=>{let t=n.substring(0,2),e=Number(n.substring(2,3));return e==4?(e=1,t=_t(t)):e++,`${t}${e}`},Gs=n=>Zt(Zt(Zt(n))),_t=n=>{let t=Number(n.toString()[0]);return t=t%4+1,`${t}w`},ye=n=>{let t=Number(n.toString()[0]);const e=[1,4,3,2],s=e.indexOf(t);return`${e[(s+1)%e.length]}w`},Ce=(n,t,e)=>{const s=Math.abs(Number(n[0])-Number(t[0]));return I(s==1||s==2||s==3),e==_.PON?s==3?0:s==2?1:2:s==3?0:s==1?3:2};function bn(n){return typeof n>"u"}function xe(n,t=0){return{a:1,c:0,e:n,b:0,d:1,f:t}}function Xe(...n){n=Array.isArray(n[0])?n[0]:n;const t=(e,s)=>({a:e.a*s.a+e.c*s.b,c:e.a*s.c+e.c*s.d,e:e.a*s.e+e.c*s.f+e.e,b:e.b*s.a+e.d*s.b,d:e.b*s.c+e.d*s.d,f:e.b*s.e+e.d*s.f+e.f});switch(n.length){case 0:throw new Error("no matrices provided");case 1:return n[0];case 2:return t(n[0],n[1]);default:{const[e,s,...r]=n,i=t(e,s);return Xe(i,...r)}}}function Zs(...n){return Xe(...n)}const{cos:Vs,sin:Js,PI:Ys}=Math;function Xs(n,t,e){const s=Vs(n),r=Js(n),i={a:s,c:-r,e:0,b:r,d:s,f:0};return bn(t)||bn(e)?i:Xe([xe(t,e),i,xe(-t,-e)])}function qs(n,t=void 0,e=void 0){return Xs(n*Ys/180,t,e)}function Qs(n){return tr(n)}function tr(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}function er(n,t){function e(){this.constructor=n}e.prototype=t.prototype,n.prototype=new e}function me(n,t,e,s){var r=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(r,me.prototype),r.expected=t,r.found=e,r.location=s,r.name="SyntaxError",r}er(me,Error);function be(n,t,e){return e=e||" ",n.length>t?n:(t-=n.length,e+=e.repeat(t),n+e.slice(0,t))}me.prototype.format=function(n){var t="Error: "+this.message;if(this.location){var e=null,s;for(s=0;s<n.length;s++)if(n[s].source===this.location.source){e=n[s].text.split(/\r\n|\n|\r/g);break}var r=this.location.start,i=this.location.source&&typeof this.location.source.offset=="function"?this.location.source.offset(r):r,o=this.location.source+":"+i.line+":"+i.column;if(e){var a=this.location.end,c=be("",i.line.toString().length," "),l=e[r.line-1],h=r.line===a.line?a.column:l.length+1,u=h-r.column||1;t+=`
2
2
  --> `+o+`
3
3
  `+c+` |
4
4
  `+i.line+" | "+l+`
5
- `+c+" | "+be("",r.column-1," ")+be("",h,"^")}else t+=`
6
- at `+o}return t};ge.buildMessage=function(n,t){var e={literal:function(l){return'"'+r(l.text)+'"'},class:function(l){var u=l.parts.map(function(h){return Array.isArray(h)?i(h[0])+"-"+i(h[1]):i(h)});return"["+(l.inverted?"^":"")+u.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function s(l){return l.charCodeAt(0).toString(16).toUpperCase()}function r(l){return l.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(u){return"\\x0"+s(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+s(u)})}function i(l){return l.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(u){return"\\x0"+s(u)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(u){return"\\x"+s(u)})}function o(l){return e[l.type](l)}function a(l){var u=l.map(o),h,d;if(u.sort(),u.length>0){for(h=1,d=1;h<u.length;h++)u[h-1]!==u[h]&&(u[d]=u[h],d++);u.length=d}switch(u.length){case 1:return u[0];case 2:return u[0]+" or "+u[1];default:return u.slice(0,-1).join(", ")+", or "+u[u.length-1]}}function c(l){return l?'"'+r(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(t)+" found."};const Ln=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",er=Ln+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",nr="["+Ln+"]["+er+"]*",sr=new RegExp("^"+nr+"$");function zn(n,t){const e=[];let s=t.exec(n);for(;s;){const r=[];r.startIndex=t.lastIndex-s[0].length;const i=s.length;for(let o=0;o<i;o++)r.push(s[o]);e.push(r),s=t.exec(n)}return e}const Ye=function(n){const t=sr.exec(n);return!(t===null||typeof t>"u")};function rr(n){return typeof n<"u"}const ir={allowBooleanAttributes:!1,unpairedTags:[]};function or(n,t){t=Object.assign({},ir,t);const e=[];let s=!1,r=!1;n[0]==="\uFEFF"&&(n=n.substr(1));for(let i=0;i<n.length;i++)if(n[i]==="<"&&n[i+1]==="?"){if(i+=2,i=An(n,i),i.err)return i}else if(n[i]==="<"){let o=i;if(i++,n[i]==="!"){i=Nn(n,i);continue}else{let a=!1;n[i]==="/"&&(a=!0,i++);let c="";for(;i<n.length&&n[i]!==">"&&n[i]!==" "&&n[i]!==" "&&n[i]!==`
7
- `&&n[i]!=="\r";i++)c+=n[i];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),i--),!pr(c)){let h;return c.trim().length===0?h="Invalid space after '<'.":h="Tag '"+c+"' is an invalid name.",I("InvalidTag",h,x(n,i))}const l=lr(n,i);if(l===!1)return I("InvalidAttr","Attributes for '"+c+"' have open quote.",x(n,i));let u=l.value;if(i=l.index,u[u.length-1]==="/"){const h=i-u.length;u=u.substring(0,u.length-1);const d=Sn(u,t);if(d===!0)s=!0;else return I(d.err.code,d.err.msg,x(n,h+d.err.line))}else if(a)if(l.tagClosed){if(u.trim().length>0)return I("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",x(n,o));if(e.length===0)return I("InvalidTag","Closing tag '"+c+"' has not been opened.",x(n,o));{const h=e.pop();if(c!==h.tagName){let d=x(n,h.tagStartPos);return I("InvalidTag","Expected closing tag '"+h.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",x(n,o))}e.length==0&&(r=!0)}}else return I("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",x(n,i));else{const h=Sn(u,t);if(h!==!0)return I(h.err.code,h.err.msg,x(n,i-u.length+h.err.line));if(r===!0)return I("InvalidXml","Multiple possible root nodes found.",x(n,i));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),s=!0}for(i++;i<n.length;i++)if(n[i]==="<")if(n[i+1]==="!"){i++,i=Nn(n,i);continue}else if(n[i+1]==="?"){if(i=An(n,++i),i.err)return i}else break;else if(n[i]==="&"){const h=dr(n,i);if(h==-1)return I("InvalidChar","char '&' is not expected.",x(n,i));i=h}else if(r===!0&&!En(n[i]))return I("InvalidXml","Extra text at the end",x(n,i));n[i]==="<"&&i--}}else{if(En(n[i]))continue;return I("InvalidChar","char '"+n[i]+"' is not expected.",x(n,i))}if(s){if(e.length==1)return I("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",x(n,e[0].tagStartPos));if(e.length>0)return I("InvalidXml","Invalid '"+JSON.stringify(e.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return I("InvalidXml","Start tag expected.",1);return!0}function En(n){return n===" "||n===" "||n===`
8
- `||n==="\r"}function An(n,t){const e=t;for(;t<n.length;t++)if(n[t]=="?"||n[t]==" "){const s=n.substr(e,t-e);if(t>5&&s==="xml")return I("InvalidXml","XML declaration allowed only at the start of the document.",x(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function Nn(n,t){if(n.length>t+5&&n[t+1]==="-"&&n[t+2]==="-"){for(t+=3;t<n.length;t++)if(n[t]==="-"&&n[t+1]==="-"&&n[t+2]===">"){t+=2;break}}else if(n.length>t+8&&n[t+1]==="D"&&n[t+2]==="O"&&n[t+3]==="C"&&n[t+4]==="T"&&n[t+5]==="Y"&&n[t+6]==="P"&&n[t+7]==="E"){let e=1;for(t+=8;t<n.length;t++)if(n[t]==="<")e++;else if(n[t]===">"&&(e--,e===0))break}else if(n.length>t+9&&n[t+1]==="["&&n[t+2]==="C"&&n[t+3]==="D"&&n[t+4]==="A"&&n[t+5]==="T"&&n[t+6]==="A"&&n[t+7]==="["){for(t+=8;t<n.length;t++)if(n[t]==="]"&&n[t+1]==="]"&&n[t+2]===">"){t+=2;break}}return t}const ar='"',cr="'";function lr(n,t){let e="",s="",r=!1;for(;t<n.length;t++){if(n[t]===ar||n[t]===cr)s===""?s=n[t]:s!==n[t]||(s="");else if(n[t]===">"&&s===""){r=!0;break}e+=n[t]}return s!==""?!1:{value:e,index:t,tagClosed:r}}const ur=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Sn(n,t){const e=zn(n,ur),s={};for(let r=0;r<e.length;r++){if(e[r][1].length===0)return I("InvalidAttr","Attribute '"+e[r][2]+"' has no space in starting.",Kt(e[r]));if(e[r][3]!==void 0&&e[r][4]===void 0)return I("InvalidAttr","Attribute '"+e[r][2]+"' is without value.",Kt(e[r]));if(e[r][3]===void 0&&!t.allowBooleanAttributes)return I("InvalidAttr","boolean attribute '"+e[r][2]+"' is not allowed.",Kt(e[r]));const i=e[r][2];if(!fr(i))return I("InvalidAttr","Attribute '"+i+"' is an invalid name.",Kt(e[r]));if(!s.hasOwnProperty(i))s[i]=1;else return I("InvalidAttr","Attribute '"+i+"' is repeated.",Kt(e[r]))}return!0}function hr(n,t){let e=/\d/;for(n[t]==="x"&&(t++,e=/[\da-fA-F]/);t<n.length;t++){if(n[t]===";")return t;if(!n[t].match(e))break}return-1}function dr(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,hr(n,t);let e=0;for(;t<n.length;t++,e++)if(!(n[t].match(/\w/)&&e<20)){if(n[t]===";")break;return-1}return t}function I(n,t,e){return{err:{code:n,msg:t,line:e.line||e,col:e.col}}}function fr(n){return Ye(n)}function pr(n){return Ye(n)}function x(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function Kt(n){return n.startIndex+n[1].length}const gr={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,t,e){return n},captureMetaData:!1},yr=function(n){return Object.assign({},gr,n)};let ae;typeof Symbol!="function"?ae="@@xmlMetadata":ae=Symbol("XML Node Metadata");class ht{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][ae]={startIndex:e})}static getMetaDataSymbol(){return ae}}function mr(n,t){const e={};if(n[t+3]==="O"&&n[t+4]==="C"&&n[t+5]==="T"&&n[t+6]==="Y"&&n[t+7]==="P"&&n[t+8]==="E"){t=t+9;let s=1,r=!1,i=!1,o="";for(;t<n.length;t++)if(n[t]==="<"&&!i){if(r&&Ar(n,t)){t+=7;let a,c;[a,c,t]=wr(n,t+1),c.indexOf("&")===-1&&(e[a]={regx:RegExp(`&${a};`,"g"),val:c})}else if(r&&Nr(n,t)){t+=8;const{index:a}=_r(n,t+1);t=a}else if(r&&Sr(n,t))t+=8;else if(r&&vr(n,t)){t+=9;const{index:a}=br(n,t+1);t=a}else if(Er)i=!0;else throw new Error("Invalid DOCTYPE");s++,o=""}else if(n[t]===">"){if(i?n[t-1]==="-"&&n[t-2]==="-"&&(i=!1,s--):s--,s===0)break}else n[t]==="["?r=!0:o+=n[t];if(s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:e,i:t}}const tt=(n,t)=>{for(;t<n.length&&/\s/.test(n[t]);)t++;return t};function wr(n,t){t=tt(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t])&&n[t]!=='"'&&n[t]!=="'";)e+=n[t],t++;if(qe(e),t=tt(n,t),n.substring(t,t+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(n[t]==="%")throw new Error("Parameter entities are not supported");let s="";return[t,s]=re(n,t,"entity"),t--,[e,s,t]}function br(n,t){t=tt(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;qe(e),t=tt(n,t);const s=n.substring(t,t+6).toUpperCase();if(s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=tt(n,t);let r=null,i=null;if(s==="PUBLIC")[t,r]=re(n,t,"publicIdentifier"),t=tt(n,t),(n[t]==='"'||n[t]==="'")&&([t,i]=re(n,t,"systemIdentifier"));else if(s==="SYSTEM"&&([t,i]=re(n,t,"systemIdentifier"),!i))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:e,publicIdentifier:r,systemIdentifier:i,index:--t}}function re(n,t,e){let s="";const r=n[t];if(r!=='"'&&r!=="'")throw new Error(`Expected quoted string, found "${r}"`);for(t++;t<n.length&&n[t]!==r;)s+=n[t],t++;if(n[t]!==r)throw new Error(`Unterminated ${e} value`);return t++,[t,s]}function _r(n,t){t=tt(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;if(!qe(e))throw new Error(`Invalid element name: "${e}"`);if(t=tt(n,t),n[t]!=="(")throw new Error(`Expected '(', found "${n[t]}"`);t++;let s="";for(;t<n.length&&n[t]!==")";)s+=n[t],t++;if(n[t]!==")")throw new Error("Unterminated content model");return{elementName:e,contentModel:s.trim(),index:t}}function Er(n,t){return n[t+1]==="!"&&n[t+2]==="-"&&n[t+3]==="-"}function Ar(n,t){return n[t+1]==="!"&&n[t+2]==="E"&&n[t+3]==="N"&&n[t+4]==="T"&&n[t+5]==="I"&&n[t+6]==="T"&&n[t+7]==="Y"}function Nr(n,t){return n[t+1]==="!"&&n[t+2]==="E"&&n[t+3]==="L"&&n[t+4]==="E"&&n[t+5]==="M"&&n[t+6]==="E"&&n[t+7]==="N"&&n[t+8]==="T"}function Sr(n,t){return n[t+1]==="!"&&n[t+2]==="A"&&n[t+3]==="T"&&n[t+4]==="T"&&n[t+5]==="L"&&n[t+6]==="I"&&n[t+7]==="S"&&n[t+8]==="T"}function vr(n,t){return n[t+1]==="!"&&n[t+2]==="N"&&n[t+3]==="O"&&n[t+4]==="T"&&n[t+5]==="A"&&n[t+6]==="T"&&n[t+7]==="I"&&n[t+8]==="O"&&n[t+9]==="N"}function qe(n){if(Ye(n))return n;throw new Error(`Invalid entity name ${n}`)}const Tr=/^[-+]?0x[a-fA-F0-9]+$/,Ir=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Or={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function kr(n,t={}){if(t=Object.assign({},Or,t),!n||typeof n!="string")return n;let e=n.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return n;if(n==="0")return 0;if(t.hex&&Tr.test(e))return xr(e,16);if(e.search(/.+[eE].+/)!==-1)return Rr(n,e,t);{const s=Ir.exec(e);if(s){const r=s[1]||"",i=s[2];let o=Mr(s[3]);const a=r?n[i.length+1]===".":n[i.length]===".";if(!t.leadingZeros&&(i.length>1||i.length===1&&!a))return n;{const c=Number(e),l=String(c);if(c===0||c===-0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:n;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${r}${o}`?c:n;let u=i?o:e;return i?u===l||r+u===l?c:n:u===l||u===r+l?c:n}}else return n}}const Cr=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Rr(n,t,e){if(!e.eNotation)return n;const s=t.match(Cr);if(s){let r=s[1]||"";const i=s[3].indexOf("e")===-1?"E":"e",o=s[2],a=r?n[o.length+1]===i:n[o.length]===i;return o.length>1&&a?n:o.length===1&&(s[3].startsWith(`.${i}`)||s[3][0]===i)?Number(t):e.leadingZeros&&!a?(t=(s[1]||"")+s[3],Number(t)):n}else return n}function Mr(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substring(0,n.length-1))),n}function xr(n,t){if(parseInt)return parseInt(n,t);if(Number.parseInt)return Number.parseInt(n,t);if(window&&window.parseInt)return window.parseInt(n,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function jn(n){return typeof n=="function"?n:Array.isArray(n)?t=>{for(const e of n)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class $r{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,16))}},this.addExternalEntities=Pr,this.parseXml=Kr,this.parseTextData=Hr,this.resolveNameSpace=Wr,this.buildAttributesMap=Dr,this.isItStopNode=Ur,this.replaceEntitiesValue=zr,this.readStopNodeData=Gr,this.saveTextToParentTag=jr,this.addChild=Lr,this.ignoreAttributesFn=jn(this.options.ignoreAttributes)}}function Pr(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:n[s]}}}function Hr(n,t,e,s,r,i,o){if(n!==void 0&&(this.options.trimValues&&!s&&(n=n.trim()),n.length>0)){o||(n=this.replaceEntitiesValue(n));const a=this.options.tagValueProcessor(t,n,e,r,i);return a==null?n:typeof a!=typeof n||a!==n?a:this.options.trimValues?Re(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?Re(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function Wr(n){if(this.options.removeNSPrefix){const t=n.split(":"),e=n.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(n=e+t[1])}return n}const Br=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Dr(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=zn(n,Br),r=s.length,i={};for(let o=0;o<r;o++){const a=this.resolveNameSpace(s[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=s[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const u=this.options.attributeValueProcessor(a,c,t);u==null?i[l]=c:typeof u!=typeof c||u!==c?i[l]=u:i[l]=Re(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(i[l]=!0)}if(!Object.keys(i).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=i,o}return i}}const Kr=function(n){n=n.replace(/\r\n?/g,`
9
- `);const t=new ht("!xml");let e=t,s="",r="";for(let i=0;i<n.length;i++)if(n[i]==="<")if(n[i+1]==="/"){const a=ft(n,">",i,"Closing Tag is not closed.");let c=n.substring(i+2,a).trim();if(this.options.removeNSPrefix){const h=c.indexOf(":");h!==-1&&(c=c.substr(h+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&(s=this.saveTextToParentTag(s,e,r));const l=r.substring(r.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let u=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(u=r.lastIndexOf(".",r.lastIndexOf(".")-1),this.tagsNodeStack.pop()):u=r.lastIndexOf("."),r=r.substring(0,u),e=this.tagsNodeStack.pop(),s="",i=a}else if(n[i+1]==="?"){let a=Ce(n,i,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,e,r),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new ht(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,r,a.tagName)),this.addChild(e,c,r,i)}i=a.closeIndex+1}else if(n.substr(i+1,3)==="!--"){const a=ft(n,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){const c=n.substring(i+4,a-2);s=this.saveTextToParentTag(s,e,r),e.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}i=a}else if(n.substr(i+1,2)==="!D"){const a=mr(n,i);this.docTypeEntities=a.entities,i=a.i}else if(n.substr(i+1,2)==="!["){const a=ft(n,"]]>",i,"CDATA is not closed.")-2,c=n.substring(i+9,a);s=this.saveTextToParentTag(s,e,r);let l=this.parseTextData(c,e.tagname,r,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):e.add(this.options.textNodeName,l),i=a+2}else{let a=Ce(n,i,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let u=a.tagExp,h=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&s&&e.tagname!=="!xml"&&(s=this.saveTextToParentTag(s,e,r,!1));const g=e;g&&this.options.unpairedTags.indexOf(g.tagname)!==-1&&(e=this.tagsNodeStack.pop(),r=r.substring(0,r.lastIndexOf("."))),c!==t.tagname&&(r+=r?"."+c:c);const f=i;if(this.isItStopNode(this.options.stopNodes,r,c)){let m="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),r=r.substr(0,r.length-1),u=c):u=u.substr(0,u.length-1),i=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)i=a.closeIndex;else{const N=this.readStopNodeData(n,l,d+1);if(!N)throw new Error(`Unexpected end of ${l}`);i=N.i,m=N.tagContent}const E=new ht(c);c!==u&&h&&(E[":@"]=this.buildAttributesMap(u,r,c)),m&&(m=this.parseTextData(m,c,r,!0,h,!0,!0)),r=r.substr(0,r.lastIndexOf(".")),E.add(this.options.textNodeName,m),this.addChild(e,E,r,f)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),r=r.substr(0,r.length-1),u=c):u=u.substr(0,u.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const m=new ht(c);c!==u&&h&&(m[":@"]=this.buildAttributesMap(u,r,c)),this.addChild(e,m,r,f),r=r.substr(0,r.lastIndexOf("."))}else{const m=new ht(c);this.tagsNodeStack.push(e),c!==u&&h&&(m[":@"]=this.buildAttributesMap(u,r,c)),this.addChild(e,m,r,f),e=m}s="",i=d}}else s+=n[i];return t.child};function Lr(n,t,e,s){this.options.captureMetaData||(s=void 0);const r=this.options.updateTag(t.tagname,e,t[":@"]);r===!1||(typeof r=="string"&&(t.tagname=r),n.addChild(t,s))}const zr=function(n){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];n=n.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];n=n.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];n=n.replace(e.regex,e.val)}n=n.replace(this.ampEntity.regex,this.ampEntity.val)}return n};function jr(n,t,e,s){return n&&(s===void 0&&(s=t.child.length===0),n=this.parseTextData(n,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,s),n!==void 0&&n!==""&&t.add(this.options.textNodeName,n),n=""),n}function Ur(n,t,e){const s="*."+e;for(const r in n){const i=n[r];if(s===i||t===i)return!0}return!1}function Fr(n,t,e=">"){let s,r="";for(let i=t;i<n.length;i++){let o=n[i];if(s)o===s&&(s="");else if(o==='"'||o==="'")s=o;else if(o===e[0])if(e[1]){if(n[i+1]===e[1])return{data:r,index:i}}else return{data:r,index:i};else o===" "&&(o=" ");r+=o}}function ft(n,t,e,s){const r=n.indexOf(t,e);if(r===-1)throw new Error(s);return r+t.length-1}function Ce(n,t,e,s=">"){const r=Fr(n,t+1,s);if(!r)return;let i=r.data;const o=r.index,a=i.search(/\s/);let c=i,l=!0;a!==-1&&(c=i.substring(0,a),i=i.substring(a+1).trimStart());const u=c;if(e){const h=c.indexOf(":");h!==-1&&(c=c.substr(h+1),l=c!==r.data.substr(h+1))}return{tagName:c,tagExp:i,closeIndex:o,attrExpPresent:l,rawTagName:u}}function Gr(n,t,e){const s=e;let r=1;for(;e<n.length;e++)if(n[e]==="<")if(n[e+1]==="/"){const i=ft(n,">",e,`${t} is not closed`);if(n.substring(e+2,i).trim()===t&&(r--,r===0))return{tagContent:n.substring(s,e),i};e=i}else if(n[e+1]==="?")e=ft(n,"?>",e+1,"StopNode is not closed.");else if(n.substr(e+1,3)==="!--")e=ft(n,"-->",e+3,"StopNode is not closed.");else if(n.substr(e+1,2)==="![")e=ft(n,"]]>",e,"StopNode is not closed.")-2;else{const i=Ce(n,e,">");i&&((i&&i.tagName)===t&&i.tagExp[i.tagExp.length-1]!=="/"&&r++,e=i.closeIndex)}}function Re(n,t,e){if(t&&typeof n=="string"){const s=n.trim();return s==="true"?!0:s==="false"?!1:kr(n,e)}else return rr(n)?n:""}const _e=ht.getMetaDataSymbol();function Zr(n,t){return Un(n,t)}function Un(n,t,e){let s;const r={};for(let i=0;i<n.length;i++){const o=n[i],a=Vr(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)s===void 0?s=o[a]:s+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Un(o[a],t,c);const u=Xr(l,t);o[_e]!==void 0&&(l[_e]=o[_e]),o[":@"]?Jr(l,o[":@"],c,t):Object.keys(l).length===1&&l[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?l=l[t.textNodeName]:Object.keys(l).length===0&&(t.alwaysCreateTextNode?l[t.textNodeName]="":l=""),r[a]!==void 0&&r.hasOwnProperty(a)?(Array.isArray(r[a])||(r[a]=[r[a]]),r[a].push(l)):t.isArray(a,c,u)?r[a]=[l]:r[a]=l}}}return typeof s=="string"?s.length>0&&(r[t.textNodeName]=s):s!==void 0&&(r[t.textNodeName]=s),r}function Vr(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(s!==":@")return s}}function Jr(n,t,e,s){if(t){const r=Object.keys(t),i=r.length;for(let o=0;o<i;o++){const a=r[o];s.isArray(a,e+"."+a,!0,!0)?n[a]=[t[a]]:n[a]=t[a]}}}function Xr(n,t){const{textNodeName:e}=t,s=Object.keys(n).length;return!!(s===0||s===1&&(n[e]||typeof n[e]=="boolean"||n[e]===0))}class Yr{constructor(t){this.externalEntities={},this.options=yr(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const i=or(t,e);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const s=new $r(this.options);s.addExternalEntities(this.externalEntities);const r=s.parseXml(t);return this.options.preserveOrder||r===void 0?r:Zr(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return ht.getMetaDataSymbol()}}const qr=`
10
- `;function Qr(n,t){let e="";return t.format&&t.indentBy.length>0&&(e=qr),Fn(n,t,"",e)}function Fn(n,t,e,s){let r="",i=!1;for(let o=0;o<n.length;o++){const a=n[o],c=ti(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];ei(l,t)||(f=t.tagValueProcessor(c,f),f=Gn(f,t)),i&&(r+=s),r+=f,i=!1;continue}else if(c===t.cdataPropName){i&&(r+=s),r+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,i=!1;continue}else if(c===t.commentPropName){r+=s+`<!--${a[c][0][t.textNodeName]}-->`,i=!0;continue}else if(c[0]==="?"){const f=vn(a[":@"],t),m=c==="?xml"?"":s;let E=a[c][0][t.textNodeName];E=E.length!==0?" "+E:"",r+=m+`<${c}${E}${f}?>`,i=!0;continue}let u=s;u!==""&&(u+=t.indentBy);const h=vn(a[":@"],t),d=s+`<${c}${h}`,g=Fn(a[c],t,l,u);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?r+=d+">":r+=d+"/>":(!g||g.length===0)&&t.suppressEmptyNode?r+=d+"/>":g&&g.endsWith(">")?r+=d+`>${g}${s}</${c}>`:(r+=d+">",g&&s!==""&&(g.includes("/>")||g.includes("</"))?r+=s+t.indentBy+g+s:r+=g,r+=`</${c}>`),i=!0}return r}function ti(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(n.hasOwnProperty(s)&&s!==":@")return s}}function vn(n,t){let e="";if(n&&!t.ignoreAttributes)for(let s in n){if(!n.hasOwnProperty(s))continue;let r=t.attributeValueProcessor(s,n[s]);r=Gn(r,t),r===!0&&t.suppressBooleanAttributes?e+=` ${s.substr(t.attributeNamePrefix.length)}`:e+=` ${s.substr(t.attributeNamePrefix.length)}="${r}"`}return e}function ei(n,t){n=n.substr(0,n.length-t.textNodeName.length-1);let e=n.substr(n.lastIndexOf(".")+1);for(let s in t.stopNodes)if(t.stopNodes[s]===n||t.stopNodes[s]==="*."+e)return!0;return!1}function Gn(n,t){if(n&&n.length>0&&t.processEntities)for(let e=0;e<t.entities.length;e++){const s=t.entities[e];n=n.replace(s.regex,s.val)}return n}const ni={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function it(n){this.options=Object.assign({},ni,n),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=jn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ii),this.processTextOrObjNode=si,this.options.format?(this.indentate=ri,this.tagEndChar=`>
5
+ `+c+" | "+be("",r.column-1," ")+be("",u,"^")}else t+=`
6
+ at `+o}return t};me.buildMessage=function(n,t){var e={literal:function(l){return'"'+r(l.text)+'"'},class:function(l){var h=l.parts.map(function(u){return Array.isArray(u)?i(u[0])+"-"+i(u[1]):i(u)});return"["+(l.inverted?"^":"")+h.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(l){return l.description}};function s(l){return l.charCodeAt(0).toString(16).toUpperCase()}function r(l){return l.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(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function i(l){return l.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(h){return"\\x0"+s(h)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(h){return"\\x"+s(h)})}function o(l){return e[l.type](l)}function a(l){var h=l.map(o),u,d;if(h.sort(),h.length>0){for(u=1,d=1;u<h.length;u++)h[u-1]!==h[u]&&(h[d]=h[u],d++);h.length=d}switch(h.length){case 1:return h[0];case 2:return h[0]+" or "+h[1];default:return h.slice(0,-1).join(", ")+", or "+h[h.length-1]}}function c(l){return l?'"'+r(l)+'"':"end of input"}return"Expected "+a(n)+" but "+c(t)+" found."};const zn=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",nr=zn+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",sr="["+zn+"]["+nr+"]*",rr=new RegExp("^"+sr+"$");function jn(n,t){const e=[];let s=t.exec(n);for(;s;){const r=[];r.startIndex=t.lastIndex-s[0].length;const i=s.length;for(let o=0;o<i;o++)r.push(s[o]);e.push(r),s=t.exec(n)}return e}const qe=function(n){const t=rr.exec(n);return!(t===null||typeof t>"u")};function ir(n){return typeof n<"u"}const or={allowBooleanAttributes:!1,unpairedTags:[]};function ar(n,t){t=Object.assign({},or,t);const e=[];let s=!1,r=!1;n[0]==="\uFEFF"&&(n=n.substr(1));for(let i=0;i<n.length;i++)if(n[i]==="<"&&n[i+1]==="?"){if(i+=2,i=Sn(n,i),i.err)return i}else if(n[i]==="<"){let o=i;if(i++,n[i]==="!"){i=Nn(n,i);continue}else{let a=!1;n[i]==="/"&&(a=!0,i++);let c="";for(;i<n.length&&n[i]!==">"&&n[i]!==" "&&n[i]!==" "&&n[i]!==`
7
+ `&&n[i]!=="\r";i++)c+=n[i];if(c=c.trim(),c[c.length-1]==="/"&&(c=c.substring(0,c.length-1),i--),!gr(c)){let u;return c.trim().length===0?u="Invalid space after '<'.":u="Tag '"+c+"' is an invalid name.",k("InvalidTag",u,$(n,i))}const l=hr(n,i);if(l===!1)return k("InvalidAttr","Attributes for '"+c+"' have open quote.",$(n,i));let h=l.value;if(i=l.index,h[h.length-1]==="/"){const u=i-h.length;h=h.substring(0,h.length-1);const d=In(h,t);if(d===!0)s=!0;else return k(d.err.code,d.err.msg,$(n,u+d.err.line))}else if(a)if(l.tagClosed){if(h.trim().length>0)return k("InvalidTag","Closing tag '"+c+"' can't have attributes or invalid starting.",$(n,o));if(e.length===0)return k("InvalidTag","Closing tag '"+c+"' has not been opened.",$(n,o));{const u=e.pop();if(c!==u.tagName){let d=$(n,u.tagStartPos);return k("InvalidTag","Expected closing tag '"+u.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",$(n,o))}e.length==0&&(r=!0)}}else return k("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",$(n,i));else{const u=In(h,t);if(u!==!0)return k(u.err.code,u.err.msg,$(n,i-h.length+u.err.line));if(r===!0)return k("InvalidXml","Multiple possible root nodes found.",$(n,i));t.unpairedTags.indexOf(c)!==-1||e.push({tagName:c,tagStartPos:o}),s=!0}for(i++;i<n.length;i++)if(n[i]==="<")if(n[i+1]==="!"){i++,i=Nn(n,i);continue}else if(n[i+1]==="?"){if(i=Sn(n,++i),i.err)return i}else break;else if(n[i]==="&"){const u=fr(n,i);if(u==-1)return k("InvalidChar","char '&' is not expected.",$(n,i));i=u}else if(r===!0&&!An(n[i]))return k("InvalidXml","Extra text at the end",$(n,i));n[i]==="<"&&i--}}else{if(An(n[i]))continue;return k("InvalidChar","char '"+n[i]+"' is not expected.",$(n,i))}if(s){if(e.length==1)return k("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",$(n,e[0].tagStartPos));if(e.length>0)return k("InvalidXml","Invalid '"+JSON.stringify(e.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return k("InvalidXml","Start tag expected.",1);return!0}function An(n){return n===" "||n===" "||n===`
8
+ `||n==="\r"}function Sn(n,t){const e=t;for(;t<n.length;t++)if(n[t]=="?"||n[t]==" "){const s=n.substr(e,t-e);if(t>5&&s==="xml")return k("InvalidXml","XML declaration allowed only at the start of the document.",$(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function Nn(n,t){if(n.length>t+5&&n[t+1]==="-"&&n[t+2]==="-"){for(t+=3;t<n.length;t++)if(n[t]==="-"&&n[t+1]==="-"&&n[t+2]===">"){t+=2;break}}else if(n.length>t+8&&n[t+1]==="D"&&n[t+2]==="O"&&n[t+3]==="C"&&n[t+4]==="T"&&n[t+5]==="Y"&&n[t+6]==="P"&&n[t+7]==="E"){let e=1;for(t+=8;t<n.length;t++)if(n[t]==="<")e++;else if(n[t]===">"&&(e--,e===0))break}else if(n.length>t+9&&n[t+1]==="["&&n[t+2]==="C"&&n[t+3]==="D"&&n[t+4]==="A"&&n[t+5]==="T"&&n[t+6]==="A"&&n[t+7]==="["){for(t+=8;t<n.length;t++)if(n[t]==="]"&&n[t+1]==="]"&&n[t+2]===">"){t+=2;break}}return t}const cr='"',lr="'";function hr(n,t){let e="",s="",r=!1;for(;t<n.length;t++){if(n[t]===cr||n[t]===lr)s===""?s=n[t]:s!==n[t]||(s="");else if(n[t]===">"&&s===""){r=!0;break}e+=n[t]}return s!==""?!1:{value:e,index:t,tagClosed:r}}const ur=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function In(n,t){const e=jn(n,ur),s={};for(let r=0;r<e.length;r++){if(e[r][1].length===0)return k("InvalidAttr","Attribute '"+e[r][2]+"' has no space in starting.",Lt(e[r]));if(e[r][3]!==void 0&&e[r][4]===void 0)return k("InvalidAttr","Attribute '"+e[r][2]+"' is without value.",Lt(e[r]));if(e[r][3]===void 0&&!t.allowBooleanAttributes)return k("InvalidAttr","boolean attribute '"+e[r][2]+"' is not allowed.",Lt(e[r]));const i=e[r][2];if(!pr(i))return k("InvalidAttr","Attribute '"+i+"' is an invalid name.",Lt(e[r]));if(!s.hasOwnProperty(i))s[i]=1;else return k("InvalidAttr","Attribute '"+i+"' is repeated.",Lt(e[r]))}return!0}function dr(n,t){let e=/\d/;for(n[t]==="x"&&(t++,e=/[\da-fA-F]/);t<n.length;t++){if(n[t]===";")return t;if(!n[t].match(e))break}return-1}function fr(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,dr(n,t);let e=0;for(;t<n.length;t++,e++)if(!(n[t].match(/\w/)&&e<20)){if(n[t]===";")break;return-1}return t}function k(n,t,e){return{err:{code:n,msg:t,line:e.line||e,col:e.col}}}function pr(n){return qe(n)}function gr(n){return qe(n)}function $(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function Lt(n){return n.startIndex+n[1].length}const yr={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(n,t,e){return n},captureMetaData:!1},mr=function(n){return Object.assign({},yr,n)};let ce;typeof Symbol!="function"?ce="@@xmlMetadata":ce=Symbol("XML Node Metadata");class pt{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),e!==void 0&&(this.child[this.child.length-1][ce]={startIndex:e})}static getMetaDataSymbol(){return ce}}function wr(n,t){const e={};if(n[t+3]==="O"&&n[t+4]==="C"&&n[t+5]==="T"&&n[t+6]==="Y"&&n[t+7]==="P"&&n[t+8]==="E"){t=t+9;let s=1,r=!1,i=!1,o="";for(;t<n.length;t++)if(n[t]==="<"&&!i){if(r&&gt(n,"!ENTITY",t)){t+=7;let a,c;[a,c,t]=_r(n,t+1),c.indexOf("&")===-1&&(e[a]={regx:RegExp(`&${a};`,"g"),val:c})}else if(r&&gt(n,"!ELEMENT",t)){t+=8;const{index:a}=br(n,t+1);t=a}else if(r&&gt(n,"!ATTLIST",t))t+=8;else if(r&&gt(n,"!NOTATION",t)){t+=9;const{index:a}=Er(n,t+1);t=a}else if(gt(n,"!--",t))i=!0;else throw new Error("Invalid DOCTYPE");s++,o=""}else if(n[t]===">"){if(i?n[t-1]==="-"&&n[t-2]==="-"&&(i=!1,s--):s--,s===0)break}else n[t]==="["?r=!0:o+=n[t];if(s!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:e,i:t}}const st=(n,t)=>{for(;t<n.length&&/\s/.test(n[t]);)t++;return t};function _r(n,t){t=st(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t])&&n[t]!=='"'&&n[t]!=="'";)e+=n[t],t++;if(Qe(e),t=st(n,t),n.substring(t,t+6).toUpperCase()==="SYSTEM")throw new Error("External entities are not supported");if(n[t]==="%")throw new Error("Parameter entities are not supported");let s="";return[t,s]=ie(n,t,"entity"),t--,[e,s,t]}function Er(n,t){t=st(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;Qe(e),t=st(n,t);const s=n.substring(t,t+6).toUpperCase();if(s!=="SYSTEM"&&s!=="PUBLIC")throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=st(n,t);let r=null,i=null;if(s==="PUBLIC")[t,r]=ie(n,t,"publicIdentifier"),t=st(n,t),(n[t]==='"'||n[t]==="'")&&([t,i]=ie(n,t,"systemIdentifier"));else if(s==="SYSTEM"&&([t,i]=ie(n,t,"systemIdentifier"),!i))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:e,publicIdentifier:r,systemIdentifier:i,index:--t}}function ie(n,t,e){let s="";const r=n[t];if(r!=='"'&&r!=="'")throw new Error(`Expected quoted string, found "${r}"`);for(t++;t<n.length&&n[t]!==r;)s+=n[t],t++;if(n[t]!==r)throw new Error(`Unterminated ${e} value`);return t++,[t,s]}function br(n,t){t=st(n,t);let e="";for(;t<n.length&&!/\s/.test(n[t]);)e+=n[t],t++;if(!Qe(e))throw new Error(`Invalid element name: "${e}"`);t=st(n,t);let s="";if(n[t]==="E"&&gt(n,"MPTY",t))t+=6;else if(n[t]==="A"&&gt(n,"NY",t))t+=4;else if(n[t]==="("){for(t++;t<n.length&&n[t]!==")";)s+=n[t],t++;if(n[t]!==")")throw new Error("Unterminated content model")}else throw new Error(`Invalid Element Expression, found "${n[t]}"`);return{elementName:e,contentModel:s.trim(),index:t}}function gt(n,t,e){for(let s=0;s<t.length;s++)if(t[s]!==n[e+s+1])return!1;return!0}function Qe(n){if(qe(n))return n;throw new Error(`Invalid entity name ${n}`)}const Ar=/^[-+]?0x[a-fA-F0-9]+$/,Sr=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Nr={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Ir(n,t={}){if(t=Object.assign({},Nr,t),!n||typeof n!="string")return n;let e=n.trim();if(t.skipLike!==void 0&&t.skipLike.test(e))return n;if(n==="0")return 0;if(t.hex&&Ar.test(e))return kr(e,16);if(e.search(/.+[eE].+/)!==-1)return Tr(n,e,t);{const s=Sr.exec(e);if(s){const r=s[1]||"",i=s[2];let o=Or(s[3]);const a=r?n[i.length+1]===".":n[i.length]===".";if(!t.leadingZeros&&(i.length>1||i.length===1&&!a))return n;{const c=Number(e),l=String(c);if(c===0||c===-0)return c;if(l.search(/[eE]/)!==-1)return t.eNotation?c:n;if(e.indexOf(".")!==-1)return l==="0"||l===o||l===`${r}${o}`?c:n;let h=i?o:e;return i?h===l||r+h===l?c:n:h===l||h===r+l?c:n}}else return n}}const vr=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Tr(n,t,e){if(!e.eNotation)return n;const s=t.match(vr);if(s){let r=s[1]||"";const i=s[3].indexOf("e")===-1?"E":"e",o=s[2],a=r?n[o.length+1]===i:n[o.length]===i;return o.length>1&&a?n:o.length===1&&(s[3].startsWith(`.${i}`)||s[3][0]===i)?Number(t):e.leadingZeros&&!a?(t=(s[1]||"")+s[3],Number(t)):n}else return n}function Or(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substring(0,n.length-1))),n}function kr(n,t){if(parseInt)return parseInt(n,t);if(Number.parseInt)return Number.parseInt(n,t);if(window&&window.parseInt)return window.parseInt(n,t);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}function Un(n){return typeof n=="function"?n:Array.isArray(n)?t=>{for(const e of n)if(typeof e=="string"&&t===e||e instanceof RegExp&&e.test(t))return!0}:()=>!1}class Cr{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,s)=>String.fromCodePoint(Number.parseInt(s,16))}},this.addExternalEntities=xr,this.parseXml=Hr,this.parseTextData=Rr,this.resolveNameSpace=Mr,this.buildAttributesMap=Pr,this.isItStopNode=Kr,this.replaceEntitiesValue=Br,this.readStopNodeData=zr,this.saveTextToParentTag=Dr,this.addChild=Wr,this.ignoreAttributesFn=Un(this.options.ignoreAttributes)}}function xr(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:n[s]}}}function Rr(n,t,e,s,r,i,o){if(n!==void 0&&(this.options.trimValues&&!s&&(n=n.trim()),n.length>0)){o||(n=this.replaceEntitiesValue(n));const a=this.options.tagValueProcessor(t,n,e,r,i);return a==null?n:typeof a!=typeof n||a!==n?a:this.options.trimValues?Me(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?Me(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function Mr(n){if(this.options.removeNSPrefix){const t=n.split(":"),e=n.charAt(0)==="/"?"/":"";if(t[0]==="xmlns")return"";t.length===2&&(n=e+t[1])}return n}const $r=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Pr(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=jn(n,$r),r=s.length,i={};for(let o=0;o<r;o++){const a=this.resolveNameSpace(s[o][1]);if(this.ignoreAttributesFn(a,t))continue;let c=s[o][4],l=this.options.attributeNamePrefix+a;if(a.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l==="__proto__"&&(l="#__proto__"),c!==void 0){this.options.trimValues&&(c=c.trim()),c=this.replaceEntitiesValue(c);const h=this.options.attributeValueProcessor(a,c,t);h==null?i[l]=c:typeof h!=typeof c||h!==c?i[l]=h:i[l]=Me(c,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(i[l]=!0)}if(!Object.keys(i).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=i,o}return i}}const Hr=function(n){n=n.replace(/\r\n?/g,`
9
+ `);const t=new pt("!xml");let e=t,s="",r="";for(let i=0;i<n.length;i++)if(n[i]==="<")if(n[i+1]==="/"){const a=mt(n,">",i,"Closing Tag is not closed.");let c=n.substring(i+2,a).trim();if(this.options.removeNSPrefix){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&(s=this.saveTextToParentTag(s,e,r));const l=r.substring(r.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let h=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(h=r.lastIndexOf(".",r.lastIndexOf(".")-1),this.tagsNodeStack.pop()):h=r.lastIndexOf("."),r=r.substring(0,h),e=this.tagsNodeStack.pop(),s="",i=a}else if(n[i+1]==="?"){let a=Re(n,i,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,e,r),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new pt(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,r,a.tagName)),this.addChild(e,c,r,i)}i=a.closeIndex+1}else if(n.substr(i+1,3)==="!--"){const a=mt(n,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){const c=n.substring(i+4,a-2);s=this.saveTextToParentTag(s,e,r),e.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}i=a}else if(n.substr(i+1,2)==="!D"){const a=wr(n,i);this.docTypeEntities=a.entities,i=a.i}else if(n.substr(i+1,2)==="!["){const a=mt(n,"]]>",i,"CDATA is not closed.")-2,c=n.substring(i+9,a);s=this.saveTextToParentTag(s,e,r);let l=this.parseTextData(c,e.tagname,r,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?e.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):e.add(this.options.textNodeName,l),i=a+2}else{let a=Re(n,i,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let h=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),e&&s&&e.tagname!=="!xml"&&(s=this.saveTextToParentTag(s,e,r,!1));const g=e;g&&this.options.unpairedTags.indexOf(g.tagname)!==-1&&(e=this.tagsNodeStack.pop(),r=r.substring(0,r.lastIndexOf("."))),c!==t.tagname&&(r+=r?"."+c:c);const f=i;if(this.isItStopNode(this.options.stopNodes,r,c)){let m="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),r=r.substr(0,r.length-1),h=c):h=h.substr(0,h.length-1),i=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)i=a.closeIndex;else{const v=this.readStopNodeData(n,l,d+1);if(!v)throw new Error(`Unexpected end of ${l}`);i=v.i,m=v.tagContent}const b=new pt(c);c!==h&&u&&(b[":@"]=this.buildAttributesMap(h,r,c)),m&&(m=this.parseTextData(m,c,r,!0,u,!0,!0)),r=r.substr(0,r.lastIndexOf(".")),b.add(this.options.textNodeName,m),this.addChild(e,b,r,f)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),r=r.substr(0,r.length-1),h=c):h=h.substr(0,h.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const m=new pt(c);c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,r,c)),this.addChild(e,m,r,f),r=r.substr(0,r.lastIndexOf("."))}else{const m=new pt(c);this.tagsNodeStack.push(e),c!==h&&u&&(m[":@"]=this.buildAttributesMap(h,r,c)),this.addChild(e,m,r,f),e=m}s="",i=d}}else s+=n[i];return t.child};function Wr(n,t,e,s){this.options.captureMetaData||(s=void 0);const r=this.options.updateTag(t.tagname,e,t[":@"]);r===!1||(typeof r=="string"&&(t.tagname=r),n.addChild(t,s))}const Br=function(n){if(this.options.processEntities){for(let t in this.docTypeEntities){const e=this.docTypeEntities[t];n=n.replace(e.regx,e.val)}for(let t in this.lastEntities){const e=this.lastEntities[t];n=n.replace(e.regex,e.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){const e=this.htmlEntities[t];n=n.replace(e.regex,e.val)}n=n.replace(this.ampEntity.regex,this.ampEntity.val)}return n};function Dr(n,t,e,s){return n&&(s===void 0&&(s=t.child.length===0),n=this.parseTextData(n,t.tagname,e,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,s),n!==void 0&&n!==""&&t.add(this.options.textNodeName,n),n=""),n}function Kr(n,t,e){const s="*."+e;for(const r in n){const i=n[r];if(s===i||t===i)return!0}return!1}function Lr(n,t,e=">"){let s,r="";for(let i=t;i<n.length;i++){let o=n[i];if(s)o===s&&(s="");else if(o==='"'||o==="'")s=o;else if(o===e[0])if(e[1]){if(n[i+1]===e[1])return{data:r,index:i}}else return{data:r,index:i};else o===" "&&(o=" ");r+=o}}function mt(n,t,e,s){const r=n.indexOf(t,e);if(r===-1)throw new Error(s);return r+t.length-1}function Re(n,t,e,s=">"){const r=Lr(n,t+1,s);if(!r)return;let i=r.data;const o=r.index,a=i.search(/\s/);let c=i,l=!0;a!==-1&&(c=i.substring(0,a),i=i.substring(a+1).trimStart());const h=c;if(e){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1),l=c!==r.data.substr(u+1))}return{tagName:c,tagExp:i,closeIndex:o,attrExpPresent:l,rawTagName:h}}function zr(n,t,e){const s=e;let r=1;for(;e<n.length;e++)if(n[e]==="<")if(n[e+1]==="/"){const i=mt(n,">",e,`${t} is not closed`);if(n.substring(e+2,i).trim()===t&&(r--,r===0))return{tagContent:n.substring(s,e),i};e=i}else if(n[e+1]==="?")e=mt(n,"?>",e+1,"StopNode is not closed.");else if(n.substr(e+1,3)==="!--")e=mt(n,"-->",e+3,"StopNode is not closed.");else if(n.substr(e+1,2)==="![")e=mt(n,"]]>",e,"StopNode is not closed.")-2;else{const i=Re(n,e,">");i&&((i&&i.tagName)===t&&i.tagExp[i.tagExp.length-1]!=="/"&&r++,e=i.closeIndex)}}function Me(n,t,e){if(t&&typeof n=="string"){const s=n.trim();return s==="true"?!0:s==="false"?!1:Ir(n,e)}else return ir(n)?n:""}const Ae=pt.getMetaDataSymbol();function jr(n,t){return Fn(n,t)}function Fn(n,t,e){let s;const r={};for(let i=0;i<n.length;i++){const o=n[i],a=Ur(o);let c="";if(e===void 0?c=a:c=e+"."+a,a===t.textNodeName)s===void 0?s=o[a]:s+=""+o[a];else{if(a===void 0)continue;if(o[a]){let l=Fn(o[a],t,c);const h=Gr(l,t);o[Ae]!==void 0&&(l[Ae]=o[Ae]),o[":@"]?Fr(l,o[":@"],c,t):Object.keys(l).length===1&&l[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?l=l[t.textNodeName]:Object.keys(l).length===0&&(t.alwaysCreateTextNode?l[t.textNodeName]="":l=""),r[a]!==void 0&&r.hasOwnProperty(a)?(Array.isArray(r[a])||(r[a]=[r[a]]),r[a].push(l)):t.isArray(a,c,h)?r[a]=[l]:r[a]=l}}}return typeof s=="string"?s.length>0&&(r[t.textNodeName]=s):s!==void 0&&(r[t.textNodeName]=s),r}function Ur(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(s!==":@")return s}}function Fr(n,t,e,s){if(t){const r=Object.keys(t),i=r.length;for(let o=0;o<i;o++){const a=r[o];s.isArray(a,e+"."+a,!0,!0)?n[a]=[t[a]]:n[a]=t[a]}}}function Gr(n,t){const{textNodeName:e}=t,s=Object.keys(n).length;return!!(s===0||s===1&&(n[e]||typeof n[e]=="boolean"||n[e]===0))}class Zr{constructor(t){this.externalEntities={},this.options=mr(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const i=ar(t,e);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const s=new Cr(this.options);s.addExternalEntities(this.externalEntities);const r=s.parseXml(t);return this.options.preserveOrder||r===void 0?r:jr(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return pt.getMetaDataSymbol()}}const Vr=`
10
+ `;function Jr(n,t){let e="";return t.format&&t.indentBy.length>0&&(e=Vr),Gn(n,t,"",e)}function Gn(n,t,e,s){let r="",i=!1;for(let o=0;o<n.length;o++){const a=n[o],c=Yr(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];Xr(l,t)||(f=t.tagValueProcessor(c,f),f=Zn(f,t)),i&&(r+=s),r+=f,i=!1;continue}else if(c===t.cdataPropName){i&&(r+=s),r+=`<![CDATA[${a[c][0][t.textNodeName]}]]>`,i=!1;continue}else if(c===t.commentPropName){r+=s+`<!--${a[c][0][t.textNodeName]}-->`,i=!0;continue}else if(c[0]==="?"){const f=vn(a[":@"],t),m=c==="?xml"?"":s;let b=a[c][0][t.textNodeName];b=b.length!==0?" "+b:"",r+=m+`<${c}${b}${f}?>`,i=!0;continue}let h=s;h!==""&&(h+=t.indentBy);const u=vn(a[":@"],t),d=s+`<${c}${u}`,g=Gn(a[c],t,l,h);t.unpairedTags.indexOf(c)!==-1?t.suppressUnpairedNode?r+=d+">":r+=d+"/>":(!g||g.length===0)&&t.suppressEmptyNode?r+=d+"/>":g&&g.endsWith(">")?r+=d+`>${g}${s}</${c}>`:(r+=d+">",g&&s!==""&&(g.includes("/>")||g.includes("</"))?r+=s+t.indentBy+g+s:r+=g,r+=`</${c}>`),i=!0}return r}function Yr(n){const t=Object.keys(n);for(let e=0;e<t.length;e++){const s=t[e];if(n.hasOwnProperty(s)&&s!==":@")return s}}function vn(n,t){let e="";if(n&&!t.ignoreAttributes)for(let s in n){if(!n.hasOwnProperty(s))continue;let r=t.attributeValueProcessor(s,n[s]);r=Zn(r,t),r===!0&&t.suppressBooleanAttributes?e+=` ${s.substr(t.attributeNamePrefix.length)}`:e+=` ${s.substr(t.attributeNamePrefix.length)}="${r}"`}return e}function Xr(n,t){n=n.substr(0,n.length-t.textNodeName.length-1);let e=n.substr(n.lastIndexOf(".")+1);for(let s in t.stopNodes)if(t.stopNodes[s]===n||t.stopNodes[s]==="*."+e)return!0;return!1}function Zn(n,t){if(n&&n.length>0&&t.processEntities)for(let e=0;e<t.entities.length;e++){const s=t.entities[e];n=n.replace(s.regex,s.val)}return n}const qr={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(n,t){return t},attributeValueProcessor:function(n,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ct(n){this.options=Object.assign({},qr,n),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Un(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ei),this.processTextOrObjNode=Qr,this.options.format?(this.indentate=ti,this.tagEndChar=`>
11
11
  `,this.newLine=`
12
- `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}it.prototype.build=function(n){return this.options.preserveOrder?Qr(n,this.options):(Array.isArray(n)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(n={[this.options.arrayNodeName]:n}),this.j2x(n,0,[]).val)};it.prototype.j2x=function(n,t,e){let s="",r="";const i=e.join(".");for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))if(typeof n[o]>"u")this.isAttribute(o)&&(r+="");else if(n[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?r+="":o[0]==="?"?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(n[o]instanceof Date)r+=this.buildTextValNode(n[o],o,"",t);else if(typeof n[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,i))s+=this.buildAttrPairStr(a,""+n[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+n[o]);r+=this.replaceEntitiesValue(c)}else r+=this.buildTextValNode(n[o],o,"",t)}else if(Array.isArray(n[o])){const a=n[o].length;let c="",l="";for(let u=0;u<a;u++){const h=n[o][u];if(!(typeof h>"u"))if(h===null)o[0]==="?"?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof h=="object")if(this.options.oneListGroup){const d=this.j2x(h,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&h.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(h,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,h);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(h,o,"",t)}this.options.oneListGroup&&(c=this.buildObjectNode(c,o,l,t)),r+=c}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const a=Object.keys(n[o]),c=a.length;for(let l=0;l<c;l++)s+=this.buildAttrPairStr(a[l],""+n[o][a[l]])}else r+=this.processTextOrObjNode(n[o],o,t,e);return{attrStr:s,val:r}};it.prototype.buildAttrPairStr=function(n,t){return t=this.options.attributeValueProcessor(n,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+n:" "+n+'="'+t+'"'};function si(n,t,e,s){const r=this.j2x(n,e+1,s.concat(t));return n[this.options.textNodeName]!==void 0&&Object.keys(n).length===1?this.buildTextValNode(n[this.options.textNodeName],t,r.attrStr,e):this.buildObjectNode(r.val,t,r.attrStr,e)}it.prototype.buildObjectNode=function(n,t,e,s){if(n==="")return t[0]==="?"?this.indentate(s)+"<"+t+e+"?"+this.tagEndChar:this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let r="</"+t+this.tagEndChar,i="";return t[0]==="?"&&(i="?",r=""),(e||e==="")&&n.indexOf("<")===-1?this.indentate(s)+"<"+t+e+i+">"+n+r:this.options.commentPropName!==!1&&t===this.options.commentPropName&&i.length===0?this.indentate(s)+`<!--${n}-->`+this.newLine:this.indentate(s)+"<"+t+e+i+this.tagEndChar+n+this.indentate(s)+r}};it.prototype.closeTag=function(n){let t="";return this.options.unpairedTags.indexOf(n)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${n}`,t};it.prototype.buildTextValNode=function(n,t,e,s){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${n}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(s)+`<!--${n}-->`+this.newLine;if(t[0]==="?")return this.indentate(s)+"<"+t+e+"?"+this.tagEndChar;{let r=this.options.tagValueProcessor(t,n);return r=this.replaceEntitiesValue(r),r===""?this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(s)+"<"+t+e+">"+r+"</"+t+this.tagEndChar}};it.prototype.replaceEntitiesValue=function(n){if(n&&n.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];n=n.replace(e.regex,e.val)}return n};function ri(n){return this.options.indentBy.repeat(n)}function ii(n){return n.startsWith(this.options.attributeNamePrefix)&&n!==this.options.textNodeName?n.substr(this.attrPrefixLen):!1}class ot{constructor(t){_(this,"type");_(this,"attrs",{});_(this,"styles",{});_(this,"deleteMarker",!1);this.type=t}dx(t){return this.attrs.x==null?this.attrs.x=t:this.attrs.x+=t,this}dy(t){return this.attrs.y==null?this.attrs.y=t:this.attrs.y+=t,this}x(t){return this.attrs.x=t,this}y(t){return this.attrs.y=t,this}size(t,e){return this.attrs.width=t,this.attrs.height=e,this}remove(){this.deleteMarker=!0}left(...t){return`<${[this.type,Jn(this.attrs),yi(this.styles),...t].filter(e=>e!="").join(" ")}>`}right(){return`</${this.type}>`}center(){return""}toString(){return this.deleteMarker?"":`${this.left()}${this.center()}${this.right()}`}attr(t){if(typeof t=="string")return this.attrs[t]??"";for(const[e,s]of Object.entries(t))this.attrs[e]=s;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class Qe extends ot{constructor(e){super("image");_(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class ye extends ot{constructor(e){super("use");_(this,"attrs",{});this.attrs={...this.attrs,href:this.make(e)}}use(e){return this.attrs.href=`#${e}`,this}make(e){return e==null?e:`#${e}`}}class tn extends ot{constructor(){super("rect");_(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class yt extends ot{constructor(e=""){super("text");_(this,"attrs");_(this,"_text","");this._text=e,this.attrs={}}plain(e){return this._text=e,this}font(e){return this.attrs.fontFamily=e.family,this.attrs.fontSize=e.size,this}center(){return this._text}}let en=class extends ot{constructor(e){super("symbol");_(this,"raw");this.raw=e}id(){return this.attr("id")}center(){return this.raw}};class v extends ot{constructor(){super("g");_(this,"children",[]);_(this,"rotateMatrix");_(this,"translateMatrix")}add(e){return this.children.push(e),this}rotate(e,s,r){return this.rotateMatrix=Ys(e,s,r),this}translate(e,s){return this.translateMatrix=ke(e,s),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){const s=[this.translateMatrix,this.rotateMatrix].filter(r=>r!=null);return s.length==0?super.left():super.left(gi(Gs(s)))}each(e,s){for(let r=0;r<this.children.length;r++){const i=this.children[r];i instanceof v&&s&&i.each(e,!0),e(r,this.children)}}}const oi=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class Zn extends ot{constructor(){super("svg");_(this,"children",[]);_(this,"viewBox")}add(e){return this.children.push(e),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){return`<${[this.type,...oi,Jn(this.attrs),pi(this.viewBox)].filter(s=>s!="").join(" ")}>`}viewbox(e,s,r,i){return this.viewBox={x:e,y:s,width:r,height:i},this}importSymbol(e){for(const s of mi(e))this.add(s);return this}x(e){throw new Error("unimplemented")}y(e){throw new Error("unimplemented")}dx(e){throw new Error("unimplemented")}dy(e){throw new Error("unimplemented")}each(e,s){for(let r=0;r<this.children.length;r++){const i=this.children[r];i instanceof v&&s&&i.each(e,!0),e(r,this.children)}}}function Vn(){return new Zn}const ai=Vn,ci=v,li=Qe,ui=ye,hi=tn,di=yt;function fi(n){return n.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function pi(n){return n==null?"":`viewBox="${n.x} ${n.y} ${n.width} ${n.height}"`}function gi(n){return n==null?"":`transform="${qs(n)}"`}function Jn(n){return Object.entries(n).filter(([t,e])=>e!==void 0).map(([t,e])=>`${fi(t)}="${e}"`).join(" ")}function yi(n){const t=Object.entries(n).map(([e,s])=>`${e}: ${s};`).join(" ");return t!=""?`style="${t}"`:""}function*mi(n){const t=new Yr({ignoreAttributes:!1}),e=new it({ignoreAttributes:!1}),s=t.parse(n);for(const r of s.svg.symbol){const i=e.build(r),o=new en(i);for(const[a,c]of Object.entries(r))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const U=(n,t)=>{const e=B(n.tiles[0],t),s=e.baseHeight,r=e.baseWidth;if(n.is(b.SHO_KAN))return{width:r*2+s,height:Math.max(r*2,s)};const i=n.tiles.reduce((a,c)=>{const l=B(c,t).height;return l>a?l:a},0);return{width:n.tiles.reduce((a,c)=>a+B(c,t).width,0),height:i}},B=(n,t)=>{const e=parseFloat((nt.HEIGHT*t).toPrecision(5)),s=parseFloat((nt.WIDTH*t).toPrecision(5)),r=n.has(y.HORIZONTAL)?{width:e,height:s,baseWidth:s,baseHeight:e}:{width:s,height:e,w:s,baseWidth:s,baseHeight:e};return(n.has(y.TSUMO)||n.has(y.DORA))&&(r.width+=s*nt.TEXT_SCALE),r};class Ct{constructor(t={}){_(this,"tileWidth");_(this,"tileHeight");_(this,"imageHostUrl");_(this,"imageExt");_(this,"scale");_(this,"svgSprite");this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=nt.WIDTH*this.scale,this.tileHeight=nt.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=B(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new Qe().load(this.buildURL(t));return this.svgSprite&&(e=new ye().use(Ct.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,s){const r=B(t,this.scale);return this.image(t).dx(e).dy(s).size(r.baseWidth,r.baseHeight)}createTextImage(t,e,s,r){const i=this.createImage(t,e,s),o=B(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,u=new yt().plain(r);u.size(o.baseWidth,o.baseHeight).font({family:Fe,size:a}).dx(c).dy(l);const h=new v;return h.add(i).add(u).translate(e,s),h}createRotate90Image(t,e,s,r=!1){const i=this.createImage(t,0,0),o=B(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),u=r?s-this.getDiffTileHeightWidth(t):s,h=new v;return h.add(i).translate(l,u).rotate(90,a,c),h}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==p.BACK||t.has(y.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${Ct.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class nn extends Ct{constructor(){super(...arguments);_(this,"blockMargin",nt.WIDTH*nt.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const s=e instanceof R?e.tilesWithBack:e.tiles,r=new v;let i=0;for(const o of s){const a=B(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),l=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,u=c(o,i,l);r.add(u),i+=a.width}return r}createBlockPonChiKan(e){const s=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let r=0;const i=new v;if(e.type==b.SHO_KAN){let o=s;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(y.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=B(e.tiles[a],this.scale);if(a==o)continue;if(a==s){const h=e.tiles[s],d=e.tiles[o],g=B(h,this.scale),f=this.createRotate90Image(h,0,0,!0),m=this.createRotate90Image(d,0,g.height,!0);i.add(new v().translate(r,0).add(f).add(m)),r+=g.width;continue}const l=c.width*2-c.height,u=this.createImage(e.tiles[a],r,l);r+=c.width,i.add(u)}return i}if(e.type==b.CHI){const o=e.tiles[s],a=this.createRotate90Image(o,r,this.getDiffTileHeightWidth(o));r+=B(o,this.scale).width,i.add(a);for(let c=0;c<e.tiles.length;c++){if(c==s)continue;const l=e.tiles[c],u=B(l,this.scale),h=this.createImage(l,r,0);r+=u.width,i.add(h)}return i}for(let o=0;o<e.tiles.length;o++){const a=o==s?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],l=o==s?this.getDiffTileHeightWidth(c):0,u=B(c,this.scale),h=a(c,r,l);r+=u.width,i.add(h)}return i}}const wi=(n,t)=>{const e=n.scale;return{[b.CHI]:function(r){const i=U(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.PON]:function(r){const i=U(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.DAI_KAN]:function(r){const i=U(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.SHO_KAN]:function(r){const i=U(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.AN_KAN]:function(r){S(r instanceof R,`block type is not ankan: ${r.type}`);const i=U(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[b.IMAGE_DORA]:function(r){r=(t==null?void 0:t.doraText)==!1?new kt([r.tiles[0].clone({remove:y.DORA})]):r;const i=U(r,e),o=new v,a=(t==null?void 0:t.doraText)===!1?n.createImage(r.tiles[0],0,0):n.createTextImage(r.tiles[0],0,0,"(ドラ)");return o.add(a),{...i,e:o}},[b.TSUMO]:function(r){r=(t==null?void 0:t.tsumoText)==!1?new kt([r.tiles[0].clone({remove:y.TSUMO})]):r;const i=U(r,e),o=new v,a=(t==null?void 0:t.tsumoText)===!1?n.createImage(r.tiles[0],0,0):n.createTextImage(r.tiles[0],0,0,"(ツモ)");return o.add(a),{...i,e:o}},[b.HAND]:function(r){const i=U(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[b.IMAGE_DISCARD]:function(r){const i=U(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[b.THREE]:function(r){throw new Error("three is unsupported")},[b.RUN]:function(r){throw new Error("run is unsupported")},[b.PAIR]:function(r){throw new Error("pair is unsupported")},[b.ISOLATED]:function(r){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(r){if(r.tiles.some(a=>a.has(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const i=U(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}}}},Tt=(n,t,e)=>{const s=wi(n,e);let r=0,i=0;const o=[];for(const h of t){const d=s[h.type],g=d(h);i+=g.width,r=g.height>r?g.height:r,o.push(g)}const a=r,c=i+(t.length-1)*n.blockMargin,l=new v;let u=0;for(const h of o){const d=a-h.height,g=new v().translate(u,d);g.add(h.e),l.add(g),u+=h.width+n.blockMargin}return{e:l,width:c,height:a}},bi=(n,t,e={},s={responsive:!1,doraText:!0,tsumoText:!0})=>{const r=new nn(e),i=Tt(r,t,s);s.responsive||n.size(i.width,i.height),n.viewbox(0,0,i.width,i.height),n.add(i.e)},Xn=()=>{const n=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(p)){if(e==p.BACK){t.push(Ct.buildID(new w(e,0)));continue}t.push(...n.map(s=>Ct.buildID(new w(e,s))).flat())}return t},_i=n=>{const t=Xn(),e=[];return n.each((s,r)=>{const i=r[s];if(i instanceof ye){const a=i.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},Ei=n=>{const t=Xn(),e=_i(n);n.each((s,r)=>{const i=r[s];i instanceof en&&(t.includes(i.id())&&e.includes(i.id())||i.remove())},!0)},Ai=n=>{const e=[];for(let s=0;s<n.length;s+=6){const r=n.slice(s,s+6);e.push(r)}return e},j=(n,t,e,s,r=0,i=0)=>{const o=new v().add(n);if(s==90){const a=r,c=i-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==180){const a=r+t,c=i-e;return o.rotate(s,0,e).translate(a,c),new v().add(o)}if(s==270){const a=r+e,c=i+(t-e);return o.rotate(s,0,e).translate(a,c),new v().add(o)}return new v().add(o)},te=(n,t)=>{const e=new v,s=Ai(n);for(let r=0;r<s.length;r++){let i=s[r],o=r*t.tileHeight;const a=t.createBlockHandDiscard(new Je(i,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*s.length}},Ni=(n,t,e)=>{const s=t.font,r=t.textWidth,i=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Ie.WIDTH*n.scale,l=Ie.HEIGHT*n.scale;let u=r*3,h=i;const d=(c+n.tileWidth+r-u)/2,g=new yt().plain(e.round).font(s).x(d).y(0);h+=25*n.scale;const f=n.tileHeight,m=new v().size(c,f).translate(0,h),E={family:s.family,size:s.size*.7},N=n.createStick(1e3).size(c,l).x(0).y(0),O=new yt().plain(a.toString()).font(E).dx(c).dy(l),M=n.createStick(100).size(c,l).x(0).y(l+l),Et=new yt().plain(o.toString()).font(E).dx(c).dy(l*3);m.add(N),m.add(O),m.add(M),m.add(Et);const At=n.createImage(e.doras[0],0,0).x(c+r).y(0);m.add(At);const Nt=new v;return Nt.add(g),Nt.add(g),Nt.add(m),{e:Nt,width:c+n.tileWidth+r,height:h+n.tileHeight}},Si=(n,t,e=0)=>{const s=Tt(n,t.front),r=Tt(n,t.right),i=Tt(n,t.opposite),o=Tt(n,t.left),a=[s.width,r.width,i.width,o.width].reduce((m,E)=>Math.max(m,E)),c=Math.max(e+n.tileHeight*2+n.blockMargin*2,a+n.tileWidth*2+n.blockMargin),l=c,u=j(s.e,s.width,s.height,0).translate((c-s.width)/2,l-s.height),h=j(r.e,r.width,r.height,270).translate(c-r.height,(c-r.width)/2),d=j(i.e,i.width,i.height,180).translate((c-i.width)/2,0),g=j(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),f=new v().size(c,l);return f.add(u),f.add(h),f.add(d),f.add(g),{e:new v().add(f),width:c,height:l}},vi=n=>{const t=Object.values(fe),e=t.indexOf(n);return[...t.slice(e),...t.slice(0,e)]},Ti=(n,t,e)=>{const s=n.tileWidth*5+n.tileHeight*1,r=t.font,i=t.textWidth,o=t.textHeight,a=t.numWidth,c=Ni(n,t,e);c.e.translate(s/2-c.width/2,s/2-c.height/2);const l=(Ms,mn,xs)=>{const $s=`${Ms} ${mn}`,Ps=new yt().plain($s).font(r).attr(xs);return{e:new v().add(Ps),width:i+a*mn.toString().length,height:o}},[u,h,d,g]=vi(e.frontPlace),f=e.scores,E=l(u,f.front,{x:s/2,y:s,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let N=l(h,f.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const O=j(N.e,N.width,N.height,270).translate(s,s/2-N.width);let M=l(d,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const Et=j(M.e,M.width,M.height,180).translate(s/2-M.width,-M.height);let At=l(g,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Nt=j(At.e,At.width,At.height,90).translate(-At.height,s/2),at=new v,Rs=new tn().size(s,s).x(0).y(0).fill("none").stroke("#000000");return at.add(Rs),at.add(c.e),at.add(E),at.add(O),at.add(Et),at.add(Nt),{e:at,width:s,height:s}},Ii=(n,t)=>{const e=te(t.front,n),s=te(t.right,n),r=te(t.opposite,n),i=te(t.left,n),o=[e.height,s.height,r.height,i.height].reduce((O,M)=>Math.max(O,M)),a=n.tileWidth*5+n.tileHeight*1,c=o,l=a+o*2+n.blockMargin,u=l,h=new v().size(l,u),d=l/2-a/2,g=u/2-a/2,f=j(e.e,a,c,0).translate(d,u-c),m=j(s.e,a,c,270).translate(l-c,g),E=j(r.e,a,c,180).translate(d,0),N=j(i.e,a,c,90).translate(0,g);return h.add(f),h.add(m),h.add(E),h.add(N),{e:new v().add(h),width:l,height:u}},Yn=(n,t,e,s,r)=>{const i=new v,o=Ii(n,s),a=Si(n,e,o.height),c=Ti(n,t,r);return o.e.translate((a.width-o.width)/2,(a.height-o.height)/2),c.e.translate((a.width-c.width)/2,(a.height-c.height)/2),i.add(a.e),i.add(o.e),i.add(c.e),{e:i,width:a.width,height:a.height}},Oi=(n,t,e={},s,r={responsive:!1})=>{const i=new nn(e),o=s,{discards:a,hands:c,scoreBoard:l}=ts(t),u=Yn(i,o,c,a,l);r.responsive||n.size(u.width,u.height),n.viewbox(0,0,u.width,u.height),n.add(u.e)};var J;function qn(n){return{lang:(n==null?void 0:n.lang)??(J==null?void 0:J.lang),message:n==null?void 0:n.message,abortEarly:(n==null?void 0:n.abortEarly)??(J==null?void 0:J.abortEarly),abortPipeEarly:(n==null?void 0:n.abortPipeEarly)??(J==null?void 0:J.abortPipeEarly)}}var Ee;function ki(n){return Ee==null?void 0:Ee.get(n)}var Ae;function Ci(n){return Ae==null?void 0:Ae.get(n)}var Ne;function Ri(n,t){var e;return(e=Ne==null?void 0:Ne.get(n))==null?void 0:e.get(t)}function Rt(n){var e,s;const t=typeof n;return t==="string"?`"${n}"`:t==="number"||t==="bigint"||t==="boolean"?`${n}`:t==="object"||t==="function"?(n&&((s=(e=Object.getPrototypeOf(n))==null?void 0:e.constructor)==null?void 0:s.name))??"null":t}function st(n,t,e,s,r){const i=r&&"input"in r?r.input:e.value,o=(r==null?void 0:r.expected)??n.expects??null,a=(r==null?void 0:r.received)??Rt(i),c={kind:n.kind,type:n.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:r==null?void 0:r.path,issues:r==null?void 0:r.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},l=n.kind==="schema",u=(r==null?void 0:r.message)??n.message??Ri(n.reference,c.lang)??(l?Ci(c.lang):null)??s.message??ki(c.lang);u!==void 0&&(c.message=typeof u=="function"?u(c):u),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Dt(n){return{version:1,vendor:"valibot",validate(t){return n["~run"]({value:t},qn())}}}function Mi(n,t){const e=[...new Set(n)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Me(n,t){return{kind:"validation",type:"max_value",reference:Me,async:!1,expects:`<=${n instanceof Date?n.toJSON():Rt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value<=this.requirement)&&st(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():Rt(e.value)}),e}}}function xe(n,t){return{kind:"validation",type:"min_value",reference:xe,async:!1,expects:`>=${n instanceof Date?n.toJSON():Rt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value>=this.requirement)&&st(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():Rt(e.value)}),e}}}function xi(n,t,e){return typeof n.fallback=="function"?n.fallback(t,e):n.fallback}function Qn(n,t,e){return typeof n.default=="function"?n.default(t,e):n.default}function ce(n){return{kind:"schema",type:"number",reference:ce,expects:"number",async:!1,message:n,get"~standard"(){return Dt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:st(this,"type",t,e),t}}}function K(n,t){return{kind:"schema",type:"optional",reference:K,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:t,get"~standard"(){return Dt(this)},"~run"(e,s){return e.value===void 0&&(this.default!==void 0&&(e.value=Qn(this,e,s)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,s)}}}function $e(n,t){return{kind:"schema",type:"picklist",reference:$e,expects:Mi(n.map(Rt),"|"),async:!1,options:n,message:t,get"~standard"(){return Dt(this)},"~run"(e,s){return this.options.includes(e.value)?e.typed=!0:st(this,"type",e,s),e}}}function Mt(n,t){return{kind:"schema",type:"strict_object",reference:Mt,expects:"Object",async:!1,entries:n,message:t,get"~standard"(){return Dt(this)},"~run"(e,s){var i;const r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=this.entries[o];if(o in r||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){const c=o in r?r[o]:Qn(a),l=a["~run"]({value:c},s);if(l.issues){const u={type:"object",origin:"value",input:r,key:o,value:c};for(const h of l.issues)h.path?h.path.unshift(u):h.path=[u],(i=e.issues)==null||i.push(h);if(e.issues||(e.issues=l.issues),s.abortEarly){e.typed=!1;break}}l.typed||(e.typed=!1),e.value[o]=l.value}else if(a.fallback!==void 0)e.value[o]=xi(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(st(this,"key",e,s,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:r,key:o,value:r[o]}]}),s.abortEarly))break}if(!e.issues||!s.abortEarly){for(const o in r)if(!(o in this.entries)){st(this,"key",e,s,{input:o,expected:"never",path:[{type:"object",origin:"key",input:r,key:o,value:r[o]}]});break}}}else st(this,"type",e,s);return e}}}function le(n){return{kind:"schema",type:"string",reference:le,expects:"string",async:!1,message:n,get"~standard"(){return Dt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:st(this,"type",t,e),t}}}function Tn(...n){return{...n[0],pipe:n,get"~standard"(){return Dt(this)},"~run"(t,e){for(const s of n)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=s["~run"](t,e))}return t}}}function $i(n,t,e){const s=n["~run"]({value:t},qn(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}const ee=K(Mt({discard:K(le(),""),hand:K(le(),""),score:K(ce(),25e3)}),{discard:"",hand:"",score:25e3}),Pi=Mt({[A.E]:ee,[A.S]:ee,[A.W]:ee,[A.N]:ee}),ct={round:k.E1,sticks:{reach:0,dead:0},doras:A.S,front:A.E},Hi=K(Mt({round:K($e(Object.keys(Ge)),ct.round),sticks:K(Mt({reach:K(Tn(ce(),xe(0,""),Me(9,"")),ct.sticks.reach),dead:K(Tn(ce(),xe(0,""),Me(9,"")),ct.sticks.dead)}),ct.sticks),doras:K(le(),ct.doras),front:K($e(Object.keys(fe)),ct.front)}),ct),Wi=Mt({...Pi.entries,board:Hi}),ts=n=>{const t=es(n);return ns(t)},es=n=>{const t=Bi(n),e=$i(Wi,t);if(!e.success)throw e.issues;return e.output},Bi=n=>{const t="table",e="board",s=n.split(`
13
- `).map(a=>a.trim()).filter(a=>a!="");if(s.length==0)throw new Error("empty input");const r=s.shift();if(!r.startsWith(t))throw new Error(`input does not start with table: ${r}`);const i={};let o=[A.E,A.S,A.W,A.N,e];for(;;){const a=s.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,u]=Ki([...s]);i.board=l;for(let h=0;h<u;h++)s.shift()}else{const[l,u]=Di([...s]);i[c]=l;for(let h=0;h<u;h++)s.shift()}}return i},F=(n,t)=>n.replace(t,"").replace(":","").trim(),Di=n=>{const t="hand",e="discard",s="score",r={};let i=0;for(;i<n.length;i++){const o=n[i];if(o.startsWith(t))r.hand=F(o,t);else if(o.startsWith(e))r.discard=F(o,e);else if(o.startsWith(s))r.score=Number(F(o,s));else break}return[r,i]},Ki=n=>{const t="doras",e="round",s="front",r="sticks",i="reach",o="dead",a={};let c=0;for(;c<n.length;c++){const l=n[c];if(l.startsWith(t))a.doras=F(l,t);else if(l.startsWith(e))a.round=F(l,e);else if(l.startsWith(s))a.front=F(l,s);else if(l.startsWith(r)){a.sticks={};const u=n[c+1]??"",h=n[c+2]??"";u.startsWith(i)&&(a.sticks.reach=Number(F(u,i))),u.startsWith(o)&&(a.sticks.dead=Number(F(u,o))),h.startsWith(i)&&(a.sticks.reach=Number(F(h,i))),h.startsWith(o)&&(a.sticks.dead=Number(F(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ns=n=>{const t=n.board.front,e=Li(t),s=a=>n[a].discard.replace(/\r?\n/g,""),r={front:new W(s(e.front)).tiles(),right:new W(s(e.right)).tiles(),opposite:new W(s(e.opposite)).tiles(),left:new W(s(e.left)).tiles()},i={front:new W(n[e.front].hand).parse(),right:new W(n[e.right].hand).parse(),opposite:new W(n[e.opposite].hand).parse(),left:new W(n[e.left].hand).parse()},o={round:Ge[n.board.round],frontPlace:fe[t],sticks:n.board.sticks,doras:new W(n.board.doras).tiles(),scores:{front:n[e.front].score,right:n[e.right].score,opposite:n[e.opposite].score,left:n[e.left].score}};return{discards:r,hands:i,scoreBoard:o}},Li=n=>({front:n,right:gt(n),opposite:gt(gt(n)),left:pe(n)});function*L(n){const t=n!=null&&n.filterBy&&n.filterBy.length>0?n==null?void 0:n.filterBy:Object.values(p);for(const e of t){if(n!=null&&n.skipBack&&e==p.BACK)continue;const s=e==p.Z?7:e==p.BACK?1:9;for(let r=1;r<=s;r++)yield[e,r]}}class me{constructor(t,e=!1){_(this,"data");this.data={[p.M]:[0,0,0,0,0,0,0,0,0,0],[p.P]:[0,0,0,0,0,0,0,0,0,0],[p.S]:[0,0,0,0,0,0,0,0,0,0],[p.Z]:[0,0,0,0,0,0,0,0],[p.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const s=Array.isArray(t)?t:new W(t).parse();for(const r of s){if(r.isCalled()){this.data.called=[...this.called,r];continue}else if(r.is(b.TSUMO)){const i=r.tiles[0];this.inc([i]),this.data.tsumo=i;continue}else if(r.is(b.HAND)){this.inc(r.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(i=>i===p.BACK)){this.inc(r.tiles);continue}else if(e){this.inc(r.tiles);continue}throw new Error(`unexpected block ${r.type} ${r.toString()}`)}}get hands(){const t=[];for(const[e,s]of L()){let r=this.get(e,s);e!=p.Z&&s==5&&this.get(e,0)>0&&(r-=this.get(e,0),t.push(new w(e,s,[y.RED])));for(let i=0;i<r;i++)t.push(new w(e,s))}if(this.drawn!=null){const e=this.drawn,s=t.findIndex(r=>r.equals(e)&&e.has(y.RED)==r.has(y.RED));S(s>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[s]=t[s].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${q}${this.called.join(q)}`:"",e=this.drawn?`${q}${this.drawn.toString()}`:"",s=this.hands.filter(i=>!i.has(y.TSUMO));return`${new kt(s).toString()}${e}${t}`}get called(){return this.data.called}get reached(){return this.data.reached}get drawn(){return this.data.tsumo}get menzen(){return!this.called.some(t=>!(t instanceof R))}sum(t){let e=0;for(const[s,r]of L({filterBy:[t]}))e+=this.get(s,r);return e}get(t,e){return t==p.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const s of t){if(s.t!=p.BACK&&this.get(s.t,s.n)>=4||s.has(y.RED)&&this.get(s.t,0)>0)throw this.dec(e),new Error(`unable to increase ${s} in ${this.toString()}`);e.push(s),s.t==p.BACK?this.data[s.t][1]+=1:(this.data[s.t][s.n]+=1,s.has(y.RED)&&(this.data[s.t][0]+=1))}return e}dec(t){const e=[];for(const s of t){if(this.get(s.t,s.n)<1||s.has(y.RED)&&this.get(s.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${s.toString()} in ${this.toString()}`);if(e.push(s),s.t==p.BACK?this.data[s.t][1]-=1:(this.data[s.t][s.n]-=1,s.has(y.RED)&&(this.data[s.t][0]-=1)),C(s)&&this.get(s.t,5)==0&&this.get(s.t,0)>0){this.data[s.t][0]=0;const r=e.pop().clone({add:y.RED});e.push(r)}}return e}draw(t){const e=t.clone({add:y.TSUMO});this.inc([e]),this.data.tsumo=e}discard(t){this.dec([t]),this.data.tsumo=null}reach(){if(!this.menzen)throw new Error("cannot reach");if(this.data.reached)throw new Error("already reached");this.data.reached=!0}call(t){const e=t.tiles.filter(s=>!s.has(y.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`removal: ${e} block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof R){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof D){const e=this.data.called.findIndex(r=>r.is(b.PON)&&r.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let s=t.tiles[0];s=C(s)?s.clone({remove:y.RED}):s,this.dec([s]),this.data.called=[...this.called.slice(0,e),...this.called.slice(e+1),t],this.data.tsumo=null;return}throw new Error(`unexpected input ${t}`)}clone(){const t=new me(this.toString());return t.data.reached=this.data.reached,t}}class Yt{constructor(t){_(this,"hand");this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[s,r]of L({skipBack:!0}))this.hand.get(s,r)==2&&t++,this.hand.get(s,r)==1&&e++;return t>7&&(t=7),t+e>=7&&(e=7-t),13-2*t-e}thirteenOrphans(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const s of Object.values(p)){if(s==p.BACK)continue;const r=s==p.Z?xt:G;for(const i of r)this.hand.get(s,i)>=1&&t++,this.hand.get(s,i)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=s=>{const r=[0,0,0];for(const[d,g]of L({filterBy:[p.Z]}))this.hand.get(d,g)>=3?r[0]++:this.hand.get(d,g)==2?r[1]++:this.hand.get(d,g)==1&&r[2]++;const i=[0,0,0],o=this.hand.get(p.BACK,0),a=o%3;i[0]=Math.floor(o/3),a==2?i[1]=1:a==1&&(i[2]=1);let c=13;const l=this.patternNumType(p.M),u=this.patternNumType(p.P),h=this.patternNumType(p.S);for(const d of[l.patternA,l.patternB])for(const g of[u.patternA,u.patternB])for(const f of[h.patternA,h.patternB]){const m=[this.hand.called.length,0,0];for(let N=0;N<3;N++)m[N]+=d[N]+g[N]+f[N]+r[N]+i[N];const E=this.calcCommon(m[0],m[1],m[2],s);E<c&&(c=E)}return c};let e=t(!1);for(const[s,r]of L())if(this.hand.get(s,r)>=2){const i=this.hand.dec(new Array(2).fill(new w(s,r))),o=t(!0);this.hand.inc(i),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let s=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const r=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),i=this.patternNumType(t,e);this.hand.inc(r),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<s.patternA[2]||i.patternA[2]==s.patternA[2]&&i.patternA[1]<s.patternA[1])&&(s.patternA=i.patternA),(i.patternB[0]>s.patternB[0]||i.patternB[0]==s.patternB[0]&&i.patternB[1]>s.patternB[1])&&(s.patternB=i.patternB)}if(this.hand.get(t,e)>=3){const r=this.hand.dec(new Array(3).fill(new w(t,e))),i=this.patternNumType(t,e);this.hand.inc(r),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<s.patternA[2]||i.patternA[2]==s.patternA[2]&&i.patternA[1]<s.patternA[1])&&(s.patternA=i.patternA),(i.patternB[0]>s.patternB[0]||i.patternB[0]==s.patternB[0]&&i.patternB[1]>s.patternB[1])&&(s.patternB=i.patternB)}return s}groupRemainingTiles(t){let e=0,s=0,r=0;for(const[i,o]of L({filterBy:[t]}))r+=this.hand.get(i,o),o<=7&&this.hand.get(i,o+1)==0&&this.hand.get(i,o+2)==0&&(e+=r>>1,s+=r%2,r=0);return e+=r>>1,s+=r%2,{patternA:[0,e,s],patternB:[0,e,s]}}calcCommon(t,e,s,r){let i=r?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(s+=t+e-4,e=4-t),t+e+s>i&&(s=i-t-e),r&&e++,13-t*3-e*2-s}}class ss{constructor(t){_(this,"hand");this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const s=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,r=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const u=a[l];if(u.isCalled())continue;const h=u.tiles.findIndex(g=>g.equals(e)&&e.has(y.RED)==g.has(y.RED));if(h<0)continue;const d=jt(u);c[d]||(c[d]=!0,r.push([o,l,h]))}}if(r.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const i=[];for(const[o,a,c]of r){const u=[...t[o]],h=u[a],d=h.tiles[c].clone({add:s});u[a]=h.clone({replace:{idx:c,tile:d}}),i.push(u)}return i}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,s]of L({skipBack:!0})){const r=this.hand.get(e,s);if(r==2){const i=this.hand.dec(new Array(2).fill(new w(e,s)));t.push(new H(i[0],i[1])),this.hand.inc(i)}else{if(r==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const s of Object.values(p)){if(s==p.BACK)continue;const r=s==p.Z?xt:G;for(let i of r)if(this.hand.get(s,i)==1)t.push(new Ve(new w(s,i)));else if(this.hand.get(s,i)==2&&e==!1)t.unshift(new H(new w(s,i),new w(s,i))),e=!0;else return[]}return[t]}nineGates(){const t=(e,s,r)=>r.includes(this.hand.get(e,s));for(const e of Object.values(p)){if(e==p.BACK||e==p.Z)continue;const s=t(e,1,[3,4])&&t(e,9,[3,4])&&t(e,2,[1,2])&&t(e,3,[1,2])&&t(e,4,[1,2])&&t(e,5,[1,2])&&t(e,6,[1,2])&&t(e,7,[1,2])&&t(e,8,[1,2]),r=this.hand.sum(e)==14;if(s&&r)return[[new kt(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of L())if(this.hand.get(e,s)>=2){const r=new Array(2).fill(new w(e,s));s==5&&this.hand.get(e,0)>0&&this.hand.get(e,s)>=3&&(r[1]=new w(e,s,[y.RED]));const i=this.hand.dec(r),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new H(i[0],i[1])),a));t=[...t,...o],this.hand.inc(i)}return t}patternAll(){return[this.addRedPattern(p.M,this.handleNumType(p.M)),this.addRedPattern(p.P,this.handleNumType(p.P)),this.addRedPattern(p.S,this.handleNumType(p.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,r)=>r.length-s.length).reduce((s,r)=>r.length===0?s:s.flatMap(i=>r.map(o=>[...i,...o])),[[]])}handleBack(){const t=p.BACK,e=this.hand.get(t,0);if(e<3)return[];const s=new w(t,0),r=Array(Math.floor(e/3)).fill(new z([s,s,s]));return r.length==0?[]:[r]}handleZ(){const t=[];for(const[e,s]of L({filterBy:[p.Z]})){if(this.hand.get(e,s)==0)continue;if(this.hand.get(e,s)!=3)return[];const r=new w(e,s);t.push(new z([r,r,r]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const s=new w(t,5),r=new w(t,5,[y.RED]),i=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],u={};for(let h=0;h<l.length;h++){const d=l[h],g=d.tiles.findIndex(E=>E.equals(s)&&!E.has(y.RED)),f=d.tiles.findIndex(E=>E.equals(r)&&E.has(y.RED));if(f>-1&&o.push([c,h,f]),f>-1&&g>-1||g<0)continue;const m=jt(d);u[m]||(u[m]=!0,i.push([c,h,g]))}}if(o.length==0)return e;const a=[];for(const[c,l,u]of i){const d=[...e[c]],g=d[l];d[l]=g.clone({replace:{idx:u,tile:r}});const f=o.find(E=>E[0]==c);if(f==null)continue;const m=d[f[1]];m==null&&console.error(f,i),d[f[1]]=m.clone({replace:{idx:f[2],tile:s}}),jt(g)!=jt(m)&&a.push(d)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const s=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const r=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let i=this.handleNumType(t,e);this.hand.inc(r),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new Q([r[0],r[1],r[2]])),s.push(o)}if(this.hand.get(t,e)==3){const r=this.hand.dec(new Array(3).fill(new w(t,e)));let i=this.handleNumType(t,e);this.hand.inc(r),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new z([r[0],r[1],r[2]])),s.push(o)}return s}}const xt=[1,2,3,4,5,6,7],G=[1,9],zt=n=>{var e;const t=n.boardContext;return{...n,hand:n.hand.map(T.deserialize),boardContext:{...t,doraMarkers:t.doraMarkers.map(w.from),blindDoraMarkers:(e=t.blindDoraMarkers)==null?void 0:e.map(w.from)}}};class Pe{constructor(t,e){_(this,"hand");_(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(s=>On(s)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(s=>On(s)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,roundUp8000:e.roundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);if(e.length==0)return!1;let s=[0,0],r=0;for(let f=0;f<e.length;f++){const m=e[f],E=m.points.reduce((N,O)=>N+O.double,0);E>s[0]?(r=f,s=[E,m.fu]):E==s[0]&&m.fu>s[1]&&(r=f,s=[E,m.fu])}const i=(f,m=100)=>Math.ceil(f/m)*m,o=s[1]!=25?i(s[1],10):25,a=s[0];let c=Math.min(o*2**(a+2),2e3);switch(a){case 26:c=16e3;break;case 13:c=8e3;break;case 12:case 11:c=6e3;break;case 10:case 9:case 8:c=4e3;break;case 7:case 6:c=3e3;break;case 5:c=2e3;break}a>=13&&a<26&&(c=8e3,this.cfg.disableCountable32000&&e[r].points.length>1&&(c=6e3)),this.cfg.roundUp8000&&(o==30&&a==4||o==60&&a==3)&&(c=2e3);const l=e[r].hand.some(f=>f.tiles.some(m=>m.has(y.TSUMO))),u=this.cfg.orig.myWind,h=u==A.E,d=$(0);if(l){const f=this.cfg.sticks.dead*100;if(h){const m=i(c*2);d[A.E]+=m*3+f*3,d[A.S]-=m+f,d[A.W]-=m+f,d[A.N]-=m+f}else for(const m of Object.values(A)){if(m==u)continue;const E=m==A.E?2:1,N=i(c*E)+f;d[m]-=N,d[u]+=N}}else{const f=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const E=i(c*(h?6:4))+f;d[u]+=E,d[this.cfg.orig.ronWind]-=E}return d[u]+=1e3*this.cfg.sticks.reach,{deltas:d,sum:a,fu:o,points:e[r].points,point:d[u],hand:e[r].hand,boardContext:this.cfg.orig}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const s of t){const r=[...this.dA13(s),...this.dB13(s),...this.dC13(s),...this.dD13(s),...this.dE13(s),...this.dF13(s),...this.dG13(s),...this.dH13(s),...this.dI13(s),...this.dJ13(s),...this.dK13(s)];r.length!=0&&e.push({points:r,fu:30,hand:s})}if(e.length>0)return e;for(const s of t){const r=this.calcFu(s),i=[...this.dA1(s),...this.dB1(s),...this.dC1(s),...this.dD1(s),...this.dE1(s),...this.dF1(s),...this.dG1(s),...this.dH1(s),...this.dI1(s),...this.dJ1(s),...this.dK1(s),...this.dA2(s),...this.dB2(s),...this.dC2(s),...this.dD2(s),...this.dE2(s),...this.dF2(s),...this.dG2(s),...this.dH2(s),...this.dI2(s),...this.dJ2(s),...this.dA3(s),...this.dB3(s),...this.dC3(s),...this.dA6(s)];i.length!=0&&(i.push(...this.dX1(s)),e.push({points:i,fu:r,hand:s}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",double:1}]:this.cfg.reached==2?[{name:"ダブル立直",double:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(s=>s.tiles.some(r=>r.has(y.TSUMO)))?[{name:"門前清自摸和",double:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",s=this.calcFu(t);return s==20?[{name:e,double:1}]:!t.some(r=>r.tiles.some(i=>i.has(y.TSUMO)))&&s==30?[{name:e,double:1}]:[]}dD1(t){return t.some(s=>s.tiles.some(r=>r.t==p.Z||G.includes(r.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:In(t)==1?[{name:"一盃口",double:1}]:[]}dF1(t){const e=[];return t.forEach(s=>{if(s instanceof H)return;const r=s.tiles[0];r.t==p.Z&&(r.equals(this.cfg.myWind)&&e.push({name:"自風",double:1}),r.equals(this.cfg.roundWind)?e.push({name:"場風",double:1}):r.n==5?e.push({name:"白",double:1}):r.n==6?e.push({name:"發",double:1}):r.n==7&&e.push({name:"中",double:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",double:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",double:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",double:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",double:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",double:1}]:[]}dX1(t){let e=0,s=0,r=0;for(const o of t)for(const a of o.tiles){for(const c of this.cfg.doras)a.equals(c)&&e++;for(const c of this.cfg.blindDoras)a.equals(c)&&s++;a.has(y.RED)&&r++}const i=[];return e>0&&i.push({name:"ドラ",double:e}),r>0&&i.push({name:"赤ドラ",double:r}),this.hand.reached&&s>0&&i.push({name:"裏ドラ",double:s}),i}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=s=>s instanceof Q||s instanceof Z;for(const s of t){if(!e(s))continue;const r=lt(s);if(r.t==p.Z)continue;const i=[p.M,p.P,p.S].filter(c=>c!=r.t),o=t.some(c=>{const l=new w(i[0],r.n);return e(c)&&l.equals(lt(c))}),a=t.some(c=>{const l=new w(i[1],r.n);return e(c)&&l.equals(lt(c))});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(s=>s instanceof R||s instanceof D||s instanceof Y||s instanceof z||s instanceof V||s instanceof H)?[{name:"対々和",double:2}]:[]}dD2(t){return t.filter(s=>(s instanceof R||s instanceof z)&&!s.tiles.some(r=>r.has(y.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(s=>s instanceof R||s instanceof D||s instanceof Y).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=s=>s instanceof R||s instanceof D||s instanceof Y||s instanceof z||s instanceof V;for(const s of t){if(!e(s))continue;const r=lt(s);if(r.t==p.Z)continue;const i=[p.M,p.P,p.S].filter(c=>c!=r.t),o=t.some(c=>{const l=new w(i[0],r.n);return e(c)&&l.equals(lt(c))}),a=t.some(c=>{const l=new w(i[1],r.n);return e(c)&&l.equals(lt(c))});if(o&&a)return[{name:"三色同刻",double:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(s=>{const r=s.tiles[0];return r.t==p.Z&&[5,6,7].includes(r.n)}).length==3?[{name:"小三元",double:2}]:[]}dH2(t){return t.every(s=>{const r=s.tiles[0].t==p.Z?xt:G;return s.tiles.every(i=>r.includes(i.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(s=>s instanceof Q||s instanceof Z)?t.some(s=>s.tiles[0].t==p.Z)?t.every(s=>{const r=s.tiles[0].t==p.Z?xt:G;return s.tiles.some(i=>r.includes(i.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[p.M]:[0,0,0],[p.S]:[0,0,0],[p.P]:[0,0,0]};for(const s of t){const r=lt(s);r.t!=p.BACK&&r.t!=p.Z&&(s instanceof Q||s instanceof Z)&&(r.n==1?e[r.t][0]++:r.n==4?e[r.t][1]++:r.n==7&&e[r.t][2]++)}for(const s of Object.values(e))if(s[0]>0&&s[1]>0&&s[2]>0)return[{name:"一気通貫",double:2-this.minus()}];return[]}dA3(t){if(!t.some(s=>s.tiles[0].t==p.Z))return[];for(const s of Object.values(p))if(t.every(i=>i.tiles[0].t==p.Z||i.tiles[0].t==s))return[{name:"混一色",double:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(s=>s instanceof Q||s instanceof Z)?t.some(s=>s.tiles[0].t==p.Z)?[]:t.every(s=>s.tiles.some(r=>G.includes(r.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:In(t)==2?[{name:"ニ盃口",double:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==p.Z))return[];for(const e of Object.values(p)){if(e==p.Z)continue;if(t.every(r=>r.tiles[0].t==e))return[{name:"清一色",double:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(s=>s instanceof H&&s.tiles.some(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"国士無双13面待ち",double:26}]:[{name:"国士無双",double:13}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",double:13}]:[]}dC13(t){return t.length==7?[]:t.every(r=>r instanceof R||r instanceof z&&!r.tiles.some(i=>i.has(y.RON))||r instanceof H)?t.some(r=>r instanceof H&&r.tiles.every(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"四暗刻単騎待ち",double:26}]:[{name:"四暗刻",double:13}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(r=>!(r instanceof H)&&r.tiles.some(i=>i.t==p.Z&&e.includes(i.n))).length==3?[{name:"大三元",double:13}]:[]}dE13(t){return t.every(s=>s.tiles[0].t==p.Z)?[{name:"字一色",double:13}]:[]}dF13(t){return t.every(s=>s.tiles.every(r=>r.t!=p.Z&&G.includes(r.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(s=>s instanceof R||s instanceof D||s instanceof Y).length==4?[{name:"四槓子",double:13}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(i=>i.tiles.some(o=>o.t==p.Z&&e.includes(o.n))).length==4?t.find(i=>i instanceof H).tiles.some(i=>i.t==p.Z&&e.includes(i.n))?[{name:"小四喜",double:13}]:[{name:"大四喜",double:13}]:[]}dI13(t){const e=s=>!!(s.equals(new w(p.Z,6))||s.t==p.S&&[2,3,4,6,8].includes(s.n));return t.every(s=>s.tiles.every(r=>e(r)))?[{name:"緑一色",double:13}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let s=20;const r=this.cfg.myWind.n,i=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(f=>f.tiles.some(m=>m.has(y.TSUMO)||m.has(y.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(y.TSUMO)),l=(f,m)=>{const E=f.tiles[0];return E.t==p.Z||G.includes(E.n)?m*2:m};for(const f of t)switch(!0){case f instanceof z:const m=f.tiles.some(E=>E.has(y.RON))?2:4;s+=l(f,m);break;case f instanceof V:s+=l(f,2);break;case(f instanceof Y||f instanceof D):s+=l(f,8);break;case f instanceof R:s+=l(f,16);break}s+=(f=>{if(f instanceof z)return 0;if(f instanceof H)return 2;const m=f.tiles,E=m.findIndex(N=>N.has(y.TSUMO)||N.has(y.RON));return E==1||E==0&&m[2].n==9||E==2&&m[0].n==1?2:0})(o);const d=t.find(f=>f instanceof H).tiles[0];d.t==p.Z&&([5,6,7].includes(d.n)&&(s+=2),(d.n==i||d.n==r)&&(s+=2));let g=!1;return!a&&s==20&&(g=!0),c&&!g&&(s+=2),!c&&!a&&(s+=10),!c&&!a&&s==30&&(g=!0),a&&s==20&&(s=30),s}}const jt=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),In=n=>{const t={};for(const s of n){if(!(s instanceof Q))continue;const r=jt(s);t[r]==null?t[r]=1:t[r]++}let e=0;for(const s in t)t[s]>=2&&e++;return e},lt=n=>[...n.tiles].sort(Xt)[0],On=n=>{const t=n.n,e=n.t;if(e==p.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class $t{static calcCandidates(t,e,s){S(e.length>0,"choices to discard is zero");const r=new Map;let i=1/0;for(const o of e){const a=t.dec([o]),c=$t.candidateTiles(t,s);t.inc(a);const l=s!=null&&s.arrangeRed&&o.has(y.RED)?o.clone({removeAll:!0}):o.has(y.RED)?o.clone({removeAll:!0,add:y.RED}):o.clone({removeAll:!0});c.shanten<i?(r.clear(),r.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),i=c.shanten):c.shanten==i&&r.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(r.values())}static candidateTiles(t,e){let s=1/0,r=[];const i=new Yt(t);for(const[o,a]of L({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),u=e!=null&&e.fourSetsOnePair?i.fourSetsOnePair():i.calc();t.dec(l),u<s?(s=u,r=[c]):u==s&&r.push(c)}return{shanten:s,candidates:r}}}const He=()=>{const n=new Set;return{on(t){n.add(t)},off(t){n.delete(t)},offAll(){n.clear()},emit(t){n.forEach(e=>e(t))}}};function rs(n){var i;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),r=os(e,t).map(o=>n[o]);return{events:r,type:as(t,(i=r[0])==null?void 0:i.choices)}}function is(n){var i;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),r=os(e,t).map(o=>n[o]);return{events:r,type:as(t,(i=r[0])==null?void 0:i.choices)}}function os(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let r=0;r<n.length;r++){const i=n[r];if(zi(i,t)){const o=ji(t,i);o<s?(s=o,e=[r]):o===s&&e.push(r)}}return e}function zi(n,t){return t.some(e=>!!n[e])}function ji(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function as(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const Ut=()=>{const n=He(),t=He(),e={emit:n.emit,on:r=>t.on(r)},s={emit:t.emit,on:r=>n.on(r)};return[e,s]},cs=()=>{const n=He();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Zt{constructor(t){_(this,"reachValue",1e3);_(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let s in e){const r=e[s],i=t[r];this.m[s]+=i}}}class Vt{constructor(t,e){_(this,"pToW",{});_(this,"wToP",$(""));_(this,"round");_(this,"sticks");this.round=(e==null?void 0:e.round)??k.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let s in this.pToW)this.wToP[this.pToW[s]]=s}update(){for(let t in this.pToW){const e=pe(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Gt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function sn(n){for(let t=n.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[n[t],n[e]]=[n[e],n[t]]}return n}class ls{constructor(t=!1){_(this,"c");_(this,"safeMap",$({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==p.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=p.BACK){if(this.get(e)<=0)throw new Error(`[counter] cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,e.has(y.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,s){return this.safeMap[s][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[p.M]:[1,4,4,4,4,4,4,4,4,4],[p.S]:[1,4,4,4,4,4,4,4,4,4],[p.P]:[1,4,4,4,4,4,4,4,4,4],[p.Z]:[0,4,4,4,4,4,4,4]}}}class rn{constructor(){_(this,"m",[])}discard(t,e){this.m.push({w:e,t})}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==t)}get lastTile(){const t=this.m.at(-1);return S(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let s=0;s<4;s++)if(!e.equals(t[s].t))return!1;return!0}}function Ui(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function Fi(){const n=Ui();if(n.__xstate__)return n.__xstate__}const Gi=n=>{if(typeof window>"u")return;const t=Fi();t&&t.register(n)};class kn{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const us=".",Zi="",hs="",Vi="#",Ji="*",ds="xstate.init",We="xstate.stop";function Xi(n,t){return{type:`xstate.after.${n}.${t}`}}function Be(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Yi(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function qi(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function fs(n){return{type:ds,input:n}}function X(n){setTimeout(()=>{throw n})}const Qi=typeof Symbol=="function"&&Symbol.observable||"@@observable";function ps(n,t){const e=Cn(n),s=Cn(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(r=>r in s?ps(e[r],s[r]):!1)}function on(n){if(ys(n))return n;const t=[];let e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function Cn(n){if($o(n))return n.value;if(typeof n!="string")return n;const t=on(n);return to(t)}function to(n){if(n.length===1)return n[0];const t={};let e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{const r=e;e={},r[n[s]]=e}return t}function Rn(n,t){const e={},s=Object.keys(n);for(let r=0;r<s.length;r++){const i=s[r];e[i]=t(n[i],i,n,r)}return e}function gs(n){return ys(n)?n:[n]}function et(n){return n===void 0?[]:gs(n)}function De(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function ys(n){return Array.isArray(n)}function eo(n){return n.type.startsWith("xstate.error.actor")}function vt(n){return gs(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ms(n){if(!(n===void 0||n===Zi))return et(n)}function Ke(n,t,e){var i,o,a;const s=typeof n=="object",r=s?n:void 0;return{next:(i=s?n.next:n)==null?void 0:i.bind(r),error:(o=s?n.error:t)==null?void 0:o.bind(r),complete:(a=s?n.complete:e)==null?void 0:a.bind(r)}}function Mn(n,t){return`${t}.${n}`}function an(n,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];const[,s,r]=e,o=n.getStateNodeById(r).config.invoke;return(Array.isArray(o)?o[s]:o).src}function xn(n,t){return`${n.sessionId}.${t}`}let no=0;function so(n,t){const e=new Map,s=new Map,r=new WeakMap,i=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,g,f,m,E=Math.random().toString(36).slice(2))=>{const N={source:d,target:g,event:f,delay:m,id:E,startedAt:Date.now()},O=xn(d,E);h._snapshot._scheduledEvents[O]=N;const M=a.setTimeout(()=>{delete o[O],delete h._snapshot._scheduledEvents[O],h._relay(d,g,f)},m);o[O]=M},cancel:(d,g)=>{const f=xn(d,g),m=o[f];delete o[f],delete h._snapshot._scheduledEvents[f],m!==void 0&&a.clearTimeout(m)},cancelAll:d=>{for(const g in h._snapshot._scheduledEvents){const f=h._snapshot._scheduledEvents[g];f.source===d&&l.cancel(d,f.id)}}},u=d=>{if(!i.size)return;const g={...d,rootId:n.sessionId};i.forEach(f=>{var m;return(m=f.next)==null?void 0:m.call(f,g)})},h={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${no++}`,_register:(d,g)=>(e.set(d,g),d),_unregister:d=>{e.delete(d.sessionId);const g=r.get(d);g!==void 0&&(s.delete(g),r.delete(d))},get:d=>s.get(d),_set:(d,g)=>{const f=s.get(d);if(f&&f!==g)throw new Error(`Actor with system ID '${d}' already exists.`);s.set(d,g),r.set(g,d)},inspect:d=>{const g=Ke(d);return i.add(g),{unsubscribe(){i.delete(g)}}},_sendInspectionEvent:u,_relay:(d,g,f)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:g,event:f}),g._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const d=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const g in d){const{source:f,target:m,event:E,delay:N,id:O}=d[g];l.schedule(f,m,E,N,O)}},_clock:a,_logger:c};return h}let Se=!1;const cn=1;let P=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const ro={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class io{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new kn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=P.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...ro,...e},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:u}=s;this.system=o?o.system:so(this,{clock:r,logger:i}),u&&!o&&this.system.inspect(Ke(u)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:h=>{this._deferred.push(h)},system:this.system,stopChild:h=>{if(h._parent!==this)throw new Error(`Cannot stop child actor ${h.id} of ${this.id} because it is not a child`);h._stop()},emit:h=>{const d=this.eventListeners.get(h.type),g=this.eventListeners.get("*");if(!d&&!g)return;const f=[...d?d.values():[],...g?g.values():[]];for(const m of f)m(h)},actionExecutor:h=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:h.type,params:h.params}}),!h.exec)return;const g=Se;try{Se=!0,h.exec(h.info,h.params)}finally{Se=g}};this._processingStatus===P.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var r,i;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){X(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){X(a)}this._stopProcedure(),this._complete(),this._doneEvent=Yi(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){var i;const r=Ke(t,e,s);if(this._processingStatus!==P.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){X(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)X(o);else try{r.error(o)}catch(a){X(a)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const r=e.bind(void 0);return s.add(r),{unsubscribe:()=>{s.delete(r)}}}start(){if(this._processingStatus===P.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=P.Running;const t=fs(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(r){s={err:r}}if(s){const{err:r}=s;this._snapshot={...this._snapshot,status:"error",error:r},this._error(r);return}this.update(e,t),t.type===We&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===P.Stopped?this:(this.mailbox.clear(),this._processingStatus===P.NotStarted?(this._processingStatus=P.Stopped,this):(this.mailbox.enqueue({type:We}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){X(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||X(t);return}let e=!1;for(const s of this.observers){const r=s.error;e||(e=!r);try{r==null||r(t)}catch(i){X(i)}}this.observers.clear(),e&&X(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,qi(this.id,t))}_stopProcedure(){return this._processingStatus!==P.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new kn(this._process.bind(this)),this._processingStatus=P.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==P.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:Gi)(this)}toJSON(){return{xstate$$type:cn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Qi](){return this}getSnapshot(){return this._snapshot}}function Pt(n,...[t]){return new io(n,t)}function oo(n,t,e,s,{sendId:r}){const i=typeof r=="function"?r(e,s):r;return[t,{sendId:i},void 0]}function ao(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function co(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=oo,t.execute=ao,t}function lo(n,t,e,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?an(t.machine,o):o,u=typeof r=="function"?r(e):r;let h,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,h=Pt(l,{id:u,src:o,parent:n.self,syncSnapshot:c,systemId:i,input:d})),[wt(t,{children:{...t.children,[u]:h}}),{id:r,systemId:i,actorRef:h,src:o,input:d},void 0]}function uo(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==P.Stopped&&t.start()})}function ho(...[n,{id:t,systemId:e,input:s,syncSnapshot:r=!1}={}]){function i(o,a){}return i.type="xstate.spawnChild",i.id=t,i.systemId=e,i.src=n,i.input=s,i.syncSnapshot=r,i.resolve=lo,i.execute=uo,i}function fo(n,t,e,s,{actorRef:r}){const i=typeof r=="function"?r(e,s):r,o=typeof i=="string"?t.children[i]:i;let a=t.children;return o&&(a={...a},delete a[o.id]),[wt(t,{children:a}),o,void 0]}function po(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==P.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function ws(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=fo,t.execute=po,t}function ln(n,t,e,s){const{machine:r}=s,i=typeof n=="function",o=i?n:r.implementations.guards[typeof n=="string"?n:n.type];if(!i&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return ln(o,t,e,s);const a={context:t,event:e},c=i||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const un=n=>n.type==="atomic"||n.type==="final";function Ht(n){return Object.values(n.states).filter(t=>t.type!=="history")}function qt(n,t){const e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function ue(n){const t=new Set(n),e=_s(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))$n(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of Ht(s))if(r.type!=="history"&&!t.has(r)){const i=$n(r);for(const o of i)t.add(o)}}for(const s of t){let r=s.parent;for(;r;)t.add(r),r=r.parent}return t}function bs(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const r=e[0];if(r){if(un(r))return r.key}else return{}}const s={};for(const r of e)s[r.key]=bs(r,t);return s}function _s(n){const t=new Map;for(const e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function Es(n,t){const e=ue(t);return bs(n,_s(e))}function hn(n,t){return t.type==="compound"?Ht(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Ht(t).every(e=>hn(n,e)):t.type==="final"}const we=n=>n[0]===Vi;function go(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>{if(s===Ji)return!0;if(!s.endsWith(".*"))return!1;const r=s.split("."),i=t.split(".");for(let o=0;o<r.length;o++){const a=r[o],c=i[o];if(a==="*")return o===r.length-1;if(a!==c)return!1}return!0}).sort((s,r)=>r.length-s.length).flatMap(s=>n.transitions.get(s))}function yo(n){const t=n.config.after;if(!t)return[];const e=r=>{const i=Xi(r,n.id),o=i.type;return n.entry.push(jo(i,{id:o,delay:r})),n.exit.push(co(o)),o};return Object.keys(t).flatMap(r=>{const i=t[r],o=typeof i=="string"?{target:i}:i,a=Number.isNaN(+r)?r:+r,c=e(a);return et(o).map(l=>({...l,event:c,delay:a}))}).map(r=>{const{delay:i}=r;return{...dt(n,r.event,r),delay:i}})}function dt(n,t,e){const s=ms(e.target),r=e.reenter??!1,i=bo(n,s),o={...e,actions:et(e.actions),guard:e.guard,target:i,source:n,reenter:r,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function mo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===hs)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,vt(s).map(r=>dt(n,e,r)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,vt(n.config.onDone).map(s=>dt(n,e,s)))}for(const e of n.invoke){if(e.onDone){const s=`xstate.done.actor.${e.id}`;t.set(s,vt(e.onDone).map(r=>dt(n,s,r)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,vt(e.onError).map(r=>dt(n,s,r)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,vt(e.onSnapshot).map(r=>dt(n,s,r)))}}for(const e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function wo(n,t){const e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);const s={source:n,actions:!t||typeof t=="string"?[]:et(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function bo(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(we(e))return n.machine.getStateNodeById(e);const s=e[0]===us;if(s&&!n.parent)return he(n,e.slice(1));const r=s?n.key+e:e;if(n.parent)try{return he(n.parent,r)}catch(i){throw new Error(`Invalid transition definition for state node '${n.id}':
14
- ${i.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function As(n){const t=ms(n.config.target);return t?{target:t.map(e=>typeof e=="string"?he(n.parent,e):e)}:n.parent.initial}function pt(n){return n.type==="history"}function $n(n){const t=Ns(n);for(const e of t)for(const s of qt(e,n))t.add(s);return t}function Ns(n){const t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(const r of Ht(s))e(r)}}return e(n),t}function Wt(n,t){if(we(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);const e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function he(n,t){if(typeof t=="string"&&we(t))try{return n.machine.getStateNodeById(t)}catch{}const e=on(t).slice();let s=n;for(;e.length;){const r=e.shift();if(!r.length)break;s=Wt(s,r)}return s}function de(n,t){if(typeof t=="string"){const r=n.states[t];if(!r)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,r]}const e=Object.keys(t),s=e.map(r=>Wt(n,r)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((r,i)=>{const o=Wt(n,i);if(!o)return r;const a=de(o,t[i]);return r.concat(a)},[]))}function _o(n,t,e,s){const i=Wt(n,t).next(e,s);return!i||!i.length?n.next(e,s):i}function Eo(n,t,e,s){const r=Object.keys(t),i=Wt(n,r[0]),o=dn(i,t[r[0]],e,s);return!o||!o.length?n.next(e,s):o}function Ao(n,t,e,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=Wt(n,i),c=dn(a,o,e,s);c&&r.push(...c)}return r.length?r:n.next(e,s)}function dn(n,t,e,s){return typeof t=="string"?_o(n,t,e,s):Object.keys(t).length===1?Eo(n,t,e,s):Ao(n,t,e,s)}function No(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function rt(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function So(n,t){const e=new Set(n),s=new Set(t);for(const r of e)if(s.has(r))return!0;for(const r of s)if(e.has(r))return!0;return!1}function Ss(n,t,e){const s=new Set;for(const r of n){let i=!1;const o=new Set;for(const a of s)if(So(Le([r],t,e),Le([a],t,e)))if(rt(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)s.delete(a);s.add(r)}}return Array.from(s)}function vo(n){const[t,...e]=n;for(const s of qt(t,void 0))if(e.every(r=>rt(r,s)))return s}function fn(n,t){if(!n.target)return[];const e=new Set;for(const s of n.target)if(pt(s))if(t[s.id])for(const r of t[s.id])e.add(r);else for(const r of fn(As(s),t))e.add(r);else e.add(s);return[...e]}function vs(n,t){const e=fn(n,t);if(!e)return;if(!n.reenter&&e.every(r=>r===n.source||rt(r,n.source)))return n.source;const s=vo(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function Le(n,t,e){var r;const s=new Set;for(const i of n)if((r=i.target)!=null&&r.length){const o=vs(i,e);i.reenter&&i.source===o&&s.add(o);for(const a of t)rt(a,o)&&s.add(a)}return[...s]}function To(n,t){if(n.length!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function ze(n,t,e,s,r,i){if(!n.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Ss(n,o,a);let l=t;r||([l,a]=Co(l,s,e,c,o,a,i,e.actionExecutor)),l=Bt(l,s,e,c.flatMap(h=>h.actions),i,void 0),l=Oo(l,s,e,c,o,i,a,r);const u=[...o];l.status==="done"&&(l=Bt(l,s,e,u.sort((h,d)=>d.order-h.order).flatMap(h=>h.exit),i,void 0));try{return a===t.historyValue&&To(t._nodes,o)?l:wt(l,{_nodes:u,historyValue:a})}catch(h){throw h}}function Io(n,t,e,s,r){if(s.output===void 0)return;const i=Be(r.id,r.output!==void 0&&r.parent?De(r.output,n.context,t,e.self):void 0);return De(s.output,n.context,i,e.self)}function Oo(n,t,e,s,r,i,o,a){let c=n;const l=new Set,u=new Set;ko(s,o,u,l),a&&u.add(n.machine.root);const h=new Set;for(const d of[...l].sort((g,f)=>g.order-f.order)){r.add(d);const g=[];g.push(...d.entry);for(const f of d.invoke)g.push(ho(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(u.has(d)){const f=d.initial.actions;g.push(...f)}if(c=Bt(c,t,e,g,i,d.invoke.map(f=>f.id)),d.type==="final"){const f=d.parent;let m=(f==null?void 0:f.type)==="parallel"?f:f==null?void 0:f.parent,E=m||d;for((f==null?void 0:f.type)==="compound"&&i.push(Be(f.id,d.output!==void 0?De(d.output,c.context,t,e.self):void 0));(m==null?void 0:m.type)==="parallel"&&!h.has(m)&&hn(r,m);)h.add(m),i.push(Be(m.id)),E=m,m=m.parent;if(m)continue;c=wt(c,{status:"done",output:Io(c,t,e,c.machine.root,E)})}}return c}function ko(n,t,e,s){for(const r of n){const i=vs(r,t);for(const a of r.target||[])!pt(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),e.add(a)),It(a,t,e,s);const o=fn(r,t);for(const a of o){const c=qt(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Ts(s,t,e,c,!r.source.parent&&r.reenter?void 0:i)}}}function It(n,t,e,s){var r;if(pt(n))if(t[n.id]){const i=t[n.id];for(const o of i)s.add(o),It(o,t,e,s);for(const o of i)ve(o,n.parent,s,t,e)}else{const i=As(n);for(const o of i.target)s.add(o),i===((r=n.parent)==null?void 0:r.initial)&&e.add(n.parent),It(o,t,e,s);for(const o of i.target)ve(o,n.parent,s,t,e)}else if(n.type==="compound"){const[i]=n.initial.target;pt(i)||(s.add(i),e.add(i)),It(i,t,e,s),ve(i,n,s,t,e)}else if(n.type==="parallel")for(const i of Ht(n).filter(o=>!pt(o)))[...s].some(o=>rt(o,i))||(pt(i)||(s.add(i),e.add(i)),It(i,t,e,s))}function Ts(n,t,e,s,r){for(const i of s)if((!r||rt(i,r))&&n.add(i),i.type==="parallel")for(const o of Ht(i).filter(a=>!pt(a)))[...n].some(a=>rt(a,o))||(n.add(o),It(o,t,e,n))}function ve(n,t,e,s,r){Ts(e,s,r,qt(n,t))}function Co(n,t,e,s,r,i,o,a){let c=n;const l=Le(s,r,i);l.sort((h,d)=>d.order-h.order);let u;for(const h of l)for(const d of No(h)){let g;d.history==="deep"?g=f=>un(f)&&rt(f,h):g=f=>f.parent===h,u??(u={...i}),u[d.id]=Array.from(r).filter(g)}for(const h of l)c=Bt(c,t,e,[...h.exit,...h.invoke.map(d=>ws(d.id))],o,void 0),r.delete(h);return[c,u||i]}function Ro(n,t){return n.implementations.actions[t]}function Is(n,t,e,s,r,i){const{machine:o}=n;let a=n;for(const c of s){const l=typeof c=="function",u=l?c:Ro(o,typeof c=="string"?c:c.type),h={context:a.context,event:t,self:e.self,system:e.system},d=l||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!u||!("resolve"in u)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:h,params:d,exec:u});continue}const g=u,[f,m,E]=g.resolve(e,a,h,d,u,r);a=f,"retryResolve"in g&&(i==null||i.push([g,m])),"execute"in g&&e.actionExecutor({type:g.type,info:h,params:m,exec:g.execute.bind(null,e,m)}),E&&(a=Is(a,t,e,E,r,i))}return a}function Bt(n,t,e,s,r,i){const o=i?[]:void 0,a=Is(n,t,e,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Te(n,t,e,s){let r=n;const i=[];function o(l,u,h){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:u,snapshot:l,_transitions:h}),i.push(l)}if(t.type===We)return r=wt(Pn(r,t,e),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==ds){const l=a,u=eo(l),h=Hn(l,r);if(u&&!h.length)return r=wt(n,{status:"error",error:l.error}),o(r,l,[]),{snapshot:r,microstates:i};r=ze(h,n,e,a,!1,s),o(r,l,h)}let c=!0;for(;r.status==="active";){let l=c?Mo(r,a):[];const u=l.length?r:void 0;if(!l.length){if(!s.length)break;a=s.shift(),l=Hn(a,r)}r=ze(l,r,e,a,!1,s),c=r!==u,o(r,a,l)}return r.status!=="active"&&Pn(r,a,e),{snapshot:r,microstates:i}}function Pn(n,t,e){return Bt(n,t,e,Object.values(n.children).map(s=>ws(s)),[],void 0)}function Hn(n,t){return t.machine.getTransitionData(t,n)}function Mo(n,t){const e=new Set,s=n._nodes.filter(un);for(const r of s)t:for(const i of[r].concat(qt(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||ln(o.guard,n.context,t,n)){e.add(o);break t}}return Ss(Array.from(e),new Set(n._nodes),n.historyValue)}function xo(n,t){const e=ue(de(n,t));return Es(n,[...e])}function $o(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}const Po=function(t){return ps(t,this.value)},Ho=function(t){return this.tags.has(t)},Wo=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},Bo=function(){const{_nodes:t,tags:e,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Do=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function ie(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:Es(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:Po,hasTag:Ho,can:Wo,getMeta:Do,toJSON:Bo}}function wt(n,t={}){return ie({...n,...t},n.machine)}function Ko(n,t){const{_nodes:e,tags:s,machine:r,children:i,context:o,can:a,hasTag:c,matches:l,getMeta:u,toJSON:h,...d}=n,g={};for(const m in i){const E=i[m];g[m]={snapshot:E.getPersistedSnapshot(t),src:E.src,systemId:E._systemId,syncSnapshot:E._syncSnapshot}}return{...d,context:Os(o),children:g}}function Os(n){let t;for(const e in n){const s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(n)?n.slice():{...n}),t[e]={xstate$$type:cn,id:s.id};else{const r=Os(s);r!==s&&(t??(t=Array.isArray(n)?n.slice():{...n}),t[e]=r)}}return t??n}function Lo(n,t,e,s,{event:r,id:i,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);const l=typeof r=="function"?r(e,s):r;let u;if(typeof o=="string"){const h=c&&c[o];u=typeof h=="function"?h(e,s):h}else u=typeof o=="function"?o(e,s):o;return typeof u!="number"&&a.push(l),[t,{event:l,id:i,delay:u},void 0]}function zo(n,t){const{event:e,delay:s,id:r}=t;if(typeof s=="number"){n.defer(()=>{const i=n.self;n.system.scheduler.schedule(i,i,e,s,r)});return}}function jo(n,t){function e(s,r){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=Lo,e.execute=zo,e}function Uo(n,{machine:t,context:e},s,r){const i=(o,a)=>{if(typeof o=="string"){const c=an(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Pt(c,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return r[l.id]=l,l}else return Pt(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{const c=i(o,a);return r[c.id]=c,n.defer(()=>{c._processingStatus!==P.Stopped&&c.start()}),c}}function Fo(n,t,e,s,{assignment:r}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:t.context,event:e.event,spawn:Uo(n,t,e.event,i),self:n.self,system:n.system};let a={};if(typeof r=="function")a=r(o,s);else for(const l of Object.keys(r)){const u=r[l];a[l]=typeof u=="function"?u(o,s):u}const c=Object.assign({},t.context,a);return[wt(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children}),void 0,void 0]}function Go(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=Fo,t}const Wn=new WeakMap;function St(n,t,e){let s=Wn.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},Wn.set(n,s)),s[t]}const Zo={},Lt=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n;class pn{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(us),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Rn(this.config.states,(s,r)=>new pn(s,{_parent:this,_key:r,_machine:this.machine})):Zo,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=et(this.config.entry).slice(),this.exit=et(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=et(t.tags).slice()}_initialize(){this.transitions=mo(this),this.config.always&&(this.always=vt(this.config.always).map(t=>dt(this,hs,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Lt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Lt),eventType:null})}:void 0,history:this.history,states:Rn(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Lt)})),entry:this.entry.map(Lt),exit:this.exit.map(Lt),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return St(this,"invoke",()=>et(this.config.invoke).map((t,e)=>{const{src:s,systemId:r}=t,i=t.id??Mn(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${Mn(this.id,e)}`;return{...t,src:o,id:i,systemId:r,toJSON(){const{onDone:a,onError:c,...l}=t;return{...l,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return St(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(r=>[e,r])).reduce((e,[s,r])=>(e[s]=e[s]||[],e[s].push(r),e),{}))}get after(){return St(this,"delayedTransitions",()=>yo(this))}get initial(){return St(this,"initial",()=>wo(this,this.config.initial))}next(t,e){const s=e.type,r=[];let i;const o=St(this,`candidates-${s}`,()=>go(this,s));for(const a of o){const{guard:c}=a,l=t.context;let u=!1;try{u=!c||ln(c,l,e,t)}catch(h){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
15
- ${h.message}`)}if(u){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return St(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const r=t[s];if(r.states)for(const i of r.events)e.add(`${i}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(e=>this.transitions.get(e).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(t)}}const Vo="#";class gn{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new pn(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:r,delays:i}=this.implementations;return new gn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const e=xo(this.root,t.value),s=ue(de(this.root,e));return ie({_nodes:[...s],context:t.context||{},children:{},status:hn(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Te(t,e,s,[]).snapshot}microstep(t,e,s){return Te(t,e,s,[]).microstates}getTransitionData(t,e){return dn(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:r}=this.config,i=ie({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?Bt(i,e,t,[Go(({spawn:a,event:c,self:l})=>r({spawn:a,input:c.input,self:l}))],s,void 0):i}getInitialSnapshot(t,e){const s=fs(e),r=[],i=this.getPreInitialState(t,s,r),o=ze([{target:[...Ns(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Te(o,s,t,r);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=on(t),s=e.slice(1),r=we(e[0])?e[0].slice(Vo.length):e[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return he(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return Ko(t,e)}restoreSnapshot(t,e){const s={},r=t.children;Object.keys(r).forEach(c=>{const l=r[c],u=l.snapshot,h=l.src,d=typeof h=="string"?an(this,h):h;if(!d)return;const g=Pt(d,{id:c,parent:e.self,syncSnapshot:l.syncSnapshot,snapshot:u,src:h,systemId:l.systemId});s[c]=g});const i=ie({...t,children:s,_nodes:Array.from(ue(de(this.root,t.value)))},this),o=new Set;function a(c,l){if(!o.has(c)){o.add(c);for(const u in c){const h=c[u];if(h&&typeof h=="object"){if("xstate$$type"in h&&h.xstate$$type===cn){c[u]=l[h.id];continue}a(h,l)}}}}return a(i.context,s),i}}function Jo(n,t){return new gn(n,t)}const ne=n=>n===!1?!1:n.map(t=>t.serialize()),Xo=n=>n===!1?!1:n.serialize(),Yo=n=>n===!1?!1:n.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),je=n=>JSON.parse(JSON.stringify(n)),se=n=>n===!1?!1:je(n),Ue=n=>Jo({id:"Untitled",initial:"distribute",context:{currentWind:A.E,oneShotMap:$(!1),missingMap:$(!1),controller:n,genEventID:ks()},states:{distribute:{on:{NEXT:{target:"drawn"}},entry:{type:"notify_distribution"}},drawn:{entry:{type:"notify_draw"},on:{NEXT:{target:"waiting_user_event_after_drawn",actions:{type:"notify_choice_after_drawn"},description:`可能なアクションとその詳細を通知\\
12
+ `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}ct.prototype.build=function(n){return this.options.preserveOrder?Jr(n,this.options):(Array.isArray(n)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(n={[this.options.arrayNodeName]:n}),this.j2x(n,0,[]).val)};ct.prototype.j2x=function(n,t,e){let s="",r="";const i=e.join(".");for(let o in n)if(Object.prototype.hasOwnProperty.call(n,o))if(typeof n[o]>"u")this.isAttribute(o)&&(r+="");else if(n[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?r+="":o[0]==="?"?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(n[o]instanceof Date)r+=this.buildTextValNode(n[o],o,"",t);else if(typeof n[o]!="object"){const a=this.isAttribute(o);if(a&&!this.ignoreAttributesFn(a,i))s+=this.buildAttrPairStr(a,""+n[o]);else if(!a)if(o===this.options.textNodeName){let c=this.options.tagValueProcessor(o,""+n[o]);r+=this.replaceEntitiesValue(c)}else r+=this.buildTextValNode(n[o],o,"",t)}else if(Array.isArray(n[o])){const a=n[o].length;let c="",l="";for(let h=0;h<a;h++){const u=n[o][h];if(!(typeof u>"u"))if(u===null)o[0]==="?"?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof u=="object")if(this.options.oneListGroup){const d=this.j2x(u,t+1,e.concat(o));c+=d.val,this.options.attributesGroupName&&u.hasOwnProperty(this.options.attributesGroupName)&&(l+=d.attrStr)}else c+=this.processTextOrObjNode(u,o,t,e);else if(this.options.oneListGroup){let d=this.options.tagValueProcessor(o,u);d=this.replaceEntitiesValue(d),c+=d}else c+=this.buildTextValNode(u,o,"",t)}this.options.oneListGroup&&(c=this.buildObjectNode(c,o,l,t)),r+=c}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const a=Object.keys(n[o]),c=a.length;for(let l=0;l<c;l++)s+=this.buildAttrPairStr(a[l],""+n[o][a[l]])}else r+=this.processTextOrObjNode(n[o],o,t,e);return{attrStr:s,val:r}};ct.prototype.buildAttrPairStr=function(n,t){return t=this.options.attributeValueProcessor(n,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+n:" "+n+'="'+t+'"'};function Qr(n,t,e,s){const r=this.j2x(n,e+1,s.concat(t));return n[this.options.textNodeName]!==void 0&&Object.keys(n).length===1?this.buildTextValNode(n[this.options.textNodeName],t,r.attrStr,e):this.buildObjectNode(r.val,t,r.attrStr,e)}ct.prototype.buildObjectNode=function(n,t,e,s){if(n==="")return t[0]==="?"?this.indentate(s)+"<"+t+e+"?"+this.tagEndChar:this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar;{let r="</"+t+this.tagEndChar,i="";return t[0]==="?"&&(i="?",r=""),(e||e==="")&&n.indexOf("<")===-1?this.indentate(s)+"<"+t+e+i+">"+n+r:this.options.commentPropName!==!1&&t===this.options.commentPropName&&i.length===0?this.indentate(s)+`<!--${n}-->`+this.newLine:this.indentate(s)+"<"+t+e+i+this.tagEndChar+n+this.indentate(s)+r}};ct.prototype.closeTag=function(n){let t="";return this.options.unpairedTags.indexOf(n)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${n}`,t};ct.prototype.buildTextValNode=function(n,t,e,s){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${n}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(s)+`<!--${n}-->`+this.newLine;if(t[0]==="?")return this.indentate(s)+"<"+t+e+"?"+this.tagEndChar;{let r=this.options.tagValueProcessor(t,n);return r=this.replaceEntitiesValue(r),r===""?this.indentate(s)+"<"+t+e+this.closeTag(t)+this.tagEndChar:this.indentate(s)+"<"+t+e+">"+r+"</"+t+this.tagEndChar}};ct.prototype.replaceEntitiesValue=function(n){if(n&&n.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const e=this.options.entities[t];n=n.replace(e.regex,e.val)}return n};function ti(n){return this.options.indentBy.repeat(n)}function ei(n){return n.startsWith(this.options.attributeNamePrefix)&&n!==this.options.textNodeName?n.substr(this.attrPrefixLen):!1}class lt{constructor(t){E(this,"type");E(this,"attrs",{});E(this,"styles",{});E(this,"deleteMarker",!1);this.type=t}dx(t){return this.attrs.x==null?this.attrs.x=t:this.attrs.x+=t,this}dy(t){return this.attrs.y==null?this.attrs.y=t:this.attrs.y+=t,this}x(t){return this.attrs.x=t,this}y(t){return this.attrs.y=t,this}size(t,e){return this.attrs.width=t,this.attrs.height=e,this}remove(){this.deleteMarker=!0}left(...t){return`<${[this.type,Yn(this.attrs),di(this.styles),...t].filter(e=>e!="").join(" ")}>`}right(){return`</${this.type}>`}center(){return""}toString(){return this.deleteMarker?"":`${this.left()}${this.center()}${this.right()}`}attr(t){if(typeof t=="string")return this.attrs[t]??"";for(const[e,s]of Object.entries(t))this.attrs[e]=s;return this}css(t){return this.styles={...this.styles,...t},this}svg(){return this.toString()}}class tn extends lt{constructor(e){super("image");E(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class we extends lt{constructor(e){super("use");E(this,"attrs",{});this.attrs={...this.attrs,href:this.make(e)}}use(e){return this.attrs.href=`#${e}`,this}make(e){return e==null?e:`#${e}`}}class en extends lt{constructor(){super("rect");E(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class Et extends lt{constructor(e=""){super("text");E(this,"attrs");E(this,"_text","");this._text=e,this.attrs={}}plain(e){return this._text=e,this}font(e){return this.attrs.fontFamily=e.family,this.attrs.fontSize=e.size,this}center(){return this._text}}let nn=class extends lt{constructor(e){super("symbol");E(this,"raw");this.raw=e}id(){return this.attr("id")}center(){return this.raw}};class T extends lt{constructor(){super("g");E(this,"children",[]);E(this,"rotateMatrix");E(this,"translateMatrix")}add(e){return this.children.push(e),this}rotate(e,s,r){return this.rotateMatrix=qs(e,s,r),this}translate(e,s){return this.translateMatrix=xe(e,s),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){const s=[this.translateMatrix,this.rotateMatrix].filter(r=>r!=null);return s.length==0?super.left():super.left(ui(Zs(s)))}each(e,s){for(let r=0;r<this.children.length;r++){const i=this.children[r];i instanceof T&&s&&i.each(e,!0),e(r,this.children)}}}const ni=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class Vn extends lt{constructor(){super("svg");E(this,"children",[]);E(this,"viewBox")}add(e){return this.children.push(e),this}center(){return this.children.map(e=>e.toString()).join("")}left(...e){return`<${[this.type,...ni,Yn(this.attrs),hi(this.viewBox)].filter(s=>s!="").join(" ")}>`}viewbox(e,s,r,i){return this.viewBox={x:e,y:s,width:r,height:i},this}importSymbol(e){for(const s of fi(e))this.add(s);return this}x(e){throw new Error("unimplemented")}y(e){throw new Error("unimplemented")}dx(e){throw new Error("unimplemented")}dy(e){throw new Error("unimplemented")}each(e,s){for(let r=0;r<this.children.length;r++){const i=this.children[r];i instanceof T&&s&&i.each(e,!0),e(r,this.children)}}}function Jn(){return new Vn}const si=Jn,ri=T,ii=tn,oi=we,ai=en,ci=Et;function li(n){return n.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function hi(n){return n==null?"":`viewBox="${n.x} ${n.y} ${n.width} ${n.height}"`}function ui(n){return n==null?"":`transform="${Qs(n)}"`}function Yn(n){return Object.entries(n).filter(([t,e])=>e!==void 0).map(([t,e])=>`${li(t)}="${e}"`).join(" ")}function di(n){const t=Object.entries(n).map(([e,s])=>`${e}: ${s};`).join(" ");return t!=""?`style="${t}"`:""}function*fi(n){const t=new Zr({ignoreAttributes:!1}),e=new ct({ignoreAttributes:!1}),s=t.parse(n);for(const r of s.svg.symbol){const i=e.build(r),o=new nn(i);for(const[a,c]of Object.entries(r))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const G=(n,t)=>{const e=D(n.tiles[0],t),s=e.baseHeight,r=e.baseWidth;if(n.is(_.SHO_KAN))return{width:r*2+s,height:Math.max(r*2,s)};const i=n.tiles.reduce((a,c)=>{const l=D(c,t).height;return l>a?l:a},0);return{width:n.tiles.reduce((a,c)=>a+D(c,t).width,0),height:i}},D=(n,t)=>{const e=parseFloat((it.HEIGHT*t).toPrecision(5)),s=parseFloat((it.WIDTH*t).toPrecision(5)),r=n.has(y.HORIZONTAL)?{width:e,height:s,baseWidth:s,baseHeight:e}:{width:s,height:e,w:s,baseWidth:s,baseHeight:e};return(n.has(y.TSUMO)||n.has(y.DORA))&&(r.width+=s*it.TEXT_SCALE),r};class xt{constructor(t={}){E(this,"tileWidth");E(this,"tileHeight");E(this,"imageHostUrl");E(this,"imageExt");E(this,"scale");E(this,"svgSprite");this.scale=t.scale??1,this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=it.WIDTH*this.scale,this.tileHeight=it.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=D(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new tn().load(this.buildURL(t));return this.svgSprite&&(e=new we().use(xt.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,s){const r=D(t,this.scale);return this.image(t).dx(e).dy(s).size(r.baseWidth,r.baseHeight)}createTextImage(t,e,s,r){const i=this.createImage(t,e,s),o=D(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,l=o.baseHeight,h=new Et().plain(r);h.size(o.baseWidth,o.baseHeight).font({family:Ge,size:a}).dx(c).dy(l);const u=new T;return u.add(i).add(h).translate(e,s),u}createRotate90Image(t,e,s,r=!1){const i=this.createImage(t,0,0),o=D(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,l=e+this.getDiffTileHeightWidth(t),h=r?s-this.getDiffTileHeightWidth(t):s,u=new T;return u.add(i).translate(l,h).rotate(90,a,c),u}createStick(t){return this.image(t)}static buildID(t){if(t==100||t==1e3)return t==100?"stick100":"stick1000";const e=t.t==p.BACK||t.has(y.RED)?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${xt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class sn extends xt{constructor(){super(...arguments);E(this,"blockMargin",it.WIDTH*it.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const s=e instanceof M?e.tilesWithBack:e.tiles,r=new T;let i=0;for(const o of s){const a=D(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),l=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,h=c(o,i,l);r.add(h),i+=a.width}return r}createBlockPonChiKan(e){const s=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let r=0;const i=new T;if(e.type==_.SHO_KAN){let o=s;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(y.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=D(e.tiles[a],this.scale);if(a==o)continue;if(a==s){const u=e.tiles[s],d=e.tiles[o],g=D(u,this.scale),f=this.createRotate90Image(u,0,0,!0),m=this.createRotate90Image(d,0,g.height,!0);i.add(new T().translate(r,0).add(f).add(m)),r+=g.width;continue}const l=c.width*2-c.height,h=this.createImage(e.tiles[a],r,l);r+=c.width,i.add(h)}return i}if(e.type==_.CHI){const o=e.tiles[s],a=this.createRotate90Image(o,r,this.getDiffTileHeightWidth(o));r+=D(o,this.scale).width,i.add(a);for(let c=0;c<e.tiles.length;c++){if(c==s)continue;const l=e.tiles[c],h=D(l,this.scale),u=this.createImage(l,r,0);r+=h.width,i.add(u)}return i}for(let o=0;o<e.tiles.length;o++){const a=o==s?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],l=o==s?this.getDiffTileHeightWidth(c):0,h=D(c,this.scale),u=a(c,r,l);r+=h.width,i.add(u)}return i}}const pi=(n,t)=>{const e=n.scale;return{[_.CHI]:function(r){const i=G(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[_.PON]:function(r){const i=G(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[_.DAI_KAN]:function(r){const i=G(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[_.SHO_KAN]:function(r){const i=G(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[_.AN_KAN]:function(r){I(r instanceof M,`block type is not ankan: ${r.type}`);const i=G(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[_.IMAGE_DORA]:function(r){r=(t==null?void 0:t.doraText)==!1?new Ct([r.tiles[0].clone({remove:y.DORA})]):r;const i=G(r,e),o=new T,a=(t==null?void 0:t.doraText)===!1?n.createImage(r.tiles[0],0,0):n.createTextImage(r.tiles[0],0,0,"(ドラ)");return o.add(a),{...i,e:o}},[_.TSUMO]:function(r){r=(t==null?void 0:t.tsumoText)==!1?new Ct([r.tiles[0].clone({remove:y.TSUMO})]):r;const i=G(r,e),o=new T,a=(t==null?void 0:t.tsumoText)===!1?n.createImage(r.tiles[0],0,0):n.createTextImage(r.tiles[0],0,0,"(ツモ)");return o.add(a),{...i,e:o}},[_.HAND]:function(r){const i=G(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[_.IMAGE_DISCARD]:function(r){const i=G(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[_.THREE]:function(r){throw new Error("three is unsupported")},[_.RUN]:function(r){throw new Error("run is unsupported")},[_.PAIR]:function(r){throw new Error("pair is unsupported")},[_.ISOLATED]:function(r){throw new Error("isolated is unsupported")},[_.UNKNOWN]:function(r){if(r.tiles.some(a=>a.has(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const i=G(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}}}},Tt=(n,t,e)=>{const s=pi(n,e);let r=0,i=0;const o=[];for(const u of t){const d=s[u.type],g=d(u);i+=g.width,r=g.height>r?g.height:r,o.push(g)}const a=r,c=i+(t.length-1)*n.blockMargin,l=new T;let h=0;for(const u of o){const d=a-u.height,g=new T().translate(h,d);g.add(u.e),l.add(g),h+=u.width+n.blockMargin}return{e:l,width:c,height:a}},gi=(n,t,e={},s={responsive:!1,doraText:!0,tsumoText:!0})=>{const r=new sn(e),i=Tt(r,t,s);s.responsive||n.size(i.width,i.height),n.viewbox(0,0,i.width,i.height),n.add(i.e)},Xn=()=>{const n=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(p)){if(e==p.BACK){t.push(xt.buildID(new w(e,0)));continue}t.push(...n.map(s=>xt.buildID(new w(e,s))).flat())}return t},yi=n=>{const t=Xn(),e=[];return n.each((s,r)=>{const i=r[s];if(i instanceof we){const a=i.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},mi=n=>{const t=Xn(),e=yi(n);n.each((s,r)=>{const i=r[s];i instanceof nn&&(t.includes(i.id())&&e.includes(i.id())||i.remove())},!0)},wi=n=>{const e=[];for(let s=0;s<n.length;s+=6){const r=n.slice(s,s+6);e.push(r)}return e},F=(n,t,e,s,r=0,i=0)=>{const o=new T().add(n);if(s==90){const a=r,c=i-e;return o.rotate(s,0,e).translate(a,c),new T().add(o)}if(s==180){const a=r+t,c=i-e;return o.rotate(s,0,e).translate(a,c),new T().add(o)}if(s==270){const a=r+e,c=i+(t-e);return o.rotate(s,0,e).translate(a,c),new T().add(o)}return new T().add(o)},ee=(n,t)=>{const e=new T,s=wi(n);for(let r=0;r<s.length;r++){let i=s[r],o=r*t.tileHeight;const a=t.createBlockHandDiscard(new Ye(i,_.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*s.length}},_i=(n,t,e)=>{const s=t.font,r=t.textWidth,i=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=ke.WIDTH*n.scale,l=ke.HEIGHT*n.scale;let h=r*3,u=i;const d=(c+n.tileWidth+r-h)/2,g=new Et().plain(e.round).font(s).x(d).y(0);u+=25*n.scale;const f=n.tileHeight,m=new T().size(c,f).translate(0,u),b={family:s.family,size:s.size*.7},v=n.createStick(1e3).size(c,l).x(0).y(0),S=new Et().plain(a.toString()).font(b).dx(c).dy(l),N=n.createStick(100).size(c,l).x(0).y(l+l),R=new Et().plain(o.toString()).font(b).dx(c).dy(l*3);m.add(v),m.add(S),m.add(N),m.add(R);const j=n.createImage(e.doras[0],0,0).x(c+r).y(0);m.add(j);const tt=new T;return tt.add(g),tt.add(g),tt.add(m),{e:tt,width:c+n.tileWidth+r,height:u+n.tileHeight}},Ei=(n,t,e=0)=>{const s=Tt(n,t.front),r=Tt(n,t.right),i=Tt(n,t.opposite),o=Tt(n,t.left),a=[s.width,r.width,i.width,o.width].reduce((m,b)=>Math.max(m,b)),c=Math.max(e+n.tileHeight*2+n.blockMargin*2,a+n.tileWidth*2+n.blockMargin),l=c,h=F(s.e,s.width,s.height,0).translate((c-s.width)/2,l-s.height),u=F(r.e,r.width,r.height,270).translate(c-r.height,(c-r.width)/2),d=F(i.e,i.width,i.height,180).translate((c-i.width)/2,0),g=F(o.e,o.width,o.height,90).translate(0,(c-o.width)/2),f=new T().size(c,l);return f.add(h),f.add(u),f.add(d),f.add(g),{e:new T().add(f),width:c,height:l}},bi=n=>{const t=Object.values(ge),e=t.indexOf(n);return[...t.slice(e),...t.slice(0,e)]},Ai=(n,t,e)=>{const s=n.tileWidth*5+n.tileHeight*1,r=t.font,i=t.textWidth,o=t.textHeight,a=t.numWidth,c=_i(n,t,e);c.e.translate(s/2-c.width/2,s/2-c.height/2);const l=(Ms,wn,$s)=>{const Ps=`${Ms} ${wn}`,Hs=new Et().plain(Ps).font(r).attr($s);return{e:new T().add(Hs),width:i+a*wn.toString().length,height:o}},[h,u,d,g]=bi(e.frontPlace),f=e.scores,b=l(h,f.front,{x:s/2,y:s,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let v=l(u,f.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const S=F(v.e,v.width,v.height,270).translate(s,s/2-v.width);let N=l(d,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const R=F(N.e,N.width,N.height,180).translate(s/2-N.width,-N.height);let j=l(g,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const tt=F(j.e,j.width,j.height,90).translate(-j.height,s/2),ht=new T,Rs=new en().size(s,s).x(0).y(0).fill("none").stroke("#000000");return ht.add(Rs),ht.add(c.e),ht.add(b),ht.add(S),ht.add(R),ht.add(tt),{e:ht,width:s,height:s}},Si=(n,t)=>{const e=ee(t.front,n),s=ee(t.right,n),r=ee(t.opposite,n),i=ee(t.left,n),o=[e.height,s.height,r.height,i.height].reduce((S,N)=>Math.max(S,N)),a=n.tileWidth*5+n.tileHeight*1,c=o,l=a+o*2+n.blockMargin,h=l,u=new T().size(l,h),d=l/2-a/2,g=h/2-a/2,f=F(e.e,a,c,0).translate(d,h-c),m=F(s.e,a,c,270).translate(l-c,g),b=F(r.e,a,c,180).translate(d,0),v=F(i.e,a,c,90).translate(0,g);return u.add(f),u.add(m),u.add(b),u.add(v),{e:new T().add(u),width:l,height:h}},qn=(n,t,e,s,r)=>{const i=new T,o=Si(n,s),a=Ei(n,e,o.height),c=Ai(n,t,r);return o.e.translate((a.width-o.width)/2,(a.height-o.height)/2),c.e.translate((a.width-c.width)/2,(a.height-c.height)/2),i.add(a.e),i.add(o.e),i.add(c.e),{e:i,width:a.width,height:a.height}},Ni=(n,t,e={},s,r={responsive:!1})=>{const i=new sn(e),o=s,{discards:a,hands:c,scoreBoard:l}=es(t),h=qn(i,o,c,a,l);r.responsive||n.size(h.width,h.height),n.viewbox(0,0,h.width,h.height),n.add(h.e)};var X;function Qn(n){return{lang:(n==null?void 0:n.lang)??(X==null?void 0:X.lang),message:n==null?void 0:n.message,abortEarly:(n==null?void 0:n.abortEarly)??(X==null?void 0:X.abortEarly),abortPipeEarly:(n==null?void 0:n.abortPipeEarly)??(X==null?void 0:X.abortPipeEarly)}}var Se;function Ii(n){return Se==null?void 0:Se.get(n)}var Ne;function vi(n){return Ne==null?void 0:Ne.get(n)}var Ie;function Ti(n,t){var e;return(e=Ie==null?void 0:Ie.get(n))==null?void 0:e.get(t)}function Rt(n){var e,s;const t=typeof n;return t==="string"?`"${n}"`:t==="number"||t==="bigint"||t==="boolean"?`${n}`:t==="object"||t==="function"?(n&&((s=(e=Object.getPrototypeOf(n))==null?void 0:e.constructor)==null?void 0:s.name))??"null":t}function ot(n,t,e,s,r){const i=r&&"input"in r?r.input:e.value,o=(r==null?void 0:r.expected)??n.expects??null,a=(r==null?void 0:r.received)??Rt(i),c={kind:n.kind,type:n.type,input:i,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:n.requirement,path:r==null?void 0:r.path,issues:r==null?void 0:r.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},l=n.kind==="schema",h=(r==null?void 0:r.message)??n.message??Ti(n.reference,c.lang)??(l?vi(c.lang):null)??s.message??Ii(c.lang);h!==void 0&&(c.message=typeof h=="function"?h(c):h),l&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Kt(n){return{version:1,vendor:"valibot",validate(t){return n["~run"]({value:t},Qn())}}}function Oi(n,t){const e=[...new Set(n)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function $e(n,t){return{kind:"validation",type:"max_value",reference:$e,async:!1,expects:`<=${n instanceof Date?n.toJSON():Rt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value<=this.requirement)&&ot(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():Rt(e.value)}),e}}}function Pe(n,t){return{kind:"validation",type:"min_value",reference:Pe,async:!1,expects:`>=${n instanceof Date?n.toJSON():Rt(n)}`,requirement:n,message:t,"~run"(e,s){return e.typed&&!(e.value>=this.requirement)&&ot(this,"value",e,s,{received:e.value instanceof Date?e.value.toJSON():Rt(e.value)}),e}}}function ki(n,t,e){return typeof n.fallback=="function"?n.fallback(t,e):n.fallback}function ts(n,t,e){return typeof n.default=="function"?n.default(t,e):n.default}function le(n){return{kind:"schema",type:"number",reference:le,expects:"number",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:ot(this,"type",t,e),t}}}function L(n,t){return{kind:"schema",type:"optional",reference:L,expects:`(${n.expects} | undefined)`,async:!1,wrapped:n,default:t,get"~standard"(){return Kt(this)},"~run"(e,s){return e.value===void 0&&(this.default!==void 0&&(e.value=ts(this,e,s)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,s)}}}function He(n,t){return{kind:"schema",type:"picklist",reference:He,expects:Oi(n.map(Rt),"|"),async:!1,options:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){return this.options.includes(e.value)?e.typed=!0:ot(this,"type",e,s),e}}}function Mt(n,t){return{kind:"schema",type:"strict_object",reference:Mt,expects:"Object",async:!1,entries:n,message:t,get"~standard"(){return Kt(this)},"~run"(e,s){var i;const r=e.value;if(r&&typeof r=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=this.entries[o];if(o in r||(a.type==="exact_optional"||a.type==="optional"||a.type==="nullish")&&a.default!==void 0){const c=o in r?r[o]:ts(a),l=a["~run"]({value:c},s);if(l.issues){const h={type:"object",origin:"value",input:r,key:o,value:c};for(const u of l.issues)u.path?u.path.unshift(h):u.path=[h],(i=e.issues)==null||i.push(u);if(e.issues||(e.issues=l.issues),s.abortEarly){e.typed=!1;break}}l.typed||(e.typed=!1),e.value[o]=l.value}else if(a.fallback!==void 0)e.value[o]=ki(a);else if(a.type!=="exact_optional"&&a.type!=="optional"&&a.type!=="nullish"&&(ot(this,"key",e,s,{input:void 0,expected:`"${o}"`,path:[{type:"object",origin:"key",input:r,key:o,value:r[o]}]}),s.abortEarly))break}if(!e.issues||!s.abortEarly){for(const o in r)if(!(o in this.entries)){ot(this,"key",e,s,{input:o,expected:"never",path:[{type:"object",origin:"key",input:r,key:o,value:r[o]}]});break}}}else ot(this,"type",e,s);return e}}}function he(n){return{kind:"schema",type:"string",reference:he,expects:"string",async:!1,message:n,get"~standard"(){return Kt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:ot(this,"type",t,e),t}}}function Tn(...n){return{...n[0],pipe:n,get"~standard"(){return Kt(this)},"~run"(t,e){for(const s of n)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=s["~run"](t,e))}return t}}}function Ci(n,t,e){const s=n["~run"]({value:t},Qn(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}const ne=L(Mt({discard:L(he(),""),hand:L(he(),""),score:L(le(),25e3)}),{discard:"",hand:"",score:25e3}),xi=Mt({[A.E]:ne,[A.S]:ne,[A.W]:ne,[A.N]:ne}),ut={round:C.E1,sticks:{reach:0,dead:0},doras:A.S,front:A.E},Ri=L(Mt({round:L(He(Object.keys(Ze)),ut.round),sticks:L(Mt({reach:L(Tn(le(),Pe(0,""),$e(9,"")),ut.sticks.reach),dead:L(Tn(le(),Pe(0,""),$e(9,"")),ut.sticks.dead)}),ut.sticks),doras:L(he(),ut.doras),front:L(He(Object.keys(ge)),ut.front)}),ut),Mi=Mt({...xi.entries,board:Ri}),es=n=>{const t=ns(n);return ss(t)},ns=n=>{const t=$i(n),e=Ci(Mi,t);if(!e.success)throw e.issues;return e.output},$i=n=>{const t="table",e="board",s=n.split(`
13
+ `).map(a=>a.trim()).filter(a=>a!="");if(s.length==0)throw new Error("empty input");const r=s.shift();if(!r.startsWith(t))throw new Error(`input does not start with table: ${r}`);const i={};let o=[A.E,A.S,A.W,A.N,e];for(;;){const a=s.shift();if(a==null)break;const c=o.find(l=>a.startsWith(l));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(l=>!a.startsWith(l)),c==e){const[l,h]=Hi([...s]);i.board=l;for(let u=0;u<h;u++)s.shift()}else{const[l,h]=Pi([...s]);i[c]=l;for(let u=0;u<h;u++)s.shift()}}return i},Z=(n,t)=>n.replace(t,"").replace(":","").trim(),Pi=n=>{const t="hand",e="discard",s="score",r={};let i=0;for(;i<n.length;i++){const o=n[i];if(o.startsWith(t))r.hand=Z(o,t);else if(o.startsWith(e))r.discard=Z(o,e);else if(o.startsWith(s))r.score=Number(Z(o,s));else break}return[r,i]},Hi=n=>{const t="doras",e="round",s="front",r="sticks",i="reach",o="dead",a={};let c=0;for(;c<n.length;c++){const l=n[c];if(l.startsWith(t))a.doras=Z(l,t);else if(l.startsWith(e))a.round=Z(l,e);else if(l.startsWith(s))a.front=Z(l,s);else if(l.startsWith(r)){a.sticks={};const h=n[c+1]??"",u=n[c+2]??"";h.startsWith(i)&&(a.sticks.reach=Number(Z(h,i))),h.startsWith(o)&&(a.sticks.dead=Number(Z(h,o))),u.startsWith(i)&&(a.sticks.reach=Number(Z(u,i))),u.startsWith(o)&&(a.sticks.dead=Number(Z(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},ss=n=>{const t=n.board.front,e=Wi(t),s=a=>n[a].discard.replace(/\r?\n/g,""),r={front:new B(s(e.front)).tiles(),right:new B(s(e.right)).tiles(),opposite:new B(s(e.opposite)).tiles(),left:new B(s(e.left)).tiles()},i={front:new B(n[e.front].hand).parse(),right:new B(n[e.right].hand).parse(),opposite:new B(n[e.opposite].hand).parse(),left:new B(n[e.left].hand).parse()},o={round:Ze[n.board.round],frontPlace:ge[t],sticks:n.board.sticks,doras:new B(n.board.doras).tiles(),scores:{front:n[e.front].score,right:n[e.right].score,opposite:n[e.opposite].score,left:n[e.left].score}};return{discards:r,hands:i,scoreBoard:o}},Wi=n=>({front:n,right:_t(n),opposite:_t(_t(n)),left:ye(n)});function*z(n){const t=n!=null&&n.filterBy&&n.filterBy.length>0?n==null?void 0:n.filterBy:Object.values(p);for(const e of t){if(n!=null&&n.skipBack&&e==p.BACK)continue;const s=e==p.Z?7:e==p.BACK?1:9;for(let r=1;r<=s;r++)yield[e,r]}}class _e{constructor(t,e=!1){E(this,"data");this.data={[p.M]:[0,0,0,0,0,0,0,0,0,0],[p.P]:[0,0,0,0,0,0,0,0,0,0],[p.S]:[0,0,0,0,0,0,0,0,0,0],[p.Z]:[0,0,0,0,0,0,0,0],[p.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const s=Array.isArray(t)?t:new B(t).parse();for(const r of s){if(r.isCalled()){this.data.called=[...this.called,r];continue}else if(r.is(_.TSUMO)){const i=r.tiles[0];this.inc([i]),this.data.tsumo=i;continue}else if(r.is(_.HAND)){this.inc(r.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(i=>i===p.BACK)){this.inc(r.tiles);continue}else if(e){this.inc(r.tiles);continue}throw new Error(`unexpected block ${r.type} ${r.toString()}`)}}get hands(){const t=[];for(const[e,s]of z()){let r=this.get(e,s);e!=p.Z&&s==5&&this.get(e,0)>0&&(r-=this.get(e,0),t.push(new w(e,s,[y.RED])));for(let i=0;i<r;i++)t.push(new w(e,s))}if(this.drawn!=null){const e=this.drawn,s=t.findIndex(r=>r.equals(e)&&e.has(y.RED)==r.has(y.RED));I(s>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[s]=t[s].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${et}${this.called.join(et)}`:"",e=this.drawn?`${et}${this.drawn.toString()}`:"",s=this.hands.filter(i=>!i.has(y.TSUMO));return`${new Ct(s).toString()}${e}${t}`}get called(){return this.data.called}get reached(){return this.data.reached}get drawn(){return this.data.tsumo}get menzen(){return!this.called.some(t=>!(t instanceof M))}sum(t){let e=0;for(const[s,r]of z({filterBy:[t]}))e+=this.get(s,r);return e}get(t,e){return t==p.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const s of t){if(s.t!=p.BACK&&this.get(s.t,s.n)>=4||s.has(y.RED)&&this.get(s.t,0)>0)throw this.dec(e),new Error(`unable to increase ${s} in ${this.toString()}`);e.push(s),s.t==p.BACK?this.data[s.t][1]+=1:(this.data[s.t][s.n]+=1,s.has(y.RED)&&(this.data[s.t][0]+=1))}return e}dec(t){const e=[];for(const s of t){if(this.get(s.t,s.n)<1||s.has(y.RED)&&this.get(s.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${s.toString()} in ${this.toString()}`);if(e.push(s),s.t==p.BACK?this.data[s.t][1]-=1:(this.data[s.t][s.n]-=1,s.has(y.RED)&&(this.data[s.t][0]-=1)),x(s)&&this.get(s.t,5)==0&&this.get(s.t,0)>0){this.data[s.t][0]=0;const r=e.pop().clone({add:y.RED});e.push(r)}}return e}draw(t){const e=t.clone({add:y.TSUMO});this.inc([e]),this.data.tsumo=e}discard(t){this.dec([t]),this.data.tsumo=null}reach(){if(!this.menzen)throw new Error("cannot reach");if(this.data.reached)throw new Error("already reached");this.data.reached=!0}call(t){const e=t.tiles.filter(s=>!s.has(y.HORIZONTAL));if(e.length!=t.tiles.length-1)throw new Error(`removal: ${e} block: ${t}`);this.dec(e),this.data.called=[...this.called,t],this.data.tsumo=null}kan(t){if(t instanceof M){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof K){const e=this.data.called.findIndex(r=>r.is(_.PON)&&r.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let s=t.tiles[0];s=x(s)?s.clone({remove:y.RED}):s,this.dec([s]),this.data.called=[...this.called.slice(0,e),...this.called.slice(e+1),t],this.data.tsumo=null;return}throw new Error(`unexpected input ${t}`)}clone(){const t=new _e(this.toString());return t.data.reached=this.data.reached,t}}class qt{constructor(t){E(this,"hand");this.hand=t}calc(){return Math.min(this.sevenPairs(),this.thirteenOrphans(),this.fourSetsOnePair())}sevenPairs(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const[s,r]of z({skipBack:!0}))this.hand.get(s,r)==2&&t++,this.hand.get(s,r)==1&&e++;return t>7&&(t=7),t+e>=7&&(e=7-t),13-2*t-e}thirteenOrphans(){if(this.hand.called.length>0)return 1/0;let t=0,e=0;for(const s of Object.values(p)){if(s==p.BACK)continue;const r=s==p.Z?$t:V;for(const i of r)this.hand.get(s,i)>=1&&t++,this.hand.get(s,i)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=s=>{const r=[0,0,0];for(const[d,g]of z({filterBy:[p.Z]}))this.hand.get(d,g)>=3?r[0]++:this.hand.get(d,g)==2?r[1]++:this.hand.get(d,g)==1&&r[2]++;const i=[0,0,0],o=this.hand.get(p.BACK,0),a=o%3;i[0]=Math.floor(o/3),a==2?i[1]=1:a==1&&(i[2]=1);let c=13;const l=this.patternNumType(p.M),h=this.patternNumType(p.P),u=this.patternNumType(p.S);for(const d of[l.patternA,l.patternB])for(const g of[h.patternA,h.patternB])for(const f of[u.patternA,u.patternB]){const m=[this.hand.called.length,0,0];for(let v=0;v<3;v++)m[v]+=d[v]+g[v]+f[v]+r[v]+i[v];const b=this.calcCommon(m[0],m[1],m[2],s);b<c&&(c=b)}return c};let e=t(!1);for(const[s,r]of z())if(this.hand.get(s,r)>=2){const i=this.hand.dec(new Array(2).fill(new w(s,r))),o=t(!0);this.hand.inc(i),o<e&&(e=o)}return e}patternNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let s=this.patternNumType(t,e+1);if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const r=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),i=this.patternNumType(t,e);this.hand.inc(r),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<s.patternA[2]||i.patternA[2]==s.patternA[2]&&i.patternA[1]<s.patternA[1])&&(s.patternA=i.patternA),(i.patternB[0]>s.patternB[0]||i.patternB[0]==s.patternB[0]&&i.patternB[1]>s.patternB[1])&&(s.patternB=i.patternB)}if(this.hand.get(t,e)>=3){const r=this.hand.dec(new Array(3).fill(new w(t,e))),i=this.patternNumType(t,e);this.hand.inc(r),i.patternA[0]++,i.patternB[0]++,(i.patternA[2]<s.patternA[2]||i.patternA[2]==s.patternA[2]&&i.patternA[1]<s.patternA[1])&&(s.patternA=i.patternA),(i.patternB[0]>s.patternB[0]||i.patternB[0]==s.patternB[0]&&i.patternB[1]>s.patternB[1])&&(s.patternB=i.patternB)}return s}groupRemainingTiles(t){let e=0,s=0,r=0;for(const[i,o]of z({filterBy:[t]}))r+=this.hand.get(i,o),o<=7&&this.hand.get(i,o+1)==0&&this.hand.get(i,o+2)==0&&(e+=r>>1,s+=r%2,r=0);return e+=r>>1,s+=r%2,{patternA:[0,e,s],patternB:[0,e,s]}}calcCommon(t,e,s,r){let i=r?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(s+=t+e-4,e=4-t),t+e+s>i&&(s=i-t-e),r&&e++,13-t*3-e*2-s}}class rs{constructor(t){E(this,"hand");this.hand=t}calc(t){return this.markDrawn([...this.sevenPairs(),...this.thirteenOrphans(),...this.nineGates(),...this.fourSetsOnePair()],t)}markDrawn(t,e){if(t.length==0)return[];const s=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,r=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let l=0;l<a.length;l++){const h=a[l];if(h.isCalled())continue;const u=h.tiles.findIndex(g=>g.equals(e)&&e.has(y.RED)==g.has(y.RED));if(u<0)continue;const d=Ut(h);c[d]||(c[d]=!0,r.push([o,l,u]))}}if(r.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const i=[];for(const[o,a,c]of r){const h=[...t[o]],u=h[a],d=u.tiles[c].clone({add:s});h[a]=u.clone({replace:{idx:c,tile:d}}),i.push(h)}return i}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,s]of z({skipBack:!0})){const r=this.hand.get(e,s);if(r==2){const i=this.hand.dec(new Array(2).fill(new w(e,s)));t.push(new W(i[0],i[1])),this.hand.inc(i)}else{if(r==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const s of Object.values(p)){if(s==p.BACK)continue;const r=s==p.Z?$t:V;for(let i of r)if(this.hand.get(s,i)==1)t.push(new Je(new w(s,i)));else if(this.hand.get(s,i)==2&&e==!1)t.unshift(new W(new w(s,i),new w(s,i))),e=!0;else return[]}return[t]}nineGates(){const t=(e,s,r)=>r.includes(this.hand.get(e,s));for(const e of Object.values(p)){if(e==p.BACK||e==p.Z)continue;const s=t(e,1,[3,4])&&t(e,9,[3,4])&&t(e,2,[1,2])&&t(e,3,[1,2])&&t(e,4,[1,2])&&t(e,5,[1,2])&&t(e,6,[1,2])&&t(e,7,[1,2])&&t(e,8,[1,2]),r=this.hand.sum(e)==14;if(s&&r)return[[new Ct(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of z())if(this.hand.get(e,s)>=2){const r=new Array(2).fill(new w(e,s));s==5&&this.hand.get(e,0)>0&&this.hand.get(e,s)>=3&&(r[1]=new w(e,s,[y.RED]));const i=this.hand.dec(r),o=this.patternAll().filter(a=>a.length==4).map(a=>(a.unshift(new W(i[0],i[1])),a));t=[...t,...o],this.hand.inc(i)}return t}patternAll(){return[this.addRedPattern(p.M,this.handleNumType(p.M)),this.addRedPattern(p.P,this.handleNumType(p.P)),this.addRedPattern(p.S,this.handleNumType(p.S)),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,r)=>r.length-s.length).reduce((s,r)=>r.length===0?s:s.flatMap(i=>r.map(o=>[...i,...o])),[[]])}handleBack(){const t=p.BACK,e=this.hand.get(t,0);if(e<3)return[];const s=new w(t,0),r=Array(Math.floor(e/3)).fill(new U([s,s,s]));return r.length==0?[]:[r]}handleZ(){const t=[];for(const[e,s]of z({filterBy:[p.Z]})){if(this.hand.get(e,s)==0)continue;if(this.hand.get(e,s)!=3)return[];const r=new w(e,s);t.push(new U([r,r,r]))}return t.length==0?[]:[t]}addRedPattern(t,e){if(!(this.hand.get(t,0)>0&&this.hand.get(t,5)>=2))return e;const s=new w(t,5),r=new w(t,5,[y.RED]),i=[],o=[];for(let c=0;c<e.length;c++){const l=e[c],h={};for(let u=0;u<l.length;u++){const d=l[u],g=d.tiles.findIndex(b=>b.equals(s)&&!b.has(y.RED)),f=d.tiles.findIndex(b=>b.equals(r)&&b.has(y.RED));if(f>-1&&o.push([c,u,f]),f>-1&&g>-1||g<0)continue;const m=Ut(d);h[m]||(h[m]=!0,i.push([c,u,g]))}}if(o.length==0)return e;const a=[];for(const[c,l,h]of i){const d=[...e[c]],g=d[l];d[l]=g.clone({replace:{idx:h,tile:r}});const f=o.find(b=>b[0]==c);if(f==null)continue;const m=d[f[1]];m==null&&console.error(f,i),d[f[1]]=m.clone({replace:{idx:f[2],tile:s}}),Ut(g)!=Ut(m)&&a.push(d)}return[...e,...a]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const s=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const r=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let i=this.handleNumType(t,e);this.hand.inc(r),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new nt([r[0],r[1],r[2]])),s.push(o)}if(this.hand.get(t,e)==3){const r=this.hand.dec(new Array(3).fill(new w(t,e)));let i=this.handleNumType(t,e);this.hand.inc(r),i.length==0&&(i=[[]]);for(const o of i)o.unshift(new U([r[0],r[1],r[2]])),s.push(o)}return s}}const $t=[1,2,3,4,5,6,7],V=[1,9],jt=n=>{var e;const t=n.boardContext;return{...n,hand:n.hand.map(O.deserialize),boardContext:{...t,doraIndicators:t.doraIndicators.map(w.from),hiddenDoraIndicators:(e=t.hiddenDoraIndicators)==null?void 0:e.map(w.from)}}},ue=n=>JSON.parse(JSON.stringify(n));class We{constructor(t,e){E(this,"hand");E(this,"cfg");this.hand=t,this.cfg={doras:e.doraIndicators.map(s=>kn(s)),blindDoras:e.hiddenDoraIndicators==null?[]:e.hiddenDoraIndicators.map(s=>kn(s)),roundWind:w.from(e.round.substring(0,2)),myWind:w.from(e.myWind),reached:e.reached??0,sticks:e.sticks??{dead:0,reach:0},replacementWin:e.replacementWin??!1,quadWin:e.quadWin??!1,finalWallWin:e.finalWallWin??!1,finalDiscardWin:e.finalDiscardWin??!1,oneShotWin:e.oneShotWin??!1,roundUp8000:e.roundUp8000??!1,disableCountable32000:e.disableCountable32000??!1,orig:e}}calc(...t){const e=this.calcPatterns(t);let s=!1,r=!1;if(e.length==0)return!1;let i=[0,0],o=0;for(let S=0;S<e.length;S++){const N=e[S];s=N.is32000??!1;const R=N.yakus.reduce((j,tt)=>j+tt.han,0);R>i[0]?(o=S,i=[R,N.fu]):R==i[0]&&N.fu>i[1]&&(o=S,i=[R,N.fu])}const a=(S,N=100)=>Math.ceil(S/N)*N,c=i[1]!=25?a(i[1],10):25,l=i[0];let h=Math.min(c*2**(l+2),2e3);switch(l){case 26:h=16e3;break;case 13:h=8e3;break;case 12:case 11:h=6e3;break;case 10:case 9:case 8:h=4e3;break;case 7:case 6:h=3e3;break;case 5:h=2e3;break}l>=13&&l<26&&(h=8e3,this.cfg.disableCountable32000&&e[o].yakus.length>1?h=6e3:r=!0),this.cfg.roundUp8000&&(c==30&&l==4||c==60&&l==3)&&(h=2e3);const u=e[o].hand.some(S=>S.tiles.some(N=>N.has(y.TSUMO))),d=this.cfg.orig.myWind,g=d==A.E;let f="";const m=P(0);if(u){const S=this.cfg.sticks.dead*100;if(g){const N=a(h*2);m[A.E]+=N*3+S*3,m[A.S]-=N+S,m[A.W]-=N+S,m[A.N]-=N+S,f=`${N}`}else{for(const N of Object.values(A)){if(N==d)continue;const R=N==A.E?2:1,j=a(h*R);m[N]-=j+S,m[d]+=j+S}f=`${h}-${h*2}`}}else{const S=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const R=a(h*(g?6:4))+S;m[d]+=R,m[this.cfg.orig.ronWind]-=R,f=`${R}`}m[d]+=1e3*this.cfg.sticks.reach;let b;return s?b="役満":r?b="数え役満":h==2e3?b=`${c}符${l}飜 満貫${f}`:h==3e3?b=`${c}符${l}飜 跳満${f}`:h==4e3?b=`${c}符${l}飜 倍満${f}`:h==6e3?b=`${c}符${l}飜 三倍満${f}`:b=`${c}符${l}飜 ${f}`,{deltas:m,sum:l,fu:c,yakus:e[o].yakus,point:m[d],hand:e[o].hand,boardContext:this.cfg.orig,description:b}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const s of t){const r=[...this.dA13(s),...this.dB13(s),...this.dC13(s),...this.dD13(s),...this.dE13(s),...this.dF13(s),...this.dG13(s),...this.dH13(s),...this.dI13(s),...this.dJ13(s),...this.dK13(s)];r.length!=0&&e.push({yakus:r,fu:30,hand:s,is32000:!0})}if(e.length>0)return e;for(const s of t){const r=this.calcFu(s),i=[...this.dA1(s),...this.dB1(s),...this.dC1(s),...this.dD1(s),...this.dE1(s),...this.dF1(s),...this.dG1(s),...this.dH1(s),...this.dI1(s),...this.dJ1(s),...this.dK1(s),...this.dA2(s),...this.dB2(s),...this.dC2(s),...this.dD2(s),...this.dE2(s),...this.dF2(s),...this.dG2(s),...this.dH2(s),...this.dI2(s),...this.dJ2(s),...this.dA3(s),...this.dB3(s),...this.dC3(s),...this.dA6(s)];i.length!=0&&(i.push(...this.dX1(s)),e.push({yakus:i,fu:r,hand:s}))}return e}minus(){return this.hand.menzen?0:1}dA1(t){return this.cfg.reached==1?[{name:"立直",han:1}]:this.cfg.reached==2?[{name:"ダブル立直",han:2}]:[]}dB1(t){return this.minus()!=0?[]:(this.hand.drawn==null,t.some(s=>s.tiles.some(r=>r.has(y.TSUMO)))?[{name:"門前清自摸和",han:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",s=this.calcFu(t);return s==20?[{name:e,han:1}]:!t.some(r=>r.tiles.some(i=>i.has(y.TSUMO)))&&s==30?[{name:e,han:1}]:[]}dD1(t){return t.some(s=>s.tiles.some(r=>r.t==p.Z||V.includes(r.n)))?[]:[{name:"断么九",han:1}]}dE1(t){return this.minus()!=0?[]:On(t)==1?[{name:"一盃口",han:1}]:[]}dF1(t){const e=[];return t.forEach(s=>{if(s instanceof W)return;const r=s.tiles[0];r.t==p.Z&&(r.equals(this.cfg.myWind)&&e.push({name:"自風",han:1}),r.equals(this.cfg.roundWind)?e.push({name:"場風",han:1}):r.n==5?e.push({name:"白",han:1}):r.n==6?e.push({name:"發",han:1}):r.n==7&&e.push({name:"中",han:1}))}),e}dG1(t){return this.cfg.oneShotWin?[{name:"一発",han:1}]:[]}dH1(t){return this.cfg.replacementWin?[{name:"嶺上開花",han:1}]:[]}dI1(t){return this.cfg.quadWin?[{name:"搶槓",han:1}]:[]}dJ1(t){return this.cfg.finalWallWin?[{name:"海底摸月",han:1}]:[]}dK1(t){return this.cfg.finalDiscardWin?[{name:"河底撈魚",han:1}]:[]}dX1(t){let e=0,s=0,r=0;for(const o of t)for(const a of o.tiles){for(const c of this.cfg.doras)a.equals(c)&&e++;for(const c of this.cfg.blindDoras)a.equals(c)&&s++;a.has(y.RED)&&r++}const i=[];return e>0&&i.push({name:"ドラ",han:e}),r>0&&i.push({name:"赤ドラ",han:r}),this.hand.reached&&s>0&&i.push({name:"裏ドラ",han:s}),i}dA2(t){return t.length==7?[{name:"七対子",han:2}]:[]}dB2(t){const e=s=>s instanceof nt||s instanceof J;for(const s of t){if(!e(s))continue;const r=dt(s);if(r.t==p.Z)continue;const i=[p.M,p.P,p.S].filter(c=>c!=r.t),o=t.some(c=>{const l=new w(i[0],r.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(i[1],r.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同順",han:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(s=>s instanceof M||s instanceof K||s instanceof Q||s instanceof U||s instanceof Y||s instanceof W)?[{name:"対々和",han:2}]:[]}dD2(t){return t.filter(s=>(s instanceof M||s instanceof U)&&!s.tiles.some(r=>r.has(y.RON))).length>=3?[{name:"三暗刻",han:2}]:[]}dE2(t){return t.filter(s=>s instanceof M||s instanceof K||s instanceof Q).length>=3?[{name:"三槓子",han:2}]:[]}dF2(t){const e=s=>s instanceof M||s instanceof K||s instanceof Q||s instanceof U||s instanceof Y;for(const s of t){if(!e(s))continue;const r=dt(s);if(r.t==p.Z)continue;const i=[p.M,p.P,p.S].filter(c=>c!=r.t),o=t.some(c=>{const l=new w(i[0],r.n);return e(c)&&l.equals(dt(c))}),a=t.some(c=>{const l=new w(i[1],r.n);return e(c)&&l.equals(dt(c))});if(o&&a)return[{name:"三色同刻",han:2}]}return[]}dG2(t){return t.length==7?[]:t.filter(s=>{const r=s.tiles[0];return r.t==p.Z&&[5,6,7].includes(r.n)}).length==3?[{name:"小三元",han:2}]:[]}dH2(t){return t.every(s=>{const r=s.tiles[0].t==p.Z?$t:V;return s.tiles.every(i=>r.includes(i.n))})?[{name:"混老頭",han:2}]:[]}dI2(t){return t.length==7?[]:t.some(s=>s instanceof nt||s instanceof J)?t.some(s=>s.tiles[0].t==p.Z)?t.every(s=>{const r=s.tiles[0].t==p.Z?$t:V;return s.tiles.some(i=>r.includes(i.n))})?[{name:"混全帯么九",han:2-this.minus()}]:[]:[]:[]}dJ2(t){const e={[p.M]:[0,0,0],[p.S]:[0,0,0],[p.P]:[0,0,0]};for(const s of t){const r=dt(s);r.t!=p.BACK&&r.t!=p.Z&&(s instanceof nt||s instanceof J)&&(r.n==1?e[r.t][0]++:r.n==4?e[r.t][1]++:r.n==7&&e[r.t][2]++)}for(const s of Object.values(e))if(s[0]>0&&s[1]>0&&s[2]>0)return[{name:"一気通貫",han:2-this.minus()}];return[]}dA3(t){if(!t.some(s=>s.tiles[0].t==p.Z))return[];for(const s of Object.values(p))if(t.every(i=>i.tiles[0].t==p.Z||i.tiles[0].t==s))return[{name:"混一色",han:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(s=>s instanceof nt||s instanceof J)?t.some(s=>s.tiles[0].t==p.Z)?[]:t.every(s=>s.tiles.some(r=>V.includes(r.n)))?[{name:"純全帯么九色",han:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:On(t)==2?[{name:"ニ盃口",han:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==p.Z))return[];for(const e of Object.values(p)){if(e==p.Z)continue;if(t.every(r=>r.tiles[0].t==e))return[{name:"清一色",han:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(s=>s instanceof W&&s.tiles.some(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"国士無双13面待ち",han:26}]:[{name:"国士無双",han:13}]}dB13(t){return t.length==1?[{name:"九蓮宝燈",han:13}]:[]}dC13(t){return t.length==7?[]:t.every(r=>r instanceof M||r instanceof U&&!r.tiles.some(i=>i.has(y.RON))||r instanceof W)?t.some(r=>r instanceof W&&r.tiles.every(i=>i.has(y.TSUMO)||i.has(y.RON)))?[{name:"四暗刻単騎待ち",han:26}]:[{name:"四暗刻",han:13}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(r=>!(r instanceof W)&&r.tiles.some(i=>i.t==p.Z&&e.includes(i.n))).length==3?[{name:"大三元",han:13}]:[]}dE13(t){return t.every(s=>s.tiles[0].t==p.Z)?[{name:"字一色",han:13}]:[]}dF13(t){return t.every(s=>s.tiles.every(r=>r.t!=p.Z&&V.includes(r.n)))?[{name:"清老頭",han:13}]:[]}dG13(t){return t.filter(s=>s instanceof M||s instanceof K||s instanceof Q).length==4?[{name:"四槓子",han:13}]:[]}dH13(t){if(t.length==13)return[];if(t.length==7)return[];const e=[1,2,3,4];return t.filter(i=>i.tiles.some(o=>o.t==p.Z&&e.includes(o.n))).length==4?t.find(i=>i instanceof W).tiles.some(i=>i.t==p.Z&&e.includes(i.n))?[{name:"小四喜",han:13}]:[{name:"大四喜",han:13}]:[]}dI13(t){const e=s=>!!(s.equals(new w(p.Z,6))||s.t==p.S&&[2,3,4,6,8].includes(s.n));return t.every(s=>s.tiles.every(r=>e(r)))?[{name:"緑一色",han:13}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let s=20;const r=this.cfg.myWind.n,i=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(f=>f.tiles.some(m=>m.has(y.TSUMO)||m.has(y.RON))),a=this.minus()==1,c=o.tiles.some(f=>f.has(y.TSUMO)),l=(f,m)=>{const b=f.tiles[0];return b.t==p.Z||V.includes(b.n)?m*2:m};for(const f of t)switch(!0){case f instanceof U:const m=f.tiles.some(b=>b.has(y.RON))?2:4;s+=l(f,m);break;case f instanceof Y:s+=l(f,2);break;case(f instanceof Q||f instanceof K):s+=l(f,8);break;case f instanceof M:s+=l(f,16);break}s+=(f=>{if(f instanceof U)return 0;if(f instanceof W)return 2;const m=f.tiles,b=m.findIndex(v=>v.has(y.TSUMO)||v.has(y.RON));return b==1||b==0&&m[2].n==9||b==2&&m[0].n==1?2:0})(o);const d=t.find(f=>f instanceof W).tiles[0];d.t==p.Z&&([5,6,7].includes(d.n)&&(s+=2),(d.n==i||d.n==r)&&(s+=2));let g=!1;return!a&&s==20&&(g=!0),c&&!g&&(s+=2),!c&&!a&&(s+=10),!c&&!a&&s==30&&(g=!0),a&&s==20&&(s=30),s}}const Ut=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),On=n=>{const t={};for(const s of n){if(!(s instanceof nt))continue;const r=Ut(s);t[r]==null?t[r]=1:t[r]++}let e=0;for(const s in t)t[s]>=2&&e++;return e},dt=n=>[...n.tiles].sort(Xt)[0],kn=n=>{const t=n.n,e=n.t;if(e==p.Z){if(t==4)return new w(e,1);if(t==7)return new w(e,5)}return new w(e,t%9+1)};class Pt{static calcCandidates(t,e,s){I(e.length>0,"choices to discard is zero");const r=new Map;let i=1/0;for(const o of e){const a=t.dec([o]),c=Pt.candidateTiles(t,s);t.inc(a);const l=s!=null&&s.arrangeRed&&o.has(y.RED)?o.clone({removeAll:!0}):o.has(y.RED)?o.clone({removeAll:!0,add:y.RED}):o.clone({removeAll:!0});c.shanten<i?(r.clear(),r.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l}),i=c.shanten):c.shanten==i&&r.set(l.toString(),{shanten:c.shanten,candidates:c.candidates,tile:l})}return Array.from(r.values())}static candidateTiles(t,e){let s=1/0,r=[];const i=new qt(t);for(const[o,a]of z({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),l=t.inc([c]),h=e!=null&&e.fourSetsOnePair?i.fourSetsOnePair():i.calc();t.dec(l),h<s?(s=h,r=[c]):h==s&&r.push(c)}return{shanten:s,candidates:r}}}const Be=()=>{const n=new Set;return{on(t){n.add(t)},off(t){n.delete(t)},offAll(){n.clear()},emit(t){n.forEach(e=>e(t))}}};function is(n){var i;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),r=as(e,t).map(o=>n[o]);return{events:r,type:cs(t,(i=r[0])==null?void 0:i.choices)}}function os(n){var i;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),r=as(e,t).map(o=>n[o]);return{events:r,type:cs(t,(i=r[0])==null?void 0:i.choices)}}function as(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let r=0;r<n.length;r++){const i=n[r];if(Bi(i,t)){const o=Di(t,i);o<s?(s=o,e=[r]):o===s&&e.push(r)}}return e}function Bi(n,t){return t.some(e=>!!n[e])}function Di(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function cs(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const Ft=()=>{const n=Be(),t=Be(),e={emit:n.emit,on:r=>t.on(r)},s={emit:t.emit,on:r=>n.on(r)};return[e,s]},ls=()=>{const n=Be();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Vt{constructor(t){E(this,"reachValue",1e3);E(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let s in e){const r=e[s],i=t[r];this.m[s]+=i}}}class Jt{constructor(t,e){E(this,"pToW",{});E(this,"wToP",P(""));E(this,"round");E(this,"sticks");this.round=(e==null?void 0:e.round)??C.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let s in this.pToW)this.wToP[this.pToW[s]]=s}update(){for(let t in this.pToW){const e=ye(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Zt(this.round);this.round=t,this.update()}resetDeadStick(){this.sticks.dead=0}resetReachStick(){this.sticks.reach=0}is(t){return this.round==t}wind(t){return this.pToW[t]}playerID(t){return this.wToP[t]}get playerMap(){return structuredClone(this.pToW)}}function rn(n){for(let t=n.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[n[t],n[e]]=[n[e],n[t]]}return n}class hs{constructor(t=!1){E(this,"c");E(this,"safeMap",P({},!0));this.disable=t,this.c=this.initial()}get(t){return t.t==p.BACK?0:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=p.BACK){if(this.get(e)<=0)throw new Error(`[counter] cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,e.has(y.RED)&&(this.c[e.t][0]-=1)}}}addTileToSafeMap(t,e){this.disable||(this.safeMap[e][this.key(t.t,t.n)]=!0)}isSafeTile(t,e,s){return this.safeMap[s][this.key(t,e)]}key(t,e){return`${t}${e}`}reset(){this.c=this.initial()}initial(){return{[p.M]:[1,4,4,4,4,4,4,4,4,4],[p.S]:[1,4,4,4,4,4,4,4,4,4],[p.P]:[1,4,4,4,4,4,4,4,4,4],[p.Z]:[0,4,4,4,4,4,4,4]}}}class on{constructor(){E(this,"m",[])}discard(t,e){this.m.push({w:e,t})}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==t)}get lastTile(){const t=this.m.at(-1);return I(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}markCalled(){this.lastTile.callMarker=!0}cannotContinue(){const t=this.discards();if(t.length!=4)return!1;let e=t[0].t;if(e.isNum())return!1;for(let s=0;s<4;s++)if(!e.equals(t[s].t))return!1;return!0}}function Ki(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function Li(){const n=Ki();if(n.__xstate__)return n.__xstate__}const zi=n=>{if(typeof window>"u")return;const t=Li();t&&t.register(n)};class Cn{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current){this._last.next=e,this._last=e;return}this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const us=".",ji="",ds="",Ui="#",Fi="*",fs="xstate.init",De="xstate.stop";function Gi(n,t){return{type:`xstate.after.${n}.${t}`}}function Ke(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Zi(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function Vi(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function ps(n){return{type:fs,input:n}}function q(n){setTimeout(()=>{throw n})}const Ji=typeof Symbol=="function"&&Symbol.observable||"@@observable";function gs(n,t){const e=xn(n),s=xn(t);return typeof s=="string"?typeof e=="string"?s===e:!1:typeof e=="string"?e in s:Object.keys(e).every(r=>r in s?gs(e[r],s[r]):!1)}function an(n){if(ms(n))return n;const t=[];let e="";for(let s=0;s<n.length;s++){switch(n.charCodeAt(s)){case 92:e+=n[s+1],s++;continue;case 46:t.push(e),e="";continue}e+=n[s]}return t.push(e),t}function xn(n){if(Co(n))return n.value;if(typeof n!="string")return n;const t=an(n);return Yi(t)}function Yi(n){if(n.length===1)return n[0];const t={};let e=t;for(let s=0;s<n.length-1;s++)if(s===n.length-2)e[n[s]]=n[s+1];else{const r=e;e={},r[n[s]]=e}return t}function Rn(n,t){const e={},s=Object.keys(n);for(let r=0;r<s.length;r++){const i=s[r];e[i]=t(n[i],i,n,r)}return e}function ys(n){return ms(n)?n:[n]}function rt(n){return n===void 0?[]:ys(n)}function Le(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function ms(n){return Array.isArray(n)}function Xi(n){return n.type.startsWith("xstate.error.actor")}function vt(n){return ys(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ws(n){if(!(n===void 0||n===ji))return rt(n)}function ze(n,t,e){var i,o,a;const s=typeof n=="object",r=s?n:void 0;return{next:(i=s?n.next:n)==null?void 0:i.bind(r),error:(o=s?n.error:t)==null?void 0:o.bind(r),complete:(a=s?n.complete:e)==null?void 0:a.bind(r)}}function Mn(n,t){return`${t}.${n}`}function cn(n,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return n.implementations.actors[t];const[,s,r]=e,o=n.getStateNodeById(r).config.invoke;return(Array.isArray(o)?o[s]:o).src}function $n(n,t){return`${n.sessionId}.${t}`}let qi=0;function Qi(n,t){const e=new Map,s=new Map,r=new WeakMap,i=new Set,o={},{clock:a,logger:c}=t,l={schedule:(d,g,f,m,b=Math.random().toString(36).slice(2))=>{const v={source:d,target:g,event:f,delay:m,id:b,startedAt:Date.now()},S=$n(d,b);u._snapshot._scheduledEvents[S]=v;const N=a.setTimeout(()=>{delete o[S],delete u._snapshot._scheduledEvents[S],u._relay(d,g,f)},m);o[S]=N},cancel:(d,g)=>{const f=$n(d,g),m=o[f];delete o[f],delete u._snapshot._scheduledEvents[f],m!==void 0&&a.clearTimeout(m)},cancelAll:d=>{for(const g in u._snapshot._scheduledEvents){const f=u._snapshot._scheduledEvents[g];f.source===d&&l.cancel(d,f.id)}}},h=d=>{if(!i.size)return;const g={...d,rootId:n.sessionId};i.forEach(f=>{var m;return(m=f.next)==null?void 0:m.call(f,g)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${qi++}`,_register:(d,g)=>(e.set(d,g),d),_unregister:d=>{e.delete(d.sessionId);const g=r.get(d);g!==void 0&&(s.delete(g),r.delete(d))},get:d=>s.get(d),_set:(d,g)=>{const f=s.get(d);if(f&&f!==g)throw new Error(`Actor with system ID '${d}' already exists.`);s.set(d,g),r.set(g,d)},inspect:d=>{const g=ze(d);return i.add(g),{unsubscribe(){i.delete(g)}}},_sendInspectionEvent:h,_relay:(d,g,f)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:d,actorRef:g,event:f}),g._send(f)},scheduler:l,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const d=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const g in d){const{source:f,target:m,event:b,delay:v,id:S}=d[g];l.schedule(f,m,b,v,S)}},_clock:a,_logger:c};return u}let ve=!1;const ln=1;let H=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const to={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class eo{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Cn(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=H.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...to,...e},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:h}=s;this.system=o?o.system:Qi(this,{clock:r,logger:i}),h&&!o&&this.system.inspect(ze(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=(e==null?void 0:e.logger)??this.system._logger,this.clock=(e==null?void 0:e.clock)??this.system._clock,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:u=>{this._deferred.push(u)},system:this.system,stopChild:u=>{if(u._parent!==this)throw new Error(`Cannot stop child actor ${u.id} of ${this.id} because it is not a child`);u._stop()},emit:u=>{const d=this.eventListeners.get(u.type),g=this.eventListeners.get("*");if(!d&&!g)return;const f=[...d?d.values():[],...g?g.values():[]];for(const m of f)m(u)},actionExecutor:u=>{const d=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:u.type,params:u.params}}),!u.exec)return;const g=ve;try{ve=!0,u.exec(u.info,u.params)}finally{ve=g}};this._processingStatus===H.Running?d():this._deferred.push(d)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),l&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){var e;try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,(e=this.options)==null?void 0:e.input)}catch(s){this._snapshot={status:"error",output:void 0,error:s}}}update(t,e){var r,i;this._snapshot=t;let s;for(;s=this._deferred.shift();)try{s()}catch(o){this._deferred.length=0,this._snapshot={...t,status:"error",error:o}}switch(this._snapshot.status){case"active":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){q(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){q(a)}this._stopProcedure(),this._complete(),this._doneEvent=Zi(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){var i;const r=ze(t,e,s);if(this._processingStatus!==H.Stopped)this.observers.add(r);else switch(this._snapshot.status){case"done":try{(i=r.complete)==null||i.call(r)}catch(o){q(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)q(o);else try{r.error(o)}catch(a){q(a)}break}}return{unsubscribe:()=>{this.observers.delete(r)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const r=e.bind(void 0);return s.add(r),{unsubscribe:()=>{s.delete(r)}}}start(){if(this._processingStatus===H.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=H.Running;const t=ps(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(s){return this._snapshot={...this._snapshot,status:"error",error:s},this._error(s),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(r){s={err:r}}if(s){const{err:r}=s;this._snapshot={...this._snapshot,status:"error",error:r},this._error(r);return}this.update(e,t),t.type===De&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===H.Stopped?this:(this.mailbox.clear(),this._processingStatus===H.NotStarted?(this._processingStatus=H.Stopped,this):(this.mailbox.enqueue({type:De}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){var t;for(const e of this.observers)try{(t=e.complete)==null||t.call(e)}catch(s){q(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||q(t);return}let e=!1;for(const s of this.observers){const r=s.error;e||(e=!r);try{r==null||r(t)}catch(i){q(i)}}this.observers.clear(),e&&q(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Vi(this.id,t))}_stopProcedure(){return this._processingStatus!==H.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Cn(this._process.bind(this)),this._processingStatus=H.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==H.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:zi)(this)}toJSON(){return{xstate$$type:ln,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Ji](){return this}getSnapshot(){return this._snapshot}}function Ht(n,...[t]){return new eo(n,t)}function no(n,t,e,s,{sendId:r}){const i=typeof r=="function"?r(e,s):r;return[t,{sendId:i},void 0]}function so(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function ro(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=no,t.execute=so,t}function io(n,t,e,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?cn(t.machine,o):o,h=typeof r=="function"?r(e):r;let u,d;return l&&(d=typeof a=="function"?a({context:t.context,event:e.event,self:n.self}):a,u=Ht(l,{id:h,src:o,parent:n.self,syncSnapshot:c,systemId:i,input:d})),[At(t,{children:{...t.children,[h]:u}}),{id:r,systemId:i,actorRef:u,src:o,input:d},void 0]}function oo(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==H.Stopped&&t.start()})}function ao(...[n,{id:t,systemId:e,input:s,syncSnapshot:r=!1}={}]){function i(o,a){}return i.type="xstate.spawnChild",i.id=t,i.systemId=e,i.src=n,i.input=s,i.syncSnapshot=r,i.resolve=io,i.execute=oo,i}function co(n,t,e,s,{actorRef:r}){const i=typeof r=="function"?r(e,s):r,o=typeof i=="string"?t.children[i]:i;let a=t.children;return o&&(a={...a},delete a[o.id]),[At(t,{children:a}),o,void 0]}function lo(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==H.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function _s(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=co,t.execute=lo,t}function hn(n,t,e,s){const{machine:r}=s,i=typeof n=="function",o=i?n:r.implementations.guards[typeof n=="string"?n:n.type];if(!i&&!o)throw new Error(`Guard '${typeof n=="string"?n:n.type}' is not implemented.'.`);if(typeof o!="function")return hn(o,t,e,s);const a={context:t,event:e},c=i||typeof n=="string"?void 0:"params"in n?typeof n.params=="function"?n.params({context:t,event:e}):n.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const un=n=>n.type==="atomic"||n.type==="final";function Wt(n){return Object.values(n.states).filter(t=>t.type!=="history")}function Qt(n,t){const e=[];if(t===n)return e;let s=n.parent;for(;s&&s!==t;)e.push(s),s=s.parent;return e}function de(n){const t=new Set(n),e=bs(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Pn(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of Wt(s))if(r.type!=="history"&&!t.has(r)){const i=Pn(r);for(const o of i)t.add(o)}}for(const s of t){let r=s.parent;for(;r;)t.add(r),r=r.parent}return t}function Es(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const r=e[0];if(r){if(un(r))return r.key}else return{}}const s={};for(const r of e)s[r.key]=Es(r,t);return s}function bs(n){const t=new Map;for(const e of n)t.has(e)||t.set(e,[]),e.parent&&(t.has(e.parent)||t.set(e.parent,[]),t.get(e.parent).push(e));return t}function As(n,t){const e=de(t);return Es(n,bs(e))}function dn(n,t){return t.type==="compound"?Wt(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Wt(t).every(e=>dn(n,e)):t.type==="final"}const Ee=n=>n[0]===Ui;function ho(n,t){return n.transitions.get(t)||[...n.transitions.keys()].filter(s=>{if(s===Fi)return!0;if(!s.endsWith(".*"))return!1;const r=s.split("."),i=t.split(".");for(let o=0;o<r.length;o++){const a=r[o],c=i[o];if(a==="*")return o===r.length-1;if(a!==c)return!1}return!0}).sort((s,r)=>r.length-s.length).flatMap(s=>n.transitions.get(s))}function uo(n){const t=n.config.after;if(!t)return[];const e=r=>{const i=Gi(r,n.id),o=i.type;return n.entry.push(Do(i,{id:o,delay:r})),n.exit.push(ro(o)),o};return Object.keys(t).flatMap(r=>{const i=t[r],o=typeof i=="string"?{target:i}:i,a=Number.isNaN(+r)?r:+r,c=e(a);return rt(o).map(l=>({...l,event:c,delay:a}))}).map(r=>{const{delay:i}=r;return{...yt(n,r.event,r),delay:i}})}function yt(n,t,e){const s=ws(e.target),r=e.reenter??!1,i=go(n,s),o={...e,actions:rt(e.actions),guard:e.guard,target:i,source:n,reenter:r,eventType:t,toJSON:()=>({...o,source:`#${n.id}`,target:i?i.map(a=>`#${a.id}`):void 0})};return o}function fo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===ds)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,vt(s).map(r=>yt(n,e,r)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,vt(n.config.onDone).map(s=>yt(n,e,s)))}for(const e of n.invoke){if(e.onDone){const s=`xstate.done.actor.${e.id}`;t.set(s,vt(e.onDone).map(r=>yt(n,s,r)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,vt(e.onError).map(r=>yt(n,s,r)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,vt(e.onSnapshot).map(r=>yt(n,s,r)))}}for(const e of n.after){let s=t.get(e.eventType);s||(s=[],t.set(e.eventType,s)),s.push(e)}return t}function po(n,t){const e=typeof t=="string"?n.states[t]:t?n.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${n.id}`);const s={source:n,actions:!t||typeof t=="string"?[]:rt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function go(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(Ee(e))return n.machine.getStateNodeById(e);const s=e[0]===us;if(s&&!n.parent)return fe(n,e.slice(1));const r=s?n.key+e:e;if(n.parent)try{return fe(n.parent,r)}catch(i){throw new Error(`Invalid transition definition for state node '${n.id}':
14
+ ${i.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function Ss(n){const t=ws(n.config.target);return t?{target:t.map(e=>typeof e=="string"?fe(n.parent,e):e)}:n.parent.initial}function wt(n){return n.type==="history"}function Pn(n){const t=Ns(n);for(const e of t)for(const s of Qt(e,n))t.add(s);return t}function Ns(n){const t=new Set;function e(s){if(!t.has(s)){if(t.add(s),s.type==="compound")e(s.initial.target[0]);else if(s.type==="parallel")for(const r of Wt(s))e(r)}}return e(n),t}function Bt(n,t){if(Ee(t))return n.machine.getStateNodeById(t);if(!n.states)throw new Error(`Unable to retrieve child state '${t}' from '${n.id}'; no child states exist.`);const e=n.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${n.id}'`);return e}function fe(n,t){if(typeof t=="string"&&Ee(t))try{return n.machine.getStateNodeById(t)}catch{}const e=an(t).slice();let s=n;for(;e.length;){const r=e.shift();if(!r.length)break;s=Bt(s,r)}return s}function pe(n,t){if(typeof t=="string"){const r=n.states[t];if(!r)throw new Error(`State '${t}' does not exist on '${n.id}'`);return[n,r]}const e=Object.keys(t),s=e.map(r=>Bt(n,r)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((r,i)=>{const o=Bt(n,i);if(!o)return r;const a=pe(o,t[i]);return r.concat(a)},[]))}function yo(n,t,e,s){const i=Bt(n,t).next(e,s);return!i||!i.length?n.next(e,s):i}function mo(n,t,e,s){const r=Object.keys(t),i=Bt(n,r[0]),o=fn(i,t[r[0]],e,s);return!o||!o.length?n.next(e,s):o}function wo(n,t,e,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=Bt(n,i),c=fn(a,o,e,s);c&&r.push(...c)}return r.length?r:n.next(e,s)}function fn(n,t,e,s){return typeof t=="string"?yo(n,t,e,s):Object.keys(t).length===1?mo(n,t,e,s):wo(n,t,e,s)}function _o(n){return Object.keys(n.states).map(t=>n.states[t]).filter(t=>t.type==="history")}function at(n,t){let e=n;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function Eo(n,t){const e=new Set(n),s=new Set(t);for(const r of e)if(s.has(r))return!0;for(const r of s)if(e.has(r))return!0;return!1}function Is(n,t,e){const s=new Set;for(const r of n){let i=!1;const o=new Set;for(const a of s)if(Eo(je([r],t,e),je([a],t,e)))if(at(r.source,a.source))o.add(a);else{i=!0;break}if(!i){for(const a of o)s.delete(a);s.add(r)}}return Array.from(s)}function bo(n){const[t,...e]=n;for(const s of Qt(t,void 0))if(e.every(r=>at(r,s)))return s}function pn(n,t){if(!n.target)return[];const e=new Set;for(const s of n.target)if(wt(s))if(t[s.id])for(const r of t[s.id])e.add(r);else for(const r of pn(Ss(s),t))e.add(r);else e.add(s);return[...e]}function vs(n,t){const e=pn(n,t);if(!e)return;if(!n.reenter&&e.every(r=>r===n.source||at(r,n.source)))return n.source;const s=bo(e.concat(n.source));if(s)return s;if(!n.reenter)return n.source.machine.root}function je(n,t,e){var r;const s=new Set;for(const i of n)if((r=i.target)!=null&&r.length){const o=vs(i,e);i.reenter&&i.source===o&&s.add(o);for(const a of t)at(a,o)&&s.add(a)}return[...s]}function Ao(n,t){if(n.length!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function Ue(n,t,e,s,r,i){if(!n.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=Is(n,o,a);let l=t;r||([l,a]=vo(l,s,e,c,o,a,i,e.actionExecutor)),l=Dt(l,s,e,c.flatMap(u=>u.actions),i,void 0),l=No(l,s,e,c,o,i,a,r);const h=[...o];l.status==="done"&&(l=Dt(l,s,e,h.sort((u,d)=>d.order-u.order).flatMap(u=>u.exit),i,void 0));try{return a===t.historyValue&&Ao(t._nodes,o)?l:At(l,{_nodes:h,historyValue:a})}catch(u){throw u}}function So(n,t,e,s,r){if(s.output===void 0)return;const i=Ke(r.id,r.output!==void 0&&r.parent?Le(r.output,n.context,t,e.self):void 0);return Le(s.output,n.context,i,e.self)}function No(n,t,e,s,r,i,o,a){let c=n;const l=new Set,h=new Set;Io(s,o,h,l),a&&h.add(n.machine.root);const u=new Set;for(const d of[...l].sort((g,f)=>g.order-f.order)){r.add(d);const g=[];g.push(...d.entry);for(const f of d.invoke)g.push(ao(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(h.has(d)){const f=d.initial.actions;g.push(...f)}if(c=Dt(c,t,e,g,i,d.invoke.map(f=>f.id)),d.type==="final"){const f=d.parent;let m=(f==null?void 0:f.type)==="parallel"?f:f==null?void 0:f.parent,b=m||d;for((f==null?void 0:f.type)==="compound"&&i.push(Ke(f.id,d.output!==void 0?Le(d.output,c.context,t,e.self):void 0));(m==null?void 0:m.type)==="parallel"&&!u.has(m)&&dn(r,m);)u.add(m),i.push(Ke(m.id)),b=m,m=m.parent;if(m)continue;c=At(c,{status:"done",output:So(c,t,e,c.machine.root,b)})}}return c}function Io(n,t,e,s){for(const r of n){const i=vs(r,t);for(const a of r.target||[])!wt(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),e.add(a)),Ot(a,t,e,s);const o=pn(r,t);for(const a of o){const c=Qt(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Ts(s,t,e,c,!r.source.parent&&r.reenter?void 0:i)}}}function Ot(n,t,e,s){var r;if(wt(n))if(t[n.id]){const i=t[n.id];for(const o of i)s.add(o),Ot(o,t,e,s);for(const o of i)Te(o,n.parent,s,t,e)}else{const i=Ss(n);for(const o of i.target)s.add(o),i===((r=n.parent)==null?void 0:r.initial)&&e.add(n.parent),Ot(o,t,e,s);for(const o of i.target)Te(o,n.parent,s,t,e)}else if(n.type==="compound"){const[i]=n.initial.target;wt(i)||(s.add(i),e.add(i)),Ot(i,t,e,s),Te(i,n,s,t,e)}else if(n.type==="parallel")for(const i of Wt(n).filter(o=>!wt(o)))[...s].some(o=>at(o,i))||(wt(i)||(s.add(i),e.add(i)),Ot(i,t,e,s))}function Ts(n,t,e,s,r){for(const i of s)if((!r||at(i,r))&&n.add(i),i.type==="parallel")for(const o of Wt(i).filter(a=>!wt(a)))[...n].some(a=>at(a,o))||(n.add(o),Ot(o,t,e,n))}function Te(n,t,e,s,r){Ts(e,s,r,Qt(n,t))}function vo(n,t,e,s,r,i,o,a){let c=n;const l=je(s,r,i);l.sort((u,d)=>d.order-u.order);let h;for(const u of l)for(const d of _o(u)){let g;d.history==="deep"?g=f=>un(f)&&at(f,u):g=f=>f.parent===u,h??(h={...i}),h[d.id]=Array.from(r).filter(g)}for(const u of l)c=Dt(c,t,e,[...u.exit,...u.invoke.map(d=>_s(d.id))],o,void 0),r.delete(u);return[c,h||i]}function To(n,t){return n.implementations.actions[t]}function Os(n,t,e,s,r,i){const{machine:o}=n;let a=n;for(const c of s){const l=typeof c=="function",h=l?c:To(o,typeof c=="string"?c:c.type),u={context:a.context,event:t,self:e.self,system:e.system},d=l||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!h||!("resolve"in h)){e.actionExecutor({type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",info:u,params:d,exec:h});continue}const g=h,[f,m,b]=g.resolve(e,a,u,d,h,r);a=f,"retryResolve"in g&&(i==null||i.push([g,m])),"execute"in g&&e.actionExecutor({type:g.type,info:u,params:m,exec:g.execute.bind(null,e,m)}),b&&(a=Os(a,t,e,b,r,i))}return a}function Dt(n,t,e,s,r,i){const o=i?[]:void 0,a=Os(n,t,e,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Oe(n,t,e,s){let r=n;const i=[];function o(l,h,u){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:h,snapshot:l,_transitions:u}),i.push(l)}if(t.type===De)return r=At(Hn(r,t,e),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==fs){const l=a,h=Xi(l),u=Wn(l,r);if(h&&!u.length)return r=At(n,{status:"error",error:l.error}),o(r,l,[]),{snapshot:r,microstates:i};r=Ue(u,n,e,a,!1,s),o(r,l,u)}let c=!0;for(;r.status==="active";){let l=c?Oo(r,a):[];const h=l.length?r:void 0;if(!l.length){if(!s.length)break;a=s.shift(),l=Wn(a,r)}r=Ue(l,r,e,a,!1,s),c=r!==h,o(r,a,l)}return r.status!=="active"&&Hn(r,a,e),{snapshot:r,microstates:i}}function Hn(n,t,e){return Dt(n,t,e,Object.values(n.children).map(s=>_s(s)),[],void 0)}function Wn(n,t){return t.machine.getTransitionData(t,n)}function Oo(n,t){const e=new Set,s=n._nodes.filter(un);for(const r of s)t:for(const i of[r].concat(Qt(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||hn(o.guard,n.context,t,n)){e.add(o);break t}}return Is(Array.from(e),new Set(n._nodes),n.historyValue)}function ko(n,t){const e=de(pe(n,t));return As(n,[...e])}function Co(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}const xo=function(t){return gs(t,this.value)},Ro=function(t){return this.tags.has(t)},Mo=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},$o=function(){const{_nodes:t,tags:e,machine:s,getMeta:r,toJSON:i,can:o,hasTag:a,matches:c,...l}=this;return{...l,tags:Array.from(e)}},Po=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function oe(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:As(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:xo,hasTag:Ro,can:Mo,getMeta:Po,toJSON:$o}}function At(n,t={}){return oe({...n,...t},n.machine)}function Ho(n,t){const{_nodes:e,tags:s,machine:r,children:i,context:o,can:a,hasTag:c,matches:l,getMeta:h,toJSON:u,...d}=n,g={};for(const m in i){const b=i[m];g[m]={snapshot:b.getPersistedSnapshot(t),src:b.src,systemId:b._systemId,syncSnapshot:b._syncSnapshot}}return{...d,context:ks(o),children:g}}function ks(n){let t;for(const e in n){const s=n[e];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)t??(t=Array.isArray(n)?n.slice():{...n}),t[e]={xstate$$type:ln,id:s.id};else{const r=ks(s);r!==s&&(t??(t=Array.isArray(n)?n.slice():{...n}),t[e]=r)}}return t??n}function Wo(n,t,e,s,{event:r,id:i,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${r}" }) instead`);const l=typeof r=="function"?r(e,s):r;let h;if(typeof o=="string"){const u=c&&c[o];h=typeof u=="function"?u(e,s):u}else h=typeof o=="function"?o(e,s):o;return typeof h!="number"&&a.push(l),[t,{event:l,id:i,delay:h},void 0]}function Bo(n,t){const{event:e,delay:s,id:r}=t;if(typeof s=="number"){n.defer(()=>{const i=n.self;n.system.scheduler.schedule(i,i,e,s,r)});return}}function Do(n,t){function e(s,r){}return e.type="xstate.raise",e.event=n,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=Wo,e.execute=Bo,e}function Ko(n,{machine:t,context:e},s,r){const i=(o,a)=>{if(typeof o=="string"){const c=cn(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=Ht(c,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:typeof(a==null?void 0:a.input)=="function"?a.input({context:e,event:s,self:n.self}):a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId});return r[l.id]=l,l}else return Ht(o,{id:a==null?void 0:a.id,parent:n.self,syncSnapshot:a==null?void 0:a.syncSnapshot,input:a==null?void 0:a.input,src:o,systemId:a==null?void 0:a.systemId})};return(o,a)=>{const c=i(o,a);return r[c.id]=c,n.defer(()=>{c._processingStatus!==H.Stopped&&c.start()}),c}}function Lo(n,t,e,s,{assignment:r}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},o={context:t.context,event:e.event,spawn:Ko(n,t,e.event,i),self:n.self,system:n.system};let a={};if(typeof r=="function")a=r(o,s);else for(const l of Object.keys(r)){const h=r[l];a[l]=typeof h=="function"?h(o,s):h}const c=Object.assign({},t.context,a);return[At(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children}),void 0,void 0]}function zo(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=Lo,t}const Bn=new WeakMap;function It(n,t,e){let s=Bn.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},Bn.set(n,s)),s[t]}const jo={},zt=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n;class gn{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(us),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Rn(this.config.states,(s,r)=>new gn(s,{_parent:this,_key:r,_machine:this.machine})):jo,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=rt(this.config.entry).slice(),this.exit=rt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=rt(t.tags).slice()}_initialize(){this.transitions=fo(this),this.config.always&&(this.always=vt(this.config.always).map(t=>yt(this,ds,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(zt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(zt),eventType:null})}:void 0,history:this.history,states:Rn(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(zt)})),entry:this.entry.map(zt),exit:this.exit.map(zt),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return It(this,"invoke",()=>rt(this.config.invoke).map((t,e)=>{const{src:s,systemId:r}=t,i=t.id??Mn(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${Mn(this.id,e)}`;return{...t,src:o,id:i,systemId:r,toJSON(){const{onDone:a,onError:c,...l}=t;return{...l,type:"xstate.invoke",src:o,id:i}}}}))}get on(){return It(this,"on",()=>[...this.transitions].flatMap(([e,s])=>s.map(r=>[e,r])).reduce((e,[s,r])=>(e[s]=e[s]||[],e[s].push(r),e),{}))}get after(){return It(this,"delayedTransitions",()=>uo(this))}get initial(){return It(this,"initial",()=>po(this,this.config.initial))}next(t,e){const s=e.type,r=[];let i;const o=It(this,`candidates-${s}`,()=>ho(this,s));for(const a of o){const{guard:c}=a,l=t.context;let h=!1;try{h=!c||hn(c,l,e,t)}catch(u){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
15
+ ${u.message}`)}if(h){r.push(...a.actions),i=a;break}}return i?[i]:void 0}get events(){return It(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const r=t[s];if(r.states)for(const i of r.events)e.add(`${i}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(e=>this.transitions.get(e).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(t)}}const Uo="#";class yn{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:(e==null?void 0:e.actors)??{},actions:(e==null?void 0:e.actions)??{},delays:(e==null?void 0:e.delays)??{},guards:(e==null?void 0:e.guards)??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new gn(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:r,delays:i}=this.implementations;return new yn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const e=ko(this.root,t.value),s=de(pe(this.root,e));return oe({_nodes:[...s],context:t.context||{},children:{},status:dn(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Oe(t,e,s,[]).snapshot}microstep(t,e,s){return Oe(t,e,s,[]).microstates}getTransitionData(t,e){return fn(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:r}=this.config,i=oe({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?Dt(i,e,t,[zo(({spawn:a,event:c,self:l})=>r({spawn:a,input:c.input,self:l}))],s,void 0):i}getInitialSnapshot(t,e){const s=ps(e),r=[],i=this.getPreInitialState(t,s,r),o=Ue([{target:[...Ns(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Oe(o,s,t,r);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=an(t),s=e.slice(1),r=Ee(e[0])?e[0].slice(Uo.length):e[0],i=this.idMap.get(r);if(!i)throw new Error(`Child state node '#${r}' does not exist on machine '${this.id}'`);return fe(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return Ho(t,e)}restoreSnapshot(t,e){const s={},r=t.children;Object.keys(r).forEach(c=>{const l=r[c],h=l.snapshot,u=l.src,d=typeof u=="string"?cn(this,u):u;if(!d)return;const g=Ht(d,{id:c,parent:e.self,syncSnapshot:l.syncSnapshot,snapshot:h,src:u,systemId:l.systemId});s[c]=g});const i=oe({...t,children:s,_nodes:Array.from(de(pe(this.root,t.value)))},this),o=new Set;function a(c,l){if(!o.has(c)){o.add(c);for(const h in c){const u=c[h];if(u&&typeof u=="object"){if("xstate$$type"in u&&u.xstate$$type===ln){c[h]=l[u.id];continue}a(u,l)}}}}return a(i.context,s),i}}function Fo(n,t){return new yn(n,t)}const se=n=>n===!1?!1:n.map(t=>t.serialize()),Go=n=>n===!1?!1:n.serialize(),Zo=n=>n===!1?!1:n.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),re=n=>n===!1?!1:ue(n),Fe=n=>Fo({id:"Untitled",initial:"distribute",context:{currentWind:A.E,oneShotMap:P(!1),missingMap:P(!1),controller:n,genEventID:Cs()},states:{distribute:{on:{NEXT:{target:"drawn"}},entry:{type:"notify_distribution"}},drawn:{entry:{type:"notify_draw"},on:{NEXT:{target:"waiting_user_event_after_drawn",actions:{type:"notify_choice_after_drawn"},description:`可能なアクションとその詳細を通知\\
16
16
  DISCARD の場合は捨てられる牌の一覧`}}},waiting_user_event_after_drawn:{description:"ツモった1ユーザからのレスポンス待ち",on:{TSUMO:{target:"tsumo",guard:"canWin"},REACH:{target:"waiting_reach_acceptance",actions:[{type:"notify_reach"},{type:"notify_choice_for_reach_acceptance"}],guard:{type:"canReach"}},SHO_KAN:{target:"an_sho_kaned"},AN_KAN:{target:"an_sho_kaned"},DISCARD:{target:"discarded",description:"入力に牌が必須",actions:{type:"disable_one_shot_for_me"}},DRAWN_GAME_BY_NINE_ORPHANS:{target:"drawn_game"}}},discarded:{entry:{type:"notify_discard"},on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"},description:`可能なアクションとその詳細を通知\\
17
17
  CHI/PON の場合は鳴ける組み合わせの一覧`}}},tsumo:{exit:[{type:"notify_tsumo"},{type:"notify_end"}],type:"final"},waiting_reach_acceptance:{on:{REACH_ACCEPT:{target:"reached"},RON:{target:"roned",guard:{type:"canWin"}}},description:"リーチに対するアクションは RON か ACCEPT のみである"},waiting_user_event_after_discarded:{description:`最大 4人から choice に対するレスポンスを待つ\\
18
18
  ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
19
- 通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const s=t.currentWind;t.currentWind=gt(s)},notify_distribution:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.initialHands();for(const i of Object.values(A)){const o=$("_____________");o[i]=r[i].toString();const a={id:s,type:"DISTRIBUTE",hands:o,wind:i,doraMarker:t.controller.wall.doraMarkers[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},s)=>{const r=t.currentWind,i=t.controller.hand(r).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:r,drawerInfo:{wind:r,tile:i.toString()},choices:{TSUMO:se(t.controller.doWin(r,i,{oneShot:t.oneShotMap[r],replacementWin:s==null?void 0:s.replacementWin})),REACH:Yo(t.controller.doReach(r)),AN_KAN:ne(t.controller.doAnKan(r)),SHO_KAN:ne(t.controller.doShoKan(r)),DISCARD:t.controller.doDiscard(r).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(r)}};t.controller.emit(a),t.controller.pollReplies(o,[r])},notify_choice_after_discarded:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.river.lastTile,i=r.t.clone({add:y.HORIZONTAL});for(const o of Object.values(A)){const a={id:s,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:r.w,tile:r.t.toString()},choices:{RON:se(t.controller.doWin(o,i,{discardedBy:r.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:ne(t.controller.doPon(o,r.w,i)),CHI:ne(t.controller.doChi(o,r.w,i)),DAI_KAN:Xo(t.controller.doDaiKan(o,r.w,i))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_choice_after_called:({context:t,event:e},s)=>{const r=t.genEventID(),i=t.currentWind;let o=t.controller.doDiscard(i);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof Z||a instanceof V)&&(o=t.controller.doDiscard(i,a));const c={id:r,type:"CHOICE_AFTER_CALLED",wind:i,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(r,[i])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.river.lastTile,i=r.t.clone({add:y.HORIZONTAL});for(const o of Object.values(A)){const a={id:s,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:r.w,tile:i.toString()},choices:{RON:se(t.controller.doWin(o,i,{discardedBy:r.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_choice_for_chankan:({context:t,event:e})=>{S(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.block.tiles[0].clone({remove:y.HORIZONTAL});for(const i of Object.values(A)){const o=t.controller.doWin(i,e.block.tiles[0].clone({remove:y.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[i],missingRon:t.missingMap[e.iam]}),a={id:s,type:"CHOICE_FOR_CHAN_KAN",wind:i,callerInfo:{wind:e.iam,tile:r.toString()},choices:{RON:e.type=="SHO_KAN"?se(o):!1}};a.choices.RON&&(t.missingMap[i]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_call:({context:t,event:e})=>{S(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.iam;t.currentWind=r;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{S(e.type=="DISCARD",`unexpected event ${e.type}`);const s=t.genEventID(),r=t.currentWind,i=e.tile;for(const o of Object.values(A)){const a={id:s,type:"DISCARD",iam:r,wind:o,tile:i.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},s)=>{const r=t.genEventID(),i=s==null?void 0:s.action;let o;i=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(A)){let l=new w(p.BACK,0,[y.TSUMO]);c==a&&(l=o);const u={id:r,type:"DRAW",subType:i,iam:a,wind:c,tile:l.toString()};t.controller.emit(u)}t.controller.next()},notify_ron:({context:t,event:e})=>{S(e.type=="RON");const s=t.genEventID(),r=e.iam;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:je(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{S(e.type=="TSUMO",`unexpected event ${e.type}`);const s=t.genEventID(),r=t.currentWind;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,lastTile:t.controller.hand(r).drawn.toString(),ret:je(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{S(e.type=="REACH",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.iam,i=e.tile.clone({add:y.HORIZONTAL});t.oneShotMap[r]=!0;for(const o of Object.values(A)){const a={id:s,type:e.type,iam:r,wind:o,tile:i.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{S(e.type=="REACH_ACCEPT");const s=t.genEventID();for(const r of Object.values(A)){const i={id:s,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:r};t.controller.emit(i)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const s=t.genEventID();if(e.type=="AN_KAN"){const r=t.controller.wall.openDoraMarker();for(const i of Object.values(A)){const o={id:s,type:"NEW_DORA",wind:i,doraMarker:r.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const s of Object.values(A))t.oneShotMap[s]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const s=t.genEventID(),r=$("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){r[e.iam]=t.controller.hand(e.iam).toString();for(const i of Object.values(A)){const o={id:s,type:"END_GAME",subType:"NINE_TILES",wind:i,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:$(0),hands:r};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const i=e.iam==A.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(A)){r[e.iam]=t.controller.hand(e.iam).toString();const c={id:s,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:i,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:r};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const i=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(A)){const a={id:s,type:"END_GAME",subType:i,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:$(0),hands:$("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const i=[];for(const l of Object.values(A)){const u=t.controller.hand(l);new Yt(u).calc()==0&&(i.push(l),r[l]=u.toString())}const o=i.length==0||i.length==4,a=$(0);for(const l of Object.values(A))i.includes(l)?a[l]+=o?0:3e3/i.length:a[l]-=o?0:3e3/(4-i.length);const c=i.length==4||a[A.E]>0;for(const l of Object.values(A)){const u={id:s,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:r};t.controller.emit(u)}}}}},actors:{},guards:{canChi:({context:t,event:e},s)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},s)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},s)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},s)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},s)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function ks(n=0){let t=n;return()=>(t++).toString()}class mt{constructor(t){_(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});_(this,"backup");_(this,"openedDoraCount",1);this.init(t),this.backup=mt.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),w.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return w.from(this.walls.drawable.pop())}openDoraMarker(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,w.from(this.walls.doraMarkers[this.openedDoraCount-1])}get doraMarkers(){return this.walls.doraMarkers.slice(0,this.openedDoraCount).map(w.from)}get blindDoraMarkers(){return this.walls.blindDoraMarkers.slice(0,this.openedDoraCount).map(w.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=$("");for(let e=0;e<3;e++)for(const s of Object.values(A))for(let r=0;r<4;r++)t[s]+=this.draw().toString();for(const e of Object.values(A))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=mt.clone(t);return}else{for(let e of Object.values(p)){if(e==p.BACK)continue;const s=e==p.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let r=0;r<4;r++)for(let i of s){let o=new w(e,i);e!=p.Z&&r==3&&i==5&&(o=o.clone({add:y.RED})),this.walls.drawable.push(o.toString())}}sn(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.blindDoraMarkers.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraMarkers.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraMarkers:t.doraMarkers.concat(),blindDoraMarkers:t.blindDoraMarkers.concat(),replacement:t.replacement.concat()}}}class Qt{constructor(t,e){_(this,"wall",new mt);_(this,"playerIDs");_(this,"actor",Pt(Ue(this),{}));_(this,"observer");_(this,"handlers",{});_(this,"mailBox",{});_(this,"histories",[]);_(this,"debugMode");this.debugMode=(e==null?void 0:e.debug)??!1,this.handlers=t.reduce((o,a)=>(o[a.id]=a.handler,o),{}),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const s=cs();this.observer=new Cs(s),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const r=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Zt(r);const i=(e==null?void 0:e.shuffle)==!1?this.playerIDs:sn([...this.playerIDs]);this.observer.placeManager=new Vt({[i[0]]:A.E,[i[1]]:A.S,[i[2]]:A.W,[i[3]]:A.N})}boardParams(t){let s=this.hand(t).reached?1:void 0;if(s){const r=this.river.discards(t);s=r.length==0||r.length==1&&r[0].t.has(y.HORIZONTAL)?2:1}return{doraMarkers:this.observer.doraMarkers,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:s}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const s=t.iam;t.wind==s?this.observer.eventHandler.emit(t):s==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const s=this.mailBox[t];if(s==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(s.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${s.length}`);if(e.length==0){console.warn("no events to handle");return}const r=s[0];if(r.type=="CHOICE_AFTER_DISCARDED"){const i=rs(s);if(i.events.length==0){this.actor.send({type:""});return}const o=i.events[0];switch(i.type){case"RON":S(o.choices.RON,"ron choice is none"),this.actor.send({type:i.type,iam:o.wind,ret:zt(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":S(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:i.type,iam:o.wind,block:Y.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[i.type];S(a,`${i.type} choice is none`),S(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const c=V.deserialize(a[0]);this.actor.send({type:i.type,iam:o.wind,block:c})}}else if(r.type=="CHOICE_AFTER_DRAWN"){const i=is(s);S(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const o=i.events[0],a=o.wind;switch(i.type){case"TSUMO":S(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:i.type,ret:zt(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[i.type];S(c,`${i.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[i.type];S(l,`${i.type} choice is none`),this.actor.send({type:i.type,tile:w.from(l[0]).clone({remove:y.TSUMO}),iam:a});break;case"AN_KAN":{const u=o.choices[i.type];S(u,`${i.type} choice is none`),this.actor.send({type:i.type,block:R.from(u[0].tiles),iam:a});break}case"SHO_KAN":{const u=o.choices[i.type];S(u,`${i.type} choice is none`),this.actor.send({type:i.type,block:D.from(u[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(r.type=="CHOICE_AFTER_CALLED"){S(r.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(r,null,2)} ${this.hand(r.wind).toString()}`);const i=r.wind,o=w.from(r.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:i})}else if(r.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const i=s.filter(a=>(S(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(i.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:w.from(r.reacherInfo.tile),wind:r.reacherInfo.wind}});return}const o=i[0];this.actor.send({type:"RON",iam:o.wind,ret:zt(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:w.from(o.reacherInfo.tile)}});return}else if(r.type=="CHOICE_FOR_CHAN_KAN"){const i=s.filter(a=>a.choices.RON!==!1);if(i.length==0){this.actor.send({type:""});return}const o=i[0];S(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:zt(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:w.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${r.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,s=Object.keys(t.players),r={emit:a=>{},on:a=>{}},i=s.map(a=>({id:a,handler:r})),o=new Qt(i);return o.playerIDs=s,o.mailBox=e,o.observer.placeManager=new Vt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Zt(t.scores),o.wall=new mt(t.wall),o}start(){this.actor.subscribe(s=>{console.debug("State:",s.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new mt,this.observer.applied={},this.mailBox={},this.actor=Pt(Ue(this)),!this.placeManager.is(k.W1););}finalResult(t,e){const s=this.hand(e),r=s.reached?this.wall.blindDoraMarkers:void 0,i=new Pe(s,{...t.boardContext,sticks:this.placeManager.sticks,blindDoraMarkers:r}).calc(t.hand);return S(i),i}doWin(t,e,s){if(e==null)return!1;let r=this.hand(t);const i=this.boardParams(t);if(r.drawn==null){if(s==null)throw new Error("should ron but params == null");if(s.discardedBy==t||s.missingRon)return!1;r=r.clone(),i.ronWind=s.discardedBy,i.finalDiscardWin=!this.wall.canDraw,i.quadWin=s.quadWin,r.inc([e])}else i.finalWallWin=!this.wall.canDraw,i.replacementWin=s==null?void 0:s.replacementWin;i.oneShotWin=s==null?void 0:s.oneShot;const o=new ss(r),a=new Pe(r,i),c=o.calc(e),l=a.calc(...c);if(!l||l.points.length==0)return!1;if(r.draw==null){const u=$t.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(h=>u.some(d=>d.equals(h.t))))return!1}return l}doPon(t,e,s){if(s==null||t==e)return!1;const r=this.hand(t);if(r.reached||r.hands.length<3||r.get(s.t,s.n)<2)return!1;const i=s.clone({removeAll:!0}),o=Oe(t,e,b.PON),a=[],c=new V([i,i,i]).clone({replace:{idx:o,tile:s.clone({add:y.HORIZONTAL})}});let l=c;C(s)&&s.has(y.RED)&&(l=c.clone({replace:{idx:o,tile:i.clone({add:[y.RED,y.HORIZONTAL]})}}));const u=o%2+1;if(C(s)&&r.get(s.t,0)>0&&(l=c.clone({replace:{idx:u,tile:i.clone({add:y.RED})}})),a.push(l),C(i)&&r.get(i.t,5)==3){const h=c.clone({replace:{idx:u,tile:i}});a.push(h)}return a}doChi(t,e,s){if(s==null||!s.isNum()||gt(e)!=t)return!1;const r=this.hand(t);if(r.reached||r.hands.length<3)return!1;const i=s.clone({remove:y.TSUMO,add:[y.HORIZONTAL]}),o=[];i.n-2>=1&&r.get(s.t,i.n-2)>0&&r.get(s.t,i.n-1)>0&&o.push(new Z([i,new w(s.t,i.n-1),new w(s.t,i.n-2)])),i.n+2<=9&&r.get(s.t,i.n+1)>0&&r.get(s.t,i.n+2)>0&&o.push(new Z([i,new w(s.t,i.n+1),new w(s.t,i.n+2)])),i.n-1>=1&&i.n+1<=9&&r.get(s.t,i.n-1)>0&&r.get(s.t,i.n+1)>0&&o.push(new Z([i,new w(s.t,i.n-1),new w(s.t,i.n+1)]));for(let d=0;d<o.length;d++){const g=o[d],f=this.cannotDiscardTile(g),m=[];for(const O of f){const M=r.get(O.t,O.n);for(let Et=0;Et<M;Et++)m.push(O.clone({remove:y.RED}))}const E=r.dec([...m,g.tiles[1],g.tiles[2]]),N=r.hands.length==0;r.inc(E),N&&o.splice(d,1)}if(o.length==0)return!1;const h=r.get(s.t,0)>0?this.redPattern(o):[];return h.length>0&&r.get(s.t,5)==1?h:[...o,...h]}redPattern(t){return t.length==0?[]:t.filter(s=>C(s.tiles[1])||C(s.tiles[2])).map(s=>{if(C(s.tiles[1])){const r=s.tiles[1].clone({add:y.RED});return s.clone({replace:{idx:1,tile:r}})}else if(C(s.tiles[2])){const r=s.tiles[2].clone({add:y.RED});return s.clone({replace:{idx:2,tile:r}})}}).filter(s=>s!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new Yt(e).calc()>0?!1:$t.calcCandidates(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const s=this.hand(t).hands;if(e==null)return s;if(e instanceof V)return s.filter(o=>!o.equals(e.tiles[0]));const r=this.cannotDiscardTile(e),i=s.filter(o=>!r.some(a=>o.equals(a)));return S(i.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${r}, block-chi: ${e}`),i}cannotDiscardTile(t){const e=t.tiles[0],s=t.tiles[1].n;return s!=1&&e.n-2==s?[new w(e.t,e.n-3),e]:s!=8&&e.n+1==s?[new w(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),s=[];if(e.reached)return!1;for(const[r,i]of L())if(e.get(r,i)==4){const o=new w(r,i),a=[o,o,o,o];C(o)&&(a[1]=o.clone({add:y.RED})),s.push(new R(a))}if(s.length==0)return!1;for(const r of s)S(r.tiles.filter(i=>i.has(y.HORIZONTAL)).length==0,`h op ${r.toString()}`);return s}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const s=e.called.filter(i=>i instanceof V);if(s.length==0)return!1;const r=[];for(const i of s){const o=i.tiles[0].clone({removeAll:!0,add:y.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=C(o)&&e.get(o.t,0)>0?o.clone({add:y.RED}):o;r.push(new D([...i.tiles,a]))}}if(r.length==0)return!1;for(const i of r)S(i.tiles.filter(o=>o.has(y.HORIZONTAL)).length==2,`h op ${i.toString()}`);return r}doDaiKan(t,e,s){const r=this.hand(t);if(r.reached||t==e)return!1;const i=s.clone({removeAll:!0});if(r.get(i.t,i.n)!=3)return!1;const o=Oe(t,e,b.DAI_KAN);let a=new Y([i,i,i,i]).clone({replace:{idx:o,tile:i.clone({add:y.HORIZONTAL})}});if(C(s)&&s.has(y.RED))a=a.clone({replace:{idx:o,tile:i.clone({add:[y.HORIZONTAL,y.RED]})}});else if(C(s)&&!s.has(y.RED)){S(r.get(s.t,0)>0,`hand does not have red tile: ${r.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:i.clone({add:y.RED})}})}return S(a.tiles.filter(c=>c.has(y.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let s=0;for(const r of Object.values(p)){if(r==p.BACK)continue;const i=r==p.Z?xt:G;for(const o of i)e.get(r,o)>0&&s++}return s>=9}initialHands(){return this.wall.initialHands()}}class bt extends me{isBackHand(){for(const t of Object.values(p))if(t!=p.BACK&&this.sum(t)>0)return!1;return this.sum(p.BACK)>0}clone(){const t=new bt(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new w(p.BACK,0))),[...t]):super.dec(t)}}class yn{constructor(t,e){_(this,"id");_(this,"river",new rn);_(this,"placeManager",new Vt({}));_(this,"scoreManager",new Zt({}));_(this,"hands",$(new bt("")));_(this,"counter",new ls);_(this,"doraMarkers",[]);_(this,"eventHandler");this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=w.from(t.doraMarker);this.setHands(t),this.placeManager=new Vt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Zt(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(const r of Object.values(A))r==t.wind&&this.counter.dec(...this.hand(r).hands);break;case"DRAW":{const r=w.from(t.tile);this.hands[t.iam].draw(r),this.counter.dec(r);break}case"DISCARD":{const r=w.from(t.tile);if(this.river.discard(r,t.iam),this.hands[t.iam].discard(r),t.iam!=t.wind){this.counter.dec(r),this.counter.addTileToSafeMap(r,t.iam);for(const i of Object.values(A))this.hand(i).reached&&this.counter.addTileToSafeMap(r,i)}break}case"PON":case"CHI":case"DAI_KAN":{const r=T.deserialize(t.block);this.hands[t.iam].call(r),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...r.tiles.filter(i=>!i.has(y.HORIZONTAL)));break}case"SHO_KAN":{const r=D.from(t.block.tiles);this.hands[t.iam].kan(r),t.iam!=t.wind&&this.counter.dec(r.tiles.filter(i=>i.has(y.HORIZONTAL))[0]);break}case"AN_KAN":{const r=R.from(t.block.tiles);this.hands[t.iam].kan(r),t.iam!=t.wind&&this.counter.dec(...r.tiles.filter(i=>!i.has(y.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const r=w.from(t.tile);if(this.river.discard(r,t.iam),this.hands[t.iam].discard(r),t.iam!=t.wind){this.counter.dec(r),this.counter.addTileToSafeMap(r,t.iam);for(const i of Object.values(A))this.hand(i).reached&&this.counter.addTileToSafeMap(r,i)}break}case"REACH_ACCEPTED":const s=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(s),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const r=w.from(t.doraMarker);this.doraMarkers.push(r),this.counter.dec(r);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const r=this.placeManager.playerMap;this.scoreManager.update(t.deltas,r),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const r=this.placeManager.playerMap;this.scoreManager.update(t.deltas,r),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class Cs extends yn{constructor(e){super("observer",e);_(this,"applied",{});this.counter.disable=!0,this.hands=$(new bt("_____________"))}setHands(e){this.hands[e.wind]=new bt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let s=!0;for(const r of Object.values(A))s&&(s=this.hand(r).get(p.BACK,0)==0);if(!s)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const r of Object.values(A))console.debug(`${this.placeManager.playerID(r)}(${r})`,`init hand: ${this.hand(r).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`draw: ${this.hand(e.iam).drawn}`,`hand: ${this.hand(e.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`discard: ${e.tile.toString()}`,`hand: ${this.hand(e.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`call: ${e.block.tiles}`,`hand: ${this.hand(e.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`reach: ${e.tile}`,`hand: ${this.hand(e.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`ron/tsumo: ${JSON.stringify(e.ret,null,2)}`,`hand: ${this.hand(e.iam).toString()}`);break;case"END_GAME":for(const r of Object.values(A))console.debug(`${this.placeManager.playerID(r)}(${pe(r)})`,`end hand: ${this.hand(r).toString()}`);console.debug("END_GAME",e.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Ft extends yn{constructor(e,s){super(e,s);_(this,"river",new rn);_(this,"doras",[]);this.eventHandler.on(r=>this.handleEvent(r))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const s of Object.values(A))this.hands[s]=new bt(e.hands[s])}handleDiscard(e){const s=Object.values(A).filter(u=>u==this.myWind?!1:this.hand(u).reached),r=new Yt(this.hand(this.myWind)).calc();if(s.length>0&&r>=2)return Ot.selectTile(this.counter,s,e);const i=$t.calcCandidates(this.hand(this.myWind),e),a=Jt.calcPlayerCandidates(this.counter,i).sort((u,h)=>h.sum-u.sum),c=a.filter(u=>u.sum==a[0].sum);return Jt.selectMinPriority(this.counter,c,this.doras).tile}handleEvent(e){switch(e.type){case"CHOICE_AFTER_DISCARDED":e.choices.CHI=!1,e.choices.DAI_KAN=!1,e.choices.PON=!1,this.eventHandler.emit(e);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(e.choices.DISCARD){const s=this.handleDiscard(e.choices.DISCARD.map(w.from));e.choices.DISCARD=[s.toString()]}this.eventHandler.emit(e);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(e);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(e);break;default:super.handleEvent(e)}}}class qo{constructor(t){_(this,"index",0);_(this,"histories",[]);this.histories=JSON.parse(t)}next(){S(this.index<this.histories.length),this.index++}prev(){this.index--,S(this.index<0)}start(){Qt.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Qo=n=>{const[t,e]=Ut(),[s,r]=Ut(),[i,o]=Ut(),[a,c]=Ut(),l=["player-1","player-2","player-3","player-4"],u=n==null?void 0:n.playerInjection,h=(u==null?void 0:u.p1)??Ft,d=(u==null?void 0:u.p2)??Ft,g=(u==null?void 0:u.p3)??Ft,f=(u==null?void 0:u.p4)??Ft,m=new h(l[0],e),E=new d(l[1],r),N=new g(l[2],o),O=new f(l[3],c),M=[{handler:t,id:l[0]},{handler:s,id:l[1]},{handler:i,id:l[2]},{handler:a,id:l[3]}];return{c:new Qt(M,{debug:n==null?void 0:n.debug,shuffle:n==null?void 0:n.shuffle}),p1:m,p2:E,p3:N,p4:O}},ut=(n,t)=>{let s=1;for(let r of t)r.equals(n)&&(s*=2);return s};class Jt{static calcPlayerCandidates(t,e){let s=[];for(let r of e){let i=0,o=[];for(let a of r.candidates)o.push({tile:a.clone(),n:t.get(a)}),i+=t.get(a);s.push({sum:i,tile:r.tile,candidates:o,shanten:r.shanten})}return s}static selectMinPriority(t,e,s){S(e.length>0);let r=0,i=0;for(let o=0;o<e.length;o++){const a=Jt.calcPriority(t,e[o],s);a<r&&(r=a,i=o)}return e[i]}static calcPriority(t,e,s){const r=e.tile;let i=0;if(r.t==p.Z)return i=t.get(r),(r.n==5||r.n==6||r.n==7)&&(i*=2),i*ut(r,s);{const o=t.get(r);i+=o*ut(r,s);const a=t.get(new w(r.t,r.n+1)),c=t.get(new w(r.t,r.n+2)),l=t.get(new w(r.t,r.n-1)),u=t.get(new w(r.t,r.n-2)),h=r.n-2>0?Math.min(l,u):0,d=r.n+2<=9?Math.min(a,c):0,g=r.n-1>=1&&r.n+1<=9?Math.min(a,l):0,f=Math.max(h,g),m=Math.max(g,d);return i+=o*ut(r,s),i+=h*ut(new w(r.t,r.n-2),s),i+=d*ut(new w(r.t,r.n+2),s),i+=f*ut(new w(r.t,r.n-1),s),i+=m*ut(new w(r.t,r.n+1),s),r.n==0,i}}}class Ot{static selectTile(t,e,s){S(e.length>0&&s.length>0);let r=s[0],i=Number.POSITIVE_INFINITY;for(let o of s){const a=Ot.rank(t,e,o);a<i&&(r=o,i=a)}return r}static rank(t,e,s){let r=0;const i=s.isNum()?Ot.rankN:Ot.rankZ;for(let o of e){const a=i(t,o,s);r<a&&(r=a)}return r}static rankZ(t,e,s){if(s.t!=p.Z)throw new Error(`expected TYPE.Z but ${s.toString()}`);if(t.isSafeTile(s.t,s.n,e))return 0;const r=t.get(s);return Math.min(r,3)}static rankN(t,e,s){if(!s.isNum())throw new Error(`expected TYPE.NUMBER but ${s.toString()}`);const r=s.n,i=s.t;if(t.isSafeTile(i,r,e))return 0;if(r==1)return t.isSafeTile(i,4,e)?3:6;if(r==9)return t.isSafeTile(i,6,e)?3:6;if(r==2||r==8)return t.isSafeTile(i,5,e)?4:8;if(r==3)return t.isSafeTile(i,6,e)?5:8;if(r==7)return t.isSafeTile(i,4,e)?5:8;const o=t.isSafeTile(i,r-3,e),a=t.isSafeTile(i,r+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=bt;exports.BLOCK=b;exports.BaseActor=yn;exports.Block=T;exports.BlockAnKan=R;exports.BlockCalculator=ss;exports.BlockChi=Z;exports.BlockDaiKan=Y;exports.BlockHand=kt;exports.BlockIsolated=Ve;exports.BlockOther=Je;exports.BlockPair=H;exports.BlockPon=V;exports.BlockRun=Q;exports.BlockShoKan=D;exports.BlockThree=z;exports.Controller=Qt;exports.Counter=ls;exports.DoubleCalculator=Pe;exports.Efficiency=$t;exports.FONT_FAMILY=Fe;exports.G=v;exports.Hand=me;exports.INPUT_SEPARATOR=q;exports.Image=Qe;exports.ImageHelper=nn;exports.Mark=ot;exports.MeasureText=Bs;exports.MyG=ci;exports.MyImage=li;exports.MyRect=hi;exports.MySVG=ai;exports.MyText=di;exports.MyUse=ui;exports.N19=G;exports.NZ=xt;exports.OP=y;exports.Observer=Cs;exports.Parser=W;exports.PlaceManager=Vt;exports.Player=Ft;exports.PlayerEfficiency=Jt;exports.ROUND=k;exports.ROUND_MAP=Ge;exports.Rect=tn;exports.Replayer=qo;exports.RiskRank=Ot;exports.River=rn;exports.STICK_CONTEXT=Ie;exports.SVG=Vn;exports.ScoreManager=Zt;exports.ShantenCalculator=Yt;exports.Svg=Zn;exports.Symbol=en;exports.TABLE_CONTEXT=Bn;exports.TILE_CONTEXT=nt;exports.TYPE=p;exports.Text=yt;exports.Tile=w;exports.Use=ye;exports.WIND=A;exports.WIND_MAP=fe;exports.Wall=mt;exports.callBlockIndex=Oe;exports.convertInput=ns;exports.createControllerMachine=Ue;exports.createEventEmitter=cs;exports.createEventPipe=Ut;exports.createHand=Tt;exports.createLocalGame=Qo;exports.createTable=Yn;exports.createWindMap=$;exports.deserializeWinResult=zt;exports.drawBlocks=bi;exports.drawTable=Oi;exports.forHand=L;exports.incrementalIDGenerator=ks;exports.isNum5=C;exports.nextRound=Gt;exports.nextWind=gt;exports.optimizeSVG=Ei;exports.parse=ts;exports.parseTableInput=es;exports.prevRound=Fs;exports.prevWind=pe;exports.prioritizeDiscardedEvents=rs;exports.prioritizeDrawnEvents=is;exports.shuffle=sn;exports.sortCalledTiles=Dn;exports.tileSortFunc=Xt;
19
+ 通知する choice がない場合、controller が\\*で遷移させる`,on:{RON:{target:"roned",guard:"canWin"},PON:{target:"poned",guard:"canPon"},CHI:{target:"chied",guard:"canChi"},DAI_KAN:{target:"dai_kaned"},"*":{target:"wildcard_after_discarded"}}},reached:{on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"}}},entry:{type:"notify_reach_accepted"}},roned:{exit:[{type:"notify_ron"},{type:"notify_end"}],type:"final"},poned:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called"}}},entry:[{type:"notify_call"},{type:"disable_none_shot"}]},chied:{on:{NEXT:{target:"waiting_discard_event",actions:{type:"notify_choice_after_called",params:{action:"chi"}}}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},wildcard_after_discarded:{exit:[],always:[{target:"drawn_game",guard:"cannotContinue"},{target:"drawn",actions:[{type:"updateNextWind"}]}]},waiting_discard_event:{description:"鳴いたユーザからの DISCARD イベントを待つ",on:{DISCARD:{target:"discarded"}}},dai_kaned:{on:{NEXT:{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]}},entry:[{type:"notify_call"},{type:"disable_one_shot"}]},an_sho_kaned:{always:{target:"waiting_chankan_event"},entry:[{type:"notify_call"},{type:"disable_one_shot"},{type:"notify_new_dora_if_needed"},{type:"notify_choice_for_chankan"}]},waiting_chankan_event:{description:"チャンカンを待つ",on:{"*":{target:"waiting_user_event_after_drawn",actions:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}]},RON:{target:"roned",guard:{type:"canWin"}}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const s=t.currentWind;t.currentWind=_t(s)},notify_distribution:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.initialHands();for(const i of Object.values(A)){const o=P("_____________");o[i]=r[i].toString();const a={id:s,type:"DISTRIBUTE",hands:o,wind:i,doraIndicator:t.controller.wall.doraIndicators[0].toString(),sticks:t.controller.placeManager.sticks,round:t.controller.placeManager.round,players:t.controller.playerIDs,places:t.controller.placeManager.playerMap,scores:t.controller.scoreManager.summary};t.controller.emit(a)}t.controller.next()},notify_choice_after_drawn:({context:t,event:e},s)=>{const r=t.currentWind,i=t.controller.hand(r).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:r,drawerInfo:{wind:r,tile:i.toString()},choices:{TSUMO:re(t.controller.doWin(r,i,{oneShot:t.oneShotMap[r],replacementWin:s==null?void 0:s.replacementWin})),REACH:Zo(t.controller.doReach(r)),AN_KAN:se(t.controller.doAnKan(r)),SHO_KAN:se(t.controller.doShoKan(r)),DISCARD:t.controller.doDiscard(r).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(r)}};t.controller.emit(a),t.controller.pollReplies(o,[r])},notify_choice_after_discarded:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.river.lastTile,i=r.t.clone({add:y.HORIZONTAL});for(const o of Object.values(A)){const a={id:s,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:r.w,tile:r.t.toString()},choices:{RON:re(t.controller.doWin(o,i,{discardedBy:r.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:se(t.controller.doPon(o,r.w,i)),CHI:se(t.controller.doChi(o,r.w,i)),DAI_KAN:Go(t.controller.doDaiKan(o,r.w,i))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_choice_after_called:({context:t,event:e},s)=>{const r=t.genEventID(),i=t.currentWind;let o=t.controller.doDiscard(i);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof J||a instanceof Y)&&(o=t.controller.doDiscard(i,a));const c={id:r,type:"CHOICE_AFTER_CALLED",wind:i,choices:{DISCARD:o.map(l=>l.toString())}};t.controller.emit(c),t.controller.pollReplies(r,[i])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const s=t.genEventID(),r=t.controller.river.lastTile,i=r.t.clone({add:y.HORIZONTAL});for(const o of Object.values(A)){const a={id:s,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:r.w,tile:i.toString()},choices:{RON:re(t.controller.doWin(o,i,{discardedBy:r.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_choice_for_chankan:({context:t,event:e})=>{I(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.block.tiles[0].clone({remove:y.HORIZONTAL});for(const i of Object.values(A)){const o=t.controller.doWin(i,e.block.tiles[0].clone({remove:y.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[i],missingRon:t.missingMap[e.iam]}),a={id:s,type:"CHOICE_FOR_CHAN_KAN",wind:i,callerInfo:{wind:e.iam,tile:r.toString()},choices:{RON:e.type=="SHO_KAN"?re(o):!1}};a.choices.RON&&(t.missingMap[i]=!0),t.controller.emit(a)}t.controller.pollReplies(s,Object.values(A))},notify_call:({context:t,event:e})=>{I(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.iam;t.currentWind=r;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{I(e.type=="DISCARD",`unexpected event ${e.type}`);const s=t.genEventID(),r=t.currentWind,i=e.tile;for(const o of Object.values(A)){const a={id:s,type:"DISCARD",iam:r,wind:o,tile:i.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},s)=>{const r=t.genEventID(),i=s==null?void 0:s.action;let o;i=="kan"?o=t.controller.wall.kan():o=t.controller.wall.draw();const a=t.currentWind;t.controller.hand(a).reached||(t.missingMap[a]=!1);for(const c of Object.values(A)){let l=new w(p.BACK,0,[y.TSUMO]);c==a&&(l=o);const h={id:r,type:"DRAW",subType:i,iam:a,wind:c,tile:l.toString()};t.controller.emit(h)}t.controller.next()},notify_ron:({context:t,event:e})=>{I(e.type=="RON");const s=t.genEventID(),r=e.iam;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:ue(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{I(e.type=="TSUMO",`unexpected event ${e.type}`);const s=t.genEventID(),r=t.currentWind;for(const i of Object.values(A)){const o={id:s,type:e.type,iam:r,wind:i,lastTile:t.controller.hand(r).drawn.toString(),ret:ue(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{I(e.type=="REACH",`unexpected event ${e.type}`);const s=t.genEventID(),r=e.iam,i=e.tile.clone({add:y.HORIZONTAL});t.oneShotMap[r]=!0;for(const o of Object.values(A)){const a={id:s,type:e.type,iam:r,wind:o,tile:i.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{I(e.type=="REACH_ACCEPT");const s=t.genEventID();for(const r of Object.values(A)){const i={id:s,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:r};t.controller.emit(i)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const s=t.genEventID();if(e.type=="AN_KAN"){const r=t.controller.wall.openDoraIndicator();for(const i of Object.values(A)){const o={id:s,type:"NEW_DORA",wind:i,doraIndicator:r.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const s of Object.values(A))t.oneShotMap[s]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const s=t.genEventID(),r=P("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){r[e.iam]=t.controller.hand(e.iam).toString();for(const i of Object.values(A)){const o={id:s,type:"END_GAME",subType:"NINE_TILES",wind:i,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:r};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const i=e.iam==A.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(A)){r[e.iam]=t.controller.hand(e.iam).toString();const c={id:s,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:i,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:r};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const i=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(A)){const a={id:s,type:"END_GAME",subType:i,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:P(0),hands:P("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const i=[];for(const l of Object.values(A)){const h=t.controller.hand(l);new qt(h).calc()==0&&(i.push(l),r[l]=h.toString())}const o=i.length==0||i.length==4,a=P(0);for(const l of Object.values(A))i.includes(l)?a[l]+=o?0:3e3/i.length:a[l]-=o?0:3e3/(4-i.length);const c=i.length==4||a[A.E]>0;for(const l of Object.values(A)){const h={id:s,type:"END_GAME",subType:"DRAWN_GAME",wind:l,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:r};t.controller.emit(h)}}}}},actors:{},guards:{canChi:({context:t,event:e},s)=>e.type=="CHI"?!!t.controller.doChi(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canChi receive ${e.type}`),!1),canPon:({context:t,event:e},s)=>e.type=="PON"?!!t.controller.doPon(e.iam,t.controller.river.lastTile.w,t.controller.river.lastTile.t):(console.error(`guards.canPon receive ${e.type}`),!1),canWin:({context:t,event:e},s)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},s)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},s)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function Cs(n=0){let t=n;return()=>(t++).toString()}class bt{constructor(t){E(this,"walls",{replacement:[],dead:[],doraIndicators:[],hiddenDoraIndicators:[],drawable:[]});E(this,"backup");E(this,"openedDoraCount",1);this.init(t),this.backup=bt.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),w.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return w.from(this.walls.drawable.pop())}openDoraIndicator(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,w.from(this.walls.doraIndicators[this.openedDoraCount-1])}get doraIndicators(){return this.walls.doraIndicators.slice(0,this.openedDoraCount).map(w.from)}get hiddenDoraIndicators(){return this.walls.hiddenDoraIndicators.slice(0,this.openedDoraCount).map(w.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}initialHands(){const t=P("");for(let e=0;e<3;e++)for(const s of Object.values(A))for(let r=0;r<4;r++)t[s]+=this.draw().toString();for(const e of Object.values(A))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=bt.clone(t);return}else{for(let e of Object.values(p)){if(e==p.BACK)continue;const s=e==p.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let r=0;r<4;r++)for(let i of s){let o=new w(e,i);e!=p.Z&&r==3&&i==5&&(o=o.clone({add:y.RED})),this.walls.drawable.push(o.toString())}}rn(this.walls.drawable)}for(let e=0;e<14;e++)this.walls.dead.push(this.walls.drawable.pop());for(let e=0;e<4;e++)this.walls.hiddenDoraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.doraIndicators.push(this.walls.dead.pop());for(let e=0;e<4;e++)this.walls.replacement.push(this.walls.dead.pop())}export(){return this.backup}static clone(t){return{drawable:t.drawable.concat(),dead:t.dead.concat(),doraIndicators:t.doraIndicators.concat(),hiddenDoraIndicators:t.hiddenDoraIndicators.concat(),replacement:t.replacement.concat()}}}class te{constructor(t,e){E(this,"wall",new bt);E(this,"playerIDs");E(this,"actor",Ht(Fe(this),{}));E(this,"observer");E(this,"handlers",{});E(this,"mailBox",{});E(this,"histories",[]);E(this,"debugMode");this.debugMode=(e==null?void 0:e.debug)??!1,this.handlers=t.reduce((o,a)=>(o[a.id]=a.handler,o),{}),this.playerIDs=t.map(o=>o.id),t.forEach(o=>o.handler.on(a=>this.enqueue(a)));const s=ls();this.observer=new xs(s),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const r=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Vt(r);const i=(e==null?void 0:e.shuffle)==!1?this.playerIDs:rn([...this.playerIDs]);this.observer.placeManager=new Jt({[i[0]]:A.E,[i[1]]:A.S,[i[2]]:A.W,[i[3]]:A.N})}boardParams(t){let s=this.hand(t).reached?1:void 0;if(s){const r=this.river.discards(t);s=r.length==0||r.length==1&&r[0].t.has(y.HORIZONTAL)?2:1}return{doraIndicators:this.observer.doraIndicators,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:s}}hand(t){return this.observer.hand(t)}get placeManager(){return this.observer.placeManager}get scoreManager(){return this.observer.scoreManager}get river(){return this.observer.river}next(t){(!this.debugMode||t)&&this.actor.send({type:"NEXT"})}emit(t){const e=this.observer.placeManager.playerID(t.wind);this.handlers[e].emit(t);const s=t.iam;t.wind==s?this.observer.eventHandler.emit(t):s==null&&(!this.observer.applied[t.id]||t.type=="DISTRIBUTE")&&(this.observer.eventHandler.emit(t),this.observer.applied[t.id]=!0)}enqueue(t){this.mailBox[t.id]==null&&(this.mailBox[t.id]=[]),this.mailBox[t.id].push(t)}pollReplies(t,e){const s=this.mailBox[t];if(s==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(s.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${s.length}`);if(e.length==0){console.warn("no events to handle");return}const r=s[0];if(r.type=="CHOICE_AFTER_DISCARDED"){const i=is(s);if(i.events.length==0){this.actor.send({type:""});return}const o=i.events[0];switch(i.type){case"RON":I(o.choices.RON,"ron choice is none"),this.actor.send({type:i.type,iam:o.wind,ret:jt(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":I(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:i.type,iam:o.wind,block:Q.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[i.type];I(a,`${i.type} choice is none`),I(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const c=Y.deserialize(a[0]);this.actor.send({type:i.type,iam:o.wind,block:c})}}else if(r.type=="CHOICE_AFTER_DRAWN"){const i=os(s);I(i.events.length==1,`found more than one selected: ${JSON.stringify(i,null,2)}`);const o=i.events[0],a=o.wind;switch(i.type){case"TSUMO":I(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:i.type,ret:jt(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[i.type];I(c,`${i.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const l=o.choices[i.type];I(l,`${i.type} choice is none`),this.actor.send({type:i.type,tile:w.from(l[0]).clone({remove:y.TSUMO}),iam:a});break;case"AN_KAN":{const h=o.choices[i.type];I(h,`${i.type} choice is none`),this.actor.send({type:i.type,block:M.from(h[0].tiles),iam:a});break}case"SHO_KAN":{const h=o.choices[i.type];I(h,`${i.type} choice is none`),this.actor.send({type:i.type,block:K.from(h[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_ORPHANS":this.actor.send({type:"DRAWN_GAME_BY_NINE_ORPHANS",iam:a});break}}else if(r.type=="CHOICE_AFTER_CALLED"){I(r.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(r,null,2)} ${this.hand(r.wind).toString()}`);const i=r.wind,o=w.from(r.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:i})}else if(r.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const i=s.filter(a=>(I(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(i.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:w.from(r.reacherInfo.tile),wind:r.reacherInfo.wind}});return}const o=i[0];this.actor.send({type:"RON",iam:o.wind,ret:jt(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:w.from(o.reacherInfo.tile)}});return}else if(r.type=="CHOICE_FOR_CHAN_KAN"){const i=s.filter(a=>a.choices.RON!==!1);if(i.length==0){this.actor.send({type:""});return}const o=i[0];I(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:jt(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:w.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${r.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,s=Object.keys(t.players),r={emit:a=>{},on:a=>{}},i=s.map(a=>({id:a,handler:r})),o=new te(i);return o.playerIDs=s,o.mailBox=e,o.observer.placeManager=new Jt(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Vt(t.scores),o.wall=new bt(t.wall),o}start(){this.actor.subscribe(s=>{console.debug("State:",s.value)});const t={scores:this.scoreManager.summary,round:this.placeManager.round,players:this.placeManager.playerMap,wall:this.wall.export(),choiceEvents:this.mailBox,sticks:this.placeManager.sticks};this.actor.start(),this.histories.push(t);const e=this.actor.getSnapshot().status;if(e!="done")throw new Error(`unexpected state ${this.actor.getSnapshot().value}(${e})`)}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new bt,this.observer.applied={},this.mailBox={},this.actor=Ht(Fe(this)),!this.placeManager.is(C.W1););}finalResult(t,e){const s=this.hand(e),r=s.reached?this.wall.hiddenDoraIndicators:void 0,i=new We(s,{...t.boardContext,sticks:this.placeManager.sticks,hiddenDoraIndicators:r}).calc(t.hand);return I(i),i}doWin(t,e,s){if(e==null)return!1;let r=this.hand(t);const i=this.boardParams(t);if(r.drawn==null){if(s==null)throw new Error("should ron but params == null");if(s.discardedBy==t||s.missingRon)return!1;r=r.clone(),i.ronWind=s.discardedBy,i.finalDiscardWin=!this.wall.canDraw,i.quadWin=s.quadWin,r.inc([e])}else i.finalWallWin=!this.wall.canDraw,i.replacementWin=s==null?void 0:s.replacementWin;i.oneShotWin=s==null?void 0:s.oneShot;const o=new rs(r),a=new We(r,i),c=o.calc(e),l=a.calc(...c);if(!l||l.yakus.length==0)return!1;if(r.draw==null){const h=Pt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(u=>h.some(d=>d.equals(u.t))))return!1}return l}doPon(t,e,s){if(s==null||t==e)return!1;const r=this.hand(t);if(r.reached||r.hands.length<3||r.get(s.t,s.n)<2)return!1;const i=s.clone({removeAll:!0}),o=Ce(t,e,_.PON),a=[],c=new Y([i,i,i]).clone({replace:{idx:o,tile:s.clone({add:y.HORIZONTAL})}});let l=c;x(s)&&s.has(y.RED)&&(l=c.clone({replace:{idx:o,tile:i.clone({add:[y.RED,y.HORIZONTAL]})}}));const h=o%2+1;if(x(s)&&r.get(s.t,0)>0&&(l=c.clone({replace:{idx:h,tile:i.clone({add:y.RED})}})),a.push(l),x(i)&&r.get(i.t,5)==3){const u=c.clone({replace:{idx:h,tile:i}});a.push(u)}return a}doChi(t,e,s){if(s==null||!s.isNum()||_t(e)!=t)return!1;const r=this.hand(t);if(r.reached||r.hands.length<3)return!1;const i=s.clone({remove:y.TSUMO,add:[y.HORIZONTAL]}),o=[];i.n-2>=1&&r.get(s.t,i.n-2)>0&&r.get(s.t,i.n-1)>0&&o.push(new J([i,new w(s.t,i.n-1),new w(s.t,i.n-2)])),i.n+2<=9&&r.get(s.t,i.n+1)>0&&r.get(s.t,i.n+2)>0&&o.push(new J([i,new w(s.t,i.n+1),new w(s.t,i.n+2)])),i.n-1>=1&&i.n+1<=9&&r.get(s.t,i.n-1)>0&&r.get(s.t,i.n+1)>0&&o.push(new J([i,new w(s.t,i.n-1),new w(s.t,i.n+1)]));for(let d=0;d<o.length;d++){const g=o[d],f=this.cannotDiscardTile(g),m=[];for(const S of f){const N=r.get(S.t,S.n);for(let R=0;R<N;R++)m.push(S.clone({remove:y.RED}))}const b=r.dec([...m,g.tiles[1],g.tiles[2]]),v=r.hands.length==0;r.inc(b),v&&o.splice(d,1)}if(o.length==0)return!1;const u=r.get(s.t,0)>0?this.redPattern(o):[];return u.length>0&&r.get(s.t,5)==1?u:[...o,...u]}redPattern(t){return t.length==0?[]:t.filter(s=>x(s.tiles[1])||x(s.tiles[2])).map(s=>{if(x(s.tiles[1])){const r=s.tiles[1].clone({add:y.RED});return s.clone({replace:{idx:1,tile:r}})}else if(x(s.tiles[2])){const r=s.tiles[2].clone({add:y.RED});return s.clone({replace:{idx:2,tile:r}})}}).filter(s=>s!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new qt(e).calc()>0?!1:Pt.calcCandidates(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const s=this.hand(t).hands;if(e==null)return s;if(e instanceof Y)return s.filter(o=>!o.equals(e.tiles[0]));const r=this.cannotDiscardTile(e),i=s.filter(o=>!r.some(a=>o.equals(a)));return I(i.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${r}, block-chi: ${e}`),i}cannotDiscardTile(t){const e=t.tiles[0],s=t.tiles[1].n;return s!=1&&e.n-2==s?[new w(e.t,e.n-3),e]:s!=8&&e.n+1==s?[new w(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),s=[];if(e.reached)return!1;for(const[r,i]of z())if(e.get(r,i)==4){const o=new w(r,i),a=[o,o,o,o];x(o)&&(a[1]=o.clone({add:y.RED})),s.push(new M(a))}if(s.length==0)return!1;for(const r of s)I(r.tiles.filter(i=>i.has(y.HORIZONTAL)).length==0,`h op ${r.toString()}`);return s}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const s=e.called.filter(i=>i instanceof Y);if(s.length==0)return!1;const r=[];for(const i of s){const o=i.tiles[0].clone({removeAll:!0,add:y.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=x(o)&&e.get(o.t,0)>0?o.clone({add:y.RED}):o;r.push(new K([...i.tiles,a]))}}if(r.length==0)return!1;for(const i of r)I(i.tiles.filter(o=>o.has(y.HORIZONTAL)).length==2,`h op ${i.toString()}`);return r}doDaiKan(t,e,s){const r=this.hand(t);if(r.reached||t==e)return!1;const i=s.clone({removeAll:!0});if(r.get(i.t,i.n)!=3)return!1;const o=Ce(t,e,_.DAI_KAN);let a=new Q([i,i,i,i]).clone({replace:{idx:o,tile:i.clone({add:y.HORIZONTAL})}});if(x(s)&&s.has(y.RED))a=a.clone({replace:{idx:o,tile:i.clone({add:[y.HORIZONTAL,y.RED]})}});else if(x(s)&&!s.has(y.RED)){I(r.get(s.t,0)>0,`hand does not have red tile: ${r.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:i.clone({add:y.RED})}})}return I(a.tiles.filter(c=>c.has(y.HORIZONTAL)).length==1,`h op ${a.toString()}`),a}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let s=0;for(const r of Object.values(p)){if(r==p.BACK)continue;const i=r==p.Z?$t:V;for(const o of i)e.get(r,o)>0&&s++}return s>=9}initialHands(){return this.wall.initialHands()}}class St extends _e{isBackHand(){for(const t of Object.values(p))if(t!=p.BACK&&this.sum(t)>0)return!1;return this.sum(p.BACK)>0}clone(){const t=new St(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new w(p.BACK,0))),[...t]):super.dec(t)}}class mn{constructor(t,e){E(this,"id");E(this,"river",new on);E(this,"placeManager",new Jt({}));E(this,"scoreManager",new Vt({}));E(this,"hands",P(new St("")));E(this,"counter",new hs);E(this,"doraIndicators",[]);E(this,"eventHandler");this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":case"CHOICE_FOR_REACH_ACCEPTANCE":break;case"DISTRIBUTE":this.counter.reset();const e=w.from(t.doraIndicator);this.setHands(t),this.placeManager=new Jt(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Vt(structuredClone(t.scores)),this.doraIndicators=[e],this.counter.dec(e);for(const r of Object.values(A))r==t.wind&&this.counter.dec(...this.hand(r).hands);break;case"DRAW":{const r=w.from(t.tile);this.hands[t.iam].draw(r),this.counter.dec(r);break}case"DISCARD":{const r=w.from(t.tile);if(this.river.discard(r,t.iam),this.hands[t.iam].discard(r),t.iam!=t.wind){this.counter.dec(r),this.counter.addTileToSafeMap(r,t.iam);for(const i of Object.values(A))this.hand(i).reached&&this.counter.addTileToSafeMap(r,i)}break}case"PON":case"CHI":case"DAI_KAN":{const r=O.deserialize(t.block);this.hands[t.iam].call(r),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...r.tiles.filter(i=>!i.has(y.HORIZONTAL)));break}case"SHO_KAN":{const r=K.from(t.block.tiles);this.hands[t.iam].kan(r),t.iam!=t.wind&&this.counter.dec(r.tiles.filter(i=>i.has(y.HORIZONTAL))[0]);break}case"AN_KAN":{const r=M.from(t.block.tiles);this.hands[t.iam].kan(r),t.iam!=t.wind&&this.counter.dec(...r.tiles.filter(i=>!i.has(y.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const r=w.from(t.tile);if(this.river.discard(r,t.iam),this.hands[t.iam].discard(r),t.iam!=t.wind){this.counter.dec(r),this.counter.addTileToSafeMap(r,t.iam);for(const i of Object.values(A))this.hand(i).reached&&this.counter.addTileToSafeMap(r,i)}break}case"REACH_ACCEPTED":const s=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(s),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const r=w.from(t.doraIndicator);this.doraIndicators.push(r),this.counter.dec(r);break}case"TSUMO":break;case"RON":break;case"END_GAME":switch(t.subType){case"NINE_TILES":case"FOUR_KAN":case"FOUR_WIND":this.placeManager.incrementDeadStick();break;case"DRAWN_GAME":{const r=this.placeManager.playerMap;this.scoreManager.update(t.deltas,r),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const r=this.placeManager.playerMap;this.scoreManager.update(t.deltas,r),t.shouldContinue?this.placeManager.incrementDeadStick():(this.placeManager.nextRound(),this.placeManager.resetDeadStick()),this.placeManager.resetReachStick();break}}break;default:throw new Error(`unexpected event ${JSON.stringify(t,null,2)}`)}}}class xs extends mn{constructor(e){super("observer",e);E(this,"applied",{});this.counter.disable=!0,this.hands=P(new St("_____________"))}setHands(e){this.hands[e.wind]=new St(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let s=!0;for(const r of Object.values(A))s&&(s=this.hand(r).get(p.BACK,0)==0);if(!s)break;console.debug("DISTRIBUTE:",`round: ${this.placeManager.round}`,`scores: ${JSON.stringify(this.scoreManager.summary,null,2)}`,`map: ${JSON.stringify(this.placeManager.playerMap,null,2)}`,`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`);for(const r of Object.values(A))console.debug(`${this.placeManager.playerID(r)}(${r})`,`init hand: ${this.hand(r).toString()}`);break;case"DRAW":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`draw: ${this.hand(e.iam).drawn}`,`hand: ${this.hand(e.iam).toString()}`);break;case"DISCARD":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`discard: ${e.tile.toString()}`,`hand: ${this.hand(e.iam).toString()}`);break;case"CHI":case"PON":case"DAI_KAN":case"AN_KAN":case"SHO_KAN":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`call: ${e.block.tiles}`,`hand: ${this.hand(e.iam).toString()}`);break;case"REACH":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`reach: ${e.tile}`,`hand: ${this.hand(e.iam).toString()}`);break;case"TSUMO":case"RON":console.debug(`${this.placeManager.playerID(e.iam)}(${e.iam})`,`ron/tsumo: ${JSON.stringify(e.ret,null,2)}`,`hand: ${this.hand(e.iam).toString()}`);break;case"END_GAME":for(const r of Object.values(A))console.debug(`${this.placeManager.playerID(r)}(${ye(r)})`,`end hand: ${this.hand(r).toString()}`);console.debug("END_GAME",e.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class Gt extends mn{constructor(e,s){super(e,s);E(this,"river",new on);E(this,"doras",[]);this.eventHandler.on(r=>this.handleEvent(r))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const s of Object.values(A))this.hands[s]=new St(e.hands[s])}handleDiscard(e){const s=Object.values(A).filter(h=>h==this.myWind?!1:this.hand(h).reached),r=new qt(this.hand(this.myWind)).calc();if(s.length>0&&r>=2)return kt.selectTile(this.counter,s,e);const i=Pt.calcCandidates(this.hand(this.myWind),e),a=Yt.calcPlayerCandidates(this.counter,i).sort((h,u)=>u.sum-h.sum),c=a.filter(h=>h.sum==a[0].sum);return Yt.selectMinPriority(this.counter,c,this.doras).tile}handleEvent(e){switch(e.type){case"CHOICE_AFTER_DISCARDED":e.choices.CHI=!1,e.choices.DAI_KAN=!1,e.choices.PON=!1,this.eventHandler.emit(e);break;case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DRAWN":if(e.choices.DISCARD){const s=this.handleDiscard(e.choices.DISCARD.map(w.from));e.choices.DISCARD=[s.toString()]}this.eventHandler.emit(e);break;case"CHOICE_FOR_REACH_ACCEPTANCE":this.eventHandler.emit(e);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(e);break;default:super.handleEvent(e)}}}class Vo{constructor(t){E(this,"index",0);E(this,"histories",[]);this.histories=JSON.parse(t)}next(){I(this.index<this.histories.length),this.index++}prev(){this.index--,I(this.index<0)}start(){te.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Jo=n=>{const[t,e]=Ft(),[s,r]=Ft(),[i,o]=Ft(),[a,c]=Ft(),l=["player-1","player-2","player-3","player-4"],h=n==null?void 0:n.playerInjection,u=(h==null?void 0:h.p1)??Gt,d=(h==null?void 0:h.p2)??Gt,g=(h==null?void 0:h.p3)??Gt,f=(h==null?void 0:h.p4)??Gt,m=new u(l[0],e),b=new d(l[1],r),v=new g(l[2],o),S=new f(l[3],c),N=[{handler:t,id:l[0]},{handler:s,id:l[1]},{handler:i,id:l[2]},{handler:a,id:l[3]}];return{c:new te(N,{debug:n==null?void 0:n.debug,shuffle:n==null?void 0:n.shuffle}),p1:m,p2:b,p3:v,p4:S}},ft=(n,t)=>{let s=1;for(let r of t)r.equals(n)&&(s*=2);return s};class Yt{static calcPlayerCandidates(t,e){let s=[];for(let r of e){let i=0,o=[];for(let a of r.candidates)o.push({tile:a.clone(),n:t.get(a)}),i+=t.get(a);s.push({sum:i,tile:r.tile,candidates:o,shanten:r.shanten})}return s}static selectMinPriority(t,e,s){I(e.length>0);let r=0,i=0;for(let o=0;o<e.length;o++){const a=Yt.calcPriority(t,e[o],s);a<r&&(r=a,i=o)}return e[i]}static calcPriority(t,e,s){const r=e.tile;let i=0;if(r.t==p.Z)return i=t.get(r),(r.n==5||r.n==6||r.n==7)&&(i*=2),i*ft(r,s);{const o=t.get(r);i+=o*ft(r,s);const a=t.get(new w(r.t,r.n+1)),c=t.get(new w(r.t,r.n+2)),l=t.get(new w(r.t,r.n-1)),h=t.get(new w(r.t,r.n-2)),u=r.n-2>0?Math.min(l,h):0,d=r.n+2<=9?Math.min(a,c):0,g=r.n-1>=1&&r.n+1<=9?Math.min(a,l):0,f=Math.max(u,g),m=Math.max(g,d);return i+=o*ft(r,s),i+=u*ft(new w(r.t,r.n-2),s),i+=d*ft(new w(r.t,r.n+2),s),i+=f*ft(new w(r.t,r.n-1),s),i+=m*ft(new w(r.t,r.n+1),s),r.n==0,i}}}class kt{static selectTile(t,e,s){I(e.length>0&&s.length>0);let r=s[0],i=Number.POSITIVE_INFINITY;for(let o of s){const a=kt.rank(t,e,o);a<i&&(r=o,i=a)}return r}static rank(t,e,s){let r=0;const i=s.isNum()?kt.rankN:kt.rankZ;for(let o of e){const a=i(t,o,s);r<a&&(r=a)}return r}static rankZ(t,e,s){if(s.t!=p.Z)throw new Error(`expected TYPE.Z but ${s.toString()}`);if(t.isSafeTile(s.t,s.n,e))return 0;const r=t.get(s);return Math.min(r,3)}static rankN(t,e,s){if(!s.isNum())throw new Error(`expected TYPE.NUMBER but ${s.toString()}`);const r=s.n,i=s.t;if(t.isSafeTile(i,r,e))return 0;if(r==1)return t.isSafeTile(i,4,e)?3:6;if(r==9)return t.isSafeTile(i,6,e)?3:6;if(r==2||r==8)return t.isSafeTile(i,5,e)?4:8;if(r==3)return t.isSafeTile(i,6,e)?5:8;if(r==7)return t.isSafeTile(i,4,e)?5:8;const o=t.isSafeTile(i,r-3,e),a=t.isSafeTile(i,r+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=St;exports.BLOCK=_;exports.BaseActor=mn;exports.Block=O;exports.BlockAnKan=M;exports.BlockCalculator=rs;exports.BlockChi=J;exports.BlockDaiKan=Q;exports.BlockHand=Ct;exports.BlockIsolated=Je;exports.BlockOther=Ye;exports.BlockPair=W;exports.BlockPon=Y;exports.BlockRun=nt;exports.BlockShoKan=K;exports.BlockThree=U;exports.Controller=te;exports.Counter=hs;exports.Efficiency=Pt;exports.FONT_FAMILY=Ge;exports.G=T;exports.Hand=_e;exports.INPUT_SEPARATOR=et;exports.Image=tn;exports.ImageHelper=sn;exports.Mark=lt;exports.MeasureText=Ds;exports.MyG=ri;exports.MyImage=ii;exports.MyRect=ai;exports.MySVG=si;exports.MyText=ci;exports.MyUse=oi;exports.N19=V;exports.NZ=$t;exports.OP=y;exports.Observer=xs;exports.Parser=B;exports.PlaceManager=Jt;exports.Player=Gt;exports.PlayerEfficiency=Yt;exports.PointCalculator=We;exports.ROUND=C;exports.ROUND_MAP=Ze;exports.Rect=en;exports.Replayer=Vo;exports.RiskRank=kt;exports.River=on;exports.STICK_CONTEXT=ke;exports.SVG=Jn;exports.ScoreManager=Vt;exports.ShantenCalculator=qt;exports.Svg=Vn;exports.Symbol=nn;exports.TABLE_CONTEXT=Dn;exports.TILE_CONTEXT=it;exports.TYPE=p;exports.Text=Et;exports.Tile=w;exports.Use=we;exports.WIND=A;exports.WIND_MAP=ge;exports.Wall=bt;exports.callBlockIndex=Ce;exports.convertInput=ss;exports.createControllerMachine=Fe;exports.createEventEmitter=ls;exports.createEventPipe=Ft;exports.createHand=Tt;exports.createLocalGame=Jo;exports.createTable=qn;exports.createWindMap=P;exports.deserializeWinResult=jt;exports.drawBlocks=gi;exports.drawTable=Ni;exports.forHand=z;exports.incrementalIDGenerator=Cs;exports.isNum5=x;exports.nextRound=Zt;exports.nextWind=_t;exports.optimizeSVG=mi;exports.parse=es;exports.parseTableInput=ns;exports.prevRound=Gs;exports.prevWind=ye;exports.prioritizeDiscardedEvents=is;exports.prioritizeDrawnEvents=os;exports.serializeWinResult=ue;exports.shuffle=rn;exports.sortCalledTiles=Kn;exports.tileSortFunc=Xt;