@konoui/mjimage 0.0.38 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +283 -274
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
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 b=(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:"_"},v={TSUMO:"t",RON:"r",DORA:"d",HORIZONTAL:"-",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"},S={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={[S.E]:"東",[S.S]:"南",[S.W]:"西",[S.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"){b(this,"ctx",null);b(this,"strText");b(this,"numText");b(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]});b(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}});b(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){b(this,"input");b(this,"position");b(this,"nextPosition");b(this,"char");b(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(v.HORIZONTAL)?{width:e,height:n,baseWidth:n,baseHeight:e}:{width:n,height:e,w:n,baseWidth:n,baseHeight:e};return(this.has(v.TSUMO)||this.has(v.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){b(this,"_tiles");b(this,"_type");if(this._tiles=t,this._type=e,this._type==_.CHI){this._tiles=[...this._tiles].sort((n,i)=>n.has(v.HORIZONTAL)?-1:i.has(v.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){b(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]=Is(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]=Is(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(v.DORA)?_.IMAGE_DORA:s[0].has(v.TSUMO)?_.TSUMO:_.HAND;const t=s.every(r=>r.equals(s[0],!0)),e=s.filter(r=>r.has(v.HORIZONTAL)).length,n=s.filter(r=>r.has(v.TSUMO)||r.has(v.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 Is(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(v);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 a=0;a<e.length;a++)s.readChar();return[new g(d.BACK,r,e),!0]}}return[new g(d.BACK,0),!1]}function G(s,t=!1){const e={[S.E]:s,[S.S]:s,[S.W]:s,[S.N]:s};if(t)for(let n of Object.values(S))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",E={window:typeof window>"u"?null:window,document:typeof document>"u"?null:document};function xr(){return E.window}class Qn{}const Rt={},ts="___SYMBOL___ROOT___";function _e(s,t=Vn){return E.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(E.document.querySelector(s));const e=t?E.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 E.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 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 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 Ir(){return this.parent().index(this)}function Er(){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:Ir,next:Er,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,Es=/^#[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"&&(Es.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(Es.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=E.document.body||E.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===E.document||(E.document.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t===E.document}).call(E.document.documentElement,s)}class L{constructor(...t){this.init(...t)}addOffset(){return this.x+=E.window.pageXOffset,this.y+=E.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)}}I([$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),{}),I([$t],s)};function ce(s,t){return new $t(Jn((t||E.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===E.window&&(t=oi),t.events||(t.events={}),t.events}function ns(s){return s.getEventTarget()}function bo(s){let t=s.getEventHolder();t===E.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 E.window.Event||(t=new E.window.CustomEvent(t,{detail:e,cancelable:!0,...n})),i.dispatchEvent(t),t}class Ie 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(Ie,"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 Ie{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 E.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=E.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(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!==E.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)}}I(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 Io(){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 Eo(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:Io,toParent:Eo,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))}}I(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=E.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 Ee 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()+")"}}I(Ee,Co);T({Container:{gradient(...s){return this.defs().gradient(...s)}},Defs:{gradient:R(function(s,t){return this.put(new Ee(s)).update(t)})}});N(Ee,"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 E.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())}}I(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}}I(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)}}I(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)&&In(s)}function In(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))In(i);else throw new Error("parser Error");--e}}return i.inNumber&&Nt(i,!1),i.inSegment&&On(i)&&In(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:En:cs.indexOf(s.constructor)>-1?s.constructor:Array.isArray(s)?Qt:t==="object"?ve:En};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 En{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=[En,Me,ve];function Jo(s=[]){cs.push(...[].concat(s))}function Vo(){I(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)})}});I(De,os);I(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)})}});I(Ce,os);I(Ce,_i);N(Ce,"Polyline");class Re extends et{constructor(t,e=t){super(H("rect",t),e)}}I(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:()=>E.window.performance||E.window.Date,transforms:[],frame(s){const t=M.frames.push({run:s});return M.nextDraw===null&&(M.nextDraw=E.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=E.window.requestAnimationFrame(M._draw)),n},immediate(s){const t=M.immediates.push(s);return M.nextDraw===null&&(M.nextDraw=E.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()?E.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=E.window;return(s.performance||s.Date).now()};class bi extends Ie{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 Ie{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(){}}I([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));I(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)}});I(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 E.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(E.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=E.window.getComputedStyle(this.node).getPropertyValue("font-size"),a=i*new k(o);this.dom.newLined&&(this.attr("x",e.attr("x")),this.text()===`
|
|
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
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+=`
|
|
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()}}
|
|
6
|
-
`:""):(typeof t=="function"?(this.clear().build(!0),t.call(this,this),this.build(!1)):this.plain(t),this)}}I(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))}}I(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 Ia(s,t=this.bbox()){return s==null?t.x:this.move(s,t.y,t)}function Ea(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:Ia,y:Ea},Symbol.toStringTag,{value:"Module"}));class z extends J{constructor(t,e=t){super(H("g",t),e)}}I(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)}}I(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");I([hs,sn,Ne,be,Fe],X("viewbox"));I([Se,Ce,De,he],X("marker"));I(F,X("Text"));I(he,X("Path"));I(ss,X("Defs"));I([F,rn],X("Tspan"));I([Re,nn,Ee,tt],X("radius"));I(Ie,X("EventTarget"));I(xt,X("Dom"));I(dt,X("Element"));I(et,X("Shape"));I([J,mi],X("Container"));I(Ee,X("Gradient"));I(tt,X("Runner"));$t.extend(_r());Jo([k,D,L,A,Qt,kt,Wt,B]);Vo();class te{constructor(t={}){b(this,"tileWidth");b(this,"tileHeight");b(this,"imageHostPath");b(this,"imageHostUrl");b(this,"imageExt");b(this,"scale");b(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(v.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);b(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(v.HORIZONTAL)?this.createRotate90Image.bind(this):this.createImage.bind(this),c=r.has(v.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(v.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(v.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(v.TSUMO)||o.has(v.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}},Ii=(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}=Ei(t),l=Ii(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({[S.E]:Pe,[S.S]:Pe,[S.W]:Pe,[S.N]:Pe}),Ot={round:P.E1,sticks:{reach:0,dead:0},doras:S.S,front:S.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}),Ei=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=[S.E,S.S,S.W,S.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){b(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:v.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(v.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:v.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(v.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){b(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){b(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(v.TSUMO)?v.TSUMO:v.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){b(this,"hand");b(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(v.TSUMO))),l=this.cfg.orig.myWind,u=l==S.E,f=G(0);if(h){const p=this.cfg.sticks.dead*100;if(u){const y=r(c*2);f[S.E]+=y*3+p*3,f[S.S]-=y+p,f[S.W]-=y+p,f[S.N]-=y+p}else for(let y of Object.values(S)){if(y==l)continue;const w=y==S.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(v.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(v.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=It(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(It(c),!0)}),a=t.some(c=>{const h=new g(r[1],i.n);return e(c)&&h.equals(It(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(v.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=It(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(It(c),!0)}),a=t.some(c=>{const h=new g(r[1],i.n);return e(c)&&h.equals(It(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=It(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(v.TSUMO)||i.has(v.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(v.RON))||i instanceof Z)?t.some(i=>i instanceof Z&&i.tiles.every(r=>r.has(v.TSUMO)||r.has(v.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(v.TSUMO)||y.has(v.RON))),a=this.minus()==1,c=o.tiles.some(p=>p.has(v.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(v.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(v.TSUMO)||x.has(v.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},It=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=!1){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);t.inc(a);const h=n&&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){let e=Number.POSITIVE_INFINITY,n=[];const i=new $e(t);for(let r of Object.values(d))if(r!=d.BACK)for(let o=1;o<t.getArrayLen(r);o++){if(t.get(r,o)>=4)continue;const a=new g(r,o),c=t.inc([a]),h=i.calc();t.dec(c),h<e?(e=h,n=[a]):h==e&&n.push(a)}return{shanten:e,candidates:n}}static partialCandidateTiles(t){const e=new He(t,!0);return Array(13-e.hands.length).fill(void 0).map(()=>e.inc([new g(d.BACK,0)])),zt.candidateTiles(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){b(this,"reachValue",1e3);b(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){b(this,"pToW",{});b(this,"wToP",G(""));b(this,"round");b(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){b(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]});b(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(){b(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&>(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 Ic(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 Ec(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",()=>Ec(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}`,()=>Ic(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:
|
|
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=!1){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);t.inc(a);const h=n&&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){let e=Number.POSITIVE_INFINITY,n=[];const i=new $e(t);for(let r of Object.values(d))if(r!=d.BACK)for(let o=1;o<t.getArrayLen(r);o++){if(t.get(r,o)>=4)continue;const a=new g(r,o),c=t.inc([a]),h=i.calc();t.dec(c),h<e?(e=h,n=[a]):h==e&&n.push(a)}return{shanten:e,candidates:n}}static partialCandidateTiles(t){const e=new He(t,!0);return Array(13-e.hands.length).fill(void 0).map(()=>e.inc([new g(d.BACK,0)])),zt.candidateTiles(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&>(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
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
11
|
立直直後のロンは立直棒が点数にならないので\\
|
|
12
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
13
|
CHI/PON の場合は鳴ける組み合わせの一覧`}}},tsumo:{exit:[{type:"notify_tsumo"},{type:"notify_end"}],type:"final"},waiting_user_event_after_discarded:{description:`最大 4人から choice に対するレスポンスを待つ\\
|
|
14
14
|
ユーザからではなく、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(S)){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:v.HORIZONTAL});for(let o of Object.values(S)){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(S))},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:v.HORIZONTAL});for(let r of Object.values(S)){const o=t.controller.doWin(r,e.block.tiles[0].clone({remove:v.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(S))},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(S)){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(S)){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(S)){let h=new g(d.BACK,0,[v.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(S)){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(S)){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:v.HORIZONTAL});t.oneShotMap[i]=!0;for(let o of Object.values(S)){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(S)){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(S))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(S)){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==S.E,o=t.controller.finalResult(e.ret,e.iam);for(let a of Object.values(S)){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(S)){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(S)){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(S))r.includes(h)?a[h]+=o?0:3e3/r.length:a[h]-=o?0:3e3/(4-r.length);const c=r.length==4||a[S.E]>0;for(let h of Object.values(S)){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){b(this,"walls",{replacement:[],dead:[],doraMarkers:[],blindDoraMarkers:[],drawable:[]});b(this,"backup");b(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){b(this,"wall",new Ht);b(this,"playerIDs");b(this,"actor",se(Fn(this),{}));b(this,"observer");b(this,"handlers",{});b(this,"mailBox",{});b(this,"histories",[]);b(this,"debugMode");b(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]]:S.E,[r[1]]:S.S,[r[2]]:S.W,[r[3]]:S.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:v.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:v.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:v.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:v.HORIZONTAL,remove:v.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(v.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,[v.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(v.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:v.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:v.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(v.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(S))for(let i=0;i<4;i++)t[n]+=this.wall.draw().toString();for(let e of Object.values(S))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){b(this,"id");b(this,"river",new ps);b(this,"placeManager",new ke({}));b(this,"scoreManager",new xe({}));b(this,"hands",G(new jt("")));b(this,"counter",new zi);b(this,"doraMarkers",[]);b(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(S))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(S))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(v.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(v.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(v.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);b(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(S))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(S))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(S))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);b(this,"river",new ps);b(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(S))this.hands[n]=new jt(e.hands[n])}handleDiscard(e){const n=Object.values(S).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){b(this,"index",0);b(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})},Et=(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*Et(i,n);{const o=t.get(i);r+=o*Et(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*Et(i,n),r+=u*Et(new g(i.t,i.n-2),n),r+=f*Et(new g(i.t,i.n+2),n),r+=p*Et(new g(i.t,i.n-1),n),r+=y*Et(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=v;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=S;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=Ii;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=Ei;exports.parseTableInput=Ni;exports.prevRound=wr;exports.prevWind=Xs;exports.prioritizeDiscardedEvents=Ri;exports.prioritizeDrawnEvents=Hi;exports.shuffle=ds;exports.tileSortFunc=ye;
|
|
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;
|