@konoui/mjimage 0.0.47 → 0.0.49
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/README.md +4 -2
- package/dist/index.cjs +16 -10
- package/dist/index.d.cts +157 -26
- package/dist/index.d.ts +157 -26
- package/dist/index.js +4262 -6658
- package/package.json +8 -9
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
"use strict";var dr=Object.defineProperty;var pr=(s,t,e)=>t in s?dr(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var A=(s,t,e)=>pr(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Zn="MS Gothic, sans-serif",Et={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Js={BASE:40},At=",",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"},v={E:"1w",S:"2w",W:"3w",N:"4w"},j={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"},nn={[v.E]:"東",[v.S]:"南",[v.W]:"西",[v.N]:"北"},Yn={[j.E1]:"東1局",[j.E2]:"東2局",[j.E3]:"東3局",[j.E4]:"東4局",[j.S1]:"南1局",[j.S2]:"南2局",[j.S3]:"南3局",[j.S4]:"南4局",[j.W1]:"西1局",[j.W2]:"西2局",[j.W3]:"西3局",[j.W4]:"西4局",[j.N1]:"北1局",[j.N2]:"北2局",[j.N3]:"北3局",[j.N4]:"北4局"};function O(s,t){if(!s)throw new Error(t)}class mr{constructor(t="東",e="2"){A(this,"ctx",null);A(this,"strText");A(this,"numText");A(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),O(this.ctx,"context is null"));const n=this.ctx;n.font=e;const i=n.measureText(t);let r=i.width,o=i.actualBoundingBoxAscent+i.actualBoundingBoxDescent;return[r,o]});A(this,"measureFontContext",(t,e)=>{const n={family:t,size:e},i=`${n.size}px ${n.family}`,[r,o]=this.measure(this.strText,i),[a,c]=this.measure(this.numText,i);return{font:{family:t,size:e},textWidth:r,textHeight:o,numWidth:a,numHeight:c}});A(this,"measureTableFontContext",t=>{const e=this.measureFontContext(Zn,Js.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class gr{constructor(t){A(this,"input");A(this,"position");A(this,"nextPosition");A(this,"char");A(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 Ie=(s,t)=>{if(s.t==t.t){if(z(s)&&z(t)){if(s.has(y.RED))return-1;if(t.has(y.RED))return 1}return s.n-t.n}const e={[p.M]:1,[p.P]:2,[p.S]:3,[p.Z]:4,[p.BACK]:5};return e[s.t]-e[t.t]},yr=(s,t)=>{const e={[y.HORIZONTAL]:1,[y.TSUMO]:2,[y.RON]:3,[y.DORA]:4,[y.COLOR_GRAYSCALE]:5,[y.RED]:6};return e[s]-e[t]},Vs=s=>{const t=[];s.forEach((n,i)=>{n.has(y.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(y.HORIZONTAL)).sort(Ie);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function z(s){return s.isNum()&&s.n==5}function wr(s){for(const t of Object.values(p))if(t==s)return[t,!0];return[p.BACK,!1]}class w{constructor(t,e,n=[]){this.t=t,this.n=e,this.ops=n}static from(t){const e=new Q(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(yr).join("")}${this.n}${this.t}`}toJSON(){return this.toString()}clone(t){const e=(t==null?void 0:t.t)??this.t,n=(t==null?void 0:t.n)??this.n,i=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),r=new Set([...i]);return t!=null&&t.add&&(Array.isArray(t.add)?t.add.forEach(o=>r.add(o)):r.add(t.add)),new w(e,n,Array.from(r))}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 B{constructor(t,e){A(this,"_tiles");A(this,"_type");if(this._tiles=t,this._type=e,this.isCalled()){this._tiles=Vs(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Ie);return}}static deserialize(t){const e=new Q(t.tiles).parse();if(e.length!=1)throw new Error(`block must be 1: ${t.tiles}`);const n=e[0].type;if(!(t.type==b.PAIR||t.type==b.ISOLATED||t.type==b.THREE||t.type==b.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return qe(e[0].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,n=[...this.tiles];return e&&(n[e.idx]=e.tile),qe(n,this._type)}}const Ut=s=>{let t="";for(const e of s){if(e.t==p.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Xn=s=>{let t=s[0].t,e="";for(const i of s){const r=i.t,o=r==p.BACK?i.toString():i.toString().slice(0,-1);r!=t&&t!=p.BACK&&(e+=t),t=r,e+=o}const n=s.at(-1);return n.t!=p.BACK&&(e+=n.t),e};class dt extends B{constructor(t){super(t,b.CHI)}static from(t){return B.deserialize({tiles:t,type:b.CHI})}toString(){return Ut(this.tiles)}}class _t extends B{constructor(t){super(t,b.PON)}static from(t){return B.deserialize({tiles:t,type:b.PON})}toString(){return Ut(this.tiles)}}class U extends B{constructor(t){const e=t.filter(i=>i.t!=p.BACK),n=e[0];if(e.length<t.length){if(z(n)){const i=new w(n.t,5);super([i.clone({add:y.RED}),i,i,i],b.AN_KAN);return}super([n,n,n,n],b.AN_KAN);return}super(t,b.AN_KAN)}get tilesWithBack(){const t=this.tiles[0].clone({remove:y.RED}),e=z(t)?t.clone({add:y.RED}):t;return[new w(p.BACK,0),e,t,new w(p.BACK,0)]}static from(t){return B.deserialize({tiles:t,type:b.AN_KAN})}toString(){return Xn(this.tilesWithBack)}}class wt extends B{constructor(t){super(t,b.DAI_KAN)}static from(t){return B.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return Ut(this.tiles)}}class ct extends B{constructor(t){super(t,b.SHO_KAN)}static from(t){return B.deserialize({tiles:t,type:b.SHO_KAN})}toString(){return Ut(this.tiles)}}class Y extends B{constructor(t,e){super([t,e],b.PAIR)}toString(){return Ut(this.tiles)}}class at extends B{constructor(t){super(t,b.THREE)}static from(t){return B.deserialize({tiles:t,type:b.THREE})}toString(){return Ut(this.tiles)}}class St extends B{constructor(t){super(t,b.RUN)}static from(t){return B.deserialize({tiles:t,type:b.RUN})}toString(){return Ut(this.tiles)}}class Jn extends B{constructor(t){super([t],b.ISOLATED)}toString(){return this.tiles[0].toString()}}class ee extends B{constructor(t){super(t,b.HAND)}toString(){return Xn(this.tiles)}}class Vn extends B{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Xn(this.tiles)}}const qe=(s,t)=>{switch(t){case b.CHI:return new dt([s[0],s[1],s[2]]);case b.PON:return new _t([s[0],s[1],s[2]]);case b.AN_KAN:return new U(s);case b.DAI_KAN:return new wt(s);case b.SHO_KAN:return new ct(s);case b.THREE:return new at(s);case b.RUN:return new St(s);case b.PAIR:return new Y(s[0],s[1]);case b.ISOLATED:return new Jn(s[0]);case b.HAND:return new ee(s);default:return new Vn(s,t)}};class Q{constructor(t){A(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!=At)}tileSeparators(){const t=new gr(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();const i=t.char;if(i===t.eof)break;if(i==At){e.push(At),t.readChar();continue}const[r,o]=Ds(i,n);if(o){if(r==p.BACK){e.push(new w(r,0)),t.readChar();continue}e.push(...br(n,r)),n=[],t.readChar();continue}else{const[a,c]=vr(t);if(c){n.push(a),t.readChar();continue}const[h,l]=Qs(i);if(!l)throw new Error(`encounter unexpected number. n: ${h}, current: ${i}, input: ${t.input}`);n.push({n:h})}t.readChar()}if(n.length>0)throw new Error(`remaining values ${n.toString()}`);return e}makeBlocks(t){let e=[];const n=[];if(t.length==0)return n;for(const o of t){if(o==At){const a=Ns(e),c=qe(e,a);n.push(c),e=[];continue}e.push(o)}const i=Ns(e),r=qe(e,i);return n.push(r),e=[],n}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),[n,i]=Ds(e,[new w(p.BACK,1)]);if(!i)throw new Error(`last character(${e}) is not type value`)}}function Ns(s){if(s.length===0)return b.UNKNOWN;if(s.length===1)return s[0].has(y.DORA)?b.IMAGE_DORA:s[0].has(y.TSUMO)?b.TSUMO:b.HAND;const t=s.every(r=>r.equals(s[0])),e=s.filter(r=>r.has(y.HORIZONTAL)).length,n=s.filter(r=>r.has(y.TSUMO)||r.has(y.DORA)).length,i=s.filter(r=>r.t==p.BACK).length;if(n>0)return b.UNKNOWN;if(e==0&&i==0)return b.HAND;if(s.length===3&&i===0)return t?b.PON:e==1&&_r(s)?b.CHI:b.IMAGE_DISCARD;if(s.length==4&&i==2)return b.AN_KAN;if(s.length==4&&t){if(e==1)return b.DAI_KAN;if(e==2)return b.SHO_KAN}return e==1||n==0?b.IMAGE_DISCARD:b.UNKNOWN}function _r(s){const t=[...s].sort(Ie);if(t.some(n=>t[0].t!=n.t))return!1;const e=t.map(n=>n.n);for(let n=0;n<e.length-1;n++)if(e[n]!=e[n+1]-1)return!1;return!0}function br(s,t){return s.map(e=>{const n=new w(t,e.n,e.ops);return n.isNum()&&n.n==0?n.clone({n:5,add:y.RED}):n})}function Ds(s,t){const[e,n]=wr(s);if(n)return[e,!0];if((s==="w"||s==="d")&&t.length>0){for(let r=0;r<t.length;r++){const o=t[r];s==="d"&&(t[r].n=o.n+4)}return[p.Z,!0]}return[p.BACK,!1]}function Qs(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function vr(s){const t=Object.values(y);if(!t.includes(s.char))return[new w(p.BACK,0),!1];const e=[];for(let n=0;n<4;n++){const i=s.peekCharN(n);if(t.includes(i))e.push(i);else{const[r,o]=Qs(i);if(!o)break;for(const c of e)s.readChar();const a=new w(p.BACK,r,e);if(a.has(y.RED)&&a.n!=5)throw new Error(`found ${y.RED} but number is not 5: ${r}`);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 Z(s,t=!1){const e={[v.E]:s,[v.S]:s,[v.W]:s,[v.N]:s};if(t)for(let n of Object.values(v))e[n]=structuredClone(s);return e}const ve=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=kt(t)):e++,`${t}${e}`},Ar=s=>ve(ve(ve(s))),kt=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}w`},Qn=s=>{let t=Number(s.toString()[0]);return t=t%2+1,`${t}w`},An=(s,t,e)=>{const n=Math.abs(Number(s[0])-Number(t[0]));return O(n==1||n==2||n==3),e==b.PON?n==3?0:n==2?1:2:n==3?0:n==1?3:2},Sn={},ti=[];function k(s,t){if(Array.isArray(s)){for(const e of s)k(e,t);return}if(typeof s=="object"){for(const e in s)k(e,s[e]);return}ei(Object.getOwnPropertyNames(t)),Sn[s]=Object.assign(Sn[s]||{},t)}function J(s){return Sn[s]||{}}function Sr(){return[...new Set(ti)]}function ei(s){ti.push(...s)}function ts(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)i.push(t(s[e]));return i}function xr(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)t(s[e])&&i.push(s[e]);return i}function un(s){return s%360*Math.PI/180}function Er(s){return s.replace(/([A-Z])/g,function(t,e){return"-"+e.toLowerCase()})}function ni(s){return s.charAt(0).toUpperCase()+s.slice(1)}function fe(s,t,e,n){return(t==null||e==null)&&(n=n||s.bbox(),t==null?t=n.width/n.height*e:e==null&&(e=n.height/n.width*t)),{width:t,height:e}}function xn(s,t){const e=s.origin;let n=s.ox!=null?s.ox:s.originX!=null?s.originX:"center",i=s.oy!=null?s.oy:s.originY!=null?s.originY:"center";e!=null&&([n,i]=Array.isArray(e)?e:typeof e=="object"?[e.x,e.y]:[e,e]);const r=typeof n=="string",o=typeof i=="string";if(r||o){const{height:a,width:c,x:h,y:l}=t.bbox();r&&(n=n.includes("left")?h:n.includes("right")?h+c:h+c/2),o&&(i=i.includes("top")?l:i.includes("bottom")?l+a:l+a/2)}return[n,i]}const kr=new Set(["desc","metadata","title"]),En=s=>kr.has(s.nodeName),si=(s,t,e={})=>{const n={...t};for(const i in n)n[i].valueOf()===e[i]&&delete n[i];Object.keys(n).length?s.node.setAttribute("data-svgjs",JSON.stringify(n)):(s.node.removeAttribute("data-svgjs"),s.node.removeAttribute("svgjs:data"))},es="http://www.w3.org/2000/svg",Tr="http://www.w3.org/1999/xhtml",fn="http://www.w3.org/2000/xmlns/",Ne="http://www.w3.org/1999/xlink",I={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function Or(){return I.window}class ns{}const Bt={},ss="___SYMBOL___ROOT___";function Ae(s,t=es){return I.document.createElementNS(t,s)}function X(s,t=!1){if(s instanceof ns)return s;if(typeof s=="object")return dn(s);if(s==null)return new Bt[ss];if(typeof s=="string"&&s.charAt(0)!=="<")return dn(I.document.querySelector(s));const e=t?I.document.createElement("div"):Ae("svg");return e.innerHTML=s,s=dn(e.firstChild),e.removeChild(e.firstChild),s}function $(s,t){return t&&(t instanceof I.window.Node||t.ownerDocument&&t instanceof t.ownerDocument.defaultView.Node)?t:Ae(s)}function st(s){if(!s)return null;if(s.instance instanceof ns)return s.instance;if(s.nodeName==="#document-fragment")return new Bt.Fragment(s);let t=ni(s.nodeName||"Dom");return t==="LinearGradient"||t==="RadialGradient"?t="Gradient":Bt[t]||(t="Dom"),new Bt[t](s)}let dn=st;function N(s,t=s.name,e=!1){return Bt[t]=s,e&&(Bt[ss]=s),ei(Object.getOwnPropertyNames(s.prototype)),s}function Ir(s){return Bt[s]}let Nr=1e3;function ii(s){return"Svgjs"+ni(s)+Nr++}function ri(s){for(let t=s.children.length-1;t>=0;t--)ri(s.children[t]);return s.id&&(s.id=ii(s.nodeName)),s}function T(s,t){let e,n;for(s=Array.isArray(s)?s:[s],n=s.length-1;n>=0;n--)for(e in t)s[n].prototype[e]=t[e]}function H(s){return function(...t){const e=t[t.length-1];return e&&e.constructor===Object&&!(e instanceof Array)?s.apply(this,t.slice(0,-1)).attr(e):s.apply(this,t)}}function Dr(){return this.parent().children()}function Cr(){return this.parent().index(this)}function Mr(){return this.siblings()[this.position()+1]}function Rr(){return this.siblings()[this.position()-1]}function Hr(){const s=this.position();return this.parent().add(this.remove(),s+1),this}function $r(){const s=this.position();return this.parent().add(this.remove(),s?s-1:0),this}function Br(){return this.parent().add(this.remove()),this}function Wr(){return this.parent().add(this.remove(),0),this}function Pr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t),this}function jr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t+1),this}function zr(s){return s=X(s),s.before(this),this}function Kr(s){return s=X(s),s.after(this),this}k("Dom",{siblings:Dr,position:Cr,next:Mr,prev:Rr,forward:Hr,backward:$r,front:Br,back:Wr,before:Pr,after:jr,insertBefore:zr,insertAfter:Kr});const oi=/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,Lr=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,Ur=/rgb\((\d+),(\d+),(\d+)\)/,Fr=/(#[a-z_][a-z0-9\-_]*)/i,qr=/\)\s*,?\s*/,Gr=/\s/g,Cs=/^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i,Ms=/^rgb\(/,Rs=/^(\s+)?$/,Hs=/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Zr=/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,bt=/[\s,]+/,is=/[MLHVCSQTAZ]/i;function Yr(){const s=this.attr("class");return s==null?[]:s.trim().split(bt)}function Xr(s){return this.classes().indexOf(s)!==-1}function Jr(s){if(!this.hasClass(s)){const t=this.classes();t.push(s),this.attr("class",t.join(" "))}return this}function Vr(s){return this.hasClass(s)&&this.attr("class",this.classes().filter(function(t){return t!==s}).join(" ")),this}function Qr(s){return this.hasClass(s)?this.removeClass(s):this.addClass(s)}k("Dom",{classes:Yr,hasClass:Xr,addClass:Jr,removeClass:Vr,toggleClass:Qr});function to(s,t){const e={};if(arguments.length===0)return this.node.style.cssText.split(/\s*;\s*/).filter(function(n){return!!n.length}).forEach(function(n){const i=n.split(/\s*:\s*/);e[i[0]]=i[1]}),e;if(arguments.length<2){if(Array.isArray(s)){for(const n of s){const i=n;e[n]=this.node.style.getPropertyValue(i)}return e}if(typeof s=="string")return this.node.style.getPropertyValue(s);if(typeof s=="object")for(const n in s)this.node.style.setProperty(n,s[n]==null||Rs.test(s[n])?"":s[n])}return arguments.length===2&&this.node.style.setProperty(s,t==null||Rs.test(t)?"":t),this}function eo(){return this.css("display","")}function no(){return this.css("display","none")}function so(){return this.css("display")!=="none"}k("Dom",{css:to,show:eo,hide:no,visible:so});function io(s,t,e){if(s==null)return this.data(ts(xr(this.node.attributes,n=>n.nodeName.indexOf("data-")===0),n=>n.nodeName.slice(5)));if(s instanceof Array){const n={};for(const i of s)n[i]=this.data(i);return n}else if(typeof s=="object")for(t in s)this.data(t,s[t]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+s))}catch{return this.attr("data-"+s)}else this.attr("data-"+s,t===null?null:e===!0||typeof t=="string"||typeof t=="number"?t:JSON.stringify(t));return this}k("Dom",{data:io});function ro(s,t){if(typeof arguments[0]=="object")for(const e in s)this.remember(e,s[e]);else{if(arguments.length===1)return this.memory()[s];this.memory()[s]=t}return this}function oo(){if(arguments.length===0)this._memory={};else for(let s=arguments.length-1;s>=0;s--)delete this.memory()[arguments[s]];return this}function ao(){return this._memory=this._memory||{}}k("Dom",{remember:ro,forget:oo,memory:ao});function co(s){return s.length===4?["#",s.substring(1,2),s.substring(1,2),s.substring(2,3),s.substring(2,3),s.substring(3,4),s.substring(3,4)].join(""):s}function ho(s){const t=Math.round(s),n=Math.max(0,Math.min(255,t)).toString(16);return n.length===1?"0"+n:n}function qt(s,t){for(let e=t.length;e--;)if(s[t[e]]==null)return!1;return!0}function lo(s,t){const e=qt(s,"rgb")?{_a:s.r,_b:s.g,_c:s.b,_d:0,space:"rgb"}:qt(s,"xyz")?{_a:s.x,_b:s.y,_c:s.z,_d:0,space:"xyz"}:qt(s,"hsl")?{_a:s.h,_b:s.s,_c:s.l,_d:0,space:"hsl"}:qt(s,"lab")?{_a:s.l,_b:s.a,_c:s.b,_d:0,space:"lab"}:qt(s,"lch")?{_a:s.l,_b:s.c,_c:s.h,_d:0,space:"lch"}:qt(s,"cmyk")?{_a:s.c,_b:s.m,_c:s.y,_d:s.k,space:"cmyk"}:{_a:0,_b:0,_c:0,space:"rgb"};return e.space=t||e.space,e}function uo(s){return s==="lab"||s==="xyz"||s==="lch"}function pn(s,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?s+(t-s)*6*e:e<1/2?t:e<2/3?s+(t-s)*(2/3-e)*6:s}class M{constructor(...t){this.init(...t)}static isColor(t){return t&&(t instanceof M||this.isRgb(t)||this.test(t))}static isRgb(t){return t&&typeof t.r=="number"&&typeof t.g=="number"&&typeof t.b=="number"}static random(t="vibrant",e){const{random:n,round:i,sin:r,PI:o}=Math;if(t==="vibrant"){const a=24*n()+57,c=38*n()+45,h=360*n();return new M(a,c,h,"lch")}else if(t==="sine"){e=e??n();const a=i(80*r(2*o*e/.5+.01)+150),c=i(50*r(2*o*e/.5+4.6)+200),h=i(100*r(2*o*e/.5+2.3)+150);return new M(a,c,h)}else if(t==="pastel"){const a=8*n()+86,c=17*n()+9,h=360*n();return new M(a,c,h,"lch")}else if(t==="dark"){const a=10+10*n(),c=50*n()+86,h=360*n();return new M(a,c,h,"lch")}else if(t==="rgb"){const a=255*n(),c=255*n(),h=255*n();return new M(a,c,h)}else if(t==="lab"){const a=100*n(),c=256*n()-128,h=256*n()-128;return new M(a,c,h,"lab")}else if(t==="grey"){const a=255*n();return new M(a,a,a)}else throw new Error("Unsupported random color mode")}static test(t){return typeof t=="string"&&(Cs.test(t)||Ms.test(t))}cmyk(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(f=>f/255),a=Math.min(1-i,1-r,1-o);if(a===1)return new M(0,0,0,1,"cmyk");const c=(1-i-a)/(1-a),h=(1-r-a)/(1-a),l=(1-o-a)/(1-a);return new M(c,h,l,a,"cmyk")}hsl(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(g=>g/255),a=Math.max(i,r,o),c=Math.min(i,r,o),h=(a+c)/2,l=a===c,u=a-c,f=l?0:h>.5?u/(2-a-c):u/(a+c),m=l?0:a===i?((r-o)/u+(r<o?6:0))/6:a===r?((o-i)/u+2)/6:a===o?((i-r)/u+4)/6:0;return new M(360*m,100*f,100*h,"hsl")}init(t=0,e=0,n=0,i=0,r="rgb"){if(t=t||0,this.space)for(const u in this.space)delete this[this.space[u]];if(typeof t=="number")r=typeof i=="string"?i:r,i=typeof i=="string"?0:i,Object.assign(this,{_a:t,_b:e,_c:n,_d:i,space:r});else if(t instanceof Array)this.space=e||(typeof t[3]=="string"?t[3]:t[4])||"rgb",Object.assign(this,{_a:t[0],_b:t[1],_c:t[2],_d:t[3]||0});else if(t instanceof Object){const u=lo(t,e);Object.assign(this,u)}else if(typeof t=="string")if(Ms.test(t)){const u=t.replace(Gr,""),[f,m,d]=Ur.exec(u).slice(1,4).map(g=>parseInt(g));Object.assign(this,{_a:f,_b:m,_c:d,_d:0,space:"rgb"})}else if(Cs.test(t)){const u=g=>parseInt(g,16),[,f,m,d]=Lr.exec(co(t)).map(u);Object.assign(this,{_a:f,_b:m,_c:d,_d:0,space:"rgb"})}else throw Error("Unsupported string format, can't construct Color");const{_a:o,_b:a,_c:c,_d:h}=this,l=this.space==="rgb"?{r:o,g:a,b:c}:this.space==="xyz"?{x:o,y:a,z:c}:this.space==="hsl"?{h:o,s:a,l:c}:this.space==="lab"?{l:o,a,b:c}:this.space==="lch"?{l:o,c:a,h:c}:this.space==="cmyk"?{c:o,m:a,y:c,k:h}:{};Object.assign(this,l)}lab(){const{x:t,y:e,z:n}=this.xyz(),i=116*e-16,r=500*(t-e),o=200*(e-n);return new M(i,r,o,"lab")}lch(){const{l:t,a:e,b:n}=this.lab(),i=Math.sqrt(e**2+n**2);let r=180*Math.atan2(n,e)/Math.PI;return r<0&&(r*=-1,r=360-r),new M(t,i,r,"lch")}rgb(){if(this.space==="rgb")return this;if(uo(this.space)){let{x:t,y:e,z:n}=this;if(this.space==="lab"||this.space==="lch"){let{l:m,a:d,b:g}=this;if(this.space==="lch"){const{c:ot,h:mt}=this,Ft=Math.PI/180;d=ot*Math.cos(Ft*mt),g=ot*Math.sin(Ft*mt)}const _=(m+16)/116,S=d/500+_,D=_-g/200,R=16/116,q=.008856,L=7.787;t=.95047*(S**3>q?S**3:(S-R)/L),e=1*(_**3>q?_**3:(_-R)/L),n=1.08883*(D**3>q?D**3:(D-R)/L)}const i=t*3.2406+e*-1.5372+n*-.4986,r=t*-.9689+e*1.8758+n*.0415,o=t*.0557+e*-.204+n*1.057,a=Math.pow,c=.0031308,h=i>c?1.055*a(i,1/2.4)-.055:12.92*i,l=r>c?1.055*a(r,1/2.4)-.055:12.92*r,u=o>c?1.055*a(o,1/2.4)-.055:12.92*o;return new M(255*h,255*l,255*u)}else if(this.space==="hsl"){let{h:t,s:e,l:n}=this;if(t/=360,e/=100,n/=100,e===0)return n*=255,new M(n,n,n);const i=n<.5?n*(1+e):n+e-n*e,r=2*n-i,o=255*pn(r,i,t+1/3),a=255*pn(r,i,t),c=255*pn(r,i,t-1/3);return new M(o,a,c)}else if(this.space==="cmyk"){const{c:t,m:e,y:n,k:i}=this,r=255*(1-Math.min(1,t*(1-i)+i)),o=255*(1-Math.min(1,e*(1-i)+i)),a=255*(1-Math.min(1,n*(1-i)+i));return new M(r,o,a)}else return this}toArray(){const{_a:t,_b:e,_c:n,_d:i,space:r}=this;return[t,e,n,i,r]}toHex(){const[t,e,n]=this._clamped().map(ho);return`#${t}${e}${n}`}toRgb(){const[t,e,n]=this._clamped();return`rgb(${t},${e},${n})`}toString(){return this.toHex()}xyz(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(S=>S/255),a=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92,c=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92,h=o>.04045?Math.pow((o+.055)/1.055,2.4):o/12.92,l=(a*.4124+c*.3576+h*.1805)/.95047,u=(a*.2126+c*.7152+h*.0722)/1,f=(a*.0193+c*.1192+h*.9505)/1.08883,m=l>.008856?Math.pow(l,1/3):7.787*l+16/116,d=u>.008856?Math.pow(u,1/3):7.787*u+16/116,g=f>.008856?Math.pow(f,1/3):7.787*f+16/116;return new M(m,d,g,"xyz")}_clamped(){const{_a:t,_b:e,_c:n}=this.rgb(),{max:i,min:r,round:o}=Math,a=c=>i(0,r(o(c),255));return[t,e,n].map(a)}}class W{constructor(...t){this.init(...t)}clone(){return new W(this)}init(t,e){const n={x:0,y:0},i=Array.isArray(t)?{x:t[0],y:t[1]}:typeof t=="object"?{x:t.x,y:t.y}:{x:t,y:e};return this.x=i.x==null?n.x:i.x,this.y=i.y==null?n.y:i.y,this}toArray(){return[this.x,this.y]}transform(t){return this.clone().transformO(t)}transformO(t){x.isMatrixLike(t)||(t=new x(t));const{x:e,y:n}=this;return this.x=t.a*e+t.c*n+t.e,this.y=t.b*e+t.d*n+t.f,this}}function fo(s,t){return new W(s,t).transformO(this.screenCTM().inverseO())}function Gt(s,t,e){return Math.abs(t-s)<1e-6}class x{constructor(...t){this.init(...t)}static formatTransforms(t){const e=t.flip==="both"||t.flip===!0,n=t.flip&&(e||t.flip==="x")?-1:1,i=t.flip&&(e||t.flip==="y")?-1:1,r=t.skew&&t.skew.length?t.skew[0]:isFinite(t.skew)?t.skew:isFinite(t.skewX)?t.skewX:0,o=t.skew&&t.skew.length?t.skew[1]:isFinite(t.skew)?t.skew:isFinite(t.skewY)?t.skewY:0,a=t.scale&&t.scale.length?t.scale[0]*n:isFinite(t.scale)?t.scale*n:isFinite(t.scaleX)?t.scaleX*n:n,c=t.scale&&t.scale.length?t.scale[1]*i:isFinite(t.scale)?t.scale*i:isFinite(t.scaleY)?t.scaleY*i:i,h=t.shear||0,l=t.rotate||t.theta||0,u=new W(t.origin||t.around||t.ox||t.originX,t.oy||t.originY),f=u.x,m=u.y,d=new W(t.position||t.px||t.positionX||NaN,t.py||t.positionY||NaN),g=d.x,_=d.y,S=new W(t.translate||t.tx||t.translateX,t.ty||t.translateY),D=S.x,R=S.y,q=new W(t.relative||t.rx||t.relativeX,t.ry||t.relativeY),L=q.x,ot=q.y;return{scaleX:a,scaleY:c,skewX:r,skewY:o,shear:h,theta:l,rx:L,ry:ot,tx:D,ty:R,ox:f,oy:m,px:g,py:_}}static fromArray(t){return{a:t[0],b:t[1],c:t[2],d:t[3],e:t[4],f:t[5]}}static isMatrixLike(t){return t.a!=null||t.b!=null||t.c!=null||t.d!=null||t.e!=null||t.f!=null}static matrixMultiply(t,e,n){const i=t.a*e.a+t.c*e.b,r=t.b*e.a+t.d*e.b,o=t.a*e.c+t.c*e.d,a=t.b*e.c+t.d*e.d,c=t.e+t.a*e.e+t.c*e.f,h=t.f+t.b*e.e+t.d*e.f;return n.a=i,n.b=r,n.c=o,n.d=a,n.e=c,n.f=h,n}around(t,e,n){return this.clone().aroundO(t,e,n)}aroundO(t,e,n){const i=t||0,r=e||0;return this.translateO(-i,-r).lmultiplyO(n).translateO(i,r)}clone(){return new x(this)}decompose(t=0,e=0){const n=this.a,i=this.b,r=this.c,o=this.d,a=this.e,c=this.f,h=n*o-i*r,l=h>0?1:-1,u=l*Math.sqrt(n*n+i*i),f=Math.atan2(l*i,l*n),m=180/Math.PI*f,d=Math.cos(f),g=Math.sin(f),_=(n*r+i*o)/h,S=r*u/(_*n-i)||o*u/(_*i+n),D=a-t+t*d*u+e*(_*d*u-g*S),R=c-e+t*g*u+e*(_*g*u+d*S);return{scaleX:u,scaleY:S,shear:_,rotate:m,translateX:D,translateY:R,originX:t,originY:e,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}equals(t){if(t===this)return!0;const e=new x(t);return Gt(this.a,e.a)&&Gt(this.b,e.b)&&Gt(this.c,e.c)&&Gt(this.d,e.d)&&Gt(this.e,e.e)&&Gt(this.f,e.f)}flip(t,e){return this.clone().flipO(t,e)}flipO(t,e){return t==="x"?this.scaleO(-1,1,e,0):t==="y"?this.scaleO(1,-1,0,e):this.scaleO(-1,-1,t,e||t)}init(t){const e=x.fromArray([1,0,0,1,0,0]);return t=t instanceof pt?t.matrixify():typeof t=="string"?x.fromArray(t.split(bt).map(parseFloat)):Array.isArray(t)?x.fromArray(t):typeof t=="object"&&x.isMatrixLike(t)?t:typeof t=="object"?new x().transform(t):arguments.length===6?x.fromArray([].slice.call(arguments)):e,this.a=t.a!=null?t.a:e.a,this.b=t.b!=null?t.b:e.b,this.c=t.c!=null?t.c:e.c,this.d=t.d!=null?t.d:e.d,this.e=t.e!=null?t.e:e.e,this.f=t.f!=null?t.f:e.f,this}inverse(){return this.clone().inverseO()}inverseO(){const t=this.a,e=this.b,n=this.c,i=this.d,r=this.e,o=this.f,a=t*i-e*n;if(!a)throw new Error("Cannot invert "+this);const c=i/a,h=-e/a,l=-n/a,u=t/a,f=-(c*r+l*o),m=-(h*r+u*o);return this.a=c,this.b=h,this.c=l,this.d=u,this.e=f,this.f=m,this}lmultiply(t){return this.clone().lmultiplyO(t)}lmultiplyO(t){const e=this,n=t instanceof x?t:new x(t);return x.matrixMultiply(n,e,this)}multiply(t){return this.clone().multiplyO(t)}multiplyO(t){const e=this,n=t instanceof x?t:new x(t);return x.matrixMultiply(e,n,this)}rotate(t,e,n){return this.clone().rotateO(t,e,n)}rotateO(t,e=0,n=0){t=un(t);const i=Math.cos(t),r=Math.sin(t),{a:o,b:a,c,d:h,e:l,f:u}=this;return this.a=o*i-a*r,this.b=a*i+o*r,this.c=c*i-h*r,this.d=h*i+c*r,this.e=l*i-u*r+n*r-e*i+e,this.f=u*i+l*r-e*r-n*i+n,this}scale(){return this.clone().scaleO(...arguments)}scaleO(t,e=t,n=0,i=0){arguments.length===3&&(i=n,n=e,e=t);const{a:r,b:o,c:a,d:c,e:h,f:l}=this;return this.a=r*t,this.b=o*e,this.c=a*t,this.d=c*e,this.e=h*t-n*t+n,this.f=l*e-i*e+i,this}shear(t,e,n){return this.clone().shearO(t,e,n)}shearO(t,e=0,n=0){const{a:i,b:r,c:o,d:a,e:c,f:h}=this;return this.a=i+r*t,this.c=o+a*t,this.e=c+h*t-n*t,this}skew(){return this.clone().skewO(...arguments)}skewO(t,e=t,n=0,i=0){arguments.length===3&&(i=n,n=e,e=t),t=un(t),e=un(e);const r=Math.tan(t),o=Math.tan(e),{a,b:c,c:h,d:l,e:u,f}=this;return this.a=a+c*r,this.b=c+a*o,this.c=h+l*r,this.d=l+h*o,this.e=u+f*r-i*r,this.f=f+u*o-n*o,this}skewX(t,e,n){return this.skew(t,0,e,n)}skewY(t,e,n){return this.skew(0,t,e,n)}toArray(){return[this.a,this.b,this.c,this.d,this.e,this.f]}toString(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}transform(t){if(x.isMatrixLike(t))return new x(t).multiplyO(this);const e=x.formatTransforms(t),n=this,{x:i,y:r}=new W(e.ox,e.oy).transform(n),o=new x().translateO(e.rx,e.ry).lmultiplyO(n).translateO(-i,-r).scaleO(e.scaleX,e.scaleY).skewO(e.skewX,e.skewY).shearO(e.shear).rotateO(e.theta).translateO(i,r);if(isFinite(e.px)||isFinite(e.py)){const a=new W(i,r).transform(o),c=isFinite(e.px)?e.px-a.x:0,h=isFinite(e.py)?e.py-a.y:0;o.translateO(c,h)}return o.translateO(e.tx,e.ty),o}translate(t,e){return this.clone().translateO(t,e)}translateO(t,e){return this.e+=t||0,this.f+=e||0,this}valueOf(){return{a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f}}}function po(){return new x(this.node.getCTM())}function mo(){try{if(typeof this.isRoot=="function"&&!this.isRoot()){const s=this.rect(1,1),t=s.node.getScreenCTM();return s.remove(),new x(t)}return new x(this.node.getScreenCTM())}catch{return console.warn(`Cannot get CTM from SVG node ${this.node.nodeName}. Is the element rendered?`),new x}}N(x,"Matrix");function vt(){if(!vt.nodes){const s=X().size(2,0);s.node.style.cssText=["opacity: 0","position: absolute","left: -100%","top: -100%","overflow: hidden"].join(";"),s.attr("focusable","false"),s.attr("aria-hidden","true");const t=s.path().node;vt.nodes={svg:s,path:t}}if(!vt.nodes.svg.node.parentNode){const s=I.document.body||I.document.documentElement;vt.nodes.svg.addTo(s)}return vt.nodes}function ai(s){return!s.width&&!s.height&&!s.x&&!s.y}function go(s){return s===I.document||(I.document.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t===I.document}).call(I.document.documentElement,s)}class K{constructor(...t){this.init(...t)}addOffset(){return this.x+=I.window.pageXOffset,this.y+=I.window.pageYOffset,new K(this)}init(t){const e=[0,0,0,0];return t=typeof t=="string"?t.split(bt).map(parseFloat):Array.isArray(t)?t:typeof t=="object"?[t.left!=null?t.left:t.x,t.top!=null?t.top:t.y,t.width,t.height]:arguments.length===4?[].slice.call(arguments):e,this.x=t[0]||0,this.y=t[1]||0,this.width=this.w=t[2]||0,this.height=this.h=t[3]||0,this.x2=this.x+this.w,this.y2=this.y+this.h,this.cx=this.x+this.w/2,this.cy=this.y+this.h/2,this}isNulled(){return ai(this)}merge(t){const e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x+t.width)-e,r=Math.max(this.y+this.height,t.y+t.height)-n;return new K(e,n,i,r)}toArray(){return[this.x,this.y,this.width,this.height]}toString(){return this.x+" "+this.y+" "+this.width+" "+this.height}transform(t){t instanceof x||(t=new x(t));let e=1/0,n=-1/0,i=1/0,r=-1/0;return[new W(this.x,this.y),new W(this.x2,this.y),new W(this.x,this.y2),new W(this.x2,this.y2)].forEach(function(a){a=a.transform(t),e=Math.min(e,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),r=Math.max(r,a.y)}),new K(e,i,n-e,r-i)}}function ci(s,t,e){let n;try{if(n=t(s.node),ai(n)&&!go(s.node))throw new Error("Element not in the dom")}catch{n=e(s)}return n}function yo(){const e=ci(this,i=>i.getBBox(),i=>{try{const r=i.clone().addTo(vt().svg).show(),o=r.node.getBBox();return r.remove(),o}catch(r){throw new Error(`Getting bbox of element "${i.node.nodeName}" is not possible: ${r.toString()}`)}});return new K(e)}function wo(s){const n=ci(this,r=>r.getBoundingClientRect(),r=>{throw new Error(`Getting rbox of element "${r.node.nodeName}" is not possible`)}),i=new K(n);return s?i.transform(s.screenCTM().inverseO()):i.addOffset()}function _o(s,t){const e=this.bbox();return s>e.x&&t>e.y&&s<e.x+e.width&&t<e.y+e.height}k({viewbox:{viewbox(s,t,e,n){return s==null?new K(this.attr("viewBox")):this.attr("viewBox",new K(s,t,e,n))},zoom(s,t){let{width:e,height:n}=this.attr(["width","height"]);if((!e&&!n||typeof e=="string"||typeof n=="string")&&(e=this.node.clientWidth,n=this.node.clientHeight),!e||!n)throw new Error("Impossible to get absolute width and height. Please provide an absolute width and height attribute on the zooming element");const i=this.viewbox(),r=e/i.width,o=n/i.height,a=Math.min(r,o);if(s==null)return a;let c=a/s;c===1/0&&(c=Number.MAX_SAFE_INTEGER/100),t=t||new W(e/2/r+i.x,n/2/o+i.y);const h=new K(i).transform(new x({scale:c,origin:t}));return this.viewbox(h)}}});N(K,"Box");class Pt extends Array{constructor(t=[],...e){if(super(t,...e),typeof t=="number")return this;this.length=0,this.push(...t)}}T([Pt],{each(s,...t){return typeof s=="function"?this.map((e,n,i)=>s.call(e,e,n,i)):this.map(e=>e[s](...t))},toArray(){return Array.prototype.concat.apply([],this)}});const bo=["toArray","constructor","each"];Pt.extend=function(s){s=s.reduce((t,e)=>(bo.includes(e)||e[0]==="_"||(e in Array.prototype&&(t["$"+e]=Array.prototype[e]),t[e]=function(...n){return this.each(e,...n)}),t),{}),T([Pt],s)};function de(s,t){return new Pt(ts((t||I.document).querySelectorAll(s),function(e){return st(e)}))}function vo(s){return de(s,this.node)}function Ao(s){return st(this.node.querySelector(s))}let So=0;const hi={};function li(s){let t=s.getEventHolder();return t===I.window&&(t=hi),t.events||(t.events={}),t.events}function rs(s){return s.getEventTarget()}function xo(s){let t=s.getEventHolder();t===I.window&&(t=hi),t.events&&(t.events={})}function kn(s,t,e,n,i){const r=e.bind(n||s),o=X(s),a=li(o),c=rs(o);t=Array.isArray(t)?t:t.split(bt),e._svgjsListenerId||(e._svgjsListenerId=++So),t.forEach(function(h){const l=h.split(".")[0],u=h.split(".")[1]||"*";a[l]=a[l]||{},a[l][u]=a[l][u]||{},a[l][u][e._svgjsListenerId]=r,c.addEventListener(l,r,i||!1)})}function Xt(s,t,e,n){const i=X(s),r=li(i),o=rs(i);typeof e=="function"&&(e=e._svgjsListenerId,!e)||(t=Array.isArray(t)?t:(t||"").split(bt),t.forEach(function(a){const c=a&&a.split(".")[0],h=a&&a.split(".")[1];let l,u;if(e)r[c]&&r[c][h||"*"]&&(o.removeEventListener(c,r[c][h||"*"][e],n||!1),delete r[c][h||"*"][e]);else if(c&&h){if(r[c]&&r[c][h]){for(u in r[c][h])Xt(o,[c,h].join("."),u);delete r[c][h]}}else if(h)for(a in r)for(l in r[a])h===l&&Xt(o,[a,h].join("."));else if(c){if(r[c]){for(l in r[c])Xt(o,[c,l].join("."));delete r[c]}}else{for(a in r)Xt(o,a);xo(i)}}))}function Eo(s,t,e,n){const i=rs(s);return t instanceof I.window.Event||(t=new I.window.CustomEvent(t,{detail:e,cancelable:!0,...n})),i.dispatchEvent(t),t}class De extends ns{addEventListener(){}dispatch(t,e,n){return Eo(this,t,e,n)}dispatchEvent(t){const e=this.getEventHolder().events;if(!e)return!0;const n=e[t.type];for(const i in n)for(const r in n[i])n[i][r](t);return!t.defaultPrevented}fire(t,e,n){return this.dispatch(t,e,n),this}getEventHolder(){return this}getEventTarget(){return this}off(t,e,n){return Xt(this,t,e,n),this}on(t,e,n,i){return kn(this,t,e,n,i),this}removeEventListener(){}}N(De,"EventTarget");function $s(){}const ye={duration:400,ease:">",delay:0},ko={"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","text-anchor":"start"};class ne extends Array{constructor(...t){super(...t),this.init(...t)}clone(){return new this.constructor(this)}init(t){return typeof t=="number"?this:(this.length=0,this.push(...this.parse(t)),this)}parse(t=[]){return t instanceof Array?t:t.trim().split(bt).map(parseFloat)}toArray(){return Array.prototype.concat.apply([],this)}toSet(){return new Set(this)}toString(){return this.join(" ")}valueOf(){const t=[];return t.push(...this),t}}class E{constructor(...t){this.init(...t)}convert(t){return new E(this.value,t)}divide(t){return t=new E(t),new E(this/t,this.unit||t.unit)}init(t,e){return e=Array.isArray(t)?t[1]:e,t=Array.isArray(t)?t[0]:t,this.value=0,this.unit=e||"",typeof t=="number"?this.value=isNaN(t)?0:isFinite(t)?t:t<0?-34e37:34e37:typeof t=="string"?(e=t.match(oi),e&&(this.value=parseFloat(e[1]),e[5]==="%"?this.value/=100:e[5]==="s"&&(this.value*=1e3),this.unit=e[5])):t instanceof E&&(this.value=t.valueOf(),this.unit=t.unit),this}minus(t){return t=new E(t),new E(this-t,this.unit||t.unit)}plus(t){return t=new E(t),new E(this+t,this.unit||t.unit)}times(t){return t=new E(t),new E(this*t,this.unit||t.unit)}toArray(){return[this.value,this.unit]}toJSON(){return this.toString()}toString(){return(this.unit==="%"?~~(this.value*1e8)/1e6:this.unit==="s"?this.value/1e3:this.value)+this.unit}valueOf(){return this.value}}const To=new Set(["fill","stroke","color","bgcolor","stop-color","flood-color","lighting-color"]),ui=[];function Oo(s){ui.push(s)}function Io(s,t,e){if(s==null){s={},t=this.node.attributes;for(const n of t)s[n.nodeName]=Hs.test(n.nodeValue)?parseFloat(n.nodeValue):n.nodeValue;return s}else{if(s instanceof Array)return s.reduce((n,i)=>(n[i]=this.attr(i),n),{});if(typeof s=="object"&&s.constructor===Object)for(t in s)this.attr(t,s[t]);else if(t===null)this.node.removeAttribute(s);else{if(t==null)return t=this.node.getAttribute(s),t==null?ko[s]:Hs.test(t)?parseFloat(t):t;t=ui.reduce((n,i)=>i(s,n,this),t),typeof t=="number"?t=new E(t):To.has(s)&&M.isColor(t)?t=new M(t):t.constructor===Array&&(t=new ne(t)),s==="leading"?this.leading&&this.leading(t):typeof e=="string"?this.node.setAttributeNS(e,s,t.toString()):this.node.setAttribute(s,t.toString()),this.rebuild&&(s==="font-size"||s==="x")&&this.rebuild()}}return this}class Tt extends De{constructor(t,e){super(),this.node=t,this.type=t.nodeName,e&&t!==e&&this.attr(e)}add(t,e){return t=X(t),t.removeNamespace&&this.node instanceof I.window.SVGElement&&t.removeNamespace(),e==null?this.node.appendChild(t.node):t.node!==this.node.childNodes[e]&&this.node.insertBefore(t.node,this.node.childNodes[e]),this}addTo(t,e){return X(t).put(this,e)}children(){return new Pt(ts(this.node.children,function(t){return st(t)}))}clear(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this}clone(t=!0,e=!0){this.writeDataToDom();let n=this.node.cloneNode(t);return e&&(n=ri(n)),new this.constructor(n)}each(t,e){const n=this.children();let i,r;for(i=0,r=n.length;i<r;i++)t.apply(n[i],[i,n]),e&&n[i].each(t,e);return this}element(t,e){return this.put(new Tt(Ae(t),e))}first(){return st(this.node.firstChild)}get(t){return st(this.node.childNodes[t])}getEventHolder(){return this.node}getEventTarget(){return this.node}has(t){return this.index(t)>=0}html(t,e){return this.xml(t,e,Tr)}id(t){return typeof t>"u"&&!this.node.id&&(this.node.id=ii(this.type)),this.attr("id",t)}index(t){return[].slice.call(this.node.childNodes).indexOf(t.node)}last(){return st(this.node.lastChild)}matches(t){const e=this.node,n=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector||null;return n&&n.call(e,t)}parent(t){let e=this;if(!e.node.parentNode)return null;if(e=st(e.node.parentNode),!t)return e;do if(typeof t=="string"?e.matches(t):e instanceof t)return e;while(e=st(e.node.parentNode));return e}put(t,e){return t=X(t),this.add(t,e),t}putIn(t,e){return X(t).add(this,e)}remove(){return this.parent()&&this.parent().removeElement(this),this}removeElement(t){return this.node.removeChild(t.node),this}replace(t){return t=X(t),this.node.parentNode&&this.node.parentNode.replaceChild(t.node,this.node),t}round(t=2,e=null){const n=10**t,i=this.attr(e);for(const r in i)typeof i[r]=="number"&&(i[r]=Math.round(i[r]*n)/n);return this.attr(i),this}svg(t,e){return this.xml(t,e,es)}toString(){return this.id()}words(t){return this.node.textContent=t,this}wrap(t){const e=this.parent();if(!e)return this.addTo(t);const n=e.index(this);return e.put(t,n).put(this)}writeDataToDom(){return this.each(function(){this.writeDataToDom()}),this}xml(t,e,n){if(typeof t=="boolean"&&(n=e,e=t,t=null),t==null||typeof t=="function"){e=e??!0,this.writeDataToDom();let a=this;if(t!=null){if(a=st(a.node.cloneNode(!0)),e){const c=t(a);if(a=c||a,c===!1)return""}a.each(function(){const c=t(this),h=c||this;c===!1?this.remove():c&&this!==h&&this.replace(h)},!0)}return e?a.node.outerHTML:a.node.innerHTML}e=e??!1;const i=Ae("wrapper",n),r=I.document.createDocumentFragment();i.innerHTML=t;for(let a=i.children.length;a--;)r.appendChild(i.firstElementChild);const o=this.parent();return e?this.replace(r)&&o:this.add(r)}}T(Tt,{attr:Io,find:vo,findOne:Ao});N(Tt,"Dom");class pt extends Tt{constructor(t,e){super(t,e),this.dom={},this.node.instance=this,(t.hasAttribute("data-svgjs")||t.hasAttribute("svgjs:data"))&&this.setData(JSON.parse(t.getAttribute("data-svgjs"))??JSON.parse(t.getAttribute("svgjs:data"))??{})}center(t,e){return this.cx(t).cy(e)}cx(t){return t==null?this.x()+this.width()/2:this.x(t-this.width()/2)}cy(t){return t==null?this.y()+this.height()/2:this.y(t-this.height()/2)}defs(){const t=this.root();return t&&t.defs()}dmove(t,e){return this.dx(t).dy(e)}dx(t=0){return this.x(new E(t).plus(this.x()))}dy(t=0){return this.y(new E(t).plus(this.y()))}getEventHolder(){return this}height(t){return this.attr("height",t)}move(t,e){return this.x(t).y(e)}parents(t=this.root()){const e=typeof t=="string";e||(t=X(t));const n=new Pt;let i=this;for(;(i=i.parent())&&i.node!==I.document&&i.nodeName!=="#document-fragment"&&(n.push(i),!(!e&&i.node===t.node||e&&i.matches(t)));)if(i.node===this.root().node)return null;return n}reference(t){if(t=this.attr(t),!t)return null;const e=(t+"").match(Fr);return e?X(e[1]):null}root(){const t=this.parent(Ir(ss));return t&&t.root()}setData(t){return this.dom=t,this}size(t,e){const n=fe(this,t,e);return this.width(new E(n.width)).height(new E(n.height))}width(t){return this.attr("width",t)}writeDataToDom(){return si(this,this.dom),super.writeDataToDom()}x(t){return this.attr("x",t)}y(t){return this.attr("y",t)}}T(pt,{bbox:yo,rbox:wo,inside:_o,point:fo,ctm:po,screenCTM:mo});N(pt,"Element");const me={stroke:["color","width","opacity","linecap","linejoin","miterlimit","dasharray","dashoffset"],fill:["color","opacity","rule"],prefix:function(s,t){return t==="color"?s:s+"-"+t}};["fill","stroke"].forEach(function(s){const t={};let e;t[s]=function(n){if(typeof n>"u")return this.attr(s);if(typeof n=="string"||n instanceof M||M.isRgb(n)||n instanceof pt)this.attr(s,n);else for(e=me[s].length-1;e>=0;e--)n[me[s][e]]!=null&&this.attr(me.prefix(s,me[s][e]),n[me[s][e]]);return this},k(["Element","Runner"],t)});k(["Element","Runner"],{matrix:function(s,t,e,n,i,r){return s==null?new x(this):this.attr("transform",new x(s,t,e,n,i,r))},rotate:function(s,t,e){return this.transform({rotate:s,ox:t,oy:e},!0)},skew:function(s,t,e,n){return arguments.length===1||arguments.length===3?this.transform({skew:s,ox:t,oy:e},!0):this.transform({skew:[s,t],ox:e,oy:n},!0)},shear:function(s,t,e){return this.transform({shear:s,ox:t,oy:e},!0)},scale:function(s,t,e,n){return arguments.length===1||arguments.length===3?this.transform({scale:s,ox:t,oy:e},!0):this.transform({scale:[s,t],ox:e,oy:n},!0)},translate:function(s,t){return this.transform({translate:[s,t]},!0)},relative:function(s,t){return this.transform({relative:[s,t]},!0)},flip:function(s="both",t="center"){return"xybothtrue".indexOf(s)===-1&&(t=s,s="both"),this.transform({flip:s,origin:t},!0)},opacity:function(s){return this.attr("opacity",s)}});k("radius",{radius:function(s,t=s){return(this._element||this).type==="radialGradient"?this.attr("r",new E(s)):this.rx(s).ry(t)}});k("Path",{length:function(){return this.node.getTotalLength()},pointAt:function(s){return new W(this.node.getPointAtLength(s))}});k(["Element","Runner"],{font:function(s,t){if(typeof s=="object"){for(t in s)this.font(t,s[t]);return this}return s==="leading"?this.leading(t):s==="anchor"?this.attr("text-anchor",t):s==="size"||s==="family"||s==="weight"||s==="stretch"||s==="variant"||s==="style"?this.attr("font-"+s,t):this.attr(s,t)}});const No=["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","touchstart","touchmove","touchleave","touchend","touchcancel","contextmenu","wheel","pointerdown","pointermove","pointerup","pointerleave","pointercancel"].reduce(function(s,t){const e=function(n){return n===null?this.off(t):this.on(t,n),this};return s[t]=e,s},{});k("Element",No);function Do(){return this.attr("transform",null)}function Co(){return(this.attr("transform")||"").split(qr).slice(0,-1).map(function(t){const e=t.trim().split("(");return[e[0],e[1].split(bt).map(function(n){return parseFloat(n)})]}).reverse().reduce(function(t,e){return e[0]==="matrix"?t.lmultiply(x.fromArray(e[1])):t[e[0]].apply(t,e[1])},new x)}function Mo(s,t){if(this===s)return this;if(En(this.node))return this.addTo(s,t);const e=this.screenCTM(),n=s.screenCTM().inverse();return this.addTo(s,t).untransform().transform(n.multiply(e)),this}function Ro(s){return this.toParent(this.root(),s)}function Ho(s,t){if(s==null||typeof s=="string"){const i=new x(this).decompose();return s==null?i:i[s]}x.isMatrixLike(s)||(s={...s,origin:xn(s,this)});const e=t===!0?this:t||!1,n=new x(e).transform(s);return this.attr("transform",n)}k("Element",{untransform:Do,matrixify:Co,toParent:Mo,toRoot:Ro,transform:Ho});class V extends pt{flatten(){return this.each(function(){if(this instanceof V)return this.flatten().ungroup()}),this}ungroup(t=this.parent(),e=t.index(this)){return e=e===-1?t.children().length:e,this.each(function(n,i){return i[i.length-n-1].toParent(t,e)}),this.remove()}}N(V,"Container");class os extends V{constructor(t,e=t){super($("defs",t),e)}flatten(){return this}ungroup(){return this}}N(os,"Defs");class nt extends pt{}N(nt,"Shape");function as(s){return this.attr("rx",s)}function cs(s){return this.attr("ry",s)}function fi(s){return s==null?this.cx()-this.rx():this.cx(s+this.rx())}function di(s){return s==null?this.cy()-this.ry():this.cy(s+this.ry())}function pi(s){return this.attr("cx",s)}function mi(s){return this.attr("cy",s)}function gi(s){return s==null?this.rx()*2:this.rx(new E(s).divide(2))}function yi(s){return s==null?this.ry()*2:this.ry(new E(s).divide(2))}const $o=Object.freeze(Object.defineProperty({__proto__:null,cx:pi,cy:mi,height:yi,rx:as,ry:cs,width:gi,x:fi,y:di},Symbol.toStringTag,{value:"Module"}));class sn extends nt{constructor(t,e=t){super($("ellipse",t),e)}size(t,e){const n=fe(this,t,e);return this.rx(new E(n.width).divide(2)).ry(new E(n.height).divide(2))}}T(sn,$o);k("Container",{ellipse:H(function(s=0,t=s){return this.put(new sn).size(s,t).move(0,0)})});N(sn,"Ellipse");class wi extends Tt{constructor(t=I.document.createDocumentFragment()){super(t)}xml(t,e,n){if(typeof t=="boolean"&&(n=e,e=t,t=null),t==null||typeof t=="function"){const i=new Tt(Ae("wrapper",n));return i.add(this.node.cloneNode(!0)),i.xml(!1,n)}return super.xml(t,!1,n)}}N(wi,"Fragment");function _i(s,t){return(this._element||this).type==="radialGradient"?this.attr({fx:new E(s),fy:new E(t)}):this.attr({x1:new E(s),y1:new E(t)})}function bi(s,t){return(this._element||this).type==="radialGradient"?this.attr({cx:new E(s),cy:new E(t)}):this.attr({x2:new E(s),y2:new E(t)})}const Bo=Object.freeze(Object.defineProperty({__proto__:null,from:_i,to:bi},Symbol.toStringTag,{value:"Module"}));class Ce extends V{constructor(t,e){super($(t+"Gradient",typeof t=="string"?null:t),e)}attr(t,e,n){return t==="transform"&&(t="gradientTransform"),super.attr(t,e,n)}bbox(){return new K}targets(){return de("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}url(){return"url(#"+this.id()+")"}}T(Ce,Bo);k({Container:{gradient(...s){return this.defs().gradient(...s)}},Defs:{gradient:H(function(s,t){return this.put(new Ce(s)).update(t)})}});N(Ce,"Gradient");class Se extends V{constructor(t,e=t){super($("pattern",t),e)}attr(t,e,n){return t==="transform"&&(t="patternTransform"),super.attr(t,e,n)}bbox(){return new K}targets(){return de("svg [fill*="+this.id()+"]")}toString(){return this.url()}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}url(){return"url(#"+this.id()+")"}}k({Container:{pattern(...s){return this.defs().pattern(...s)}},Defs:{pattern:H(function(s,t,e){return this.put(new Se).update(e).attr({x:0,y:0,width:s,height:t,patternUnits:"userSpaceOnUse"})})}});N(Se,"Pattern");class Me extends nt{constructor(t,e=t){super($("image",t),e)}load(t,e){if(!t)return this;const n=new I.window.Image;return kn(n,"load",function(i){const r=this.parent(Se);this.width()===0&&this.height()===0&&this.size(n.width,n.height),r instanceof Se&&r.width()===0&&r.height()===0&&r.size(this.width(),this.height()),typeof e=="function"&&e.call(this,i)},this),kn(n,"load error",function(){Xt(n)}),this.attr("href",n.src=t,Ne)}}Oo(function(s,t,e){return(s==="fill"||s==="stroke")&&Zr.test(t)&&(t=e.root().defs().image(t)),t instanceof Me&&(t=e.root().defs().pattern(0,0,n=>{n.add(t)})),t});k({Container:{image:H(function(s,t){return this.put(new Me).size(0,0).load(s,t)})}});N(Me,"Image");class Ot extends ne{bbox(){let t=-1/0,e=-1/0,n=1/0,i=1/0;return this.forEach(function(r){t=Math.max(r[0],t),e=Math.max(r[1],e),n=Math.min(r[0],n),i=Math.min(r[1],i)}),new K(n,i,t-n,e-i)}move(t,e){const n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(let i=this.length-1;i>=0;i--)this[i]=[this[i][0]+t,this[i][1]+e];return this}parse(t=[0,0]){const e=[];t instanceof Array?t=Array.prototype.concat.apply([],t):t=t.trim().split(bt).map(parseFloat),t.length%2!==0&&t.pop();for(let n=0,i=t.length;n<i;n=n+2)e.push([t[n],t[n+1]]);return e}size(t,e){let n;const i=this.bbox();for(n=this.length-1;n>=0;n--)i.width&&(this[n][0]=(this[n][0]-i.x)*t/i.width+i.x),i.height&&(this[n][1]=(this[n][1]-i.y)*e/i.height+i.y);return this}toLine(){return{x1:this[0][0],y1:this[0][1],x2:this[1][0],y2:this[1][1]}}toString(){const t=[];for(let e=0,n=this.length;e<n;e++)t.push(this[e].join(","));return t.join(" ")}transform(t){return this.clone().transformO(t)}transformO(t){x.isMatrixLike(t)||(t=new x(t));for(let e=this.length;e--;){const[n,i]=this[e];this[e][0]=t.a*n+t.c*i+t.e,this[e][1]=t.b*n+t.d*i+t.f}return this}}const Wo=Ot;function Po(s){return s==null?this.bbox().x:this.move(s,this.bbox().y)}function jo(s){return s==null?this.bbox().y:this.move(this.bbox().x,s)}function zo(s){const t=this.bbox();return s==null?t.width:this.size(s,t.height)}function Ko(s){const t=this.bbox();return s==null?t.height:this.size(t.width,s)}const hs=Object.freeze(Object.defineProperty({__proto__:null,MorphArray:Wo,height:Ko,width:zo,x:Po,y:jo},Symbol.toStringTag,{value:"Module"}));class xe extends nt{constructor(t,e=t){super($("line",t),e)}array(){return new Ot([[this.attr("x1"),this.attr("y1")],[this.attr("x2"),this.attr("y2")]])}move(t,e){return this.attr(this.array().move(t,e).toLine())}plot(t,e,n,i){return t==null?this.array():(typeof e<"u"?t={x1:t,y1:e,x2:n,y2:i}:t=new Ot(t).toLine(),this.attr(t))}size(t,e){const n=fe(this,t,e);return this.attr(this.array().size(n.width,n.height).toLine())}}T(xe,hs);k({Container:{line:H(function(...s){return xe.prototype.plot.apply(this.put(new xe),s[0]!=null?s:[0,0,0,0])})}});N(xe,"Line");class Ge extends V{constructor(t,e=t){super($("marker",t),e)}height(t){return this.attr("markerHeight",t)}orient(t){return this.attr("orient",t)}ref(t,e){return this.attr("refX",t).attr("refY",e)}toString(){return"url(#"+this.id()+")"}update(t){return this.clear(),typeof t=="function"&&t.call(this,this),this}width(t){return this.attr("markerWidth",t)}}k({Container:{marker(...s){return this.defs().marker(...s)}},Defs:{marker:H(function(s,t,e){return this.put(new Ge).size(s,t).ref(s/2,t/2).viewbox(0,0,s,t).attr("orient","auto").update(e)})},marker:{marker(s,t,e,n){let i=["marker"];return s!=="all"&&i.push(s),i=i.join("-"),s=arguments[1]instanceof Ge?arguments[1]:this.defs().marker(t,e,n),this.attr(i,s)}}});N(Ge,"Marker");function Jt(s,t){return function(e){return e==null?this[s]:(this[s]=e,t&&t.call(this),this)}}const Lo={"-":function(s){return s},"<>":function(s){return-Math.cos(s*Math.PI)/2+.5},">":function(s){return Math.sin(s*Math.PI/2)},"<":function(s){return-Math.cos(s*Math.PI/2)+1},bezier:function(s,t,e,n){return function(i){return i<0?s>0?t/s*i:e>0?n/e*i:0:i>1?e<1?(1-n)/(1-e)*i+(n-e)/(1-e):s<1?(1-t)/(1-s)*i+(t-s)/(1-s):1:3*i*(1-i)**2*t+3*i**2*(1-i)*n+i**3}},steps:function(s,t="end"){t=t.split("-").reverse()[0];let e=s;return t==="none"?--e:t==="both"&&++e,(n,i=!1)=>{let r=Math.floor(n*s);const o=n*r%1===0;return(t==="start"||t==="both")&&++r,i&&o&&--r,n>=0&&r<0&&(r=0),n<=1&&r>e&&(r=e),r/e}}};class ls{done(){return!1}}class Tn extends ls{constructor(t=ye.ease){super(),this.ease=Lo[t]||t}step(t,e,n){return typeof t!="number"?n<1?t:e:t+(e-t)*this.ease(n)}}let Ze=class extends ls{constructor(t){super(),this.stepper=t}done(t){return t.done}step(t,e,n,i){return this.stepper(t,e,n,i)}};function Bs(){const s=(this._duration||500)/1e3,t=this._overshoot||0,e=1e-10,n=Math.PI,i=Math.log(t/100+e),r=-i/Math.sqrt(n*n+i*i),o=3.9/(r*s);this.d=2*r*o,this.k=o*o}class Uo extends Ze{constructor(t=500,e=0){super(),this.duration(t).overshoot(e)}step(t,e,n,i){if(typeof t=="string")return t;if(i.done=n===1/0,n===1/0)return e;if(n===0)return t;n>100&&(n=16),n/=1e3;const r=i.velocity||0,o=-this.d*r-this.k*(t-e),a=t+r*n+o*n*n/2;return i.velocity=r+o*n,i.done=Math.abs(e-a)+Math.abs(r)<.002,i.done?e:a}}T(Uo,{duration:Jt("_duration",Bs),overshoot:Jt("_overshoot",Bs)});class Fo extends Ze{constructor(t=.1,e=.01,n=0,i=1e3){super(),this.p(t).i(e).d(n).windup(i)}step(t,e,n,i){if(typeof t=="string")return t;if(i.done=n===1/0,n===1/0)return e;if(n===0)return t;const r=e-t;let o=(i.integral||0)+r*n;const a=(r-(i.error||0))/n,c=this._windup;return c!==!1&&(o=Math.max(-c,Math.min(o,c))),i.error=r,i.integral=o,i.done=Math.abs(r)<.001,i.done?e:t+(this.P*r+this.I*o+this.D*a)}}T(Fo,{windup:Jt("_windup"),p:Jt("P"),i:Jt("I"),d:Jt("D")});const qo={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},On={M:function(s,t,e){return t.x=e.x=s[0],t.y=e.y=s[1],["M",t.x,t.y]},L:function(s,t){return t.x=s[0],t.y=s[1],["L",s[0],s[1]]},H:function(s,t){return t.x=s[0],["H",s[0]]},V:function(s,t){return t.y=s[0],["V",s[0]]},C:function(s,t){return t.x=s[4],t.y=s[5],["C",s[0],s[1],s[2],s[3],s[4],s[5]]},S:function(s,t){return t.x=s[2],t.y=s[3],["S",s[0],s[1],s[2],s[3]]},Q:function(s,t){return t.x=s[2],t.y=s[3],["Q",s[0],s[1],s[2],s[3]]},T:function(s,t){return t.x=s[0],t.y=s[1],["T",s[0],s[1]]},Z:function(s,t,e){return t.x=e.x,t.y=e.y,["Z"]},A:function(s,t){return t.x=s[5],t.y=s[6],["A",s[0],s[1],s[2],s[3],s[4],s[5],s[6]]}},mn="mlhvqtcsaz".split("");for(let s=0,t=mn.length;s<t;++s)On[mn[s]]=function(e){return function(n,i,r){if(e==="H")n[0]=n[0]+i.x;else if(e==="V")n[0]=n[0]+i.y;else if(e==="A")n[5]=n[5]+i.x,n[6]=n[6]+i.y;else for(let o=0,a=n.length;o<a;++o)n[o]=n[o]+(o%2?i.y:i.x);return On[e](n,i,r)}}(mn[s].toUpperCase());function Go(s){const t=s.segment[0];return On[t](s.segment.slice(1),s.p,s.p0)}function In(s){return s.segment.length&&s.segment.length-1===qo[s.segment[0].toUpperCase()]}function Zo(s,t){s.inNumber&&Mt(s,!1);const e=is.test(t);if(e)s.segment=[t];else{const n=s.lastCommand,i=n.toLowerCase(),r=n===i;s.segment=[i==="m"?r?"l":"L":n]}return s.inSegment=!0,s.lastCommand=s.segment[0],e}function Mt(s,t){if(!s.inNumber)throw new Error("Parser Error");s.number&&s.segment.push(parseFloat(s.number)),s.inNumber=t,s.number="",s.pointSeen=!1,s.hasExponent=!1,In(s)&&Nn(s)}function Nn(s){s.inSegment=!1,s.absolute&&(s.segment=Go(s)),s.segments.push(s.segment)}function Yo(s){if(!s.segment.length)return!1;const t=s.segment[0].toUpperCase()==="A",e=s.segment.length;return t&&(e===4||e===5)}function Xo(s){return s.lastToken.toUpperCase()==="E"}const Jo=new Set([" ",","," ",`
|
|
2
|
-
`,"\r","\f"]);function Vo(s,t=!0){let e=0,n="";const i={segment:[],inNumber:!1,number:"",lastToken:"",inSegment:!1,segments:[],pointSeen:!1,hasExponent:!1,absolute:t,p0:new W,p:new W};for(;i.lastToken=n,n=s.charAt(e++);)if(!(!i.inSegment&&Zo(i,n))){if(n==="."){if(i.pointSeen||i.hasExponent){Mt(i,!1),--e;continue}i.inNumber=!0,i.pointSeen=!0,i.number+=n;continue}if(!isNaN(parseInt(n))){if(i.number==="0"||Yo(i)){i.inNumber=!0,i.number=n,Mt(i,!0);continue}i.inNumber=!0,i.number+=n;continue}if(Jo.has(n)){i.inNumber&&Mt(i,!1);continue}if(n==="-"||n==="+"){if(i.inNumber&&!Xo(i)){Mt(i,!1),--e;continue}i.number+=n,i.inNumber=!0;continue}if(n.toUpperCase()==="E"){i.number+=n,i.hasExponent=!0;continue}if(is.test(n)){if(i.inNumber)Mt(i,!1);else if(In(i))Nn(i);else throw new Error("parser Error");--e}}return i.inNumber&&Mt(i,!1),i.inSegment&&In(i)&&Nn(i),i.segments}function Qo(s){let t="";for(let e=0,n=s.length;e<n;e++)t+=s[e][0],s[e][1]!=null&&(t+=s[e][1],s[e][2]!=null&&(t+=" ",t+=s[e][2],s[e][3]!=null&&(t+=" ",t+=s[e][3],t+=" ",t+=s[e][4],s[e][5]!=null&&(t+=" ",t+=s[e][5],t+=" ",t+=s[e][6],s[e][7]!=null&&(t+=" ",t+=s[e][7])))));return t+" "}class jt extends ne{bbox(){return vt().path.setAttribute("d",this.toString()),new K(vt.nodes.path.getBBox())}move(t,e){const n=this.bbox();if(t-=n.x,e-=n.y,!isNaN(t)&&!isNaN(e))for(let i,r=this.length-1;r>=0;r--)i=this[r][0],i==="M"||i==="L"||i==="T"?(this[r][1]+=t,this[r][2]+=e):i==="H"?this[r][1]+=t:i==="V"?this[r][1]+=e:i==="C"||i==="S"||i==="Q"?(this[r][1]+=t,this[r][2]+=e,this[r][3]+=t,this[r][4]+=e,i==="C"&&(this[r][5]+=t,this[r][6]+=e)):i==="A"&&(this[r][6]+=t,this[r][7]+=e);return this}parse(t="M0 0"){return Array.isArray(t)&&(t=Array.prototype.concat.apply([],t).toString()),Vo(t)}size(t,e){const n=this.bbox();let i,r;for(n.width=n.width===0?1:n.width,n.height=n.height===0?1:n.height,i=this.length-1;i>=0;i--)r=this[i][0],r==="M"||r==="L"||r==="T"?(this[i][1]=(this[i][1]-n.x)*t/n.width+n.x,this[i][2]=(this[i][2]-n.y)*e/n.height+n.y):r==="H"?this[i][1]=(this[i][1]-n.x)*t/n.width+n.x:r==="V"?this[i][1]=(this[i][1]-n.y)*e/n.height+n.y:r==="C"||r==="S"||r==="Q"?(this[i][1]=(this[i][1]-n.x)*t/n.width+n.x,this[i][2]=(this[i][2]-n.y)*e/n.height+n.y,this[i][3]=(this[i][3]-n.x)*t/n.width+n.x,this[i][4]=(this[i][4]-n.y)*e/n.height+n.y,r==="C"&&(this[i][5]=(this[i][5]-n.x)*t/n.width+n.x,this[i][6]=(this[i][6]-n.y)*e/n.height+n.y)):r==="A"&&(this[i][1]=this[i][1]*t/n.width,this[i][2]=this[i][2]*e/n.height,this[i][6]=(this[i][6]-n.x)*t/n.width+n.x,this[i][7]=(this[i][7]-n.y)*e/n.height+n.y);return this}toString(){return Qo(this)}}const vi=s=>{const t=typeof s;return t==="number"?E:t==="string"?M.isColor(s)?M:bt.test(s)?is.test(s)?jt:ne:oi.test(s)?E:Dn:us.indexOf(s.constructor)>-1?s.constructor:Array.isArray(s)?ne:t==="object"?Ee:Dn};class Rt{constructor(t){this._stepper=t||new Tn("-"),this._from=null,this._to=null,this._type=null,this._context=null,this._morphObj=null}at(t){return this._morphObj.morph(this._from,this._to,t,this._stepper,this._context)}done(){return this._context.map(this._stepper.done).reduce(function(e,n){return e&&n},!0)}from(t){return t==null?this._from:(this._from=this._set(t),this)}stepper(t){return t==null?this._stepper:(this._stepper=t,this)}to(t){return t==null?this._to:(this._to=this._set(t),this)}type(t){return t==null?this._type:(this._type=t,this)}_set(t){this._type||this.type(vi(t));let e=new this._type(t);return this._type===M&&(e=this._to?e[this._to[4]]():this._from?e[this._from[4]]():e),this._type===Ee&&(e=this._to?e.align(this._to):this._from?e.align(this._from):e),e=e.toConsumable(),this._morphObj=this._morphObj||new this._type,this._context=this._context||Array.apply(null,Array(e.length)).map(Object).map(function(n){return n.done=!0,n}),e}}class Dn{constructor(...t){this.init(...t)}init(t){return t=Array.isArray(t)?t[0]:t,this.value=t,this}toArray(){return[this.value]}valueOf(){return this.value}}class Re{constructor(...t){this.init(...t)}init(t){return Array.isArray(t)&&(t={scaleX:t[0],scaleY:t[1],shear:t[2],rotate:t[3],translateX:t[4],translateY:t[5],originX:t[6],originY:t[7]}),Object.assign(this,Re.defaults,t),this}toArray(){const t=this;return[t.scaleX,t.scaleY,t.shear,t.rotate,t.translateX,t.translateY,t.originX,t.originY]}}Re.defaults={scaleX:1,scaleY:1,shear:0,rotate:0,translateX:0,translateY:0,originX:0,originY:0};const ta=(s,t)=>s[0]<t[0]?-1:s[0]>t[0]?1:0;class Ee{constructor(...t){this.init(...t)}align(t){const e=this.values;for(let n=0,i=e.length;n<i;++n){if(e[n+1]===t[n+1]){if(e[n+1]===M&&t[n+7]!==e[n+7]){const a=t[n+7],c=new M(this.values.splice(n+3,5))[a]().toArray();this.values.splice(n+3,0,...c)}n+=e[n+2]+2;continue}if(!t[n+1])return this;const r=new t[n+1]().toArray(),o=e[n+2]+3;e.splice(n,o,t[n],t[n+1],t[n+2],...r),n+=e[n+2]+2}return this}init(t){if(this.values=[],Array.isArray(t)){this.values=t.slice();return}t=t||{};const e=[];for(const n in t){const i=vi(t[n]),r=new i(t[n]).toArray();e.push([n,i,r.length,...r])}return e.sort(ta),this.values=e.reduce((n,i)=>n.concat(i),[]),this}toArray(){return this.values}valueOf(){const t={},e=this.values;for(;e.length;){const n=e.shift(),i=e.shift(),r=e.shift(),o=e.splice(0,r);t[n]=new i(o)}return t}}const us=[Dn,Re,Ee];function ea(s=[]){us.push(...[].concat(s))}function na(){T(us,{to(s){return new Rt().type(this.constructor).from(this.toArray()).to(s)},fromArray(s){return this.init(s),this},toConsumable(){return this.toArray()},morph(s,t,e,n,i){const r=function(o,a){return n.step(o,t[a],e,i[a],i)};return this.fromArray(s.map(r))}})}class pe extends nt{constructor(t,e=t){super($("path",t),e)}array(){return this._array||(this._array=new jt(this.attr("d")))}clear(){return delete this._array,this}height(t){return t==null?this.bbox().height:this.size(this.bbox().width,t)}move(t,e){return this.attr("d",this.array().move(t,e))}plot(t){return t==null?this.array():this.clear().attr("d",typeof t=="string"?t:this._array=new jt(t))}size(t,e){const n=fe(this,t,e);return this.attr("d",this.array().size(n.width,n.height))}width(t){return t==null?this.bbox().width:this.size(t,this.bbox().height)}x(t){return t==null?this.bbox().x:this.move(t,this.bbox().y)}y(t){return t==null?this.bbox().y:this.move(this.bbox().x,t)}}pe.prototype.MorphArray=jt;k({Container:{path:H(function(s){return this.put(new pe).plot(s||new jt)})}});N(pe,"Path");function sa(){return this._array||(this._array=new Ot(this.attr("points")))}function ia(){return delete this._array,this}function ra(s,t){return this.attr("points",this.array().move(s,t))}function oa(s){return s==null?this.array():this.clear().attr("points",typeof s=="string"?s:this._array=new Ot(s))}function aa(s,t){const e=fe(this,s,t);return this.attr("points",this.array().size(e.width,e.height))}const Ai=Object.freeze(Object.defineProperty({__proto__:null,array:sa,clear:ia,move:ra,plot:oa,size:aa},Symbol.toStringTag,{value:"Module"}));class He extends nt{constructor(t,e=t){super($("polygon",t),e)}}k({Container:{polygon:H(function(s){return this.put(new He).plot(s||new Ot)})}});T(He,hs);T(He,Ai);N(He,"Polygon");class $e extends nt{constructor(t,e=t){super($("polyline",t),e)}}k({Container:{polyline:H(function(s){return this.put(new $e).plot(s||new Ot)})}});T($e,hs);T($e,Ai);N($e,"Polyline");class Be extends nt{constructor(t,e=t){super($("rect",t),e)}}T(Be,{rx:as,ry:cs});k({Container:{rect:H(function(s,t){return this.put(new Be).size(s,t)})}});N(Be,"Rect");class gn{constructor(){this._first=null,this._last=null}first(){return this._first&&this._first.value}last(){return this._last&&this._last.value}push(t){const e=typeof t.next<"u"?t:{value:t,next:null,prev:null};return this._last?(e.prev=this._last,this._last.next=e,this._last=e):(this._last=e,this._first=e),e}remove(t){t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t===this._last&&(this._last=t.prev),t===this._first&&(this._first=t.next),t.prev=null,t.next=null}shift(){const t=this._first;return t?(this._first=t.next,this._first&&(this._first.prev=null),this._last=this._first?this._last:null,t.value):null}}const C={nextDraw:null,frames:new gn,timeouts:new gn,immediates:new gn,timer:()=>I.window.performance||I.window.Date,transforms:[],frame(s){const t=C.frames.push({run:s});return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),t},timeout(s,t){t=t||0;const e=C.timer().now()+t,n=C.timeouts.push({run:s,time:e});return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),n},immediate(s){const t=C.immediates.push(s);return C.nextDraw===null&&(C.nextDraw=I.window.requestAnimationFrame(C._draw)),t},cancelFrame(s){s!=null&&C.frames.remove(s)},clearTimeout(s){s!=null&&C.timeouts.remove(s)},cancelImmediate(s){s!=null&&C.immediates.remove(s)},_draw(s){let t=null;const e=C.timeouts.last();for(;(t=C.timeouts.shift())&&(s>=t.time?t.run():C.timeouts.push(t),t!==e););let n=null;const i=C.frames.last();for(;n!==i&&(n=C.frames.shift());)n.run(s);let r=null;for(;r=C.immediates.shift();)r();C.nextDraw=C.timeouts.first()||C.frames.first()?I.window.requestAnimationFrame(C._draw):null}},ca=function(s){const t=s.start,e=s.runner.duration(),n=t+e;return{start:t,duration:e,end:n,runner:s.runner}},ha=function(){const s=I.window;return(s.performance||s.Date).now()};class Si extends De{constructor(t=ha){super(),this._timeSource=t,this.terminate()}active(){return!!this._nextFrame}finish(){return this.time(this.getEndTimeOfTimeline()+1),this.pause()}getEndTime(){const t=this.getLastRunnerInfo(),e=t?t.runner.duration():0;return(t?t.start:this._time)+e}getEndTimeOfTimeline(){const t=this._runners.map(e=>e.start+e.runner.duration());return Math.max(0,...t)}getLastRunnerInfo(){return this.getRunnerInfoById(this._lastRunnerId)}getRunnerInfoById(t){return this._runners[this._runnerIds.indexOf(t)]||null}pause(){return this._paused=!0,this._continue()}persist(t){return t==null?this._persist:(this._persist=t,this)}play(){return this._paused=!1,this.updateTime()._continue()}reverse(t){const e=this.speed();if(t==null)return this.speed(-e);const n=Math.abs(e);return this.speed(t?-n:n)}schedule(t,e,n){if(t==null)return this._runners.map(ca);let i=0;const r=this.getEndTime();if(e=e||0,n==null||n==="last"||n==="after")i=r;else if(n==="absolute"||n==="start")i=e,e=0;else if(n==="now")i=this._time;else if(n==="relative"){const c=this.getRunnerInfoById(t.id);c&&(i=c.start+e,e=0)}else if(n==="with-last"){const c=this.getLastRunnerInfo();i=c?c.start:this._time}else throw new Error('Invalid value for the "when" parameter');t.unschedule(),t.timeline(this);const o=t.persist(),a={persist:o===null?this._persist:o,start:i+e,runner:t};return this._lastRunnerId=t.id,this._runners.push(a),this._runners.sort((c,h)=>c.start-h.start),this._runnerIds=this._runners.map(c=>c.runner.id),this.updateTime()._continue(),this}seek(t){return this.time(this._time+t)}source(t){return t==null?this._timeSource:(this._timeSource=t,this)}speed(t){return t==null?this._speed:(this._speed=t,this)}stop(){return this.time(0),this.pause()}time(t){return t==null?this._time:(this._time=t,this._continue(!0))}unschedule(t){const e=this._runnerIds.indexOf(t.id);return e<0?this:(this._runners.splice(e,1),this._runnerIds.splice(e,1),t.timeline(null),this)}updateTime(){return this.active()||(this._lastSourceTime=this._timeSource()),this}_continue(t=!1){return C.cancelFrame(this._nextFrame),this._nextFrame=null,t?this._stepImmediate():this._paused?this:(this._nextFrame=C.frame(this._step),this)}_stepFn(t=!1){const e=this._timeSource();let n=e-this._lastSourceTime;t&&(n=0);const i=this._speed*n+(this._time-this._lastStepTime);this._lastSourceTime=e,t||(this._time+=i,this._time=this._time<0?0:this._time),this._lastStepTime=this._time,this.fire("time",this._time);for(let o=this._runners.length;o--;){const a=this._runners[o],c=a.runner;this._time-a.start<=0&&c.reset()}let r=!1;for(let o=0,a=this._runners.length;o<a;o++){const c=this._runners[o],h=c.runner;let l=i;const u=this._time-c.start;if(u<=0){r=!0;continue}else u<l&&(l=u);if(!h.active())continue;h.step(l).done?c.persist!==!0&&h.duration()-h.time()+this._time+c.persist<this._time&&(h.unschedule(),--o,--a):r=!0}return r&&!(this._speed<0&&this._time===0)||this._runnerIds.length&&this._speed<0&&this._time>0?this._continue():(this.pause(),this.fire("finished")),this}terminate(){this._startTime=0,this._speed=1,this._persist=0,this._nextFrame=null,this._paused=!0,this._runners=[],this._runnerIds=[],this._lastRunnerId=-1,this._time=0,this._lastSourceTime=0,this._lastStepTime=0,this._step=this._stepFn.bind(this,!1),this._stepImmediate=this._stepFn.bind(this,!0)}}k({Element:{timeline:function(s){return s==null?(this._timeline=this._timeline||new Si,this._timeline):(this._timeline=s,this)}}});class et extends De{constructor(t){super(),this.id=et.id++,t=t??ye.duration,t=typeof t=="function"?new Ze(t):t,this._element=null,this._timeline=null,this.done=!1,this._queue=[],this._duration=typeof t=="number"&&t,this._isDeclarative=t instanceof Ze,this._stepper=this._isDeclarative?t:new Tn,this._history={},this.enabled=!0,this._time=0,this._lastTime=0,this._reseted=!0,this.transforms=new x,this.transformId=1,this._haveReversed=!1,this._reverse=!1,this._loopsDone=0,this._swing=!1,this._wait=0,this._times=1,this._frameId=null,this._persist=this._isDeclarative?!0:null}static sanitise(t,e,n){let i=1,r=!1,o=0;return t=t??ye.duration,e=e??ye.delay,n=n||"last",typeof t=="object"&&!(t instanceof ls)&&(e=t.delay??e,n=t.when??n,r=t.swing||r,i=t.times??i,o=t.wait??o,t=t.duration??ye.duration),{duration:t,delay:e,swing:r,times:i,wait:o,when:n}}active(t){return t==null?this.enabled:(this.enabled=t,this)}addTransform(t){return this.transforms.lmultiplyO(t),this}after(t){return this.on("finished",t)}animate(t,e,n){const i=et.sanitise(t,e,n),r=new et(i.duration);return this._timeline&&r.timeline(this._timeline),this._element&&r.element(this._element),r.loop(i).schedule(i.delay,i.when)}clearTransform(){return this.transforms=new x,this}clearTransformsFromQueue(){(!this.done||!this._timeline||!this._timeline._runnerIds.includes(this.id))&&(this._queue=this._queue.filter(t=>!t.isTransform))}delay(t){return this.animate(0,t)}duration(){return this._times*(this._wait+this._duration)-this._wait}during(t){return this.queue(null,t)}ease(t){return this._stepper=new Tn(t),this}element(t){return t==null?this._element:(this._element=t,t._prepareRunner(),this)}finish(){return this.step(1/0)}loop(t,e,n){return typeof t=="object"&&(e=t.swing,n=t.wait,t=t.times),this._times=t||1/0,this._swing=e||!1,this._wait=n||0,this._times===!0&&(this._times=1/0),this}loops(t){const e=this._duration+this._wait;if(t==null){const o=Math.floor(this._time/e),c=(this._time-o*e)/this._duration;return Math.min(o+c,this._times)}const n=Math.floor(t),i=t%1,r=e*n+this._duration*i;return this.time(r)}persist(t){return t==null?this._persist:(this._persist=t,this)}position(t){const e=this._time,n=this._duration,i=this._wait,r=this._times,o=this._swing,a=this._reverse;let c;if(t==null){const f=function(d){const g=o*Math.floor(d%(2*(i+n))/(i+n)),_=g&&!a||!g&&a,S=Math.pow(-1,_)*(d%(i+n))/n+_;return Math.max(Math.min(S,1),0)},m=r*(i+n)-i;return c=e<=0?Math.round(f(1e-5)):e<m?f(e):Math.round(f(m-1e-5)),c}const h=Math.floor(this.loops()),l=o&&h%2===0;return c=h+(l&&!a||a&&l?t:1-t),this.loops(c)}progress(t){return t==null?Math.min(1,this._time/this.duration()):this.time(t*this.duration())}queue(t,e,n,i){return this._queue.push({initialiser:t||$s,runner:e||$s,retarget:n,isTransform:i,initialised:!1,finished:!1}),this.timeline()&&this.timeline()._continue(),this}reset(){return this._reseted?this:(this.time(0),this._reseted=!0,this)}reverse(t){return this._reverse=t??!this._reverse,this}schedule(t,e,n){if(t instanceof Si||(n=e,e=t,t=this.timeline()),!t)throw Error("Runner cannot be scheduled without timeline");return t.schedule(this,e,n),this}step(t){if(!this.enabled)return this;t=t??16,this._time+=t;const e=this.position(),n=this._lastPosition!==e&&this._time>=0;this._lastPosition=e;const i=this.duration(),r=this._lastTime<=0&&this._time>0,o=this._lastTime<i&&this._time>=i;this._lastTime=this._time,r&&this.fire("start",this);const a=this._isDeclarative;this.done=!a&&!o&&this._time>=i,this._reseted=!1;let c=!1;return(n||a)&&(this._initialise(n),this.transforms=new x,c=this._run(a?t:e),this.fire("step",this)),this.done=this.done||c&&a,o&&this.fire("finished",this),this}time(t){if(t==null)return this._time;const e=t-this._time;return this.step(e),this}timeline(t){return typeof t>"u"?this._timeline:(this._timeline=t,this)}unschedule(){const t=this.timeline();return t&&t.unschedule(this),this}_initialise(t){if(!(!t&&!this._isDeclarative))for(let e=0,n=this._queue.length;e<n;++e){const i=this._queue[e],r=this._isDeclarative||!i.initialised&&t;t=!i.finished,r&&t&&(i.initialiser.call(this),i.initialised=!0)}}_rememberMorpher(t,e){if(this._history[t]={morpher:e,caller:this._queue[this._queue.length-1]},this._isDeclarative){const n=this.timeline();n&&n.play()}}_run(t){let e=!0;for(let n=0,i=this._queue.length;n<i;++n){const r=this._queue[n],o=r.runner.call(this,t);r.finished=r.finished||o===!0,e=e&&r.finished}return e}_tryRetarget(t,e,n){if(this._history[t]){if(!this._history[t].caller.initialised){const r=this._queue.indexOf(this._history[t].caller);return this._queue.splice(r,1),!1}this._history[t].caller.retarget?this._history[t].caller.retarget.call(this,e,n):this._history[t].morpher.to(e),this._history[t].caller.finished=!1;const i=this.timeline();return i&&i.play(),!0}return!1}}et.id=0;class Ye{constructor(t=new x,e=-1,n=!0){this.transforms=t,this.id=e,this.done=n}clearTransformsFromQueue(){}}T([et,Ye],{mergeWith(s){return new Ye(s.transforms.lmultiply(this.transforms),s.id)}});const xi=(s,t)=>s.lmultiplyO(t),Ei=s=>s.transforms;function la(){const t=this._transformationRunners.runners.map(Ei).reduce(xi,new x);this.transform(t),this._transformationRunners.merge(),this._transformationRunners.length()===1&&(this._frameId=null)}class ua{constructor(){this.runners=[],this.ids=[]}add(t){if(this.runners.includes(t))return;const e=t.id+1;return this.runners.push(t),this.ids.push(e),this}clearBefore(t){const e=this.ids.indexOf(t+1)||1;return this.ids.splice(0,e,0),this.runners.splice(0,e,new Ye).forEach(n=>n.clearTransformsFromQueue()),this}edit(t,e){const n=this.ids.indexOf(t+1);return this.ids.splice(n,1,t+1),this.runners.splice(n,1,e),this}getByID(t){return this.runners[this.ids.indexOf(t+1)]}length(){return this.ids.length}merge(){let t=null;for(let e=0;e<this.runners.length;++e){const n=this.runners[e];if(t&&n.done&&t.done&&(!n._timeline||!n._timeline._runnerIds.includes(n.id))&&(!t._timeline||!t._timeline._runnerIds.includes(t.id))){this.remove(n.id);const r=n.mergeWith(t);this.edit(t.id,r),t=r,--e}else t=n}return this}remove(t){const e=this.ids.indexOf(t+1);return this.ids.splice(e,1),this.runners.splice(e,1),this}}k({Element:{animate(s,t,e){const n=et.sanitise(s,t,e),i=this.timeline();return new et(n.duration).loop(n).element(this).timeline(i.play()).schedule(n.delay,n.when)},delay(s,t){return this.animate(0,s,t)},_clearTransformRunnersBefore(s){this._transformationRunners.clearBefore(s.id)},_currentTransform(s){return this._transformationRunners.runners.filter(t=>t.id<=s.id).map(Ei).reduce(xi,new x)},_addRunner(s){this._transformationRunners.add(s),C.cancelImmediate(this._frameId),this._frameId=C.immediate(la.bind(this))},_prepareRunner(){this._frameId==null&&(this._transformationRunners=new ua().add(new Ye(new x(this))))}}});const fa=(s,t)=>s.filter(e=>!t.includes(e));T(et,{attr(s,t){return this.styleAttr("attr",s,t)},css(s,t){return this.styleAttr("css",s,t)},styleAttr(s,t,e){if(typeof t=="string")return this.styleAttr(s,{[t]:e});let n=t;if(this._tryRetarget(s,n))return this;let i=new Rt(this._stepper).to(n),r=Object.keys(n);return this.queue(function(){i=i.from(this.element()[s](r))},function(o){return this.element()[s](i.at(o).valueOf()),i.done()},function(o){const a=Object.keys(o),c=fa(a,r);if(c.length){const l=this.element()[s](c),u=new Ee(i.from()).valueOf();Object.assign(u,l),i.from(u)}const h=new Ee(i.to()).valueOf();Object.assign(h,o),i.to(h),r=a,n=o}),this._rememberMorpher(s,i),this},zoom(s,t){if(this._tryRetarget("zoom",s,t))return this;let e=new Rt(this._stepper).to(new E(s));return this.queue(function(){e=e.from(this.element().zoom())},function(n){return this.element().zoom(e.at(n),t),e.done()},function(n,i){t=i,e.to(n)}),this._rememberMorpher("zoom",e),this},transform(s,t,e){if(t=s.relative||t,this._isDeclarative&&!t&&this._tryRetarget("transform",s))return this;const n=x.isMatrixLike(s);e=s.affine!=null?s.affine:e??!n;const i=new Rt(this._stepper).type(e?Re:x);let r,o,a,c,h;function l(){o=o||this.element(),r=r||xn(s,o),h=new x(t?void 0:o),o._addRunner(this),t||o._clearTransformRunnersBefore(this)}function u(m){t||this.clearTransform();const{x:d,y:g}=new W(r).transform(o._currentTransform(this));let _=new x({...s,origin:[d,g]}),S=this._isDeclarative&&a?a:h;if(e){_=_.decompose(d,g),S=S.decompose(d,g);const R=_.rotate,q=S.rotate,L=[R-360,R,R+360],ot=L.map(ln=>Math.abs(ln-q)),mt=Math.min(...ot),Ft=ot.indexOf(mt);_.rotate=L[Ft]}t&&(n||(_.rotate=s.rotate||0),this._isDeclarative&&c&&(S.rotate=c)),i.from(S),i.to(_);const D=i.at(m);return c=D.rotate,a=new x(D),this.addTransform(a),o._addRunner(this),i.done()}function f(m){(m.origin||"center").toString()!==(s.origin||"center").toString()&&(r=xn(m,o)),s={...m,origin:r}}return this.queue(l,u,f,!0),this._isDeclarative&&this._rememberMorpher("transform",i),this},x(s){return this._queueNumber("x",s)},y(s){return this._queueNumber("y",s)},ax(s){return this._queueNumber("ax",s)},ay(s){return this._queueNumber("ay",s)},dx(s=0){return this._queueNumberDelta("x",s)},dy(s=0){return this._queueNumberDelta("y",s)},dmove(s,t){return this.dx(s).dy(t)},_queueNumberDelta(s,t){if(t=new E(t),this._tryRetarget(s,t))return this;const e=new Rt(this._stepper).to(t);let n=null;return this.queue(function(){n=this.element()[s](),e.from(n),e.to(n+t)},function(i){return this.element()[s](e.at(i)),e.done()},function(i){e.to(n+new E(i))}),this._rememberMorpher(s,e),this},_queueObject(s,t){if(this._tryRetarget(s,t))return this;const e=new Rt(this._stepper).to(t);return this.queue(function(){e.from(this.element()[s]())},function(n){return this.element()[s](e.at(n)),e.done()}),this._rememberMorpher(s,e),this},_queueNumber(s,t){return this._queueObject(s,new E(t))},cx(s){return this._queueNumber("cx",s)},cy(s){return this._queueNumber("cy",s)},move(s,t){return this.x(s).y(t)},amove(s,t){return this.ax(s).ay(t)},center(s,t){return this.cx(s).cy(t)},size(s,t){let e;return(!s||!t)&&(e=this._element.bbox()),s||(s=e.width/e.height*t),t||(t=e.height/e.width*s),this.width(s).height(t)},width(s){return this._queueNumber("width",s)},height(s){return this._queueNumber("height",s)},plot(s,t,e,n){if(arguments.length===4)return this.plot([s,t,e,n]);if(this._tryRetarget("plot",s))return this;const i=new Rt(this._stepper).type(this._element.MorphArray).to(s);return this.queue(function(){i.from(this._element.array())},function(r){return this._element.plot(i.at(r)),i.done()}),this._rememberMorpher("plot",i),this},leading(s){return this._queueNumber("leading",s)},viewbox(s,t,e,n){return this._queueObject("viewbox",new K(s,t,e,n))},update(s){return typeof s!="object"?this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]}):(s.opacity!=null&&this.attr("stop-opacity",s.opacity),s.color!=null&&this.attr("stop-color",s.color),s.offset!=null&&this.attr("offset",s.offset),this)}});T(et,{rx:as,ry:cs,from:_i,to:bi});N(et,"Runner");class fs extends V{constructor(t,e=t){super($("svg",t),e),this.namespace()}defs(){return this.isRoot()?st(this.node.querySelector("defs"))||this.put(new os):this.root().defs()}isRoot(){return!this.node.parentNode||!(this.node.parentNode instanceof I.window.SVGElement)&&this.node.parentNode.nodeName!=="#document-fragment"}namespace(){return this.isRoot()?this.attr({xmlns:es,version:"1.1"}).attr("xmlns:xlink",Ne,fn):this.root().namespace()}removeNamespace(){return this.attr({xmlns:null,version:null}).attr("xmlns:xlink",null,fn).attr("xmlns:svgjs",null,fn)}root(){return this.isRoot()?this:super.root()}}k({Container:{nested:H(function(){return this.put(new fs)})}});N(fs,"Svg",!0);let rn=class extends V{constructor(t,e=t){super($("symbol",t),e)}};k({Container:{symbol:H(function(){return this.put(new rn)})}});N(rn,"Symbol");function da(s){return this._build===!1&&this.clear(),this.node.appendChild(I.document.createTextNode(s)),this}function pa(){return this.node.getComputedTextLength()}function ma(s,t=this.bbox()){return s==null?t.x:this.attr("x",this.attr("x")+s-t.x)}function ga(s,t=this.bbox()){return s==null?t.y:this.attr("y",this.attr("y")+s-t.y)}function ya(s,t,e=this.bbox()){return this.x(s,e).y(t,e)}function wa(s,t=this.bbox()){return s==null?t.cx:this.attr("x",this.attr("x")+s-t.cx)}function _a(s,t=this.bbox()){return s==null?t.cy:this.attr("y",this.attr("y")+s-t.cy)}function ba(s,t,e=this.bbox()){return this.cx(s,e).cy(t,e)}function va(s){return this.attr("x",s)}function Aa(s){return this.attr("y",s)}function Sa(s,t){return this.ax(s).ay(t)}function xa(s){return this._build=!!s,this}const ki=Object.freeze(Object.defineProperty({__proto__:null,amove:Sa,ax:va,ay:Aa,build:xa,center:ba,cx:wa,cy:_a,length:pa,move:ya,plain:da,x:ma,y:ga},Symbol.toStringTag,{value:"Module"}));class F extends nt{constructor(t,e=t){super($("text",t),e),this.dom.leading=this.dom.leading??new E(1.3),this._rebuild=!0,this._build=!1}leading(t){return t==null?this.dom.leading:(this.dom.leading=new E(t),this.rebuild())}rebuild(t){if(typeof t=="boolean"&&(this._rebuild=t),this._rebuild){const e=this;let n=0;const i=this.dom.leading;this.each(function(r){if(En(this.node))return;const o=I.window.getComputedStyle(this.node).getPropertyValue("font-size"),a=i*new E(o);this.dom.newLined&&(this.attr("x",e.attr("x")),this.text()===`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`:""):(typeof t=="function"?(this.clear().build(!0),t.call(this,this),this.build(!1)):this.plain(t),this)}}T(on,ki);k({Tspan:{tspan:H(function(s=""){const t=new on;return this._build||this.clear(),this.put(t).text(s)})},Text:{newLine:function(s=""){return this.tspan(s).newLine()}}});N(on,"Tspan");class ds extends nt{constructor(t,e=t){super($("circle",t),e)}radius(t){return this.attr("r",t)}rx(t){return this.attr("r",t)}ry(t){return this.rx(t)}size(t){return this.radius(new E(t).divide(2))}}T(ds,{x:fi,y:di,cx:pi,cy:mi,width:gi,height:yi});k({Container:{circle:H(function(s=0){return this.put(new ds).size(s).move(0,0)})}});N(ds,"Circle");class Cn extends V{constructor(t,e=t){super($("clipPath",t),e)}remove(){return this.targets().forEach(function(t){t.unclip()}),super.remove()}targets(){return de("svg [clip-path*="+this.id()+"]")}}k({Container:{clip:H(function(){return this.defs().put(new Cn)})},Element:{clipper(){return this.reference("clip-path")},clipWith(s){const t=s instanceof Cn?s:this.parent().clip().add(s);return this.attr("clip-path","url(#"+t.id()+")")},unclip(){return this.attr("clip-path",null)}}});N(Cn,"ClipPath");class Ti extends pt{constructor(t,e=t){super($("foreignObject",t),e)}}k({Container:{foreignObject:H(function(s,t){return this.put(new Ti).size(s,t)})}});N(Ti,"ForeignObject");function Ea(s,t){return this.children().forEach(e=>{let n;try{n=e.node instanceof Or().SVGSVGElement?new K(e.attr(["x","y","width","height"])):e.bbox()}catch{return}const i=new x(e),r=i.translate(s,t).transform(i.inverse()),o=new W(n.x,n.y).transform(r);e.move(o.x,o.y)}),this}function ka(s){return this.dmove(s,0)}function Ta(s){return this.dmove(0,s)}function Oa(s,t=this.bbox()){return s==null?t.height:this.size(t.width,s,t)}function Ia(s=0,t=0,e=this.bbox()){const n=s-e.x,i=t-e.y;return this.dmove(n,i)}function Na(s,t,e=this.bbox()){const n=fe(this,s,t,e),i=n.width/e.width,r=n.height/e.height;return this.children().forEach(o=>{const a=new W(e).transform(new x(o).inverse());o.scale(i,r,a.x,a.y)}),this}function Da(s,t=this.bbox()){return s==null?t.width:this.size(s,t.height,t)}function Ca(s,t=this.bbox()){return s==null?t.x:this.move(s,t.y,t)}function Ma(s,t=this.bbox()){return s==null?t.y:this.move(t.x,s,t)}const Oi=Object.freeze(Object.defineProperty({__proto__:null,dmove:Ea,dx:ka,dy:Ta,height:Oa,move:Ia,size:Na,width:Da,x:Ca,y:Ma},Symbol.toStringTag,{value:"Module"}));class P extends V{constructor(t,e=t){super($("g",t),e)}}T(P,Oi);k({Container:{group:H(function(){return this.put(new P)})}});N(P,"G");class Xe extends V{constructor(t,e=t){super($("a",t),e)}target(t){return this.attr("target",t)}to(t){return this.attr("href",t,Ne)}}T(Xe,Oi);k({Container:{link:H(function(s){return this.put(new Xe).to(s)})},Element:{unlink(){const s=this.linker();if(!s)return this;const t=s.parent();if(!t)return this.remove();const e=t.index(s);return t.add(this,e),s.remove(),this},linkTo(s){let t=this.linker();return t||(t=new Xe,this.wrap(t)),typeof s=="function"?s.call(t,t):t.to(s),this},linker(){const s=this.parent();return s&&s.node.nodeName.toLowerCase()==="a"?s:null}}});N(Xe,"A");class Mn extends V{constructor(t,e=t){super($("mask",t),e)}remove(){return this.targets().forEach(function(t){t.unmask()}),super.remove()}targets(){return de("svg [mask*="+this.id()+"]")}}k({Container:{mask:H(function(){return this.defs().put(new Mn)})},Element:{masker(){return this.reference("mask")},maskWith(s){const t=s instanceof Mn?s:this.parent().mask().add(s);return this.attr("mask","url(#"+t.id()+")")},unmask(){return this.attr("mask",null)}}});N(Mn,"Mask");class Ii extends pt{constructor(t,e=t){super($("stop",t),e)}update(t){return(typeof t=="number"||t instanceof E)&&(t={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),t.opacity!=null&&this.attr("stop-opacity",t.opacity),t.color!=null&&this.attr("stop-color",t.color),t.offset!=null&&this.attr("offset",new E(t.offset)),this}}k({Gradient:{stop:function(s,t,e){return this.put(new Ii).update(s,t,e)}}});N(Ii,"Stop");function Ra(s,t){if(!s)return"";if(!t)return s;let e=s+"{";for(const n in t)e+=Er(n)+":"+t[n]+";";return e+="}",e}class Rn extends pt{constructor(t,e=t){super($("style",t),e)}addText(t=""){return this.node.textContent+=t,this}font(t,e,n={}){return this.rule("@font-face",{fontFamily:t,src:e,...n})}rule(t,e){return this.addText(Ra(t,e))}}k("Dom",{style(s,t){return this.put(new Rn).rule(s,t)},fontface(s,t,e){return this.put(new Rn).font(s,t,e)}});N(Rn,"Style");class ps extends F{constructor(t,e=t){super($("textPath",t),e)}array(){const t=this.track();return t?t.array():null}plot(t){const e=this.track();let n=null;return e&&(n=e.plot(t)),t==null?n:this}track(){return this.reference("href")}}k({Container:{textPath:H(function(s,t){return s instanceof F||(s=this.text(s)),s.path(t)})},Text:{path:H(function(s,t=!0){const e=new ps;s instanceof pe||(s=this.defs().path(s)),e.attr("href","#"+s,Ne);let n;if(t)for(;n=this.node.firstChild;)e.node.appendChild(n);return this.put(e)}),textPath(){return this.findOne("textPath")}},Path:{text:H(function(s){return s instanceof F||(s=new F().addTo(this.parent()).text(s)),s.path(this)}),targets(){return de("svg textPath").filter(s=>(s.attr("href")||"").includes(this.id()))}}});ps.prototype.MorphArray=jt;N(ps,"TextPath");class an extends nt{constructor(t,e=t){super($("use",t),e)}use(t,e){return this.attr("href",(e||"")+"#"+t,Ne)}}k({Container:{use:H(function(s,t){return this.put(new an).use(s,t)})}});N(an,"Use");T([fs,rn,Me,Se,Ge],J("viewbox"));T([xe,$e,He,pe],J("marker"));T(F,J("Text"));T(pe,J("Path"));T(os,J("Defs"));T([F,on],J("Tspan"));T([Be,sn,Ce,et],J("radius"));T(De,J("EventTarget"));T(Tt,J("Dom"));T(pt,J("Element"));T(nt,J("Shape"));T([V,wi],J("Container"));T(Ce,J("Gradient"));T(et,J("Runner"));Pt.extend(Sr());ea([E,M,K,x,ne,Ot,jt,W]);na();const lt=(s,t)=>{const e=tt(s.tiles[0],t),n=e.baseHeight,i=e.baseWidth;if(s.is(b.SHO_KAN))return{width:i*2+n,height:Math.max(i*2,n)};const r=s.tiles.reduce((a,c)=>{const h=tt(c,t).height;return h>a?h:a},0);return{width:s.tiles.reduce((a,c)=>a+tt(c,t).width,0),height:r}},tt=(s,t)=>{const e=parseFloat((Et.HEIGHT*t).toPrecision(5)),n=parseFloat((Et.WIDTH*t).toPrecision(5)),i=s.has(y.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(s.has(y.TSUMO)||s.has(y.DORA))&&(i.width+=n*Et.TEXT_SCALE),i};class se{constructor(t={}){A(this,"tileWidth");A(this,"tileHeight");A(this,"imageHostPath");A(this,"imageHostUrl");A(this,"imageExt");A(this,"scale");A(this,"svgSprite");this.scale=t.scale??1,this.imageHostPath=t.imageHostPath??"",this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=Et.WIDTH*this.scale,this.tileHeight=Et.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=tt(t,this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new Me().load(this.buildURL(t));return this.svgSprite&&(e=new an().use(se.buildID(t))),t instanceof w&&t.has(y.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=tt(t,this.scale);return this.image(t).dx(e).dy(n).size(i.baseWidth,i.baseHeight)}createTextImage(t,e,n,i){const r=this.createImage(t,e,n),o=tt(t,this.scale),a=o.baseHeight*.2,c=o.baseWidth,h=o.baseHeight,l=new F().text(i);l.size(o.baseWidth,o.baseHeight).font({family:Zn,size:a}).dx(c).dy(h);const u=new P;return u.add(r).add(l).translate(e,n),u}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=tt(t,this.scale),a=o.baseWidth/2,c=o.baseHeight/2,h=e+this.getDiffTileHeightWidth(t),l=i?n-this.getDiffTileHeightWidth(t):n,u=new P;return u.add(r).translate(h,l).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=`${se.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:`${this.imageHostPath}${e}`}}class ms extends se{constructor(){super(...arguments);A(this,"blockMargin",Et.WIDTH*Et.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const n=e instanceof U?e.tilesWithBack:e.tiles,i=new P;let r=0;for(const o of n){const a=tt(o,this.scale),c=o.has(y.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),h=o.has(y.HORIZONTAL)?this.getDiffTileHeightWidth(o):0,l=c(o,r,h);i.add(l),r+=a.width}return i}createBlockPonChiKan(e){const n=e.tiles.findIndex(o=>o.has(y.HORIZONTAL));let i=0;const r=new P;if(e.type==b.SHO_KAN){let o=n;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=tt(e.tiles[a],this.scale);if(a==o)continue;if(a==n){const u=e.tiles[n],f=e.tiles[o],m=tt(u,this.scale),d=this.createRotate90Image(u,0,0,!0),g=this.createRotate90Image(f,0,m.height,!0);r.add(new P().translate(i,0).add(d).add(g)),i+=m.width;continue}const h=c.width*2-c.height,l=this.createImage(e.tiles[a],i,h);i+=c.width,r.add(l)}return r}if(e.type==b.CHI){const o=e.tiles[n],a=this.createRotate90Image(o,i,this.getDiffTileHeightWidth(o));i+=tt(o,this.scale).width,r.add(a);for(let c=0;c<e.tiles.length;c++){if(c==n)continue;const h=e.tiles[c],l=tt(h,this.scale),u=this.createImage(h,i,0);i+=l.width,r.add(u)}return r}for(let o=0;o<e.tiles.length;o++){const a=o==n?this.createRotate90Image.bind(this):this.createImage.bind(this),c=e.tiles[o],h=o==n?this.getDiffTileHeightWidth(c):0,l=tt(c,this.scale),u=a(c,i,h);i+=l.width,r.add(u)}return r}}const Ha=(s,t)=>{const e=s.scale;return{[b.CHI]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.PON]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.DAI_KAN]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.SHO_KAN]:function(i){const r=lt(i,e),o=s.createBlockPonChiKan(i);return{...r,e:o}},[b.AN_KAN]:function(i){O(i instanceof U,`block type is not ankan: ${i.type}`);const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DORA]:function(i){i=(t==null?void 0:t.doraText)==!1?new ee([i.tiles[0].clone({remove:y.DORA})]):i;const r=lt(i,e),o=new P,a=(t==null?void 0:t.doraText)===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ドラ)");return o.add(a),{...r,e:o}},[b.TSUMO]:function(i){i=(t==null?void 0:t.tsumoText)==!1?new ee([i.tiles[0].clone({remove:y.TSUMO})]):i;const r=lt(i,e),o=new P,a=(t==null?void 0:t.tsumoText)===!1?s.createImage(i.tiles[0],0,0):s.createTextImage(i.tiles[0],0,0,"(ツモ)");return o.add(a),{...r,e:o}},[b.HAND]:function(i){const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.IMAGE_DISCARD]:function(i){const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}},[b.THREE]:function(i){throw new Error("three is unsupported")},[b.RUN]:function(i){throw new Error("run is unsupported")},[b.PAIR]:function(i){throw new Error("pair is unsupported")},[b.ISOLATED]:function(i){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(i){if(i.tiles.some(a=>a.has(y.TSUMO)||a.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const r=lt(i,e),o=s.createBlockHandDiscard(i);return{...r,e:o}}}},Vt=(s,t,e)=>{const n=Ha(s,e);let i=0,r=0;const o=[];for(const u of t){const f=n[u.type],m=f(u);r+=m.width,i=m.height>i?m.height:i,o.push(m)}const a=i,c=r+(t.length-1)*s.blockMargin,h=new P;let l=0;for(const u of o){const f=a-u.height,m=new P().translate(l,f);m.add(u.e),h.add(m),l+=u.width+s.blockMargin}return{e:h,width:c,height:a}},$a=(s,t,e={},n={responsive:!1,doraText:!0,tsumoText:!0})=>{const i=new ms(e),r=Vt(i,t,n);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Ni=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(const e of Object.values(p)){if(e==p.BACK){t.push(se.buildID(new w(e,0)));continue}t.push(...s.map(n=>se.buildID(new w(e,n))).flat())}return t},Ba=s=>{const t=Ni(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof an){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}}),e},Wa=s=>{const t=Ni(),e=Ba(s);s.each((n,i)=>{const r=i[n];r instanceof rn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},Pa=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},ht=(s,t,e,n,i=0,r=0)=>{const o=new P().add(s);if(n==90){const a=i,c=r-e;return o.rotate(n,0,e).translate(a,c),o}if(n==180){const a=i+t,c=r-e;return o.rotate(n,0,e).translate(a,c),o}if(n==270){const a=i+e,c=r+(t-e);return o.rotate(n,0,e).translate(a,c),o}return o},ze=(s,t)=>{const e=new P,n=Pa(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Vn(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},ja=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=new P,a=e.sticks.dead,c=e.sticks.reach,h=125*s.scale,l=27.5*s.scale;let u=i*3,f=r;const m=(h+s.tileWidth+i-u)/2,d=new F().plain(e.round).font(n).move(m,0);o.add(d),f+=25*s.scale;const g=s.tileHeight,_=new P().size(h,g).translate(0,f),S={family:n.family,size:n.size*.7},D=s.createStick(1e3).size(h,l).move(0,0),R=new F().plain(c.toString()).font(S).attr({x:h,y:l});_.add(D),_.add(R);const q=s.createStick(100).size(h,l).move(0,l+l),L=new F().plain(a.toString()).font(S).attr({x:h,y:l*3});_.add(q),_.add(L);const ot=s.createImage(e.doras[0],0,0).move(h+i,0);return _.add(ot),o.add(d),o.add(_),{e:o,width:h+s.tileWidth+i,height:f+s.tileHeight}},za=(s,t,e=0)=>{const n=Vt(s,t.front),i=Vt(s,t.right),r=Vt(s,t.opposite),o=Vt(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((g,_)=>Math.max(g,_)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),h=c,l=new P().size(c,h),u=ht(n.e,n.width,n.height,0).translate((c-n.width)/2,h-n.height),f=ht(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),m=ht(r.e,r.width,r.height,180).translate((c-r.width)/2,0),d=ht(o.e,o.width,o.height,90).translate(0,(c-o.width)/2);return l.add(u),l.add(f),l.add(m),l.add(d),{e:l,width:c,height:h}},Ka=s=>{const t=Object.values(nn),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},La=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=new P,r=new Be().size(n,n).move(0,0).fill("none").stroke("#000000");i.add(r);const o=t.font,a=t.textWidth,c=t.textHeight,h=t.numWidth,l=ja(s,t,e);l.e.translate(n/2-l.width/2,n/2-l.height/2);const u=(ln,Is,lr)=>{const ur=`${ln} ${Is}`,fr=new F().plain(ur).font(o).attr(lr);return{e:new P().add(fr),width:a+h*Is.toString().length,height:c}},[f,m,d,g]=Ka(e.frontPlace),_=e.scores,D=u(f,_.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let R=u(m,_.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const q=ht(R.e,R.width,R.height,270).translate(n,n/2-R.width);let L=u(d,_.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const ot=ht(L.e,L.width,L.height,180).translate(n/2-L.width,-L.height);let mt=u(g,_.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Ft=ht(mt.e,mt.width,mt.height,90).translate(-mt.height,n/2);return i.add(l.e),i.add(D),i.add(q),i.add(ot),i.add(Ft),{e:i,width:n,height:n}},Ua=(s,t)=>{const e=ze(t.front,s),n=ze(t.right,s),i=ze(t.opposite,s),r=ze(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((D,R)=>Math.max(D,R)),a=s.tileWidth*5+s.tileHeight*1,c=o,h=a+o*2+s.blockMargin,l=h,u=new P().size(h,l),f=h/2-a/2,m=l/2-a/2,d=ht(e.e,a,c,0).translate(f,l-c),g=ht(n.e,a,c,270).translate(h-c,m),_=ht(i.e,a,c,180).translate(f,0),S=ht(r.e,a,c,90).translate(0,m);return u.add(d),u.add(g),u.add(_),u.add(S),{e:u,width:h,height:l}},Di=(s,t,e,n,i)=>{const r=new P,o=Ua(s,n),a=za(s,e,o.height),c=La(s,t,i);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),r.add(a.e),r.add(o.e),r.add(c.e),{e:r,width:a.width,height:a.height}},Fa=(s,t,e={},n,i={responsive:!1})=>{const r=new ms(e),o=n,{discards:a,hands:c,scoreBoard:h}=Ci(t),l=Di(r,o,c,a,h);i.responsive||s.size(l.width,l.height),s.viewbox(0,0,l.width,l.height),s.add(l.e)};var gt;function qa(s){return{lang:(s==null?void 0:s.lang)??(gt==null?void 0:gt.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(gt==null?void 0:gt.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(gt==null?void 0:gt.abortPipeEarly)}}var yn;function Ga(s){return yn==null?void 0:yn.get(s)}var wn;function Za(s){return wn==null?void 0:wn.get(s)}var _n;function Ya(s,t){var e;return(e=_n==null?void 0:_n.get(s))==null?void 0:e.get(t)}function ie(s){var e,n;const t=typeof s;return t==="string"?`"${s}"`:t==="number"||t==="bigint"||t==="boolean"?`${s}`:t==="object"||t==="function"?(s&&((n=(e=Object.getPrototypeOf(s))==null?void 0:e.constructor)==null?void 0:n.name))??"null":t}function zt(s,t,e,n,i){const r=i&&"input"in i?i.input:e.value,o=(i==null?void 0:i.expected)??s.expects??null,a=(i==null?void 0:i.received)??ie(r),c={kind:s.kind,type:s.type,input:r,expected:o,received:a,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:s.requirement,path:i==null?void 0:i.path,issues:i==null?void 0:i.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},h=s.kind==="schema",l=(i==null?void 0:i.message)??s.message??Ya(s.reference,c.lang)??(h?Za(c.lang):null)??n.message??Ga(c.lang);l&&(c.message=typeof l=="function"?l(c):l),h&&(e.typed=!1),e.issues?e.issues.push(c):e.issues=[c]}function Xa(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Hn(s,t){return{kind:"validation",type:"max_value",reference:Hn,async:!1,expects:`<=${s instanceof Date?s.toJSON():ie(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value>this.requirement&&zt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ie(e.value)}),e}}}function $n(s,t){return{kind:"validation",type:"min_value",reference:$n,async:!1,expects:`>=${s instanceof Date?s.toJSON():ie(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value<this.requirement&&zt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ie(e.value)}),e}}}function Ja(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function Je(s){return{kind:"schema",type:"number",reference:Je,expects:"number",async:!1,message:s,_run(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:zt(this,"type",t,e),t}}}function it(s,...t){const e={kind:"schema",type:"optional",reference:it,expects:`(${s.expects} | undefined)`,async:!1,wrapped:s,_run(n,i){return n.value===void 0&&("default"in this&&(n.value=Ja(this,n,i)),n.value===void 0)?(n.typed=!0,n):this.wrapped._run(n,i)}};return 0 in t&&(e.default=t[0]),e}function Bn(s,t){return{kind:"schema",type:"picklist",reference:Bn,expects:Xa(s.map(ie),"|"),async:!1,options:s,message:t,_run(e,n){return this.options.includes(e.value)?e.typed=!0:zt(this,"type",e,n),e}}}function re(s,t){return{kind:"schema",type:"strict_object",reference:re,expects:"Object",async:!1,entries:s,message:t,_run(e,n){var r;const i=e.value;if(i&&typeof i=="object"){e.typed=!0,e.value={};for(const o in this.entries){const a=i[o],c=this.entries[o]._run({typed:!1,value:a},n);if(c.issues){const h={type:"object",origin:"value",input:i,key:o,value:a};for(const l of c.issues)l.path?l.path.unshift(h):l.path=[h],(r=e.issues)==null||r.push(l);if(e.issues||(e.issues=c.issues),n.abortEarly){e.typed=!1;break}}c.typed||(e.typed=!1),(c.value!==void 0||o in i)&&(e.value[o]=c.value)}if(!e.issues||!n.abortEarly){for(const o in i)if(!(o in this.entries)){const a=i[o];zt(this,"type",e,n,{input:a,expected:"never",path:[{type:"object",origin:"value",input:i,key:o,value:a}]});break}}}else zt(this,"type",e,n);return e}}}function Ve(s){return{kind:"schema",type:"string",reference:Ve,expects:"string",async:!1,message:s,_run(t,e){return typeof t.value=="string"?t.typed=!0:zt(this,"type",t,e),t}}}function Ws(...s){return{...s[0],pipe:s,_run(t,e){for(const n of s)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!e.abortEarly&&!e.abortPipeEarly)&&(t=n._run(t,e))}return t}}}function Va(s,t,e){const n=s._run({typed:!1,value:t},qa(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const Ke=it(re({discard:it(Ve(),""),hand:it(Ve(),""),score:it(Je(),25e3)}),{discard:"",hand:"",score:25e3}),Qa=re({[v.E]:Ke,[v.S]:Ke,[v.W]:Ke,[v.N]:Ke}),Nt={round:j.E1,sticks:{reach:0,dead:0},doras:v.S,front:v.E},tc=it(re({round:it(Bn(Object.keys(Yn)),Nt.round),sticks:it(re({reach:it(Ws(Je(),$n(0,""),Hn(9,"")),Nt.sticks.reach),dead:it(Ws(Je(),$n(0,""),Hn(9,"")),Nt.sticks.dead)}),Nt.sticks),doras:it(Ve(),Nt.doras),front:it(Bn(Object.keys(nn)),Nt.front)}),Nt),ec=re({...Qa.entries,board:tc}),Ci=s=>{const t=Mi(s);return Ri(t)},Mi=s=>{const t=nc(s),e=Va(ec,t);if(!e.success)throw e.issues;return e.output},nc=s=>{const t="table",e="board",n=s.split(`
|
|
7
|
-
`).map(a=>a.trim()).filter(a=>a!="");if(n.length==0)throw new Error("empty input");const i=n.shift();if(!i.startsWith(t))throw new Error(`input does not start with table: ${i}`);const r={};let o=[v.E,v.S,v.W,v.N,e];for(;;){const a=n.shift();if(a==null)break;const c=o.find(h=>a.startsWith(h));if(c==null)throw new Error(`encountered unexpected line ${a}`);if(o=o.filter(h=>!a.startsWith(h)),c==e){const[h,l]=ic([...n]);r.board=h;for(let u=0;u<l;u++)n.shift()}else{const[h,l]=sc([...n]);r[c]=h;for(let u=0;u<l;u++)n.shift()}}return r},ut=(s,t)=>s.replace(t,"").replace(":","").trim(),sc=s=>{const t="hand",e="discard",n="score",i={};let r=0;for(;r<s.length;r++){const o=s[r];if(o.startsWith(t))i.hand=ut(o,t);else if(o.startsWith(e))i.discard=ut(o,e);else if(o.startsWith(n))i.score=Number(ut(o,n));else break}return[i,r]},ic=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead",a={};let c=0;for(;c<s.length;c++){const h=s[c];if(h.startsWith(t))a.doras=ut(h,t);else if(h.startsWith(e))a.round=ut(h,e);else if(h.startsWith(n))a.front=ut(h,n);else if(h.startsWith(i)){a.sticks={};const l=s[c+1]??"",u=s[c+2]??"";l.startsWith(r)&&(a.sticks.reach=Number(ut(l,r))),l.startsWith(o)&&(a.sticks.dead=Number(ut(l,o))),u.startsWith(r)&&(a.sticks.reach=Number(ut(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(ut(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Ri=s=>{const t=s.board.front,e=rc(t),n=a=>s[a].discard.replace(/\r?\n/g,""),i={front:new Q(n(e.front)).tiles(),right:new Q(n(e.right)).tiles(),opposite:new Q(n(e.opposite)).tiles(),left:new Q(n(e.left)).tiles()},r={front:new Q(s[e.front].hand).parse(),right:new Q(s[e.right].hand).parse(),opposite:new Q(s[e.opposite].hand).parse(),left:new Q(s[e.left].hand).parse()},o={round:Yn[s.board.round],frontPlace:nn[t],sticks:s.board.sticks,doras:new Q(s.board.doras).tiles(),scores:{front:s[e.front].score,right:s[e.right].score,opposite:s[e.opposite].score,left:s[e.left].score}};return{discards:i,hands:r,scoreBoard:o}},rc=s=>({front:s,right:kt(s),opposite:kt(kt(s)),left:Qn(s)});function*rt(s){const t=s!=null&&s.filterBy&&s.filterBy.length>0?s==null?void 0:s.filterBy:Object.values(p);for(const e of t){if(s!=null&&s.skipBack&&e==p.BACK)continue;const n=e==p.Z?7:e==p.BACK?1:9;for(let i=1;i<=n;i++)yield[e,i]}}class cn{constructor(t,e=!1){A(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 n=Array.isArray(t)?t:new Q(t).parse();for(const i of n){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(b.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(b.HAND)){this.inc(i.tiles);continue}else if(!Array.isArray(t)&&t.split("").every(r=>r===p.BACK)){this.inc(i.tiles);continue}else if(e){this.inc(i.tiles);continue}throw new Error(`unexpected block ${i.type} ${i.toString()}`)}}get hands(){const t=[];for(const[e,n]of rt()){let i=this.get(e,n);e!=p.Z&&n==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new w(e,n,[y.RED])));for(let r=0;r<i;r++)t.push(new w(e,n))}if(this.drawn!=null){const e=this.drawn,n=t.findIndex(i=>i.equals(e));O(n>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[n]=t[n].clone({add:y.TSUMO})}return t}toString(){const t=this.called.length>0?`${At}${this.called.join(At)}`:"",e=this.drawn?`${At}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(y.TSUMO));return`${new ee(n).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 U))}sum(t){let e=0;for(const[n,i]of rt({filterBy:[t]}))e+=this.get(n,i);return e}get(t,e){return t==p.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(const n of t){if(n.t!=p.BACK&&this.get(n.t,n.n)>=4||n.has(y.RED)&&this.get(n.t,0)>0)throw this.dec(e),new Error(`unable to increase ${n} in ${this.toString()}`);e.push(n),n.t==p.BACK?this.data[n.t][1]+=1:(this.data[n.t][n.n]+=1,n.has(y.RED)&&(this.data[n.t][0]+=1))}return e}dec(t){const e=[];for(const n of t){if(this.get(n.t,n.n)<1||n.has(y.RED)&&this.get(n.t,0)<=0)throw this.inc(e),new Error(`unable to decrease ${n.toString()} in ${this.toString()}`);if(e.push(n),n.t==p.BACK?this.data[n.t][1]-=1:(this.data[n.t][n.n]-=1,n.has(y.RED)&&(this.data[n.t][0]-=1)),z(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.t][0]=0;const i=e.pop().clone({add:y.RED});e.push(i)}}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(n=>!n.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 U){this.dec(t.tiles),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof ct){const e=this.data.called.findIndex(i=>i.is(b.PON)&&i.tiles[0].equals(t.tiles[0]));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let n=t.tiles[0];n=z(n)?n.clone({remove:y.RED}):n,this.dec([n]),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 cn(this.toString());return t.data.reached=this.data.reached,t}}class We{constructor(t){A(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[n,i]of rt({skipBack:!0}))this.hand.get(n,i)==2&&t++,this.hand.get(n,i)==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 n of Object.values(p)){if(n==p.BACK)continue;const i=n==p.Z?oe:ft;for(const r of i)this.hand.get(n,r)>=1&&t++,this.hand.get(n,r)>=2&&e++}return e>=1?12-t:13-t}fourSetsOnePair(){const t=n=>{const i=[0,0,0];for(const[f,m]of rt({filterBy:[p.Z]}))this.hand.get(f,m)>=3?i[0]++:this.hand.get(f,m)==2?i[1]++:this.hand.get(f,m)==1&&i[2]++;const r=[0,0,0],o=this.hand.get(p.BACK,0),a=o%3;r[0]=Math.floor(o/3),a==2?r[1]=1:a==1&&(r[2]=1);let c=13;const h=this.patternByNumType(p.M),l=this.patternByNumType(p.P),u=this.patternByNumType(p.S);for(const f of[h.patternA,h.patternB])for(const m of[l.patternA,l.patternB])for(const d of[u.patternA,u.patternB]){const g=[this.hand.called.length,0,0];for(let S=0;S<3;S++)g[S]+=f[S]+m[S]+d[S]+i[S]+r[S];const _=this.calcCommon(g[0],g[1],g[2],n);_<c&&(c=_)}return c};let e=t(!1);for(const[n,i]of rt())if(this.hand.get(n,i)>=2){const r=this.hand.dec(new Array(2).fill(new w(n,i))),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}patternByNumType(t,e=1){if(e>9)return this.groupRemainingTiles(t);let n=this.patternByNumType(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 i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]),r=this.patternByNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}if(this.hand.get(t,e)>=3){const i=this.hand.dec(new Array(3).fill(new w(t,e))),r=this.patternByNumType(t,e);this.hand.inc(i),r.patternA[0]++,r.patternB[0]++,(r.patternA[2]<n.patternA[2]||r.patternA[2]==n.patternA[2]&&r.patternA[1]<n.patternA[1])&&(n.patternA=r.patternA),(r.patternB[0]>n.patternB[0]||r.patternB[0]==n.patternB[0]&&r.patternB[1]>n.patternB[1])&&(n.patternB=r.patternB)}return n}groupRemainingTiles(t){let e=0,n=0,i=0;for(const[r,o]of rt({filterBy:[t]}))i+=this.hand.get(r,o),o<=7&&this.hand.get(r,o+1)==0&&this.hand.get(r,o+2)==0&&(e+=i>>1,n+=i%2,i=0);return e+=i>>1,n+=i%2,{patternA:[0,e,n],patternB:[0,e,n]}}calcCommon(t,e,n,i){let r=i?4:5;return t>4&&(e+=t-4,t=4),t+e>4&&(n+=t+e-4,e=4-t),t+e+n>r&&(n=r-t-e),i&&e++,13-t*3-e*2-n}}class Hi{constructor(t){A(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 n=this.hand.drawn!=null||e.has(y.TSUMO)?y.TSUMO:y.RON,i=[];for(let o=0;o<t.length;o++){const a=t[o],c={};for(let h=0;h<a.length;h++){const l=a[h];if(l.isCalled())continue;const u=l.tiles.findIndex(m=>m.equals(e)&&e.has(y.RED)==m.has(y.RED));if(u<0)continue;const f=$i(l);c[f]||(c[f]=!0,i.push([o,h,u]))}}if(i.length==0)throw new Error(`found no tile ${e.toString()} in hands ${t[0].toString()}`);const r=[];for(const[o,a,c]of i){const l=[...t[o]],u=l[a],f=u.tiles[c].clone({add:n});l[a]=u.clone({replace:{idx:c,tile:f}}),r.push(l)}return r}sevenPairs(){if(this.hand.called.length>0)return[];const t=[];for(const[e,n]of rt({skipBack:!0})){const i=this.hand.get(e,n);if(i==2){const r=this.hand.dec(new Array(2).fill(new w(e,n)));t.push(new Y(r[0],r[1])),this.hand.inc(r)}else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(const n of Object.values(p)){if(n==p.BACK)continue;const i=n==p.Z?oe:ft;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Jn(new w(n,r)));else if(this.hand.get(n,r)==2&&e==!1)t.unshift(new Y(new w(n,r),new w(n,r))),e=!0;else return[]}return[t]}nineGates(){const t=(e,n,i)=>i.includes(this.hand.get(e,n));for(const e of Object.values(p)){if(e==p.BACK||e==p.Z)continue;const n=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]),i=this.hand.sum(e)==14;if(n&&i)return[[new ee(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,n]of rt())if(this.hand.get(e,n)>=2){const i=this.hand.dec(new Array(2).fill(new w(e,n))),r=this.patternAll().filter(o=>o.length==4).map(o=>(o.unshift(new Y(i[0],i[1])),o));t=[...t,...r],this.hand.inc(i)}return t}patternAll(){const t=[this.handleNumType(p.M),this.handleNumType(p.P),this.handleNumType(p.S),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((n,i)=>i.length-n.length),e=t[0].concat();for(let n=0;n<e.length;n++)for(let i=1;i<t.length;i++)for(const r of t[i])e[n]=[...e[n],...r];return e}handleBack(){const t=[],e=p.BACK,n=this.hand.get(e,0);return n<3?[]:(Array(Math.floor(n/3)).fill(void 0).map(i=>{t.push(new at([new w(e,0),new w(e,0),new w(e,0)]))}),t.length==0?[]:[t])}handleZ(){const t=[];for(const[e,n]of rt({filterBy:[p.Z]}))if(this.hand.get(e,n)!=0){if(this.hand.get(e,n)!=3)return[];t.push(new at([new w(e,n),new w(e,n),new w(e,n)]))}return t.length==0?[]:[t]}handleNumType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.handleNumType(t,e+1);const n=[];if(e<=7&&this.hand.get(t,e)>0&&this.hand.get(t,e+1)>0&&this.hand.get(t,e+2)>0){const i=this.hand.dec([new w(t,e),new w(t,e+1),new w(t,e+2)]);let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new St([i[0],i[1],i[2]])),n.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec(new Array(3).fill(new w(t,e)));let r=this.handleNumType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(const o of r)o.unshift(new at([i[0],i[1],i[2]])),n.push(o)}return n}}const oe=[1,2,3,4,5,6,7],ft=[1,9],we=s=>{var e;const t=s.boardContext;return{...s,hand:s.hand.map(B.deserialize),boardContext:{...t,doraMarkers:t.doraMarkers.map(w.from),blindDoraMarkers:(e=t.blindDoraMarkers)==null?void 0:e.map(w.from)}}};class Wn{constructor(t,e){A(this,"hand");A(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(n=>js(n)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(n=>js(n)),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,orig:e}}calc(...t){const e=this.calcPatterns(t);if(e.length==0)return!1;let n=[0,0],i=0;for(let d=0;d<e.length;d++){const g=e[d],_=g.points.reduce((S,D)=>S+D.double,0);_>n[0]?(i=d,n=[_,g.fu]):_==n[0]&&g.fu>n[1]&&(i=d,n=[_,g.fu])}const r=(d,g=100)=>Math.ceil(d/g)*g,o=n[1]!=25?r(n[1],10):25,a=n[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);const h=e[i].hand.some(d=>d.tiles.some(g=>g.has(y.TSUMO))),l=this.cfg.orig.myWind,u=l==v.E,f=Z(0);if(h){const d=this.cfg.sticks.dead*100;if(u){const g=r(c*2);f[v.E]+=g*3+d*3,f[v.S]-=g+d,f[v.W]-=g+d,f[v.N]-=g+d}else for(const g of Object.values(v)){if(g==l)continue;const _=g==v.E?2:1,S=r(c*_)+d;f[g]-=S,f[l]+=S}}else{const d=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const _=r(c*(u?6:4))+d;f[l]+=_,f[this.cfg.orig.ronWind]-=_}return f[l]+=1e3*this.cfg.sticks.reach,{deltas:f,sum:a,fu:o,points:e[i].points,point:f[l],hand:e[i].hand,boardContext:this.cfg.orig}}calcPatterns(t){const e=[];if(t.length==0)return e;for(const n of t){const i=[...this.dA13(n),...this.dB13(n),...this.dC13(n),...this.dD13(n),...this.dE13(n),...this.dF13(n),...this.dG13(n),...this.dH13(n),...this.dI13(n),...this.dJ13(n),...this.dK13(n)];i.length!=0&&e.push({points:i,fu:30,hand:n})}if(e.length>0)return e;for(const n of t){const i=this.calcFu(n),r=[...this.dA1(n),...this.dB1(n),...this.dC1(n),...this.dD1(n),...this.dE1(n),...this.dF1(n),...this.dG1(n),...this.dH1(n),...this.dI1(n),...this.dJ1(n),...this.dK1(n),...this.dA2(n),...this.dB2(n),...this.dC2(n),...this.dD2(n),...this.dE2(n),...this.dF2(n),...this.dG2(n),...this.dH2(n),...this.dI2(n),...this.dJ2(n),...this.dA3(n),...this.dB3(n),...this.dC3(n),...this.dA6(n)];r.length>0&&r.push(...this.dX1(n)),e.push({points:r,fu:i,hand:n})}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(n=>n.tiles.some(i=>i.has(y.TSUMO)))?[{name:"門前清自摸和",double:1}]:[])}dC1(t){if(this.minus()!=0)return[];const e="平和",n=this.calcFu(t);return n==20?[{name:e,double:1}]:!t.some(i=>i.tiles.some(r=>r.has(y.TSUMO)))&&n==30?[{name:e,double:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(i=>i.t==p.Z||ft.includes(i.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:Ps(t)==1?[{name:"一盃口",double:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof Y)return;const i=n.tiles[0];i.t==p.Z&&(i.equals(this.cfg.myWind)?e.push({name:"自風",double:1}):i.equals(this.cfg.roundWind)?e.push({name:"場風",double:1}):i.n==5?e.push({name:"白",double:1}):i.n==6?e.push({name:"發",double:1}):i.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,n=0,i=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)&&n++;a.has(y.RED)&&i++}const r=[];return e>0&&r.push({name:"ドラ",double:e}),i>0&&r.push({name:"赤ドラ",double:i}),this.hand.reached&&n>0&&r.push({name:"裏ドラ",double:n}),r}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=n=>n instanceof St||n instanceof dt;for(const n of t){if(!e(n))continue;const i=Dt(n);if(i.t==p.Z)continue;const r=[p.M,p.P,p.S].filter(c=>c!=i.t),o=t.some(c=>{const h=new w(r[0],i.n);return e(c)&&h.equals(Dt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Dt(c))});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof U||n instanceof ct||n instanceof wt||n instanceof at||n instanceof _t||n instanceof Y)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(n=>(n instanceof U||n instanceof at)&&!n.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(n=>n instanceof U||n instanceof ct||n instanceof wt).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=n=>n instanceof U||n instanceof ct||n instanceof wt||n instanceof at||n instanceof _t;for(const n of t){if(!e(n))continue;const i=Dt(n);if(i.t==p.Z)continue;const r=[p.M,p.P,p.S].filter(c=>c!=i.t),o=t.some(c=>{const h=new w(r[0],i.n);return e(c)&&h.equals(Dt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Dt(c))});if(o&&a)return[{name:"三色同刻",double:2}]}return[]}dG2(t){return t.filter(n=>{const i=n.tiles[0];return i.t==p.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",double:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0].t==p.Z?oe:ft;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof St||n instanceof dt)?t.some(n=>n.tiles[0].t==p.Z)?t.every(n=>{const i=n.tiles[0].t==p.Z?oe:ft;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];const e={[p.M]:[0,0,0],[p.S]:[0,0,0],[p.P]:[0,0,0]};for(const n of t){const i=Dt(n);i.t!=p.BACK&&i.t!=p.Z&&(n instanceof St||n instanceof dt)&&(i.n==1?e[i.t][0]++:i.n==4?e[i.t][1]++:i.n==7&&e[i.t][2]++)}for(const n of Object.values(e))if(n.filter(i=>i>0).length==n.length)return[{name:"一気通貫",double:2-this.minus()}];return[]}dA3(t){if(!t.some(n=>n.tiles[0].t==p.Z))return[];for(const n of Object.values(p))if(t.every(r=>r.tiles[0].t==p.Z||r.tiles[0].t==n))return[{name:"混一色",double:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof St||n instanceof dt)?t.some(n=>n.tiles[0].t==p.Z)?[]:t.every(n=>n.tiles.some(i=>ft.includes(i.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:Ps(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(i=>i.tiles[0].t==e))return[{name:"清一色",double:6-this.minus()}]}return[]}dA13(t){return t.length!=13?[]:t.some(n=>n instanceof Y&&n.tiles.some(i=>i.has(y.TSUMO)||i.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(i=>i instanceof U||i instanceof at&&!i.tiles.some(r=>r.has(y.RON))||i instanceof Y)?t.some(i=>i instanceof Y&&i.tiles.every(r=>r.has(y.TSUMO)||r.has(y.RON)))?[{name:"四暗刻単騎待ち",double:26}]:[{name:"四暗刻",double:13}]:[]}dD13(t){if(t.length==13)return[];const e=[5,6,7];return t.filter(i=>!(i instanceof Y)&&i.tiles.some(r=>r.t==p.Z&&e.includes(r.n))).length==3?[{name:"大三元",double:13}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==p.Z)?[{name:"字一色",double:13}]:[]}dF13(t){return t.every(n=>n.tiles.every(i=>i.t!=p.Z&&ft.includes(i.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(n=>n instanceof U||n instanceof ct||n instanceof wt).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(r=>r.tiles.some(o=>o.t==p.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof Y).tiles.some(r=>r.t==p.Z&&e.includes(r.n))?[{name:"小四喜",double:13}]:[{name:"大四喜",double:13}]:[]}dI13(t){const e=n=>!!(n.equals(new w(p.Z,6))||n.t==p.S&&[2,3,4,6,8].includes(n.n));return t.every(n=>n.tiles.every(i=>e(i)))?[{name:"緑一色",double:13}]:[]}dJ13(t){return[]}dK13(t){return[]}calcFu(t){let n=20;const i=this.cfg.myWind.n,r=this.cfg.roundWind.n;if(t.length==7)return 25;const o=t.find(d=>d.tiles.some(g=>g.has(y.TSUMO)||g.has(y.RON))),a=this.minus()==1,c=o.tiles.some(d=>d.has(y.TSUMO)),h=(d,g)=>{const _=d.tiles[0];return _.t==p.Z&&[5,6,7].includes(_.n)||_.t==p.Z&&[i,r].includes(_.n)||ft.includes(_.n)?g*2:g};for(const d of t)switch(!0){case d instanceof at:const g=d.tiles.some(_=>_.has(y.RON))?2:4;n+=h(d,g);break;case d instanceof _t:n+=h(d,2);break;case(d instanceof wt||d instanceof ct):n+=h(d,8);break;case d instanceof U:n+=h(d,16);break}n+=(d=>{if(d instanceof at)return 0;if(d instanceof Y)return 2;const g=d.tiles,_=g.findIndex(S=>S.has(y.TSUMO)||S.has(y.RON));return _==1||_==0&&g[2].n==9||_==2&&g[0].n==1?2:0})(o);const f=t.find(d=>d instanceof Y).tiles[0];f.t==p.Z&&([5,6,7].includes(f.n)&&(n+=2),f.n==r&&(n+=2),f.n==i&&(n+=2));let m=!1;return!a&&n==20&&(m=!0),c&&!m&&(n+=2),!c&&!a&&(n+=10),!c&&!a&&n==30&&(m=!0),a&&n==20&&(n=30),n}}const $i=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Ps=s=>{const t={};for(const n of s){if(!(n instanceof St))continue;const i=$i(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(const n in t)t[n]>=2&&e++;return e},Dt=s=>[...s.tiles].sort(Ie)[0],js=s=>{const t=s.n,e=s.t;return new w(e,t%9+1)};class ae{static calcCandidates(t,e,n){O(e.length>0,"choices to discard is zero");const i=new Map;let r=1/0;for(const o of e){const a=t.dec([o]),c=ae.candidateTiles(t,n);t.inc(a);const h=n!=null&&n.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<r?(i.clear(),i.set(h.toString(),{shanten:c.shanten,candidates:c.candidates,tile:h}),r=c.shanten):c.shanten==r&&i.set(h.toString(),{shanten:c.shanten,candidates:c.candidates,tile:h})}return Array.from(i.values())}static candidateTiles(t,e){let n=1/0,i=[];const r=new We(t);for(const[o,a]of rt({skipBack:!0,filterBy:e==null?void 0:e.typeFilter})){if(t.get(o,a)>=4)continue;const c=new w(o,a),h=t.inc([c]),l=e!=null&&e.fourSetsOnePair?r.fourSetsOnePair():r.calc();t.dec(h),l<n?(n=l,i=[c]):l==n&&i.push(c)}return{shanten:n,candidates:i}}}const Pn=()=>{const s=new Set;return{on(t){s.add(t)},off(t){s.delete(t)},offAll(){s.clear()},emit(t){s.forEach(e=>e(t))}}};function Bi(s){var r;const t=["RON","DAI_KAN","PON","CHI"],e=s.map(o=>o.choices),i=Pi(e,t).map(o=>s[o]);return{events:i,type:ji(t,(r=i[0])==null?void 0:r.choices)}}function Wi(s){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(o=>o.choices),i=Pi(e,t).map(o=>s[o]);return{events:i,type:ji(t,(r=i[0])==null?void 0:r.choices)}}function Pi(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(oc(r,t)){const o=ac(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function oc(s,t){return t.some(e=>!!s[e])}function ac(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function ji(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const _e=()=>{const s=Pn(),t=Pn(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},zi=()=>{const s=Pn();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class ke{constructor(t){A(this,"reachValue",1e3);A(this,"m");this.m=structuredClone(t)}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}update(t,e){for(let n in e){const i=e[n],r=t[i];this.m[n]+=r}}}class Te{constructor(t,e){A(this,"pToW",{});A(this,"wToP",Z(""));A(this,"round");A(this,"sticks");this.round=(e==null?void 0:e.round)??j.E1,this.sticks=structuredClone(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=structuredClone(t);for(let n in this.pToW)this.wToP[this.pToW[n]]=n}update(){for(let t in this.pToW){const e=kt(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=ve(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 gs(s){for(let t=s.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[s[t],s[e]]=[s[e],s[t]]}return s}class Ki{constructor(t=!1){A(this,"c");A(this,"safeMap",Z({},!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,n){return this.safeMap[n][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 ys{constructor(){A(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 O(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 n=0;n<4;n++)if(!e.equals(t[n].t))return!1;return!0}}function cc(){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 hc(){const s=cc();if(s.__xstate__)return s.__xstate__}const lc=s=>{if(typeof window>"u")return;const t=hc();t&&t.register(s)};class zs{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 Li=".",uc="",Ui="",fc="#",dc="*",Fi="xstate.init",jn="xstate.stop";function pc(s,t){return{type:`xstate.after.${s}.${t}`}}function zn(s,t){return{type:`xstate.done.state.${s}`,output:t}}function mc(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function gc(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function qi(s){return{type:Fi,input:s}}function yt(s){setTimeout(()=>{throw s})}const yc=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Gi(s,t){const e=Ks(s),n=Ks(t);return typeof n=="string"?typeof e=="string"?n===e:!1:typeof e=="string"?e in n:Object.keys(e).every(i=>i in n?Gi(e[i],n[i]):!1)}function ws(s){if(Yi(s))return s;let t=[],e="";for(let n=0;n<s.length;n++){switch(s.charCodeAt(n)){case 92:e+=s[n+1],n++;continue;case 46:t.push(e),e="";continue}e+=s[n]}return t.push(e),t}function Ks(s){if(Xc(s))return s.value;if(typeof s!="string")return s;const t=ws(s);return wc(t)}function wc(s){if(s.length===1)return s[0];const t={};let e=t;for(let n=0;n<s.length-1;n++)if(n===s.length-2)e[s[n]]=s[n+1];else{const i=e;e={},i[s[n]]=e}return t}function Ls(s,t){const e={},n=Object.keys(s);for(let i=0;i<n.length;i++){const r=n[i];e[r]=t(s[r],r,s,i)}return e}function Zi(s){return Yi(s)?s:[s]}function xt(s){return s===void 0?[]:Zi(s)}function Kn(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function Yi(s){return Array.isArray(s)}function _c(s){return s.type.startsWith("xstate.error.actor")}function Yt(s){return Zi(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Xi(s){if(!(s===void 0||s===uc))return xt(s)}function Ln(s,t,e){var r,o,a;const n=typeof s=="object",i=n?s:void 0;return{next:(r=n?s.next:s)==null?void 0:r.bind(i),error:(o=n?s.error:t)==null?void 0:o.bind(i),complete:(a=n?s.complete:e)==null?void 0:a.bind(i)}}function Us(s,t){return`${t}.${s}`}function _s(s,t){const e=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!e)return s.implementations.actors[t];const[,n,i]=e,o=s.getStateNodeById(i).config.invoke;return(Array.isArray(o)?o[n]:o).src}function Fs(s,t){return`${s.sessionId}.${t}`}let bc=0;function vc(s,t){const e=new Map,n=new Map,i=new WeakMap,r=new Set,o={},{clock:a,logger:c}=t,h={schedule:(f,m,d,g,_=Math.random().toString(36).slice(2))=>{const S={source:f,target:m,event:d,delay:g,id:_,startedAt:Date.now()},D=Fs(f,_);u._snapshot._scheduledEvents[D]=S;const R=a.setTimeout(()=>{delete o[D],delete u._snapshot._scheduledEvents[D],u._relay(f,m,d)},g);o[D]=R},cancel:(f,m)=>{const d=Fs(f,m),g=o[d];delete o[d],delete u._snapshot._scheduledEvents[d],g!==void 0&&a.clearTimeout(g)},cancelAll:f=>{for(const m in u._snapshot._scheduledEvents){const d=u._snapshot._scheduledEvents[m];d.source===f&&h.cancel(f,d.id)}}},l=f=>{if(!r.size)return;const m={...f,rootId:s.sessionId};r.forEach(d=>{var g;return(g=d.next)==null?void 0:g.call(d,m)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${bc++}`,_register:(f,m)=>(e.set(f,m),f),_unregister:f=>{e.delete(f.sessionId);const m=i.get(f);m!==void 0&&(n.delete(m),i.delete(f))},get:f=>n.get(f),_set:(f,m)=>{const d=n.get(f);if(d&&d!==m)throw new Error(`Actor with system ID '${f}' already exists.`);n.set(f,m),i.set(m,f)},inspect:f=>{const m=Ln(f);return r.add(m),{unsubscribe(){r.delete(m)}}},_sendInspectionEvent:l,_relay:(f,m,d)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:f,actorRef:m,event:d}),m._send(d)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const f=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const m in f){const{source:d,target:g,event:_,delay:S,id:D}=f[m];h.schedule(d,g,_,S,D)}},_clock:a,_logger:c};return u}const bs=1;let G=function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s}({});const Ac={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class Sc{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 zs(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=G.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 n={...Ac,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:h,inspect:l}=n;this.system=o?o.system:vc(this,{clock:i,logger:r}),l&&!o&&this.system.inspect(Ln(l)),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=n,this.src=n.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 f=this.eventListeners.get(u.type),m=this.eventListeners.get("*");if(!f&&!m)return;const d=new Set([...f?f.values():[],...m?m.values():[]]);for(const g of Array.from(d))g(u)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this._systemId=h,this.system._set(h,this)),this._initState((e==null?void 0:e.snapshot)??(e==null?void 0:e.state)),h&&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(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,e){var i,r;this._snapshot=t;let n;for(;n=this._deferred.shift();)try{n()}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{(i=o.next)==null||i.call(o,t)}catch(a){yt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){yt(a)}this._stopProcedure(),this._complete(),this._doneEvent=mc(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,n){var r;const i=Ln(t,e,n);if(this._processingStatus!==G.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){yt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)yt(o);else try{i.error(o)}catch(a){yt(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,e){let n=this.eventListeners.get(t);n||(n=new Set,this.eventListeners.set(t,n));const i=e.bind(void 0);return n.add(i),{unsubscribe:()=>{n.delete(i)}}}start(){if(this._processingStatus===G.Running)return this;this._syncSnapshot&&this.subscribe({next:n=>{n.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=G.Running;const t=qi(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(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){n={err:i}}if(n){const{err:i}=n;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(e,t),t.type===jn&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===G.Stopped?this:(this.mailbox.clear(),this._processingStatus===G.NotStarted?(this._processingStatus=G.Stopped,this):(this.mailbox.enqueue({type:jn}),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(n){yt(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||yt(t);return}let e=!1;for(const n of this.observers){const i=n.error;e||(e=!i);try{i==null||i(t)}catch(r){yt(r)}}this.observers.clear(),e&&yt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,gc(this.id,t))}_stopProcedure(){return this._processingStatus!==G.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new zs(this._process.bind(this)),this._processingStatus=G.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==G.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:lc)(this)}toJSON(){return{xstate$$type:bs,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[yc](){return this}getSnapshot(){return this._snapshot}}function ce(s,...[t]){return new Sc(s,t)}function xc(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,r]}function Ec(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t)})}function kc(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=xc,t.execute=Ec,t}function Tc(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const h=typeof o=="string"?_s(t.machine,o):o,l=typeof i=="function"?i(e):i;let u;return h&&(u=ce(h,{id:l,src:o,parent:s.self,syncSnapshot:c,systemId:r,input:typeof a=="function"?a({context:t.context,event:e.event,self:s.self}):a})),[Kt(t,{children:{...t.children,[l]:u}}),{id:i,actorRef:u}]}function Oc(s,{id:t,actorRef:e}){e&&s.defer(()=>{e._processingStatus!==G.Stopped&&e.start()})}function Ic(...[s,{id:t,systemId:e,input:n,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="snapshot.spawnChild",r.id=t,r.systemId=e,r.src=s,r.input=n,r.syncSnapshot=i,r.resolve=Tc,r.execute=Oc,r}function Nc(s,t,e,n,{actorRef:i}){const r=typeof i=="function"?i(e,n):i,o=typeof r=="string"?t.children[r]:r;let a=t.children;return o&&(a={...a},delete a[o.id]),[Kt(t,{children:a}),o]}function Dc(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==G.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function Ji(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=Nc,t.execute=Dc,t}function vs(s,t,e,n){const{machine:i}=n,r=typeof s=="function",o=r?s:i.implementations.guards[typeof s=="string"?s:s.type];if(!r&&!o)throw new Error(`Guard '${typeof s=="string"?s:s.type}' is not implemented.'.`);if(typeof o!="function")return vs(o,t,e,n);const a={context:t,event:e},c=r||typeof s=="string"?void 0:"params"in s?typeof s.params=="function"?s.params({context:t,event:e}):s.params:void 0;return"check"in o?o.check(n,a,o):o(a,c)}const As=s=>s.type==="atomic"||s.type==="final";function he(s){return Object.values(s.states).filter(t=>t.type!=="history")}function Pe(s,t){const e=[];if(t===s)return e;let n=s.parent;for(;n&&n!==t;)e.push(n),n=n.parent;return e}function Qe(s){const t=new Set(s),e=Qi(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))qs(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of he(n))if(i.type!=="history"&&!t.has(i)){const r=qs(i);for(const o of r)t.add(o)}}for(const n of t){let i=n.parent;for(;i;)t.add(i),i=i.parent}return t}function Vi(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(As(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=Vi(i,t);return n}function Qi(s){const t=new Map;for(const e of s)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 tr(s,t){const e=Qe(t);return Vi(s,Qi(e))}function Ss(s,t){return t.type==="compound"?he(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?he(t).every(e=>Ss(s,e)):t.type==="final"}const hn=s=>s[0]===fc;function Cc(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===dc)return!0;if(!n.endsWith(".*"))return!1;const i=n.split("."),r=t.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((n,i)=>i.length-n.length).flatMap(n=>s.transitions.get(n))}function Mc(s){const t=s.config.after;if(!t)return[];const e=(i,r)=>{const o=pc(i,s.id),a=o.type;return s.entry.push(rh(o,{id:a,delay:i})),s.exit.push(kc(a)),a};return Object.keys(t).flatMap((i,r)=>{const o=t[i],a=typeof o=="string"?{target:o}:o,c=Number.isNaN(+i)?i:+i,h=e(c);return xt(a).map(l=>({...l,event:h,delay:c}))}).map(i=>{const{delay:r}=i;return{...Ht(s,i.event,i),delay:r}})}function Ht(s,t,e){const n=Xi(e.target),i=e.reenter??!1,r=$c(s,n),o={...e,actions:xt(e.actions),guard:e.guard,target:r,source:s,reenter:i,eventType:t,toJSON:()=>({...o,source:`#${s.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function Rc(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===Ui)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,Yt(n).map(i=>Ht(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,Yt(s.config.onDone).map(n=>Ht(s,e,n)))}for(const e of s.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,Yt(e.onDone).map(i=>Ht(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,Yt(e.onError).map(i=>Ht(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,Yt(e.onSnapshot).map(i=>Ht(s,n,i)))}}for(const e of s.after){let n=t.get(e.eventType);n||(n=[],t.set(e.eventType,n)),n.push(e)}return t}function Hc(s,t){const e=typeof t=="string"?s.states[t]:t?s.states[t.target]:void 0;if(!e&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${s.id}`);const n={source:s,actions:!t||typeof t=="string"?[]:xt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function $c(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(hn(e))return s.machine.getStateNodeById(e);const n=e[0]===Li;if(n&&!s.parent)return tn(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return tn(s.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${s.id}':
|
|
8
|
-
${r.message}`)}else throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`)})}function er(s){const t=Xi(s.config.target);return t?{target:t.map(e=>typeof e=="string"?tn(s.parent,e):e)}:s.parent.initial}function $t(s){return s.type==="history"}function qs(s){const t=nr(s);for(const e of t)for(const n of Pe(e,s))t.add(n);return t}function nr(s){const t=new Set;function e(n){if(!t.has(n)){if(t.add(n),n.type==="compound")e(n.initial.target[0]);else if(n.type==="parallel")for(const i of he(n))e(i)}}return e(s),t}function le(s,t){if(hn(t))return s.machine.getStateNodeById(t);if(!s.states)throw new Error(`Unable to retrieve child state '${t}' from '${s.id}'; no child states exist.`);const e=s.states[t];if(!e)throw new Error(`Child state '${t}' does not exist on '${s.id}'`);return e}function tn(s,t){if(typeof t=="string"&&hn(t))try{return s.machine.getStateNodeById(t)}catch{}const e=ws(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=le(n,i)}return n}function en(s,t){if(typeof t=="string"){const i=s.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${s.id}'`);return[s,i]}const e=Object.keys(t),n=e.map(i=>le(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=le(s,r);if(!o)return i;const a=en(o,t[r]);return i.concat(a)},[]))}function Bc(s,t,e,n){const r=le(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function Wc(s,t,e,n){const i=Object.keys(t),r=le(s,i[0]),o=xs(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function Pc(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=le(s,r),c=xs(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function xs(s,t,e,n){return typeof t=="string"?Bc(s,t,e,n):Object.keys(t).length===1?Wc(s,t,e,n):Pc(s,t,e,n)}function jc(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function It(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function zc(s,t){const e=new Set(s),n=new Set(t);for(const i of e)if(n.has(i))return!0;for(const i of n)if(e.has(i))return!0;return!1}function sr(s,t,e){const n=new Set;for(const i of s){let r=!1;const o=new Set;for(const a of n)if(zc(Un([i],t,e),Un([a],t,e)))if(It(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)n.delete(a);n.add(i)}}return Array.from(n)}function Kc(s){const[t,...e]=s;for(const n of Pe(t,void 0))if(e.every(i=>It(i,n)))return n}function Es(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if($t(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of Es(er(n),t))e.add(i);else e.add(n);return[...e]}function ir(s,t){const e=Es(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||It(i,s.source)))return s.source;const n=Kc(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Un(s,t,e){var i;const n=new Set;for(const r of s)if((i=r.target)!=null&&i.length){const o=ir(r,e);r.reenter&&r.source===o&&n.add(o);for(const a of t)It(a,o)&&n.add(a)}return[...n]}function Lc(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function Fn(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=sr(s,o,a);let h=t;i||([h,a]=Gc(h,n,e,c,o,a,r)),h=ue(h,n,e,c.flatMap(u=>u.actions),r),h=Fc(h,n,e,c,o,r,a,i);const l=[...o];h.status==="done"&&(h=ue(h,n,e,l.sort((u,f)=>f.order-u.order).flatMap(u=>u.exit),r));try{return a===t.historyValue&&Lc(t._nodes,o)?h:Kt(h,{_nodes:l,historyValue:a})}catch(u){throw u}}function Uc(s,t,e,n,i){if(n.output===void 0)return;const r=zn(i.id,i.output!==void 0&&i.parent?Kn(i.output,s.context,t,e.self):void 0);return Kn(n.output,s.context,r,e.self)}function Fc(s,t,e,n,i,r,o,a){let c=s;const h=new Set,l=new Set;qc(n,o,l,h),a&&l.add(s.machine.root);const u=new Set;for(const f of[...h].sort((m,d)=>m.order-d.order)){i.add(f);const m=[];m.push(...f.entry);for(const d of f.invoke)m.push(Ic(d.src,{...d,syncSnapshot:!!d.onSnapshot}));if(l.has(f)){const d=f.initial.actions;m.push(...d)}if(c=ue(c,t,e,m,r,f.invoke.map(d=>d.id)),f.type==="final"){const d=f.parent;let g=(d==null?void 0:d.type)==="parallel"?d:d==null?void 0:d.parent,_=g||f;for((d==null?void 0:d.type)==="compound"&&r.push(zn(d.id,f.output!==void 0?Kn(f.output,c.context,t,e.self):void 0));(g==null?void 0:g.type)==="parallel"&&!u.has(g)&&Ss(i,g);)u.add(g),r.push(zn(g.id)),_=g,g=g.parent;if(g)continue;c=Kt(c,{status:"done",output:Uc(c,t,e,c.machine.root,_)})}}return c}function qc(s,t,e,n){for(const i of s){const r=ir(i,t);for(const a of i.target||[])!$t(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),Qt(a,t,e,n);const o=Es(i,t);for(const a of o){const c=Pe(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),rr(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Qt(s,t,e,n){var i;if($t(s))if(t[s.id]){const r=t[s.id];for(const o of r)n.add(o),Qt(o,t,e,n);for(const o of r)bn(o,s.parent,n,t,e)}else{const r=er(s);for(const o of r.target)n.add(o),r===((i=s.parent)==null?void 0:i.initial)&&e.add(s.parent),Qt(o,t,e,n);for(const o of r.target)bn(o,s.parent,n,t,e)}else if(s.type==="compound"){const[r]=s.initial.target;$t(r)||(n.add(r),e.add(r)),Qt(r,t,e,n),bn(r,s,n,t,e)}else if(s.type==="parallel")for(const r of he(s).filter(o=>!$t(o)))[...n].some(o=>It(o,r))||($t(r)||(n.add(r),e.add(r)),Qt(r,t,e,n))}function rr(s,t,e,n,i){for(const r of n)if((!i||It(r,i))&&s.add(r),r.type==="parallel")for(const o of he(r).filter(a=>!$t(a)))[...s].some(a=>It(a,o))||(s.add(o),Qt(o,t,e,s))}function bn(s,t,e,n,i){rr(e,n,i,Pe(s,t))}function Gc(s,t,e,n,i,r,o){let a=s;const c=Un(n,i,r);c.sort((l,u)=>u.order-l.order);let h;for(const l of c)for(const u of jc(l)){let f;u.history==="deep"?f=m=>As(m)&&It(m,l):f=m=>m.parent===l,h??(h={...r}),h[u.id]=Array.from(i).filter(f)}for(const l of c)a=ue(a,t,e,[...l.exit,...l.invoke.map(u=>Ji(u.id))],o),i.delete(l);return[a,h||r]}let Gs=!1;function or(s,t,e,n,i,r){const{machine:o}=s;let a=s;for(const c of n){let m=function(){e.system._sendInspectionEvent({type:"@xstate.action",actorRef:e.self,action:{type:typeof c=="string"?c:typeof c=="object"?c.type:c.name||"(anonymous)",params:f}});try{Gs=l,l(u,f)}finally{Gs=!1}};const h=typeof c=="function",l=h?c:o.implementations.actions[typeof c=="string"?c:c.type];if(!l)continue;const u={context:a.context,event:t,self:e.self,system:e.system},f=h||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:t}):c.params:void 0;if(!("resolve"in l)){e.self._processingStatus===G.Running?m():e.defer(()=>{m()});continue}const d=l,[g,_,S]=d.resolve(e,a,u,f,l,i);a=g,"retryResolve"in d&&(r==null||r.push([d,_])),"execute"in d&&(e.self._processingStatus===G.Running?d.execute(e,_):e.defer(d.execute.bind(null,e,_))),S&&(a=or(a,t,e,S,i,r))}return a}function ue(s,t,e,n,i,r){const o=r?[]:void 0,a=or(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,h])=>{c.retryResolve(e,a,h)}),a}function vn(s,t,e,n=[]){let i=s;const r=[];function o(h,l,u){e.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:e.self,event:l,snapshot:h,_transitions:u}),r.push(h)}if(t.type===jn)return i=Kt(Zs(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==Fi){const h=a,l=_c(h),u=Ys(h,i);if(l&&!u.length)return i=Kt(s,{status:"error",error:h.error}),o(i,h,[]),{snapshot:i,microstates:r};i=Fn(u,s,e,a,!1,n),o(i,h,u)}let c=!0;for(;i.status==="active";){let h=c?Zc(i,a):[];const l=h.length?i:void 0;if(!h.length){if(!n.length)break;a=n.shift(),h=Ys(a,i)}i=Fn(h,i,e,a,!1,n),c=i!==l,o(i,a,h)}return i.status!=="active"&&Zs(i,a,e),{snapshot:i,microstates:r}}function Zs(s,t,e){return ue(s,t,e,Object.values(s.children).map(n=>Ji(n)),[])}function Ys(s,t){return t.machine.getTransitionData(t,s)}function Zc(s,t){const e=new Set,n=s._nodes.filter(As);for(const i of n)t:for(const r of[i].concat(Pe(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||vs(o.guard,s.context,t,s)){e.add(o);break t}}return sr(Array.from(e),new Set(s._nodes),s.historyValue)}function Yc(s,t){const e=Qe(en(s,t));return tr(s,[...e])}function Xc(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Jc=function(t){return Gi(t,this.value)},Vc=function(t){return this.tags.has(t)},Qc=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(n=>n.target!==void 0||n.actions.length)},th=function(){const{_nodes:t,tags:e,machine:n,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...h}=this;return{...h,tags:Array.from(e)}},eh=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function Fe(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:tr(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Jc,hasTag:Vc,can:Qc,getMeta:eh,toJSON:th}}function Kt(s,t={}){return Fe({...s,...t},s.machine)}function nh(s,t){const{_nodes:e,tags:n,machine:i,children:r,context:o,can:a,hasTag:c,matches:h,getMeta:l,toJSON:u,...f}=s,m={};for(const g in r){const _=r[g];m[g]={snapshot:_.getPersistedSnapshot(t),src:_.src,systemId:_._systemId,syncSnapshot:_._syncSnapshot}}return{...f,context:ar(o),children:m}}function ar(s){let t;for(const e in s){const n=s[e];if(n&&typeof n=="object")if("sessionId"in n&&"send"in n&&"ref"in n)t??(t=Array.isArray(s)?s.slice():{...s}),t[e]={xstate$$type:bs,id:n.id};else{const i=ar(n);i!==n&&(t??(t=Array.isArray(s)?s.slice():{...s}),t[e]=i)}}return t??s}function sh(s,t,e,n,{event:i,id:r,delay:o},{internalQueue:a}){const c=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const h=typeof i=="function"?i(e,n):i;let l;if(typeof o=="string"){const u=c&&c[o];l=typeof u=="function"?u(e,n):u}else l=typeof o=="function"?o(e,n):o;return typeof l!="number"&&a.push(h),[t,{event:h,id:r,delay:l}]}function ih(s,t){const{event:e,delay:n,id:i}=t;if(typeof n=="number"){s.defer(()=>{const r=s.self;s.system.scheduler.schedule(r,r,e,n,i)});return}}function rh(s,t){function e(n,i){}return e.type="xstate.raise",e.event=s,e.id=t==null?void 0:t.id,e.delay=t==null?void 0:t.delay,e.resolve=sh,e.execute=ih,e}function oh(s,{machine:t,context:e},n,i){const r=(o,a={})=>{const{systemId:c,input:h}=a;if(typeof o=="string"){const l=_s(t,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const u=ce(l,{id:a.id,parent:s.self,syncSnapshot:a.syncSnapshot,input:typeof h=="function"?h({context:e,event:n,self:s.self}):h,src:o,systemId:c});return i[u.id]=u,u}else return ce(o,{id:a.id,parent:s.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,s.defer(()=>{c._processingStatus!==G.Stopped&&c.start()}),c}}function ah(s,t,e,n,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const r={},o={context:t.context,event:e.event,spawn:oh(s,t,e.event,r),self:s.self,system:s.system};let a={};if(typeof i=="function")a=i(o,n);else for(const h of Object.keys(i)){const l=i[h];a[h]=typeof l=="function"?l(o,n):l}const c=Object.assign({},t.context,a);return[Kt(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children})]}function ch(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=ah,t}const Xs=new WeakMap;function Zt(s,t,e){let n=Xs.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},Xs.set(s,n)),n[t]}const hh={},ge=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class ks{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(Li),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?Ls(this.config.states,(n,i)=>new ks(n,{_parent:this,_key:i,_machine:this.machine})):hh,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=xt(this.config.entry).slice(),this.exit=xt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=xt(t.tags).slice()}_initialize(){this.transitions=Rc(this),this.config.always&&(this.always=Yt(this.config.always).map(t=>Ht(this,Ui,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(ge),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ge),eventType:null})}:void 0,history:this.history,states:Ls(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ge)})),entry:this.entry.map(ge),exit:this.exit.map(ge),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 Zt(this,"invoke",()=>xt(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??Us(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${Us(this.id,e)}`;return{...t,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...h}=t;return{...h,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return Zt(this,"on",()=>[...this.transitions].flatMap(([e,n])=>n.map(i=>[e,i])).reduce((e,[n,i])=>(e[n]=e[n]||[],e[n].push(i),e),{}))}get after(){return Zt(this,"delayedTransitions",()=>Mc(this))}get initial(){return Zt(this,"initial",()=>Hc(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=Zt(this,`candidates-${n}`,()=>Cc(this,n));for(const a of o){const{guard:c}=a,h=t.context;let l=!1;try{l=!c||vs(c,h,e,t)}catch(u){const f=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${f?`'${f}' `:""}in transition for event '${n}' in state node '${this.id}':
|
|
9
|
-
|
|
1
|
+
"use strict";var Ms=Object.defineProperty;var $s=(n,t,e)=>t in n?Ms(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var _=(n,t,e)=>$s(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Le="MS Gothic, sans-serif",et={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Ne={WIDTH:125,HEIGHT:27.5},$n={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"},ue={[A.E]:"東",[A.S]:"南",[A.W]:"西",[A.N]:"北"},ze={[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 Ps{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(Le,$n.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class Hs{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 Vt=(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]},Ws=(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]},Pn=n=>{const t=[];n.forEach((s,r)=>{s.has(y.HORIZONTAL)&&t.push(r)});const e=n.filter(s=>!s.has(y.HORIZONTAL)).sort(Vt);return t.forEach(s=>{e.splice(s,0,n[s])}),e};function C(n){return n.isNum()&&n.n==5}function Bs(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(Ws).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=Pn(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Vt);return}}static deserialize(t){const e=new W(t.tiles).parse();if(e.length!=1)throw new Error(`block must be 1: ${t.tiles}`);const s=e[0].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 se(e[0].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),se(s,this._type)}}const bt=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}`},je=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 bt(this.tiles)}}class Y extends T{constructor(t){super(t,b.PON)}static from(t){return T.deserialize({tiles:t,type:b.PON})}toString(){return bt(this.tiles)}}class x 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 je(this.tilesWithBack)}}class X extends T{constructor(t){super(t,b.DAI_KAN)}static from(t){return T.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return bt(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 bt(this.tiles)}}class H extends T{constructor(t,e){super([t,e],b.PAIR)}toString(){return bt(this.tiles)}}class z extends T{constructor(t){super(t,b.THREE)}static from(t){return T.deserialize({tiles:t,type:b.THREE})}toString(){return bt(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 bt(this.tiles)}}class Fe extends T{constructor(t){super([t],b.ISOLATED)}toString(){return this.tiles[0].toString()}}class Ot extends T{constructor(t){super(t,b.HAND)}toString(){return je(this.tiles)}}class Ge extends T{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):je(this.tiles)}}const se=(n,t)=>{switch(t){case b.CHI:return new Z([n[0],n[1],n[2]]);case b.PON:return new Y([n[0],n[1],n[2]]);case b.AN_KAN:return new x(n);case b.DAI_KAN:return new X(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 Fe(n[0]);case b.HAND:return new Ot(n);default:return new Ge(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 Hs(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]=gn(r,s);if(o){if(i==p.BACK){e.push(new w(i,0)),t.readChar();continue}e.push(...Ks(s,i)),s=[],t.readChar();continue}else{const[a,c]=Ls(t);if(c){s.push(a),t.readChar();continue}const[l,u]=Hn(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=pn(e),c=se(e,a);s.push(c),e=[];continue}e.push(o)}const r=pn(e),i=se(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]=gn(e,[new w(p.BACK,1)]);if(!r)throw new Error(`last character(${e}) is not type value`)}}function pn(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&&Ds(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 Ds(n){const t=[...n].sort(Vt);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 Ks(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 gn(n,t){const[e,s]=Bs(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 Hn(n){const t=Number(n),e=0<=t&&t<=9;return[t,e]}function Ls(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]=Hn(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 Ft=n=>{let t=n.substring(0,2),e=Number(n.substring(2,3));return e==4?(e=1,t=nt(t)):e++,`${t}${e}`},zs=n=>Ft(Ft(Ft(n))),nt=n=>{let t=Number(n.toString()[0]);return t=t%4+1,`${t}w`},Ue=n=>{let t=Number(n.toString()[0]);return t=t%2+1,`${t}w`},Se=(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 yn(n){return typeof n>"u"}function ve(n,t=0){return{a:1,c:0,e:n,b:0,d:1,f:t}}function Ze(...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 Ze(i,...r)}}}function js(...n){return Ze(...n)}const{cos:Fs,sin:Gs,PI:Us}=Math;function Zs(n,t,e){const s=Fs(n),r=Gs(n),i={a:s,c:-r,e:0,b:r,d:s,f:0};return yn(t)||yn(e)?i:Ze([ve(t,e),i,ve(-t,-e)])}function Vs(n,t=void 0,e=void 0){return Zs(n*Us/180,t,e)}function Js(n){return Xs(n)}function Xs(n){return`matrix(${n.a},${n.b},${n.c},${n.d},${n.e},${n.f})`}function Ys(n,t){function e(){this.constructor=n}e.prototype=t.prototype,n.prototype=new e}function he(n,t,e,s){var r=Error.call(this,n);return Object.setPrototypeOf&&Object.setPrototypeOf(r,he.prototype),r.expected=t,r.found=e,r.location=s,r.name="SyntaxError",r}Ys(he,Error);function ge(n,t,e){return e=e||" ",n.length>t?n:(t-=n.length,e+=e.repeat(t),n+e.slice(0,t))}he.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=ge("",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+=`
|
|
2
|
+
--> `+o+`
|
|
3
|
+
`+c+` |
|
|
4
|
+
`+i.line+" | "+l+`
|
|
5
|
+
`+c+" | "+ge("",r.column-1," ")+ge("",h,"^")}else t+=`
|
|
6
|
+
at `+o}return t};he.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 Wn=":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",qs=Wn+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Qs="["+Wn+"]["+qs+"]*",tr=new RegExp("^"+Qs+"$");function Bn(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 Ve=function(n){const t=tr.exec(n);return!(t===null||typeof t>"u")};function er(n){return typeof n<"u"}const nr={allowBooleanAttributes:!1,unpairedTags:[]};function sr(n,t){t=Object.assign({},nr,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=wn(n,i),i.err)return i}else if(n[i]==="<"){let o=i;if(i++,n[i]==="!"){i=bn(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--),!hr(c)){let h;return c.trim().length===0?h="Invalid space after '<'.":h="Tag '"+c+"' is an invalid name.",I("InvalidTag",h,M(n,i))}const l=or(n,i);if(l===!1)return I("InvalidAttr","Attributes for '"+c+"' have open quote.",M(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=_n(u,t);if(d===!0)s=!0;else return I(d.err.code,d.err.msg,M(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.",M(n,o));if(e.length===0)return I("InvalidTag","Closing tag '"+c+"' has not been opened.",M(n,o));{const h=e.pop();if(c!==h.tagName){let d=M(n,h.tagStartPos);return I("InvalidTag","Expected closing tag '"+h.tagName+"' (opened in line "+d.line+", col "+d.col+") instead of closing tag '"+c+"'.",M(n,o))}e.length==0&&(r=!0)}}else return I("InvalidTag","Closing tag '"+c+"' doesn't have proper closing.",M(n,i));else{const h=_n(u,t);if(h!==!0)return I(h.err.code,h.err.msg,M(n,i-u.length+h.err.line));if(r===!0)return I("InvalidXml","Multiple possible root nodes found.",M(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=bn(n,i);continue}else if(n[i+1]==="?"){if(i=wn(n,++i),i.err)return i}else break;else if(n[i]==="&"){const h=lr(n,i);if(h==-1)return I("InvalidChar","char '&' is not expected.",M(n,i));i=h}else if(r===!0&&!mn(n[i]))return I("InvalidXml","Extra text at the end",M(n,i));n[i]==="<"&&i--}}else{if(mn(n[i]))continue;return I("InvalidChar","char '"+n[i]+"' is not expected.",M(n,i))}if(s){if(e.length==1)return I("InvalidTag","Unclosed tag '"+e[0].tagName+"'.",M(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 mn(n){return n===" "||n===" "||n===`
|
|
8
|
+
`||n==="\r"}function wn(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.",M(n,t));if(n[t]=="?"&&n[t+1]==">"){t++;break}else continue}return t}function bn(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 rr='"',ir="'";function or(n,t){let e="",s="",r=!1;for(;t<n.length;t++){if(n[t]===rr||n[t]===ir)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 ar=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function _n(n,t){const e=Bn(n,ar),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.",Dt(e[r]));if(e[r][3]!==void 0&&e[r][4]===void 0)return I("InvalidAttr","Attribute '"+e[r][2]+"' is without value.",Dt(e[r]));if(e[r][3]===void 0&&!t.allowBooleanAttributes)return I("InvalidAttr","boolean attribute '"+e[r][2]+"' is not allowed.",Dt(e[r]));const i=e[r][2];if(!ur(i))return I("InvalidAttr","Attribute '"+i+"' is an invalid name.",Dt(e[r]));if(!s.hasOwnProperty(i))s[i]=1;else return I("InvalidAttr","Attribute '"+i+"' is repeated.",Dt(e[r]))}return!0}function cr(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 lr(n,t){if(t++,n[t]===";")return-1;if(n[t]==="#")return t++,cr(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 ur(n){return Ve(n)}function hr(n){return Ve(n)}function M(n,t){const e=n.substring(0,t).split(/\r?\n/);return{line:e.length,col:e[e.length-1].length+1}}function Dt(n){return n.startIndex+n[1].length}const dr={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},fr=function(n){return Object.assign({},dr,n)};let re;typeof Symbol!="function"?re="@@xmlMetadata":re=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][re]={startIndex:e})}static getMetaDataSymbol(){return re}}function pr(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&&mr(n,t)){t+=7;let a,c;[a,c,t]=gr(n,t+1),c.indexOf("&")===-1&&(e[Ar(a)]={regx:RegExp(`&${a};`,"g"),val:c})}else if(r&&wr(n,t))t+=8;else if(r&&br(n,t))t+=8;else if(r&&_r(n,t))t+=9;else if(yr)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}}function gr(n,t){let e="";for(;t<n.length&&n[t]!=="'"&&n[t]!=='"';t++)e+=n[t];if(e=e.trim(),e.indexOf(" ")!==-1)throw new Error("External entites are not supported");const s=n[t++];let r="";for(;t<n.length&&n[t]!==s;t++)r+=n[t];return[e,r,t]}function yr(n,t){return n[t+1]==="!"&&n[t+2]==="-"&&n[t+3]==="-"}function mr(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 wr(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 br(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 _r(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 Ar(n){if(Ve(n))return n;throw new Error(`Invalid entity name ${n}`)}const Er=/^[-+]?0x[a-fA-F0-9]+$/,Nr=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Sr={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function vr(n,t={}){if(t=Object.assign({},Sr,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&&Er.test(e))return Ir(e,16);if(e.search(/[eE]/)!==-1){const s=e.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(s){if(t.leadingZeros)e=(s[1]||"")+s[3];else if(!(s[2]==="0"&&s[3][0]==="."))return n;return t.eNotation?Number(e):n}else return n}else{const s=Nr.exec(e);if(s){const r=s[1],i=s[2];let o=Tr(s[3]);if(!t.leadingZeros&&i.length>0&&r&&e[2]!==".")return n;if(!t.leadingZeros&&i.length>0&&!r&&e[1]!==".")return n;if(t.leadingZeros&&i===n)return 0;{const a=Number(e),c=""+a;return c.search(/[eE]/)!==-1?t.eNotation?a:n:e.indexOf(".")!==-1?c==="0"&&o===""||c===o||r&&c==="-"+o?a:n:i?o===c||r+o===c?a:n:e===c||e===r+c?a:n}}else return n}}function Tr(n){return n&&n.indexOf(".")!==-1&&(n=n.replace(/0+$/,""),n==="."?n="0":n[0]==="."?n="0"+n:n[n.length-1]==="."&&(n=n.substr(0,n.length-1))),n}function Ir(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 Dn(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 Or{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=kr,this.parseXml=$r,this.parseTextData=Cr,this.resolveNameSpace=xr,this.buildAttributesMap=Mr,this.isItStopNode=Br,this.replaceEntitiesValue=Hr,this.readStopNodeData=Kr,this.saveTextToParentTag=Wr,this.addChild=Pr,this.ignoreAttributesFn=Dn(this.options.ignoreAttributes)}}function kr(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 Cr(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?Ie(n,this.options.parseTagValue,this.options.numberParseOptions):n.trim()===n?Ie(n,this.options.parseTagValue,this.options.numberParseOptions):n}}function xr(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 Rr=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function Mr(n,t,e){if(this.options.ignoreAttributes!==!0&&typeof n=="string"){const s=Bn(n,Rr),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]=Ie(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 $r=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=Te(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=pr(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=Te(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 Pr(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 Hr=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 Wr(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 Br(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 Dr(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 Te(n,t,e,s=">"){const r=Dr(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 Kr(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=Te(n,e,">");i&&((i&&i.tagName)===t&&i.tagExp[i.tagExp.length-1]!=="/"&&r++,e=i.closeIndex)}}function Ie(n,t,e){if(t&&typeof n=="string"){const s=n.trim();return s==="true"?!0:s==="false"?!1:vr(n,e)}else return er(n)?n:""}const ye=ht.getMetaDataSymbol();function Lr(n,t){return Kn(n,t)}function Kn(n,t,e){let s;const r={};for(let i=0;i<n.length;i++){const o=n[i],a=zr(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=Kn(o[a],t,c);const u=Fr(l,t);o[ye]!==void 0&&(l[ye]=o[ye]),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 zr(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 Fr(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 Gr{constructor(t){this.externalEntities={},this.options=fr(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=sr(t,e);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const s=new Or(this.options);s.addExternalEntities(this.externalEntities);const r=s.parseXml(t);return this.options.preserveOrder||r===void 0?r:Lr(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 '
'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return ht.getMetaDataSymbol()}}const Ur=`
|
|
10
|
+
`;function Zr(n,t){let e="";return t.format&&t.indentBy.length>0&&(e=Ur),Ln(n,t,"",e)}function Ln(n,t,e,s){let r="",i=!1;for(let o=0;o<n.length;o++){const a=n[o],c=Vr(a);if(c===void 0)continue;let l="";if(e.length===0?l=c:l=`${e}.${c}`,c===t.textNodeName){let f=a[c];Jr(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=An(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=An(a[":@"],t),d=s+`<${c}${h}`,g=Ln(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 Vr(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 An(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 Jr(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 Xr={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function it(n){this.options=Object.assign({},Xr,n),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Dn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Qr),this.processTextOrObjNode=Yr,this.options.format?(this.indentate=qr,this.tagEndChar=`>
|
|
11
|
+
`,this.newLine=`
|
|
12
|
+
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}it.prototype.build=function(n){return this.options.preserveOrder?Zr(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 Yr(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 qr(n){return this.options.indentBy.repeat(n)}function Qr(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,Gn(this.attrs),ui(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 Je extends ot{constructor(e){super("image");_(this,"attrs",{});this.attrs={...this.attrs,href:e}}load(e){return this.attrs.href=e,this}}class de 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 Xe extends ot{constructor(){super("rect");_(this,"attrs",{})}fill(e){return this.attrs.fill=e,this}stroke(e){return this.attrs.stroke=e,this}}class gt 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 Ye=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=Vs(e,s,r),this}translate(e,s){return this.translateMatrix=ve(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(li(js(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 ti=['xmlns="http://www.w3.org/2000/svg"','version="1.1"','xmlns:xlink="http://www.w3.org/1999/xlink"'];class jn 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,...ti,Gn(this.attrs),ci(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 hi(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 Fn(){return new jn}const ei=Fn,ni=v,si=Je,ri=de,ii=Xe,oi=gt;function ai(n){return n.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function ci(n){return n==null?"":`viewBox="${n.x} ${n.y} ${n.width} ${n.height}"`}function li(n){return n==null?"":`transform="${Js(n)}"`}function Gn(n){return Object.entries(n).filter(([t,e])=>e!==void 0).map(([t,e])=>`${ai(t)}="${e}"`).join(" ")}function ui(n){const t=Object.entries(n).map(([e,s])=>`${e}: ${s};`).join(" ");return t!=""?`style="${t}"`:""}function*hi(n){const t=new Gr({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 Ye(i);for(const[a,c]of Object.entries(r))a.startsWith("@_")&&(o.attrs[a.substring(2)]=c);yield o}}const F=(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((et.HEIGHT*t).toPrecision(5)),s=parseFloat((et.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*et.TEXT_SCALE),r};class kt{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=et.WIDTH*this.scale,this.tileHeight=et.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 Je().load(this.buildURL(t));return this.svgSprite&&(e=new de().use(kt.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 gt().plain(r);u.size(o.baseWidth,o.baseHeight).font({family:Le,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=`${kt.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:e}}class qe extends kt{constructor(){super(...arguments);_(this,"blockMargin",et.WIDTH*et.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const s=e instanceof x?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 di=(n,t)=>{const e=n.scale;return{[b.CHI]:function(r){const i=F(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.PON]:function(r){const i=F(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.DAI_KAN]:function(r){const i=F(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.SHO_KAN]:function(r){const i=F(r,e),o=n.createBlockPonChiKan(r);return{...i,e:o}},[b.AN_KAN]:function(r){S(r instanceof x,`block type is not ankan: ${r.type}`);const i=F(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[b.IMAGE_DORA]:function(r){r=(t==null?void 0:t.doraText)==!1?new Ot([r.tiles[0].clone({remove:y.DORA})]):r;const i=F(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 Ot([r.tiles[0].clone({remove:y.TSUMO})]):r;const i=F(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=F(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}},[b.IMAGE_DISCARD]:function(r){const i=F(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=F(r,e),o=n.createBlockHandDiscard(r);return{...i,e:o}}}},vt=(n,t,e)=>{const s=di(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}},fi=(n,t,e={},s={responsive:!1,doraText:!0,tsumoText:!0})=>{const r=new qe(e),i=vt(r,t,s);s.responsive||n.size(i.width,i.height),n.viewbox(0,0,i.width,i.height),n.add(i.e)},Un=()=>{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(kt.buildID(new w(e,0)));continue}t.push(...n.map(s=>kt.buildID(new w(e,s))).flat())}return t},pi=n=>{const t=Un(),e=[];return n.each((s,r)=>{const i=r[s];if(i instanceof de){const a=i.attr("href").substring(1);t.includes(a)&&e.push(a)}},!0),e},gi=n=>{const t=Un(),e=pi(n);n.each((s,r)=>{const i=r[s];i instanceof Ye&&(t.includes(i.id())&&e.includes(i.id())||i.remove())},!0)},yi=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)},qt=(n,t)=>{const e=new v,s=yi(n);for(let r=0;r<s.length;r++){let i=s[r],o=r*t.tileHeight;const a=t.createBlockHandDiscard(new Ge(i,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*s.length}},mi=(n,t,e)=>{const s=t.font,r=t.textWidth,i=t.textHeight,o=e.sticks.dead,a=e.sticks.reach,c=Ne.WIDTH*n.scale,l=Ne.HEIGHT*n.scale;let u=r*3,h=i;const d=(c+n.tileWidth+r-u)/2,g=new gt().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 gt().plain(a.toString()).font(E).dx(c).dy(l),R=n.createStick(100).size(c,l).x(0).y(l+l),_t=new gt().plain(o.toString()).font(E).dx(c).dy(l*3);m.add(N),m.add(O),m.add(R),m.add(_t);const At=n.createImage(e.doras[0],0,0).x(c+r).y(0);m.add(At);const Et=new v;return Et.add(g),Et.add(g),Et.add(m),{e:Et,width:c+n.tileWidth+r,height:h+n.tileHeight}},wi=(n,t,e=0)=>{const s=vt(n,t.front),r=vt(n,t.right),i=vt(n,t.opposite),o=vt(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}},bi=n=>{const t=Object.values(ue),e=t.indexOf(n);return[...t.slice(e),...t.slice(0,e)]},_i=(n,t,e)=>{const s=n.tileWidth*5+n.tileHeight*1,r=t.font,i=t.textWidth,o=t.textHeight,a=t.numWidth,c=mi(n,t,e);c.e.translate(s/2-c.width/2,s/2-c.height/2);const l=(ks,fn,Cs)=>{const xs=`${ks} ${fn}`,Rs=new gt().plain(xs).font(r).attr(Cs);return{e:new v().add(Rs),width:i+a*fn.toString().length,height:o}},[u,h,d,g]=bi(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 R=l(d,f.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const _t=j(R.e,R.width,R.height,180).translate(s/2-R.width,-R.height);let At=l(g,f.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Et=j(At.e,At.width,At.height,90).translate(-At.height,s/2),at=new v,Os=new Xe().size(s,s).x(0).y(0).fill("none").stroke("#000000");return at.add(Os),at.add(c.e),at.add(E),at.add(O),at.add(_t),at.add(Et),{e:at,width:s,height:s}},Ai=(n,t)=>{const e=qt(t.front,n),s=qt(t.right,n),r=qt(t.opposite,n),i=qt(t.left,n),o=[e.height,s.height,r.height,i.height].reduce((O,R)=>Math.max(O,R)),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}},Zn=(n,t,e,s,r)=>{const i=new v,o=Ai(n,s),a=wi(n,e,o.height),c=_i(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}},Ei=(n,t,e={},s,r={responsive:!1})=>{const i=new qe(e),o=s,{discards:a,hands:c,scoreBoard:l}=Xn(t),u=Zn(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 V;function Vn(n){return{lang:(n==null?void 0:n.lang)??(V==null?void 0:V.lang),message:n==null?void 0:n.message,abortEarly:(n==null?void 0:n.abortEarly)??(V==null?void 0:V.abortEarly),abortPipeEarly:(n==null?void 0:n.abortPipeEarly)??(V==null?void 0:V.abortPipeEarly)}}var me;function Ni(n){return me==null?void 0:me.get(n)}var we;function Si(n){return we==null?void 0:we.get(n)}var be;function vi(n,t){var e;return(e=be==null?void 0:be.get(n))==null?void 0:e.get(t)}function Ct(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)??Ct(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??vi(n.reference,c.lang)??(l?Si(c.lang):null)??s.message??Ni(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 Bt(n){return{version:1,vendor:"valibot",validate(t){return n["~run"]({value:t},Vn())}}}function Ti(n,t){const e=[...new Set(n)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Oe(n,t){return{kind:"validation",type:"max_value",reference:Oe,async:!1,expects:`<=${n instanceof Date?n.toJSON():Ct(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():Ct(e.value)}),e}}}function ke(n,t){return{kind:"validation",type:"min_value",reference:ke,async:!1,expects:`>=${n instanceof Date?n.toJSON():Ct(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():Ct(e.value)}),e}}}function Ii(n,t,e){return typeof n.fallback=="function"?n.fallback(t,e):n.fallback}function Jn(n,t,e){return typeof n.default=="function"?n.default(t,e):n.default}function ie(n){return{kind:"schema",type:"number",reference:ie,expects:"number",async:!1,message:n,get"~standard"(){return Bt(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 Bt(this)},"~run"(e,s){return e.value===void 0&&(this.default!==void 0&&(e.value=Jn(this,e,s)),e.value===void 0)?(e.typed=!0,e):this.wrapped["~run"](e,s)}}}function Ce(n,t){return{kind:"schema",type:"picklist",reference:Ce,expects:Ti(n.map(Ct),"|"),async:!1,options:n,message:t,get"~standard"(){return Bt(this)},"~run"(e,s){return this.options.includes(e.value)?e.typed=!0:st(this,"type",e,s),e}}}function xt(n,t){return{kind:"schema",type:"strict_object",reference:xt,expects:"Object",async:!1,entries:n,message:t,get"~standard"(){return Bt(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]:Jn(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]=Ii(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 oe(n){return{kind:"schema",type:"string",reference:oe,expects:"string",async:!1,message:n,get"~standard"(){return Bt(this)},"~run"(t,e){return typeof t.value=="string"?t.typed=!0:st(this,"type",t,e),t}}}function En(...n){return{...n[0],pipe:n,get"~standard"(){return Bt(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 Oi(n,t,e){const s=n["~run"]({value:t},Vn(e));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}const Qt=K(xt({discard:K(oe(),""),hand:K(oe(),""),score:K(ie(),25e3)}),{discard:"",hand:"",score:25e3}),ki=xt({[A.E]:Qt,[A.S]:Qt,[A.W]:Qt,[A.N]:Qt}),ct={round:k.E1,sticks:{reach:0,dead:0},doras:A.S,front:A.E},Ci=K(xt({round:K(Ce(Object.keys(ze)),ct.round),sticks:K(xt({reach:K(En(ie(),ke(0,""),Oe(9,"")),ct.sticks.reach),dead:K(En(ie(),ke(0,""),Oe(9,"")),ct.sticks.dead)}),ct.sticks),doras:K(oe(),ct.doras),front:K(Ce(Object.keys(ue)),ct.front)}),ct),xi=xt({...ki.entries,board:Ci}),Xn=n=>{const t=Yn(n);return qn(t)},Yn=n=>{const t=Ri(n),e=Oi(xi,t);if(!e.success)throw e.issues;return e.output},Ri=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]=$i([...s]);i.board=l;for(let h=0;h<u;h++)s.shift()}else{const[l,u]=Mi([...s]);i[c]=l;for(let h=0;h<u;h++)s.shift()}}return i},G=(n,t)=>n.replace(t,"").replace(":","").trim(),Mi=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=G(o,t);else if(o.startsWith(e))r.discard=G(o,e);else if(o.startsWith(s))r.score=Number(G(o,s));else break}return[r,i]},$i=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=G(l,t);else if(l.startsWith(e))a.round=G(l,e);else if(l.startsWith(s))a.front=G(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(G(u,i))),u.startsWith(o)&&(a.sticks.dead=Number(G(u,o))),h.startsWith(i)&&(a.sticks.reach=Number(G(h,i))),h.startsWith(o)&&(a.sticks.dead=Number(G(h,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},qn=n=>{const t=n.board.front,e=Pi(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:ze[n.board.round],frontPlace:ue[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}},Pi=n=>({front:n,right:nt(n),opposite:nt(nt(n)),left:Ue(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 fe{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));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 Ot(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 x))}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 x){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 fe(this.toString());return t.data.reached=this.data.reached,t}}class Jt{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?Rt:U;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 Qn{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=ts(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?Rt:U;for(let i of r)if(this.hand.get(s,i)==1)t.push(new Fe(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 Ot(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(const[e,s]of L())if(this.hand.get(e,s)>=2){const r=this.hand.dec(new Array(2).fill(new w(e,s))),i=this.patternAll().filter(o=>o.length==4).map(o=>(o.unshift(new H(r[0],r[1])),o));t=[...t,...i],this.hand.inc(r)}return t}patternAll(){const t=[this.handleNumType(p.M),this.handleNumType(p.P),this.handleNumType(p.S),this.handleZ(),this.handleBack(),[this.hand.called.concat()]].sort((s,r)=>r.length-s.length),e=t[0].concat();for(let s=0;s<e.length;s++)for(let r=1;r<t.length;r++)for(const i of t[r])e[s]=[...e[s],...i];return e}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]}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 Rt=[1,2,3,4,5,6,7],U=[1,9],Lt=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 xe{constructor(t,e){_(this,"hand");_(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(s=>Sn(s)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(s=>Sn(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,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);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||U.includes(r.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:Nn(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 x||s instanceof D||s instanceof X||s instanceof z||s instanceof Y||s instanceof H)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(s=>(s instanceof x||s instanceof z)&&!s.tiles.some(r=>r.has(y.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(s=>s instanceof x||s instanceof D||s instanceof X).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=s=>s instanceof x||s instanceof D||s instanceof X||s instanceof z||s instanceof Y;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.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?Rt:U;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?Rt:U;return s.tiles.some(i=>r.includes(i.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];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.filter(r=>r>0).length==s.length)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=>U.includes(r.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:Nn(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 x||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&&U.includes(r.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(s=>s instanceof x||s instanceof D||s instanceof X).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&&[5,6,7].includes(E.n)||E.t==p.Z&&[r,i].includes(E.n)||U.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 Y:s+=l(f,2);break;case(f instanceof X||f instanceof D):s+=l(f,8);break;case f instanceof x: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&&(s+=2),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 ts=n=>n.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Nn=n=>{const t={};for(const s of n){if(!(s instanceof Q))continue;const r=ts(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(Vt)[0],Sn=n=>{const t=n.n,e=n.t;return new w(e,t%9+1)};class Mt{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=Mt.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 Jt(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 Re=()=>{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 es(n){var i;const t=["RON","DAI_KAN","PON","CHI"],e=n.map(o=>o.choices),r=ss(e,t).map(o=>n[o]);return{events:r,type:rs(t,(i=r[0])==null?void 0:i.choices)}}function ns(n){var i;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=n.map(o=>o.choices),r=ss(e,t).map(o=>n[o]);return{events:r,type:rs(t,(i=r[0])==null?void 0:i.choices)}}function ss(n,t){let e=[],s=Number.POSITIVE_INFINITY;for(let r=0;r<n.length;r++){const i=n[r];if(Hi(i,t)){const o=Wi(t,i);o<s?(s=o,e=[r]):o===s&&e.push(r)}}return e}function Hi(n,t){return t.some(e=>!!n[e])}function Wi(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(t[s])return e}return Number.POSITIVE_INFINITY}function rs(n,t){if(t==null)return!1;for(const e of n)if(t[e])return e;return!1}const zt=()=>{const n=Re(),t=Re(),e={emit:n.emit,on:r=>t.on(r)},s={emit:t.emit,on:r=>n.on(r)};return[e,s]},is=()=>{const n=Re();return{emit:s=>{n.emit(s)},on:s=>{n.on(s)}}};class Gt{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 Ut{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=nt(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=Ft(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 Qe(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 os{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 tn{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 Bi(){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 Di(){const n=Bi();if(n.__xstate__)return n.__xstate__}const Ki=n=>{if(typeof window>"u")return;const t=Di();t&&t.register(n)};class vn{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 as=".",Li="",cs="",zi="#",ji="*",ls="xstate.init",Me="xstate.stop";function Fi(n,t){return{type:`xstate.after.${n}.${t}`}}function $e(n,t){return{type:`xstate.done.state.${n}`,output:t}}function Gi(n,t){return{type:`xstate.done.actor.${n}`,output:t,actorId:n}}function Ui(n,t){return{type:`xstate.error.actor.${n}`,error:t,actorId:n}}function us(n){return{type:ls,input:n}}function J(n){setTimeout(()=>{throw n})}const Zi=typeof Symbol=="function"&&Symbol.observable||"@@observable";function hs(n,t){const e=Tn(n),s=Tn(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?hs(e[r],s[r]):!1)}function en(n){if(fs(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 Tn(n){if(Oo(n))return n.value;if(typeof n!="string")return n;const t=en(n);return Vi(t)}function Vi(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 In(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 ds(n){return fs(n)?n:[n]}function tt(n){return n===void 0?[]:ds(n)}function Pe(n,t,e,s){return typeof n=="function"?n({context:t,event:e,self:s}):n}function fs(n){return Array.isArray(n)}function Ji(n){return n.type.startsWith("xstate.error.actor")}function St(n){return ds(n).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function ps(n){if(!(n===void 0||n===Li))return tt(n)}function He(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 On(n,t){return`${t}.${n}`}function nn(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 kn(n,t){return`${n.sessionId}.${t}`}let Xi=0;function Yi(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=kn(d,E);h._snapshot._scheduledEvents[O]=N;const R=a.setTimeout(()=>{delete o[O],delete h._snapshot._scheduledEvents[O],h._relay(d,g,f)},m);o[O]=R},cancel:(d,g)=>{const f=kn(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:${Xi++}`,_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=He(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 _e=!1;const sn=1;let P=function(n){return n[n.NotStarted=0]="NotStarted",n[n.Running=1]="Running",n[n.Stopped=2]="Stopped",n}({});const qi={clock:{setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:n=>clearTimeout(n)},logger:console.log.bind(console),devTools:!1};class Qi{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 vn(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={...qi,...e},{clock:r,logger:i,parent:o,syncSnapshot:a,id:c,systemId:l,inspect:u}=s;this.system=o?o.system:Yi(this,{clock:r,logger:i}),u&&!o&&this.system.inspect(He(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=_e;try{_e=!0,h.exec(h.info,h.params)}finally{_e=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){J(a)}break;case"done":for(const o of this.observers)try{(i=o.next)==null||i.call(o,t)}catch(a){J(a)}this._stopProcedure(),this._complete(),this._doneEvent=Gi(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=He(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){J(o)}break;case"error":{const o=this._snapshot.error;if(!r.error)J(o);else try{r.error(o)}catch(a){J(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=us(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===Me&&(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:Me}),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){J(s)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||J(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){J(i)}}this.observers.clear(),e&&J(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Ui(this.id,t))}_stopProcedure(){return this._processingStatus!==P.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new vn(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:Ki)(this)}toJSON(){return{xstate$$type:sn,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[Zi](){return this}getSnapshot(){return this._snapshot}}function $t(n,...[t]){return new Qi(n,t)}function to(n,t,e,s,{sendId:r}){const i=typeof r=="function"?r(e,s):r;return[t,{sendId:i},void 0]}function eo(n,t){n.defer(()=>{n.system.scheduler.cancel(n.self,t.sendId)})}function no(n){function t(e,s){}return t.type="xstate.cancel",t.sendId=n,t.resolve=to,t.execute=eo,t}function so(n,t,e,s,{id:r,systemId:i,src:o,input:a,syncSnapshot:c}){const l=typeof o=="string"?nn(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=$t(l,{id:u,src:o,parent:n.self,syncSnapshot:c,systemId:i,input:d})),[mt(t,{children:{...t.children,[u]:h}}),{id:r,systemId:i,actorRef:h,src:o,input:d},void 0]}function ro(n,{actorRef:t}){t&&n.defer(()=>{t._processingStatus!==P.Stopped&&t.start()})}function io(...[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=so,i.execute=ro,i}function oo(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]),[mt(t,{children:a}),o,void 0]}function ao(n,t){if(t){if(n.system._unregister(t),t._processingStatus!==P.Running){n.stopChild(t);return}n.defer(()=>{n.stopChild(t)})}}function gs(n){function t(e,s){}return t.type="xstate.stopChild",t.actorRef=n,t.resolve=oo,t.execute=ao,t}function rn(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 rn(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 on=n=>n.type==="atomic"||n.type==="final";function Pt(n){return Object.values(n.states).filter(t=>t.type!=="history")}function Xt(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 ae(n){const t=new Set(n),e=ms(t);for(const s of t)if(s.type==="compound"&&(!e.get(s)||!e.get(s).length))Cn(s).forEach(r=>t.add(r));else if(s.type==="parallel"){for(const r of Pt(s))if(r.type!=="history"&&!t.has(r)){const i=Cn(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 ys(n,t){const e=t.get(n);if(!e)return{};if(n.type==="compound"){const r=e[0];if(r){if(on(r))return r.key}else return{}}const s={};for(const r of e)s[r.key]=ys(r,t);return s}function ms(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 ws(n,t){const e=ae(t);return ys(n,ms(e))}function an(n,t){return t.type==="compound"?Pt(t).some(e=>e.type==="final"&&n.has(e)):t.type==="parallel"?Pt(t).every(e=>an(n,e)):t.type==="final"}const pe=n=>n[0]===zi;function co(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 lo(n){const t=n.config.after;if(!t)return[];const e=r=>{const i=Fi(r,n.id),o=i.type;return n.entry.push(Wo(i,{id:o,delay:r})),n.exit.push(no(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 tt(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=ps(e.target),r=e.reenter??!1,i=fo(n,s),o={...e,actions:tt(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 uo(n){const t=new Map;if(n.config.on)for(const e of Object.keys(n.config.on)){if(e===cs)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=n.config.on[e];t.set(e,St(s).map(r=>dt(n,e,r)))}if(n.config.onDone){const e=`xstate.done.state.${n.id}`;t.set(e,St(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,St(e.onDone).map(r=>dt(n,s,r)))}if(e.onError){const s=`xstate.error.actor.${e.id}`;t.set(s,St(e.onError).map(r=>dt(n,s,r)))}if(e.onSnapshot){const s=`xstate.snapshot.${e.id}`;t.set(s,St(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 ho(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"?[]:tt(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...s,source:`#${n.id}`,target:e?[`#${e.id}`]:[]})};return s}function fo(n,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(pe(e))return n.machine.getStateNodeById(e);const s=e[0]===as;if(s&&!n.parent)return ce(n,e.slice(1));const r=s?n.key+e:e;if(n.parent)try{return ce(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 bs(n){const t=ps(n.config.target);return t?{target:t.map(e=>typeof e=="string"?ce(n.parent,e):e)}:n.parent.initial}function pt(n){return n.type==="history"}function Cn(n){const t=_s(n);for(const e of t)for(const s of Xt(e,n))t.add(s);return t}function _s(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 Pt(s))e(r)}}return e(n),t}function Ht(n,t){if(pe(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 ce(n,t){if(typeof t=="string"&&pe(t))try{return n.machine.getStateNodeById(t)}catch{}const e=en(t).slice();let s=n;for(;e.length;){const r=e.shift();if(!r.length)break;s=Ht(s,r)}return s}function le(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=>Ht(n,r)).filter(Boolean);return[n.machine.root,n].concat(s,e.reduce((r,i)=>{const o=Ht(n,i);if(!o)return r;const a=le(o,t[i]);return r.concat(a)},[]))}function po(n,t,e,s){const i=Ht(n,t).next(e,s);return!i||!i.length?n.next(e,s):i}function go(n,t,e,s){const r=Object.keys(t),i=Ht(n,r[0]),o=cn(i,t[r[0]],e,s);return!o||!o.length?n.next(e,s):o}function yo(n,t,e,s){const r=[];for(const i of Object.keys(t)){const o=t[i];if(!o)continue;const a=Ht(n,i),c=cn(a,o,e,s);c&&r.push(...c)}return r.length?r:n.next(e,s)}function cn(n,t,e,s){return typeof t=="string"?po(n,t,e,s):Object.keys(t).length===1?go(n,t,e,s):yo(n,t,e,s)}function mo(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 wo(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 As(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(wo(We([r],t,e),We([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 bo(n){const[t,...e]=n;for(const s of Xt(t,void 0))if(e.every(r=>rt(r,s)))return s}function ln(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 ln(bs(s),t))e.add(r);else e.add(s);return[...e]}function Es(n,t){const e=ln(n,t);if(!e)return;if(!n.reenter&&e.every(r=>r===n.source||rt(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 We(n,t,e){var r;const s=new Set;for(const i of n)if((r=i.target)!=null&&r.length){const o=Es(i,e);i.reenter&&i.source===o&&s.add(o);for(const a of t)rt(a,o)&&s.add(a)}return[...s]}function _o(n,t){if(n.length!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function Be(n,t,e,s,r,i){if(!n.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=As(n,o,a);let l=t;r||([l,a]=So(l,s,e,c,o,a,i,e.actionExecutor)),l=Wt(l,s,e,c.flatMap(h=>h.actions),i,void 0),l=Eo(l,s,e,c,o,i,a,r);const u=[...o];l.status==="done"&&(l=Wt(l,s,e,u.sort((h,d)=>d.order-h.order).flatMap(h=>h.exit),i,void 0));try{return a===t.historyValue&&_o(t._nodes,o)?l:mt(l,{_nodes:u,historyValue:a})}catch(h){throw h}}function Ao(n,t,e,s,r){if(s.output===void 0)return;const i=$e(r.id,r.output!==void 0&&r.parent?Pe(r.output,n.context,t,e.self):void 0);return Pe(s.output,n.context,i,e.self)}function Eo(n,t,e,s,r,i,o,a){let c=n;const l=new Set,u=new Set;No(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(io(f.src,{...f,syncSnapshot:!!f.onSnapshot}));if(u.has(d)){const f=d.initial.actions;g.push(...f)}if(c=Wt(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($e(f.id,d.output!==void 0?Pe(d.output,c.context,t,e.self):void 0));(m==null?void 0:m.type)==="parallel"&&!h.has(m)&&an(r,m);)h.add(m),i.push($e(m.id)),E=m,m=m.parent;if(m)continue;c=mt(c,{status:"done",output:Ao(c,t,e,c.machine.root,E)})}}return c}function No(n,t,e,s){for(const r of n){const i=Es(r,t);for(const a of r.target||[])!pt(a)&&(r.source!==a||r.source!==i||r.reenter)&&(s.add(a),e.add(a)),Tt(a,t,e,s);const o=ln(r,t);for(const a of o){const c=Xt(a,i);(i==null?void 0:i.type)==="parallel"&&c.push(i),Ns(s,t,e,c,!r.source.parent&&r.reenter?void 0:i)}}}function Tt(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),Tt(o,t,e,s);for(const o of i)Ae(o,n.parent,s,t,e)}else{const i=bs(n);for(const o of i.target)s.add(o),i===((r=n.parent)==null?void 0:r.initial)&&e.add(n.parent),Tt(o,t,e,s);for(const o of i.target)Ae(o,n.parent,s,t,e)}else if(n.type==="compound"){const[i]=n.initial.target;pt(i)||(s.add(i),e.add(i)),Tt(i,t,e,s),Ae(i,n,s,t,e)}else if(n.type==="parallel")for(const i of Pt(n).filter(o=>!pt(o)))[...s].some(o=>rt(o,i))||(pt(i)||(s.add(i),e.add(i)),Tt(i,t,e,s))}function Ns(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 Pt(i).filter(a=>!pt(a)))[...n].some(a=>rt(a,o))||(n.add(o),Tt(o,t,e,n))}function Ae(n,t,e,s,r){Ns(e,s,r,Xt(n,t))}function So(n,t,e,s,r,i,o,a){let c=n;const l=We(s,r,i);l.sort((h,d)=>d.order-h.order);let u;for(const h of l)for(const d of mo(h)){let g;d.history==="deep"?g=f=>on(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=Wt(c,t,e,[...h.exit,...h.invoke.map(d=>gs(d.id))],o,void 0),r.delete(h);return[c,u||i]}function vo(n,t){return n.implementations.actions[t]}function Ss(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:vo(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=Ss(a,t,e,E,r,i))}return a}function Wt(n,t,e,s,r,i){const o=i?[]:void 0,a=Ss(n,t,e,s,{internalQueue:r,deferredActorIds:i},o);return o==null||o.forEach(([c,l])=>{c.retryResolve(e,a,l)}),a}function Ee(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===Me)return r=mt(xn(r,t,e),{status:"stopped"}),o(r,t,[]),{snapshot:r,microstates:i};let a=t;if(a.type!==ls){const l=a,u=Ji(l),h=Rn(l,r);if(u&&!h.length)return r=mt(n,{status:"error",error:l.error}),o(r,l,[]),{snapshot:r,microstates:i};r=Be(h,n,e,a,!1,s),o(r,l,h)}let c=!0;for(;r.status==="active";){let l=c?To(r,a):[];const u=l.length?r:void 0;if(!l.length){if(!s.length)break;a=s.shift(),l=Rn(a,r)}r=Be(l,r,e,a,!1,s),c=r!==u,o(r,a,l)}return r.status!=="active"&&xn(r,a,e),{snapshot:r,microstates:i}}function xn(n,t,e){return Wt(n,t,e,Object.values(n.children).map(s=>gs(s)),[],void 0)}function Rn(n,t){return t.machine.getTransitionData(t,n)}function To(n,t){const e=new Set,s=n._nodes.filter(on);for(const r of s)t:for(const i of[r].concat(Xt(r,void 0)))if(i.always){for(const o of i.always)if(o.guard===void 0||rn(o.guard,n.context,t,n)){e.add(o);break t}}return As(Array.from(e),new Set(n._nodes),n.historyValue)}function Io(n,t){const e=ae(le(n,t));return ws(n,[...e])}function Oo(n){return!!n&&typeof n=="object"&&"machine"in n&&"value"in n}const ko=function(t){return hs(t,this.value)},Co=function(t){return this.tags.has(t)},xo=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(s=>s.target!==void 0||s.actions.length)},Ro=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)}},Mo=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function ne(n,t){return{status:n.status,output:n.output,error:n.error,machine:t,context:n.context,_nodes:n._nodes,value:ws(t.root,n._nodes),tags:new Set(n._nodes.flatMap(e=>e.tags)),children:n.children,historyValue:n.historyValue||{},matches:ko,hasTag:Co,can:xo,getMeta:Mo,toJSON:Ro}}function mt(n,t={}){return ne({...n,...t},n.machine)}function $o(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:vs(o),children:g}}function vs(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:sn,id:s.id};else{const r=vs(s);r!==s&&(t??(t=Array.isArray(n)?n.slice():{...n}),t[e]=r)}}return t??n}function Po(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 Ho(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 Wo(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=Po,e.execute=Ho,e}function Bo(n,{machine:t,context:e},s,r){const i=(o,a)=>{if(typeof o=="string"){const c=nn(t,o);if(!c)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const l=$t(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 $t(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 Do(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:Bo(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[mt(t,{context:c,children:Object.keys(i).length?{...t.children,...i}:t.children}),void 0,void 0]}function Ko(n){function t(e,s){}return t.type="xstate.assign",t.assignment=n,t.resolve=Do,t}const Mn=new WeakMap;function Nt(n,t,e){let s=Mn.get(n);return s?t in s||(s[t]=e()):(s={[t]:e()},Mn.set(n,s)),s[t]}const Lo={},Kt=n=>typeof n=="string"?{type:n}:typeof n=="function"?"resolve"in n?{type:n.type}:{type:n.name}:n;class un{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(as),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?In(this.config.states,(s,r)=>new un(s,{_parent:this,_key:r,_machine:this.machine})):Lo,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=tt(this.config.entry).slice(),this.exit=tt(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=tt(t.tags).slice()}_initialize(){this.transitions=uo(this),this.config.always&&(this.always=St(this.config.always).map(t=>dt(this,cs,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(Kt),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Kt),eventType:null})}:void 0,history:this.history,states:In(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Kt)})),entry:this.entry.map(Kt),exit:this.exit.map(Kt),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 Nt(this,"invoke",()=>tt(this.config.invoke).map((t,e)=>{const{src:s,systemId:r}=t,i=t.id??On(this.id,e),o=typeof s=="string"?s:`xstate.invoke.${On(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 Nt(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 Nt(this,"delayedTransitions",()=>lo(this))}get initial(){return Nt(this,"initial",()=>ho(this,this.config.initial))}next(t,e){const s=e.type,r=[];let i;const o=Nt(this,`candidates-${s}`,()=>co(this,s));for(const a of o){const{guard:c}=a,l=t.context;let u=!1;try{u=!c||rn(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 Nt(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 zo="#";class hn{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 un(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 hn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...r,...t.actors},delays:{...i,...t.delays}})}resolveState(t){const e=Io(this.root,t.value),s=ae(le(this.root,e));return ne({_nodes:[...s],context:t.context||{},children:{},status:an(s,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ee(t,e,s,[]).snapshot}microstep(t,e,s){return Ee(t,e,s,[]).microstates}getTransitionData(t,e){return cn(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:r}=this.config,i=ne({context:typeof r!="function"&&r?r:{},_nodes:[this.root],children:{},status:"active"},this);return typeof r=="function"?Wt(i,e,t,[Ko(({spawn:a,event:c,self:l})=>r({spawn:a,input:c.input,self:l}))],s,void 0):i}getInitialSnapshot(t,e){const s=us(e),r=[],i=this.getPreInitialState(t,s,r),o=Be([{target:[..._s(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],i,t,s,!0,r),{snapshot:a}=Ee(o,s,t,r);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=en(t),s=e.slice(1),r=pe(e[0])?e[0].slice(zo.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 ce(i,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return $o(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"?nn(this,h):h;if(!d)return;const g=$t(d,{id:c,parent:e.self,syncSnapshot:l.syncSnapshot,snapshot:u,src:h,systemId:l.systemId});s[c]=g});const i=ne({...t,children:s,_nodes:Array.from(ae(le(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===sn){c[u]=l[h.id];continue}a(h,l)}}}}return a(i.context,s),i}}function jo(n,t){return new hn(n,t)}const te=n=>n===!1?!1:n.map(t=>t.serialize()),Fo=n=>n===!1?!1:n.serialize(),Go=n=>n===!1?!1:n.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),De=n=>JSON.parse(JSON.stringify(n)),ee=n=>n===!1?!1:De(n),Ke=n=>jo({id:"Untitled",initial:"distribute",context:{currentWind:A.E,oneShotMap:$(!1),missingMap:$(!1),controller:n,genEventID:Ts()},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:`可能なアクションとその詳細を通知\\
|
|
10
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:`可能なアクションとその詳細を通知\\
|
|
11
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 に対するレスポンスを待つ\\
|
|
12
18
|
ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
|
|
13
|
-
通知する 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 n=t.currentWind;t.currentWind=kt(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(const r of Object.values(v)){const o=Z("_____________");o[r]=i[r].toString();const a={id:n,type:"DISTRIBUTE",hands:o,wind:r,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},n)=>{const i=t.currentWind,r=t.controller.hand(i).drawn,o=t.genEventID(),a={id:o,type:"CHOICE_AFTER_DRAWN",wind:i,drawerInfo:{wind:i,tile:r.toString()},choices:{TSUMO:Ue(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n==null?void 0:n.replacementWin})),REACH:dh(t.controller.doReach(i)),AN_KAN:Le(t.controller.doAnKan(i)),SHO_KAN:Le(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_ORPHANS:t.controller.canDrawnGame(i)}};t.controller.emit(a),t.controller.pollReplies(o,[i])},notify_choice_after_discarded:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:y.HORIZONTAL});for(const o of Object.values(v)){const a={id:n,type:"CHOICE_AFTER_DISCARDED",wind:o,discarterInfo:{wind:i.w,tile:i.t.toString()},choices:{RON:Ue(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:Le(t.controller.doPon(o,i.w,r)),CHI:Le(t.controller.doChi(o,i.w,r)),DAI_KAN:fh(t.controller.doDaiKan(o,i.w,r))}};a.choices.RON&&(t.missingMap[o]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(v))},notify_choice_after_called:({context:t,event:e},n)=>{const i=t.genEventID(),r=t.currentWind;let o=t.controller.doDiscard(r);const a=t.controller.hand(t.currentWind).called.at(-1);(a instanceof dt||a instanceof _t)&&(o=t.controller.doDiscard(r,a));const c={id:i,type:"CHOICE_AFTER_CALLED",wind:r,choices:{DISCARD:o.map(h=>h.toString())}};t.controller.emit(c),t.controller.pollReplies(i,[r])},notify_choice_for_reach_acceptance:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.river.lastTile,r=i.t.clone({add:y.HORIZONTAL});for(const o of Object.values(v)){const a={id:n,type:"CHOICE_FOR_REACH_ACCEPTANCE",wind:o,reacherInfo:{wind:i.w,tile:r.toString()},choices:{RON:Ue(t.controller.doWin(o,r,{discardedBy:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]}))}};t.controller.emit(a)}t.controller.pollReplies(n,Object.values(v))},notify_choice_for_chankan:({context:t,event:e})=>{O(e.type=="SHO_KAN"||e.type=="AN_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:y.HORIZONTAL});for(const r of Object.values(v)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:y.HORIZONTAL}),{discardedBy:e.iam,quadWin:!0,oneShot:t.oneShotMap[r],missingRon:t.missingMap[e.iam]}),a={id:n,type:"CHOICE_FOR_CHAN_KAN",wind:r,callerInfo:{wind:e.iam,tile:i.toString()},choices:{RON:e.type=="SHO_KAN"?Ue(o):!1}};a.choices.RON&&(t.missingMap[r]=!0),t.controller.emit(a)}t.controller.pollReplies(n,Object.values(v))},notify_call:({context:t,event:e})=>{O(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam;t.currentWind=i;for(const r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,block:e.block.serialize()};t.controller.emit(o)}t.controller.next()},notify_discard:({context:t,event:e})=>{O(e.type=="DISCARD",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(const o of Object.values(v)){const a={id:n,type:"DISCARD",iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}t.controller.next()},notify_draw:({context:t,event:e},n)=>{const i=t.genEventID(),r=n==null?void 0:n.action;let o;r=="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(v)){let h=new w(p.BACK,0,[y.TSUMO]);c==a&&(h=o);const l={id:i,type:"DRAW",subType:r,iam:a,wind:c,tile:h.toString()};t.controller.emit(l)}t.controller.next()},notify_ron:({context:t,event:e})=>{O(e.type=="RON");const n=t.genEventID(),i=e.iam;for(const r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:qn(e.ret)};t.controller.emit(o)}},notify_tsumo:({context:t,event:e})=>{O(e.type=="TSUMO",`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(const r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:qn(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{O(e.type=="REACH",`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:y.HORIZONTAL});t.oneShotMap[i]=!0;for(const o of Object.values(v)){const a={id:n,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},notify_reach_accepted:({context:t,event:e})=>{O(e.type=="REACH_ACCEPT");const n=t.genEventID();for(const i of Object.values(v)){const r={id:n,type:"REACH_ACCEPTED",reacherInfo:{wind:e.reacherInfo.wind,tile:e.reacherInfo.tile.toString()},wind:i};t.controller.emit(r)}t.controller.next()},notify_new_dora_if_needed:({context:t,event:e})=>{const n=t.genEventID();if(e.type=="AN_KAN"){const i=t.controller.wall.openDoraMarker();for(const r of Object.values(v)){const o={id:n,type:"NEW_DORA",wind:r,doraMarker:i.toString()};t.controller.emit(o)}}e.type=="SHO_KAN"},disable_one_shot:({context:t,event:e})=>{for(const n of Object.values(v))t.oneShotMap[n]=!1},disable_one_shot_for_me:({context:t,event:e})=>{t.oneShotMap[t.currentWind]=!1},notify_end:({context:t,event:e})=>{const n=t.genEventID(),i=Z("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(const r of Object.values(v)){const o={id:n,type:"END_GAME",subType:"NINE_TILES",wind:r,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:Z(0),hands:i};t.controller.emit(o)}}else if(e.type=="RON"||e.type=="TSUMO"){const r=e.iam==v.E,o=t.controller.finalResult(e.ret,e.iam);for(const a of Object.values(v)){i[e.iam]=t.controller.hand(e.iam).toString();const c={id:n,type:"END_GAME",subType:"WIN_GAME",wind:a,shouldContinue:r,sticks:{reach:0,dead:0},scores:t.controller.scoreManager.summary,deltas:o.deltas,hands:i};t.controller.emit(c)}}else if(!t.controller.wall.canKan||t.controller.river.cannotContinue()){const r=t.controller.wall.canKan?"FOUR_WIND":"FOUR_KAN";for(const o of Object.values(v)){const a={id:n,type:"END_GAME",subType:r,wind:o,shouldContinue:!0,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:Z(0),hands:Z("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(const h of Object.values(v)){const l=t.controller.hand(h);new We(l).calc()==0&&(r.push(h),i[h]=l.toString())}const o=r.length==0||r.length==4,a=Z(0);for(const h of Object.values(v))r.includes(h)?a[h]+=o?0:3e3/r.length:a[h]-=o?0:3e3/(4-r.length);const c=r.length==4||a[v.E]>0;for(const h of Object.values(v)){const l={id:n,type:"END_GAME",subType:"DRAWN_GAME",wind:h,shouldContinue:c,sticks:t.controller.placeManager.sticks,scores:t.controller.scoreManager.summary,deltas:a,hands:i};t.controller.emit(l)}}}}},actors:{},guards:{canChi:({context:t,event:e},n)=>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},n)=>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},n)=>e.type=="TSUMO"||e.type=="RON"?!0:(console.error(`guards.canWin receive ${e.type}`),!1),canReach:({context:t,event:e},n)=>e.type=="REACH"?!!t.controller.doReach(e.iam):(console.error(`guards.canReach receive ${e.type}`),!1),cannotContinue:({context:t,event:e},n)=>!t.controller.wall.canDraw||!t.controller.wall.canKan||t.controller.river.cannotContinue()},delays:{}});function cr(s=0){let t=s;return()=>(t++).toString()}class Wt{constructor(t){A(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});A(this,"backup");A(this,"openedDoraCount",1);this.init(t),this.backup=Wt.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=Z("");for(let e=0;e<3;e++)for(const n of Object.values(v))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(const e of Object.values(v))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Wt.clone(t);return}else{for(let e of Object.values(p)){if(e==p.BACK)continue;const n=e==p.Z?[1,2,3,4,5,6,7]:[1,2,3,4,5,6,7,8,9];for(let i=0;i<4;i++)for(let r of n){let o=new w(e,r);e!=p.Z&&i==3&&r==5&&(o=o.clone({add:y.RED})),this.walls.drawable.push(o.toString())}}gs(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 je{constructor(t,e){A(this,"wall",new Wt);A(this,"playerIDs");A(this,"actor",ce(Gn(this),{}));A(this,"observer");A(this,"handlers",{});A(this,"mailBox",{});A(this,"histories",[]);A(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 n=zi();this.observer=new hr(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new ke(i);const r=(e==null?void 0:e.shuffle)==!1?this.playerIDs:gs([...this.playerIDs]);this.observer.placeManager=new Te({[r[0]]:v.E,[r[1]]:v.S,[r[2]]:v.W,[r[3]]:v.N})}boardParams(t){let n=this.hand(t).reached?1:void 0;if(n){const i=this.river.discards(t);n=i.length==0||i.length==1&&i[0].t.has(y.HORIZONTAL)?2:1}return{doraMarkers:this.observer.doraMarkers,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:n}}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 n=t.iam;t.wind==n?this.observer.eventHandler.emit(t):n==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 n=this.mailBox[t];if(n==null)throw new Error(`not enqueued ${t} at ${this.actor.getSnapshot().value}`);if(n.length!=e.length)throw new Error(`${t}: num of event: got: ${e.length}, want: ${n.length}`);if(e.length==0){console.warn("no events to handle");return}const i=n[0];if(i.type=="CHOICE_AFTER_DISCARDED"){const r=Bi(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":O(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:we(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:w.from(o.discarterInfo.tile)}});break;case"DAI_KAN":O(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:wt.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];O(a,`${r.type} choice is none`),O(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=B.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=Wi(n);O(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const o=r.events[0],a=o.wind;switch(r.type){case"TSUMO":O(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:we(o.choices.TSUMO),lastTile:w.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];O(c,`${r.type} candidates is none`),this.actor.send({type:"REACH",tile:w.from(c[0].tile),iam:a});break;case"DISCARD":const h=o.choices[r.type];O(h,`${r.type} choice is none`),this.actor.send({type:r.type,tile:w.from(h[0]).clone({remove:y.TSUMO}),iam:a});break;case"AN_KAN":{const l=o.choices[r.type];O(l,`${r.type} choice is none`),this.actor.send({type:r.type,block:U.from(l[0].tiles),iam:a});break}case"SHO_KAN":{const l=o.choices[r.type];O(l,`${r.type} choice is none`),this.actor.send({type:r.type,block:ct.from(l[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(i.type=="CHOICE_AFTER_CALLED"){O(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=w.from(i.choices.DISCARD[0]);this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_REACH_ACCEPTANCE"){const r=n.filter(a=>(O(a.type=="CHOICE_FOR_REACH_ACCEPTANCE"),a.choices.RON!==!1));if(r.length==0){this.actor.send({type:"REACH_ACCEPT",reacherInfo:{tile:w.from(i.reacherInfo.tile),wind:i.reacherInfo.wind}});return}const o=r[0];this.actor.send({type:"RON",iam:o.wind,ret:we(o.choices.RON),targetInfo:{wind:o.reacherInfo.wind,tile:w.from(o.reacherInfo.tile)}});return}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=n.filter(a=>a.choices.RON!==!1);if(r.length==0){this.actor.send({type:""});return}const o=r[0];O(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:we(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:w.from(o.callerInfo.tile)}});return}else console.warn(`controller found unexpected event: ${i.type}`)}export(){return this.histories.concat()}static load(t){const e=t.choiceEvents,n=Object.keys(t.players),i={emit:a=>{},on:a=>{}},r=n.map(a=>({id:a,handler:i})),o=new je(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Te(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new ke(t.scores),o.wall=new Wt(t.wall),o}start(){this.actor.subscribe(n=>{console.debug("State:",n.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 Wt,this.observer.applied={},this.mailBox={},this.actor=ce(Gn(this)),!this.placeManager.is(j.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.blindDoraMarkers:void 0,r=new Wn(n,{...t.boardContext,sticks:this.placeManager.sticks,blindDoraMarkers:i}).calc(t.hand);return O(r),r}doWin(t,e,n){if(e==null)return!1;let i=this.hand(t);const r=this.boardParams(t);if(i.drawn==null){if(n==null)throw new Error("should ron but params == null");if(n.discardedBy==t||n.missingRon)return!1;i=i.clone(),r.ronWind=n.discardedBy,r.finalDiscardWin=!this.wall.canDraw,r.quadWin=n.quadWin,i.inc([e])}else r.finalWallWin=!this.wall.canDraw,r.replacementWin=n==null?void 0:n.replacementWin;r.oneShotWin=n==null?void 0:n.oneShot;const o=new Hi(i),a=new Wn(i,r),c=o.calc(e),h=a.calc(...c);if(!h||h.points.length==0)return!1;if(i.draw==null){const l=ae.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).some(u=>l.some(f=>f.equals(u.t))))return!1}return h}doPon(t,e,n){if(n==null||t==e)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3||i.get(n.t,n.n)<2)return!1;const r=n.clone({removeAll:!0}),o=An(t,e,b.PON),a=[],c=new _t([r,r,r]).clone({replace:{idx:o,tile:n.clone({add:y.HORIZONTAL})}});let h=c;z(n)&&n.has(y.RED)&&(h=c.clone({replace:{idx:o,tile:r.clone({add:[y.RED,y.HORIZONTAL]})}}));const l=o%2+1;if(z(n)&&i.get(n.t,0)>0&&(h=c.clone({replace:{idx:l,tile:r.clone({add:y.RED})}})),a.push(h),z(r)&&i.get(r.t,5)==3){const u=c.clone({replace:{idx:l,tile:r}});a.push(u)}return a}doChi(t,e,n){if(n==null||!n.isNum()||kt(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;const r=n.clone({remove:y.TSUMO,add:[y.HORIZONTAL]}),o=[];r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0&&o.push(new dt([r,new w(n.t,r.n-1),new w(n.t,r.n-2)])),r.n+2<=9&&i.get(n.t,r.n+1)>0&&i.get(n.t,r.n+2)>0&&o.push(new dt([r,new w(n.t,r.n+1),new w(n.t,r.n+2)])),r.n-1>=1&&r.n+1<=9&&i.get(n.t,r.n-1)>0&&i.get(n.t,r.n+1)>0&&o.push(new dt([r,new w(n.t,r.n-1),new w(n.t,r.n+1)]));for(let f=0;f<o.length;f++){const m=o[f],d=this.cannotDiscardTile(m),g=[];for(const D of d){const R=i.get(D.t,D.n);for(let q=0;q<R;q++)g.push(D.clone({remove:y.RED}))}const _=i.dec([...g,m.tiles[1],m.tiles[2]]),S=i.hands.length==0;i.inc(_),S&&o.splice(f,1)}if(o.length==0)return!1;const u=i.get(n.t,0)>0?this.redPattern(o):[];return u.length>0&&i.get(n.t,5)==1?u:[...o,...u]}redPattern(t){return t.length==0?[]:t.filter(n=>z(n.tiles[1])||z(n.tiles[2])).map(n=>{if(z(n.tiles[1])){const i=n.tiles[1].clone({add:y.RED});return n.clone({replace:{idx:1,tile:i}})}else if(z(n.tiles[2])){const i=n.tiles[2].clone({add:y.RED});return n.clone({replace:{idx:2,tile:i}})}}).filter(n=>n!=null)}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new We(e).calc()>0?!1:ae.calcCandidates(e,e.hands)}doDiscard(t,e){if(this.hand(t).reached)return[this.hand(t).drawn];const n=this.hand(t).hands;if(e==null)return n;if(e instanceof _t)return n.filter(o=>!o.equals(e.tiles[0]));const i=this.cannotDiscardTile(e),r=n.filter(o=>!i.some(a=>o.equals(a)));return O(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){const e=t.tiles[0],n=t.tiles[1].n;return n!=1&&e.n-2==n?[new w(e.t,e.n-3),e]:n!=8&&e.n+1==n?[new w(e.t,e.n+3),e]:[e]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(const[i,r]of rt())if(e.get(i,r)==4){const o=new w(i,r),a=[o,o,o,o];z(o)&&(a[1]=o.clone({add:y.RED})),n.push(new U(a))}if(n.length==0)return!1;for(const i of n)O(i.tiles.filter(r=>r.has(y.HORIZONTAL)).length==0,`h op ${i.toString()}`);return n}doShoKan(t){const e=this.hand(t);if(e.reached)return!1;const n=e.called.filter(r=>r instanceof _t);if(n.length==0)return!1;const i=[];for(const r of n){const o=r.tiles[0].clone({removeAll:!0,add:y.HORIZONTAL});if(e.get(o.t,o.n)==1){const a=z(o)&&e.get(o.t,0)>0?o.clone({add:y.RED}):o;i.push(new ct([...r.tiles,a]))}}if(i.length==0)return!1;for(const r of i)O(r.tiles.filter(o=>o.has(y.HORIZONTAL)).length==2,`h op ${r.toString()}`);return i}doDaiKan(t,e,n){const i=this.hand(t);if(i.reached||t==e)return!1;const r=n.clone({removeAll:!0});if(i.get(r.t,r.n)!=3)return!1;const o=An(t,e,b.DAI_KAN);let a=new wt([r,r,r,r]).clone({replace:{idx:o,tile:r.clone({add:y.HORIZONTAL})}});if(z(n)&&n.has(y.RED))a=a.clone({replace:{idx:o,tile:r.clone({add:[y.HORIZONTAL,y.RED]})}});else if(z(n)&&!n.has(y.RED)){O(i.get(n.t,0)>0,`hand does not have red tile: ${i.toString()}`);const c=o%3+1;a=a.clone({replace:{idx:c,tile:r.clone({add:y.RED})}})}return O(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 n=0;for(const i of Object.values(p)){if(i==p.BACK)continue;const r=i==p.Z?oe:ft;for(const o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class Lt extends cn{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 Lt(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 Os{constructor(t,e){A(this,"id");A(this,"river",new ys);A(this,"placeManager",new Te({}));A(this,"scoreManager",new ke({}));A(this,"hands",Z(new Lt("")));A(this,"counter",new Ki);A(this,"doraMarkers",[]);A(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 Te(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new ke(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(const i of Object.values(v))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=w.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(v))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=B.deserialize(t.block);this.hands[t.iam].call(i),this.river.markCalled(),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(y.HORIZONTAL)));break}case"SHO_KAN":{const i=ct.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(y.HORIZONTAL))[0]);break}case"AN_KAN":{const i=U.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(...i.tiles.filter(r=>!r.has(y.HORIZONTAL)));break}case"REACH":{this.hands[t.iam].reach();const i=w.from(t.tile);if(this.river.discard(i,t.iam),this.hands[t.iam].discard(i),t.iam!=t.wind){this.counter.dec(i),this.counter.addTileToSafeMap(i,t.iam);for(const r of Object.values(v))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"REACH_ACCEPTED":const n=this.placeManager.playerID(t.reacherInfo.wind);this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=w.from(t.doraMarker);this.doraMarkers.push(i),this.counter.dec(i);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 i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),this.placeManager.incrementDeadStick(),t.shouldContinue||this.placeManager.nextRound();break}case"WIN_GAME":{const i=this.placeManager.playerMap;this.scoreManager.update(t.deltas,i),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 hr extends Os{constructor(e){super("observer",e);A(this,"applied",{});this.counter.disable=!0,this.hands=Z(new Lt("_____________"))}setHands(e){this.hands[e.wind]=new Lt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let n=!0;for(const i of Object.values(v))n&&(n=this.hand(i).get(p.BACK,0)==0);if(!n)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 i of Object.values(v))console.debug(`${this.placeManager.playerID(i)}(${i})`,`init hand: ${this.hand(i).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 i of Object.values(v))console.debug(`${this.placeManager.playerID(i)}(${Qn(i)})`,`end hand: ${this.hand(i).toString()}`);console.debug("END_GAME",e.subType,"scores",JSON.stringify(this.scoreManager.summary,null,2),`sticks: ${JSON.stringify(this.placeManager.sticks,null,2)}`)}}}class be extends Os{constructor(e,n){super(e,n);A(this,"river",new ys);A(this,"doras",[]);this.eventHandler.on(i=>this.handleEvent(i))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(const n of Object.values(v))this.hands[n]=new Lt(e.hands[n])}handleDiscard(e){const n=Object.values(v).filter(l=>l==this.myWind?!1:this.hand(l).reached),i=new We(this.hand(this.myWind)).calc();if(n.length>0&&i>=2)return te.selectTile(this.counter,n,e);const r=ae.calcCandidates(this.hand(this.myWind),e),a=Oe.calcPlayerCandidates(this.counter,r).sort((l,u)=>u.sum-l.sum),c=a.filter(l=>l.sum==a[0].sum);return Oe.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 n=this.handleDiscard(e.choices.DISCARD.map(w.from));e.choices.DISCARD=[n.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 ph{constructor(t){A(this,"index",0);A(this,"histories",[]);this.histories=JSON.parse(t)}next(){O(this.index<this.histories.length),this.index++}prev(){this.index--,O(this.index<0)}start(){je.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const mh=s=>{const[t,e]=_e(),[n,i]=_e(),[r,o]=_e(),[a,c]=_e(),h=["player-1","player-2","player-3","player-4"],l=s==null?void 0:s.playerInjection,u=(l==null?void 0:l.p1)??be,f=(l==null?void 0:l.p2)??be,m=(l==null?void 0:l.p3)??be,d=(l==null?void 0:l.p4)??be,g=new u(h[0],e),_=new f(h[1],i),S=new m(h[2],o),D=new d(h[3],c),R=[{handler:t,id:h[0]},{handler:n,id:h[1]},{handler:r,id:h[2]},{handler:a,id:h[3]}];return{c:new je(R,{debug:s==null?void 0:s.debug,shuffle:s==null?void 0:s.shuffle}),p1:g,p2:_,p3:S,p4:D}},Ct=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class Oe{static calcPlayerCandidates(t,e){let n=[];for(let i of e){let r=0,o=[];for(let a of i.candidates)o.push({tile:a.clone(),n:t.get(a)}),r+=t.get(a);n.push({sum:r,tile:i.tile,candidates:o,shanten:i.shanten})}return n}static selectMinPriority(t,e,n){O(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=Oe.calcPriority(t,e[o],n);a<i&&(i=a,r=o)}return e[r]}static calcPriority(t,e,n){const i=e.tile;let r=0;if(i.t==p.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*Ct(i,n);{const o=t.get(i);r+=o*Ct(i,n);const a=t.get(new w(i.t,i.n+1)),c=t.get(new w(i.t,i.n+2)),h=t.get(new w(i.t,i.n-1)),l=t.get(new w(i.t,i.n-2)),u=i.n-2>0?Math.min(h,l):0,f=i.n+2<=9?Math.min(a,c):0,m=i.n-1>=1&&i.n+1<=9?Math.min(a,h):0,d=Math.max(u,m),g=Math.max(m,f);return r+=o*Ct(i,n),r+=u*Ct(new w(i.t,i.n-2),n),r+=f*Ct(new w(i.t,i.n+2),n),r+=d*Ct(new w(i.t,i.n-1),n),r+=g*Ct(new w(i.t,i.n+1),n),i.n==0,r}}}class te{static selectTile(t,e,n){O(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=te.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?te.rankN:te.rankZ;for(let o of e){const a=r(t,o,n);i<a&&(i=a)}return i}static rankZ(t,e,n){if(n.t!=p.Z)throw new Error(`expected TYPE.Z but ${n.toString()}`);if(t.isSafeTile(n.t,n.n,e))return 0;const i=t.get(n);return Math.min(i,3)}static rankN(t,e,n){if(!n.isNum())throw new Error(`expected TYPE.NUMBER but ${n.toString()}`);const i=n.n,r=n.t;if(t.isSafeTile(r,i,e))return 0;if(i==1)return t.isSafeTile(r,4,e)?3:6;if(i==9)return t.isSafeTile(r,6,e)?3:6;if(i==2||i==8)return t.isSafeTile(r,5,e)?4:8;if(i==3)return t.isSafeTile(r,6,e)?5:8;if(i==7)return t.isSafeTile(r,4,e)?5:8;const o=t.isSafeTile(r,i-3,e),a=t.isSafeTile(r,i+3,e);return o&&a?4:o||a?8:12}}exports.ActorHand=Lt;exports.BLOCK=b;exports.BaseActor=Os;exports.Block=B;exports.BlockAnKan=U;exports.BlockCalculator=Hi;exports.BlockChi=dt;exports.BlockDaiKan=wt;exports.BlockHand=ee;exports.BlockIsolated=Jn;exports.BlockOther=Vn;exports.BlockPair=Y;exports.BlockPon=_t;exports.BlockRun=St;exports.BlockShoKan=ct;exports.BlockThree=at;exports.Controller=je;exports.Counter=Ki;exports.DoubleCalculator=Wn;exports.Efficiency=ae;exports.FONT_FAMILY=Zn;exports.Hand=cn;exports.INPUT_SEPARATOR=At;exports.ImageHelper=ms;exports.MeasureText=mr;exports.N19=ft;exports.NZ=oe;exports.OPERATOR=y;exports.Observer=hr;exports.Parser=Q;exports.PlaceManager=Te;exports.Player=be;exports.PlayerEfficiency=Oe;exports.ROUND=j;exports.ROUND_MAP=Yn;exports.Replayer=ph;exports.RiskRank=te;exports.River=ys;exports.ScoreManager=ke;exports.ShantenCalculator=We;exports.TABLE_CONTEXT=Js;exports.TILE_CONTEXT=Et;exports.TYPE=p;exports.Tile=w;exports.WIND=v;exports.WIND_MAP=nn;exports.Wall=Wt;exports.callBlockIndex=An;exports.convertInput=Ri;exports.createControllerMachine=Gn;exports.createEventEmitter=zi;exports.createEventPipe=_e;exports.createHand=Vt;exports.createLocalGame=mh;exports.createTable=Di;exports.createWindMap=Z;exports.deserializeWinResult=we;exports.drawBlocks=$a;exports.drawTable=Fa;exports.forHand=rt;exports.incrementalIDGenerator=cr;exports.isNum5=z;exports.nextRound=ve;exports.nextWind=kt;exports.optimizeSVG=Wa;exports.parse=Ci;exports.parseTableInput=Mi;exports.prevRound=Ar;exports.prevWind=Qn;exports.prioritizeDiscardedEvents=Bi;exports.prioritizeDrawnEvents=Wi;exports.shuffle=gs;exports.sortCalledTiles=Vs;exports.tileSortFunc=Ie;
|
|
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=nt(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:ee(t.controller.doWin(r,i,{oneShot:t.oneShotMap[r],replacementWin:s==null?void 0:s.replacementWin})),REACH:Go(t.controller.doReach(r)),AN_KAN:te(t.controller.doAnKan(r)),SHO_KAN:te(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:ee(t.controller.doWin(o,i,{discardedBy:r.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:te(t.controller.doPon(o,r.w,i)),CHI:te(t.controller.doChi(o,r.w,i)),DAI_KAN:Fo(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 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:ee(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"?ee(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:De(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:De(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 Jt(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 Ts(n=0){let t=n;return()=>(t++).toString()}class yt{constructor(t){_(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});_(this,"backup");_(this,"openedDoraCount",1);this.init(t),this.backup=yt.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=yt.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())}}Qe(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 Yt{constructor(t,e){_(this,"wall",new yt);_(this,"playerIDs");_(this,"actor",$t(Ke(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=is();this.observer=new Is(s),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const r=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new Gt(r);const i=(e==null?void 0:e.shuffle)==!1?this.playerIDs:Qe([...this.playerIDs]);this.observer.placeManager=new Ut({[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=es(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:Lt(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:X.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=T.deserialize(a[0]);this.actor.send({type:i.type,iam:o.wind,block:c})}}else if(r.type=="CHOICE_AFTER_DRAWN"){const i=ns(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:Lt(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:x.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:Lt(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:Lt(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 Yt(i);return o.playerIDs=s,o.mailBox=e,o.observer.placeManager=new Ut(t.players,{round:t.round,sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new Gt(t.scores),o.wall=new yt(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 yt,this.observer.applied={},this.mailBox={},this.actor=$t(Ke(this)),!this.placeManager.is(k.W1););}finalResult(t,e){const s=this.hand(e),r=s.reached?this.wall.blindDoraMarkers:void 0,i=new xe(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 Qn(r),a=new xe(r,i),c=o.calc(e),l=a.calc(...c);if(!l||l.points.length==0)return!1;if(r.draw==null){const u=Mt.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=Se(t,e,b.PON),a=[],c=new Y([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()||nt(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 R=r.get(O.t,O.n);for(let _t=0;_t<R;_t++)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 Jt(e).calc()>0?!1:Mt.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 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 x(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 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=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=Se(t,e,b.DAI_KAN);let a=new X([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?Rt:U;for(const o of i)e.get(r,o)>0&&s++}return s>=9}initialHands(){return this.wall.initialHands()}}class wt extends fe{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 wt(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 dn{constructor(t,e){_(this,"id");_(this,"river",new tn);_(this,"placeManager",new Ut({}));_(this,"scoreManager",new Gt({}));_(this,"hands",$(new wt("")));_(this,"counter",new os);_(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 Ut(structuredClone(t.places),{round:t.round,sticks:structuredClone(t.sticks)}),this.scoreManager=new Gt(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=x.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 Is extends dn{constructor(e){super("observer",e);_(this,"applied",{});this.counter.disable=!0,this.hands=$(new wt("_____________"))}setHands(e){this.hands[e.wind]=new wt(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)}(${Ue(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 jt extends dn{constructor(e,s){super(e,s);_(this,"river",new tn);_(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 wt(e.hands[s])}handleDiscard(e){const s=Object.values(A).filter(u=>u==this.myWind?!1:this.hand(u).reached),r=new Jt(this.hand(this.myWind)).calc();if(s.length>0&&r>=2)return It.selectTile(this.counter,s,e);const i=Mt.calcCandidates(this.hand(this.myWind),e),a=Zt.calcPlayerCandidates(this.counter,i).sort((u,h)=>h.sum-u.sum),c=a.filter(u=>u.sum==a[0].sum);return Zt.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 Uo{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(){Yt.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const Zo=n=>{const[t,e]=zt(),[s,r]=zt(),[i,o]=zt(),[a,c]=zt(),l=["player-1","player-2","player-3","player-4"],u=n==null?void 0:n.playerInjection,h=(u==null?void 0:u.p1)??jt,d=(u==null?void 0:u.p2)??jt,g=(u==null?void 0:u.p3)??jt,f=(u==null?void 0:u.p4)??jt,m=new h(l[0],e),E=new d(l[1],r),N=new g(l[2],o),O=new f(l[3],c),R=[{handler:t,id:l[0]},{handler:s,id:l[1]},{handler:i,id:l[2]},{handler:a,id:l[3]}];return{c:new Yt(R,{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 Zt{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=Zt.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 It{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=It.rank(t,e,o);a<i&&(r=o,i=a)}return r}static rank(t,e,s){let r=0;const i=s.isNum()?It.rankN:It.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=wt;exports.BLOCK=b;exports.BaseActor=dn;exports.Block=T;exports.BlockAnKan=x;exports.BlockCalculator=Qn;exports.BlockChi=Z;exports.BlockDaiKan=X;exports.BlockHand=Ot;exports.BlockIsolated=Fe;exports.BlockOther=Ge;exports.BlockPair=H;exports.BlockPon=Y;exports.BlockRun=Q;exports.BlockShoKan=D;exports.BlockThree=z;exports.Controller=Yt;exports.Counter=os;exports.DoubleCalculator=xe;exports.Efficiency=Mt;exports.FONT_FAMILY=Le;exports.G=v;exports.Hand=fe;exports.INPUT_SEPARATOR=q;exports.Image=Je;exports.ImageHelper=qe;exports.Mark=ot;exports.MeasureText=Ps;exports.MyG=ni;exports.MyImage=si;exports.MyRect=ii;exports.MySVG=ei;exports.MyText=oi;exports.MyUse=ri;exports.N19=U;exports.NZ=Rt;exports.OP=y;exports.Observer=Is;exports.Parser=W;exports.PlaceManager=Ut;exports.Player=jt;exports.PlayerEfficiency=Zt;exports.ROUND=k;exports.ROUND_MAP=ze;exports.Rect=Xe;exports.Replayer=Uo;exports.RiskRank=It;exports.River=tn;exports.STICK_CONTEXT=Ne;exports.SVG=Fn;exports.ScoreManager=Gt;exports.ShantenCalculator=Jt;exports.Svg=jn;exports.Symbol=Ye;exports.TABLE_CONTEXT=$n;exports.TILE_CONTEXT=et;exports.TYPE=p;exports.Text=gt;exports.Tile=w;exports.Use=de;exports.WIND=A;exports.WIND_MAP=ue;exports.Wall=yt;exports.callBlockIndex=Se;exports.convertInput=qn;exports.createControllerMachine=Ke;exports.createEventEmitter=is;exports.createEventPipe=zt;exports.createHand=vt;exports.createLocalGame=Zo;exports.createTable=Zn;exports.createWindMap=$;exports.deserializeWinResult=Lt;exports.drawBlocks=fi;exports.drawTable=Ei;exports.forHand=L;exports.incrementalIDGenerator=Ts;exports.isNum5=C;exports.nextRound=Ft;exports.nextWind=nt;exports.optimizeSVG=gi;exports.parse=Xn;exports.parseTableInput=Yn;exports.prevRound=zs;exports.prevWind=Ue;exports.prioritizeDiscardedEvents=es;exports.prioritizeDrawnEvents=ns;exports.shuffle=Qe;exports.sortCalledTiles=Pn;exports.tileSortFunc=Vt;
|