@konoui/mjimage 0.0.41 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,15 +1,13 @@
1
- "use strict";var lr=Object.defineProperty;var ur=(s,t,e)=>t in s?lr(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var S=(s,t,e)=>ur(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qn="MS Gothic, sans-serif",vt={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Zs={BASE:40},fe=",",d={M:"m",P:"p",S:"s",Z:"z",BACK:"_"},b={TSUMO:"t",RON:"v",DORA:"d",HORIZONTAL:"-",RED:"r",COLOR_GRAYSCALE:"^"},_={PON:"pon",CHI:"chi",SHO_KAN:"shokan",DAI_KAN:"daikan",AN_KAN:"ankan",TSUMO:"tsumo",PAIR:"pair",ISOLATED:"isolated",THREE:"three",RUN:"run",HAND:"hand",IMAGE_DORA:"dora",IMAGE_DISCARD:"simple-discard",UNKNOWN:"unknown"},v={E:"1w",S:"2w",W:"3w",N:"4w"},P={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"},tn={[v.E]:"東",[v.S]:"南",[v.W]:"西",[v.N]:"北"},Gn={[P.E1]:"東1局",[P.E2]:"東2局",[P.E3]:"東3局",[P.E4]:"東4局",[P.S1]:"南1局",[P.S2]:"南2局",[P.S3]:"南3局",[P.S4]:"南4局",[P.W1]:"西1局",[P.W2]:"西2局",[P.W3]:"西3局",[P.W4]:"西4局",[P.N1]:"北1局",[P.N2]:"北2局",[P.N3]:"北3局",[P.N4]:"北4局"};function C(s,t){if(!s)throw new Error(t)}class fr{constructor(t="東",e="2"){S(this,"ctx",null);S(this,"strText");S(this,"numText");S(this,"measure",(t,e)=>{this.ctx==null&&(this.ctx=document.createElement("canvas").getContext("2d"),C(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]});S(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}});S(this,"measureTableFontContext",t=>{const e=this.measureFontContext(qn,Zs.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class dr{constructor(t){S(this,"input");S(this,"position");S(this,"nextPosition");S(this,"char");S(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 ye=(s,t)=>{if(s.t==t.t)return j(s)?5-t.n:j(t)?s.n-5:s.n-t.n;const e={[d.M]:1,[d.P]:2,[d.S]:3,[d.Z]:4,[d.BACK]:5};return e[s.t]-e[t.t]};function pr(s){for(let t of Object.values(d))if(t==s)return[t,!0];return[d.BACK,!1]}class g{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===d.BACK?this.t:`${this.ops.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=>(t==null?void 0:t.remove)!=o),r=new Set([...i]);return t!=null&&t.add&&r.add(t.add),new g(e,n,Array.from(r))}has(t){return this.ops.includes(t)}isNum(){return this.t==d.M||this.t==d.P||this.t==d.S}equals(t,e=!1){let n=this.n==t.n;return e&&(n||(n=we(this)&&we(t))),this.t==t.t&&n}imageSize(t){const e=parseFloat((vt.HEIGHT*t).toPrecision(5)),n=parseFloat((vt.WIDTH*t).toPrecision(5)),i=this.has(b.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(this.has(b.TSUMO)||this.has(b.DORA))&&(i.width+=n*vt.TEXT_SCALE),i}}function we(s){return j(s)||V(s)}function V(s){return s.isNum()&&s.n==5}function j(s){return s.isNum()&&s.n==0}class W{constructor(t,e){S(this,"_tiles");S(this,"_type");if(this._tiles=t,this._type=e,this._type==_.CHI){this._tiles=[...this._tiles].sort((n,i)=>n.has(b.HORIZONTAL)?-1:i.has(b.HORIZONTAL)?1:ye(n,i));return}this._type!=_.SHO_KAN&&this._type!=_.IMAGE_DISCARD&&(this._tiles=[...this._tiles].sort(ye))}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==_.PAIR||t.type==_.ISOLATED||t.type==_.THREE||t.type==_.RUN)&&n!=t.type)throw new Error(`input type is ${t.type} but got is ${n}: ${t.tiles}`);return Ue(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[_.PON.toString(),_.CHI.toString(),_.DAI_KAN.toString(),_.SHO_KAN.toString(),_.AN_KAN.toString()].includes(this._type.toString())}clone(t){const e=t==null?void 0:t.replace;let n=[...this.tiles];return e&&(n[e.idx]=e.tile),Ue(n,this._type)}imageSize(t){const e=this.tiles[0].imageSize(t).baseHeight,n=this.tiles[0].imageSize(t).baseWidth;if(this.is(_.SHO_KAN))return{width:n*2+e,height:Math.max(n*2,e)};const i=this.tiles.reduce((o,a)=>{const c=a.imageSize(t).height;return c>o?c:o},0);return{width:this.tiles.reduce((o,a)=>o+a.imageSize(t).width,0),height:i}}}const Lt=s=>{let t="";for(let e of s){if(e.t==d.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Zn=s=>{let t=s[0].t,e="";for(let i=0;i<s.length;i++){const r=s[i],o=r.t,a=o==d.BACK?r.toString():r.toString().slice(0,-1);o!=t&&t!=d.BACK&&(e+=t),t=o,e+=a}const n=s.at(-1);return n.t!=d.BACK&&(e+=n.t),e};class ct extends W{constructor(t){super(t,_.CHI)}static from(t){return W.deserialize({tiles:t,type:_.CHI})}toString(){return Lt(this.tiles)}}class ft extends W{constructor(t){super(t,_.PON)}static from(t){return W.deserialize({tiles:t,type:_.PON})}toString(){return Lt(this.tiles)}}class U extends W{constructor(t){const e=t.filter(i=>i.t!=d.BACK),n=e[0];if(e.length<t.length){if(we(n)){const i=new g(n.t,5);super([new g(n.t,0),i,i,i],_.AN_KAN);return}super([n,n,n,n],_.AN_KAN);return}super(t,_.AN_KAN)}get tilesWithBack(){const t=this.tiles[0];return we(t)?[new g(d.BACK,0),new g(t.t,0),new g(t.t,5),new g(d.BACK,0)]:[new g(d.BACK,0),t,t,new g(d.BACK,0)]}static from(t){return W.deserialize({tiles:t,type:_.AN_KAN})}toString(){return Zn(this.tilesWithBack)}}class ut extends W{constructor(t){super(t,_.DAI_KAN)}static from(t){return W.deserialize({tiles:t,type:_.DAI_KAN})}toString(){return Lt(this.tiles)}}class at extends W{constructor(t){super(t,_.SHO_KAN)}static from(t){return W.deserialize({tiles:t,type:_.SHO_KAN})}toString(){return Lt(this.tiles)}}class Z extends W{constructor(t,e){super([t,e],_.PAIR)}toString(){return Lt(this.tiles)}}class ot extends W{constructor(t){super(t,_.THREE)}static from(t){return W.deserialize({tiles:t,type:_.THREE})}toString(){return Lt(this.tiles)}}class bt extends W{constructor(t){super(t,_.RUN)}static from(t){return W.deserialize({tiles:t,type:_.RUN})}toString(){return Lt(this.tiles)}}class Yn extends W{constructor(t){super([t],_.ISOLATED)}toString(){return this.tiles[0].toString()}}class en extends W{constructor(t){super(t,_.HAND)}toString(){return Zn(this.tiles)}}class Xn extends W{constructor(t,e){super(t,e)}toString(){return this.is(_.IMAGE_DISCARD)?this.tiles.join(""):Zn(this.tiles)}}const Ue=(s,t)=>{switch(t){case _.CHI:return new ct([s[0],s[1],s[2]]);case _.PON:return new ft([s[0],s[1],s[2]]);case _.AN_KAN:return new U(s);case _.DAI_KAN:return new ut(s);case _.SHO_KAN:return new at(s);case _.THREE:return new ot(s);case _.RUN:return new bt(s);case _.PAIR:return new Z(s[0],s[1]);case _.ISOLATED:return new Yn(s[0]);case _.HAND:return new en(s);default:return new Xn(s,t)}};class Q{constructor(t){S(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!=fe)}tileSeparators(){const t=new dr(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();let i=t.char;if(i===t.eof)break;if(i==fe){e.push(fe),t.readChar();continue}let[r,o]=Es(i,n);if(o){if(r==d.BACK){e.push(new g(r,0)),t.readChar();continue}e.push(...gr(n,r)),n=[],t.readChar();continue}else{const[a,c]=yr(t);if(c){n.push(a),t.readChar();continue}const[h,l]=Ys(i);if(!l)throw new Error(`encounter unexpected number. n: ${h}, current: ${i}, input: ${t.input}`);n.push(new g(d.BACK,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==fe){const a=Os(e),c=Ue(e,a);n.push(c),e=[];continue}e.push(o)}const i=Os(e),r=Ue(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]=Es(e,[new g(d.BACK,1)]);if(!i)throw new Error(`last character(${e}) is not type value`)}}function Os(s){if(s.length===0)return _.UNKNOWN;if(s.length===1)return s[0].has(b.DORA)?_.IMAGE_DORA:s[0].has(b.TSUMO)?_.TSUMO:_.HAND;const t=s.every(r=>r.equals(s[0],!0)),e=s.filter(r=>r.has(b.HORIZONTAL)).length,n=s.filter(r=>r.has(b.TSUMO)||r.has(b.DORA)).length,i=s.filter(r=>r.t==d.BACK).length;if(n>0)return _.UNKNOWN;if(e==0&&i==0)return _.HAND;if(s.length===3&&i===0)return t?_.PON:e==1&&mr(s)?_.CHI:_.IMAGE_DISCARD;if(s.length==4&&i==2)return _.AN_KAN;if(s.length==4&&t){if(e==1)return _.DAI_KAN;if(e==2)return _.SHO_KAN}return e==1||n==0?_.IMAGE_DISCARD:_.UNKNOWN}function mr(s){const t=[...s].sort(ye);if(!t.every(n=>t[0].t==n.t))return!1;const e=t.map(n=>j(n)?5:n.n);for(let n=0;n<e.length-1;n++)if(e[n]!=e[n+1]-1)return!1;return!0}function gr(s,t){return s.map(e=>new g(t,e.n,e.ops))}function Es(s,t){const[e,n]=pr(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]=o.clone({n:o.n+4}))}return[d.Z,!0]}return[d.BACK,!1]}function Ys(s){const t=["0","1","2","3","4","5","6","7","8","9"];return[Number(s),t.includes(s)]}function yr(s){const t=Object.values(b);if(!t.includes(s.char))return[new g(d.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]=Ys(i);if(!o)break;for(let c=0;c<e.length;c++)s.readChar();let a=new g(d.BACK,r,e);if(a.has(b.RED)){if(a.n!=5)throw new Error(`${b.RED} is specified for an invalid number: ${a.n}`);a=a.clone({n:0,remove:b.RED})}return[a,!0]}}return[new g(d.BACK,0),!1]}function G(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 ge=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=At(t)):e++,`${t}${e}`},wr=s=>ge(ge(ge(s))),At=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}w`},Xs=s=>{let t=Number(s.toString()[0]);return t=t%2+1,`${t}w`},Sn={},Js=[];function T(s,t){if(Array.isArray(s)){for(const e of s)T(e,t);return}if(typeof s=="object"){for(const e in s)T(e,s[e]);return}Vs(Object.getOwnPropertyNames(t)),Sn[s]=Object.assign(Sn[s]||{},t)}function X(s){return Sn[s]||{}}function _r(){return[...new Set(Js)]}function Vs(s){Js.push(...s)}function Jn(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)i.push(t(s[e]));return i}function br(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 hn(s){return s%360*Math.PI/180}function Sr(s){return s.replace(/([A-Z])/g,function(t,e){return"-"+e.toLowerCase()})}function Qs(s){return s.charAt(0).toUpperCase()+s.slice(1)}function ae(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 vn(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 vr=new Set(["desc","metadata","title"]),An=s=>vr.has(s.nodeName),ti=(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"))},Vn="http://www.w3.org/2000/svg",Ar="http://www.w3.org/1999/xhtml",ln="http://www.w3.org/2000/xmlns/",Oe="http://www.w3.org/1999/xlink",I={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function xr(){return I.window}class Qn{}const Rt={},ts="___SYMBOL___ROOT___";function _e(s,t=Vn){return I.document.createElementNS(t,s)}function Y(s,t=!1){if(s instanceof Qn)return s;if(typeof s=="object")return un(s);if(s==null)return new Rt[ts];if(typeof s=="string"&&s.charAt(0)!=="<")return un(I.document.querySelector(s));const e=t?I.document.createElement("div"):_e("svg");return e.innerHTML=s,s=un(e.firstChild),e.removeChild(e.firstChild),s}function H(s,t){return t&&(t instanceof I.window.Node||t.ownerDocument&&t instanceof t.ownerDocument.defaultView.Node)?t:_e(s)}function st(s){if(!s)return null;if(s.instance instanceof Qn)return s.instance;if(s.nodeName==="#document-fragment")return new Rt.Fragment(s);let t=Qs(s.nodeName||"Dom");return t==="LinearGradient"||t==="RadialGradient"?t="Gradient":Rt[t]||(t="Dom"),new Rt[t](s)}let un=st;function N(s,t=s.name,e=!1){return Rt[t]=s,e&&(Rt[ts]=s),Vs(Object.getOwnPropertyNames(s.prototype)),s}function kr(s){return Rt[s]}let Tr=1e3;function ei(s){return"Svgjs"+Qs(s)+Tr++}function ni(s){for(let t=s.children.length-1;t>=0;t--)ni(s.children[t]);return s.id&&(s.id=ei(s.nodeName)),s}function E(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 R(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 Or(){return this.parent().children()}function Er(){return this.parent().index(this)}function Ir(){return this.siblings()[this.position()+1]}function Nr(){return this.siblings()[this.position()-1]}function Mr(){const s=this.position();return this.parent().add(this.remove(),s+1),this}function Dr(){const s=this.position();return this.parent().add(this.remove(),s?s-1:0),this}function Cr(){return this.parent().add(this.remove()),this}function Rr(){return this.parent().add(this.remove(),0),this}function Hr(s){s=Y(s),s.remove();const t=this.position();return this.parent().add(s,t),this}function $r(s){s=Y(s),s.remove();const t=this.position();return this.parent().add(s,t+1),this}function Wr(s){return s=Y(s),s.before(this),this}function Br(s){return s=Y(s),s.after(this),this}T("Dom",{siblings:Or,position:Er,next:Ir,prev:Nr,forward:Mr,backward:Dr,front:Cr,back:Rr,before:Hr,after:$r,insertBefore:Wr,insertAfter:Br});const si=/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,zr=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,Pr=/rgb\((\d+),(\d+),(\d+)\)/,jr=/(#[a-z_][a-z0-9\-_]*)/i,Lr=/\)\s*,?\s*/,Kr=/\s/g,Is=/^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i,Ns=/^rgb\(/,Ms=/^(\s+)?$/,Ds=/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Ur=/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,wt=/[\s,]+/,es=/[MLHVCSQTAZ]/i;function Fr(){const s=this.attr("class");return s==null?[]:s.trim().split(wt)}function qr(s){return this.classes().indexOf(s)!==-1}function Gr(s){if(!this.hasClass(s)){const t=this.classes();t.push(s),this.attr("class",t.join(" "))}return this}function Zr(s){return this.hasClass(s)&&this.attr("class",this.classes().filter(function(t){return t!==s}).join(" ")),this}function Yr(s){return this.hasClass(s)?this.removeClass(s):this.addClass(s)}T("Dom",{classes:Fr,hasClass:qr,addClass:Gr,removeClass:Zr,toggleClass:Yr});function Xr(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||Ms.test(s[n])?"":s[n])}return arguments.length===2&&this.node.style.setProperty(s,t==null||Ms.test(t)?"":t),this}function Jr(){return this.css("display","")}function Vr(){return this.css("display","none")}function Qr(){return this.css("display")!=="none"}T("Dom",{css:Xr,show:Jr,hide:Vr,visible:Qr});function to(s,t,e){if(s==null)return this.data(Jn(br(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}T("Dom",{data:to});function eo(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 no(){if(arguments.length===0)this._memory={};else for(let s=arguments.length-1;s>=0;s--)delete this.memory()[arguments[s]];return this}function so(){return this._memory=this._memory||{}}T("Dom",{remember:eo,forget:no,memory:so});function io(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 ro(s){const t=Math.round(s),n=Math.max(0,Math.min(255,t)).toString(16);return n.length===1?"0"+n:n}function Ut(s,t){for(let e=t.length;e--;)if(s[t[e]]==null)return!1;return!0}function oo(s,t){const e=Ut(s,"rgb")?{_a:s.r,_b:s.g,_c:s.b,_d:0,space:"rgb"}:Ut(s,"xyz")?{_a:s.x,_b:s.y,_c:s.z,_d:0,space:"xyz"}:Ut(s,"hsl")?{_a:s.h,_b:s.s,_c:s.l,_d:0,space:"hsl"}:Ut(s,"lab")?{_a:s.l,_b:s.a,_c:s.b,_d:0,space:"lab"}:Ut(s,"lch")?{_a:s.l,_b:s.c,_c:s.h,_d:0,space:"lch"}:Ut(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 ao(s){return s==="lab"||s==="xyz"||s==="lch"}function fn(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 D{constructor(...t){this.init(...t)}static isColor(t){return t&&(t instanceof D||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 D(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 D(a,c,h)}else if(t==="pastel"){const a=8*n()+86,c=17*n()+9,h=360*n();return new D(a,c,h,"lch")}else if(t==="dark"){const a=10+10*n(),c=50*n()+86,h=360*n();return new D(a,c,h,"lch")}else if(t==="rgb"){const a=255*n(),c=255*n(),h=255*n();return new D(a,c,h)}else if(t==="lab"){const a=100*n(),c=256*n()-128,h=256*n()-128;return new D(a,c,h,"lab")}else if(t==="grey"){const a=255*n();return new D(a,a,a)}else throw new Error("Unsupported random color mode")}static test(t){return typeof t=="string"&&(Is.test(t)||Ns.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 D(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 D(c,h,l,a,"cmyk")}hsl(){const{_a:t,_b:e,_c:n}=this.rgb(),[i,r,o]=[t,e,n].map(y=>y/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 D(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=oo(t,e);Object.assign(this,u)}else if(typeof t=="string")if(Ns.test(t)){const u=t.replace(Kr,""),[f,m,p]=Pr.exec(u).slice(1,4).map(y=>parseInt(y));Object.assign(this,{_a:f,_b:m,_c:p,_d:0,space:"rgb"})}else if(Is.test(t)){const u=y=>parseInt(y,16),[,f,m,p]=zr.exec(io(t)).map(u);Object.assign(this,{_a:f,_b:m,_c:p,_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 D(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 D(t,i,r,"lch")}rgb(){if(this.space==="rgb")return this;if(ao(this.space)){let{x:t,y:e,z:n}=this;if(this.space==="lab"||this.space==="lch"){let{l:m,a:p,b:y}=this;if(this.space==="lch"){const{c:rt,h:pt}=this,Kt=Math.PI/180;p=rt*Math.cos(Kt*pt),y=rt*Math.sin(Kt*pt)}const w=(m+16)/116,x=p/500+w,O=w-y/200,$=16/116,nt=.008856,K=7.787;t=.95047*(x**3>nt?x**3:(x-$)/K),e=1*(w**3>nt?w**3:(w-$)/K),n=1.08883*(O**3>nt?O**3:(O-$)/K)}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 D(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 D(n,n,n);const i=n<.5?n*(1+e):n+e-n*e,r=2*n-i,o=255*fn(r,i,t+1/3),a=255*fn(r,i,t),c=255*fn(r,i,t-1/3);return new D(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 D(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(ro);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(x=>x/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,p=u>.008856?Math.pow(u,1/3):7.787*u+16/116,y=f>.008856?Math.pow(f,1/3):7.787*f+16/116;return new D(m,p,y,"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 B{constructor(...t){this.init(...t)}clone(){return new B(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){A.isMatrixLike(t)||(t=new A(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 co(s,t){return new B(s,t).transformO(this.screenCTM().inverseO())}function Ft(s,t,e){return Math.abs(t-s)<1e-6}class A{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 B(t.origin||t.around||t.ox||t.originX,t.oy||t.originY),f=u.x,m=u.y,p=new B(t.position||t.px||t.positionX||NaN,t.py||t.positionY||NaN),y=p.x,w=p.y,x=new B(t.translate||t.tx||t.translateX,t.ty||t.translateY),O=x.x,$=x.y,nt=new B(t.relative||t.rx||t.relativeX,t.ry||t.relativeY),K=nt.x,rt=nt.y;return{scaleX:a,scaleY:c,skewX:r,skewY:o,shear:h,theta:l,rx:K,ry:rt,tx:O,ty:$,ox:f,oy:m,px:y,py:w}}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 A(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,p=Math.cos(f),y=Math.sin(f),w=(n*r+i*o)/h,x=r*u/(w*n-i)||o*u/(w*i+n),O=a-t+t*p*u+e*(w*p*u-y*x),$=c-e+t*y*u+e*(w*y*u+p*x);return{scaleX:u,scaleY:x,shear:w,rotate:m,translateX:O,translateY:$,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 A(t);return Ft(this.a,e.a)&&Ft(this.b,e.b)&&Ft(this.c,e.c)&&Ft(this.d,e.d)&&Ft(this.e,e.e)&&Ft(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=A.fromArray([1,0,0,1,0,0]);return t=t instanceof dt?t.matrixify():typeof t=="string"?A.fromArray(t.split(wt).map(parseFloat)):Array.isArray(t)?A.fromArray(t):typeof t=="object"&&A.isMatrixLike(t)?t:typeof t=="object"?new A().transform(t):arguments.length===6?A.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 A?t:new A(t);return A.matrixMultiply(n,e,this)}multiply(t){return this.clone().multiplyO(t)}multiplyO(t){const e=this,n=t instanceof A?t:new A(t);return A.matrixMultiply(e,n,this)}rotate(t,e,n){return this.clone().rotateO(t,e,n)}rotateO(t,e=0,n=0){t=hn(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=hn(t),e=hn(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(A.isMatrixLike(t))return new A(t).multiplyO(this);const e=A.formatTransforms(t),n=this,{x:i,y:r}=new B(e.ox,e.oy).transform(n),o=new A().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 B(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 ho(){return new A(this.node.getCTM())}function lo(){try{if(typeof this.isRoot=="function"&&!this.isRoot()){const s=this.rect(1,1),t=s.node.getScreenCTM();return s.remove(),new A(t)}return new A(this.node.getScreenCTM())}catch{return console.warn(`Cannot get CTM from SVG node ${this.node.nodeName}. Is the element rendered?`),new A}}N(A,"Matrix");function _t(){if(!_t.nodes){const s=Y().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;_t.nodes={svg:s,path:t}}if(!_t.nodes.svg.node.parentNode){const s=I.document.body||I.document.documentElement;_t.nodes.svg.addTo(s)}return _t.nodes}function ii(s){return!s.width&&!s.height&&!s.x&&!s.y}function uo(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 L{constructor(...t){this.init(...t)}addOffset(){return this.x+=I.window.pageXOffset,this.y+=I.window.pageYOffset,new L(this)}init(t){const e=[0,0,0,0];return t=typeof t=="string"?t.split(wt).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 ii(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 L(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 A||(t=new A(t));let e=1/0,n=-1/0,i=1/0,r=-1/0;return[new B(this.x,this.y),new B(this.x2,this.y),new B(this.x,this.y2),new B(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 L(e,i,n-e,r-i)}}function ri(s,t,e){let n;try{if(n=t(s.node),ii(n)&&!uo(s.node))throw new Error("Element not in the dom")}catch{n=e(s)}return n}function fo(){const e=ri(this,i=>i.getBBox(),i=>{try{const r=i.clone().addTo(_t().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 L(e)}function po(s){const n=ri(this,r=>r.getBoundingClientRect(),r=>{throw new Error(`Getting rbox of element "${r.node.nodeName}" is not possible`)}),i=new L(n);return s?i.transform(s.screenCTM().inverseO()):i.addOffset()}function mo(s,t){const e=this.bbox();return s>e.x&&t>e.y&&s<e.x+e.width&&t<e.y+e.height}T({viewbox:{viewbox(s,t,e,n){return s==null?new L(this.attr("viewBox")):this.attr("viewBox",new L(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 B(e/2/r+i.x,n/2/o+i.y);const h=new L(i).transform(new A({scale:c,origin:t}));return this.viewbox(h)}}});N(L,"Box");class $t extends Array{constructor(t=[],...e){if(super(t,...e),typeof t=="number")return this;this.length=0,this.push(...t)}}E([$t],{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 go=["toArray","constructor","each"];$t.extend=function(s){s=s.reduce((t,e)=>(go.includes(e)||e[0]==="_"||(e in Array.prototype&&(t["$"+e]=Array.prototype[e]),t[e]=function(...n){return this.each(e,...n)}),t),{}),E([$t],s)};function ce(s,t){return new $t(Jn((t||I.document).querySelectorAll(s),function(e){return st(e)}))}function yo(s){return ce(s,this.node)}function wo(s){return st(this.node.querySelector(s))}let _o=0;const oi={};function ai(s){let t=s.getEventHolder();return t===I.window&&(t=oi),t.events||(t.events={}),t.events}function ns(s){return s.getEventTarget()}function bo(s){let t=s.getEventHolder();t===I.window&&(t=oi),t.events&&(t.events={})}function xn(s,t,e,n,i){const r=e.bind(n||s),o=Y(s),a=ai(o),c=ns(o);t=Array.isArray(t)?t:t.split(wt),e._svgjsListenerId||(e._svgjsListenerId=++_o),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 Zt(s,t,e,n){const i=Y(s),r=ai(i),o=ns(i);typeof e=="function"&&(e=e._svgjsListenerId,!e)||(t=Array.isArray(t)?t:(t||"").split(wt),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])Zt(o,[c,h].join("."),u);delete r[c][h]}}else if(h)for(a in r)for(l in r[a])h===l&&Zt(o,[a,h].join("."));else if(c){if(r[c]){for(l in r[c])Zt(o,[c,l].join("."));delete r[c]}}else{for(a in r)Zt(o,a);bo(i)}}))}function So(s,t,e,n){const i=ns(s);return t instanceof I.window.Event||(t=new I.window.CustomEvent(t,{detail:e,cancelable:!0,...n})),i.dispatchEvent(t),t}class Ee extends Qn{addEventListener(){}dispatch(t,e,n){return So(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 Zt(this,t,e,n),this}on(t,e,n,i){return xn(this,t,e,n,i),this}removeEventListener(){}}N(Ee,"EventTarget");function Cs(){}const de={duration:400,ease:">",delay:0},vo={"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 Qt 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(wt).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 k{constructor(...t){this.init(...t)}convert(t){return new k(this.value,t)}divide(t){return t=new k(t),new k(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(si),e&&(this.value=parseFloat(e[1]),e[5]==="%"?this.value/=100:e[5]==="s"&&(this.value*=1e3),this.unit=e[5])):t instanceof k&&(this.value=t.valueOf(),this.unit=t.unit),this}minus(t){return t=new k(t),new k(this-t,this.unit||t.unit)}plus(t){return t=new k(t),new k(this+t,this.unit||t.unit)}times(t){return t=new k(t),new k(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 Ao=new Set(["fill","stroke","color","bgcolor","stop-color","flood-color","lighting-color"]),ci=[];function xo(s){ci.push(s)}function ko(s,t,e){if(s==null){s={},t=this.node.attributes;for(const n of t)s[n.nodeName]=Ds.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?vo[s]:Ds.test(t)?parseFloat(t):t;t=ci.reduce((n,i)=>i(s,n,this),t),typeof t=="number"?t=new k(t):Ao.has(s)&&D.isColor(t)?t=new D(t):t.constructor===Array&&(t=new Qt(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 xt extends Ee{constructor(t,e){super(),this.node=t,this.type=t.nodeName,e&&t!==e&&this.attr(e)}add(t,e){return t=Y(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 Y(t).put(this,e)}children(){return new $t(Jn(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=ni(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 xt(_e(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,Ar)}id(t){return typeof t>"u"&&!this.node.id&&(this.node.id=ei(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=Y(t),this.add(t,e),t}putIn(t,e){return Y(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=Y(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,Vn)}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=_e("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)}}E(xt,{attr:ko,find:yo,findOne:wo});N(xt,"Dom");class dt extends xt{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 k(t).plus(this.x()))}dy(t=0){return this.y(new k(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=Y(t));const n=new $t;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(jr);return e?Y(e[1]):null}root(){const t=this.parent(kr(ts));return t&&t.root()}setData(t){return this.dom=t,this}size(t,e){const n=ae(this,t,e);return this.width(new k(n.width)).height(new k(n.height))}width(t){return this.attr("width",t)}writeDataToDom(){return ti(this,this.dom),super.writeDataToDom()}x(t){return this.attr("x",t)}y(t){return this.attr("y",t)}}E(dt,{bbox:fo,rbox:po,inside:mo,point:co,ctm:ho,screenCTM:lo});N(dt,"Element");const le={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 D||D.isRgb(n)||n instanceof dt)this.attr(s,n);else for(e=le[s].length-1;e>=0;e--)n[le[s][e]]!=null&&this.attr(le.prefix(s,le[s][e]),n[le[s][e]]);return this},T(["Element","Runner"],t)});T(["Element","Runner"],{matrix:function(s,t,e,n,i,r){return s==null?new A(this):this.attr("transform",new A(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)}});T("radius",{radius:function(s,t=s){return(this._element||this).type==="radialGradient"?this.attr("r",new k(s)):this.rx(s).ry(t)}});T("Path",{length:function(){return this.node.getTotalLength()},pointAt:function(s){return new B(this.node.getPointAtLength(s))}});T(["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 To=["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},{});T("Element",To);function Oo(){return this.attr("transform",null)}function Eo(){return(this.attr("transform")||"").split(Lr).slice(0,-1).map(function(t){const e=t.trim().split("(");return[e[0],e[1].split(wt).map(function(n){return parseFloat(n)})]}).reverse().reduce(function(t,e){return e[0]==="matrix"?t.lmultiply(A.fromArray(e[1])):t[e[0]].apply(t,e[1])},new A)}function Io(s,t){if(this===s)return this;if(An(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 No(s){return this.toParent(this.root(),s)}function Mo(s,t){if(s==null||typeof s=="string"){const i=new A(this).decompose();return s==null?i:i[s]}A.isMatrixLike(s)||(s={...s,origin:vn(s,this)});const e=t===!0?this:t||!1,n=new A(e).transform(s);return this.attr("transform",n)}T("Element",{untransform:Oo,matrixify:Eo,toParent:Io,toRoot:No,transform:Mo});class J extends dt{flatten(){return this.each(function(){if(this instanceof J)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(J,"Container");class ss extends J{constructor(t,e=t){super(H("defs",t),e)}flatten(){return this}ungroup(){return this}}N(ss,"Defs");class et extends dt{}N(et,"Shape");function is(s){return this.attr("rx",s)}function rs(s){return this.attr("ry",s)}function hi(s){return s==null?this.cx()-this.rx():this.cx(s+this.rx())}function li(s){return s==null?this.cy()-this.ry():this.cy(s+this.ry())}function ui(s){return this.attr("cx",s)}function fi(s){return this.attr("cy",s)}function di(s){return s==null?this.rx()*2:this.rx(new k(s).divide(2))}function pi(s){return s==null?this.ry()*2:this.ry(new k(s).divide(2))}const Do=Object.freeze(Object.defineProperty({__proto__:null,cx:ui,cy:fi,height:pi,rx:is,ry:rs,width:di,x:hi,y:li},Symbol.toStringTag,{value:"Module"}));class nn extends et{constructor(t,e=t){super(H("ellipse",t),e)}size(t,e){const n=ae(this,t,e);return this.rx(new k(n.width).divide(2)).ry(new k(n.height).divide(2))}}E(nn,Do);T("Container",{ellipse:R(function(s=0,t=s){return this.put(new nn).size(s,t).move(0,0)})});N(nn,"Ellipse");class mi extends xt{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 xt(_e("wrapper",n));return i.add(this.node.cloneNode(!0)),i.xml(!1,n)}return super.xml(t,!1,n)}}N(mi,"Fragment");function gi(s,t){return(this._element||this).type==="radialGradient"?this.attr({fx:new k(s),fy:new k(t)}):this.attr({x1:new k(s),y1:new k(t)})}function yi(s,t){return(this._element||this).type==="radialGradient"?this.attr({cx:new k(s),cy:new k(t)}):this.attr({x2:new k(s),y2:new k(t)})}const Co=Object.freeze(Object.defineProperty({__proto__:null,from:gi,to:yi},Symbol.toStringTag,{value:"Module"}));class Ie extends J{constructor(t,e){super(H(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 L}targets(){return ce("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()+")"}}E(Ie,Co);T({Container:{gradient(...s){return this.defs().gradient(...s)}},Defs:{gradient:R(function(s,t){return this.put(new Ie(s)).update(t)})}});N(Ie,"Gradient");class be extends J{constructor(t,e=t){super(H("pattern",t),e)}attr(t,e,n){return t==="transform"&&(t="patternTransform"),super.attr(t,e,n)}bbox(){return new L}targets(){return ce("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({Container:{pattern(...s){return this.defs().pattern(...s)}},Defs:{pattern:R(function(s,t,e){return this.put(new be).update(e).attr({x:0,y:0,width:s,height:t,patternUnits:"userSpaceOnUse"})})}});N(be,"Pattern");class Ne extends et{constructor(t,e=t){super(H("image",t),e)}load(t,e){if(!t)return this;const n=new I.window.Image;return xn(n,"load",function(i){const r=this.parent(be);this.width()===0&&this.height()===0&&this.size(n.width,n.height),r instanceof be&&r.width()===0&&r.height()===0&&r.size(this.width(),this.height()),typeof e=="function"&&e.call(this,i)},this),xn(n,"load error",function(){Zt(n)}),this.attr("href",n.src=t,Oe)}}xo(function(s,t,e){return(s==="fill"||s==="stroke")&&Ur.test(t)&&(t=e.root().defs().image(t)),t instanceof Ne&&(t=e.root().defs().pattern(0,0,n=>{n.add(t)})),t});T({Container:{image:R(function(s,t){return this.put(new Ne).size(0,0).load(s,t)})}});N(Ne,"Image");class kt extends Qt{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 L(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(wt).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){A.isMatrixLike(t)||(t=new A(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 Ro=kt;function Ho(s){return s==null?this.bbox().x:this.move(s,this.bbox().y)}function $o(s){return s==null?this.bbox().y:this.move(this.bbox().x,s)}function Wo(s){const t=this.bbox();return s==null?t.width:this.size(s,t.height)}function Bo(s){const t=this.bbox();return s==null?t.height:this.size(t.width,s)}const os=Object.freeze(Object.defineProperty({__proto__:null,MorphArray:Ro,height:Bo,width:Wo,x:Ho,y:$o},Symbol.toStringTag,{value:"Module"}));class Se extends et{constructor(t,e=t){super(H("line",t),e)}array(){return new kt([[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 kt(t).toLine(),this.attr(t))}size(t,e){const n=ae(this,t,e);return this.attr(this.array().size(n.width,n.height).toLine())}}E(Se,os);T({Container:{line:R(function(...s){return Se.prototype.plot.apply(this.put(new Se),s[0]!=null?s:[0,0,0,0])})}});N(Se,"Line");class Fe extends J{constructor(t,e=t){super(H("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)}}T({Container:{marker(...s){return this.defs().marker(...s)}},Defs:{marker:R(function(s,t,e){return this.put(new Fe).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 Fe?arguments[1]:this.defs().marker(t,e,n),this.attr(i,s)}}});N(Fe,"Marker");function Yt(s,t){return function(e){return e==null?this[s]:(this[s]=e,t&&t.call(this),this)}}const zo={"-":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 as{done(){return!1}}class kn extends as{constructor(t=de.ease){super(),this.ease=zo[t]||t}step(t,e,n){return typeof t!="number"?n<1?t:e:t+(e-t)*this.ease(n)}}let qe=class extends as{constructor(t){super(),this.stepper=t}done(t){return t.done}step(t,e,n,i){return this.stepper(t,e,n,i)}};function Rs(){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 Po extends qe{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}}E(Po,{duration:Yt("_duration",Rs),overshoot:Yt("_overshoot",Rs)});class jo extends qe{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)}}E(jo,{windup:Yt("_windup"),p:Yt("P"),i:Yt("I"),d:Yt("D")});const Lo={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Tn={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]]}},dn="mlhvqtcsaz".split("");for(let s=0,t=dn.length;s<t;++s)Tn[dn[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 Tn[e](n,i,r)}}(dn[s].toUpperCase());function Ko(s){const t=s.segment[0];return Tn[t](s.segment.slice(1),s.p,s.p0)}function On(s){return s.segment.length&&s.segment.length-1===Lo[s.segment[0].toUpperCase()]}function Uo(s,t){s.inNumber&&Nt(s,!1);const e=es.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 Nt(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,On(s)&&En(s)}function En(s){s.inSegment=!1,s.absolute&&(s.segment=Ko(s)),s.segments.push(s.segment)}function Fo(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 qo(s){return s.lastToken.toUpperCase()==="E"}const Go=new Set([" ",","," ",`
2
- `,"\r","\f"]);function Zo(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 B,p:new B};for(;i.lastToken=n,n=s.charAt(e++);)if(!(!i.inSegment&&Uo(i,n))){if(n==="."){if(i.pointSeen||i.hasExponent){Nt(i,!1),--e;continue}i.inNumber=!0,i.pointSeen=!0,i.number+=n;continue}if(!isNaN(parseInt(n))){if(i.number==="0"||Fo(i)){i.inNumber=!0,i.number=n,Nt(i,!0);continue}i.inNumber=!0,i.number+=n;continue}if(Go.has(n)){i.inNumber&&Nt(i,!1);continue}if(n==="-"||n==="+"){if(i.inNumber&&!qo(i)){Nt(i,!1),--e;continue}i.number+=n,i.inNumber=!0;continue}if(n.toUpperCase()==="E"){i.number+=n,i.hasExponent=!0;continue}if(es.test(n)){if(i.inNumber)Nt(i,!1);else if(On(i))En(i);else throw new Error("parser Error");--e}}return i.inNumber&&Nt(i,!1),i.inSegment&&On(i)&&En(i),i.segments}function Yo(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 Wt extends Qt{bbox(){return _t().path.setAttribute("d",this.toString()),new L(_t.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()),Zo(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 Yo(this)}}const wi=s=>{const t=typeof s;return t==="number"?k:t==="string"?D.isColor(s)?D:wt.test(s)?es.test(s)?Wt:Qt:si.test(s)?k:In:cs.indexOf(s.constructor)>-1?s.constructor:Array.isArray(s)?Qt:t==="object"?ve:In};class Mt{constructor(t){this._stepper=t||new kn("-"),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(wi(t));let e=new this._type(t);return this._type===D&&(e=this._to?e[this._to[4]]():this._from?e[this._from[4]]():e),this._type===ve&&(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 In{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 Me{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,Me.defaults,t),this}toArray(){const t=this;return[t.scaleX,t.scaleY,t.shear,t.rotate,t.translateX,t.translateY,t.originX,t.originY]}}Me.defaults={scaleX:1,scaleY:1,shear:0,rotate:0,translateX:0,translateY:0,originX:0,originY:0};const Xo=(s,t)=>s[0]<t[0]?-1:s[0]>t[0]?1:0;class ve{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]===D&&t[n+7]!==e[n+7]){const a=t[n+7],c=new D(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=wi(t[n]),r=new i(t[n]).toArray();e.push([n,i,r.length,...r])}return e.sort(Xo),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 cs=[In,Me,ve];function Jo(s=[]){cs.push(...[].concat(s))}function Vo(){E(cs,{to(s){return new Mt().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 he extends et{constructor(t,e=t){super(H("path",t),e)}array(){return this._array||(this._array=new Wt(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 Wt(t))}size(t,e){const n=ae(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)}}he.prototype.MorphArray=Wt;T({Container:{path:R(function(s){return this.put(new he).plot(s||new Wt)})}});N(he,"Path");function Qo(){return this._array||(this._array=new kt(this.attr("points")))}function ta(){return delete this._array,this}function ea(s,t){return this.attr("points",this.array().move(s,t))}function na(s){return s==null?this.array():this.clear().attr("points",typeof s=="string"?s:this._array=new kt(s))}function sa(s,t){const e=ae(this,s,t);return this.attr("points",this.array().size(e.width,e.height))}const _i=Object.freeze(Object.defineProperty({__proto__:null,array:Qo,clear:ta,move:ea,plot:na,size:sa},Symbol.toStringTag,{value:"Module"}));class De extends et{constructor(t,e=t){super(H("polygon",t),e)}}T({Container:{polygon:R(function(s){return this.put(new De).plot(s||new kt)})}});E(De,os);E(De,_i);N(De,"Polygon");class Ce extends et{constructor(t,e=t){super(H("polyline",t),e)}}T({Container:{polyline:R(function(s){return this.put(new Ce).plot(s||new kt)})}});E(Ce,os);E(Ce,_i);N(Ce,"Polyline");class Re extends et{constructor(t,e=t){super(H("rect",t),e)}}E(Re,{rx:is,ry:rs});T({Container:{rect:R(function(s,t){return this.put(new Re).size(s,t)})}});N(Re,"Rect");class pn{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 M={nextDraw:null,frames:new pn,timeouts:new pn,immediates:new pn,timer:()=>I.window.performance||I.window.Date,transforms:[],frame(s){const t=M.frames.push({run:s});return M.nextDraw===null&&(M.nextDraw=I.window.requestAnimationFrame(M._draw)),t},timeout(s,t){t=t||0;const e=M.timer().now()+t,n=M.timeouts.push({run:s,time:e});return M.nextDraw===null&&(M.nextDraw=I.window.requestAnimationFrame(M._draw)),n},immediate(s){const t=M.immediates.push(s);return M.nextDraw===null&&(M.nextDraw=I.window.requestAnimationFrame(M._draw)),t},cancelFrame(s){s!=null&&M.frames.remove(s)},clearTimeout(s){s!=null&&M.timeouts.remove(s)},cancelImmediate(s){s!=null&&M.immediates.remove(s)},_draw(s){let t=null;const e=M.timeouts.last();for(;(t=M.timeouts.shift())&&(s>=t.time?t.run():M.timeouts.push(t),t!==e););let n=null;const i=M.frames.last();for(;n!==i&&(n=M.frames.shift());)n.run(s);let r=null;for(;r=M.immediates.shift();)r();M.nextDraw=M.timeouts.first()||M.frames.first()?I.window.requestAnimationFrame(M._draw):null}},ia=function(s){const t=s.start,e=s.runner.duration(),n=t+e;return{start:t,duration:e,end:n,runner:s.runner}},ra=function(){const s=I.window;return(s.performance||s.Date).now()};class bi extends Ee{constructor(t=ra){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(ia);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 M.cancelFrame(this._nextFrame),this._nextFrame=null,t?this._stepImmediate():this._paused?this:(this._nextFrame=M.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)}}T({Element:{timeline:function(s){return s==null?(this._timeline=this._timeline||new bi,this._timeline):(this._timeline=s,this)}}});class tt extends Ee{constructor(t){super(),this.id=tt.id++,t=t??de.duration,t=typeof t=="function"?new qe(t):t,this._element=null,this._timeline=null,this.done=!1,this._queue=[],this._duration=typeof t=="number"&&t,this._isDeclarative=t instanceof qe,this._stepper=this._isDeclarative?t:new kn,this._history={},this.enabled=!0,this._time=0,this._lastTime=0,this._reseted=!0,this.transforms=new A,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??de.duration,e=e??de.delay,n=n||"last",typeof t=="object"&&!(t instanceof as)&&(e=t.delay??e,n=t.when??n,r=t.swing||r,i=t.times??i,o=t.wait??o,t=t.duration??de.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=tt.sanitise(t,e,n),r=new tt(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 A,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 kn(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(p){const y=o*Math.floor(p%(2*(i+n))/(i+n)),w=y&&!a||!y&&a,x=Math.pow(-1,w)*(p%(i+n))/n+w;return Math.max(Math.min(x,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||Cs,runner:e||Cs,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 bi||(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 A,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}}tt.id=0;class Ge{constructor(t=new A,e=-1,n=!0){this.transforms=t,this.id=e,this.done=n}clearTransformsFromQueue(){}}E([tt,Ge],{mergeWith(s){return new Ge(s.transforms.lmultiply(this.transforms),s.id)}});const Si=(s,t)=>s.lmultiplyO(t),vi=s=>s.transforms;function oa(){const t=this._transformationRunners.runners.map(vi).reduce(Si,new A);this.transform(t),this._transformationRunners.merge(),this._transformationRunners.length()===1&&(this._frameId=null)}class aa{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 Ge).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}}T({Element:{animate(s,t,e){const n=tt.sanitise(s,t,e),i=this.timeline();return new tt(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(vi).reduce(Si,new A)},_addRunner(s){this._transformationRunners.add(s),M.cancelImmediate(this._frameId),this._frameId=M.immediate(oa.bind(this))},_prepareRunner(){this._frameId==null&&(this._transformationRunners=new aa().add(new Ge(new A(this))))}}});const ca=(s,t)=>s.filter(e=>!t.includes(e));E(tt,{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 Mt(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=ca(a,r);if(c.length){const l=this.element()[s](c),u=new ve(i.from()).valueOf();Object.assign(u,l),i.from(u)}const h=new ve(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 Mt(this._stepper).to(new k(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=A.isMatrixLike(s);e=s.affine!=null?s.affine:e??!n;const i=new Mt(this._stepper).type(e?Me:A);let r,o,a,c,h;function l(){o=o||this.element(),r=r||vn(s,o),h=new A(t?void 0:o),o._addRunner(this),t||o._clearTransformRunnersBefore(this)}function u(m){t||this.clearTransform();const{x:p,y}=new B(r).transform(o._currentTransform(this));let w=new A({...s,origin:[p,y]}),x=this._isDeclarative&&a?a:h;if(e){w=w.decompose(p,y),x=x.decompose(p,y);const $=w.rotate,nt=x.rotate,K=[$-360,$,$+360],rt=K.map(cn=>Math.abs(cn-nt)),pt=Math.min(...rt),Kt=rt.indexOf(pt);w.rotate=K[Kt]}t&&(n||(w.rotate=s.rotate||0),this._isDeclarative&&c&&(x.rotate=c)),i.from(x),i.to(w);const O=i.at(m);return c=O.rotate,a=new A(O),this.addTransform(a),o._addRunner(this),i.done()}function f(m){(m.origin||"center").toString()!==(s.origin||"center").toString()&&(r=vn(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 k(t),this._tryRetarget(s,t))return this;const e=new Mt(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 k(i))}),this._rememberMorpher(s,e),this},_queueObject(s,t){if(this._tryRetarget(s,t))return this;const e=new Mt(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 k(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 Mt(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 L(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)}});E(tt,{rx:is,ry:rs,from:gi,to:yi});N(tt,"Runner");class hs extends J{constructor(t,e=t){super(H("svg",t),e),this.namespace()}defs(){return this.isRoot()?st(this.node.querySelector("defs"))||this.put(new ss):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:Vn,version:"1.1"}).attr("xmlns:xlink",Oe,ln):this.root().namespace()}removeNamespace(){return this.attr({xmlns:null,version:null}).attr("xmlns:xlink",null,ln).attr("xmlns:svgjs",null,ln)}root(){return this.isRoot()?this:super.root()}}T({Container:{nested:R(function(){return this.put(new hs)})}});N(hs,"Svg",!0);let sn=class extends J{constructor(t,e=t){super(H("symbol",t),e)}};T({Container:{symbol:R(function(){return this.put(new sn)})}});N(sn,"Symbol");function ha(s){return this._build===!1&&this.clear(),this.node.appendChild(I.document.createTextNode(s)),this}function la(){return this.node.getComputedTextLength()}function ua(s,t=this.bbox()){return s==null?t.x:this.attr("x",this.attr("x")+s-t.x)}function fa(s,t=this.bbox()){return s==null?t.y:this.attr("y",this.attr("y")+s-t.y)}function da(s,t,e=this.bbox()){return this.x(s,e).y(t,e)}function pa(s,t=this.bbox()){return s==null?t.cx:this.attr("x",this.attr("x")+s-t.cx)}function ma(s,t=this.bbox()){return s==null?t.cy:this.attr("y",this.attr("y")+s-t.cy)}function ga(s,t,e=this.bbox()){return this.cx(s,e).cy(t,e)}function ya(s){return this.attr("x",s)}function wa(s){return this.attr("y",s)}function _a(s,t){return this.ax(s).ay(t)}function ba(s){return this._build=!!s,this}const Ai=Object.freeze(Object.defineProperty({__proto__:null,amove:_a,ax:ya,ay:wa,build:ba,center:ga,cx:pa,cy:ma,length:la,move:da,plain:ha,x:ua,y:fa},Symbol.toStringTag,{value:"Module"}));class F extends et{constructor(t,e=t){super(H("text",t),e),this.dom.leading=this.dom.leading??new k(1.3),this._rebuild=!0,this._build=!1}leading(t){return t==null?this.dom.leading:(this.dom.leading=new k(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(An(this.node))return;const o=I.window.getComputedStyle(this.node).getPropertyValue("font-size"),a=i*new k(o);this.dom.newLined&&(this.attr("x",e.attr("x")),this.text()===`
3
- `?n+=a:(this.attr("dy",r?a+n:0),n=0))}),this.fire("rebuild")}return this}setData(t){return this.dom=t,this.dom.leading=new k(t.leading||1.3),this}writeDataToDom(){return ti(this,this.dom,{leading:1.3}),this}text(t){if(t===void 0){const e=this.node.childNodes;let n=0;t="";for(let i=0,r=e.length;i<r;++i){if(e[i].nodeName==="textPath"||An(e[i])){i===0&&(n=i+1);continue}i!==n&&e[i].nodeType!==3&&st(e[i]).dom.newLined===!0&&(t+=`
1
+ "use strict";var fr=Object.defineProperty;var dr=(s,t,e)=>t in s?fr(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var A=(s,t,e)=>dr(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qn="MS Gothic, sans-serif",xt={WIDTH:66,HEIGHT:90,TEXT_SCALE:.8,BLOCK_MARGIN_SCALE:.3},Ys={BASE:40},vt=",",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"},en={[v.E]:"東",[v.S]:"南",[v.W]:"西",[v.N]:"北"},Gn={[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 pr{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(qn,Ys.BASE*t);return e.textHeight=e.textWidth,e.numHeight=e.numWidth,e});this.strText=t,this.numText=e}}class mr{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 Te=(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]},gr=(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]},Xs=s=>{const t=[];s.forEach((n,i)=>{n.has(y.HORIZONTAL)&&t.push(i)});const e=s.filter(n=>!n.has(y.HORIZONTAL)).sort(Te);return t.forEach(n=>{e.splice(n,0,s[n])}),e};function z(s){return s.isNum()&&s.n==5}function yr(s){for(let 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(gr).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=>(t==null?void 0:t.remove)!=o),r=new Set([...i]);return t!=null&&t.add&&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=Xs(this._tiles);return}if(this._type!=b.IMAGE_DISCARD){this._tiles=[...this._tiles].sort(Te);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 Ue(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;let n=[...this.tiles];return e&&(n[e.idx]=e.tile),Ue(n,this._type)}}const Ft=s=>{let t="";for(let e of s){if(e.t==p.BACK)return s.join("");t+=e.toString().slice(0,-1)}return`${t}${s[0].t}`},Yn=s=>{let t=s[0].t,e="";for(let i=0;i<s.length;i++){const r=s[i],o=r.t,a=o==p.BACK?r.toString():r.toString().slice(0,-1);o!=t&&t!=p.BACK&&(e+=t),t=o,e+=a}const n=s.at(-1);return n.t!=p.BACK&&(e+=n.t),e};class ht extends B{constructor(t){super(t,b.CHI)}static from(t){return B.deserialize({tiles:t,type:b.CHI})}toString(){return Ft(this.tiles)}}class pt extends B{constructor(t){super(t,b.PON)}static from(t){return B.deserialize({tiles:t,type:b.PON})}toString(){return Ft(this.tiles)}}class F 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 Yn(this.tilesWithBack)}}class dt extends B{constructor(t){super(t,b.DAI_KAN)}static from(t){return B.deserialize({tiles:t,type:b.DAI_KAN})}toString(){return Ft(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 Ft(this.tiles)}}class Y extends B{constructor(t,e){super([t,e],b.PAIR)}toString(){return Ft(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 Ft(this.tiles)}}class At extends B{constructor(t){super(t,b.RUN)}static from(t){return B.deserialize({tiles:t,type:b.RUN})}toString(){return Ft(this.tiles)}}class Xn extends B{constructor(t){super([t],b.ISOLATED)}toString(){return this.tiles[0].toString()}}class nn extends B{constructor(t){super(t,b.HAND)}toString(){return Yn(this.tiles)}}class Jn extends B{constructor(t,e){super(t,e)}toString(){return this.is(b.IMAGE_DISCARD)?this.tiles.join(""):Yn(this.tiles)}}const Ue=(s,t)=>{switch(t){case b.CHI:return new ht([s[0],s[1],s[2]]);case b.PON:return new pt([s[0],s[1],s[2]]);case b.AN_KAN:return new F(s);case b.DAI_KAN:return new dt(s);case b.SHO_KAN:return new ct(s);case b.THREE:return new at(s);case b.RUN:return new At(s);case b.PAIR:return new Y(s[0],s[1]);case b.ISOLATED:return new Xn(s[0]);case b.HAND:return new nn(s);default:return new Jn(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!=vt)}tileSeparators(){const t=new mr(this.input),e=[];let n=[];for(this.validate(this.input);;){t.skipWhitespace();let i=t.char;if(i===t.eof)break;if(i==vt){e.push(vt),t.readChar();continue}let[r,o]=Is(i,n);if(o){if(r==p.BACK){e.push(new w(r,0)),t.readChar();continue}e.push(..._r(n,r)),n=[],t.readChar();continue}else{const[a,c]=br(t);if(c){n.push(a),t.readChar();continue}const[h,l]=Js(i);if(!l)throw new Error(`encounter unexpected number. n: ${h}, current: ${i}, input: ${t.input}`);n.push(new w(p.BACK,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==vt){const a=Os(e),c=Ue(e,a);n.push(c),e=[];continue}e.push(o)}const i=Os(e),r=Ue(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]=Is(e,[new w(p.BACK,1)]);if(!i)throw new Error(`last character(${e}) is not type value`)}}function Os(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&&wr(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 wr(s){const t=[...s].sort(Te);if(!t.every(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 _r(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 Is(s,t){const[e,n]=yr(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]=o.clone({n:o.n+4}))}return[p.Z,!0]}return[p.BACK,!1]}function Js(s){const t=Number(s),e=0<=t&&t<=9;return[t,e]}function br(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]=Js(i);if(!o)break;for(let c=0;c<e.length;c++)s.readChar();if(e.some(c=>c==y.RED)&&r!=5)throw new Error(`found ${y.RED} but number is not 5: ${r}`);return[new w(p.BACK,r,e),!0]}}return[new w(p.BACK,0),!1]}function G(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 _e=s=>{let t=s.substring(0,2),e=Number(s.substring(2,3));return e==4?(e=1,t=Et(t)):e++,`${t}${e}`},vr=s=>_e(_e(_e(s))),Et=s=>{let t=Number(s.toString()[0]);return t=t%4+1,`${t}w`},Vs=s=>{let t=Number(s.toString()[0]);return t=t%2+1,`${t}w`},vn=(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},An={},Qs=[];function T(s,t){if(Array.isArray(s)){for(const e of s)T(e,t);return}if(typeof s=="object"){for(const e in s)T(e,s[e]);return}ti(Object.getOwnPropertyNames(t)),An[s]=Object.assign(An[s]||{},t)}function J(s){return An[s]||{}}function Ar(){return[...new Set(Qs)]}function ti(s){Qs.push(...s)}function Vn(s,t){let e;const n=s.length,i=[];for(e=0;e<n;e++)i.push(t(s[e]));return i}function Sr(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 ln(s){return s%360*Math.PI/180}function xr(s){return s.replace(/([A-Z])/g,function(t,e){return"-"+e.toLowerCase()})}function ei(s){return s.charAt(0).toUpperCase()+s.slice(1)}function le(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 Sn(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 Er=new Set(["desc","metadata","title"]),xn=s=>Er.has(s.nodeName),ni=(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"))},Qn="http://www.w3.org/2000/svg",kr="http://www.w3.org/1999/xhtml",un="http://www.w3.org/2000/xmlns/",Oe="http://www.w3.org/1999/xlink",N={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function Tr(){return N.window}class ts{}const $t={},es="___SYMBOL___ROOT___";function be(s,t=Qn){return N.document.createElementNS(t,s)}function X(s,t=!1){if(s instanceof ts)return s;if(typeof s=="object")return fn(s);if(s==null)return new $t[es];if(typeof s=="string"&&s.charAt(0)!=="<")return fn(N.document.querySelector(s));const e=t?N.document.createElement("div"):be("svg");return e.innerHTML=s,s=fn(e.firstChild),e.removeChild(e.firstChild),s}function $(s,t){return t&&(t instanceof N.window.Node||t.ownerDocument&&t instanceof t.ownerDocument.defaultView.Node)?t:be(s)}function st(s){if(!s)return null;if(s.instance instanceof ts)return s.instance;if(s.nodeName==="#document-fragment")return new $t.Fragment(s);let t=ei(s.nodeName||"Dom");return t==="LinearGradient"||t==="RadialGradient"?t="Gradient":$t[t]||(t="Dom"),new $t[t](s)}let fn=st;function C(s,t=s.name,e=!1){return $t[t]=s,e&&($t[es]=s),ti(Object.getOwnPropertyNames(s.prototype)),s}function Or(s){return $t[s]}let Ir=1e3;function si(s){return"Svgjs"+ei(s)+Ir++}function ii(s){for(let t=s.children.length-1;t>=0;t--)ii(s.children[t]);return s.id&&(s.id=si(s.nodeName)),s}function I(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 Nr(){return this.parent().children()}function Cr(){return this.parent().index(this)}function Dr(){return this.siblings()[this.position()+1]}function Mr(){return this.siblings()[this.position()-1]}function Rr(){const s=this.position();return this.parent().add(this.remove(),s+1),this}function Hr(){const s=this.position();return this.parent().add(this.remove(),s?s-1:0),this}function $r(){return this.parent().add(this.remove()),this}function Br(){return this.parent().add(this.remove(),0),this}function Wr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t),this}function Pr(s){s=X(s),s.remove();const t=this.position();return this.parent().add(s,t+1),this}function jr(s){return s=X(s),s.before(this),this}function zr(s){return s=X(s),s.after(this),this}T("Dom",{siblings:Nr,position:Cr,next:Dr,prev:Mr,forward:Rr,backward:Hr,front:$r,back:Br,before:Wr,after:Pr,insertBefore:jr,insertAfter:zr});const ri=/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,Lr=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,Kr=/rgb\((\d+),(\d+),(\d+)\)/,Fr=/(#[a-z_][a-z0-9\-_]*)/i,Ur=/\)\s*,?\s*/,Zr=/\s/g,Ns=/^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i,Cs=/^rgb\(/,Ds=/^(\s+)?$/,Ms=/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,qr=/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,_t=/[\s,]+/,ns=/[MLHVCSQTAZ]/i;function Gr(){const s=this.attr("class");return s==null?[]:s.trim().split(_t)}function Yr(s){return this.classes().indexOf(s)!==-1}function Xr(s){if(!this.hasClass(s)){const t=this.classes();t.push(s),this.attr("class",t.join(" "))}return this}function Jr(s){return this.hasClass(s)&&this.attr("class",this.classes().filter(function(t){return t!==s}).join(" ")),this}function Vr(s){return this.hasClass(s)?this.removeClass(s):this.addClass(s)}T("Dom",{classes:Gr,hasClass:Yr,addClass:Xr,removeClass:Jr,toggleClass:Vr});function Qr(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||Ds.test(s[n])?"":s[n])}return arguments.length===2&&this.node.style.setProperty(s,t==null||Ds.test(t)?"":t),this}function to(){return this.css("display","")}function eo(){return this.css("display","none")}function no(){return this.css("display")!=="none"}T("Dom",{css:Qr,show:to,hide:eo,visible:no});function so(s,t,e){if(s==null)return this.data(Vn(Sr(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}T("Dom",{data:so});function io(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 ro(){if(arguments.length===0)this._memory={};else for(let s=arguments.length-1;s>=0;s--)delete this.memory()[arguments[s]];return this}function oo(){return this._memory=this._memory||{}}T("Dom",{remember:io,forget:ro,memory:oo});function ao(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 co(s){const t=Math.round(s),n=Math.max(0,Math.min(255,t)).toString(16);return n.length===1?"0"+n:n}function Zt(s,t){for(let e=t.length;e--;)if(s[t[e]]==null)return!1;return!0}function ho(s,t){const e=Zt(s,"rgb")?{_a:s.r,_b:s.g,_c:s.b,_d:0,space:"rgb"}:Zt(s,"xyz")?{_a:s.x,_b:s.y,_c:s.z,_d:0,space:"xyz"}:Zt(s,"hsl")?{_a:s.h,_b:s.s,_c:s.l,_d:0,space:"hsl"}:Zt(s,"lab")?{_a:s.l,_b:s.a,_c:s.b,_d:0,space:"lab"}:Zt(s,"lch")?{_a:s.l,_b:s.c,_c:s.h,_d:0,space:"lch"}:Zt(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 lo(s){return s==="lab"||s==="xyz"||s==="lch"}function dn(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"&&(Ns.test(t)||Cs.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=ho(t,e);Object.assign(this,u)}else if(typeof t=="string")if(Cs.test(t)){const u=t.replace(Zr,""),[f,m,d]=Kr.exec(u).slice(1,4).map(g=>parseInt(g));Object.assign(this,{_a:f,_b:m,_c:d,_d:0,space:"rgb"})}else if(Ns.test(t)){const u=g=>parseInt(g,16),[,f,m,d]=Lr.exec(ao(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(lo(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:rt,h:gt}=this,Ut=Math.PI/180;d=rt*Math.cos(Ut*gt),g=rt*Math.sin(Ut*gt)}const _=(m+16)/116,x=d/500+_,k=_-g/200,R=16/116,Z=.008856,K=7.787;t=.95047*(x**3>Z?x**3:(x-R)/K),e=1*(_**3>Z?_**3:(_-R)/K),n=1.08883*(k**3>Z?k**3:(k-R)/K)}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*dn(r,i,t+1/3),a=255*dn(r,i,t),c=255*dn(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(co);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(x=>x/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){S.isMatrixLike(t)||(t=new S(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 uo(s,t){return new W(s,t).transformO(this.screenCTM().inverseO())}function qt(s,t,e){return Math.abs(t-s)<1e-6}class S{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,x=new W(t.translate||t.tx||t.translateX,t.ty||t.translateY),k=x.x,R=x.y,Z=new W(t.relative||t.rx||t.relativeX,t.ry||t.relativeY),K=Z.x,rt=Z.y;return{scaleX:a,scaleY:c,skewX:r,skewY:o,shear:h,theta:l,rx:K,ry:rt,tx:k,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 S(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,x=r*u/(_*n-i)||o*u/(_*i+n),k=a-t+t*d*u+e*(_*d*u-g*x),R=c-e+t*g*u+e*(_*g*u+d*x);return{scaleX:u,scaleY:x,shear:_,rotate:m,translateX:k,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 S(t);return qt(this.a,e.a)&&qt(this.b,e.b)&&qt(this.c,e.c)&&qt(this.d,e.d)&&qt(this.e,e.e)&&qt(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=S.fromArray([1,0,0,1,0,0]);return t=t instanceof mt?t.matrixify():typeof t=="string"?S.fromArray(t.split(_t).map(parseFloat)):Array.isArray(t)?S.fromArray(t):typeof t=="object"&&S.isMatrixLike(t)?t:typeof t=="object"?new S().transform(t):arguments.length===6?S.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 S?t:new S(t);return S.matrixMultiply(n,e,this)}multiply(t){return this.clone().multiplyO(t)}multiplyO(t){const e=this,n=t instanceof S?t:new S(t);return S.matrixMultiply(e,n,this)}rotate(t,e,n){return this.clone().rotateO(t,e,n)}rotateO(t,e=0,n=0){t=ln(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=ln(t),e=ln(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(S.isMatrixLike(t))return new S(t).multiplyO(this);const e=S.formatTransforms(t),n=this,{x:i,y:r}=new W(e.ox,e.oy).transform(n),o=new S().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 fo(){return new S(this.node.getCTM())}function po(){try{if(typeof this.isRoot=="function"&&!this.isRoot()){const s=this.rect(1,1),t=s.node.getScreenCTM();return s.remove(),new S(t)}return new S(this.node.getScreenCTM())}catch{return console.warn(`Cannot get CTM from SVG node ${this.node.nodeName}. Is the element rendered?`),new S}}C(S,"Matrix");function bt(){if(!bt.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;bt.nodes={svg:s,path:t}}if(!bt.nodes.svg.node.parentNode){const s=N.document.body||N.document.documentElement;bt.nodes.svg.addTo(s)}return bt.nodes}function oi(s){return!s.width&&!s.height&&!s.x&&!s.y}function mo(s){return s===N.document||(N.document.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t===N.document}).call(N.document.documentElement,s)}class L{constructor(...t){this.init(...t)}addOffset(){return this.x+=N.window.pageXOffset,this.y+=N.window.pageYOffset,new L(this)}init(t){const e=[0,0,0,0];return t=typeof t=="string"?t.split(_t).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 oi(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 L(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 S||(t=new S(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 L(e,i,n-e,r-i)}}function ai(s,t,e){let n;try{if(n=t(s.node),oi(n)&&!mo(s.node))throw new Error("Element not in the dom")}catch{n=e(s)}return n}function go(){const e=ai(this,i=>i.getBBox(),i=>{try{const r=i.clone().addTo(bt().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 L(e)}function yo(s){const n=ai(this,r=>r.getBoundingClientRect(),r=>{throw new Error(`Getting rbox of element "${r.node.nodeName}" is not possible`)}),i=new L(n);return s?i.transform(s.screenCTM().inverseO()):i.addOffset()}function wo(s,t){const e=this.bbox();return s>e.x&&t>e.y&&s<e.x+e.width&&t<e.y+e.height}T({viewbox:{viewbox(s,t,e,n){return s==null?new L(this.attr("viewBox")):this.attr("viewBox",new L(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 L(i).transform(new S({scale:c,origin:t}));return this.viewbox(h)}}});C(L,"Box");class Wt extends Array{constructor(t=[],...e){if(super(t,...e),typeof t=="number")return this;this.length=0,this.push(...t)}}I([Wt],{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 _o=["toArray","constructor","each"];Wt.extend=function(s){s=s.reduce((t,e)=>(_o.includes(e)||e[0]==="_"||(e in Array.prototype&&(t["$"+e]=Array.prototype[e]),t[e]=function(...n){return this.each(e,...n)}),t),{}),I([Wt],s)};function ue(s,t){return new Wt(Vn((t||N.document).querySelectorAll(s),function(e){return st(e)}))}function bo(s){return ue(s,this.node)}function vo(s){return st(this.node.querySelector(s))}let Ao=0;const ci={};function hi(s){let t=s.getEventHolder();return t===N.window&&(t=ci),t.events||(t.events={}),t.events}function ss(s){return s.getEventTarget()}function So(s){let t=s.getEventHolder();t===N.window&&(t=ci),t.events&&(t.events={})}function En(s,t,e,n,i){const r=e.bind(n||s),o=X(s),a=hi(o),c=ss(o);t=Array.isArray(t)?t:t.split(_t),e._svgjsListenerId||(e._svgjsListenerId=++Ao),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=hi(i),o=ss(i);typeof e=="function"&&(e=e._svgjsListenerId,!e)||(t=Array.isArray(t)?t:(t||"").split(_t),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);So(i)}}))}function xo(s,t,e,n){const i=ss(s);return t instanceof N.window.Event||(t=new N.window.CustomEvent(t,{detail:e,cancelable:!0,...n})),i.dispatchEvent(t),t}class Ie extends ts{addEventListener(){}dispatch(t,e,n){return xo(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 En(this,t,e,n,i),this}removeEventListener(){}}C(Ie,"EventTarget");function Rs(){}const me={duration:400,ease:">",delay:0},Eo={"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 ee 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(_t).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(ri),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 ko=new Set(["fill","stroke","color","bgcolor","stop-color","flood-color","lighting-color"]),li=[];function To(s){li.push(s)}function Oo(s,t,e){if(s==null){s={},t=this.node.attributes;for(const n of t)s[n.nodeName]=Ms.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?Eo[s]:Ms.test(t)?parseFloat(t):t;t=li.reduce((n,i)=>i(s,n,this),t),typeof t=="number"?t=new E(t):ko.has(s)&&M.isColor(t)?t=new M(t):t.constructor===Array&&(t=new ee(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 kt extends Ie{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 N.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 Wt(Vn(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=ii(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 kt(be(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,kr)}id(t){return typeof t>"u"&&!this.node.id&&(this.node.id=si(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,Qn)}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=be("wrapper",n),r=N.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)}}I(kt,{attr:Oo,find:bo,findOne:vo});C(kt,"Dom");class mt extends kt{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 Wt;let i=this;for(;(i=i.parent())&&i.node!==N.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(Or(es));return t&&t.root()}setData(t){return this.dom=t,this}size(t,e){const n=le(this,t,e);return this.width(new E(n.width)).height(new E(n.height))}width(t){return this.attr("width",t)}writeDataToDom(){return ni(this,this.dom),super.writeDataToDom()}x(t){return this.attr("x",t)}y(t){return this.attr("y",t)}}I(mt,{bbox:go,rbox:yo,inside:wo,point:uo,ctm:fo,screenCTM:po});C(mt,"Element");const de={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 mt)this.attr(s,n);else for(e=de[s].length-1;e>=0;e--)n[de[s][e]]!=null&&this.attr(de.prefix(s,de[s][e]),n[de[s][e]]);return this},T(["Element","Runner"],t)});T(["Element","Runner"],{matrix:function(s,t,e,n,i,r){return s==null?new S(this):this.attr("transform",new S(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)}});T("radius",{radius:function(s,t=s){return(this._element||this).type==="radialGradient"?this.attr("r",new E(s)):this.rx(s).ry(t)}});T("Path",{length:function(){return this.node.getTotalLength()},pointAt:function(s){return new W(this.node.getPointAtLength(s))}});T(["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 Io=["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},{});T("Element",Io);function No(){return this.attr("transform",null)}function Co(){return(this.attr("transform")||"").split(Ur).slice(0,-1).map(function(t){const e=t.trim().split("(");return[e[0],e[1].split(_t).map(function(n){return parseFloat(n)})]}).reverse().reduce(function(t,e){return e[0]==="matrix"?t.lmultiply(S.fromArray(e[1])):t[e[0]].apply(t,e[1])},new S)}function Do(s,t){if(this===s)return this;if(xn(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 Mo(s){return this.toParent(this.root(),s)}function Ro(s,t){if(s==null||typeof s=="string"){const i=new S(this).decompose();return s==null?i:i[s]}S.isMatrixLike(s)||(s={...s,origin:Sn(s,this)});const e=t===!0?this:t||!1,n=new S(e).transform(s);return this.attr("transform",n)}T("Element",{untransform:No,matrixify:Co,toParent:Do,toRoot:Mo,transform:Ro});class V extends mt{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()}}C(V,"Container");class is extends V{constructor(t,e=t){super($("defs",t),e)}flatten(){return this}ungroup(){return this}}C(is,"Defs");class nt extends mt{}C(nt,"Shape");function rs(s){return this.attr("rx",s)}function os(s){return this.attr("ry",s)}function ui(s){return s==null?this.cx()-this.rx():this.cx(s+this.rx())}function fi(s){return s==null?this.cy()-this.ry():this.cy(s+this.ry())}function di(s){return this.attr("cx",s)}function pi(s){return this.attr("cy",s)}function mi(s){return s==null?this.rx()*2:this.rx(new E(s).divide(2))}function gi(s){return s==null?this.ry()*2:this.ry(new E(s).divide(2))}const Ho=Object.freeze(Object.defineProperty({__proto__:null,cx:di,cy:pi,height:gi,rx:rs,ry:os,width:mi,x:ui,y:fi},Symbol.toStringTag,{value:"Module"}));class sn extends nt{constructor(t,e=t){super($("ellipse",t),e)}size(t,e){const n=le(this,t,e);return this.rx(new E(n.width).divide(2)).ry(new E(n.height).divide(2))}}I(sn,Ho);T("Container",{ellipse:H(function(s=0,t=s){return this.put(new sn).size(s,t).move(0,0)})});C(sn,"Ellipse");class yi extends kt{constructor(t=N.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 kt(be("wrapper",n));return i.add(this.node.cloneNode(!0)),i.xml(!1,n)}return super.xml(t,!1,n)}}C(yi,"Fragment");function wi(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 _i(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 $o=Object.freeze(Object.defineProperty({__proto__:null,from:wi,to:_i},Symbol.toStringTag,{value:"Module"}));class Ne 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 L}targets(){return ue("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()+")"}}I(Ne,$o);T({Container:{gradient(...s){return this.defs().gradient(...s)}},Defs:{gradient:H(function(s,t){return this.put(new Ne(s)).update(t)})}});C(Ne,"Gradient");class ve 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 L}targets(){return ue("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({Container:{pattern(...s){return this.defs().pattern(...s)}},Defs:{pattern:H(function(s,t,e){return this.put(new ve).update(e).attr({x:0,y:0,width:s,height:t,patternUnits:"userSpaceOnUse"})})}});C(ve,"Pattern");class Ce extends nt{constructor(t,e=t){super($("image",t),e)}load(t,e){if(!t)return this;const n=new N.window.Image;return En(n,"load",function(i){const r=this.parent(ve);this.width()===0&&this.height()===0&&this.size(n.width,n.height),r instanceof ve&&r.width()===0&&r.height()===0&&r.size(this.width(),this.height()),typeof e=="function"&&e.call(this,i)},this),En(n,"load error",function(){Xt(n)}),this.attr("href",n.src=t,Oe)}}To(function(s,t,e){return(s==="fill"||s==="stroke")&&qr.test(t)&&(t=e.root().defs().image(t)),t instanceof Ce&&(t=e.root().defs().pattern(0,0,n=>{n.add(t)})),t});T({Container:{image:H(function(s,t){return this.put(new Ce).size(0,0).load(s,t)})}});C(Ce,"Image");class Tt extends ee{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 L(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(_t).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){S.isMatrixLike(t)||(t=new S(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 Bo=Tt;function Wo(s){return s==null?this.bbox().x:this.move(s,this.bbox().y)}function Po(s){return s==null?this.bbox().y:this.move(this.bbox().x,s)}function jo(s){const t=this.bbox();return s==null?t.width:this.size(s,t.height)}function zo(s){const t=this.bbox();return s==null?t.height:this.size(t.width,s)}const as=Object.freeze(Object.defineProperty({__proto__:null,MorphArray:Bo,height:zo,width:jo,x:Wo,y:Po},Symbol.toStringTag,{value:"Module"}));class Ae extends nt{constructor(t,e=t){super($("line",t),e)}array(){return new Tt([[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 Tt(t).toLine(),this.attr(t))}size(t,e){const n=le(this,t,e);return this.attr(this.array().size(n.width,n.height).toLine())}}I(Ae,as);T({Container:{line:H(function(...s){return Ae.prototype.plot.apply(this.put(new Ae),s[0]!=null?s:[0,0,0,0])})}});C(Ae,"Line");class Ze 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)}}T({Container:{marker(...s){return this.defs().marker(...s)}},Defs:{marker:H(function(s,t,e){return this.put(new Ze).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 Ze?arguments[1]:this.defs().marker(t,e,n),this.attr(i,s)}}});C(Ze,"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 cs{done(){return!1}}class kn extends cs{constructor(t=me.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 qe=class extends cs{constructor(t){super(),this.stepper=t}done(t){return t.done}step(t,e,n,i){return this.stepper(t,e,n,i)}};function Hs(){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 Ko extends qe{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}}I(Ko,{duration:Jt("_duration",Hs),overshoot:Jt("_overshoot",Hs)});class Fo extends qe{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)}}I(Fo,{windup:Jt("_windup"),p:Jt("P"),i:Jt("I"),d:Jt("D")});const Uo={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0},Tn={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]]}},pn="mlhvqtcsaz".split("");for(let s=0,t=pn.length;s<t;++s)Tn[pn[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 Tn[e](n,i,r)}}(pn[s].toUpperCase());function Zo(s){const t=s.segment[0];return Tn[t](s.segment.slice(1),s.p,s.p0)}function On(s){return s.segment.length&&s.segment.length-1===Uo[s.segment[0].toUpperCase()]}function qo(s,t){s.inNumber&&Dt(s,!1);const e=ns.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 Dt(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,On(s)&&In(s)}function In(s){s.inSegment=!1,s.absolute&&(s.segment=Zo(s)),s.segments.push(s.segment)}function Go(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 Yo(s){return s.lastToken.toUpperCase()==="E"}const Xo=new Set([" ",","," ",`
2
+ `,"\r","\f"]);function Jo(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&&qo(i,n))){if(n==="."){if(i.pointSeen||i.hasExponent){Dt(i,!1),--e;continue}i.inNumber=!0,i.pointSeen=!0,i.number+=n;continue}if(!isNaN(parseInt(n))){if(i.number==="0"||Go(i)){i.inNumber=!0,i.number=n,Dt(i,!0);continue}i.inNumber=!0,i.number+=n;continue}if(Xo.has(n)){i.inNumber&&Dt(i,!1);continue}if(n==="-"||n==="+"){if(i.inNumber&&!Yo(i)){Dt(i,!1),--e;continue}i.number+=n,i.inNumber=!0;continue}if(n.toUpperCase()==="E"){i.number+=n,i.hasExponent=!0;continue}if(ns.test(n)){if(i.inNumber)Dt(i,!1);else if(On(i))In(i);else throw new Error("parser Error");--e}}return i.inNumber&&Dt(i,!1),i.inSegment&&On(i)&&In(i),i.segments}function Vo(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 Pt extends ee{bbox(){return bt().path.setAttribute("d",this.toString()),new L(bt.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()),Jo(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 Vo(this)}}const bi=s=>{const t=typeof s;return t==="number"?E:t==="string"?M.isColor(s)?M:_t.test(s)?ns.test(s)?Pt:ee:ri.test(s)?E:Nn:hs.indexOf(s.constructor)>-1?s.constructor:Array.isArray(s)?ee:t==="object"?Se:Nn};class Mt{constructor(t){this._stepper=t||new kn("-"),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(bi(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===Se&&(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 Nn{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 De{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,De.defaults,t),this}toArray(){const t=this;return[t.scaleX,t.scaleY,t.shear,t.rotate,t.translateX,t.translateY,t.originX,t.originY]}}De.defaults={scaleX:1,scaleY:1,shear:0,rotate:0,translateX:0,translateY:0,originX:0,originY:0};const Qo=(s,t)=>s[0]<t[0]?-1:s[0]>t[0]?1:0;class Se{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=bi(t[n]),r=new i(t[n]).toArray();e.push([n,i,r.length,...r])}return e.sort(Qo),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 hs=[Nn,De,Se];function ta(s=[]){hs.push(...[].concat(s))}function ea(){I(hs,{to(s){return new Mt().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 fe extends nt{constructor(t,e=t){super($("path",t),e)}array(){return this._array||(this._array=new Pt(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 Pt(t))}size(t,e){const n=le(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)}}fe.prototype.MorphArray=Pt;T({Container:{path:H(function(s){return this.put(new fe).plot(s||new Pt)})}});C(fe,"Path");function na(){return this._array||(this._array=new Tt(this.attr("points")))}function sa(){return delete this._array,this}function ia(s,t){return this.attr("points",this.array().move(s,t))}function ra(s){return s==null?this.array():this.clear().attr("points",typeof s=="string"?s:this._array=new Tt(s))}function oa(s,t){const e=le(this,s,t);return this.attr("points",this.array().size(e.width,e.height))}const vi=Object.freeze(Object.defineProperty({__proto__:null,array:na,clear:sa,move:ia,plot:ra,size:oa},Symbol.toStringTag,{value:"Module"}));class Me extends nt{constructor(t,e=t){super($("polygon",t),e)}}T({Container:{polygon:H(function(s){return this.put(new Me).plot(s||new Tt)})}});I(Me,as);I(Me,vi);C(Me,"Polygon");class Re extends nt{constructor(t,e=t){super($("polyline",t),e)}}T({Container:{polyline:H(function(s){return this.put(new Re).plot(s||new Tt)})}});I(Re,as);I(Re,vi);C(Re,"Polyline");class He extends nt{constructor(t,e=t){super($("rect",t),e)}}I(He,{rx:rs,ry:os});T({Container:{rect:H(function(s,t){return this.put(new He).size(s,t)})}});C(He,"Rect");class mn{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 D={nextDraw:null,frames:new mn,timeouts:new mn,immediates:new mn,timer:()=>N.window.performance||N.window.Date,transforms:[],frame(s){const t=D.frames.push({run:s});return D.nextDraw===null&&(D.nextDraw=N.window.requestAnimationFrame(D._draw)),t},timeout(s,t){t=t||0;const e=D.timer().now()+t,n=D.timeouts.push({run:s,time:e});return D.nextDraw===null&&(D.nextDraw=N.window.requestAnimationFrame(D._draw)),n},immediate(s){const t=D.immediates.push(s);return D.nextDraw===null&&(D.nextDraw=N.window.requestAnimationFrame(D._draw)),t},cancelFrame(s){s!=null&&D.frames.remove(s)},clearTimeout(s){s!=null&&D.timeouts.remove(s)},cancelImmediate(s){s!=null&&D.immediates.remove(s)},_draw(s){let t=null;const e=D.timeouts.last();for(;(t=D.timeouts.shift())&&(s>=t.time?t.run():D.timeouts.push(t),t!==e););let n=null;const i=D.frames.last();for(;n!==i&&(n=D.frames.shift());)n.run(s);let r=null;for(;r=D.immediates.shift();)r();D.nextDraw=D.timeouts.first()||D.frames.first()?N.window.requestAnimationFrame(D._draw):null}},aa=function(s){const t=s.start,e=s.runner.duration(),n=t+e;return{start:t,duration:e,end:n,runner:s.runner}},ca=function(){const s=N.window;return(s.performance||s.Date).now()};class Ai extends Ie{constructor(t=ca){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(aa);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 D.cancelFrame(this._nextFrame),this._nextFrame=null,t?this._stepImmediate():this._paused?this:(this._nextFrame=D.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)}}T({Element:{timeline:function(s){return s==null?(this._timeline=this._timeline||new Ai,this._timeline):(this._timeline=s,this)}}});class et extends Ie{constructor(t){super(),this.id=et.id++,t=t??me.duration,t=typeof t=="function"?new qe(t):t,this._element=null,this._timeline=null,this.done=!1,this._queue=[],this._duration=typeof t=="number"&&t,this._isDeclarative=t instanceof qe,this._stepper=this._isDeclarative?t:new kn,this._history={},this.enabled=!0,this._time=0,this._lastTime=0,this._reseted=!0,this.transforms=new S,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??me.duration,e=e??me.delay,n=n||"last",typeof t=="object"&&!(t instanceof cs)&&(e=t.delay??e,n=t.when??n,r=t.swing||r,i=t.times??i,o=t.wait??o,t=t.duration??me.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 S,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 kn(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,x=Math.pow(-1,_)*(d%(i+n))/n+_;return Math.max(Math.min(x,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||Rs,runner:e||Rs,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 Ai||(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 S,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 Ge{constructor(t=new S,e=-1,n=!0){this.transforms=t,this.id=e,this.done=n}clearTransformsFromQueue(){}}I([et,Ge],{mergeWith(s){return new Ge(s.transforms.lmultiply(this.transforms),s.id)}});const Si=(s,t)=>s.lmultiplyO(t),xi=s=>s.transforms;function ha(){const t=this._transformationRunners.runners.map(xi).reduce(Si,new S);this.transform(t),this._transformationRunners.merge(),this._transformationRunners.length()===1&&(this._frameId=null)}class la{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 Ge).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}}T({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(xi).reduce(Si,new S)},_addRunner(s){this._transformationRunners.add(s),D.cancelImmediate(this._frameId),this._frameId=D.immediate(ha.bind(this))},_prepareRunner(){this._frameId==null&&(this._transformationRunners=new la().add(new Ge(new S(this))))}}});const ua=(s,t)=>s.filter(e=>!t.includes(e));I(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 Mt(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=ua(a,r);if(c.length){const l=this.element()[s](c),u=new Se(i.from()).valueOf();Object.assign(u,l),i.from(u)}const h=new Se(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 Mt(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=S.isMatrixLike(s);e=s.affine!=null?s.affine:e??!n;const i=new Mt(this._stepper).type(e?De:S);let r,o,a,c,h;function l(){o=o||this.element(),r=r||Sn(s,o),h=new S(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 S({...s,origin:[d,g]}),x=this._isDeclarative&&a?a:h;if(e){_=_.decompose(d,g),x=x.decompose(d,g);const R=_.rotate,Z=x.rotate,K=[R-360,R,R+360],rt=K.map(hn=>Math.abs(hn-Z)),gt=Math.min(...rt),Ut=rt.indexOf(gt);_.rotate=K[Ut]}t&&(n||(_.rotate=s.rotate||0),this._isDeclarative&&c&&(x.rotate=c)),i.from(x),i.to(_);const k=i.at(m);return c=k.rotate,a=new S(k),this.addTransform(a),o._addRunner(this),i.done()}function f(m){(m.origin||"center").toString()!==(s.origin||"center").toString()&&(r=Sn(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 Mt(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 Mt(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 Mt(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 L(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)}});I(et,{rx:rs,ry:os,from:wi,to:_i});C(et,"Runner");class ls extends V{constructor(t,e=t){super($("svg",t),e),this.namespace()}defs(){return this.isRoot()?st(this.node.querySelector("defs"))||this.put(new is):this.root().defs()}isRoot(){return!this.node.parentNode||!(this.node.parentNode instanceof N.window.SVGElement)&&this.node.parentNode.nodeName!=="#document-fragment"}namespace(){return this.isRoot()?this.attr({xmlns:Qn,version:"1.1"}).attr("xmlns:xlink",Oe,un):this.root().namespace()}removeNamespace(){return this.attr({xmlns:null,version:null}).attr("xmlns:xlink",null,un).attr("xmlns:svgjs",null,un)}root(){return this.isRoot()?this:super.root()}}T({Container:{nested:H(function(){return this.put(new ls)})}});C(ls,"Svg",!0);let rn=class extends V{constructor(t,e=t){super($("symbol",t),e)}};T({Container:{symbol:H(function(){return this.put(new rn)})}});C(rn,"Symbol");function fa(s){return this._build===!1&&this.clear(),this.node.appendChild(N.document.createTextNode(s)),this}function da(){return this.node.getComputedTextLength()}function pa(s,t=this.bbox()){return s==null?t.x:this.attr("x",this.attr("x")+s-t.x)}function ma(s,t=this.bbox()){return s==null?t.y:this.attr("y",this.attr("y")+s-t.y)}function ga(s,t,e=this.bbox()){return this.x(s,e).y(t,e)}function ya(s,t=this.bbox()){return s==null?t.cx:this.attr("x",this.attr("x")+s-t.cx)}function wa(s,t=this.bbox()){return s==null?t.cy:this.attr("y",this.attr("y")+s-t.cy)}function _a(s,t,e=this.bbox()){return this.cx(s,e).cy(t,e)}function ba(s){return this.attr("x",s)}function va(s){return this.attr("y",s)}function Aa(s,t){return this.ax(s).ay(t)}function Sa(s){return this._build=!!s,this}const Ei=Object.freeze(Object.defineProperty({__proto__:null,amove:Aa,ax:ba,ay:va,build:Sa,center:_a,cx:ya,cy:wa,length:da,move:ga,plain:fa,x:pa,y:ma},Symbol.toStringTag,{value:"Module"}));class U 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(xn(this.node))return;const o=N.window.getComputedStyle(this.node).getPropertyValue("font-size"),a=i*new E(o);this.dom.newLined&&(this.attr("x",e.attr("x")),this.text()===`
3
+ `?n+=a:(this.attr("dy",r?a+n:0),n=0))}),this.fire("rebuild")}return this}setData(t){return this.dom=t,this.dom.leading=new E(t.leading||1.3),this}writeDataToDom(){return ni(this,this.dom,{leading:1.3}),this}text(t){if(t===void 0){const e=this.node.childNodes;let n=0;t="";for(let i=0,r=e.length;i<r;++i){if(e[i].nodeName==="textPath"||xn(e[i])){i===0&&(n=i+1);continue}i!==n&&e[i].nodeType!==3&&st(e[i]).dom.newLined===!0&&(t+=`
4
4
  `),t+=e[i].textContent}return t}if(this.clear().build(!0),typeof t=="function")t.call(this,this);else{t=(t+"").split(`
5
- `);for(let e=0,n=t.length;e<n;e++)this.newLine(t[e])}return this.build(!1).rebuild()}}E(F,Ai);T({Container:{text:R(function(s=""){return this.put(new F).text(s)}),plain:R(function(s=""){return this.put(new F).plain(s)})}});N(F,"Text");class rn extends et{constructor(t,e=t){super(H("tspan",t),e),this._build=!1}dx(t){return this.attr("dx",t)}dy(t){return this.attr("dy",t)}newLine(){this.dom.newLined=!0;const t=this.parent();if(!(t instanceof F))return this;const e=t.index(this),n=I.window.getComputedStyle(this.node).getPropertyValue("font-size"),i=t.dom.leading*new k(n);return this.dy(e?i:0).attr("x",t.x())}text(t){return t==null?this.node.textContent+(this.dom.newLined?`
6
- `:""):(typeof t=="function"?(this.clear().build(!0),t.call(this,this),this.build(!1)):this.plain(t),this)}}E(rn,Ai);T({Tspan:{tspan:R(function(s=""){const t=new rn;return this._build||this.clear(),this.put(t).text(s)})},Text:{newLine:function(s=""){return this.tspan(s).newLine()}}});N(rn,"Tspan");class ls extends et{constructor(t,e=t){super(H("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 k(t).divide(2))}}E(ls,{x:hi,y:li,cx:ui,cy:fi,width:di,height:pi});T({Container:{circle:R(function(s=0){return this.put(new ls).size(s).move(0,0)})}});N(ls,"Circle");class Nn extends J{constructor(t,e=t){super(H("clipPath",t),e)}remove(){return this.targets().forEach(function(t){t.unclip()}),super.remove()}targets(){return ce("svg [clip-path*="+this.id()+"]")}}T({Container:{clip:R(function(){return this.defs().put(new Nn)})},Element:{clipper(){return this.reference("clip-path")},clipWith(s){const t=s instanceof Nn?s:this.parent().clip().add(s);return this.attr("clip-path","url(#"+t.id()+")")},unclip(){return this.attr("clip-path",null)}}});N(Nn,"ClipPath");class xi extends dt{constructor(t,e=t){super(H("foreignObject",t),e)}}T({Container:{foreignObject:R(function(s,t){return this.put(new xi).size(s,t)})}});N(xi,"ForeignObject");function Sa(s,t){return this.children().forEach(e=>{let n;try{n=e.node instanceof xr().SVGSVGElement?new L(e.attr(["x","y","width","height"])):e.bbox()}catch{return}const i=new A(e),r=i.translate(s,t).transform(i.inverse()),o=new B(n.x,n.y).transform(r);e.move(o.x,o.y)}),this}function va(s){return this.dmove(s,0)}function Aa(s){return this.dmove(0,s)}function xa(s,t=this.bbox()){return s==null?t.height:this.size(t.width,s,t)}function ka(s=0,t=0,e=this.bbox()){const n=s-e.x,i=t-e.y;return this.dmove(n,i)}function Ta(s,t,e=this.bbox()){const n=ae(this,s,t,e),i=n.width/e.width,r=n.height/e.height;return this.children().forEach(o=>{const a=new B(e).transform(new A(o).inverse());o.scale(i,r,a.x,a.y)}),this}function Oa(s,t=this.bbox()){return s==null?t.width:this.size(s,t.height,t)}function Ea(s,t=this.bbox()){return s==null?t.x:this.move(s,t.y,t)}function Ia(s,t=this.bbox()){return s==null?t.y:this.move(t.x,s,t)}const ki=Object.freeze(Object.defineProperty({__proto__:null,dmove:Sa,dx:va,dy:Aa,height:xa,move:ka,size:Ta,width:Oa,x:Ea,y:Ia},Symbol.toStringTag,{value:"Module"}));class z extends J{constructor(t,e=t){super(H("g",t),e)}}E(z,ki);T({Container:{group:R(function(){return this.put(new z)})}});N(z,"G");class Ze extends J{constructor(t,e=t){super(H("a",t),e)}target(t){return this.attr("target",t)}to(t){return this.attr("href",t,Oe)}}E(Ze,ki);T({Container:{link:R(function(s){return this.put(new Ze).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 Ze,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(Ze,"A");class Mn extends J{constructor(t,e=t){super(H("mask",t),e)}remove(){return this.targets().forEach(function(t){t.unmask()}),super.remove()}targets(){return ce("svg [mask*="+this.id()+"]")}}T({Container:{mask:R(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 Ti extends dt{constructor(t,e=t){super(H("stop",t),e)}update(t){return(typeof t=="number"||t instanceof k)&&(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 k(t.offset)),this}}T({Gradient:{stop:function(s,t,e){return this.put(new Ti).update(s,t,e)}}});N(Ti,"Stop");function Na(s,t){if(!s)return"";if(!t)return s;let e=s+"{";for(const n in t)e+=Sr(n)+":"+t[n]+";";return e+="}",e}class Dn extends dt{constructor(t,e=t){super(H("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(Na(t,e))}}T("Dom",{style(s,t){return this.put(new Dn).rule(s,t)},fontface(s,t,e){return this.put(new Dn).font(s,t,e)}});N(Dn,"Style");class us extends F{constructor(t,e=t){super(H("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")}}T({Container:{textPath:R(function(s,t){return s instanceof F||(s=this.text(s)),s.path(t)})},Text:{path:R(function(s,t=!0){const e=new us;s instanceof he||(s=this.defs().path(s)),e.attr("href","#"+s,Oe);let n;if(t)for(;n=this.node.firstChild;)e.node.appendChild(n);return this.put(e)}),textPath(){return this.findOne("textPath")}},Path:{text:R(function(s){return s instanceof F||(s=new F().addTo(this.parent()).text(s)),s.path(this)}),targets(){return ce("svg textPath").filter(s=>(s.attr("href")||"").includes(this.id()))}}});us.prototype.MorphArray=Wt;N(us,"TextPath");class on extends et{constructor(t,e=t){super(H("use",t),e)}use(t,e){return this.attr("href",(e||"")+"#"+t,Oe)}}T({Container:{use:R(function(s,t){return this.put(new on).use(s,t)})}});N(on,"Use");E([hs,sn,Ne,be,Fe],X("viewbox"));E([Se,Ce,De,he],X("marker"));E(F,X("Text"));E(he,X("Path"));E(ss,X("Defs"));E([F,rn],X("Tspan"));E([Re,nn,Ie,tt],X("radius"));E(Ee,X("EventTarget"));E(xt,X("Dom"));E(dt,X("Element"));E(et,X("Shape"));E([J,mi],X("Container"));E(Ie,X("Gradient"));E(tt,X("Runner"));$t.extend(_r());Jo([k,D,L,A,Qt,kt,Wt,B]);Vo();class te{constructor(t={}){S(this,"tileWidth");S(this,"tileHeight");S(this,"imageHostPath");S(this,"imageHostUrl");S(this,"imageExt");S(this,"scale");S(this,"svgSprite");this.scale=t.scale??1,this.imageHostPath=t.imageHostPath??"",this.imageHostUrl=t.imageHostUrl??"",this.imageExt=t.imageExt??"svg",this.tileWidth=vt.WIDTH*this.scale,this.tileHeight=vt.HEIGHT*this.scale,this.svgSprite=t.svgSprite??!1}getDiffTileHeightWidth(t){const e=t.imageSize(this.scale);return(e.baseHeight-e.baseWidth)/2}image(t){let e=new Ne().load(this.buildURL(t));return this.svgSprite&&(e=new on().use(te.buildID(t))),t instanceof g&&t.has(b.COLOR_GRAYSCALE)&&e.css({filter:"contrast(65%)"}),e}createImage(t,e,n){const i=t.imageSize(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=t.imageSize(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:qn,size:a}).dx(c).dy(h);const u=new z;return u.add(r).add(l).translate(e,n),u}createRotate90Image(t,e,n,i=!1){const r=this.createImage(t,0,0),o=t.imageSize(this.scale),a=o.baseWidth/2,c=o.baseHeight/2,h=e+this.getDiffTileHeightWidth(t),l=i?n-this.getDiffTileHeightWidth(t):n,u=new z;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==d.BACK?0:t.n;return`${t.t}${e}`}buildURL(t){const e=`${te.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:`${this.imageHostPath}${e}`}}class fs extends te{constructor(){super(...arguments);S(this,"blockMargin",vt.WIDTH*vt.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const n=new z;let i=0;for(let r of e.tiles){const o=r.imageSize(this.scale),a=r.has(b.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),c=r.has(b.HORIZONTAL)?this.getDiffTileHeightWidth(r):0,h=a(r,i,c);n.add(h),i+=o.width}return n}createBlockPonChiKan(e){const n=e.tiles.findIndex(o=>o.has(b.HORIZONTAL));let i=0;const r=new z;if(e.type==_.SHO_KAN){let o=n;for(let a=0;a<e.tiles.length;a++)e.tiles[a].has(b.HORIZONTAL)&&(o=a);for(let a=0;a<e.tiles.length;a++){const c=e.tiles[a].imageSize(this.scale);if(a==o)continue;if(a==n){const u=e.tiles[n],f=e.tiles[o],m=u.imageSize(this.scale),p=this.createRotate90Image(u,0,0,!0),y=this.createRotate90Image(f,0,m.height,!0);r.add(new z().translate(i,0).add(p).add(y)),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==_.CHI){const o=this.createRotate90Image(e.tiles[n],i,this.getDiffTileHeightWidth(e.tiles[n]));i+=e.tiles[n].imageSize(this.scale).width,r.add(o);for(let a=0;a<e.tiles.length;a++){if(a==n)continue;const c=e.tiles[a].imageSize(this.scale),h=this.createImage(e.tiles[a],i,0);i+=c.width,r.add(h)}return r}for(let o=0;o<e.tiles.length;o++){const a=o==n?this.createRotate90Image.bind(this):this.createImage.bind(this),c=o==n?this.getDiffTileHeightWidth(e.tiles[o]):0,h=e.tiles[o].imageSize(this.scale),l=a(e.tiles[o],i,c);i+=h.width,r.add(l)}return r}}const Ma=s=>{const t=s.scale;return{[_.CHI]:function(n){const i=n.imageSize(t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[_.PON]:function(n){const i=n.imageSize(t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[_.DAI_KAN]:function(n){const i=n.imageSize(t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[_.SHO_KAN]:function(n){const i=n.imageSize(t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[_.AN_KAN]:function(n){assert(n instanceof U,`block type is not ankan: ${n.type}`);const i=n.imageSize(t),r=n.tilesWithBack.filter(a=>a.t!==d.BACK);assert(r!=null&&r.length==2,`back tile must be two but ${n}`);const o=s.createBlockHandDiscard(new U([r[0],r[1],r[0],r[1]]));return{...i,e:o}},[_.IMAGE_DORA]:function(n){const i=n.imageSize(t),r=new z,o=s.createTextImage(n.tiles[0],0,0,"(ドラ)");return r.add(o),{...i,e:r}},[_.TSUMO]:function(n){const i=n.imageSize(t),r=new z,o=s.createTextImage(n.tiles[0],0,0,"(ツモ)");return r.add(o),{...i,e:r}},[_.HAND]:function(n){const i=n.imageSize(t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[_.IMAGE_DISCARD]:function(n){const i=n.imageSize(t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[_.THREE]:function(n){throw new Error("three is unsupported")},[_.RUN]:function(n){throw new Error("run is unsupported")},[_.UNKNOWN]:function(n){if(n.tiles.some(o=>o.has(b.TSUMO)||o.has(b.DORA)))throw new Error("found an unknown block with operator tiles");const i=n.imageSize(t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[_.PAIR]:function(n){throw new Error("pair is unsupported")},[_.ISOLATED]:function(n){throw new Error("isolated is unsupported")}}},Xt=(s,t)=>{const{maxHeight:e,sumWidth:n}=t.reduce((l,u)=>{const f=u.imageSize(s.scale);return{maxHeight:f.height>l.maxHeight?f.height:l.maxHeight,sumWidth:l.sumWidth+f.width}},{maxHeight:0,sumWidth:0}),i=e,r=n+(t.length-1)*s.blockMargin,o=Ma(s),a=[];for(let l of t){const u=o[l.type],f=u(l);a.push(f)}const c=new z;let h=0;for(let l of a){const u=i-l.height,f=new z().translate(h,u);f.add(l.e),c.add(f),h+=l.width+s.blockMargin}return{e:c,width:r,height:i}},Da=(s,t,e={},n={responsive:!1})=>{const i=new fs(e),r=Xt(i,t);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Oi=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(let e of Object.values(d)){if(e==d.BACK){t.push(te.buildID(new g(e,0)));continue}t.push(...s.map(n=>te.buildID(new g(e,n))).flat())}return t},Ca=s=>{const t=Oi(),e=[];return s.each((n,i)=>{const r=i[n];if(r instanceof on){const a=r.attr("href").substring(1);t.includes(a)&&e.push(a)}}),e},Ra=s=>{const t=Oi(),e=Ca(s);s.each((n,i)=>{const r=i[n];r instanceof sn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},Ha=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 z().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 z,n=Ha(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Xn(r,_.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},$a=(s,t,e)=>{const n=t.font,i=t.textWidth,r=t.textHeight,o=new z,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,p=new F().plain(e.round).font(n).move(m,0);o.add(p),f+=25*s.scale;const y=s.tileHeight,w=new z().size(h,y).translate(0,f),x={family:n.family,size:n.size*.7},O=s.createStick(1e3).size(h,l).move(0,0),$=new F().plain(c.toString()).font(x).attr({x:h,y:l});w.add(O),w.add($);const nt=s.createStick(100).size(h,l).move(0,l+l),K=new F().plain(a.toString()).font(x).attr({x:h,y:l*3});w.add(nt),w.add(K);const rt=s.createImage(e.doras[0],0,0).move(h+i,0);return w.add(rt),o.add(p),o.add(w),{e:o,width:h+s.tileWidth+i,height:f+s.tileHeight}},Wa=(s,t,e=0)=>{const n=Xt(s,t.front),i=Xt(s,t.right),r=Xt(s,t.opposite),o=Xt(s,t.left),a=[n.width,i.width,r.width,o.width].reduce((y,w)=>Math.max(y,w)),c=Math.max(e+s.tileHeight*2+s.blockMargin*2,a+s.tileWidth*2+s.blockMargin),h=c,l=new z().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),p=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(p),{e:l,width:c,height:h}},Ba=s=>{const t=Object.values(tn),e=t.indexOf(s);return[...t.slice(e),...t.slice(0,e)]},za=(s,t,e)=>{const n=s.tileWidth*5+s.tileHeight*1,i=new z,r=new Re().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=$a(s,t,e);l.e.translate(n/2-l.width/2,n/2-l.height/2);const u=(cn,Ts,ar)=>{const cr=`${cn} ${Ts}`,hr=new F().plain(cr).font(o).attr(ar);return{e:new z().add(hr),width:a+h*Ts.toString().length,height:c}},[f,m,p,y]=Ba(e.frontPlace),w=e.scores,O=u(f,w.front,{x:n/2,y:n,"dominant-baseline":"text-after-edge","text-anchor":"middle"}).e;let $=u(m,w.right,{"dominant-baseline":"text-after-edge","text-anchor":"middle"});const nt=ht($.e,$.width,$.height,270).translate(n,n/2-$.width);let K=u(p,w.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const rt=ht(K.e,K.width,K.height,180).translate(n/2-K.width,-K.height);let pt=u(y,w.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Kt=ht(pt.e,pt.width,pt.height,90).translate(-pt.height,n/2);return i.add(l.e),i.add(O),i.add(nt),i.add(rt),i.add(Kt),{e:i,width:n,height:n}},Pa=(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((O,$)=>Math.max(O,$)),a=s.tileWidth*5+s.tileHeight*1,c=o,h=a+o*2+s.blockMargin,l=h,u=new z().size(h,l),f=h/2-a/2,m=l/2-a/2,p=ht(e.e,a,c,0).translate(f,l-c),y=ht(n.e,a,c,270).translate(h-c,m),w=ht(i.e,a,c,180).translate(f,0),x=ht(r.e,a,c,90).translate(0,m);return u.add(p),u.add(y),u.add(w),u.add(x),{e:u,width:h,height:l}},Ei=(s,t,e,n,i)=>{const r=new z,o=Pa(s,n),a=Wa(s,e,o.height),c=za(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}},ja=(s,t,e={},n,i={responsive:!1})=>{const r=new fs(e),o=n,{discards:a,hands:c,scoreBoard:h}=Ii(t),l=Ei(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 mt;function La(s){return{lang:(s==null?void 0:s.lang)??(mt==null?void 0:mt.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(mt==null?void 0:mt.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(mt==null?void 0:mt.abortPipeEarly)}}var mn;function Ka(s){return mn==null?void 0:mn.get(s)}var gn;function Ua(s){return gn==null?void 0:gn.get(s)}var yn;function Fa(s,t){var e;return(e=yn==null?void 0:yn.get(s))==null?void 0:e.get(t)}function ee(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 Bt(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)??ee(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??Fa(s.reference,c.lang)??(h?Ua(c.lang):null)??n.message??Ka(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 qa(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Cn(s,t){return{kind:"validation",type:"max_value",reference:Cn,async:!1,expects:`<=${s instanceof Date?s.toJSON():ee(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value>this.requirement&&Bt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ee(e.value)}),e}}}function Rn(s,t){return{kind:"validation",type:"min_value",reference:Rn,async:!1,expects:`>=${s instanceof Date?s.toJSON():ee(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value<this.requirement&&Bt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():ee(e.value)}),e}}}function Ga(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function Ye(s){return{kind:"schema",type:"number",reference:Ye,expects:"number",async:!1,message:s,_run(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Bt(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=Ga(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 Hn(s,t){return{kind:"schema",type:"picklist",reference:Hn,expects:qa(s.map(ee),"|"),async:!1,options:s,message:t,_run(e,n){return this.options.includes(e.value)?e.typed=!0:Bt(this,"type",e,n),e}}}function ne(s,t){return{kind:"schema",type:"strict_object",reference:ne,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];Bt(this,"type",e,n,{input:a,expected:"never",path:[{type:"object",origin:"value",input:i,key:o,value:a}]});break}}}else Bt(this,"type",e,n);return e}}}function Xe(s){return{kind:"schema",type:"string",reference:Xe,expects:"string",async:!1,message:s,_run(t,e){return typeof t.value=="string"?t.typed=!0:Bt(this,"type",t,e),t}}}function Hs(...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 Za(s,t,e){const n=s._run({typed:!1,value:t},La(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const Pe=it(ne({discard:it(Xe(),""),hand:it(Xe(),""),score:it(Ye(),25e3)}),{discard:"",hand:"",score:25e3}),Ya=ne({[v.E]:Pe,[v.S]:Pe,[v.W]:Pe,[v.N]:Pe}),Ot={round:P.E1,sticks:{reach:0,dead:0},doras:v.S,front:v.E},Xa=it(ne({round:it(Hn(Object.keys(Gn)),Ot.round),sticks:it(ne({reach:it(Hs(Ye(),Rn(0,""),Cn(9,"")),Ot.sticks.reach),dead:it(Hs(Ye(),Rn(0,""),Cn(9,"")),Ot.sticks.dead)}),Ot.sticks),doras:it(Xe(),Ot.doras),front:it(Hn(Object.keys(tn)),Ot.front)}),Ot),Ja=ne({...Ya.entries,board:Xa}),Ii=s=>{const t=Ni(s);return Mi(t)},Ni=s=>{const t=Va(s),e=Za(Ja,t);if(!e.success)throw e.issues;return e.output},Va=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]=tc([...n]);r.board=h;for(let u=0;u<l;u++)n.shift()}else{const[h,l]=Qa([...n]);r[c]=h;for(let u=0;u<l;u++)n.shift()}}return r},lt=(s,t)=>s.replace(t,"").replace(":","").trim(),Qa=s=>{const t="hand",e="discard",n="score";let i={},r=0;for(;r<s.length;r++){const o=s[r];if(o.startsWith(t))i.hand=lt(o,t);else if(o.startsWith(e))i.discard=lt(o,e);else if(o.startsWith(n))i.score=Number(lt(o,n));else break}return[i,r]},tc=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead";let a={},c=0;for(;c<s.length;c++){const h=s[c];if(h.startsWith(t))a.doras=lt(h,t);else if(h.startsWith(e))a.round=lt(h,e);else if(h.startsWith(n))a.front=lt(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(lt(l,r))),l.startsWith(o)&&(a.sticks.dead=Number(lt(l,o))),u.startsWith(r)&&(a.sticks.reach=Number(lt(u,r))),u.startsWith(o)&&(a.sticks.dead=Number(lt(u,o))),a.sticks.dead!=null&&c++,a.sticks.reach!=null&&c++}else break}return[a,c]},Mi=s=>{const t=s.board.front,e=ec(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:Gn[s.board.round],frontPlace:tn[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}},ec=s=>({front:s,right:At(s),opposite:At(At(s)),left:Xs(s)});class He{constructor(t,e=!1){S(this,"data");this.data={[d.M]:[0,0,0,0,0,0,0,0,0,0],[d.P]:[0,0,0,0,0,0,0,0,0,0],[d.S]:[0,0,0,0,0,0,0,0,0,0],[d.Z]:[0,0,0,0,0,0,0,0],[d.BACK]:["untouchable",0],called:[],reached:!1,tsumo:null},this.init(t,e)}init(t,e){const n=new Q(t).parse();for(let i of n){if(i.isCalled()){this.data.called=[...this.called,i];continue}else if(i.is(_.TSUMO)){const r=i.tiles[0];this.inc([r]),this.data.tsumo=r;continue}else if(i.is(_.HAND)){this.inc(i.tiles);continue}else if(t.split("").every(r=>r===d.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(let e of Object.values(d))for(let n=1;n<this.getArrayLen(e);n++){let i=this.get(e,n);e!=d.Z&&n==5&&this.get(e,0)>0&&(i-=this.get(e,0),t.push(new g(e,0)));for(let r=0;r<i;r++)t.push(new g(e,n))}if(this.drawn!=null){const e=this.drawn,n=t.findIndex(i=>i.equals(e));C(n>=0,`hand has drawn: ${this.drawn} but no tile in hands: ${t.join("")}`),t[n]=t[n].clone({add:b.TSUMO})}return C(t.length>0,`no tiles in hand ${t.length}, called: ${this.called}, data: ${JSON.stringify(this.data,null,2)}`),t}toString(){let t="";for(let r of this.called)t=`${t},${r.toString()}`;let e="";this.drawn&&(e=`,${this.drawn.toString()}`);const n=this.hands.filter(r=>!r.has(b.TSUMO));return`${new en(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))}getArrayLen(t){return this.data[t].length}sum(t){let e=0;for(let n=1;n<this.getArrayLen(t);n++)e+=this.get(t,n);return e}get(t,e){return t==d.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(let n of t){if(n.t!=d.BACK&&this.get(n.t,n.n)>=4)throw this.dec(e),new Error(`unable to increase ${n} in ${this.toString()}`);if(e.push(n),j(n)&&(this.data[n.t][5]+=1),n.t==d.BACK?this.data[n.t][1]+=1:this.data[n.t][n.n]+=1,V(n)&&this.get(n.t,5)==4&&this.get(n.t,0)==0){this.data[n.t][0]=1;const i=e.pop().clone({n:0});e.push(i)}}return e}dec(t){const e=[];for(let n of t){if(this.get(n.t,n.n)<1)throw this.inc(e),new Error(`unable to decrease ${n.toString()} in ${this.toString()}`);if(e.push(n),j(n)&&(this.data[n.t][5]-=1),n.t==d.BACK?this.data[n.t][1]-=1:this.data[n.t][n.n]-=1,V(n)&&this.get(n.t,5)==0&&this.get(n.t,0)>0){this.data[n.t][0]=0;const i=e.pop().clone({n:0});e.push(i)}}return e}draw(t){const e=t.clone({add:b.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){if(!(t instanceof ft||t instanceof ct||t instanceof ut))throw new Error(`unexpected input ${t} ${t.type}`);const e=t.tiles.filter(n=>!n.has(b.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){let e=t.tiles[0];j(e)&&(e=new g(e.t,5)),this.dec([e,e,e,e]),this.data.called=[...this.called,t],this.data.tsumo=null;return}if(t instanceof at){const e=this.data.called.findIndex(i=>i.is(_.PON)&&i.tiles[0].equals(t.tiles[0],!0));if(e==-1)throw new Error(`unable to find ${t.tiles[0]}`);let n=t.tiles[0];j(n)&&(n=new g(n.t,5)),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 He(this.toString());return t.data.reached=this.data.reached,t}}class $e{constructor(t){S(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(let n of Object.values(d))if(n!=d.BACK)for(let i=1;i<this.hand.getArrayLen(n);i++)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(let n of Object.values(d)){if(n==d.BACK)continue;const i=n==d.Z?Ae:yt;for(let 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],r=d.Z;for(let m=1;m<this.hand.getArrayLen(r);m++)this.hand.get(r,m)>=3?i[0]++:this.hand.get(r,m)==2?i[1]++:this.hand.get(r,m)==1&&i[2]++;const o=[0,0,0],a=this.hand.get(d.BACK,0),c=a%3;o[0]=Math.floor(a/3),c==2&&(o[1]=1),c==1&&(o[2]=1);let h=13;const l=this.commonByType(d.M),u=this.commonByType(d.P),f=this.commonByType(d.S);for(let m of[l.patternA,l.patternB])for(let p of[u.patternA,u.patternB])for(let y of[f.patternA,f.patternB]){const w=[this.hand.called.length,0,0];for(let O=0;O<3;O++)w[O]+=m[O]+p[O]+y[O]+i[O]+o[O];let x=this.calcCommon(w[0],w[1],w[2],n);x<h&&(h=x)}return h};let e=t(!1);for(let n of Object.values(d))for(let i=1;i<this.hand.getArrayLen(n);i++)if(this.hand.get(n,i)>=2){const r=this.hand.dec([new g(n,i),new g(n,i)]),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}commonByType(t,e=1){if(t==d.BACK||t==d.Z)throw new Error(`expect number type but ${t}`);if(e>9)return this.groupRemainingTiles(t);let n=this.commonByType(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 g(t,e),new g(t,e+1),new g(t,e+2)]),r=this.commonByType(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 g(t,e),new g(t,e),new g(t,e)]),r=this.commonByType(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(let r=1;r<this.hand.getArrayLen(t);r++)i+=this.hand.get(t,r),r<=7&&this.hand.get(t,r+1)==0&&this.hand.get(t,r+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 Di{constructor(t){S(this,"hand");this.hand=t}calc(t){return this.hand.drawn!=null&&(t=this.hand.drawn),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(b.TSUMO)?b.TSUMO:b.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,!0));if(u<0)continue;const f=Ci(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(let[o,a,c]of i){const l=t[o].map(m=>m.clone()),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(let e of Object.values(d))if(e!=d.BACK)for(let n=1;n<this.hand.getArrayLen(e);n++){const i=this.hand.get(e,n);if(i==2)t.push(new Z(new g(e,n),new g(e,n)));else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e="";for(let n of Object.values(d)){if(n==d.BACK)continue;const i=n==d.Z?Ae:yt;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Yn(new g(n,r)));else if(this.hand.get(n,r)==2&&e=="")t.unshift(new Z(new g(n,r),new g(n,r)));else return[]}return[t]}nineGates(){const t=(e,n,i)=>i.includes(this.hand.get(e,n));for(let e of Object.values(d)){if(e==d.BACK||e==d.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 en(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(let e of Object.values(d))for(let n=1;n<this.hand.getArrayLen(e);n++)if(this.hand.get(e,n)>=2){const i=this.hand.dec([new g(e,n),new g(e,n)]),r=this.commonAll().filter(o=>o.length==4).map(o=>(o.unshift(new Z(i[0],i[1])),o));t=[...t,...r],this.hand.inc(i)}return t}commonAll(){const t=()=>{const r=[],o=d.Z;for(let a=1;a<this.hand.getArrayLen(o);a++)if(this.hand.get(o,a)!=0){if(this.hand.get(o,a)!=3)return[];r.push(new ot([new g(o,a),new g(o,a),new g(o,a)]))}return r.length==0?[]:[r]},e=()=>{const r=[],o=d.BACK,a=this.hand.get(o,0);return a<3?[]:(Array(Math.floor(a/3)).fill(void 0).map(c=>{r.push(new ot([new g(o,0),new g(o,0),new g(o,0)]))}),r.length==0?[]:[r])},n=[this.commonByType(d.M),this.commonByType(d.P),this.commonByType(d.S),t(),e(),[this.hand.called.concat()]].sort((r,o)=>o.length-r.length),i=n[0].concat();for(let r=0;r<i.length;r++)for(let o=1;o<n.length;o++)for(let a of n[o])i[r]=[...i[r],...a];return i}commonByType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.commonByType(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 g(t,e),new g(t,e+1),new g(t,e+2)]),r=this.commonByType(t,e);this.hand.inc(i),r.length==0&&r.push([]);for(let o of r)o.unshift(new bt([i[0],i[1],i[2]])),n.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec([new g(t,e),new g(t,e),new g(t,e)]),r=this.commonByType(t,e);this.hand.inc(i),r.length==0&&r.push([]);for(let o of r)o.unshift(new ot([i[0],i[1],i[2]])),n.push(o)}return n}}const Ae=[1,2,3,4,5,6,7],yt=[1,9],Le=s=>{var e;const t=s.boardContext;return{...s,hand:s.hand.map(W.deserialize),boardContext:{...t,doraMarkers:t.doraMarkers.map(g.from),blindDoraMarkers:(e=t.blindDoraMarkers)==null?void 0:e.map(g.from)}}};class $n{constructor(t,e){S(this,"hand");S(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(n=>Ws(n)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(n=>Ws(n)),roundWind:g.from(e.round.substring(0,2)),myWind:g.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 p=0;p<e.length;p++){const y=e[p],w=y.points.reduce((x,O)=>x+O.double,0);(w>n[0]||w==n[0]&&y.fu>n[1])&&(i=p,n[0]=w,n[1]=y.fu)}const r=(p,y=100)=>Math.ceil(p/y)*y,o=n[1]!=25?r(n[1],10):25,a=n[0];let c=o*2**(a+2);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=6e3;break;case 7:case 6:c=4e3;break;case 5:c=2e3;break}a>13&&a<26&&(c=8e3);const h=e[i].hand.some(p=>p.tiles.some(y=>y.has(b.TSUMO))),l=this.cfg.orig.myWind,u=l==v.E,f=G(0);if(h){const p=this.cfg.sticks.dead*100;if(u){const y=r(c*2);f[v.E]+=y*3+p*3,f[v.S]-=y+p,f[v.W]-=y+p,f[v.N]-=y+p}else for(let y of Object.values(v)){if(y==l)continue;const w=y==v.E?2:1,x=r(c*w)+p;f[y]-=x,f[l]+=x}}else{const p=this.cfg.sticks.dead*300;if(this.cfg.orig.ronWind==null)throw new Error("ron wind is not specified in the parameters");const w=r(c*(u?6:4))+p;f[l]+=w,f[this.cfg.orig.ronWind]-=w}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(let 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(let 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(b.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(b.TSUMO)))&&n==30?[{name:e,double:1}]:[]}dD1(t){return t.some(n=>n.tiles.some(i=>i.t==d.Z||yt.includes(i.n)))?[]:[{name:"断么九",double:1}]}dE1(t){return this.minus()!=0?[]:$s(t)==1?[{name:"一盃口",double:1}]:[]}dF1(t){const e=[];return t.forEach(n=>{if(n instanceof Z)return;const i=n.tiles[0];i.t==d.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(let o of t)for(let a of o.tiles){for(let c of this.cfg.doras)a.equals(c,!0)&&e++;for(let c of this.cfg.blindDoras)a.equals(c,!0)&&i++;j(a)&&n++}const r=[];return e>0&&r.push({name:"ドラ",double:e}),n>0&&r.push({name:"赤ドラ",double:n}),this.hand.reached&&i>0&&r.push({name:"裏ドラ",double:i}),r}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=n=>n instanceof bt||n instanceof ct;for(let n of t){if(!e(n))continue;const i=Et(n);if(i.t==d.Z)continue;const r=[d.M,d.P,d.S].filter(c=>c!=i.t),o=t.some(c=>{const h=new g(r[0],i.n);return e(c)&&h.equals(Et(c),!0)}),a=t.some(c=>{const h=new g(r[1],i.n);return e(c)&&h.equals(Et(c),!0)});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof U||n instanceof at||n instanceof ut||n instanceof ot||n instanceof ft||n instanceof Z)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(n=>(n instanceof U||n instanceof ot)&&!n.tiles.some(i=>i.has(b.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(n=>n instanceof U||n instanceof at||n instanceof ut).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=n=>n instanceof U||n instanceof at||n instanceof ut||n instanceof ot||n instanceof ft;for(let n of t){if(!e(n))continue;const i=Et(n);if(i.t==d.Z)continue;const r=[d.M,d.P,d.S].filter(c=>c!=i.t),o=t.some(c=>{const h=new g(r[0],i.n);return e(c)&&h.equals(Et(c),!0)}),a=t.some(c=>{const h=new g(r[1],i.n);return e(c)&&h.equals(Et(c),!0)});if(o&&a)return[{name:"三色同刻",double:2}]}return[]}dG2(t){return t.filter(n=>{const i=n.tiles[0];return i.t==d.Z&&[5,6,7].includes(i.n)}).length==3?[{name:"小三元",double:2}]:[]}dH2(t){return t.every(n=>{const i=n.tiles[0].t==d.Z?Ae:yt;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof bt||n instanceof ct)?t.some(n=>n.tiles[0].t==d.Z)?t.every(n=>{const i=n.tiles[0].t==d.Z?Ae:yt;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];let e={[d.M]:[0,0,0],[d.S]:[0,0,0],[d.P]:[0,0,0]};for(let n of t){const i=Et(n);i.t!=d.BACK&&i.t!=d.Z&&(n instanceof bt||n instanceof ct)&&(i.n==1&&e[i.t][0]++,i.n==4&&e[i.t][1]++,i.n==7&&e[i.t][2]++)}for(let 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==d.Z))return[];for(let n of Object.values(d))if(t.every(r=>r.tiles[0].t==d.Z||r.tiles[0].t==n))return[{name:"混一色",double:3-this.minus()}];return[]}dB3(t){return t.length==7?[]:t.some(n=>n instanceof bt||n instanceof ct)?t.some(n=>n.tiles[0].t==d.Z)?[]:t.every(n=>n.tiles.some(i=>yt.includes(i.n)))?[{name:"純全帯么九色",double:3-this.minus()}]:[]:[]}dC3(t){return this.minus()!=0?[]:$s(t)==2?[{name:"ニ盃口",double:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==d.Z))return[];for(let e of Object.values(d)){if(e==d.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 Z&&n.tiles.some(i=>i.has(b.TSUMO)||i.has(b.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 ot&&!i.tiles.some(r=>r.has(b.RON))||i instanceof Z)?t.some(i=>i instanceof Z&&i.tiles.every(r=>r.has(b.TSUMO)||r.has(b.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 Z)&&i.tiles.some(r=>r.t==d.Z&&e.includes(r.n))).length==3?[{name:"大三元",double:13}]:[]}dE13(t){return t.every(n=>n.tiles[0].t==d.Z)?[{name:"字一色",double:13}]:[]}dF13(t){return t.every(n=>n.tiles.every(i=>i.t!=d.Z&&yt.includes(i.n)))?[{name:"清老頭",double:13}]:[]}dG13(t){return t.filter(n=>n instanceof U||n instanceof at||n instanceof ut).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==d.Z&&e.includes(o.n))).length==4?t.find(r=>r instanceof Z).tiles.some(r=>r.t==d.Z&&e.includes(r.n))?[{name:"小四喜",double:13}]:[{name:"大四喜",double:13}]:[]}dI13(t){const e=n=>!!(n.equals(new g(d.Z,6))||n.t==d.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(p=>p.tiles.some(y=>y.has(b.TSUMO)||y.has(b.RON))),a=this.minus()==1,c=o.tiles.some(p=>p.has(b.TSUMO)),h=(p,y)=>{const w=p.tiles[0];return w.t==d.Z&&[5,6,7].includes(w.n)||w.t==d.Z&&[i,r].includes(w.n)||yt.includes(w.n)?y*2:y};for(let p of t)switch(!0){case p instanceof ot:let y=p.tiles.some(w=>w.has(b.RON))?2:4;n+=h(p,y);break;case p instanceof ft:n+=h(p,2);break;case(p instanceof ut||p instanceof at):n+=h(p,8);break;case p instanceof U:n+=h(p,16);break}n+=(p=>{if(p instanceof ot)return 0;if(p instanceof Z)return 2;const y=p.tiles,w=y.findIndex(x=>x.has(b.TSUMO)||x.has(b.RON));return w==1||w==0&&y[2].n==9||w==2&&y[0].n==1?2:0})(o);let f=t.find(p=>p instanceof Z).tiles[0];f.t==d.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 Ci=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),$s=s=>{let t={};for(let n of s){if(!(n instanceof bt))continue;const i=Ci(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(let n in t)t[n]>=2&&e++;return e},Et=s=>[...s.tiles].sort(ye)[0],Ws=s=>{let t=j(s)?5:s.n,e=s.t;return new g(e,t%9+1)};class zt{static calcCandidates(t,e,n){C(e.length>0,"choices to discard is zero");const i=new Map;let r=Number.POSITIVE_INFINITY;for(let o of e){const a=t.dec([o]),c=zt.candidateTiles(t,n);t.inc(a);const h=n!=null&&n.arrangeRed&&j(o)?o.clone({n:5,removeAll:!0}):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=Number.POSITIVE_INFINITY,i=[];const r=new $e(t);for(let o of Object.values(d))if(o!=d.BACK)for(let a=1;a<t.getArrayLen(o);a++){if(t.get(o,a)>=4)continue;const c=new g(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}}static partialCandidateTiles(t,e){const n=new He(t,!0);return Array(13-n.hands.length).fill(void 0).map(()=>n.inc([new g(d.BACK,0)])),zt.candidateTiles(n,e)}}const Wn=()=>{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 Ri(s){var r;const t=["RON","DAI_KAN","PON","CHI"],e=s.map(o=>o.choices),i=$i(e,t).map(o=>s[o]);return{events:i,type:Wi(t,(r=i[0])==null?void 0:r.choices)}}function Hi(s){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_TILES","DISCARD"],e=s.map(o=>o.choices),i=$i(e,t).map(o=>s[o]);return{events:i,type:Wi(t,(r=i[0])==null?void 0:r.choices)}}function $i(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(nc(r,t)){const o=sc(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function nc(s,t){return t.some(e=>!!s[e])}function sc(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function Wi(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const pe=()=>{const s=Wn(),t=Wn(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},Bi=()=>{const s=Wn();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class xe{constructor(t){S(this,"reachValue",1e3);S(this,"m");this.m=t}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}restoreReachStick(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 ke{constructor(t,e){S(this,"pToW",{});S(this,"wToP",G(""));S(this,"round");S(this,"sticks");this.round=(e==null?void 0:e.round)??"1w1",this.sticks=(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=t;for(let n in this.pToW)this.wToP[this.pToW[n]]=n}update(){for(let t in this.pToW){const e=At(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=ge(this.round);this.round=t,this.update()}decrementReachStick(){this.sticks.reach--,C(this.sticks.reach>=0)}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 ds(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 zi{constructor(t=!1){S(this,"c",{[d.M]:[1,4,4,4,4,4,4,4,4,4],[d.S]:[1,4,4,4,4,4,4,4,4,4],[d.P]:[1,4,4,4,4,4,4,4,4,4],[d.Z]:[0,4,4,4,4,4,4,4]});S(this,"safeMap",G({},!0));this.disable=t}get(t){return t.t==d.BACK?0:j(t)?this.c[t.t][5]:this.c[t.t][t.n]}dec(...t){if(!this.disable){for(let e of t)if(e.t!=d.BACK){if(this.get(e)<=0)throw new Error(`cannot decrease ${e.toString()} due to zero`);this.c[e.t][e.n]-=1,j(e)&&(this.c[e.t][5]-=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 e==0&&(e=5),`${t}${e}`}reset(){this.c={[d.M]:[1,4,4,4,4,4,4,4,4,4],[d.S]:[1,4,4,4,4,4,4,4,4,4],[d.P]:[1,4,4,4,4,4,4,4,4,4],[d.Z]:[0,4,4,4,4,4,4,4]}}}class ps{constructor(){S(this,"m",[])}discard(t,e){this.m.push({w:e,t})}get lastTile(){const t=this.m.at(-1);return C(t!=null,`lastTile is null(${t}). river: ${JSON.stringify(this.m,null,2)}`),t}discards(t){return t==null?[...this.m]:this.m.filter(e=>e.w==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 ic(){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 rc(){const s=ic();if(s.__xstate__)return s.__xstate__}const oc=s=>{if(typeof window>"u")return;const t=rc();t&&t.register(s)};class Bs{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 Pi=".",ac="",ji="",cc="#",hc="*",Li="xstate.init",Bn="xstate.stop";function lc(s,t){return{type:`xstate.after.${s}.${t}`}}function zn(s,t){return{type:`xstate.done.state.${s}`,output:t}}function uc(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function fc(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function Ki(s){return{type:Li,input:s}}function gt(s){setTimeout(()=>{throw s})}const dc=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Ui(s,t){const e=zs(s),n=zs(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?Ui(e[i],n[i]):!1)}function ms(s){if(qi(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 zs(s){if(qc(s))return s.value;if(typeof s!="string")return s;const t=ms(s);return pc(t)}function pc(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 Ps(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 Fi(s){return qi(s)?s:[s]}function St(s){return s===void 0?[]:Fi(s)}function Pn(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function qi(s){return Array.isArray(s)}function mc(s){return s.type.startsWith("xstate.error.actor")}function Gt(s){return Fi(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Gi(s){if(!(s===void 0||s===ac))return St(s)}function jn(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 js(s,t){return`${t}.${s}`}function gs(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 Ls(s,t){return`${s.sessionId}.${t}`}let gc=0;function yc(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,p,y,w=Math.random().toString(36).slice(2))=>{const x={source:f,target:m,event:p,delay:y,id:w,startedAt:Date.now()},O=Ls(f,w);u._snapshot._scheduledEvents[O]=x;const $=a.setTimeout(()=>{delete o[O],delete u._snapshot._scheduledEvents[O],u._relay(f,m,p)},y);o[O]=$},cancel:(f,m)=>{const p=Ls(f,m),y=o[p];delete o[p],delete u._snapshot._scheduledEvents[p],y!==void 0&&a.clearTimeout(y)},cancelAll:f=>{for(const m in u._snapshot._scheduledEvents){const p=u._snapshot._scheduledEvents[m];p.source===f&&h.cancel(f,p.id)}}},l=f=>{if(!r.size)return;const m={...f,rootId:s.sessionId};r.forEach(p=>{var y;return(y=p.next)==null?void 0:y.call(p,m)})},u={_snapshot:{_scheduledEvents:((t==null?void 0:t.snapshot)&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${gc++}`,_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 p=n.get(f);if(p&&p!==m)throw new Error(`Actor with system ID '${f}' already exists.`);n.set(f,m),i.set(m,f)},inspect:f=>{const m=jn(f);return r.add(m),{unsubscribe(){r.delete(m)}}},_sendInspectionEvent:l,_relay:(f,m,p)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:f,actorRef:m,event:p}),m._send(p)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const f=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const m in f){const{source:p,target:y,event:w,delay:x,id:O}=f[m];h.schedule(p,y,w,x,O)}},_clock:a,_logger:c};return u}const ys=1;let q=function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s}({});const wc={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class _c{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 Bs(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=q.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={...wc,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:h,inspect:l}=n;this.system=o?o.system:yc(this,{clock:i,logger:r}),l&&!o&&this.system.inspect(jn(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 p=new Set([...f?f.values():[],...m?m.values():[]]);for(const y of Array.from(p))y(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){gt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){gt(a)}this._stopProcedure(),this._complete(),this._doneEvent=uc(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=jn(t,e,n);if(this._processingStatus!==q.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){gt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)gt(o);else try{i.error(o)}catch(a){gt(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===q.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=q.Running;const t=Ki(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===Bn&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===q.Stopped?this:(this.mailbox.clear(),this._processingStatus===q.NotStarted?(this._processingStatus=q.Stopped,this):(this.mailbox.enqueue({type:Bn}),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){gt(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||gt(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){gt(r)}}this.observers.clear(),e&&gt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,fc(this.id,t))}_stopProcedure(){return this._processingStatus!==q.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Bs(this._process.bind(this)),this._processingStatus=q.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==q.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:oc)(this)}toJSON(){return{xstate$$type:ys,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[dc](){return this}getSnapshot(){return this._snapshot}}function se(s,...[t]){return new _c(s,t)}function bc(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,r]}function Sc(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t)})}function vc(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=bc,t.execute=Sc,t}function Ac(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const h=typeof o=="string"?gs(t.machine,o):o,l=typeof i=="function"?i(e):i;let u;return h&&(u=se(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})),[Pt(t,{children:{...t.children,[l]:u}}),{id:i,actorRef:u}]}function xc(s,{id:t,actorRef:e}){e&&s.defer(()=>{e._processingStatus!==q.Stopped&&e.start()})}function kc(...[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=Ac,r.execute=xc,r}function Tc(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]),[Pt(t,{children:a}),o]}function Oc(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==q.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function Zi(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=Tc,t.execute=Oc,t}function ws(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 ws(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 _s=s=>s.type==="atomic"||s.type==="final";function ie(s){return Object.values(s.states).filter(t=>t.type!=="history")}function We(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 Je(s){const t=new Set(s),e=Xi(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))Ks(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of ie(n))if(i.type!=="history"&&!t.has(i)){const r=Ks(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 Yi(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(_s(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=Yi(i,t);return n}function Xi(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 Ji(s,t){const e=Je(t);return Yi(s,Xi(e))}function bs(s,t){return t.type==="compound"?ie(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?ie(t).every(e=>bs(s,e)):t.type==="final"}const an=s=>s[0]===cc;function Ec(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===hc)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 Ic(s){const t=s.config.after;if(!t)return[];const e=(i,r)=>{const o=lc(i,s.id),a=o.type;return s.entry.push(eh(o,{id:a,delay:i})),s.exit.push(vc(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 St(a).map(l=>({...l,event:h,delay:c}))}).map(i=>{const{delay:r}=i;return{...Dt(s,i.event,i),delay:r}})}function Dt(s,t,e){const n=Gi(e.target),i=e.reenter??!1,r=Dc(s,n),o={...e,actions:St(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 Nc(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===ji)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=s.config.on[e];t.set(e,Gt(n).map(i=>Dt(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,Gt(s.config.onDone).map(n=>Dt(s,e,n)))}for(const e of s.invoke){if(e.onDone){const n=`xstate.done.actor.${e.id}`;t.set(n,Gt(e.onDone).map(i=>Dt(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,Gt(e.onError).map(i=>Dt(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,Gt(e.onSnapshot).map(i=>Dt(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 Mc(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"?[]:St(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function Dc(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(an(e))return s.machine.getStateNodeById(e);const n=e[0]===Pi;if(n&&!s.parent)return Ve(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return Ve(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 Vi(s){const t=Gi(s.config.target);return t?{target:t.map(e=>typeof e=="string"?Ve(s.parent,e):e)}:s.parent.initial}function Ct(s){return s.type==="history"}function Ks(s){const t=Qi(s);for(const e of t)for(const n of We(e,s))t.add(n);return t}function Qi(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 ie(n))e(i)}}return e(s),t}function re(s,t){if(an(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 Ve(s,t){if(typeof t=="string"&&an(t))try{return s.machine.getStateNodeById(t)}catch{}const e=ms(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=re(n,i)}return n}function Qe(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=>re(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=re(s,r);if(!o)return i;const a=Qe(o,t[r]);return i.concat(a)},[]))}function Cc(s,t,e,n){const r=re(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function Rc(s,t,e,n){const i=Object.keys(t),r=re(s,i[0]),o=Ss(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function Hc(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=re(s,r),c=Ss(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function Ss(s,t,e,n){return typeof t=="string"?Cc(s,t,e,n):Object.keys(t).length===1?Rc(s,t,e,n):Hc(s,t,e,n)}function $c(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function Tt(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function Wc(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 tr(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(Wc(Ln([i],t,e),Ln([a],t,e)))if(Tt(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 Bc(s){const[t,...e]=s;for(const n of We(t,void 0))if(e.every(i=>Tt(i,n)))return n}function vs(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if(Ct(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of vs(Vi(n),t))e.add(i);else e.add(n);return[...e]}function er(s,t){const e=vs(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||Tt(i,s.source)))return s.source;const n=Bc(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Ln(s,t,e){var i;const n=new Set;for(const r of s)if((i=r.target)!=null&&i.length){const o=er(r,e);r.reenter&&r.source===o&&n.add(o);for(const a of t)Tt(a,o)&&n.add(a)}return[...n]}function zc(s,t){if(s.length!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;return!0}function Kn(s,t,e,n,i,r){if(!s.length)return t;const o=new Set(t._nodes);let a=t.historyValue;const c=tr(s,o,a);let h=t;i||([h,a]=Kc(h,n,e,c,o,a,r)),h=oe(h,n,e,c.flatMap(u=>u.actions),r),h=jc(h,n,e,c,o,r,a,i);const l=[...o];h.status==="done"&&(h=oe(h,n,e,l.sort((u,f)=>f.order-u.order).flatMap(u=>u.exit),r));try{return a===t.historyValue&&zc(t._nodes,o)?h:Pt(h,{_nodes:l,historyValue:a})}catch(u){throw u}}function Pc(s,t,e,n,i){if(n.output===void 0)return;const r=zn(i.id,i.output!==void 0&&i.parent?Pn(i.output,s.context,t,e.self):void 0);return Pn(n.output,s.context,r,e.self)}function jc(s,t,e,n,i,r,o,a){let c=s;const h=new Set,l=new Set;Lc(n,o,l,h),a&&l.add(s.machine.root);const u=new Set;for(const f of[...h].sort((m,p)=>m.order-p.order)){i.add(f);const m=[];m.push(...f.entry);for(const p of f.invoke)m.push(kc(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(l.has(f)){const p=f.initial.actions;m.push(...p)}if(c=oe(c,t,e,m,r,f.invoke.map(p=>p.id)),f.type==="final"){const p=f.parent;let y=(p==null?void 0:p.type)==="parallel"?p:p==null?void 0:p.parent,w=y||f;for((p==null?void 0:p.type)==="compound"&&r.push(zn(p.id,f.output!==void 0?Pn(f.output,c.context,t,e.self):void 0));(y==null?void 0:y.type)==="parallel"&&!u.has(y)&&bs(i,y);)u.add(y),r.push(zn(y.id)),w=y,y=y.parent;if(y)continue;c=Pt(c,{status:"done",output:Pc(c,t,e,c.machine.root,w)})}}return c}function Lc(s,t,e,n){for(const i of s){const r=er(i,t);for(const a of i.target||[])!Ct(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),Jt(a,t,e,n);const o=vs(i,t);for(const a of o){const c=We(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),nr(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Jt(s,t,e,n){var i;if(Ct(s))if(t[s.id]){const r=t[s.id];for(const o of r)n.add(o),Jt(o,t,e,n);for(const o of r)wn(o,s.parent,n,t,e)}else{const r=Vi(s);for(const o of r.target)n.add(o),r===((i=s.parent)==null?void 0:i.initial)&&e.add(s.parent),Jt(o,t,e,n);for(const o of r.target)wn(o,s.parent,n,t,e)}else if(s.type==="compound"){const[r]=s.initial.target;Ct(r)||(n.add(r),e.add(r)),Jt(r,t,e,n),wn(r,s,n,t,e)}else if(s.type==="parallel")for(const r of ie(s).filter(o=>!Ct(o)))[...n].some(o=>Tt(o,r))||(Ct(r)||(n.add(r),e.add(r)),Jt(r,t,e,n))}function nr(s,t,e,n,i){for(const r of n)if((!i||Tt(r,i))&&s.add(r),r.type==="parallel")for(const o of ie(r).filter(a=>!Ct(a)))[...s].some(a=>Tt(a,o))||(s.add(o),Jt(o,t,e,s))}function wn(s,t,e,n,i){nr(e,n,i,We(s,t))}function Kc(s,t,e,n,i,r,o){let a=s;const c=Ln(n,i,r);c.sort((l,u)=>u.order-l.order);let h;for(const l of c)for(const u of $c(l)){let f;u.history==="deep"?f=m=>_s(m)&&Tt(m,l):f=m=>m.parent===l,h??(h={...r}),h[u.id]=Array.from(i).filter(f)}for(const l of c)a=oe(a,t,e,[...l.exit,...l.invoke.map(u=>Zi(u.id))],o),i.delete(l);return[a,h||r]}let Us=!1;function sr(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{Us=l,l(u,f)}finally{Us=!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===q.Running?m():e.defer(()=>{m()});continue}const p=l,[y,w,x]=p.resolve(e,a,u,f,l,i);a=y,"retryResolve"in p&&(r==null||r.push([p,w])),"execute"in p&&(e.self._processingStatus===q.Running?p.execute(e,w):e.defer(p.execute.bind(null,e,w))),x&&(a=sr(a,t,e,x,i,r))}return a}function oe(s,t,e,n,i,r){const o=r?[]:void 0,a=sr(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,h])=>{c.retryResolve(e,a,h)}),a}function _n(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===Bn)return i=Pt(Fs(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==Li){const h=a,l=mc(h),u=qs(h,i);if(l&&!u.length)return i=Pt(s,{status:"error",error:h.error}),o(i,h,[]),{snapshot:i,microstates:r};i=Kn(u,s,e,a,!1,n),o(i,h,u)}let c=!0;for(;i.status==="active";){let h=c?Uc(i,a):[];const l=h.length?i:void 0;if(!h.length){if(!n.length)break;a=n.shift(),h=qs(a,i)}i=Kn(h,i,e,a,!1,n),c=i!==l,o(i,a,h)}return i.status!=="active"&&Fs(i,a,e),{snapshot:i,microstates:r}}function Fs(s,t,e){return oe(s,t,e,Object.values(s.children).map(n=>Zi(n)),[])}function qs(s,t){return t.machine.getTransitionData(t,s)}function Uc(s,t){const e=new Set,n=s._nodes.filter(_s);for(const i of n)t:for(const r of[i].concat(We(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||ws(o.guard,s.context,t,s)){e.add(o);break t}}return tr(Array.from(e),new Set(s._nodes),s.historyValue)}function Fc(s,t){const e=Je(Qe(s,t));return Ji(s,[...e])}function qc(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Gc=function(t){return Ui(t,this.value)},Zc=function(t){return this.tags.has(t)},Yc=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(n=>n.target!==void 0||n.actions.length)},Xc=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)}},Jc=function(){return this._nodes.reduce((t,e)=>(e.meta!==void 0&&(t[e.id]=e.meta),t),{})};function Ke(s,t){return{status:s.status,output:s.output,error:s.error,machine:t,context:s.context,_nodes:s._nodes,value:Ji(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Gc,hasTag:Zc,can:Yc,getMeta:Jc,toJSON:Xc}}function Pt(s,t={}){return Ke({...s,...t},s.machine)}function Vc(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 y in r){const w=r[y];m[y]={snapshot:w.getPersistedSnapshot(t),src:w.src,systemId:w._systemId,syncSnapshot:w._syncSnapshot}}return{...f,context:ir(o),children:m}}function ir(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:ys,id:n.id};else{const i=ir(n);i!==n&&(t??(t=Array.isArray(s)?s.slice():{...s}),t[e]=i)}}return t??s}function Qc(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 th(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 eh(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=Qc,e.execute=th,e}function nh(s,{machine:t,context:e},n,i){const r=(o,a={})=>{const{systemId:c,input:h}=a;if(typeof o=="string"){const l=gs(t,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const u=se(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 se(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!==q.Stopped&&c.start()}),c}}function sh(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:nh(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[Pt(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children})]}function ih(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=sh,t}const Gs=new WeakMap;function qt(s,t,e){let n=Gs.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},Gs.set(s,n)),n[t]}const rh={},ue=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class As{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(Pi),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?Ps(this.config.states,(n,i)=>new As(n,{_parent:this,_key:i,_machine:this.machine})):rh,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=St(this.config.entry).slice(),this.exit=St(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=St(t.tags).slice()}_initialize(){this.transitions=Nc(this),this.config.always&&(this.always=Gt(this.config.always).map(t=>Dt(this,ji,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(ue),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ue),eventType:null})}:void 0,history:this.history,states:Ps(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ue)})),entry:this.entry.map(ue),exit:this.exit.map(ue),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 qt(this,"invoke",()=>St(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??js(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${js(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 qt(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 qt(this,"delayedTransitions",()=>Ic(this))}get initial(){return qt(this,"initial",()=>Mc(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=qt(this,`candidates-${n}`,()=>Ec(this,n));for(const a of o){const{guard:c}=a,h=t.context;let l=!1;try{l=!c||ws(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
- ${u.message}`)}if(l){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return qt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const n of Object.keys(t)){const i=t[n];if(i.states)for(const r of i.events)e.add(`${r}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(e=>this.transitions.get(e).some(n=>!(!n.target&&!n.actions.length&&!n.reenter))));return Array.from(t)}}const oh="#";class xs{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 As(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:n,actors:i,delays:r}=this.implementations;return new xs(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=Fc(this.root,t.value),n=Je(Qe(this.root,e));return Ke({_nodes:[...n],context:t.context||{},children:{},status:bs(n,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return _n(t,e,n).snapshot}microstep(t,e,n){return _n(t,e,n).microstates}getTransitionData(t,e){return Ss(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:i}=this.config,r=Ke({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?oe(r,e,t,[ih(({spawn:a,event:c,self:h})=>i({spawn:a,input:c.input,self:h}))],n):r}getInitialSnapshot(t,e){const n=Ki(e),i=[],r=this.getPreInitialState(t,n,i),o=Kn([{target:[...Qi(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,n,!0,i),{snapshot:a}=_n(o,n,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=ms(t),n=e.slice(1),i=an(e[0])?e[0].slice(oh.length):e[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return Ve(r,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return Vc(t,e)}restoreSnapshot(t,e){const n={},i=t.children;Object.keys(i).forEach(c=>{const h=i[c],l=h.snapshot,u=h.src,f=typeof u=="string"?gs(this,u):u;if(!f)return;const m=se(f,{id:c,parent:e.self,syncSnapshot:h.syncSnapshot,snapshot:l,src:u,systemId:h.systemId});n[c]=m});const r=Ke({...t,children:n,_nodes:Array.from(Je(Qe(this.root,t.value)))},this);let o=new Set;function a(c,h){if(!o.has(c)){o.add(c);for(let l in c){const u=c[l];if(u&&typeof u=="object"){if("xstate$$type"in u&&u.xstate$$type===ys){c[l]=h[u.id];continue}a(u,h)}}}}return a(r.context,n),r}}function ah(s,t){return new xs(s,t)}const je=s=>s===!1?!1:s.map(t=>t.serialize()),ch=s=>s===!1?!1:s.serialize(),hh=s=>s===!1?!1:s.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),Un=s=>JSON.parse(JSON.stringify(s)),bn=s=>s===!1?!1:Un(s),Fn=s=>ah({id:"Untitled",initial:"distribute",context:{currentWind:v.E,oneShotMap:G(!1),missingMap:G(!1),controller:s,genEventID:rr()},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
- DISCARD の場合は捨てられる牌の一覧`}}},waiting_user_event_after_drawn:{description:"ツモった1ユーザからのレスポンス待ち",on:{TSUMO:{target:"tsumo",guard:"canWin"},REACH:{target:"discarded",guard:"canReach",actions:{type:"notify_reach"},description:`入力に牌が必要\\
11
- 立直直後のロンは立直棒が点数にならないので\\
12
- 別途状態を保つ必要がある`},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_TILES:{target:"drawn_game"}}},discarded:{entry:{type:"notify_discard"},on:{NEXT:{target:"waiting_user_event_after_discarded",actions:{type:"notify_choice_after_discarded"},description:`可能なアクションとその詳細を通知\\
13
- CHI/PON の場合は鳴ける組み合わせの一覧`}}},tsumo:{exit:[{type:"notify_tsumo"},{type:"notify_end"}],type:"final"},waiting_user_event_after_discarded:{description:`最大 4人から choice に対するレスポンスを待つ\\
5
+ `);for(let e=0,n=t.length;e<n;e++)this.newLine(t[e])}return this.build(!1).rebuild()}}I(U,Ei);T({Container:{text:H(function(s=""){return this.put(new U).text(s)}),plain:H(function(s=""){return this.put(new U).plain(s)})}});C(U,"Text");class on extends nt{constructor(t,e=t){super($("tspan",t),e),this._build=!1}dx(t){return this.attr("dx",t)}dy(t){return this.attr("dy",t)}newLine(){this.dom.newLined=!0;const t=this.parent();if(!(t instanceof U))return this;const e=t.index(this),n=N.window.getComputedStyle(this.node).getPropertyValue("font-size"),i=t.dom.leading*new E(n);return this.dy(e?i:0).attr("x",t.x())}text(t){return t==null?this.node.textContent+(this.dom.newLined?`
6
+ `:""):(typeof t=="function"?(this.clear().build(!0),t.call(this,this),this.build(!1)):this.plain(t),this)}}I(on,Ei);T({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()}}});C(on,"Tspan");class us 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))}}I(us,{x:ui,y:fi,cx:di,cy:pi,width:mi,height:gi});T({Container:{circle:H(function(s=0){return this.put(new us).size(s).move(0,0)})}});C(us,"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 ue("svg [clip-path*="+this.id()+"]")}}T({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)}}});C(Cn,"ClipPath");class ki extends mt{constructor(t,e=t){super($("foreignObject",t),e)}}T({Container:{foreignObject:H(function(s,t){return this.put(new ki).size(s,t)})}});C(ki,"ForeignObject");function xa(s,t){return this.children().forEach(e=>{let n;try{n=e.node instanceof Tr().SVGSVGElement?new L(e.attr(["x","y","width","height"])):e.bbox()}catch{return}const i=new S(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 Ea(s){return this.dmove(s,0)}function ka(s){return this.dmove(0,s)}function Ta(s,t=this.bbox()){return s==null?t.height:this.size(t.width,s,t)}function Oa(s=0,t=0,e=this.bbox()){const n=s-e.x,i=t-e.y;return this.dmove(n,i)}function Ia(s,t,e=this.bbox()){const n=le(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 S(o).inverse());o.scale(i,r,a.x,a.y)}),this}function Na(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 Da(s,t=this.bbox()){return s==null?t.y:this.move(t.x,s,t)}const Ti=Object.freeze(Object.defineProperty({__proto__:null,dmove:xa,dx:Ea,dy:ka,height:Ta,move:Oa,size:Ia,width:Na,x:Ca,y:Da},Symbol.toStringTag,{value:"Module"}));class P extends V{constructor(t,e=t){super($("g",t),e)}}I(P,Ti);T({Container:{group:H(function(){return this.put(new P)})}});C(P,"G");class Ye extends V{constructor(t,e=t){super($("a",t),e)}target(t){return this.attr("target",t)}to(t){return this.attr("href",t,Oe)}}I(Ye,Ti);T({Container:{link:H(function(s){return this.put(new Ye).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 Ye,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}}});C(Ye,"A");class Dn extends V{constructor(t,e=t){super($("mask",t),e)}remove(){return this.targets().forEach(function(t){t.unmask()}),super.remove()}targets(){return ue("svg [mask*="+this.id()+"]")}}T({Container:{mask:H(function(){return this.defs().put(new Dn)})},Element:{masker(){return this.reference("mask")},maskWith(s){const t=s instanceof Dn?s:this.parent().mask().add(s);return this.attr("mask","url(#"+t.id()+")")},unmask(){return this.attr("mask",null)}}});C(Dn,"Mask");class Oi extends mt{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}}T({Gradient:{stop:function(s,t,e){return this.put(new Oi).update(s,t,e)}}});C(Oi,"Stop");function Ma(s,t){if(!s)return"";if(!t)return s;let e=s+"{";for(const n in t)e+=xr(n)+":"+t[n]+";";return e+="}",e}class Mn extends mt{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(Ma(t,e))}}T("Dom",{style(s,t){return this.put(new Mn).rule(s,t)},fontface(s,t,e){return this.put(new Mn).font(s,t,e)}});C(Mn,"Style");class fs extends U{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")}}T({Container:{textPath:H(function(s,t){return s instanceof U||(s=this.text(s)),s.path(t)})},Text:{path:H(function(s,t=!0){const e=new fs;s instanceof fe||(s=this.defs().path(s)),e.attr("href","#"+s,Oe);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 U||(s=new U().addTo(this.parent()).text(s)),s.path(this)}),targets(){return ue("svg textPath").filter(s=>(s.attr("href")||"").includes(this.id()))}}});fs.prototype.MorphArray=Pt;C(fs,"TextPath");class an extends nt{constructor(t,e=t){super($("use",t),e)}use(t,e){return this.attr("href",(e||"")+"#"+t,Oe)}}T({Container:{use:H(function(s,t){return this.put(new an).use(s,t)})}});C(an,"Use");I([ls,rn,Ce,ve,Ze],J("viewbox"));I([Ae,Re,Me,fe],J("marker"));I(U,J("Text"));I(fe,J("Path"));I(is,J("Defs"));I([U,on],J("Tspan"));I([He,sn,Ne,et],J("radius"));I(Ie,J("EventTarget"));I(kt,J("Dom"));I(mt,J("Element"));I(nt,J("Shape"));I([V,yi],J("Container"));I(Ne,J("Gradient"));I(et,J("Runner"));Wt.extend(Ar());ta([E,M,L,S,ee,Tt,Pt,W]);ea();const ot=(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((xt.HEIGHT*t).toPrecision(5)),n=parseFloat((xt.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*xt.TEXT_SCALE),i};class ne{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=xt.WIDTH*this.scale,this.tileHeight=xt.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 Ce().load(this.buildURL(t));return this.svgSprite&&(e=new an().use(ne.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 U().text(i);l.size(o.baseWidth,o.baseHeight).font({family:qn,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=`${ne.buildID(t)}.${this.imageExt}`;return this.imageHostUrl!=""?`${this.imageHostUrl}${e}`:`${this.imageHostPath}${e}`}}class ds extends ne{constructor(){super(...arguments);A(this,"blockMargin",xt.WIDTH*xt.BLOCK_MARGIN_SCALE*this.scale)}createBlockHandDiscard(e){const n=e instanceof F?e.tilesWithBack:e.tiles,i=new P;let r=0;for(let 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 Ra=s=>{const t=s.scale;return{[b.CHI]:function(n){const i=ot(n,t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[b.PON]:function(n){const i=ot(n,t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[b.DAI_KAN]:function(n){const i=ot(n,t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[b.SHO_KAN]:function(n){const i=ot(n,t),r=s.createBlockPonChiKan(n);return{...i,e:r}},[b.AN_KAN]:function(n){O(n instanceof F,`block type is not ankan: ${n.type}`);const i=ot(n,t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[b.IMAGE_DORA]:function(n){const i=ot(n,t),r=new P,o=s.createTextImage(n.tiles[0],0,0,"(ドラ)");return r.add(o),{...i,e:r}},[b.TSUMO]:function(n){const i=ot(n,t),r=new P,o=s.createTextImage(n.tiles[0],0,0,"(ツモ)");return r.add(o),{...i,e:r}},[b.HAND]:function(n){const i=ot(n,t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[b.IMAGE_DISCARD]:function(n){const i=ot(n,t),r=s.createBlockHandDiscard(n);return{...i,e:r}},[b.THREE]:function(n){throw new Error("three is unsupported")},[b.RUN]:function(n){throw new Error("run is unsupported")},[b.PAIR]:function(n){throw new Error("pair is unsupported")},[b.ISOLATED]:function(n){throw new Error("isolated is unsupported")},[b.UNKNOWN]:function(n){if(n.tiles.some(o=>o.has(y.TSUMO)||o.has(y.DORA)))throw new Error("found an unknown block with operator tiles");const i=ot(n,t),r=s.createBlockHandDiscard(n);return{...i,e:r}}}},Vt=(s,t)=>{const{maxHeight:e,sumWidth:n}=t.reduce((l,u)=>{const f=ot(u,s.scale);return{maxHeight:f.height>l.maxHeight?f.height:l.maxHeight,sumWidth:l.sumWidth+f.width}},{maxHeight:0,sumWidth:0}),i=e,r=n+(t.length-1)*s.blockMargin,o=Ra(s),a=[];for(let l of t){const u=o[l.type],f=u(l);a.push(f)}const c=new P;let h=0;for(let l of a){const u=i-l.height,f=new P().translate(h,u);f.add(l.e),c.add(f),h+=l.width+s.blockMargin}return{e:c,width:r,height:i}},Ha=(s,t,e={},n={responsive:!1})=>{const i=new ds(e),r=Vt(i,t);n.responsive||s.size(r.width,r.height),s.viewbox(0,0,r.width,r.height),s.add(r.e)},Ii=()=>{const s=[0,1,2,3,4,5,6,7,8,9],t=[];for(let e of Object.values(p)){if(e==p.BACK){t.push(ne.buildID(new w(e,0)));continue}t.push(...s.map(n=>ne.buildID(new w(e,n))).flat())}return t},$a=s=>{const t=Ii(),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},Ba=s=>{const t=Ii(),e=$a(s);s.each((n,i)=>{const r=i[n];r instanceof rn&&(t.includes(r.id())&&e.includes(r.id())||r.remove())},!0)},Wa=s=>{const e=[];for(let n=0;n<s.length;n+=6){const i=s.slice(n,n+6);e.push(i)}return e},lt=(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},je=(s,t)=>{const e=new P,n=Wa(s);for(let i=0;i<n.length;i++){let r=n[i],o=i*t.tileHeight;const a=t.createBlockHandDiscard(new Jn(r,b.IMAGE_DISCARD)).translate(0,o);e.add(a)}return{e,width:t.tileWidth*5+t.tileHeight*1,height:t.tileHeight*n.length}},Pa=(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 U().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),x={family:n.family,size:n.size*.7},k=s.createStick(1e3).size(h,l).move(0,0),R=new U().plain(c.toString()).font(x).attr({x:h,y:l});_.add(k),_.add(R);const Z=s.createStick(100).size(h,l).move(0,l+l),K=new U().plain(a.toString()).font(x).attr({x:h,y:l*3});_.add(Z),_.add(K);const rt=s.createImage(e.doras[0],0,0).move(h+i,0);return _.add(rt),o.add(d),o.add(_),{e:o,width:h+s.tileWidth+i,height:f+s.tileHeight}},ja=(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=lt(n.e,n.width,n.height,0).translate((c-n.width)/2,h-n.height),f=lt(i.e,i.width,i.height,270).translate(c-i.height,(c-i.width)/2),m=lt(r.e,r.width,r.height,180).translate((c-r.width)/2,0),d=lt(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}},za=s=>{const t=Object.values(en),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 He().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=Pa(s,t,e);l.e.translate(n/2-l.width/2,n/2-l.height/2);const u=(hn,Ts,hr)=>{const lr=`${hn} ${Ts}`,ur=new U().plain(lr).font(o).attr(hr);return{e:new P().add(ur),width:a+h*Ts.toString().length,height:c}},[f,m,d,g]=za(e.frontPlace),_=e.scores,k=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 Z=lt(R.e,R.width,R.height,270).translate(n,n/2-R.width);let K=u(d,_.opposite,{"text-anchor":"middle","dominant-baseline":"text-after-edge"});const rt=lt(K.e,K.width,K.height,180).translate(n/2-K.width,-K.height);let gt=u(g,_.left,{"dominant-baseline":"ideographic","text-anchor":"middle"});const Ut=lt(gt.e,gt.width,gt.height,90).translate(-gt.height,n/2);return i.add(l.e),i.add(k),i.add(Z),i.add(rt),i.add(Ut),{e:i,width:n,height:n}},Ka=(s,t)=>{const e=je(t.front,s),n=je(t.right,s),i=je(t.opposite,s),r=je(t.left,s),o=[e.height,n.height,i.height,r.height].reduce((k,R)=>Math.max(k,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=lt(e.e,a,c,0).translate(f,l-c),g=lt(n.e,a,c,270).translate(h-c,m),_=lt(i.e,a,c,180).translate(f,0),x=lt(r.e,a,c,90).translate(0,m);return u.add(d),u.add(g),u.add(_),u.add(x),{e:u,width:h,height:l}},Ni=(s,t,e,n,i)=>{const r=new P,o=Ka(s,n),a=ja(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 ds(e),o=n,{discards:a,hands:c,scoreBoard:h}=Ci(t),l=Ni(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 yt;function Ua(s){return{lang:(s==null?void 0:s.lang)??(yt==null?void 0:yt.lang),message:s==null?void 0:s.message,abortEarly:(s==null?void 0:s.abortEarly)??(yt==null?void 0:yt.abortEarly),abortPipeEarly:(s==null?void 0:s.abortPipeEarly)??(yt==null?void 0:yt.abortPipeEarly)}}var gn;function Za(s){return gn==null?void 0:gn.get(s)}var yn;function qa(s){return yn==null?void 0:yn.get(s)}var wn;function Ga(s,t){var e;return(e=wn==null?void 0:wn.get(s))==null?void 0:e.get(t)}function se(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 jt(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)??se(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??Ga(s.reference,c.lang)??(h?qa(c.lang):null)??n.message??Za(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 Ya(s,t){const e=[...new Set(s)];return e.length>1?`(${e.join(` ${t} `)})`:e[0]??"never"}function Rn(s,t){return{kind:"validation",type:"max_value",reference:Rn,async:!1,expects:`<=${s instanceof Date?s.toJSON():se(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value>this.requirement&&jt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():se(e.value)}),e}}}function Hn(s,t){return{kind:"validation",type:"min_value",reference:Hn,async:!1,expects:`>=${s instanceof Date?s.toJSON():se(s)}`,requirement:s,message:t,_run(e,n){return e.typed&&e.value<this.requirement&&jt(this,"value",e,n,{received:e.value instanceof Date?e.value.toJSON():se(e.value)}),e}}}function Xa(s,t,e){return typeof s.default=="function"?s.default(t,e):s.default}function Xe(s){return{kind:"schema",type:"number",reference:Xe,expects:"number",async:!1,message:s,_run(t,e){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:jt(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=Xa(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 $n(s,t){return{kind:"schema",type:"picklist",reference:$n,expects:Ya(s.map(se),"|"),async:!1,options:s,message:t,_run(e,n){return this.options.includes(e.value)?e.typed=!0:jt(this,"type",e,n),e}}}function ie(s,t){return{kind:"schema",type:"strict_object",reference:ie,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];jt(this,"type",e,n,{input:a,expected:"never",path:[{type:"object",origin:"value",input:i,key:o,value:a}]});break}}}else jt(this,"type",e,n);return e}}}function Je(s){return{kind:"schema",type:"string",reference:Je,expects:"string",async:!1,message:s,_run(t,e){return typeof t.value=="string"?t.typed=!0:jt(this,"type",t,e),t}}}function $s(...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 Ja(s,t,e){const n=s._run({typed:!1,value:t},Ua(e));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}const ze=it(ie({discard:it(Je(),""),hand:it(Je(),""),score:it(Xe(),25e3)}),{discard:"",hand:"",score:25e3}),Va=ie({[v.E]:ze,[v.S]:ze,[v.W]:ze,[v.N]:ze}),It={round:j.E1,sticks:{reach:0,dead:0},doras:v.S,front:v.E},Qa=it(ie({round:it($n(Object.keys(Gn)),It.round),sticks:it(ie({reach:it($s(Xe(),Hn(0,""),Rn(9,"")),It.sticks.reach),dead:it($s(Xe(),Hn(0,""),Rn(9,"")),It.sticks.dead)}),It.sticks),doras:it(Je(),It.doras),front:it($n(Object.keys(en)),It.front)}),It),tc=ie({...Va.entries,board:Qa}),Ci=s=>{const t=Di(s);return Mi(t)},Di=s=>{const t=ec(s),e=Ja(tc,t);if(!e.success)throw e.issues;return e.output},ec=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]=sc([...n]);r.board=h;for(let u=0;u<l;u++)n.shift()}else{const[h,l]=nc([...n]);r[c]=h;for(let u=0;u<l;u++)n.shift()}}return r},ut=(s,t)=>s.replace(t,"").replace(":","").trim(),nc=s=>{const t="hand",e="discard",n="score";let i={},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]},sc=s=>{const t="doras",e="round",n="front",i="sticks",r="reach",o="dead";let a={},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]},Mi=s=>{const t=s.board.front,e=ic(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:Gn[s.board.round],frontPlace:en[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}},ic=s=>({front:s,right:Et(s),opposite:Et(Et(s)),left:Vs(s)});class $e{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=new Q(t).parse();for(let 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(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(let e of Object.values(p))for(let n=1;n<this.getArrayLen(e);n++){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,5,[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?`${vt}${this.called.join(vt)}`:"",e=this.drawn?`${vt}${this.drawn.toString()}`:"",n=this.hands.filter(r=>!r.has(y.TSUMO));return`${new nn(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 F))}getArrayLen(t){return this.data[t].length}sum(t){let e=0;for(let n=1;n<this.getArrayLen(t);n++)e+=this.get(t,n);return e}get(t,e){return t==p.BACK?this.data[t][1]:this.data[t][e]}inc(t){const e=[];for(let n of t){if(O(!(n.isNum()&&n.n==0),`found 0s/0p/0m ${n.toString()}`),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(let n of t){if(O(!(n.isNum()&&n.n==0),`found 0s/0p/0m ${n.toString()}`),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){if(!(t instanceof pt||t instanceof ht||t instanceof dt))throw new Error(`unexpected input ${t} ${t.type}`);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 F){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)&&this.get(n.t,0)>0?n.clone({add:y.RED}):n.clone({remove:y.RED}),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 $e(this.toString());return t.data.reached=this.data.reached,t}}class Be{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(let n of Object.values(p))if(n!=p.BACK)for(let i=1;i<this.hand.getArrayLen(n);i++)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(let n of Object.values(p)){if(n==p.BACK)continue;const i=n==p.Z?re:ft;for(let 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],r=p.Z;for(let m=1;m<this.hand.getArrayLen(r);m++)this.hand.get(r,m)>=3?i[0]++:this.hand.get(r,m)==2?i[1]++:this.hand.get(r,m)==1&&i[2]++;const o=[0,0,0],a=this.hand.get(p.BACK,0),c=a%3;o[0]=Math.floor(a/3),c==2&&(o[1]=1),c==1&&(o[2]=1);let h=13;const l=this.commonByType(p.M),u=this.commonByType(p.P),f=this.commonByType(p.S);for(let m of[l.patternA,l.patternB])for(let d of[u.patternA,u.patternB])for(let g of[f.patternA,f.patternB]){const _=[this.hand.called.length,0,0];for(let k=0;k<3;k++)_[k]+=m[k]+d[k]+g[k]+i[k]+o[k];let x=this.calcCommon(_[0],_[1],_[2],n);x<h&&(h=x)}return h};let e=t(!1);for(let n of Object.values(p))for(let i=1;i<this.hand.getArrayLen(n);i++)if(this.hand.get(n,i)>=2){const r=this.hand.dec([new w(n,i),new w(n,i)]),o=t(!0);this.hand.inc(r),o<e&&(e=o)}return e}commonByType(t,e=1){if(t==p.BACK||t==p.Z)throw new Error(`expect number type but ${t}`);if(e>9)return this.groupRemainingTiles(t);let n=this.commonByType(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.commonByType(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 w(t,e),new w(t,e),new w(t,e)]),r=this.commonByType(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(let r=1;r<this.hand.getArrayLen(t);r++)i+=this.hand.get(t,r),r<=7&&this.hand.get(t,r+1)==0&&this.hand.get(t,r+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 Ri{constructor(t){A(this,"hand");this.hand=t}calc(t){return this.hand.drawn!=null&&(t=this.hand.drawn),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));if(u<0)continue;const f=Hi(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(let[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(let e of Object.values(p))if(e!=p.BACK)for(let n=1;n<this.hand.getArrayLen(e);n++){const i=this.hand.get(e,n);if(i==2)t.push(new Y(new w(e,n),new w(e,n)));else{if(i==0)continue;return[]}}return[t]}thirteenOrphans(){const t=[];let e=!1;for(let n of Object.values(p)){if(n==p.BACK)continue;const i=n==p.Z?re:ft;for(let r of i)if(this.hand.get(n,r)==1)t.push(new Xn(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(let 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 nn(this.hand.hands)]]}return[]}fourSetsOnePair(){let t=[];for(let e of Object.values(p))for(let n=1;n<this.hand.getArrayLen(e);n++)if(this.hand.get(e,n)>=2){const i=this.hand.dec([new w(e,n),new w(e,n)]),r=this.commonAll().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}commonAll(){const t=()=>{const r=[],o=p.Z;for(let a=1;a<this.hand.getArrayLen(o);a++)if(this.hand.get(o,a)!=0){if(this.hand.get(o,a)!=3)return[];r.push(new at([new w(o,a),new w(o,a),new w(o,a)]))}return r.length==0?[]:[r]},e=()=>{const r=[],o=p.BACK,a=this.hand.get(o,0);return a<3?[]:(Array(Math.floor(a/3)).fill(void 0).map(c=>{r.push(new at([new w(o,0),new w(o,0),new w(o,0)]))}),r.length==0?[]:[r])},n=[this.commonByType(p.M),this.commonByType(p.P),this.commonByType(p.S),t(),e(),[this.hand.called.concat()]].sort((r,o)=>o.length-r.length),i=n[0].concat();for(let r=0;r<i.length;r++)for(let o=1;o<n.length;o++)for(let a of n[o])i[r]=[...i[r],...a];return i}commonByType(t,e=1){if(e>9)return[];if(this.hand.get(t,e)==0)return this.commonByType(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.commonByType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(let o of r)o.unshift(new At([i[0],i[1],i[2]])),n.push(o)}if(this.hand.get(t,e)==3){const i=this.hand.dec([new w(t,e),new w(t,e),new w(t,e)]);let r=this.commonByType(t,e);this.hand.inc(i),r.length==0&&(r=[[]]);for(let o of r)o.unshift(new at([i[0],i[1],i[2]])),n.push(o)}return n}}const re=[1,2,3,4,5,6,7],ft=[1,9],ge=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 Bn{constructor(t,e){A(this,"hand");A(this,"cfg");this.hand=t,this.cfg={doras:e.doraMarkers.map(n=>Ws(n)),blindDoras:e.blindDoraMarkers==null?[]:e.blindDoraMarkers.map(n=>Ws(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((x,k)=>x+k.double,0);(_>n[0]||_==n[0]&&g.fu>n[1])&&(i=d,n[0]=_,n[1]=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=G(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(let g of Object.values(v)){if(g==l)continue;const _=g==v.E?2:1,x=r(c*_)+d;f[g]-=x,f[l]+=x}}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(let 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(let 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?[]:Bs(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(let o of t)for(let a of o.tiles){for(let c of this.cfg.doras)a.equals(c)&&e++;for(let c of this.cfg.blindDoras)a.equals(c)&&i++;a.has(y.RED)&&n++}const r=[];return e>0&&r.push({name:"ドラ",double:e}),n>0&&r.push({name:"赤ドラ",double:n}),this.hand.reached&&i>0&&r.push({name:"裏ドラ",double:i}),r}dA2(t){return t.length==7?[{name:"七対子",double:2}]:[]}dB2(t){const e=n=>n instanceof At||n instanceof ht;for(let n of t){if(!e(n))continue;const i=Nt(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(Nt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Nt(c))});if(o&&a)return[{name:"三色同順",double:2-this.minus()}]}return[]}dC2(t){return t.length==7?[]:t.every(n=>n instanceof F||n instanceof ct||n instanceof dt||n instanceof at||n instanceof pt||n instanceof Y)?[{name:"対々和",double:2}]:[]}dD2(t){return this.minus()!=0?[]:t.filter(n=>(n instanceof F||n instanceof at)&&!n.tiles.some(i=>i.has(y.RON))).length>=3?[{name:"三暗刻",double:2}]:[]}dE2(t){return t.filter(n=>n instanceof F||n instanceof ct||n instanceof dt).length>=3?[{name:"三槓子",double:2}]:[]}dF2(t){const e=n=>n instanceof F||n instanceof ct||n instanceof dt||n instanceof at||n instanceof pt;for(let n of t){if(!e(n))continue;const i=Nt(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(Nt(c))}),a=t.some(c=>{const h=new w(r[1],i.n);return e(c)&&h.equals(Nt(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?re:ft;return n.tiles.every(r=>i.includes(r.n))})?[{name:"混老頭",double:2}]:[]}dI2(t){return t.length==7?[]:t.some(n=>n instanceof At||n instanceof ht)?t.some(n=>n.tiles[0].t==p.Z)?t.every(n=>{const i=n.tiles[0].t==p.Z?re:ft;return n.tiles.some(r=>i.includes(r.n))})?[{name:"混全帯么九",double:2-this.minus()}]:[]:[]:[]}dJ2(t){if(this.minus()!=0)return[];let e={[p.M]:[0,0,0],[p.S]:[0,0,0],[p.P]:[0,0,0]};for(let n of t){const i=Nt(n);i.t!=p.BACK&&i.t!=p.Z&&(n instanceof At||n instanceof ht)&&(i.n==1&&e[i.t][0]++,i.n==4&&e[i.t][1]++,i.n==7&&e[i.t][2]++)}for(let 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(let 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 At||n instanceof ht)?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?[]:Bs(t)==2?[{name:"ニ盃口",double:3}]:[]}dA6(t){if(t.some(e=>e.tiles[0].t==p.Z))return[];for(let 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 F||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 F||n instanceof ct||n instanceof dt).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(let d of t)switch(!0){case d instanceof at:let g=d.tiles.some(_=>_.has(y.RON))?2:4;n+=h(d,g);break;case d instanceof pt:n+=h(d,2);break;case(d instanceof dt||d instanceof ct):n+=h(d,8);break;case d instanceof F: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(x=>x.has(y.TSUMO)||x.has(y.RON));return _==1||_==0&&g[2].n==9||_==2&&g[0].n==1?2:0})(o);let 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 Hi=s=>s.tiles.reduce((t,e)=>`${t}${e.n}${e.t}`,""),Bs=s=>{let t={};for(let n of s){if(!(n instanceof At))continue;const i=Hi(n);t[i]==null?t[i]=1:t[i]++}let e=0;for(let n in t)t[n]>=2&&e++;return e},Nt=s=>[...s.tiles].sort(Te)[0],Ws=s=>{let t=s.n,e=s.t;return new w(e,t%9+1)};class zt{static calcCandidates(t,e,n){O(e.length>0,"choices to discard is zero");const i=new Map;let r=Number.POSITIVE_INFINITY;for(let o of e){const a=t.dec([o]),c=zt.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=Number.POSITIVE_INFINITY,i=[];const r=new Be(t);for(let o of Object.values(p))if(o!=p.BACK)for(let a=1;a<t.getArrayLen(o);a++){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}}static partialCandidateTiles(t,e){const n=new $e(t,!0);return Array(13-(n.hands.length+n.called.length*3)).fill(void 0).map(()=>n.inc([new w(p.BACK,0)])),zt.candidateTiles(n,e)}}const Wn=()=>{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 $i(s){var r;const t=["RON","DAI_KAN","PON","CHI"],e=s.map(o=>o.choices),i=Wi(e,t).map(o=>s[o]);return{events:i,type:Pi(t,(r=i[0])==null?void 0:r.choices)}}function Bi(s){var r;const t=["TSUMO","REACH","AN_KAN","SHO_KAN","DRAWN_GAME_BY_NINE_ORPHANS","DISCARD"],e=s.map(o=>o.choices),i=Wi(e,t).map(o=>s[o]);return{events:i,type:Pi(t,(r=i[0])==null?void 0:r.choices)}}function Wi(s,t){let e=[],n=Number.POSITIVE_INFINITY;for(let i=0;i<s.length;i++){const r=s[i];if(rc(r,t)){const o=oc(t,r);o<n?(n=o,e=[i]):o===n&&e.push(i)}}return e}function rc(s,t){return t.some(e=>!!s[e])}function oc(s,t){for(let e=0;e<s.length;e++){const n=s[e];if(t[n])return e}return Number.POSITIVE_INFINITY}function Pi(s,t){if(t==null)return!1;for(const e of s)if(t[e])return e;return!1}const ye=()=>{const s=Wn(),t=Wn(),e={emit:s.emit,on:i=>t.on(i)},n={emit:t.emit,on:i=>s.on(i)};return[e,n]},ji=()=>{const s=Wn();return{emit:n=>{s.emit(n)},on:n=>{s.on(n)}}};class xe{constructor(t){A(this,"reachValue",1e3);A(this,"m");this.m=t}get summary(){return structuredClone(this.m)}reach(t){this.m[t]-=this.reachValue}restoreReachStick(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 Ee{constructor(t,e){A(this,"pToW",{});A(this,"wToP",G(""));A(this,"round");A(this,"sticks");this.round=(e==null?void 0:e.round)??"1w1",this.sticks=(e==null?void 0:e.sticks)??{reach:0,dead:0},this.pToW=t;for(let n in this.pToW)this.wToP[this.pToW[n]]=n}update(){for(let t in this.pToW){const e=Et(this.pToW[t]);this.pToW[t]=e,this.wToP[e]=t}}incrementDeadStick(){this.sticks.dead++}incrementReachStick(){this.sticks.reach++}nextRound(){const t=_e(this.round);this.round=t,this.update()}decrementReachStick(){this.sticks.reach--,O(this.sticks.reach>=0)}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 ps(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 zi{constructor(t=!1){A(this,"c",{[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]});A(this,"safeMap",G({},!0));this.disable=t}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 e==0&&(e=5),`${t}${e}`}reset(){this.c={[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 ms{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 ac(){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 cc(){const s=ac();if(s.__xstate__)return s.__xstate__}const hc=s=>{if(typeof window>"u")return;const t=cc();t&&t.register(s)};class Ps{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=".",lc="",Ki="",uc="#",fc="*",Fi="xstate.init",Pn="xstate.stop";function dc(s,t){return{type:`xstate.after.${s}.${t}`}}function jn(s,t){return{type:`xstate.done.state.${s}`,output:t}}function pc(s,t){return{type:`xstate.done.actor.${s}`,output:t,actorId:s}}function mc(s,t){return{type:`xstate.error.actor.${s}`,error:t,actorId:s}}function Ui(s){return{type:Fi,input:s}}function wt(s){setTimeout(()=>{throw s})}const gc=typeof Symbol=="function"&&Symbol.observable||"@@observable";function Zi(s,t){const e=js(s),n=js(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?Zi(e[i],n[i]):!1)}function gs(s){if(Gi(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 js(s){if(Yc(s))return s.value;if(typeof s!="string")return s;const t=gs(s);return yc(t)}function yc(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 zs(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 qi(s){return Gi(s)?s:[s]}function St(s){return s===void 0?[]:qi(s)}function zn(s,t,e,n){return typeof s=="function"?s({context:t,event:e,self:n}):s}function Gi(s){return Array.isArray(s)}function wc(s){return s.type.startsWith("xstate.error.actor")}function Yt(s){return qi(s).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function Yi(s){if(!(s===void 0||s===lc))return St(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 Ls(s,t){return`${t}.${s}`}function ys(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 Ks(s,t){return`${s.sessionId}.${t}`}let _c=0;function bc(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 x={source:f,target:m,event:d,delay:g,id:_,startedAt:Date.now()},k=Ks(f,_);u._snapshot._scheduledEvents[k]=x;const R=a.setTimeout(()=>{delete o[k],delete u._snapshot._scheduledEvents[k],u._relay(f,m,d)},g);o[k]=R},cancel:(f,m)=>{const d=Ks(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:${_c++}`,_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:x,id:k}=f[m];h.schedule(d,g,_,x,k)}},_clock:a,_logger:c};return u}const ws=1;let q=function(s){return s[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Stopped=2]="Stopped",s}({});const vc={clock:{setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s)},logger:console.log.bind(console),devTools:!1};class Ac{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 Ps(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=q.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={...vc,...e},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:h,inspect:l}=n;this.system=o?o.system:bc(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){wt(a)}break;case"done":for(const o of this.observers)try{(r=o.next)==null||r.call(o,t)}catch(a){wt(a)}this._stopProcedure(),this._complete(),this._doneEvent=pc(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!==q.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{(r=i.complete)==null||r.call(i)}catch(o){wt(o)}break;case"error":{const o=this._snapshot.error;if(!i.error)wt(o);else try{i.error(o)}catch(a){wt(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===q.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=q.Running;const t=Ui(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===Pn&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===q.Stopped?this:(this.mailbox.clear(),this._processingStatus===q.NotStarted?(this._processingStatus=q.Stopped,this):(this.mailbox.enqueue({type:Pn}),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){wt(n)}this.observers.clear()}_reportError(t){if(!this.observers.size){this._parent||wt(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){wt(r)}}this.observers.clear(),e&&wt(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,mc(this.id,t))}_stopProcedure(){return this._processingStatus!==q.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Ps(this._process.bind(this)),this._processingStatus=q.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==q.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:hc)(this)}toJSON(){return{xstate$$type:ws,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[gc](){return this}getSnapshot(){return this._snapshot}}function oe(s,...[t]){return new Ac(s,t)}function Sc(s,t,e,n,{sendId:i}){const r=typeof i=="function"?i(e,n):i;return[t,r]}function xc(s,t){s.defer(()=>{s.system.scheduler.cancel(s.self,t)})}function Ec(s){function t(e,n){}return t.type="xstate.cancel",t.sendId=s,t.resolve=Sc,t.execute=xc,t}function kc(s,t,e,n,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const h=typeof o=="string"?ys(t.machine,o):o,l=typeof i=="function"?i(e):i;let u;return h&&(u=oe(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})),[Lt(t,{children:{...t.children,[l]:u}}),{id:i,actorRef:u}]}function Tc(s,{id:t,actorRef:e}){e&&s.defer(()=>{e._processingStatus!==q.Stopped&&e.start()})}function Oc(...[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=kc,r.execute=Tc,r}function Ic(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]),[Lt(t,{children:a}),o]}function Nc(s,t){if(t){if(s.system._unregister(t),t._processingStatus!==q.Running){s.stopChild(t);return}s.defer(()=>{s.stopChild(t)})}}function Xi(s){function t(e,n){}return t.type="xstate.stopChild",t.actorRef=s,t.resolve=Ic,t.execute=Nc,t}function _s(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 _s(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 bs=s=>s.type==="atomic"||s.type==="final";function ae(s){return Object.values(s.states).filter(t=>t.type!=="history")}function We(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 Ve(s){const t=new Set(s),e=Vi(t);for(const n of t)if(n.type==="compound"&&(!e.get(n)||!e.get(n).length))Fs(n).forEach(i=>t.add(i));else if(n.type==="parallel"){for(const i of ae(n))if(i.type!=="history"&&!t.has(i)){const r=Fs(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 Ji(s,t){const e=t.get(s);if(!e)return{};if(s.type==="compound"){const i=e[0];if(i){if(bs(i))return i.key}else return{}}const n={};for(const i of e)n[i.key]=Ji(i,t);return n}function Vi(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 Qi(s,t){const e=Ve(t);return Ji(s,Vi(e))}function vs(s,t){return t.type==="compound"?ae(t).some(e=>e.type==="final"&&s.has(e)):t.type==="parallel"?ae(t).every(e=>vs(s,e)):t.type==="final"}const cn=s=>s[0]===uc;function Cc(s,t){return s.transitions.get(t)||[...s.transitions.keys()].filter(n=>{if(n===fc)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 Dc(s){const t=s.config.after;if(!t)return[];const e=(i,r)=>{const o=dc(i,s.id),a=o.type;return s.entry.push(ih(o,{id:a,delay:i})),s.exit.push(Ec(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 St(a).map(l=>({...l,event:h,delay:c}))}).map(i=>{const{delay:r}=i;return{...Rt(s,i.event,i),delay:r}})}function Rt(s,t,e){const n=Yi(e.target),i=e.reenter??!1,r=Hc(s,n),o={...e,actions:St(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 Mc(s){const t=new Map;if(s.config.on)for(const e of Object.keys(s.config.on)){if(e===Ki)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=>Rt(s,e,i)))}if(s.config.onDone){const e=`xstate.done.state.${s.id}`;t.set(e,Yt(s.config.onDone).map(n=>Rt(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=>Rt(s,n,i)))}if(e.onError){const n=`xstate.error.actor.${e.id}`;t.set(n,Yt(e.onError).map(i=>Rt(s,n,i)))}if(e.onSnapshot){const n=`xstate.snapshot.${e.id}`;t.set(n,Yt(e.onSnapshot).map(i=>Rt(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 Rc(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"?[]:St(t.actions),eventType:null,reenter:!1,target:e?[e]:[],toJSON:()=>({...n,source:`#${s.id}`,target:e?[`#${e.id}`]:[]})};return n}function Hc(s,t){if(t!==void 0)return t.map(e=>{if(typeof e!="string")return e;if(cn(e))return s.machine.getStateNodeById(e);const n=e[0]===Li;if(n&&!s.parent)return Qe(s,e.slice(1));const i=n?s.key+e:e;if(s.parent)try{return Qe(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 tr(s){const t=Yi(s.config.target);return t?{target:t.map(e=>typeof e=="string"?Qe(s.parent,e):e)}:s.parent.initial}function Ht(s){return s.type==="history"}function Fs(s){const t=er(s);for(const e of t)for(const n of We(e,s))t.add(n);return t}function er(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 ae(n))e(i)}}return e(s),t}function ce(s,t){if(cn(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 Qe(s,t){if(typeof t=="string"&&cn(t))try{return s.machine.getStateNodeById(t)}catch{}const e=gs(t).slice();let n=s;for(;e.length;){const i=e.shift();if(!i.length)break;n=ce(n,i)}return n}function tn(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=>ce(s,i)).filter(Boolean);return[s.machine.root,s].concat(n,e.reduce((i,r)=>{const o=ce(s,r);if(!o)return i;const a=tn(o,t[r]);return i.concat(a)},[]))}function $c(s,t,e,n){const r=ce(s,t).next(e,n);return!r||!r.length?s.next(e,n):r}function Bc(s,t,e,n){const i=Object.keys(t),r=ce(s,i[0]),o=As(r,t[i[0]],e,n);return!o||!o.length?s.next(e,n):o}function Wc(s,t,e,n){const i=[];for(const r of Object.keys(t)){const o=t[r];if(!o)continue;const a=ce(s,r),c=As(a,o,e,n);c&&i.push(...c)}return i.length?i:s.next(e,n)}function As(s,t,e,n){return typeof t=="string"?$c(s,t,e,n):Object.keys(t).length===1?Bc(s,t,e,n):Wc(s,t,e,n)}function Pc(s){return Object.keys(s.states).map(t=>s.states[t]).filter(t=>t.type==="history")}function Ot(s,t){let e=s;for(;e.parent&&e.parent!==t;)e=e.parent;return e.parent===t}function jc(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 nr(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(jc(Kn([i],t,e),Kn([a],t,e)))if(Ot(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 zc(s){const[t,...e]=s;for(const n of We(t,void 0))if(e.every(i=>Ot(i,n)))return n}function Ss(s,t){if(!s.target)return[];const e=new Set;for(const n of s.target)if(Ht(n))if(t[n.id])for(const i of t[n.id])e.add(i);else for(const i of Ss(tr(n),t))e.add(i);else e.add(n);return[...e]}function sr(s,t){const e=Ss(s,t);if(!e)return;if(!s.reenter&&e.every(i=>i===s.source||Ot(i,s.source)))return s.source;const n=zc(e.concat(s.source));if(n)return n;if(!s.reenter)return s.source.machine.root}function Kn(s,t,e){var i;const n=new Set;for(const r of s)if((i=r.target)!=null&&i.length){const o=sr(r,e);r.reenter&&r.source===o&&n.add(o);for(const a of t)Ot(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=nr(s,o,a);let h=t;i||([h,a]=Zc(h,n,e,c,o,a,r)),h=he(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=he(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:Lt(h,{_nodes:l,historyValue:a})}catch(u){throw u}}function Kc(s,t,e,n,i){if(n.output===void 0)return;const r=jn(i.id,i.output!==void 0&&i.parent?zn(i.output,s.context,t,e.self):void 0);return zn(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;Uc(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(Oc(d.src,{...d,syncSnapshot:!!d.onSnapshot}));if(l.has(f)){const d=f.initial.actions;m.push(...d)}if(c=he(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(jn(d.id,f.output!==void 0?zn(f.output,c.context,t,e.self):void 0));(g==null?void 0:g.type)==="parallel"&&!u.has(g)&&vs(i,g);)u.add(g),r.push(jn(g.id)),_=g,g=g.parent;if(g)continue;c=Lt(c,{status:"done",output:Kc(c,t,e,c.machine.root,_)})}}return c}function Uc(s,t,e,n){for(const i of s){const r=sr(i,t);for(const a of i.target||[])!Ht(a)&&(i.source!==a||i.source!==r||i.reenter)&&(n.add(a),e.add(a)),Qt(a,t,e,n);const o=Ss(i,t);for(const a of o){const c=We(a,r);(r==null?void 0:r.type)==="parallel"&&c.push(r),ir(n,t,e,c,!i.source.parent&&i.reenter?void 0:r)}}}function Qt(s,t,e,n){var i;if(Ht(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)_n(o,s.parent,n,t,e)}else{const r=tr(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)_n(o,s.parent,n,t,e)}else if(s.type==="compound"){const[r]=s.initial.target;Ht(r)||(n.add(r),e.add(r)),Qt(r,t,e,n),_n(r,s,n,t,e)}else if(s.type==="parallel")for(const r of ae(s).filter(o=>!Ht(o)))[...n].some(o=>Ot(o,r))||(Ht(r)||(n.add(r),e.add(r)),Qt(r,t,e,n))}function ir(s,t,e,n,i){for(const r of n)if((!i||Ot(r,i))&&s.add(r),r.type==="parallel")for(const o of ae(r).filter(a=>!Ht(a)))[...s].some(a=>Ot(a,o))||(s.add(o),Qt(o,t,e,s))}function _n(s,t,e,n,i){ir(e,n,i,We(s,t))}function Zc(s,t,e,n,i,r,o){let a=s;const c=Kn(n,i,r);c.sort((l,u)=>u.order-l.order);let h;for(const l of c)for(const u of Pc(l)){let f;u.history==="deep"?f=m=>bs(m)&&Ot(m,l):f=m=>m.parent===l,h??(h={...r}),h[u.id]=Array.from(i).filter(f)}for(const l of c)a=he(a,t,e,[...l.exit,...l.invoke.map(u=>Xi(u.id))],o),i.delete(l);return[a,h||r]}let Us=!1;function rr(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{Us=l,l(u,f)}finally{Us=!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===q.Running?m():e.defer(()=>{m()});continue}const d=l,[g,_,x]=d.resolve(e,a,u,f,l,i);a=g,"retryResolve"in d&&(r==null||r.push([d,_])),"execute"in d&&(e.self._processingStatus===q.Running?d.execute(e,_):e.defer(d.execute.bind(null,e,_))),x&&(a=rr(a,t,e,x,i,r))}return a}function he(s,t,e,n,i,r){const o=r?[]:void 0,a=rr(s,t,e,n,{internalQueue:i,deferredActorIds:r},o);return o==null||o.forEach(([c,h])=>{c.retryResolve(e,a,h)}),a}function bn(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===Pn)return i=Lt(Zs(i,t,e),{status:"stopped"}),o(i,t,[]),{snapshot:i,microstates:r};let a=t;if(a.type!==Fi){const h=a,l=wc(h),u=qs(h,i);if(l&&!u.length)return i=Lt(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?qc(i,a):[];const l=h.length?i:void 0;if(!h.length){if(!n.length)break;a=n.shift(),h=qs(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 he(s,t,e,Object.values(s.children).map(n=>Xi(n)),[])}function qs(s,t){return t.machine.getTransitionData(t,s)}function qc(s,t){const e=new Set,n=s._nodes.filter(bs);for(const i of n)t:for(const r of[i].concat(We(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||_s(o.guard,s.context,t,s)){e.add(o);break t}}return nr(Array.from(e),new Set(s._nodes),s.historyValue)}function Gc(s,t){const e=Ve(tn(s,t));return Qi(s,[...e])}function Yc(s){return!!s&&typeof s=="object"&&"machine"in s&&"value"in s}const Xc=function(t){return Zi(t,this.value)},Jc=function(t){return this.tags.has(t)},Vc=function(t){const e=this.machine.getTransitionData(this,t);return!!(e!=null&&e.length)&&e.some(n=>n.target!==void 0||n.actions.length)},Qc=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)}},th=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:Qi(t.root,s._nodes),tags:new Set(s._nodes.flatMap(e=>e.tags)),children:s.children,historyValue:s.historyValue||{},matches:Xc,hasTag:Jc,can:Vc,getMeta:th,toJSON:Qc}}function Lt(s,t={}){return Fe({...s,...t},s.machine)}function eh(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:or(o),children:m}}function or(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:ws,id:n.id};else{const i=or(n);i!==n&&(t??(t=Array.isArray(s)?s.slice():{...s}),t[e]=i)}}return t??s}function nh(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 sh(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 ih(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=nh,e.execute=sh,e}function rh(s,{machine:t,context:e},n,i){const r=(o,a={})=>{const{systemId:c,input:h}=a;if(typeof o=="string"){const l=ys(t,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${t.id}'`);const u=oe(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 oe(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!==q.Stopped&&c.start()}),c}}function oh(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:rh(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[Lt(t,{context:c,children:Object.keys(r).length?{...t.children,...r}:t.children})]}function ah(s){function t(e,n){}return t.type="xstate.assign",t.assignment=s,t.resolve=oh,t}const Gs=new WeakMap;function Gt(s,t,e){let n=Gs.get(s);return n?t in n||(n[t]=e()):(n={[t]:e()},Gs.set(s,n)),n[t]}const ch={},pe=s=>typeof s=="string"?{type:s}:typeof s=="function"?"resolve"in s?{type:s.type}:{type:s.name}:s;class xs{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?zs(this.config.states,(n,i)=>new xs(n,{_parent:this,_key:i,_machine:this.machine})):ch,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=St(this.config.entry).slice(),this.exit=St(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=St(t.tags).slice()}_initialize(){this.transitions=Mc(this),this.config.always&&(this.always=Yt(this.config.always).map(t=>Rt(this,Ki,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(pe),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(pe),eventType:null})}:void 0,history:this.history,states:zs(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(pe)})),entry:this.entry.map(pe),exit:this.exit.map(pe),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 Gt(this,"invoke",()=>St(this.config.invoke).map((t,e)=>{const{src:n,systemId:i}=t,r=t.id??Ls(this.id,e),o=typeof n=="string"?n:`xstate.invoke.${Ls(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 Gt(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 Gt(this,"delayedTransitions",()=>Dc(this))}get initial(){return Gt(this,"initial",()=>Rc(this,this.config.initial))}next(t,e){const n=e.type,i=[];let r;const o=Gt(this,`candidates-${n}`,()=>Cc(this,n));for(const a of o){const{guard:c}=a,h=t.context;let l=!1;try{l=!c||_s(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
+ ${u.message}`)}if(l){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return Gt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const n of Object.keys(t)){const i=t[n];if(i.states)for(const r of i.events)e.add(`${r}`)}return Array.from(e)})}get ownEvents(){const t=new Set([...this.transitions.keys()].filter(e=>this.transitions.get(e).some(n=>!(!n.target&&!n.actions.length&&!n.reenter))));return Array.from(t)}}const hh="#";class Es{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 xs(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:n,actors:i,delays:r}=this.implementations;return new Es(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...i,...t.actors},delays:{...r,...t.delays}})}resolveState(t){const e=Gc(this.root,t.value),n=Ve(tn(this.root,e));return Fe({_nodes:[...n],context:t.context||{},children:{},status:vs(n,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return bn(t,e,n).snapshot}microstep(t,e,n){return bn(t,e,n).microstates}getTransitionData(t,e){return As(this.root,t.value,t,e)||[]}getPreInitialState(t,e,n){const{context:i}=this.config,r=Fe({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?he(r,e,t,[ah(({spawn:a,event:c,self:h})=>i({spawn:a,input:c.input,self:h}))],n):r}getInitialSnapshot(t,e){const n=Ui(e),i=[],r=this.getPreInitialState(t,n,i),o=Fn([{target:[...er(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,t,n,!0,i),{snapshot:a}=bn(o,n,t,i);return a}start(t){Object.values(t.children).forEach(e=>{e.getSnapshot().status==="active"&&e.start()})}getStateNodeById(t){const e=gs(t),n=e.slice(1),i=cn(e[0])?e[0].slice(hh.length):e[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return Qe(r,n)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return eh(t,e)}restoreSnapshot(t,e){const n={},i=t.children;Object.keys(i).forEach(c=>{const h=i[c],l=h.snapshot,u=h.src,f=typeof u=="string"?ys(this,u):u;if(!f)return;const m=oe(f,{id:c,parent:e.self,syncSnapshot:h.syncSnapshot,snapshot:l,src:u,systemId:h.systemId});n[c]=m});const r=Fe({...t,children:n,_nodes:Array.from(Ve(tn(this.root,t.value)))},this);let o=new Set;function a(c,h){if(!o.has(c)){o.add(c);for(let l in c){const u=c[l];if(u&&typeof u=="object"){if("xstate$$type"in u&&u.xstate$$type===ws){c[l]=h[u.id];continue}a(u,h)}}}}return a(r.context,n),r}}function lh(s,t){return new Es(s,t)}const Le=s=>s===!1?!1:s.map(t=>t.serialize()),uh=s=>s===!1?!1:s.serialize(),fh=s=>s===!1?!1:s.map(t=>({tile:t.tile.toString(),candidates:t.candidates.map(e=>e.toString()),shanten:t.shanten})),Un=s=>JSON.parse(JSON.stringify(s)),Ke=s=>s===!1?!1:Un(s),Zn=s=>lh({id:"Untitled",initial:"distribute",context:{currentWind:v.E,oneShotMap:G(!1),missingMap:G(!1),controller:s,genEventID:ar()},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
+ 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
+ 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 に対するレスポンスを待つ\\
14
12
  ユーザからではなく、controller が優先順位を考慮して遷移させる必要がある\\
15
- 通知する 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"}}},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:{on:{NEXT:{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:"チャンカンを待つ",exit:[{type:"notify_draw",params:{action:"kan"}},{type:"notify_choice_after_drawn",params:{replacementWin:!0}}],on:{RON:{target:"roned",guard:"canWin"},"*":{target:"waiting_user_event_after_drawn"}}},drawn_game:{exit:{type:"notify_end",params:{}},type:"final"}},types:{events:{},context:{}}},{actions:{updateNextWind:({context:t,event:e})=>{const n=t.currentWind;t.currentWind=At(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(let r of Object.values(v)){const o=G("_____________");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:bn(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n==null?void 0:n.replacementWin})),REACH:hh(t.controller.doReach(i)),AN_KAN:je(t.controller.doAnKan(i)),SHO_KAN:je(t.controller.doShoKan(i)),DISCARD:t.controller.doDiscard(i).map(c=>c.toString()),DRAWN_GAME_BY_NINE_TILES: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:b.HORIZONTAL});for(let 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:bn(t.controller.doWin(o,r,{whoDiscarded:i.w,oneShot:t.oneShotMap[o],missingRon:t.missingMap[o]})),PON:je(t.controller.doPon(o,i.w,r)),CHI:je(t.controller.doChi(o,i.w,r)),DAI_KAN:ch(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 ct||a instanceof ft)&&(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_chankan:({context:t,event:e})=>{if(e.type!="SHO_KAN"&&e.type!="AN_KAN")throw new Error(`unexpected event ${e.type}`);const n=t.genEventID(),i=e.block.tiles[0].clone({remove:b.HORIZONTAL});for(let r of Object.values(v)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:b.HORIZONTAL}),{whoDiscarded: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"?bn(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})=>{if(!(e.type=="CHI"||e.type=="PON"||e.type=="DAI_KAN"||e.type=="AN_KAN"||e.type=="SHO_KAN"))throw new Error(`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam;t.currentWind=i;for(let 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})=>{if(e.type!="DISCARD"&&e.type!="REACH")throw new Error(`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind,r=e.tile;for(let 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(let c of Object.values(v)){let h=new g(d.BACK,0,[b.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})=>{const n=t.genEventID();if(e.type=="RON"){const i=e.targetInfo.wind,r=t.currentWind,o=i==r&&t.oneShotMap[r]==!0,a=e.iam;for(let c of Object.values(v)){const h={id:n,type:e.type,iam:a,wind:c,victimInfo:{wind:e.targetInfo.wind,tile:e.targetInfo.tile.toString()},ret:Un(e.ret),pushBackReachStick:o};t.controller.emit(h)}}},notify_tsumo:({context:t,event:e})=>{if(e.type!="TSUMO")throw new Error(`unexpected event ${e.type}`);const n=t.genEventID(),i=t.currentWind;for(let r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:Un(e.ret)};t.controller.emit(o)}},notify_reach:({context:t,event:e})=>{if(e.type!="REACH")throw new Error(`unexpected event ${e.type}`);const n=t.genEventID(),i=e.iam,r=e.tile.clone({add:b.HORIZONTAL});t.oneShotMap[i]=!0;for(let o of Object.values(v)){const a={id:n,type:e.type,iam:i,wind:o,tile:r.toString()};t.controller.emit(a)}},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(let 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(let 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=G("");if(e.type=="DRAWN_GAME_BY_NINE_TILES"){i[e.iam]=t.controller.hand(e.iam).toString();for(let 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:G(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(let 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(let 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:G(0),hands:G("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(let h of Object.values(v)){const l=t.controller.hand(h);new $e(l).calc()==0&&(r.push(h),i[h]=l.toString())}const o=r.length==0||r.length==4,a=G(0);for(let 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(let 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 rr(s=0){let t=s;return()=>(t++).toString()}class Ht{constructor(t){S(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});S(this,"backup");S(this,"openedDoraCount",1);this.init(t),this.backup=Ht.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(),g.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return g.from(this.walls.drawable.pop())}openDoraMarker(){if(this.openedDoraCount>=4)throw new Error("exceeded maximum open dora");return this.openedDoraCount++,g.from(this.walls.doraMarkers[this.openedDoraCount-1])}get doraMarkers(){return this.walls.doraMarkers.slice(0,this.openedDoraCount).map(g.from)}get blindDoraMarkers(){return this.walls.blindDoraMarkers.slice(0,this.openedDoraCount).map(g.from)}get canKan(){return this.walls.replacement.length>0}get canDraw(){return this.walls.drawable.length>0}init(t){if(t!=null){this.walls=Ht.clone(t);return}else{for(let e of Object.values(d)){if(e==d.BACK)continue;const n=e==d.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)e!=d.Z&&i==3&&r==5&&(r=0),this.walls.drawable.push(new g(e,r).toString())}ds(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 Be{constructor(t,e){S(this,"wall",new Ht);S(this,"playerIDs");S(this,"actor",se(Fn(this),{}));S(this,"observer");S(this,"handlers",{});S(this,"mailBox",{});S(this,"histories",[]);S(this,"debugMode");S(this,"snapshot");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=Bi();this.observer=new or(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new xe(i);const r=ds(this.playerIDs.concat());this.observer.placeManager=new ke({[r[0]]:v.E,[r[1]]:v.S,[r[2]]:v.W,[r[3]]:v.N})}boardParams(t){const e=this.hand(t);return{doraMarkers:this.observer.doraMarkers,round:this.placeManager.round,myWind:t,sticks:this.observer.placeManager.sticks,reached:e.reached?this.river.discards(t).length!=0?1:2:void 0}}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=Ri(n);if(r.events.length==0){this.actor.send({type:""});return}const o=r.events[0];switch(r.type){case"RON":C(o.choices.RON,"ron choice is none"),this.actor.send({type:r.type,iam:o.wind,ret:Le(o.choices.RON),targetInfo:{wind:o.discarterInfo.wind,tile:g.from(o.discarterInfo.tile)}});break;case"DAI_KAN":C(o.choices.DAI_KAN,"daikan choice is none"),this.actor.send({type:r.type,iam:o.wind,block:ut.from(o.choices.DAI_KAN.tiles)});break;case"CHI":case"PON":const a=o.choices[r.type];C(a,`${r.type} choice is none`),C(r.events.length==1,`found more than one selected: ${JSON.stringify(r,null,2)}`);const c=W.deserialize(a[0]);this.actor.send({type:r.type,iam:o.wind,block:c})}}else if(i.type=="CHOICE_AFTER_DRAWN"){const r=Hi(n);C(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":C(o.choices.TSUMO,"tsumo choice is none"),this.actor.send({type:r.type,ret:Le(o.choices.TSUMO),lastTile:g.from(o.drawerInfo.tile),iam:a});break;case"REACH":const c=o.choices[r.type];C(c,`${r.type} candidates is none`),this.actor.send({type:r.type,tile:g.from(c[0].tile),iam:a});break;case"DISCARD":const h=o.choices[r.type];C(h,`${r.type} choice is none`),this.actor.send({type:r.type,tile:g.from(h[0]).clone({remove:b.TSUMO}),iam:a});break;case"AN_KAN":{const l=o.choices[r.type];C(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];C(l,`${r.type} choice is none`),this.actor.send({type:r.type,block:at.from(l[0].tiles),iam:a});break}case"DRAWN_GAME_BY_NINE_TILES":this.actor.send({type:"DRAWN_GAME_BY_NINE_TILES",iam:a});break}}else if(i.type=="CHOICE_AFTER_CALLED"){C(i.choices.DISCARD,`discard candidate tile is none: ${JSON.stringify(i,null,2)} ${this.hand(i.wind).toString()}`);const r=i.wind,o=g.from(i.choices.DISCARD[0]);C(o!=null,`undefined tile ${this.hand(r).toString()}`),this.actor.send({type:"DISCARD",tile:o,iam:r})}else if(i.type=="CHOICE_FOR_CHAN_KAN"){const r=n.filter(a=>a.choices.RON);if(r.length==0){this.actor.send({type:""});return}const o=r[0];C(o.choices.RON,"ron choice is none"),this.actor.send({type:"RON",iam:o.wind,ret:Le(o.choices.RON),quadWin:!0,targetInfo:{wind:o.callerInfo.wind,tile:g.from(o.callerInfo.tile)}})}}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 Be(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new ke(t.players,{round:structuredClone(t.round),sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new xe(t.scores),o.wall=new Ht(t.wall),o}start(){this.actor.subscribe(e=>{console.debug("State:",e.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),this.actor.getSnapshot().status}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new Ht,this.observer.applied={},this.mailBox={},this.actor=se(Fn(this)),!this.placeManager.is(P.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.blindDoraMarkers:void 0,r=new $n(n,{...t.boardContext,sticks:this.placeManager.sticks,blindDoraMarkers:i}).calc([t.hand]);return C(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.whoDiscarded==t||n.missingRon)return!1;i=i.clone(),r.ronWind=n.whoDiscarded,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 Di(i),a=new $n(i,r),c=o.calc(e),h=a.calc(c);if(!h||h.points.length==0)return!1;if(i.draw==null){const l=zt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).map(f=>f.t).some(f=>l.some(m=>m.equals(f,!0))))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)return!1;let r=n.clone({remove:b.HORIZONTAL});if(j(n)&&(r=r.clone({n:5})),i.get(n.t,r.n)<2)return!1;const o=[];let a=Math.abs(Number(t[0])-Number(e[0]));a==3&&(a=0),a==2&&(a=1),a==1&&(a=2);let c=new ft([r,r,r]);c=c.clone({replace:{idx:a,tile:n.clone({add:b.HORIZONTAL})}});const h=a%2+1,l=c.tiles[h];if(V(n)&&i.get(n.t,0)>0&&(c=c.clone({replace:{idx:h,tile:l.clone({n:0})}})),o.push(c),V(n)&&i.get(n.t,r.n)==3){const u=c.clone({replace:{idx:h,tile:l.clone({n:5})}});o.push(u)}return o}doChi(t,e,n){if(n==null||!n.isNum()||At(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;let r=n;j(r)&&(r=n.clone({n:5}));const o=[],a=r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0,c=n.clone({add:b.HORIZONTAL,remove:b.TSUMO});if(a&&o.push(new ct([c,new g(n.t,r.n-1),new g(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 ct([c,new g(n.t,r.n+1),new g(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 ct([c,new g(n.t,r.n-1),new g(n.t,r.n+1)])),o.length==0)return!1;if(i.hands.length==4){const m=o[0],p=this.cannotDiscardTile(o[0]),y=i.dec([m.tiles[1],m.tiles[2]]),w=p.reduce((x,O)=>x+i.get(O.t,O.n),0)==2;if(i.inc(y),w)return!1}const u=i.get(n.t,0)>0,f=this.redPattern(o,u);return f.length>0&&i.get(n.t,5)==1?f:o.concat(f)}redPattern(t,e){return t.length==0?[]:e?t.filter(i=>V(i.tiles[1])||V(i.tiles[2])).map(i=>{if(V(i.tiles[1])){const r=i.tiles[1].clone({n:0});return i.clone({replace:{idx:1,tile:r}})}else if(V(i.tiles[2])){const r=i.tiles[2].clone({n:0});return i.clone({replace:{idx:2,tile:r}})}}).filter(i=>i!=null):[]}doReach(t){const e=this.hand(t);return e.reached||!e.menzen||new $e(e).calc()>0?!1:zt.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 ft)return n.filter(o=>!o.equals(e.tiles[0],!0));const i=this.cannotDiscardTile(e),r=n.filter(o=>!i.some(a=>o.equals(a,!0)));return C(r.length>0,`no tiles to discard. hand: ${this.hand(t)}, suji: ${i}, block-chi: ${e}`),r}cannotDiscardTile(t){let e=t.tiles[0].n,n=t.tiles[1].n;const i=t.tiles[0].t;return e==0&&(e=5),n==0&&(n=5),e-2==n?[new g(i,e-3),new g(i,e)]:e+1==n?[new g(i,e+3),new g(i,e)]:[]}doAnKan(t){const e=this.hand(t),n=[];if(e.reached)return!1;for(let i of Object.values(d))for(let r=1;r<e.getArrayLen(i);r++)if(e.get(i,r)==4){const o=[new g(i,r),new g(i,r),new g(i,r),new g(i,r)];i!=d.Z&&r==5&&(o[0]=o[0].clone({n:0})),n.push(new U(o))}if(n.length==0)return!1;for(let i of n)C(i.tiles.filter(r=>r.has(b.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 ft);if(n.length==0)return!1;const i=[];for(let r of n){const o=r.tiles[0];if(e.get(o.t,o.n)==1){const a=[...r.tiles,new g(o.t,o.n,[b.HORIZONTAL])];V(o)&&e.get(o.t,0)==1&&a[3].n==0,i.push(new at(a))}}if(i.length==0)return!1;for(let r of i)C(r.tiles.filter(o=>o.has(b.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;let r=n.clone({remove:b.HORIZONTAL});if(j(r)&&(r=r.clone({n:5})),i.get(r.t,r.n)!=3)return!1;let o=new ut([r,r,r,r]),a=Math.abs(Number(t[0])-Number(e[0]));a==3&&(a=0),a==1&&(a=3);let c=o.clone({replace:{idx:a,tile:n.clone({add:b.HORIZONTAL})}});if(V(r)&&V(n)){const h=a%3+1,l=c.tiles[h].clone({n:0});c=c.clone({replace:{idx:h,tile:l}})}return C(c.tiles.filter(h=>h.has(b.HORIZONTAL)).length==1,`h op ${c.toString()}`),c}canDrawnGame(t){if(this.river.discards(t).length!=0)return!1;const e=this.hand(t);let n=e.get(d.M,1)+e.get(d.M,9)+e.get(d.S,1)+e.get(d.S,9)+e.get(d.P,1)+e.get(d.P,9);for(let i=0;i<e.getArrayLen(d.Z);i++)n+=e.get(d.Z,i);return n>=9}initialHands(){const t=G("");for(let e=0;e<3;e++)for(let n of Object.values(v))for(let i=0;i<4;i++)t[n]+=this.wall.draw().toString();for(let e of Object.values(v))t[e]+=this.wall.draw().toString();return t}}class jt extends He{isBackHand(){for(let t of Object.values(d))if(t!=d.BACK&&this.sum(t)>0)return!1;return this.sum(d.BACK)>0}clone(){const t=new jt(this.toString());return t.data.reached=this.data.reached,t}dec(t){return this.isBackHand()?(super.dec(t.map(()=>new g(d.BACK,0))),[...t]):super.dec(t)}}class ks{constructor(t,e){S(this,"id");S(this,"river",new ps);S(this,"placeManager",new ke({}));S(this,"scoreManager",new xe({}));S(this,"hands",G(new jt("")));S(this,"counter",new zi);S(this,"doraMarkers",[]);S(this,"eventHandler");this.id=t,this.eventHandler=e}hand(t){return this.hands[t]}handleEvent(t){try{switch(t.type){case"CHOICE_AFTER_CALLED":case"CHOICE_AFTER_DISCARDED":case"CHOICE_AFTER_DRAWN":case"CHOICE_FOR_CHAN_KAN":break;case"DISTRIBUTE":this.counter.reset();const e=g.from(t.doraMarker);this.setHands(t),this.placeManager=new ke(structuredClone(t.places),{round:structuredClone(t.round),sticks:structuredClone(t.sticks)}),this.scoreManager=new xe(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(let i of Object.values(v))i==t.wind&&this.counter.dec(...this.hand(i).hands);break;case"DRAW":{const i=g.from(t.tile);this.hands[t.iam].draw(i),this.counter.dec(i);break}case"DISCARD":{const i=g.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(let r of Object.values(v))this.hand(r).reached&&this.counter.addTileToSafeMap(i,r)}break}case"PON":case"CHI":case"DAI_KAN":{const i=W.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(b.HORIZONTAL)));break}case"SHO_KAN":{const i=at.from(t.block.tiles);this.hands[t.iam].kan(i),t.iam!=t.wind&&this.counter.dec(i.tiles.filter(r=>r.has(b.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(b.HORIZONTAL)));break}case"REACH":const n=this.placeManager.playerID(t.iam);this.hands[t.iam].reach(),this.scoreManager.reach(n),this.placeManager.incrementReachStick();break;case"NEW_DORA":{const i=g.from(t.doraMarker);this.doraMarkers.push(i),this.counter.dec(i);break}case"TSUMO":break;case"RON":if(t.pushBackReachStick){const i=t.victimInfo.wind,r=this.placeManager.playerID(i);this.scoreManager.restoreReachStick(r),this.placeManager.decrementReachStick()}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)}`)}}catch(e){throw new Error(`${this.id} ${t.type} ${e}`)}}}class or extends ks{constructor(e){super("observer",e);S(this,"applied",{});this.counter.disable=!0,this.hands=G(new jt("_____________"))}setHands(e){this.hands[e.wind]=new jt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let n=!0;for(let i of Object.values(v))n&&(n=this.hand(i).get(d.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(let i of Object.values(v))console.debug(this.placeManager.playerID(i),`init hand: ${this.hand(i).toString()}`);break;case"DRAW":console.debug(this.placeManager.playerID(e.iam),`draw: ${this.hand(e.iam).drawn}`,`hand: ${this.hand(e.iam).toString()}`);break;case"DISCARD":console.debug(this.placeManager.playerID(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),`call: ${e.block.toString()}`,`hand: ${this.hand(e.iam).toString()}`);break;case"REACH":console.debug(this.placeManager.playerID(e.iam),`reach: ${this.hand(e.iam).toString()}`,`tile: ${e.tile}`);break;case"TSUMO":case"RON":console.debug(this.placeManager.playerID(e.iam),`ron/tsumo: ${JSON.stringify(e.ret,null,2)}`,`hand: ${this.hand(e.iam).toString()}`);break;case"END_GAME":for(let i of Object.values(v))console.debug(this.placeManager.playerID(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 me extends ks{constructor(e,n){super(e,n);S(this,"river",new ps);S(this,"doras",[]);this.eventHandler.on(i=>this.handleEvent(i))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(let n of Object.values(v))this.hands[n]=new jt(e.hands[n])}handleDiscard(e){const n=Object.values(v).filter(l=>l==this.myWind?!1:this.hand(l).reached),i=new $e(this.hand(this.myWind)).calc();if(n.length>0&&i>=2)return Vt.selectTile(this.counter,n,e);const r=zt.calcCandidates(this.hand(this.myWind),e),a=Te.calcPlayerCandidates(this.counter,r).sort((l,u)=>u.sum-l.sum),c=a.filter(l=>l.sum==a[0].sum);return Te.selectMinPriority(this.counter,c,this.doras).tile}handleEvent(e){switch(e.type){case"CHOICE_AFTER_DISCARDED":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(g.from));e.choices.DISCARD=[n.toString()]}this.eventHandler.emit(e);break;case"CHOICE_FOR_CHAN_KAN":this.eventHandler.emit(e);break;default:super.handleEvent(e)}}}class lh{constructor(t){S(this,"index",0);S(this,"histories",[]);this.histories=JSON.parse(t)}next(){C(this.index<this.histories.length),this.index++}prev(){this.index--,C(this.index<0)}start(){Be.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const uh=s=>{const[t,e]=pe(),[n,i]=pe(),[r,o]=pe(),[a,c]=pe(),h=(s==null?void 0:s.playerIDs)??["player-1","player-2","player-3","player-4"];new me(h[0],e),new me(h[1],i),new me(h[2],o),new me(h[3],c);const l=[{handler:t,id:h[0]},{handler:n,id:h[1]},{handler:r,id:h[2]},{handler:a,id:h[3]}];return new Be(l,{debug:s==null?void 0:s.debug})},It=(s,t)=>{let n=1;for(let i of t)i.equals(s,!0)&&(n*=2);return n};class Te{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){C(e.length>0);let i=0,r=0;for(let o=0;o<e.length;o++){const a=Te.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==d.Z)return r=t.get(i),(i.n==5||i.n==6||i.n==7)&&(r*=2),r*It(i,n);{const o=t.get(i);r+=o*It(i,n);const a=t.get(new g(i.t,i.n+1)),c=t.get(new g(i.t,i.n+2)),h=t.get(new g(i.t,i.n-1)),l=t.get(new g(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,p=Math.max(u,m),y=Math.max(m,f);return r+=o*It(i,n),r+=u*It(new g(i.t,i.n-2),n),r+=f*It(new g(i.t,i.n+2),n),r+=p*It(new g(i.t,i.n-1),n),r+=y*It(new g(i.t,i.n+1),n),i.n==0,r}}}class Vt{static selectTile(t,e,n){C(e.length>0&&n.length>0);let i=n[0],r=Number.POSITIVE_INFINITY;for(let o of n){const a=Vt.rank(t,e,o);a<r&&(i=o,r=a)}return i}static rank(t,e,n){let i=0;const r=n.isNum()?Vt.rankN:Vt.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!=d.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=jt;exports.BLOCK=_;exports.BaseActor=ks;exports.Block=W;exports.BlockAnKan=U;exports.BlockCalculator=Di;exports.BlockChi=ct;exports.BlockDaiKan=ut;exports.BlockHand=en;exports.BlockIsolated=Yn;exports.BlockOther=Xn;exports.BlockPair=Z;exports.BlockPon=ft;exports.BlockRun=bt;exports.BlockShoKan=at;exports.BlockThree=ot;exports.Controller=Be;exports.Counter=zi;exports.DoubleCalculator=$n;exports.Efficiency=zt;exports.FONT_FAMILY=qn;exports.Hand=He;exports.INPUT_SEPARATOR=fe;exports.ImageHelper=fs;exports.MeasureText=fr;exports.N19=yt;exports.NZ=Ae;exports.OPERATOR=b;exports.Observer=or;exports.Parser=Q;exports.PlaceManager=ke;exports.Player=me;exports.PlayerEfficiency=Te;exports.ROUND=P;exports.ROUND_MAP=Gn;exports.Replayer=lh;exports.RiskRank=Vt;exports.River=ps;exports.ScoreManager=xe;exports.ShantenCalculator=$e;exports.TABLE_CONTEXT=Zs;exports.TILE_CONTEXT=vt;exports.TYPE=d;exports.Tile=g;exports.WIND=v;exports.WIND_MAP=tn;exports.Wall=Ht;exports.convertInput=Mi;exports.createControllerMachine=Fn;exports.createEventEmitter=Bi;exports.createEventPipe=pe;exports.createHand=Xt;exports.createLocalGame=uh;exports.createTable=Ei;exports.createWindMap=G;exports.deserializeWinResult=Le;exports.drawBlocks=Da;exports.drawTable=ja;exports.incrementalIDGenerator=rr;exports.isNum0=j;exports.isNum5=V;exports.isNum5or0=we;exports.nextRound=ge;exports.nextWind=At;exports.optimizeSVG=Ra;exports.parse=Ii;exports.parseTableInput=Ni;exports.prevRound=wr;exports.prevWind=Xs;exports.prioritizeDiscardedEvents=Ri;exports.prioritizeDrawnEvents=Hi;exports.shuffle=ds;exports.tileSortFunc=ye;
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=Et(n)},notify_distribution:({context:t,event:e})=>{const n=t.genEventID(),i=t.controller.initialHands();for(let r of Object.values(v)){const o=G("_____________");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:Ke(t.controller.doWin(i,r,{oneShot:t.oneShotMap[i],replacementWin:n==null?void 0:n.replacementWin})),REACH:fh(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(let 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:Ke(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:uh(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 ht||a instanceof pt)&&(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(let 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:Ke(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(let 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"?Ke(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(let 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(let 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(let 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(let 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:Un(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(let r of Object.values(v)){const o={id:n,type:e.type,iam:i,wind:r,lastTile:t.controller.hand(i).drawn.toString(),ret:Un(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(let 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(let 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(let 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(let 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=G("");if(e.type=="DRAWN_GAME_BY_NINE_ORPHANS"){i[e.iam]=t.controller.hand(e.iam).toString();for(let 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:G(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(let 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(let 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:G(0),hands:G("")};t.controller.emit(a)}}else{if(t.controller.wall.canDraw)throw new Error(`unexpected event ${e.type}`);{const r=[];for(let h of Object.values(v)){const l=t.controller.hand(h);new Be(l).calc()==0&&(r.push(h),i[h]=l.toString())}const o=r.length==0||r.length==4,a=G(0);for(let 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(let 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 ar(s=0){let t=s;return()=>(t++).toString()}class Bt{constructor(t){A(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});A(this,"backup");A(this,"openedDoraCount",1);this.init(t),this.backup=Bt.clone(this.walls)}kan(){if(this.walls.replacement.length==0)throw new Error("exceeded maximum kan");const t=this.walls.replacement.pop();return this.walls.drawable.pop(),w.from(t)}draw(){if(!this.walls.drawable)throw new Error("cannot draw any more");return w.from(this.walls.drawable.pop())}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=G("");for(let e=0;e<3;e++)for(let n of Object.values(v))for(let i=0;i<4;i++)t[n]+=this.draw().toString();for(let e of Object.values(v))t[e]+=this.draw().toString();return t}init(t){if(t!=null){this.walls=Bt.clone(t);return}else{for(let e of Object.values(p)){if(e==p.BACK)continue;const 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())}}ps(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 Pe{constructor(t,e){A(this,"wall",new Bt);A(this,"playerIDs");A(this,"actor",oe(Zn(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=ji();this.observer=new cr(n),this.observer.eventHandler.on(o=>this.observer.handleEvent(o));const i=Object.fromEntries(this.playerIDs.map(o=>[o,25e3]));this.observer.scoreManager=new xe(i);const r=(e==null?void 0:e.shuffle)==!1?this.playerIDs:ps([...this.playerIDs]);this.observer.placeManager=new Ee({[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=$i(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:ge(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:dt.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=Bi(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:ge(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:F.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:ge(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:ge(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 Pe(r);return o.playerIDs=n,o.mailBox=e,o.observer.placeManager=new Ee(t.players,{round:structuredClone(t.round),sticks:structuredClone(t.sticks)}),o.observer.scoreManager=new xe(t.scores),o.wall=new Bt(t.wall),o}start(){this.actor.subscribe(e=>{console.debug("State:",e.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),this.actor.getSnapshot().status}startGame(){for(;console.debug(`start========${this.placeManager.round}=============`),this.start(),this.wall=new Bt,this.observer.applied={},this.mailBox={},this.actor=oe(Zn(this)),!this.placeManager.is(j.W1););}finalResult(t,e){const n=this.hand(e),i=n.reached?this.wall.blindDoraMarkers:void 0,r=new Bn(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 Ri(i),a=new Bn(i,r),c=o.calc(e),h=a.calc(c);if(!h||h.points.length==0)return!1;if(i.draw==null){const l=zt.candidateTiles(this.hand(t)).candidates;if(this.river.discards(t).map(f=>f.t).some(f=>l.some(m=>m.equals(f))))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)return!1;let r=n.clone({removeAll:!0});if(i.get(n.t,r.n)<2)return!1;const o=vn(t,e,b.PON),a=[],c=new pt([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:new w(r.t,r.n,[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()||Et(e)!=t)return!1;const i=this.hand(t);if(i.reached||i.hands.length<3)return!1;let r=n.has(y.RED)?new w(n.t,n.n,[y.HORIZONTAL,y.RED]):n.clone({removeAll:!0,add:y.HORIZONTAL});const o=[];r.n-2>=1&&i.get(n.t,r.n-2)>0&&i.get(n.t,r.n-1)>0&&o.push(new ht([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 ht([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 ht([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(let k of d){const R=i.get(k.t,k.n);for(let Z=0;Z<R;Z++)g.push(k.clone({remove:y.RED}))}const _=i.dec([...g,m.tiles[1],m.tiles[2]]),x=i.hands.length==0;i.inc(_),x&&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 Be(e).calc()>0?!1:zt.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 pt)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];let 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(let i of Object.values(p))for(let r=1;r<e.getArrayLen(i);r++)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 F(a))}if(n.length==0)return!1;for(let 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 pt);if(n.length==0)return!1;const i=[];for(let 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(let 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=vn(t,e,b.DAI_KAN);let a=new dt([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:new w(r.t,r.n,[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(let i of Object.values(p)){if(i==p.BACK)continue;const r=i==p.Z?re:ft;for(let o of r)e.get(i,o)>0&&n++}return n>=9}initialHands(){return this.wall.initialHands()}}class Kt extends $e{isBackHand(){for(let 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 Kt(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 ks{constructor(t,e){A(this,"id");A(this,"river",new ms);A(this,"placeManager",new Ee({}));A(this,"scoreManager",new xe({}));A(this,"hands",G(new Kt("")));A(this,"counter",new zi);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 Ee(structuredClone(t.places),{round:structuredClone(t.round),sticks:structuredClone(t.sticks)}),this.scoreManager=new xe(structuredClone(t.scores)),this.doraMarkers=[e],this.counter.dec(e);for(let 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(let 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=F.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(let 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 cr extends ks{constructor(e){super("observer",e);A(this,"applied",{});this.counter.disable=!0,this.hands=G(new Kt("_____________"))}setHands(e){this.hands[e.wind]=new Kt(e.hands[e.wind])}handleEvent(e){switch(super.handleEvent(e),e.type){case"DISTRIBUTE":let n=!0;for(let 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(let 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(let i of Object.values(v))console.debug(`${this.placeManager.playerID(i)}(${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 we extends ks{constructor(e,n){super(e,n);A(this,"river",new ms);A(this,"doras",[]);this.eventHandler.on(i=>this.handleEvent(i))}get myWind(){return this.placeManager.wind(this.id)}setHands(e){for(let n of Object.values(v))this.hands[n]=new Kt(e.hands[n])}handleDiscard(e){const n=Object.values(v).filter(l=>l==this.myWind?!1:this.hand(l).reached),i=new Be(this.hand(this.myWind)).calc();if(n.length>0&&i>=2)return te.selectTile(this.counter,n,e);const r=zt.calcCandidates(this.hand(this.myWind),e),a=ke.calcPlayerCandidates(this.counter,r).sort((l,u)=>u.sum-l.sum),c=a.filter(l=>l.sum==a[0].sum);return ke.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 dh{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(){Pe.load(this.histories[this.index]).start()}auto(){for(;this.index<this.histories.length;this.next())this.start()}}const ph=s=>{const[t,e]=ye(),[n,i]=ye(),[r,o]=ye(),[a,c]=ye(),h=["player-1","player-2","player-3","player-4"],l=s==null?void 0:s.playerInjection,u=(l==null?void 0:l.p1)??we,f=(l==null?void 0:l.p2)??we,m=(l==null?void 0:l.p3)??we,d=(l==null?void 0:l.p4)??we,g=new u(h[0],e),_=new f(h[1],i),x=new m(h[2],o),k=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 Pe(R,{debug:s==null?void 0:s.debug,shuffle:s==null?void 0:s.shuffle}),p1:g,p2:_,p3:x,p4:k}},Ct=(s,t)=>{let n=1;for(let i of t)i.equals(s)&&(n*=2);return n};class ke{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=ke.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=Kt;exports.BLOCK=b;exports.BaseActor=ks;exports.Block=B;exports.BlockAnKan=F;exports.BlockCalculator=Ri;exports.BlockChi=ht;exports.BlockDaiKan=dt;exports.BlockHand=nn;exports.BlockIsolated=Xn;exports.BlockOther=Jn;exports.BlockPair=Y;exports.BlockPon=pt;exports.BlockRun=At;exports.BlockShoKan=ct;exports.BlockThree=at;exports.Controller=Pe;exports.Counter=zi;exports.DoubleCalculator=Bn;exports.Efficiency=zt;exports.FONT_FAMILY=qn;exports.Hand=$e;exports.INPUT_SEPARATOR=vt;exports.ImageHelper=ds;exports.MeasureText=pr;exports.N19=ft;exports.NZ=re;exports.OPERATOR=y;exports.Observer=cr;exports.Parser=Q;exports.PlaceManager=Ee;exports.Player=we;exports.PlayerEfficiency=ke;exports.ROUND=j;exports.ROUND_MAP=Gn;exports.Replayer=dh;exports.RiskRank=te;exports.River=ms;exports.ScoreManager=xe;exports.ShantenCalculator=Be;exports.TABLE_CONTEXT=Ys;exports.TILE_CONTEXT=xt;exports.TYPE=p;exports.Tile=w;exports.WIND=v;exports.WIND_MAP=en;exports.Wall=Bt;exports.callBlockIndex=vn;exports.convertInput=Mi;exports.createControllerMachine=Zn;exports.createEventEmitter=ji;exports.createEventPipe=ye;exports.createHand=Vt;exports.createLocalGame=ph;exports.createTable=Ni;exports.createWindMap=G;exports.deserializeWinResult=ge;exports.drawBlocks=Ha;exports.drawTable=Fa;exports.incrementalIDGenerator=ar;exports.isNum5=z;exports.nextRound=_e;exports.nextWind=Et;exports.optimizeSVG=Ba;exports.parse=Ci;exports.parseTableInput=Di;exports.prevRound=vr;exports.prevWind=Vs;exports.prioritizeDiscardedEvents=$i;exports.prioritizeDrawnEvents=Bi;exports.shuffle=ps;exports.sortCalledTiles=Xs;exports.tileSortFunc=Te;