p&&(p=t.high,h=Math.min(h+l,c)):t.high>d?(u=!0,d=p,h=a,p=t.high):t.low1?`_${t+1}`:""),f="SAR"+a+","+l+","+c+(o>1?` #${t+1}`:"");r.push({key:g,title:f,type:"line",data:m})}return r}},zn={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=In(t,"factor",this.paramMap.factor.defaultValue),s=In(t,"atrPeriod",this.paramMap.atrPeriod.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(id||e[i-1].closep?m:p),u=isNaN(h)?1:h===p?t.close>m?-1:1:t.close1?`_${t+1}`:"";o.push({key:"superTrend"+m,title:"SuperTrend"+r+(n>1?` #${t+1}`:""),type:"line",data:l}),o.push({key:"direction"+m,title:"Direction"+(n>1?` #${t+1}`:""),type:"line",data:c})}return o}},Hn={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=In(t,"window",this.paramMap.window.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="SWMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Wn={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=In(t,"n",this.paramMap.n.defaultValue),s=In(t,"m",this.paramMap.m.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{p+=e.close,t===r-1?l=p/r:t>r-1&&(l=(2*e.close+(r-1)*l)/(r+1)),t>=r-1&&(t===2*r-2?c=l:t>2*r-2&&(c=(2*l+(r-1)*c)/(r+1)));let i=NaN;if(t>=2*r-2)if(t===3*r-3)h=c;else if(t>3*r-3){const e=h;h=(2*c+(r-1)*e)/(r+1),i=(h-e)/e*100}if(d.push({time:e.time,value:i}),g.push(i),m+=isNaN(i)?0:i,g.length>a){const e=g[g.length-1-a];m-=isNaN(e)?0:e}const s=g.length>=a&&!isNaN(i)?m/a:NaN;u.push({time:e.time,value:s})}));const f=n>1?`_${t+1}`:"";o.push({key:"trix"+f,title:"TRIX"+r+(n>1?` #${t+1}`:""),type:"line",data:d}),o.push({key:"maTrix"+f,title:n>1?`MATRIX #${t+1}`:"MATRIX",type:"line",data:u})}return o}},qn={name:"Volume Weighted Average Price",shortName:"VWAP",shouldOhlc:!0,paramMap:{anchorInterval:{defaultValue:[1],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwap",title:"VWAP",type:"line",data:[]}];const s=In(t,"anchorInterval",this.paramMap.anchorInterval.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((e,s)=>{s%t==0&&(r=0,a=0);const n=i[s]?.value??0,o=(e.high+e.low+e.close)/3;a+=o*n,r+=n;const c=0!==r?a/r:NaN;l.push({time:e.time,value:c})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwap"+c,title:"VWAP"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Xn={name:"Volume Weighted Moving Average",shortName:"VWMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwma",title:"VWMA",type:"line",data:[]}];const s=In(t,"length",this.paramMap.length.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((s,n)=>{const o=i[n]?.value??0;if(r+=s.close*o,a+=o,n>=t-1){const o=0!==a?r/a:NaN;l.push({time:s.time,value:o});const c=i[n-(t-1)].value??0;r-=e[n-(t-1)].close*c,a-=c}else l.push({time:s.time,value:NaN})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwma"+c,title:"VWMA"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Jn={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"wma"+r,title:"WMA"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o})})),s}},Yn={name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=In(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[],r=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"hh"+a,title:"HH"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o}),s.push({key:"ll"+a,title:"LL"+t+(i.length>1?` #${n+1}`:""),type:"line",data:r})})),s}},Kn=[Dn,Nn,On,Vn,Yn,Rn,Bn,$n,Gn,Fn,jn,Un,zn,Hn,Wn,qn,Xn,Jn],Qn={name:"Awesome Oscillator",shortName:"AO",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:[5],type:"numberArray",min:1,max:100},longPeriod:{defaultValue:[34],type:"numberArray",min:1,max:200}},calc(e,t){const i=In(t,"shortPeriod",[5]),s=In(t,"longPeriod",[34]),n=Math.max(i.length,s.length),o=[];for(let r=0;r{const s=(t.high+t.low)/2;h+=s,p+=s;let n=NaN,o=NaN;if(i>=a-1){n=h/a;const t=(e[i-(a-1)].high+e[i-(a-1)].low)/2;h-=t}if(i>=l-1){o=p/l;const t=(e[i-(l-1)].high+e[i-(l-1)].low)/2;p-=t}let r=NaN;i>=c-1&&(r=n-o),d.push({time:t.time,value:r})}));const u="ao"+(n>1?`_${r+1}`:""),m="AO"+An(i,r)+(n>1?` #${r+1}`:"");Tn(d,t?.upColor??"green",t?.downColor??"red"),o.push({key:u,title:m,type:"histogram",data:d,pane:1})}return o}},Zn={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;const a=[];e.forEach(((i,s)=>{if(0===s)return void o.push({time:i.time,value:NaN});const n=e[s-1].close,l=Math.max(i.high-i.low,Math.abs(i.high-n),Math.abs(i.low-n));a.push(l),r+=l,a.length>t&&(r-=a.shift());const c=a.length>=t?r/t:NaN;o.push({time:i.time,value:c})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"atr"+l,title:"ATR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},eo={name:"Bias",shortName:"BIAS",shouldOhlc:!0,paramMap:{period1:{defaultValue:[6],type:"numberArray",min:1,max:999},period2:{defaultValue:[12],type:"numberArray",min:1,max:999},period3:{defaultValue:[24],type:"numberArray",min:1,max:999}},calc(e,t){const i=In(t,"period1",[6]),s=In(t,"period2",[12]),n=In(t,"period3",[24]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t0)),c=a.map(((e,i)=>({key:`bias${i+1}`+(o>1?`_${t+1}`:""),title:`BIAS${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const s=t.close;a.forEach(((n,o)=>{if(l[o]+=s,i>=n-1){const r=l[o]/n,a=(s-r)/r*100;c[o].data.push({time:t.time,value:a}),l[o]-=e[i-(n-1)].close}else c[o].data.push({time:t.time,value:NaN})}))})),r.push(...c)}return r}},to={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0,a=0,l=0;const c=[],h=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i;if(a+=i.high-i.open,l+=i.open-i.low,o+=i.high-n.close,r+=n.close-i.low,s>=t-1){const n=0!==r?o/r*100:0,p=0!==l?a/l*100:0;c.push({time:i.time,value:n}),h.push({time:i.time,value:p});const d=e[s-(t-1)],u=s-t>=0?e[s-t]:d;o-=d.high-u.close,r-=u.close-d.low,a-=d.high-d.open,l-=d.open-d.low}else c.push({time:i.time,value:NaN}),h.push({time:i.time,value:NaN})}));const p=i.length>1?`_${n+1}`:"";s.push({key:"br"+p,title:"BR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1}),s.push({key:"ar"+p,title:"AR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:h,pane:1})})),s}},io={name:"Bull and Bear Index",shortName:"BBI",shouldOhlc:!0,paramMap:{p1:{defaultValue:[3],type:"numberArray",min:1},p2:{defaultValue:[6],type:"numberArray",min:1},p3:{defaultValue:[12],type:"numberArray",min:1},p4:{defaultValue:[24],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[3]),s=In(t,"p2",[6]),n=In(t,"p3",[12]),o=In(t,"p4",[24]),r=Math.max(i.length,s.length,n.length,o.length),a=[];for(let t=0;t{const s=t.close;if(d.forEach(((t,n)=>{u[n]+=s,i>=t-1&&(m[n]=u[n]/t,u[n]-=e[i-(t-1)].close)})),i>=Math.max(...d)-1){const e=(m[0]+m[1]+m[2]+m[3])/4;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}));const f=r>1?`_${t+1}`:"";a.push({key:"bbi"+f,title:"BBI"+[l,c,h,p].join(",")+(r>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return a}},so={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[20]),s=[];return i.forEach(((t,n)=>{let o=0;const r=[],a=[];e.forEach(((i,s)=>{const n=(i.high+i.low+i.close)/3;if(o+=n,r.push(n),s>=t-1){const l=o/t;let c=0;for(let e=s-(t-1);e<=s;e++)c+=Math.abs(r[e]-l);const h=c/t,p=0!==h?(n-l)/(.015*h):0;a.push({time:i.time,value:p});const d=(e[s-(t-1)].high+e[s-(t-1)].low+e[s-(t-1)].close)/3;o-=d}else a.push({time:i.time,value:NaN})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"cci"+l,title:"CCI"+t+(i.length>1?` #${n+1}`:""),type:"line",data:a,pane:1})})),s}},no={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=In(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[],l=[],c=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i,h=(n.high+n.low)/2,p=Math.max(0,i.high-h),d=Math.max(0,h-i.low);o+=p,r+=d,a.push(p),l.push(d);let u=NaN;s>=t-1&&(u=0!==r?o/r*100:0,o-=a[s-(t-1)],r-=l[s-(t-1)]),c.push({time:i.time,value:u})}));const h=i.length>1?`_${n+1}`:"";s.push({key:"cr"+h,title:"CR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1})})),s}},oo={name:"Difference of Moving Average",shortName:"DMA",shouldOhlc:!0,paramMap:{n1:{defaultValue:[10],type:"numberArray",min:1},n2:{defaultValue:[50],type:"numberArray",min:1},m:{defaultValue:[10],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n1",[10]),s=In(t,"n2",[50]),n=In(t,"m",[10]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{p+=t.close,d+=t.close;let s=NaN,n=NaN;if(i>=a-1&&(s=p/a,p-=e[i-(a-1)].close),i>=l-1&&(n=d/l,d-=e[i-(l-1)].close),i>=h-1){const e=s-n;if(f.push(e),m.push({time:t.time,value:e}),u+=e,f.length>c){u-=f[f.length-1-c];const e=u/c;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}else m.push({time:t.time,value:NaN}),g.push({time:t.time,value:NaN})}));const y=o>1?`_${t+1}`:"";r.push({key:"dma"+y,title:"DMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1}),r.push({key:"ama"+y,title:"AMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return r}},ro={name:"Directional Movement Index",shortName:"DMI",shouldOhlc:!0,paramMap:{n:{defaultValue:[14],type:"numberArray",min:1},mm:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[14]),s=In(t,"mm",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.high-s.high,o=s.low-t.low,y=Math.max(t.high-t.low,Math.abs(t.high-s.close),Math.abs(s.close-t.low));let b=0,v=0;n>0&&n>o&&(b=n),o>0&&o>n&&(v=o),0===i?(l=y,c=b,h=v):(l=(l*(r-1)+y)/r,c=(c*(r-1)+b)/r,h=(h*(r-1)+v)/r);let x=NaN,_=NaN;0!==l&&(x=c/l*100,_=h/l*100),u.push({time:t.time,value:x}),m.push({time:t.time,value:_});let w=NaN;if(isNaN(x)||isNaN(_)||x+_===0||(w=Math.abs(_-x)/(_+x)*100),i1?`_${t+1}`:"";o.push({key:"pdi"+y,title:"PDI"+r+(n>1?` #${t+1}`:""),type:"line",data:u,pane:1}),o.push({key:"mdi"+y,title:"MDI"+r+(n>1?` #${t+1}`:""),type:"line",data:m,pane:1}),o.push({key:"adx"+y,title:"ADX"+r+(n>1?` #${t+1}`:""),type:"line",data:g,pane:1}),o.push({key:"adxr"+y,title:"ADXR"+r+(n>1?` #${t+1}`:""),type:"line",data:f,pane:1})}return o}},ao={name:"Momentum",shortName:"MTM",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r],n=t.close-s.close;l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"mtm"+d,title:"MTM"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maMtm"+d,title:"MAMTM"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},lo={name:"Psychological Line",shortName:"PSY",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.close>s.close?1:0;if(c.push(n),l+=n,i>=r-1){const e=l/r*100;p.push({time:t.time,value:e}),u.push(e),h+=e,u.length>a&&(h-=u[u.length-1-a]);const s=u.length>=a?h/a:NaN;d.push({time:t.time,value:s}),l-=c[i-(r-1)]}else p.push({time:t.time,value:NaN}),d.push({time:t.time,value:NaN})}));const m=n>1?`_${t+1}`:"";o.push({key:"psy"+m,title:"PSY"+r+(n>1?` #${t+1}`:""),type:"line",data:p,pane:1}),o.push({key:"maPsy"+m,title:"MAPSY"+r+(n>1?` #${t+1}`:""),type:"line",data:d,pane:1})}return o}},co={name:"Rate of Change",shortName:"ROC",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[12]),s=In(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r].close;let n=0;0!==s&&(n=(t.close-s)/s*100),l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"roc"+d,title:"ROC"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maRoc"+d,title:"MAROC"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},ho={name:"RSI + SMA",shortName:"RSI_SMA",shouldOhlc:!0,paramMap:{p1:{defaultValue:[14],type:"numberArray",min:1},p2:{defaultValue:[21],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[14]),s=In(t,"p2",[10]),n=Math.max(i.length,s.length),o=e.map((e=>e.close)),r=[];for(let t=0;t{const i=Pn(o.slice(0,t+1),a);c.push(i);const s=En(c,l);h.push({time:e.time,value:i}),p.push({time:e.time,value:s})}));const d=n>1?`_${t+1}`:"",u={key:`rsi${d}`,title:`RSI(${a})${d}`,type:"line",data:h,pane:1},m={key:`smaOfRsi${d}`,title:`SMA(${l}) of RSI(${a})${d}`,type:"line",data:p,pane:1};r.push(u,m)}return r}},po={name:"Stochastic",shortName:"KDJ",shouldOhlc:!0,paramMap:{n:{defaultValue:[9],type:"numberArray",min:1},kPeriod:{defaultValue:[3],type:"numberArray",min:1},dPeriod:{defaultValue:[3],type:"numberArray",min:1}},calc(e,t){const i=In(t,"n",[9]),s=In(t,"kPeriod",[3]),n=In(t,"dPeriod",[3]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{if(ie.high))),o=Math.min(...s.map((e=>e.low))),r=n===o?100:(t.close-o)/(n-o)*100,g=((l-1)*h+r)/l,f=((c-1)*p+g)/c,y=3*g-2*f;d.push({time:t.time,value:g}),u.push({time:t.time,value:f}),m.push({time:t.time,value:y}),h=g,p=f}));const g=o>1?`_${t+1}`:"";r.push({key:"k"+g,title:"K"+a+(o>1?` #${t+1}`:""),type:"line",data:d,pane:1}),r.push({key:"d"+g,title:"D"+a+(o>1?` #${t+1}`:""),type:"line",data:u,pane:1}),r.push({key:"j"+g,title:"J"+a+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1})}return r}},uo={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length;o.push({time:i.time,value:a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"variance"+r,title:"Variance"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},mo={name:"Williams %R",shortName:"WR",shouldOhlc:!0,paramMap:{p1:{defaultValue:[6],type:"numberArray",min:1},p2:{defaultValue:[10],type:"numberArray",min:1},p3:{defaultValue:[14],type:"numberArray",min:1}},calc(e,t){const i=In(t,"p1",[6]),s=In(t,"p2",[10]),n=In(t,"p3",[14]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t({key:`wr${i+1}`+(o>1?`_${t+1}`:""),title:`WR${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{a.forEach(((s,n)=>{if(i>=s-1){let o=-1/0,r=1/0;for(let t=i-(s-1);t<=i;t++)o=Math.max(o,e[t].high),r=Math.min(r,e[t].low);const a=o!==r?(t.close-o)/(o-r)*100:0;l[n].data.push({time:t.time,value:a})}else l[n].data.push({time:t.time,value:NaN})}))})),r.push(...l)}return r}},go={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[1]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"change"+r,title:"Change"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},fo={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.high))),a=Math.min(...n.map((e=>e.low)));o.push({time:i.time,value:r-a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"range"+r,title:"Range"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},yo={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=In(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length,l=Math.sqrt(a);o.push({time:i.time,value:l})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"stdDev"+r,title:"StdDev"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},bo={name:"Moving Average Convergence Divergence",shortName:"MACD",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:12,type:"number",min:1},longPeriod:{defaultValue:26,type:"number",min:1},signalPeriod:{defaultValue:9,type:"number",min:1}},calc(e,t){const i=function(e,t){const i={};for(const[s,n]of Object.entries(e.paramMap)){const e=t?.[s]??n.defaultValue;i[s]=e}return i}(this,t),s=i.shortPeriod,n=i.longPeriod,o=i.signalPeriod;let r=0,a=0,l=0,c=0,h=0;const p=[],d=[],u=[];let m=0;e.forEach(((e,t)=>{m+=e.close,t===s-1?r=m/s:t>s-1&&(r=(2*e.close+(s-1)*r)/(s+1)),t===n-1?a=m/n:t>n-1&&(a=(2*e.close+(n-1)*a)/(n+1)),t>=Math.max(s,n)-1?(l=r-a,p.push({time:e.time,value:l}),h+=l,p.length===o?c=h/o:p.length>o&&(c=(2*l+(o-1)*c)/(o+1)),p.length>=o?(d.push({time:e.time,value:c}),u.push({time:e.time,value:2*(l-c)})):(d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))):(p.push({time:e.time,value:NaN}),d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))}));return Tn(u,t?.upColor??"green",t?.downColor??"red"),[{key:"dif",title:"DIF",type:"line",data:p,pane:1},{key:"dea",title:"DEA",type:"line",data:d,pane:1},{key:"macd",title:"MACD",type:"histogram",data:u,pane:1}]}},vo=[...Kn,...[Qn,Zn,eo,to,io,so,no,oo,ro,ao,bo,lo,co,ho,po,uo,mo,go,fo,yo]];class xo{contextMenu;handler;container;currentTab="options";constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler,this.container=this.contextMenu.div}openMenu(e,t,i){const s={type:i||e._type||e.constructor.name,object:e.toJSON(),title:e.title},n=JSON.stringify(s,null,2);let o={};e instanceof Lo?o=e.chart.options():void 0!==e.options?o="function"==typeof e.options?e.options():e.options:void 0!==e._options&&(o=e._options);const r={...o},a=JSON.stringify(r,null,2),l=document.createElement("div");l.style.position="fixed",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.backgroundColor="rgba(0, 0, 0, 0.5)",l.style.display="flex",l.style.justifyContent="center",l.style.alignItems="center",l.style.zIndex="1000";const c=e=>{"Escape"===e.key&&this.close(l,c)};document.addEventListener("keydown",c);const h=document.createElement("div");h.style.backgroundColor="#333",h.style.color="#fff",h.style.padding="20px",h.style.borderRadius="8px",h.style.width="80%",h.style.maxWidth="800px",h.style.maxHeight="90%",h.style.overflowY="auto",h.style.boxShadow="0 2px 10px rgba(0,0,0,0.5)",h.setAttribute("tabindex","-1"),h.focus();const p=document.createElement("div");p.style.display="flex",p.style.borderBottom="1px solid #555",p.style.marginBottom="10px";const d=document.createElement("button");d.textContent="Options",d.style.flex="1",d.style.padding="10px",d.style.cursor="pointer",d.style.border="none",d.style.backgroundColor="options"===this.currentTab?"#555":"#333",d.onclick=()=>{this.currentTab="options",d.style.backgroundColor="#555",u.style.backgroundColor="#333",g.value=a,v.style.display="flex",f.style.display="none"};const u=document.createElement("button");u.textContent="Full",u.style.flex="1",u.style.padding="10px",u.style.cursor="pointer",u.style.border="none",u.style.backgroundColor="full"===this.currentTab?"#555":"#333",u.onclick=()=>{this.currentTab="full",u.style.backgroundColor="#555",d.style.backgroundColor="#333",g.value=n,f.style.display="flex",v.style.display="none"},p.appendChild(d),p.appendChild(u),h.appendChild(p);const m=document.createElement("h2");m.textContent=`Export/Import ${e.title} Data`,h.appendChild(m);const g=document.createElement("textarea");g.value="full"===this.currentTab?n:a,g.style.width="100%",g.style.height="400px",g.style.marginTop="10px",g.style.marginBottom="10px",g.style.resize="vertical",g.style.backgroundColor="#444",g.style.color="#fff",g.setAttribute("aria-label","JSON Data Editor"),h.appendChild(g);const f=document.createElement("div");f.style.display="full"===this.currentTab?"flex":"none",f.style.flexWrap="wrap",f.style.justifyContent="flex-end",f.style.gap="10px";const y=document.createElement("button");y.textContent="Export",y.style.padding="8px 12px",y.style.cursor="pointer",y.style.backgroundColor="#f44336",y.style.color="#fff",y.style.border="none",y.style.borderRadius="4px",y.onclick=()=>{this.downloadJson(n,`${e.title}_full.json`)},f.appendChild(y);const b=document.createElement("button");b.textContent="Import",b.style.padding="8px 12px",b.style.cursor="pointer",b.style.backgroundColor="#4CAF50",b.style.color="#fff",b.style.border="none",b.style.borderRadius="4px",b.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.object)throw new Error("Invalid structure: missing 'object'.");e.fromJSON(t.object),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Whole data imported successfully.","success")}catch(e){this.showNotification("Failed to import whole data: "+e.message,"error")}},f.appendChild(b);const v=document.createElement("div");v.style.display="options"===this.currentTab?"flex":"none",v.style.flexWrap="wrap",v.style.justifyContent="flex-end",v.style.gap="10px";const x=document.createElement("button");x.textContent="Export Options",x.style.padding="8px 12px",x.style.cursor="pointer",x.style.backgroundColor="#f44336",x.style.color="#fff",x.style.border="none",x.style.borderRadius="4px",x.onclick=()=>{this.downloadJson(a,`${e.title}_options.json`)},v.appendChild(x);const _=document.createElement("button");_.textContent="Import Options",_.style.padding="8px 12px",_.style.cursor="pointer",_.style.backgroundColor="#4CAF50",_.style.color="#fff",_.style.border="none",_.style.borderRadius="4px",_.onclick=()=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.style.display="none",t.addEventListener("change",(()=>{if(t.files&&t.files.length>0){const i=t.files[0],s=new FileReader;s.onload=()=>{try{const t=s.result;if("string"!=typeof t)throw new Error("File content is not a string.");g.value=t;const i=JSON.parse(t);if("object"!=typeof i||!i.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(i.options),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Options imported successfully.","success")}catch(e){this.showNotification("Failed to import options: "+e.message,"error")}},s.readAsText(i)}})),t.click()},v.appendChild(_);const w=document.createElement("button");w.textContent="Save",w.style.padding="8px 12px",w.style.cursor="pointer",w.style.backgroundColor="#008CBA",w.style.color="#fff",w.style.border="none",w.style.borderRadius="4px",w.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(t),"function"==typeof e.updateView&&e.updateView();JSON.stringify(t,null,2);this.showNotification("Options applied and exported successfully.","success")}catch(e){this.showNotification("Failed to save options: "+e.message,"error")}};const C=document.createElement("button");C.textContent="Save as Default",C.style.padding="8px 12px",C.style.cursor="pointer",C.style.backgroundColor="#008CBA",C.style.color="#fff",C.style.border="none",C.style.borderRadius="4px",C.onclick=()=>{let t={};e instanceof Lo?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2);let s;if(e._type&&"custom/custom"===e._type.toLowerCase()){if(s=prompt("Enter save key (e.g., area, line, candlestick):",e.title.toLowerCase())||"",!s)return}else s=e._type?e._type.toLowerCase():e.title.toLowerCase();const n=`save_defaults_~_${s};;;${i}`;window.callbackFunction(n)},this.container.appendChild(C);const S=document.createElement("div");S.style.display="flex",S.style.flexDirection="column",S.style.gap="10px",S.appendChild(f),S.appendChild(v),S.appendChild(w),S.appendChild(C),h.appendChild(S),l.appendChild(h),this.container.appendChild(l)}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s)}catch(e){this.showNotification("Failed to download data: "+e,"error")}}addSaveDefaultButton(e){const t=document.createElement("button");t.textContent="Save as Default",t.style.padding="8px 12px",t.style.cursor="pointer",t.style.backgroundColor="#008CBA",t.style.color="#fff",t.style.border="none",t.style.borderRadius="4px",t.onclick=()=>{let t={};e instanceof Lo?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2),s=prompt("Enter save key (area, line, trend-trace, candlestick etc):",e.title.toLowerCase());if(!s)return;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n)},this.container.appendChild(t)}close(e,t){e.parentElement&&e.parentElement.removeChild(e),document.removeEventListener("keydown",t)}showNotification(e,t){const i=document.createElement("div");i.textContent=e,i.style.position="fixed",i.style.bottom="20px",i.style.right="20px",i.style.padding="10px 20px",i.style.borderRadius="4px",i.style.color="#fff",i.style.backgroundColor="success"===t?"#4CAF50":"#f44336",i.style.boxShadow="0 2px 6px rgba(0,0,0,0.2)",i.style.zIndex="1001",i.style.opacity="0",i.style.transition="opacity 0.5s ease-in-out",this.container.appendChild(i),setTimeout((()=>{i.style.opacity="1"}),100),setTimeout((()=>{i.style.opacity="0",setTimeout((()=>{i.parentElement&&i.parentElement.removeChild(i)}),500)}),3e3)}openDefaultOptions(e){const t=this.handler.defaultsManager;if(!t)return void this.showNotification("No defaults manager found.","error");const i=t.get(e);if(!i)return void this.showNotification(`No default config found for key: "${e}"`,"error");JSON.stringify(i,null,2);const s=document.createElement("div");Object.assign(s.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:"1000"});const n=e=>{"Escape"===e.key&&this.close(s,n)};document.addEventListener("keydown",n);const o=document.createElement("div");Object.assign(o.style,{backgroundColor:"#333",color:"#fff",padding:"20px",borderRadius:"8px",width:"80%",maxWidth:"800px",maxHeight:"90%",overflowY:"auto",boxShadow:"0 2px 10px rgba(0,0,0,0.5)"}),o.setAttribute("tabindex","-1"),o.focus();const r=document.createElement("h2");r.textContent=`Edit Default Options - "${e}"`,o.appendChild(r);const a=document.createElement("textarea");a.value=JSON.stringify(i,null,2),Object.assign(a.style,{width:"100%",height:"400px",resize:"vertical",backgroundColor:"#444",color:"#fff",border:"none",margin:"10px 0",padding:"10px"}),o.appendChild(a);const l=document.createElement("div");Object.assign(l.style,{display:"flex",flexWrap:"wrap",gap:"10px",justifyContent:"flex-end"});const c=document.createElement("button");c.textContent="Export",Object.assign(c.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#f44336",color:"#fff",border:"none",borderRadius:"4px"}),c.onclick=()=>{this.downloadJson(a.value,`${e}_defaults.json`)},l.appendChild(c);const h=document.createElement("button");h.textContent="Import",Object.assign(h.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#4CAF50",color:"#fff",border:"none",borderRadius:"4px"}),h.onclick=()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.style.display="none",e.addEventListener("change",(()=>{if(e.files&&e.files.length>0){const t=e.files[0],i=new FileReader;i.onload=()=>{try{if("string"!=typeof i.result)throw new Error("File content is not a string.");a.value=i.result}catch(e){this.showNotification("Failed to read defaults file: "+e.message,"error")}},i.readAsText(t)}})),e.click()},l.appendChild(h);const p=document.createElement("button");p.textContent="Save",Object.assign(p.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"4px"}),p.onclick=()=>{try{const t=JSON.parse(a.value),i=JSON.stringify(t,null,2);let s=e;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n),this.showNotification(`Defaults for "${s}" saved successfully.`,"success")}catch(e){this.showNotification("Failed to save defaults: "+e.message,"error")}},l.appendChild(p);const d=document.createElement("button");d.textContent="Cancel",Object.assign(d.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#444",color:"#fff",border:"none",borderRadius:"4px"}),d.onclick=()=>{this.close(s,n)},l.appendChild(d),o.appendChild(l),s.appendChild(o),this.container.appendChild(s)}}class _o{container;backdrop;isOpen=!1;categories=[];contentArea;activeCategoryId="";handler;colorPicker=null;_originalOpacities={};constructor(e){this.handler=e;const t=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new xn("#ff0000",(()=>null),t&&0!==t.length?t:void 0),this.backdrop=document.createElement("div"),Object.assign(this.backdrop.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",opacity:"0",transition:"opacity 0.3s ease",zIndex:"9998",display:"none"}),this.backdrop.addEventListener("click",(e=>{e.target===this.backdrop&&this.close(!1)})),document.body.appendChild(this.backdrop),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"700px",maxWidth:"90%",height:"500px",maxHeight:"90%",backgroundColor:"#1E1E1E",color:"#FFF",borderRadius:"6px",boxShadow:"0 2px 10px rgba(0,0,0,0.8)",zIndex:"9999",opacity:"0",display:"none",transition:"opacity 0.3s ease, transform 0.3s ease"}),document.body.appendChild(this.container);const i=document.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #3C3C3C",backgroundColor:"#2B2B2B"});const s=document.createElement("div");Object.assign(s.style,{fontSize:"16px",fontWeight:"bold"}),s.innerText="Settings",i.appendChild(s);const n=document.createElement("div");Object.assign(n.style,{fontSize:"20px",cursor:"pointer",userSelect:"none"}),n.innerText="×",n.onclick=()=>this.close(!1),i.appendChild(n),this.container.appendChild(i);const o=document.createElement("div");Object.assign(o.style,{display:"flex",flex:"1 1 auto",height:"calc(100% - 50px)",backgroundColor:"#1E1E1E"}),this.container.appendChild(o);const r=document.createElement("div");Object.assign(r.style,{width:"180px",borderRight:"1px solid #3C3C3C",display:"flex",flexDirection:"column",backgroundColor:"#2B2B2B"}),o.appendChild(r),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",padding:"16px",overflowY:"auto"}),o.appendChild(this.contentArea);const a=document.createElement("div");Object.assign(a.style,{borderTop:"1px solid #3C3C3C",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",backgroundColor:"#2B2B2B"});const l=document.createElement("button");Object.assign(l.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),l.innerText="Template ▾",a.appendChild(l);const c=document.createElement("div");Object.assign(c.style,{display:"flex",gap:"8px"});const h=document.createElement("button");Object.assign(h.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),h.innerText="Cancel",h.onclick=()=>this.close(!1),c.appendChild(h);const p=document.createElement("button");Object.assign(p.style,{backgroundColor:"#008CBA",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),p.innerText="Ok",p.onclick=()=>this.close(!0),c.appendChild(p),a.appendChild(c),this.container.appendChild(a),this.categories=[{id:"series-colors",label:"Series Colors",buildContent:()=>this.buildSeriesColorsTab()},{id:"primitive-colors",label:"Primitives Colors",buildContent:()=>this.buildPrimitivesTab()},{id:"layout-options",label:"Layout Options",buildContent:()=>this.buildLayoutOptionsTab()},{id:"grid-options",label:"Grid Options",buildContent:()=>this.buildGridOptionsTab()},{id:"crosshair-options",label:"Crosshair Options",buildContent:()=>this.buildCrosshairOptionsTab()},{id:"time-scale-options",label:"Time Scale",buildContent:()=>this.buildTimeScaleOptionsTab()},{id:"price-scale-options",label:"Price Scale",buildContent:()=>this.buildPriceScaleOptionsTab()},{id:"defaults-list",label:"Defaults",buildContent:()=>this.buildDefaultsListTab()},{id:"source-code",label:"source-code",buildContent:()=>this.buildSourceCodeTab()}],this.categories.forEach((e=>{const t=document.createElement("div");t.innerText=e.label,Object.assign(t.style,{padding:"12px 16px",cursor:"pointer",borderBottom:"1px solid #3C3C3C",userSelect:"none",transition:"background-color 0.2s"}),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#3A3A3A"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor=""})),t.addEventListener("click",(()=>this.switchCategory(e.id))),r.appendChild(t)})),this.categories.length>0&&(this.buildSeriesColorsTab(),this.switchCategory(this.categories[0].id))}open(){this.isOpen||(this.isOpen=!0,this.backdrop.style.display="block",setTimeout((()=>{this.backdrop.style.opacity="1"}),10),this.container.style.display="block",setTimeout((()=>{this.container.style.opacity="1",this.container.style.transform="translate(-50%, -50%) scale(1)"}),10),this.buildSeriesColorsTab())}close(e){e?console.log("Settings Modal: OK clicked. Save changes here."):console.log("Settings Modal: Cancel clicked."),this.isOpen=!1,this.backdrop.style.opacity="0",this.container.style.opacity="0",this.container.style.transform="translate(-50%, -50%) scale(0.95)",setTimeout((()=>{this.isOpen||(this.backdrop.style.display="none",this.container.style.display="none")}),300)}switchCategory(e){this.activeCategoryId=e,this.contentArea.innerHTML="";const t=this.categories.find((t=>t.id===e));t&&t.buildContent()}buildLayoutOptionsTab(){const e=document.createElement("div");e.innerText="Layout Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("layout.textColor")||"#000000";this.addColorPicker("Text Color",i,(e=>{this.handler.chart.applyOptions({layout:{textColor:e}})}));const s=this.handler.chart.options().layout?.background;if(s&&"solid"===s.type){const e=s.color||"#FFFFFF";this.addColorPicker("Background Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:e}}})}))}else if(s&&s.type===t.ColorType.VerticalGradient){let e=s.topColor||"rgba(255,0,0,0.33)",i=s.bottomColor||"rgba(0,255,0,0.33)";this.addColorPicker("Top Color",e,(e=>{i=s.bottomColor||"rgba(0,255,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})})),this.addColorPicker("Bottom Color",i,(i=>{e=s.topColor||"rgba(255,0,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})}))}else console.warn("Unknown background type.");const n=document.createElement("button");n.innerText="Switch Background Type",n.style.marginTop="12px",n.onclick=()=>this.toggleBackgroundType(),this.contentArea.appendChild(n)}buildGridOptionsTab(){const e=document.createElement("div");e.innerText="Grid Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("grid.vertLines.color")||"#D6DCDE";this.addColorPicker("Vertical Line Color",i,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{color:e}}})}));const s=this.getCurrentOptionValue("grid.horzLines.color")||"#D6DCDE";this.addColorPicker("Horizontal Line Color",s,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{color:e}}})}));const n={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted};this.addDropdown("Vertical Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{vertLines:{style:t}}})})),this.addDropdown("Horizontal Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{horzLines:{style:t}}})}));const o=!1!==this.getCurrentOptionValue("grid.vertLines.visible");this.addCheckbox("Show Vertical Lines",o,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{visible:e}}})}));const r=!1!==this.getCurrentOptionValue("grid.horzLines.visible");this.addCheckbox("Show Horizontal Lines",r,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{visible:e}}})}))}buildCrosshairOptionsTab(){const e=document.createElement("div");e.innerText="Crosshair Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted},s=this.getCurrentOptionValue("crosshair.vertLine.style")||"Solid",n=this.getCurrentOptionValue("crosshair.horzLine.style")||"Solid",o=this.getCurrentOptionValue("crosshair.mode")||"Normal";this.addDropdown("Crosshair Mode",["Normal","Magnet","Hidden"],(e=>{this.handler.chart.applyOptions({crosshair:{mode:e}})}),o);const r=Array.from({length:10},((e,t)=>(t+1).toString())),a=(this.getCurrentOptionValue("crosshair.vertLine.width")||"1").toString();this.addDropdown("Vertical Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{vertLine:{width:t}}})}),a),this.addDropdown("Vertical Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{vertLine:{style:t}}})}),s);const l=this.getCurrentOptionValue("crosshair.vertLine.color")||"#C3BCDB44";this.addColorPicker("Vertical Line Color",l,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{color:e}}})}));const c=this.getCurrentOptionValue("crosshair.vertLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Vertical Label Background",c,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{labelBackgroundColor:e}}})})),(this.getCurrentOptionValue("crosshair.horzLine.width")||"1").toString(),this.addDropdown("Horizontal Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{horzLine:{width:t}}})})),this.addDropdown("Horizontal Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{horzLine:{style:t}}})}),n);const h=this.getCurrentOptionValue("crosshair.horzLine.color")||"#9B7DFF";this.addColorPicker("Horizontal Line Color",h,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{color:e}}})}));const p=this.getCurrentOptionValue("crosshair.horzLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Horizontal Label Background",p,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{labelBackgroundColor:e}}})}))}buildTimeScaleOptionsTab(){const e=document.createElement("div");e.innerText="Time Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const t=this.getCurrentOptionValue("timeScale.rightOffset")||0;this.addNumberField("Right Offset",t,(e=>{this.handler.chart.applyOptions({timeScale:{rightOffset:e}})}));const i=this.getCurrentOptionValue("timeScale.barSpacing")||10;this.addNumberField("Bar Spacing",i,(e=>{this.handler.chart.applyOptions({timeScale:{barSpacing:e}})}));const s=this.getCurrentOptionValue("timeScale.minBarSpacing")||.1;this.addNumberField("Min Bar Spacing",s,(e=>{this.handler.chart.applyOptions({timeScale:{minBarSpacing:e}})}));const n=this.getCurrentOptionValue("timeScale.fixLeftEdge")||!1;this.addCheckbox("Fix Left Edge",n,(e=>{this.handler.chart.applyOptions({timeScale:{fixLeftEdge:e}})}));const o=this.getCurrentOptionValue("timeScale.fixRightEdge")||!1;this.addCheckbox("Fix Right Edge",o,(e=>{this.handler.chart.applyOptions({timeScale:{fixRightEdge:e}})}));const r=this.getCurrentOptionValue("timeScale.lockVisibleTimeRangeOnResize")||!1;this.addCheckbox("Lock Visible Range on Resize",r,(e=>{this.handler.chart.applyOptions({timeScale:{lockVisibleTimeRangeOnResize:e}})}));const a=this.getCurrentOptionValue("timeScale.visible");this.addCheckbox("Time Scale Visible",!1!==a,(e=>{this.handler.chart.applyOptions({timeScale:{visible:e}})}));const l=this.getCurrentOptionValue("timeScale.borderVisible");this.addCheckbox("Border Visible",!1!==l,(e=>{this.handler.chart.applyOptions({timeScale:{borderVisible:e}})}));const c=this.getCurrentOptionValue("timeScale.borderColor")||"#000000";this.addColorPicker("Border Color",c,(e=>{this.handler.chart.applyOptions({timeScale:{borderColor:e}})}))}buildPriceScaleOptionsTab(){const e=document.createElement("div");e.innerText="Price Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.handler.chart.priceScale("right");i.options().mode||t.PriceScaleMode.Normal;const s=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],n=s.map((e=>e.label));this.addDropdown("Price Scale Mode",n,(e=>{const t=s.find((t=>t.label===e));t&&i.applyOptions({mode:t.value})}));const o=void 0===i.options().autoScale||i.options().autoScale;this.addCheckbox("Auto Scale",o,(e=>{i.applyOptions({autoScale:e})}));const r=i.options().invertScale||!1;this.addCheckbox("Invert Scale",r,(e=>{i.applyOptions({invertScale:e})}));const a=void 0===i.options().alignLabels||i.options().alignLabels;this.addCheckbox("Align Labels",a,(e=>{i.applyOptions({alignLabels:e})}));const l=void 0===i.options().borderVisible||i.options().borderVisible;this.addCheckbox("Border Visible",l,(e=>{i.applyOptions({borderVisible:e})}));const c=i.options().ticksVisible||!1;this.addCheckbox("Ticks Visible",c,(e=>{i.applyOptions({ticksVisible:e})}))}buildCloneSeriesTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Clone Series - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Clone Series logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildVisibilityOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Visibility Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Visibility Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildStyleOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Style Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Style Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildWidthOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Width Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Width Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildPrimitivesTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Primitives",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e),this.handler._seriesList.forEach((e=>{if(e.primitives&&Array.isArray(e.primitives)&&e.primitives.length>0){let t="Unnamed Series";const i=e.options();i&&i.title&&(t=i.title);const s=document.createElement("div");Object.assign(s.style,{border:"2px solid #666",marginBottom:"12px",padding:"8px",borderRadius:"4px"});const n=document.createElement("div");n.innerText=`Series: ${t}`,Object.assign(n.style,{fontSize:"18px",fontWeight:"bold",marginBottom:"8px"}),s.appendChild(n),e.primitives.forEach(((e,t)=>{let i;if("function"==typeof e.options?i=e.options():e._options?i=e._options:e.options&&(i=e.options),!i)return;const n=document.createElement("div");Object.assign(n.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const o=document.createElement("div");o.innerText=`Primitive ${t+1}: ${e.name||"Unnamed"}`,Object.assign(o.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),n.appendChild(o),this.buildPrimitiveColorOptions(i,n,(t=>{e.applyOptions(t)})),s.appendChild(n)})),this.contentArea.appendChild(s)}}))}buildIndicatorsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Indicators - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Indicators logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildSourceCodeTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Source Code & Licensing",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="12px",this.contentArea.appendChild(e);const t=document.createElement("div");t.style.marginBottom="12px",t.style.fontSize="16px",t.innerHTML='\n \n This project is a derivative work that incorporates components from the following repositories:\n
\n \n Base Source Repositories:\n
\n \n \n Modified/Forked Repositories (by EsIstJosh):\n
\n \n ',this.contentArea.appendChild(t),this.addButton("⤝ Back",(()=>this.switchCategory(this.categories[0].id)),{backgroundColor:"#444"})}buildSeriesMenuTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Series Settings - ${e.options().title??"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t),this.addTextInput("Title",e.options().title||"",(t=>{e.applyOptions({title:t});const i=e.options().title;i&&this.handler.seriesMap.has(i)&&this.handler.seriesMap.delete(i),this.handler.seriesMap.set(t,e)})),this.addButton("Clone Series ▸",(()=>this.buildCloneSeriesTab(e))),this.addButton("Visibility Options ▸",(()=>this.buildVisibilityOptionsTab(e))),this.addButton("Style Options ▸",(()=>this.buildStyleOptionsTab(e))),this.addButton("Width Options ▸",(()=>this.buildWidthOptionsTab(e))),this.addButton("Color Options ▸",(()=>this.buildSeriesColorsTabSingle(e))),this.addButton("Price Scale Options ▸",(()=>this.buildPriceScaleOptionsTab())),this.addButton("Primitives ▸",(()=>this.buildPrimitivesTab())),this.addButton("Indicators ▸",(()=>this.buildIndicatorsTab(e))),this.addButton("Export/Import Series Data ▸",(()=>this.buildDataExportImportTab(e)))}buildSeriesColorsTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Series Colors (All Series)",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=Array.from(this.handler.seriesMap.entries());if(0===t.length){const e=document.createElement("div");return e.innerText="No series found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}if(t.forEach((([e,t])=>{this.buildSeriesColorSection(e,t)})),this.handler.volumeSeries){const e=document.createElement("div");Object.assign(e.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const t=document.createElement("div");t.innerText="Series: Volume",Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),e.appendChild(t);const i=this.handler.volumeSeries,s=this.handler.series.options().borderUpColor||"#00FF00",n=this.handler.series.options().borderDownColor||"#FF0000";let o=this.handler.volumeUpColor,r=this.handler.volumeDownColor;let a=o??s,l=r??n;const c=(e,t)=>{const s=[...i.data()];if(!s||0===s.length)return void console.warn("No volume data available to update colors.");const n=s.map(((i,n)=>{if(0===n)return{...i,color:e};const o=s[n-1].value,r=i.value>o?e:t;return{...i,color:r}}));i.setData(n),this.handler.volumeUpColor=e,this.handler.volumeDownColor=t};this.addSideBySideColors("Volume Colors",a,l,((e,t)=>{a=e,l=t,c(e,t)}),e),this.contentArea.appendChild(e)}}buildSeriesColorSection(e,t){const i=document.createElement("div");Object.assign(i.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const s=document.createElement("div");s.innerText=`Series: ${e}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),i.appendChild(s);const n=t.seriesType?.();if("Candlestick"===n||"Bar"===n||"Custom"===n&&"upColor"in t.options())"upColor"in t.options()&&this.addSideBySideColors("Body",t.options().upColor,t.options().downColor,((e,i)=>{t.applyOptions({upColor:e,downColor:i})}),i),"borderUpColor"in t.options()&&(this.addSideBySideColors("Borders",t.options().borderUpColor,t.options().borderDownColor,((e,i)=>{t.applyOptions({borderUpColor:e,borderDownColor:i})}),i,t),this.addSideBySideColors("Wick",t.options().wickUpColor,t.options().wickDownColor,((e,i)=>{t.applyOptions({wickUpColor:e,wickDownColor:i})}),i,t));else if("Line"===n||"Custom"===n&&"color"in t.options()){const e=t.options().color||"#ffffff";this.addColorPicker("Line Color",e,(e=>t.applyOptions({color:e})),i)}else if("Area"===n){const e=t.options();this.addColorPicker("Line Color",e.lineColor||"#EEEEEE",(e=>{t.applyOptions({lineColor:e})}),i,t),this.addColorPicker("Top Fill",e.topColor||"#008cff44",(e=>{t.applyOptions({topColor:e})}),i,t),this.addColorPicker("Bottom Fill",e.bottomColor||"#008cff00",(e=>{t.applyOptions({bottomColor:e})}),i,t)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${n}`,e.style.color="#bbb",i.appendChild(e)}this.contentArea.appendChild(i)}buildSeriesColorsTabSingle(e){this.contentArea.innerHTML="";const t=document.createElement("div");Object.assign(t.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText=`Color Options - ${e.options().title||"Untitled"}`,Object.assign(i.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),t.appendChild(i);const s=e.type?.();if("Candlestick"===s||"Bar"===s||"Custom"===s&&"upColor"in e.options())"upColor"in e.options()&&this.addSideBySideColors("Body",e.options().upColor,e.options().downColor,((t,i)=>{e.applyOptions({upColor:t,downColor:i})}),t,e),"borderUpColor"in e.options()&&(this.addSideBySideColors("Borders",e.options().borderUpColor,e.options().borderDownColor,((t,i)=>{e.applyOptions({borderUpColor:t,borderDownColor:i})}),t,e),this.addSideBySideColors("Wick",e.options().wickUpColor,e.options().wickDownColor,((t,i)=>{e.applyOptions({wickUpColor:t,wickDownColor:i})}),t,e));else if("Line"===s||"Custom"===s&&"color"in e.options()){const i=e.options().color||"#FFFFFF";this.addColorPicker("Line Color",i,(t=>{e.applyOptions({color:t})}),t,e)}else if("Area"===s){const i=e.options();this.addColorPicker("Line Color",i.lineColor||"#EEEEEE",(t=>{e.applyOptions({lineColor:t})}),t,e)}else{const e=document.createElement("div");e.innerText=`No color settings for series type: ${s}`,e.style.color="#bbb",t.appendChild(e)}const n=document.createElement("button");n.innerText="⤝ Back",Object.assign(n.style,{backgroundColor:"#444",marginTop:"16px",padding:"8px 12px",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"}),n.onclick=()=>this.buildSeriesMenuTab(e),t.appendChild(n)}buildDataExportImportTab(e){this.subTabSkeleton("Export/Import",e,"(Export/Import logic not yet implemented.)")}subTabSkeleton(e,t,i){this.contentArea.innerHTML="";const s=document.createElement("div");s.innerText=`${e} - ${t.options().title||"Untitled"}`,Object.assign(s.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(s);const n=document.createElement("div");n.innerText=i,Object.assign(n.style,{color:"#ccc",marginBottom:"12px"}),this.contentArea.appendChild(n),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(t)),{backgroundColor:"#444"})}buildDefaultsListTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Default Configurations",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e);const t=this.handler?.defaultsManager;if(!t){const e=document.createElement("div");return e.innerText="No defaults manager found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}const i=t.getAll(),s=Array.from(i.keys());if(0===s.length){const e=document.createElement("div");return e.innerText="No default configurations found.",e.style.color="#ccc",void this.contentArea.appendChild(e)}this.addButton("Current Chart Config ▸",(e=>{this.handler.ContextMenu.dataMenu||(this.handler.ContextMenu.dataMenu=new xo({contextMenu:this.handler.ContextMenu,handler:this.handler})),this.handler.ContextMenu.dataMenu.openMenu(this.handler,e,"Handler")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"}),s.forEach((e=>{this.addButton(`Edit "${e}" Defaults`,(()=>{this.handler.ContextMenu?.dataMenu&&"function"==typeof this.handler.ContextMenu.dataMenu.openDefaultOptions?this.handler.ContextMenu.dataMenu.openDefaultOptions(e):console.warn("No dataMenu or openDefaultOptions method found on handler.")}),{backgroundColor:"#444",borderRadius:"8px",marginBottom:"8px",display:"block"})}))}addColorPicker(e,t,i,s=this.contentArea,n){const o=document.createElement("div");Object.assign(o.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const r=document.createElement("span");r.innerText=e,o.appendChild(r);const a=document.createElement("div");Object.assign(a.style,{width:"26px",height:"26px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:t}),o.appendChild(a);const l=e=>{if(!n)return;const t=this.handler.legend._lines.find((e=>e.series===n));t&&(t.colors[0]=e)};a.addEventListener("click",(e=>{this.colorPicker?(this.colorPicker.update(a.style.backgroundColor,(e=>{a.style.backgroundColor=e,i(e),l(e)})),this.colorPicker.openMenu(e,a.offsetWidth,(e=>{a.style.backgroundColor=e,i(e),l(e)}))):console.warn("No colorPicker defined!")})),s.appendChild(o)}addDropdown(e,t,i,s){const n=document.createElement("div");n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="space-between",n.style.marginBottom="8px";const o=document.createElement("span");o.innerText=e,n.appendChild(o);const r=document.createElement("select");r.style.backgroundColor="#444",r.style.color="#fff",r.style.border="1px solid #555",r.style.borderRadius="4px",r.style.outline="none",t.forEach((e=>{const t=document.createElement("option");t.value=e,t.innerText=e,s&&e===s&&(t.selected=!0),r.appendChild(t)})),s&&(r.value=s),r.onchange=()=>i(r.value),n.appendChild(r),this.contentArea.appendChild(n)}addButton(e,t,i){const s=document.createElement("button");s.innerText=e,Object.assign(s.style,{padding:"8px 12px",margin:"4px 0",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"8px",cursor:"pointer",fontFamily:"sans-serif",fontSize:"16px"}),i&&Object.assign(s.style,i),s.onclick=t,this.contentArea.appendChild(s)}addNumberField(e,t,i){const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between",s.style.marginBottom="8px";const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="number",o.value=t.toString(),o.style.width="60px",o.style.backgroundColor="#444",o.style.color="#fff",o.style.border="1px solid #555",o.style.borderRadius="4px",o.oninput=()=>{const e=parseFloat(o.value);i(isNaN(e)?0:e)},s.appendChild(o),this.contentArea.appendChild(s)}addCheckbox(e,t,i){const s=document.createElement("label");s.style.display="flex",s.style.alignItems="center",s.style.marginBottom="8px";const n=document.createElement("input");n.type="checkbox",n.checked=t,n.style.marginRight="8px",n.onchange=()=>i(n.checked),s.appendChild(n);const o=document.createElement("span");o.innerText=e,s.appendChild(o),this.contentArea.appendChild(s)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}toggleBackgroundType(){const e=this.handler.chart.options().layout?.background;if(!e)return this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}}),void this.buildLayoutOptionsTab();if(e.type===t.ColorType.Solid){const i=e.color||"#FFFFFF",s="rgba(0,255,0,0.33)",n={type:t.ColorType.VerticalGradient,topColor:i,bottomColor:s};this.handler.chart.applyOptions({layout:{background:n}})}else if(e.type===t.ColorType.VerticalGradient){const i=e.topColor||"#FFFFFF",s={type:t.ColorType.Solid,color:i};this.handler.chart.applyOptions({layout:{background:s}})}else console.warn("Unknown background type. Falling back to solid #FFFFFF."),this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:"#FFFFFF"}}});this.buildLayoutOptionsTab()}addTextInput(e,t,i){const s=document.createElement("div");Object.assign(s.style,{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"8px",fontFamily:"sans-serif",fontSize:"16px"});const n=document.createElement("span");n.innerText=e,s.appendChild(n);const o=document.createElement("input");o.type="text",o.value=t,Object.assign(o.style,{width:"150px",padding:"4px",backgroundColor:"#444",color:"#fff",border:"1px solid #555",borderRadius:"4px"}),o.oninput=()=>i(o.value),s.appendChild(o),this.contentArea.appendChild(s)}addSideBySideColors(e,t,i,s,n=this.contentArea,o){const r=document.createElement("div");Object.assign(r.style,{display:"flex",alignItems:"center",marginBottom:"8px",gap:"12px"});const a=document.createElement("input");a.type="checkbox",a.checked=!(0===p(t)&&0===p(i)),r.appendChild(a);const c=document.createElement("span");c.innerText=e,Object.assign(c.style,{minWidth:"60px"}),r.appendChild(c);const h=document.createElement("div");Object.assign(h.style,{display:"flex",gap:"8px"}),r.appendChild(h);let d=t,u=i;e in this._originalOpacities||(this._originalOpacities[e]={up:p(t)??1,down:p(i)??1});const m=document.createElement("div");Object.assign(m.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:d});const g=document.createElement("div");Object.assign(g.style,{width:"32px",height:"32px",borderRadius:"4px",cursor:"pointer",border:"1px solid #999",backgroundColor:u}),h.appendChild(m),h.appendChild(g);const f=()=>{if(s(d,u),o){const e=this.handler.legend._lines.find((e=>e.series===o));e&&(e.colors[0]=d,e.colors[1]=u)}};a.addEventListener("change",(()=>{a.checked?(d=l(d,this._originalOpacities[e].up??p(t)),u=l(u,this._originalOpacities[e].down??p(i)),m.style.border="1px solid #999",g.style.border="1px solid #999"):(this._originalOpacities[e].up=p(d),this._originalOpacities[e].down=p(u),d=l(d,0),u=l(u,0),m.style.border="0px",g.style.border="0px"),m.style.backgroundColor=d,g.style.backgroundColor=u,a.checked=!(0===p(d)&&0===p(u)),f()})),m.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,m.offsetWidth+g.offsetWidth,(e=>{d=e,m.style.backgroundColor=e,f()}))})),g.addEventListener("click",(e=>{a.checked||(a.checked=!0,a.dispatchEvent(new Event("change"))),this.colorPicker.openMenu(e,g.offsetWidth,(e=>{u=e,g.style.backgroundColor=e,f()}))})),n.appendChild(r)}buildPrimitiveColorOptions(e,t,i){const s={Body:["upColor","downColor"],Borders:["borderUpColor","borderDownColor"],Wick:["wickUpColor","wickDownColor"]},n=new Set;for(const o in s){const[r,a]=s[o];r in e&&a in e&&(n.add(r),n.add(a),this.addSideBySideColors(o,e[r],e[a],((t,s)=>{e[r]=t,e[a]=s,i(e)}),t))}Object.keys(e).forEach((s=>{s.toLowerCase().includes("color")&&!n.has(s)&&this.addColorPicker(s,e[s],(t=>{e[s]=t,i(e)}),t)}))}}let wo=null;class Co{handler;handlerMap;getMouseEventParams;div;hoverItem;items=[];colorPicker;saveDrawings=null;drawingTool=null;recentSeries=null;recentDrawing=null;SettingsModal=null;volumeProfile=null;dataMenu;constructor(e,t,i){this.handler=e,this.handlerMap=t,this.getMouseEventParams=i,this.div=document.createElement("div"),this.div.classList.add("context-menu"),document.body.appendChild(this.div),this.div.style.overflowY="scroll",this.hoverItem=null,document.body.addEventListener("contextmenu",this._onRightClick.bind(this)),document.body.addEventListener("click",this._onClick.bind(this));const s=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new xn("#ff0000",(()=>null),s&&0!==s.length?s:void 0),this.dataMenu=new xo({contextMenu:this,handler:this.handler}),this.SettingsModal=new _o(this.handler),this.setupMenu()}constraints={baseline:{skip:!0},title:{skip:!0},PriceLineSource:{skip:!0},tickInterval:{min:0,max:100},lastPriceAnimation:{skip:!0},lineType:{min:0,max:2},lineStyle:{min:0,max:4},seriesType:{skip:!0},chandelierSize:{min:1},volumeMALength:{skip:!0},volumeMultiplier:{skip:!0},volumeOpacityPeriod:{skip:!0}};setupDrawingTools(e,t){this.saveDrawings=e,this.drawingTool=t}shouldSkipOption(e){return!!(this.constraints[e]||{}).skip}separator(){const e=document.createElement("div");e.style.width="90%",e.style.height="1px",e.style.margin="3px 0px",e.style.backgroundColor=window.pane.borderColor,this.div.appendChild(e),this.items.push(e)}menuItem(e,t,i=null){const s=document.createElement("span");s.classList.add("context-menu-item"),this.div.appendChild(s);const n=document.createElement("span");if(n.innerText=e,n.style.pointerEvents="none",s.appendChild(n),i){let e=document.createElement("span");e.innerText="►",e.style.fontSize="8px",e.style.pointerEvents="none",s.appendChild(e)}if(s.addEventListener("mouseover",(()=>{this.hoverItem&&this.hoverItem.closeAction&&this.hoverItem.closeAction(),this.hoverItem={elem:n,action:t,closeAction:i}})),i){let e;s.addEventListener("mouseover",(()=>e=setTimeout((()=>t(s.getBoundingClientRect())),100))),s.addEventListener("mouseout",(()=>clearTimeout(e)))}else s.addEventListener("click",(e=>{t(e),this.div.style.display="none"}));this.items.push(s)}_onClick(e){const t=e.target;this.colorPicker&&!this.colorPicker.getElement().contains(t)&&this.colorPicker.closeMenu()}_onRightClick(e){e.preventDefault();const t=this.getMouseEventParams(),i=this.getProximitySeries(this.getMouseEventParams()),s=this.getProximityDrawing(),n=this.getProximityTrendTrace();console.log("Mouse Event Params:",t),console.log("Proximity Series:",i),console.log("Proximity Drawing:",s),this.clearMenu(),this.clearAllMenus(),i?(console.log("Right-click detected on a series (proximity)."),this.populateSeriesMenu(i,e),this.recentSeries=i):s?(console.log("Right-click detected on a drawing."),this.populateDrawingMenu(e,s),this.recentDrawing=s):n?(console.log("Right-click detected on a drawing."),this.populateTrendTraceMenu(e,n)):t?.hoveredSeries?(console.log("Right-click detected on a series (hovered)."),this.populateSeriesMenu(t.hoveredSeries,e),this.recentSeries=i):(console.log("Right-click detected on the chart background."),this.populateChartMenu(e)),this.showMenu(e),e.preventDefault(),e.stopPropagation()}getProximityDrawing(){return O.hoveredObject?O.hoveredObject:null}getProximityTrendTrace(){return Zs.hoveredObject?Zs.hoveredObject:null}getProximitySeries(e){if(!e||!e.seriesData)return console.warn("No mouse event parameters or series data available."),null;if(!e.point)return console.warn("No point data in MouseEventParams."),null;const t=e.point.y;let i=null;const s=this.handler.chart.panes()[e.paneIndex??0].getSeries()[0];if(this.handler.series&&this.handler.series.getPane().paneIndex()===e.paneIndex)i=this.handler.series,console.log("Using handler.series for coordinate conversion.");else{if(!s)return console.warn("No handler.series or referenceSeries available."),null;i=s,console.log("Using referenceSeries for coordinate conversion.")}e.paneIndex!==i.getPane().paneIndex()&&(i=this.handler.chart.panes()[e.paneIndex??1].getSeries()[0]);const n=i.coordinateToPrice(t);if(console.log(`Converted chart Y (${t}) to Price: ${n}`),null===n)return console.warn("Cursor price is null. Unable to determine proximity."),null;const o=[];return e.seriesData.forEach(((t,s)=>{let r;if(f(t)?r=t.value:y(t)&&(r=t.close),void 0!==r&&!isNaN(r)){const t=Math.abs(r-n),a=this.handler.chart.panes()[e.paneIndex].getHeight(),l=i.coordinateToPrice(0),c=i.coordinateToPrice(a);if(null===l||null===c)return null;t/(l-c)*100<=3&&e.paneIndex===s.getPane().paneIndex()&&o.push({distance:t,series:s})}})),o.sort(((e,t)=>e.distance-t.distance)),o.length>1&&this.recentSeries===o[0].series?(console.log("Multiple series found."),o[1].series):o.length>0?(console.log("Closest series found."),o[0].series):(console.log("No series found within the proximity threshold."),null)}showMenu(e){const t=e.clientX,i=e.clientY;this.div.style.position="absolute",this.div.style.zIndex="10000",this.div.style.left=`${t}px`,this.div.style.top=`${i}px`,this.div.style.width="250px",this.div.style.maxHeight="400px",this.div.style.overflowY="auto",this.div.style.display="block",this.div.style.overflowX="hidden",console.log("Displaying Menu at:",t,i),wo=this.div,console.log("Displaying Menu",t,i),document.addEventListener("mousedown",this.hideMenuOnOutsideClick.bind(this),{once:!0}),window.menu=!0}hideMenuOnOutsideClick(e){this.div.contains(e.target)||this.hideMenu()}hideMenu(){this.div.style.display="none",wo===this.div&&(wo=null,window.menu=!1)}clearAllMenus(){this.handlerMap.forEach((e=>{e.ContextMenu&&e.ContextMenu.clearMenu()}))}setupMenu(){if(!this.div.querySelector(".chart-options-container")){const e=document.createElement("div");e.classList.add("chart-options-container"),this.div.appendChild(e)}this.div.querySelector(".context-menu-item.close-menu")||this.addMenuItem("Close Menu",(()=>this.hideMenu()))}addNumberInput(e,t,i,s,n,o){return this.addMenuInput(this.div,{type:"number",label:e,value:t,onChange:i,min:s,max:n,step:o})}addCheckbox(e,t,i){return this.addMenuInput(this.div,{type:"boolean",label:e,value:t,onChange:i})}addSelectInput(e,t,i,s){return this.addMenuInput(this.div,{type:"select",label:e,value:t,onChange:s,options:i})}addMenuInput(e,t,i=""){const s=document.createElement("div");if(s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="right",s.style.justifyContent="space-around",t.label){const o=document.createElement("label");o.innerText=t.label,o.htmlFor=`${i}${t.label.toLowerCase()}`,o.style.flex="0.8",o.style.whiteSpace="nowrap",s.appendChild(o)}let n;switch(t.type){case"hybrid":{if(!t.hybridConfig)throw new Error("Hybrid type requires hybridConfig.");const r=document.createElement("div");r.classList.add("context-menu-item"),r.style.position="relative",r.style.display="flex",r.style.flexDirection="row",r.style.justifyContent="flex-end",r.style.alignItems="right";const a={backgroundColor:"#2b2b2b",color:"#fff",border:"1px solid #444",padding:"2px 2px",textAlign:"center",cursor:"pointer",boxSizing:"border-box",display:"flex",alignItems:"right",justifyContent:"right"};function l(e,t){for(const[i,s]of Object.entries(t))e.style[i]=s}const c=document.createElement("div");l(c,a),c.style.borderRadius="4px 0 0 4px",c.innerText=t.sublabel??"▵",c.addEventListener("click",(e=>{e.stopPropagation(),t.hybridConfig.defaultAction()}));const h=document.createElement("div");l(h,a),h.style.borderLeft="none",h.style.borderRadius="0 4px 4px 0",h.innerText="☷";const p=document.createElement("div");if(p.style.position="absolute",p.style.top="100%",p.style.right="0",p.style.backgroundColor="#2b2b2b",p.style.color="#fff",p.style.border="1px solid #444",p.style.borderRadius="4px",p.style.minWidth="100px",p.style.boxShadow="0px 2px 5px rgba(0, 0, 0, 0.5)",p.style.zIndex="10000",p.style.display="none",1===t.hybridConfig.options.length){const d=t.hybridConfig.options[0];h.addEventListener("click",(e=>{e.stopPropagation(),d.action()}))}else t.hybridConfig.options.forEach((e=>{const t=document.createElement("div");t.innerText=e.name,t.style.cursor="pointer",t.style.padding="5px 10px",t.addEventListener("click",(t=>{t.stopPropagation(),p.style.display="none",e.action()})),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#444"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor="#2b2b2b"})),p.appendChild(t)})),h.addEventListener("click",(e=>{e.stopPropagation(),p.style.display="none"===p.style.display?"block":"none"})),r.appendChild(p);r.appendChild(c),r.appendChild(h),n=r;break}case"number":{const u=document.createElement("input");u.type="number",u.value=void 0!==t.value?t.value.toString():"",u.style.backgroundColor="#2b2b2b",u.style.color="#fff",u.style.border="1px solid #444",u.style.borderRadius="4px",u.style.textAlign="center",u.style.marginLeft="auto",u.style.marginRight="8px",u.style.width="40px",void 0!==t.min&&(u.min=t.min.toString()),void 0!==t.max&&(u.max=t.max.toString()),void 0===t.step||isNaN(t.step)?u.step="1":u.step=t.step.toString(),u.addEventListener("input",(e=>{const i=e.target;let s=parseFloat(i.value);isNaN(s)||t.onChange(s)})),n=u;break}case"boolean":{const m=document.createElement("input");m.type="checkbox",m.checked=t.value??!1,m.style.marginLeft="auto",m.style.marginRight="8px",m.addEventListener("change",(e=>{const i=e.target;t.onChange(i.checked)})),n=m;break}case"select":{const g=document.createElement("select");g.id=`${i}${t.label?t.label.toLowerCase():"select"}`,g.style.backgroundColor="#2b2b2b",g.style.color="#fff",g.style.border="1px solid #444",g.style.borderRadius="4px",g.style.marginLeft="auto",g.style.marginRight="8px",g.style.width="80px",t.options?.forEach((e=>{const i=document.createElement("option");i.value=e,i.text=e,i.style.whiteSpace="normal",i.style.textAlign="right",e===t.value&&(i.selected=!0),g.appendChild(i)})),g.addEventListener("change",(e=>{const i=e.target;t.onChange(i.value)})),n=g;break}case"string":{const f=document.createElement("input");f.type="text",f.value=t.value??"",f.style.backgroundColor="#2b2b2b",f.style.color="#fff",f.style.border="1px solid #444",f.style.borderRadius="4px",f.style.marginLeft="auto",f.style.textAlign="center",f.style.marginRight="8px",f.style.width="60px",f.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=f;break}case"color":{const y=document.createElement("input");y.type="color",y.value=t.value??"#000000",y.style.marginLeft="auto",y.style.cursor="pointer",y.style.marginRight="8px",y.style.width="100px",y.addEventListener("input",(e=>{const i=e.target;t.onChange(i.value)})),n=y;break}default:throw new Error("Unsupported input type")}return s.style.padding="2px 10px 2px 10px",s.appendChild(n),e.appendChild(s),s}addMenuItem(e,t,i=!0,s=!1,n=1){const o=document.createElement("span");if(o.classList.add("context-menu-item"),o.innerText=e,s){const e=document.createElement("span");e.classList.add("submenu-arrow"),e.innerText="ː".repeat(n),o.appendChild(e)}o.addEventListener("click",(e=>{e.stopPropagation(),t(),i&&this.hideMenu()}));const r=["➩","➯","➱","➬","➫"];return o.addEventListener("mouseenter",(()=>{if(o.style.backgroundColor="royalblue",o.style.color="white",!o.querySelector(".hover-arrow")){const e=document.createElement("span");e.classList.add("hover-arrow");const t=Math.floor(Math.random()*r.length),i=r[t];e.innerText=i,e.style.marginLeft="auto",e.style.fontSize="8px",e.style.color="white",o.appendChild(e)}})),o.addEventListener("mouseleave",(()=>{o.style.backgroundColor="",o.style.color="";const e=o.querySelector(".hover-arrow");e&&o.removeChild(e)})),this.div.appendChild(o),this.items.push(o),o}clearMenu(){this.div.querySelectorAll(".context-menu-item:not(.close-menu), .context-submenu").forEach((e=>e.remove())),this.items=[],this.div.innerHTML=""}addColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{const t=Gs(i,e);s.applyOptions(t),console.log(`Updated ${i} to ${e}`);if("object"==typeof(n=s)&&null!==n&&"function"==typeof n.applyOptions&&"function"==typeof n.dataByIndex&&["color","lineColor","upColor","downColor"].includes(i)){const t=this.handler.legend._lines.find((e=>e.series===s));t&&("downColor"===i?(t.colors[1]=e,console.log(`Legend down color updated to: ${e}`)):(t.colors[0]=e,console.log(`Legend up/main color updated to: ${e}`)))}var n};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new xn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}currentWidthOptions=[];currentStyleOptions=[];populateSeriesMenu(e,i){const s=Ns(e,this.handler.legend),o=e.options();if(!o)return void console.warn("No options found for the selected series.");this.div.innerHTML="";const r=[],a=[],l=[],c=[],h=[];for(const e of Object.keys(o)){const i=o[e];if(this.shouldSkipOption(e))continue;if(e.toLowerCase().includes("base"))continue;const s=Fs(e).toLowerCase(),d=s.includes("width")||"radius"===s||s.includes("radius");if(s.includes("color"))"string"==typeof i?r.push({label:e,value:i}):console.warn(`Expected string value for color option "${e}".`);else if(d){if("number"==typeof i){let t=1,n=10,o=1;s.includes("radius")&&(t=0,n=1,o=.1),c.push({name:e,label:e,value:i,min:t,max:n,step:o})}}else if(s.includes("visible")||s.includes("visibility"))"boolean"==typeof i?a.push({label:e,value:i}):console.warn(`Expected boolean value for visibility option "${e}".`);else if("lineType"===e){const t=this.getPredefinedOptions(Fs(e));h.push({name:e,label:e,value:i,options:t})}else if("crosshairMarkerRadius"===e)"number"==typeof i?c.push({name:e,label:e,value:i,min:1,max:50}):console.warn(`Expected number value for crosshairMarkerRadius option "${e}".`);else if(s.includes("style")){if("string"==typeof i||Object.values(t.LineStyle).includes(i)||"number"==typeof i){const t=["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"];h.push({name:e,label:e,value:i,options:t})}}else if(s.includes("shape")){if(p=i,Object.values(n).includes(p)){const t=["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"];t&&h.push({name:e,label:e,value:i,options:t})}}else l.push({label:e,value:i})}var p;this.currentWidthOptions=c,this.currentStyleOptions=h,this.addTextInput("Title",e.options().title||"",(t=>{const i={title:t};this.handler.seriesMap.has(e.options().title)&&this.handler.seriesMap.delete(e.options().title),this.handler.seriesMap.set(t,e),console.log(`Updated seriesMap label to: ${t}`);const s=this.handler.legend._lines.find((t=>t.series===e));s&&s.series===e&&(s.name=t,console.log(`Updated legend title to: ${t}`)),e.applyOptions(i),console.log(`Updated title to: ${t}`)}));const d=e.getPane().paneIndex(),u=this.handler.chart.panes(),m=`Pane ${d}`,g=[];for(let t=0;t{e.moveToPane(t),console.log(`Moved series to existing pane ${t}.`)}});if(g.push({name:"New Pane",action:()=>{e.moveToPane(u.length),console.log(`Moved series to a new pane at index ${u.length}.`)}}),this.addMenuInput(this.div,{type:"hybrid",label:"Move to pane",sublabel:0===d?"New Pane":"Top",value:m,onChange:e=>{const t=g.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:()=>{0===d?(e.moveToPane(u.length),console.log(`Default: Moved series from pane ${d} to a new pane at index ${u.length}.`)):(e.moveToPane(0),console.log(`Default: Moved series from pane ${d} back to main pane (0).`))},options:g.map((e=>({name:e.name,action:e.action})))}}),this.addMenuItem("Clone Series ▸",(()=>{this.populateCloneSeriesMenu(e,i)}),!1,!0),a.length>0&&this.addMenuItem("Visibility Options ▸",(()=>{this.populateVisibilityMenu(i,e)}),!1,!0),this.currentStyleOptions.length>0&&this.addMenuItem("Style Options ▸",(()=>{this.populateStyleMenu(i,e)}),!1,!0),this.currentWidthOptions.length>0&&this.addMenuItem("Width Options ▸",(()=>{this.populateWidthMenu(i,e)}),!1,!0),r.length>0&&this.addMenuItem("Color Options ▸",(()=>{this.populateColorOptionsMenu(r,e,i)}),!1,!0),o.enableVolumeOpacity&&this.addNumberInput("Volume Opacity Period",o.volumeOpacityPeriod??21,(t=>{const i={volumeOpacityPeriod:t};e.applyOptions(i),console.log(`Updated Volume Opacity Period to ${t}`)}),1,1e4,1),o.enableVolumeOpacity){const t=["/ max","> previous","> average"],i=t.includes(o.volumeOpacityMode)?o.volumeOpacityMode:"/ max";this.addSelectInput("Volume Opacity Mode",i??"> previous",t,(t=>{const i={volumeOpacityMode:t};e.applyOptions(i),console.log(`Updated Volume Opacity Mode to: ${t}`)}))}if(void 0!==o.dynamicCandles){const t=["false","trend","trigger","volume_trend"],s=o.dynamicCandles;this.addSelectInput("Dynamic Candles",s,t,(t=>{const s={dynamicCandles:t};e.applyOptions(s),console.log(`Updated dynamicCandles to: ${t}`),this.populateSeriesMenu(e,i)}))}if(l.forEach((t=>{const i=Fs(t.label);if(!this.constraints[t.label]?.skip)if("boolean"==typeof t.value)this.addCheckbox(Fs(t.label),Boolean(t.value),(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}));else if("string"==typeof t.value){const s=this.getPredefinedOptions(t.label);s&&s.length>0?this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addSelectInput(i,t.value,s,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0):this.addMenuItem(`${i} ▸`,(()=>{this.div.innerHTML="",this.addTextInput(i,t.value,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}))}),!1,!0)}else{if("number"!=typeof t.value)return;{const s=this.constraints[t.label]?.min,n=this.constraints[t.label]?.max;this.addNumberInput(i,t.value,(i=>{const s=Gs(t.label,i);e.applyOptions(s),console.log(`Updated ${t.label} to ${i}`)}),s,n)}}})),this.addMenuItem("Price Scale Options ▸",(()=>{this.populatePriceScaleMenu(i,e.options().priceScaleId??"right",e)}),!1,!0),this.addMenuItem("Primitives ▸",(()=>{this.populatePrimitivesMenu(s,i)}),!1,!0),this.addMenuItem("Indicators ▸",(()=>{this.populateIndicatorMenu(e,i)}),!1,!0),function(e){return void 0!==e.figures&&void 0!==e.sourceSeries&&void 0!==e.indicator}(e)){const t=e;this.addMenuItem(`Configure ${t.indicator.name}`,(()=>{this.configureIndicatorParams(t,i,t.figureCount)}),!1)}this.addMenuItem("Export/Import Series Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(e,i,"Series")}),!1),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(i)}),!1,!1),this.showMenu(i)}populateDrawingMenu(e,t){this.div.innerHTML="",this.drawingTool||(this.drawingTool=new $(this.handler.chart,this.handler._seriesList[0]));for(const e of Object.keys(t._options)){let t;if(e.toLowerCase().includes("color"))t=new vn(this.saveDrawings,e);else{if("lineStyle"!==e)continue;t=new _n(this.saveDrawings)}const i=e=>t.openMenu(e);this.menuItem(Fs(e),i,(()=>{document.removeEventListener("click",t.closeMenu),t._div.style.display="none"}))}if("PitchFork"===t._type){const i=t._options.variant||"standard",s=["standard","schiff","modifiedSchiff","inside"];this.addSelectInput("Pitchfork Variant",i,s,(e=>{t._options.variant=e,this.saveDrawings&&this.saveDrawings()})),this.addNumberInput("Length",t._options.length,(e=>{t._options.length=e,this.saveDrawings&&this.saveDrawings()}),0,1e3,.1),this.addMenuItem("Fork Line Options ▸",(()=>{this.populateForkLineMainMenu(e,t)}),!1,!0),this.addMenuItem("Export/Import PitchFork Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"PitchFork")}),!1)}if(t.points?.length>=2&&t.points[0]&&t.points[1]){let i;i=(t.points,t),i.linkedObjects?.length&&i.linkedObjects.forEach((t=>{t instanceof Zs?this.addMenuItem(`${t.title} Options`,(()=>{this.populateTrendTraceMenu(e,t)}),!1,!0):t instanceof Cn&&this.addMenuItem("Volume Profile Options",(()=>{this.populateVolumeProfileMenu(e,t)}),!1,!0)})),this.addMenuItem("Trend Trace ▸",(()=>{this._createTrendTrace(e,i)}),!1,!0),this.addMenuItem("Volume Profile ▸",(()=>{this._createVolumeProfile(i)}),!1,!0)}this.separator(),this.menuItem("Delete Drawing",(()=>this.drawingTool.delete(t))),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}populateChartMenu(e){this.div.innerHTML="",console.log("Displaying Menu Options: Chart"),this.addResetViewOption();const t=this.getMouseEventParams(),i=this.handler.chart.panes(),s=t?.paneIndex,n=this.handler.chart.panes()[s??0],o=()=>{s?n.moveTo(0):n.moveTo(i.length-1)},r=[];r.push({name:"Top",action:()=>{n.moveTo(0),console.log("Moved pane to top")}}),i.length>2&&(s??0)>1&&r.push({name:"Up",action:()=>{n.moveTo((s??2)-1),console.log("Moved pane up")}}),i.length>2&&(s??0){n.moveTo((s??0)+1),console.log("Moved pane down")}}),r.push({name:"Bottom",action:()=>{n.moveTo(i.length-1),console.log("Moved pane to bottom")}}),i.length>1&&this.addMenuInput(this.div,{type:"hybrid",label:"Move pane",sublabel:s?"Top":"Bottom",hybridConfig:{defaultAction:o,options:r.map((e=>({name:e.name,action:e.action})))}}),this.addMenuInput(this.div,{type:"hybrid",label:"Display Volume Profile",sublabel:"≖",hybridConfig:{defaultAction:()=>{this.volumeProfile?(this.handler.series.detachPrimitive(this.volumeProfile),this.volumeProfile=null,console.log("[ChartMenu] Detached Volume Profile.")):(this.volumeProfile=new Cn(this.handler,wn),this.handler.series.attachPrimitive(this.volumeProfile,"Visible Range Volume Profile",!1,!0),console.log("[ChartMenu] Attached Volume Profile."))},options:[{name:"Options",action:()=>{this.volumeProfile&&this.populateVolumeProfileMenu(e,this.volumeProfile)}}]}}),this.addMenuItem(" ~ Series List",(()=>{this.populateSeriesListMenu(e,!1,(t=>{this.populateSeriesMenu(t,e)}))}),!1,!0),this.addMenuItem("Settings...",(()=>{this.SettingsModal.open()}),!0),this.showMenu(e)}populateLayoutMenu(e){this.div.innerHTML="";const t="Text Color",i="layout.textColor",s=this.getCurrentOptionValue(i)||"#000000";this.addColorPickerMenuItem(Fs(t),s,i,this.handler.chart);const n=this.handler.chart.options().layout?.background;m(n)?this.addColorPickerMenuItem("Background Color",n.color||"#FFFFFF","layout.background.color",this.handler.chart):g(n)?(this.addColorPickerMenuItem("Top Color",n.topColor||"rgba(255,0,0,0.33)","layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem("Bottom Color",n.bottomColor||"rgba(0,255,0,0.33)","layout.background.bottomColor",this.handler.chart)):console.warn("Unknown background type; no color options displayed."),this.addMenuItem("Switch Background Type",(()=>{this.toggleBackgroundType(e)}),!1,!0),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1,!1),this.showMenu(e)}toggleBackgroundType(e){const i=this.handler.chart.options().layout?.background;let s;s=m(i)?{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,0.2)",bottomColor:"rgba(0,255,0,0.2)"}:{type:t.ColorType.Solid,color:"#000000"},this.handler.chart.applyOptions({layout:{background:s}}),this.populateLayoutMenu(e)}populateWidthMenu(e,t){this.div.innerHTML="",this.currentWidthOptions.forEach((e=>{"number"==typeof e.value&&this.addNumberInput(Fs(e.label),e.value,(i=>{const s=Gs(e.name,i);t.applyOptions(s),console.log(`Updated ${e.label} to ${i}`)}),e.min,e.max)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populatePrimitivesMenu(e,t){this.div.innerHTML="",console.log("Showing Primitive Menu ");const i=e.primitives;this.addMenuItem("Fill Area Between",(()=>{this.startFillAreaBetween(t,e)}),!1,!1),console.log("Primitives:",i);const s=i?.FillArea??i?.pt;i.FillArea&&this.addMenuItem("Customize Fill Area",(()=>{this.customizeFillAreaOptions(t,s)}),!1,!0),this.addMenuItem("Create TrendTrace",(()=>{this._createTrendTrace(t,this.recentDrawing)}),!1,!1),console.log("Primitives:",i),i.TrendTrace&&this.addMenuItem("Customize TrendTrace",(()=>{this.populateTrendTraceMenu(t,i.TrendTrace)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}populateStyleMenu(e,t){this.div.innerHTML="",this.currentStyleOptions.forEach((e=>{const i=this.getPredefinedOptions(e.name);i?this.addSelectInput(Fs(e.name),e.value.toString(),i,(i=>{let s=i;if(e.name.toLowerCase().includes("style")){s={Solid:0,Dotted:1,Dashed:2,"Large Dashed":3,"Sparse Dotted":4}[i]??0}else if(e.name.toLowerCase().includes("linetype")){s={Simple:0,WithSteps:1,Curved:2}[i]??0}const n=Gs(e.name,s);if(t.applyOptions(n),console.log(`Updated ${e.name} to "${i}" =>`,s),e.name.toLowerCase().includes("style")&&"Line"===t.seriesType()){const e=s,i=(()=>{switch(e){case 0:return"―";case 1:return"··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),n=this.handler.legend._lines.find((e=>e.series===t));n&&(n.legendSymbol=[i],console.log(`Updated legend symbol for lineStyle(${e}) to: ${i}`))}})):console.warn(`No predefined options found for "${e.name}".`)})),this.addMenuItem("⤝ Back",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateCloneSeriesMenu(e,t){this.div.innerHTML="";const i=e.data(),s=["Line","Histogram","Area"];if(i&&i.length>0){i.some((e=>y(e)))&&s.push("Bar","Candlestick","Ohlc")}s.forEach((t=>{this.addMenuItem(`Clone as ${t}`,(()=>{const i=function(e,t,i,s){try{const n=e.options(),o=Is(i),r={...o,...s},a=e.options().title??i;let l;switch(console.log(`Cloning ${e.seriesType()} as ${i}...`),i){case"Line":l=t.createLineSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Histogram":l=t.createHistogramSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Area":l=t.createAreaSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Bar":l=t.createBarSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;case"Candlestick":l={name:`${a}<${i}>`,series:t.createCandlestickSeries()};break;case"Ohlc":l=t.createCustomOHLCSeries(`${a}<${i}>`,void 0,e.getPane().paneIndex());break;default:return console.error(`Unsupported series type: ${i}`),null}let c=e.data().map(((t,s)=>As(e,i,s))).filter((e=>null!==e));return l.series.setData(c),h(n,((e,t)=>{if(function(e,t){const i=e.split(".");let s=t;for(const e of i){if(!(e in s))return("color"===e||"LineColor"===e)&&("color"in s||"LineColor"in s);s=s[e]}return!0}(e,o))if("LineColor"===e||"color"===e){const e="LineColor"in o||"LineColor"in r,i="color"in o||"color"in r;e&&i?(Ds(l.series,"LineColor",t),Ds(l.series,"color",t)):e?Ds(l.series,"LineColor",t):i&&Ds(l.series,"color",t)}else Ds(l.series,e,t)})),Object.keys(r).forEach((e=>{e.toString().toLowerCase().includes("color")&&h({[e]:r[e]},((e,t)=>{console.log(`Found color option: ${e} = ${t}`)}))})),e.subscribeDataChanged((()=>{const t=e.data().map(((t,s)=>As(e,i,s))).filter((e=>null!==e));l.series.setData(t),console.log(`Updated synced series of type ${i}`)})),l.series}catch(e){return console.error("Error cloning series:",e),null}}(e,this.handler,t,this.handler.defaultsManager.defaults.get(t.toLowerCase())||{});i?console.log(`Cloned series as ${t}:`,i):console.warn(`Failed to clone as ${t}.`)}),!1)})),this.addMenuItem("⤝ Series Options",(()=>{this.populateSeriesMenu(e,t)}),!1,!1),this.showMenu(t)}addTextInput(e,t,i){const s=document.createElement("div");s.classList.add("context-menu-item"),s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between";const n=document.createElement("label");n.innerText=e,n.htmlFor=`${e.toLowerCase()}-input`,n.style.marginRight="8px",n.style.flex="1",s.appendChild(n);const o=document.createElement("input");return o.type="text",o.value=t,o.id=`${e.toLowerCase()}-input`,o.style.flex="0 0 100px",o.style.marginLeft="auto",o.style.backgroundColor="#2b2b2b",o.style.color="#fff",o.style.border="1px solid #444",o.style.borderRadius="4px",o.style.cursor="pointer",o.addEventListener("input",(e=>{const t=e.target;i(t.value)})),s.appendChild(o),this.div.appendChild(s),s}populateColorOptionsMenu(e,t,i){this.div.innerHTML="",e.forEach((e=>{this.addColorPickerMenuItem(Fs(e.label),e.value,e.label,t)})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,i)}),!1,!1),this.showMenu(i)}populateVisibilityMenu(e,t){this.div.innerHTML="";const i=t.options();["visible","crosshairMarkerVisible","priceLineVisible"].forEach((e=>{const s=i[e];"boolean"==typeof s&&this.addCheckbox(Fs(e),s,(i=>{const s=Gs(e,i);t.applyOptions(s),console.log(`Toggled ${e} to ${i}`)}))})),this.addMenuItem("⤝ Back to Series Options",(()=>{this.populateSeriesMenu(t,e)}),!1,!1),this.showMenu(e)}populateBackgroundTypeMenu(e){this.div.innerHTML="";[{text:"Solid",action:()=>this.setBackgroundType(e,t.ColorType.Solid)},{text:"Vertical Gradient",action:()=>this.setBackgroundType(e,t.ColorType.VerticalGradient)}].forEach((e=>{this.addMenuItem(e.text,e.action,!1,!1,1)})),this.addMenuItem("⤝ Chart Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateGradientBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Fs("Top Color"),t.topColor,"layout.background.topColor",this.handler.chart),this.addColorPickerMenuItem(Fs("Bottom Color"),t.bottomColor,"layout.background.bottomColor",this.handler.chart),this.addMenuItem("⤝ Background Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateGridMenu(e){this.div.innerHTML="";[{name:"Vertical Line Color",type:"color",valuePath:"grid.vertLines.color",defaultValue:"#D6DCDE"},{name:"Horizontal Line Color",type:"color",valuePath:"grid.horzLines.color",defaultValue:"#D6DCDE"},{name:"Vertical Line Style",type:"select",valuePath:"grid.vertLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Horizontal Line Style",type:"select",valuePath:"grid.horzLines.style",options:["Solid","Dashed","Dotted","LargeDashed"],defaultValue:"Solid"},{name:"Show Vertical Lines",type:"boolean",valuePath:"grid.vertLines.visible",defaultValue:!0},{name:"Show Horizontal Lines",type:"boolean",valuePath:"grid.horzLines.visible",defaultValue:!0}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)??e.defaultValue;"color"===e.type?this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart):"select"===e.type?this.addSelectInput(Fs(e.name),t,e.options,(t=>{const i=e.options.indexOf(t),s=Gs(e.valuePath,i);this.handler.chart.applyOptions(s),console.log(`Updated ${e.name} to: ${t}`)})):"boolean"===e.type&&this.addCheckbox(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated ${e.name} to: ${t}`)}))})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateBackgroundMenu(e){this.div.innerHTML="",this.addMenuItem("Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1,!0),this.addMenuItem("Options",(()=>{this.populateBackgroundOptionsMenu(e)}),!1,!0),this.addMenuItem("⤝ Layout Options",(()=>{this.populateLayoutMenu(e)}),!1),this.showMenu(e)}populateBackgroundOptionsMenu(e){this.div.innerHTML="";[{name:"Background Color",valuePath:"layout.background.color"},{name:"Background Top Color",valuePath:"layout.background.topColor"},{name:"Background Bottom Color",valuePath:"layout.background.bottomColor"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#FFFFFF";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Background",(()=>{this.populateBackgroundMenu(e)}),!1),this.showMenu(e)}populateSolidBackgroundMenuInline(e,t){this.div.innerHTML="",this.addColorPickerMenuItem(Fs("Background Color"),t.color,"layout.background.color",this.handler.chart),this.addMenuItem("⤝ Type & Colors",(()=>{this.populateBackgroundTypeMenu(e)}),!1),this.showMenu(e)}populateCrosshairOptionsMenu(e){this.div.innerHTML="";[{name:"Line Color",valuePath:"crosshair.lineColor"},{name:"Vertical Line Color",valuePath:"crosshair.vertLine.color"},{name:"Horizontal Line Color",valuePath:"crosshair.horzLine.color"}].forEach((e=>{const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populateTimeScaleMenu(e){this.div.innerHTML="";[{name:"Right Offset",type:"number",valuePath:"timeScale.rightOffset",min:0,max:100},{name:"Bar Spacing",type:"number",valuePath:"timeScale.barSpacing",min:1,max:100},{name:"Min Bar Spacing",type:"number",valuePath:"timeScale.minBarSpacing",min:.1,max:10,step:.1},{name:"Fix Left Edge",type:"boolean",valuePath:"timeScale.fixLeftEdge"},{name:"Fix Right Edge",type:"boolean",valuePath:"timeScale.fixRightEdge"},{name:"Lock Visible Range on Resize",type:"boolean",valuePath:"timeScale.lockVisibleTimeRangeOnResize"},{name:"Visible",type:"boolean",valuePath:"timeScale.visible"},{name:"Border Visible",type:"boolean",valuePath:"timeScale.borderVisible"},{name:"Border Color",type:"color",valuePath:"timeScale.borderColor"}].forEach((e=>{if("number"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addNumberInput(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}),e.min,e.max)}else if("boolean"===e.type){const t=this.getCurrentOptionValue(e.valuePath);this.addCheckbox(Fs(e.name),t,(t=>{const i=Gs(e.valuePath,t);this.handler.chart.applyOptions(i),console.log(`Updated TimeScale ${e.name} to: ${t}`)}))}else if("color"===e.type){const t=this.getCurrentOptionValue(e.valuePath)||"#000000";this.addColorPickerMenuItem(Fs(e.name),t,e.valuePath,this.handler.chart)}})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}populatePriceScaleMenu(e,i="right",s){if(this.div.innerHTML="",s)this.addMenuInput(this.div,{type:"hybrid",label:"Price Scale",value:s.options().priceScaleId||"",onChange:e=>{s.applyOptions({priceScaleId:e}),console.log(`Updated price scale to: ${e}`)},hybridConfig:{defaultAction:()=>{const e="left"===s.options().priceScaleId?"right":"left";s.applyOptions({priceScaleId:e}),console.log(`Series price scale switched to: ${e}`)},options:[{name:"Left",action:()=>s.applyOptions({priceScaleId:"left"})},{name:"Right",action:()=>s.applyOptions({priceScaleId:"right"})},{name:"Volume",action:()=>s.applyOptions({priceScaleId:"volume_scale"})},{name:"Custom",action:()=>{const e=document.createElement("div"),t=document.createElement("input");t.type="text",t.placeholder="Enter custom scale ID",t.value=s.options().priceScaleId||"",t.addEventListener("change",(()=>{s.applyOptions({priceScaleId:t.value}),console.log(`Custom scale ID set to: ${t.value}`)})),e.appendChild(t),this.div.appendChild(e)}}]}});else{const n=this.handler.chart.priceScale(i).options().mode??t.PriceScaleMode.Normal,o=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],r=o.map((e=>e.label));this.addSelectInput("Price Scale Mode",o.find((e=>e.value===n))?.label||"Normal",r,(t=>{const n=o.find((e=>e.label===t));n&&(this.applyPriceScaleOptions(i,{mode:n.value}),console.log(`Price scale (${i}) mode set to: ${t}`),this.populatePriceScaleMenu(e,i,s))}));const a=this.handler.chart.priceScale(i).options();[{name:"Auto Scale",value:a.autoScale??!0,action:e=>{this.applyPriceScaleOptions(i,{autoScale:e}),console.log(`Price scale (${i}) autoScale set to: ${e}`)}},{name:"Invert Scale",value:a.invertScale??!1,action:e=>{this.applyPriceScaleOptions(i,{invertScale:e}),console.log(`Price scale (${i}) invertScale set to: ${e}`)}},{name:"Align Labels",value:a.alignLabels??!0,action:e=>{this.applyPriceScaleOptions(i,{alignLabels:e}),console.log(`Price scale (${i}) alignLabels set to: ${e}`)}},{name:"Border Visible",value:a.borderVisible??!0,action:e=>{this.applyPriceScaleOptions(i,{borderVisible:e}),console.log(`Price scale (${i}) borderVisible set to: ${e}`)}},{name:"Ticks Visible",value:a.ticksVisible??!1,action:e=>{this.applyPriceScaleOptions(i,{ticksVisible:e}),console.log(`Price scale (${i}) ticksVisible set to: ${e}`)}}].forEach((t=>{this.addMenuItem(`${t.name}: ${t.value?"On":"Off"}`,(()=>{const n=!t.value;t.action(n),this.populatePriceScaleMenu(e,i,s)}),!1,!1)}))}this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}applyPriceScaleOptions(e,t){const i=this.handler.chart.priceScale(e);i?(i.applyOptions(t),console.log(`Applied options to price scale "${e}":`,t)):console.warn(`Price scale with ID "${e}" not found.`)}getCurrentOptionValue(e){const t=e.split(".");let i=this.handler.chart.options();for(const s of t){if(!i||!(s in i))return console.warn(`Option path "${e}" is invalid.`),null;i=i[s]}return i}setBackgroundType(e,i){const s=this.handler.chart.options().layout?.background;let n;if(i===t.ColorType.Solid)n=m(s)?{type:t.ColorType.Solid,color:s.color}:{type:t.ColorType.Solid,color:"#000000"};else{if(i!==t.ColorType.VerticalGradient)return void console.error(`Unsupported ColorType: ${i}`);n=g(s)?{type:t.ColorType.VerticalGradient,topColor:s.topColor,bottomColor:s.bottomColor}:{type:t.ColorType.VerticalGradient,topColor:"rgba(255,0,0,.2)",bottomColor:"rgba(0,255,0,.2)"}}this.handler.chart.applyOptions({layout:{background:n}}),i===t.ColorType.Solid?this.populateSolidBackgroundMenuInline(e,n):i===t.ColorType.VerticalGradient&&this.populateGradientBackgroundMenuInline(e,n)}startFillAreaBetween(e,t){console.log("Fill Area Between started. Origin series set:",t.options().title),this.populateSeriesListMenu(e,!1,(e=>{e&&e!==t?(console.log("Destination series selected:",e.options().title),t.primitives.FillArea=new _(t,e,{...S}),t.attachPrimitive(t.primitives.FillArea,`Fill Area ⥵ ${e.options().title}`,!1,!0),console.log("Fill Area successfully added between selected series."),alert(`Fill Area added between ${t.options().title} and ${e.options().title}`)):alert("Invalid selection. Please choose a different series as the destination.")}))}getPredefinedOptions(e){return{"Series Type":["Line","Histogram","Area","Bar","Candlestick"],"Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Line Type":["Simple","WithSteps","Curved"],seriesType:["Line","Histogram","Area","Bar","Candlestick"],lineStyle:["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],"Price Line Style":["Solid","Dotted","Dashed","Large Dashed","Sparse Dotted"],lineType:["Simple","WithSteps","Curved"],Shape:["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"],"Candle Shape":["Rectangle","Rounded","Ellipse","Arrow","3d","Polygon","Bar","Slanted"]}[Fs(e)]||null}populateSeriesListMenu(e,t,i){this.div.innerHTML="";let s=[...Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})))];if(this.handler.volumeSeries){s=[{label:"Volume",value:this.handler.volumeSeries},...s]}console.log(s),s.forEach((s=>{this.addMenuItem(s.label,(()=>{i(s.value),t?this.hideMenu():(this.div.innerHTML="",this.populateSeriesMenu(s.value,e),this.showMenu(e))}),!1,!0)})),this.addMenuItem("Cancel",(()=>{console.log("Operation canceled."),this.hideMenu()})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}customizeFillAreaOptions(e,t){var i;this.div.innerHTML="",null!==(i=t).options.originColor&&null!==i.options.destinationColor&&(this.addColorPickerMenuItem("Origin > Destination",t.options.originColor,"originColor",t),this.addColorPickerMenuItem("Origin < Destination",t.options.destinationColor,"destinationColor",t)),this.addMenuItem("⤝ Back to Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}addResetViewOption(){const e=this.addMenuInput(this.div,{type:"hybrid",label:"∟ Reset",sublabel:"View",hybridConfig:{defaultAction:()=>{this.handler.chart.timeScale().resetTimeScale(),this.handler.chart.timeScale().fitContent()},options:[{name:"⥗ Time Scale",action:()=>this.handler.chart.timeScale().resetTimeScale()},{name:"⥘ Price Scale",action:()=>this.handler.chart.timeScale().fitContent}]}});this.div.appendChild(e)}_createTrendTrace(e,t){this.populateSeriesListMenu(e,!1,(e=>{let i;if("PitchFork"===t._type&&e&&t.p1&&t.p2){console.log("Series selected:",e.options().title);i=(t._options.length??1)*Math.abs(t.p2.logical-t.p1.logical)}e&&t.p1&&t.p2&&(console.log("Series selected:",e.options().title),e.primitives.TrendTrace=new Zs(this.handler,e,t.p1,t.p2,Ks,i),e.attachPrimitive(e.primitives.TrendTrace,`${t.p1?.logical} ⥵ ${t.p2?.logical}`,!1,!0),console.log("Trend Trace successfully created for selected series."),t.linkedObjects.push(e.primitives.TrendTrace))}))}_createVolumeProfile(e){const t=this.handler.series??this.handler._seriesList[0];if(t&&e.p1&&e.p2){console.log("Series selected:",t.options().title);const i=new Cn(this.handler,wn,e.p1,e.p2);t.attachPrimitive(i,"Volume Profile",!1,!0),console.log("Volume Profile successfully created for selected series."),e.linkedObjects.push(i)}}populateTrendTraceMenu(e,t){this.div.innerHTML="",this.addMenuItem("Color Options ▸",(()=>this.populateTrendColorMenu(e,t)),!1,!0),this.addMenuItem("General Options ▸",(()=>this.populateTrendOptionsMenu(e,t)),!1,!0),this.addMenuItem("Export/Import Data ▸",(()=>{this.dataMenu||(this.dataMenu=new xo({contextMenu:this,handler:this.handler})),this.dataMenu.openMenu(t,e,"Trend Trace")}),!1),this.addMenuItem("⤝ Main Menu",(()=>this.populateChartMenu(e)),!1),this.showMenu(e)}populateTrendColorMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))?s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??"rgba(0,255,0,.25)"},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??"rgba(255,0,0,.25)"},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??"#1c9d1c"},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??"#d5160c"},{name:"Wick Up Color",type:"color",valuePath:"wickUpColor",defaultValue:i.wickUpColor??"#1c9d1c"},{name:"Wick Down Color",type:"color",valuePath:"wickDownColor",defaultValue:i.wickDownColor??"#d5160c"}):s.push({name:"Line Color",type:"color",valuePath:"lineColor",defaultValue:i.lineColor??"#ffffff"}),s.forEach((e=>{this.addColorPickerMenuItem(Fs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateTrendOptionsMenu(e,t){this.div.innerHTML="";const i=t.getOptions(),s=[];t._sequence.data.every((e=>void 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))&&s.push({name:"Bar Spacing",type:"number",valuePath:"barSpacing",defaultValue:i.barSpacing??.8,min:.1,max:10,step:.1},{name:"Radius",type:"number",valuePath:"radius",defaultValue:i.radius??.6,min:0,max:1,step:.1},{name:"Shape",type:"select",valuePath:"shape",defaultValue:i.shape??"Rounded",options:[{label:"Rectangle",value:n.Rectangle},{label:"Rounded",value:n.Rounded},{label:"Ellipse",value:n.Ellipse},{label:"Arrow",value:n.Arrow},{label:"Polygon",value:n.Polygon},{label:"Bar",value:n.Bar},{label:"Slanted",value:n.Slanted}]},{name:"Show Wicks",type:"boolean",valuePath:"wickVisible",defaultValue:i.wickVisible??!0},{name:"Show Borders",type:"boolean",valuePath:"borderVisible",defaultValue:i.borderVisible??!0},{name:"Chandelier Size",type:"number",valuePath:"chandelierSize",defaultValue:i.chandelierSize??1,min:1,max:100,step:1},{name:"Auto Aggregate",type:"boolean",valuePath:"autoscale",defaultValue:i.autoScale??!0}),s.push({name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Line Width",type:"number",valuePath:"lineWidth",defaultValue:i.lineWidth??1,min:.5,max:10,step:.5}),s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Fs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=Gs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}})),this.addMenuItem("⤝ Trend Trace Menu",(()=>this.populateTrendTraceMenu(e,t)),!1),this.showMenu(e)}populateVolumeProfileMenu(e,t){this.div.innerHTML="";const i=t._options,s=[];s.push({name:"Visible",type:"boolean",valuePath:"visible",defaultValue:i.visible??!0},{name:"Sections",type:"number",valuePath:"sections",defaultValue:i.sections??20,min:1,step:1},{name:"Right Side",type:"boolean",valuePath:"rightSide",defaultValue:i.rightSide??!0},{name:"Width",type:"number",valuePath:"width",defaultValue:i.width??30,min:1,step:1},{name:"Line Style",type:"select",valuePath:"lineStyle",defaultValue:i.lineStyle??0,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]},{name:"Draw Grid",type:"boolean",valuePath:"drawGrid",defaultValue:i.drawGrid??!0},{name:"Grid Width",type:"number",valuePath:"gridWidth",defaultValue:i.gridWidth??void 0,min:1,step:1},{name:"Grid Line Style",type:"select",valuePath:"gridLineStyle",defaultValue:i.gridLineStyle??4,options:[{label:"Solid",value:0},{label:"Dotted",value:1},{label:"Dashed",value:2},{label:"Large Dashed",value:3},{label:"Sparse Dotted",value:4}]}),s.push({name:"Up Color",type:"color",valuePath:"upColor",defaultValue:i.upColor??wn.upColor},{name:"Down Color",type:"color",valuePath:"downColor",defaultValue:i.downColor??wn.downColor},{name:"Border Up Color",type:"color",valuePath:"borderUpColor",defaultValue:i.borderUpColor??wn.borderUpColor},{name:"Border Down Color",type:"color",valuePath:"borderDownColor",defaultValue:i.borderDownColor??wn.borderDownColor},{name:"Grid Color",type:"color",valuePath:"gridColor",defaultValue:i.gridColor??wn.gridColor}),s.forEach((e=>{if("number"===e.type)this.addNumberInput(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}),e.min,e.max,e.step);else if("boolean"===e.type)this.addCheckbox(Fs(e.name),e.defaultValue,(i=>{const s=Gs(e.valuePath,i);t.applyOptions(s),console.log(`Updated ${e.name} to: ${i}`)}));else if("select"===e.type){const i=Array.isArray(e.options)&&"object"==typeof e.options[0]?e.options.map((e=>e.label)):e.options;this.addSelectInput(Fs(e.name),e.defaultValue,i,(i=>{const s=e.options.find((e=>e.label===i));if(s){const i=Gs(e.valuePath,s.value);t.applyOptions(i),console.log(`Updated ${e.name} to: ${s.value}`)}}))}else"color"===e.type&&this.addColorPickerMenuItem(Fs(e.name),e.defaultValue,e.valuePath,t)})),this.addMenuItem("⤝ Main Menu",(()=>{this.populateChartMenu(e)}),!1),this.showMenu(e)}indicatorSeriesMap=new Map;populateIndicatorMenu(e,t){this.div.innerHTML="",vo.forEach((i=>{this.addMenuItem(`${i.name} (${i.shortName})`,(()=>{i.paramMap?this.configureIndicatorParams({series:e,indicator:i},t,1,!0):this.applyIndicator(e,i,{},1)}),!1)})),this.addMenuItem("⤝ Back",(()=>{this.hideMenu()}),!1),this.showMenu(t)}configureIndicatorParams(e,t,i,s=!1){let n;this.div.innerHTML="";const o="sourceSeries"in e?e:e.series,r=e.indicator,a="paramMap"in e?e.paramMap:{},l={};let c=!1,h=0;Object.entries(r.paramMap).forEach((([e,t])=>{if("numberArray"===t.type||"selectArray"===t.type||"booleanArray"===t.type||"stringArray"===t.type){c=!0;const e=Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue];h=Math.max(h,e.length)}})),c&&s&&(void 0!==i?(n=i,e.figureCount=i):n="figureCount"in e&&void 0!==e.figureCount?e.figureCount:h||1,this.addNumberInput("Number of Figures",n,(i=>{e.figureCount=i,this.configureIndicatorParams(e,t,i,!0)}),1,10,1)),Object.entries(r.paramMap).forEach((([t,s])=>{const n=t,o=void 0!==a[t]?a[t]:s.defaultValue;if("numberArray"===s.type||"selectArray"===s.type||"booleanArray"===s.type||"stringArray"===s.type){const r=i??e.figureCount,a=s.type.replace("Array","");l[t]=[];for(let e=0;e{l[t]||(l[t]=[]),l[t][e]=i}),s.min,s.max,s.step):"boolean"===a?this.addCheckbox(`${n} ${e+1}`,Boolean(i),(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"select"===a?this.addSelectInput(`${n} ${e+1}`,String(i),s.options||[],(i=>{l[t]||(l[t]=[]),l[t][e]=i})):"string"===a&&this.addMenuInput(this.div,{type:"string",label:`${n} ${e+1}`,value:i,onChange:i=>{l[t]||(l[t]=[]),l[t][e]=i}}),l[t]||(l[t]=[]),l[t][e]=i}}else"number"===s.type?(this.addNumberInput(n,o,(e=>{l[t]=e}),s.min,s.max,s.step),l[t]=o):"boolean"===s.type?(this.addCheckbox(n,Boolean(o),(e=>{l[t]=e})),l[t]=o):"select"===s.type?(this.addSelectInput(n,String(o),s.options||[],(e=>{l[t]=e})),l[t]=o):(this.addMenuInput(this.div,{type:"string",label:n,value:o,onChange:e=>{l[t]=e}}),l[t]=o)})),this.addMenuItem("Apply",(()=>{this.hideMenu(),Object.entries(l).forEach((([e,t])=>{r.paramMap[e]&&(r.paramMap[e].defaultValue=t)})),"recalculate"in e?(e.recalculate(l),e.figures.forEach((e=>{const t=this.handler.legend._lines.find((t=>t.series===e));t&&(this.handler.seriesMap.set(e.options().title,o),t.name=e.options().title)}))):this.applyIndicator(o,r,l,n)}),!1),this.addMenuItem("Cancel",(()=>{this.hideMenu()}),!1),this.showMenu(t)}applyIndicator(e,t,i,s){const n=[...e.data()];if(!n||0===n.length)return void console.warn("No data found on this series.");let o;o=n.every(y)?n:n.map(Vs);const r=this.handler.volumeSeries.data(),a=t.calc([...o],i,r??void 0),l=new Map,c=function(e){const t={"#ff0000":["#ff0000","#f20000","#e60000","#d90000","#cc0000","#bf0000","#b30000","#a60000","#990000","#8c0000"],"#ff8700":["#ff8700","#f28000","#e67a00","#d97300","#cc6c00","#bf6500","#b35f00","#a65800","#995100","#8c4a00"],"#ffd300":["#ffd300","#fcca00","#e6c000","#d9b600","#ccb000","#bfaa00","#b3a000","#a69a00","#999000","#8c8600"],"#a1ff0a":["#a1ff0a","#97f207","#8ded04","#83e701","#79db00","#6fd200","#65c900","#5bc000","#51b700","#47ae00"],"#117a03":["#117a03","#107203","#0e6c03","#0c6603","#0a6003","#085a03","#065403","#044e03","#024803","#004203"],"#580aff":["#580aff","#5109f2","#4a08e6","#4307da","#3c06ce","#3505c2","#2e04b6","#2703aa","#2002a0","#190196"],"#be0aff":["#be0aff","#b308f2","#aa07e6","#a005da","#9704ce","#8e03c2","#8502b6","#7c01aa","#7300a0","#6a0096"]},i=Object.keys(t),s=t[i[Math.floor(Math.random()*i.length)]];if(e===s.length)return s;const n=[];for(let t=0;t{const r=c[o];let h=null;if("histogram"===n.type){const i=this.handler.createHistogramSeries(n.title,{color:r,base:0,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}else{const i=this.handler.createLineSeries(n.title,{color:r,lineWidth:2,title:n.title,...a.length>1?{group:t.name}:{}});i.series&&(i.series.setData(n.data),h=i.series,e.getPane().paneIndex()!==h.getPane().paneIndex()&&h.moveToPane(e.getPane().paneIndex()))}if(h){const o=function(e,t,i,s,n,o,r){const a=Object.assign(e,{sourceSeries:t,indicator:i,figures:s,paramMap:o,figureCount:n,recalculate:function(e){r(this,e)}});return"function"==typeof t.subscribeDataChanged&&t.subscribeDataChanged((()=>{t.data()[t.data().length-1].time>e.data()[e.data().length-1].time&&r(a)})),a}(h,e,t,l,s,i,Os);if(l.set(n.key,o),n.pane&&o.getPane()===e.getPane()){const e=o.getPane().paneIndex();o.moveToPane(e+n.pane)}}})),this.indicatorSeriesMap.set(t.name,l)}populateForkLineMainMenu(e,i){if(this.div.innerHTML="","PitchFork"!==i._type)return;const s=i._options;s.forkLines||(s.forkLines=[]);const n=s.forkLines;n.forEach(((t,s)=>{this.addMenuItem(`Fork Line ${s+1}`,(()=>{this.populateForkLineOptions(e,i,s)}),!1,!0)})),this.addMenuItem("Add Fork Line",(()=>{const s={value:.5,width:1,style:t.LineStyle.Solid,color:"#ffffff",fillColor:void 0};n.push(s),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateDrawingMenu(e,i)}),!1,!1),this.showMenu(e)}populateForkLineOptions(e,i,s){this.div.innerHTML="";const n=i._options;if(!n.forkLines||!n.forkLines[s])return;const o=n.forkLines[s];this.addNumberInput("Value",o.value,(e=>{o.value=e,this.saveDrawings&&this.saveDrawings()}),0,10,.1),this.addNumberInput("Width",o.width,(e=>{o.width=e,this.saveDrawings&&this.saveDrawings()}),1,10,1);const r=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];this.addSelectInput("Style",r.find((e=>e.var===o.style))?.name||r[0].name,r.map((e=>e.name)),(e=>{const t=r.find((t=>t.name===e));t&&(o.style=t.var,this.saveDrawings&&this.saveDrawings())})),this.addForkLineColorPickerMenuItem("Color",o.color,o,"color"),this.addForkLineColorPickerMenuItem("Fill Color",o.fillColor||"",o,"fillColor"),this.addMenuItem("Remove Fork Line",(()=>{n.forkLines.splice(s,1),this.saveDrawings&&this.saveDrawings(),this.populateForkLineMainMenu(e,i)}),!1,!0),this.addMenuItem("⤝ Back",(()=>{this.populateForkLineMainMenu(e,i)}),!1,!1),this.showMenu(e)}addForkLineColorPickerMenuItem(e,t,i,s){const n=document.createElement("span");n.classList.add("context-menu-item"),n.innerText=e,this.div.appendChild(n);const o=e=>{i[s]=e,console.log(`Updated fork line ${s} to ${e}`),this.saveDrawings&&this.saveDrawings()};return n.addEventListener("click",(e=>{e.stopPropagation(),this.colorPicker||(this.colorPicker=new xn(t??"#000000",o)),this.colorPicker.openMenu(e,225,o)})),n}}function So(e){return function(e){return Math.max(1,Math.floor(e))}(e)/e}class ko{_options;constructor(e){this._options=e}staticAggregate(e,t){const i=this._options?.chandelierSize??1,s=[];for(let n=0;n=s[0].open;r.close>=r.open!==e&&(a=!0)}else if("trigger"===n){(this._options?.dynamicTrigger&&this._options?.dynamicTrigger().newBar||r.newBar)&&(a=!0)}else if("volume_trend"===n){const e=s[0].volume,t=s[s.length-1].volume,i=r.volume;if(e&&t&&i){const s=t>=e;(s&&it)&&(a=!0)}}if(a){const e=o-s.length,n=o-1,a=this._chandelier(s,e,n,t,!1);i.push(a),s=[r]}else s.push(r)}if(s.length>0){const n=e.length-s.length,o=e.length-1,r=this._chandelier(s,n,o,t,!1);i.push(r)}return this.applyVolumeOpacity(i),i}applyVolumeOpacity(e){if(!this._options?.enableVolumeOpacity)return;if(!e.every((e=>void 0!==e.volume&&"number"==typeof e.volume)))return void console.warn("Volume opacity enabled but not all aggregated bars have volume data. Skipping volume-based opacity adjustment.");const t=this._options?.upColor||"rgba(0,255,0,0.333)",i=this._options?.downColor||"rgba(255,0,0,0.333)",s=p(t),n=p(i);if(0===s||0===n)return void console.warn("Volume opacity enabled but upColor/downColor alpha is zero. Skipping volume-based opacity adjustment.");const o=(this._options.volumeOpacityPeriod??20)*(this._options?.chandelierSize??1),r=this._options?.maxOpacity??.3;e.forEach(((e,s,n)=>{if(null==e.volume)return;const a=Math.max(0,s-o+1),c=n.slice(a,s+1);let h=1;if("/ max"!==this._options?.volumeOpacityMode&&this._options?.volumeOpacityMode)if("> previous"===this._options?.volumeOpacityMode)if(0!==s&&n[s-1].volume&&0!==n[s-1].volume){const t=n[s-1].volume??0;h=e.volume>t?r:0}else h=r;else if("> average"===this._options?.volumeOpacityMode){const t=c.reduce(((e,t)=>e+(void 0!==t.volume?t.volume:0)),0),i=c.length>0?t/c.length:0;h=i>0&&e.volume>i?r:0}else h=0;else{const t=c.reduce(((e,t)=>void 0!==t.volume&&t.volume>e?t.volume:e),0);h=t>0?e.volume/t*r:1}e.isUp?e.color=l(t,h):e.color=l(i,h)}))}_chandelier(e,t,i,s,o=!1){if(0===e.length)throw new Error("Bucket cannot be empty in _chandelier method.");const r=e[0].originalData?.open??e[0].open??0,a=e[e.length-1].originalData?.close??e[e.length-1].close??0,c=s(r)??0,h=s(a)??0,p=e.map((e=>e.originalData?.high??e.high)),d=e.map((e=>e.originalData?.low??e.low)),m=p.length>0?Math.max(...p):0,g=d.length>0?Math.min(...d):0,f=s(m)??0,y=s(g)??0,b=e[0].x,v=a>r,x=v?this._options?.upColor||"rgba(0,255,0,0.333)":this._options?.downColor||"rgba(255,0,0,0.333)",_=v?this._options?.borderUpColor||l(x,1):this._options?.borderDownColor||l(x,1),w=v?this._options?.wickUpColor||_:this._options?.wickDownColor||_,C=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options?.lineStyle??1),S=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options?.lineWidth??1),k=e.reduce(((e,t)=>(t.shape?u(t.shape):t.originalData?.shape?u(t.originalData.shape):void 0)??e),this._options?.shape??n.Rectangle);return{open:c,high:f,low:y,close:h,volume:e.reduce(((e,t)=>e+(t.originalData?.volume??t.volume??0)),0),x:b,isUp:v,startIndex:t,endIndex:i,isInProgress:o,color:x,borderColor:_,wickColor:w,shape:k||n.Rectangle,lineStyle:C,lineWidth:S}}}class Eo{_data=null;_options=null;_aggregator=null;draw(e,t){e.useBitmapCoordinateSpace((e=>this._drawImpl(e,t)))}update(e,t){this._data=e,this._options=t,this._aggregator=new ko(t)}_drawImpl(e,t){if(!this._data||0===this._data.bars.length||!this._data.visibleRange||!this._options)return;const i=this._data.bars.map(((e,t)=>({open:e.originalData?.open??0,high:e.originalData?.high??0,low:e.originalData?.low??0,close:e.originalData?.close??0,volume:e.originalData?.volume??0,x:e.x,shape:e.originalData?.shape??this._options?.shape??"Rectangle",lineStyle:e.originalData?.lineStyle??this._options?.lineStyle??1,lineWidth:e.originalData?.lineWidth??this._options?.lineWidth??1,isUp:(e.originalData?.close??0)>=(e.originalData?.open??0),color:this._options?.color??"rgba(0,0,0,0)",borderColor:this._options?.borderColor??"rgba(0,0,0,0)",wickColor:this._options?.wickColor??"rgba(0,0,0,0)",startIndex:t,endIndex:t})));let s;s="use Chandelier Size"===this._options.dynamicCandles?this._aggregator?.staticAggregate(i,t)??[]:this._aggregator?.dynamicAggregate(i,t)??[];const n=this._options.radius,{horizontalPixelRatio:o,verticalPixelRatio:r}=e,a=this._data.barSpacing*o;this._drawCandles(e,s,this._data.visibleRange,n,a,o,r),this._drawWicks(e,s,this._data.visibleRange)}_drawWicks(e,t,i){if(null===this._data||null===this._options)return;if("3d"===this._options.shape)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,r=this._data.barSpacing*n,a=So(n),l=this._options?.barSpacing??.8;s.save();for(const e of t){if(e.startIndexi.to)continue;const t=e.low*o,c=e.high*o,h=Math.min(e.open,e.close)*o,p=Math.max(e.open,e.close)*o,d=e.endIndex-e.startIndex,u=1!==this._options?.chandelierSize?r*Math.max(1,d+1)-(1-l)*r:r*l,m=e.x*n-r*l/2+u/2;let g=c,f=h,y=p,b=t;"Polygon"===this._options.shape&&(f=(c+h)/2,y=(t+p)/2),s.fillStyle=e.color,s.strokeStyle=e.wickColor??e.color;const v=(e,t,i,n,o)=>{s.roundRect?s.roundRect(e,t,i,n,o):s.rect(e,t,i,n)},x=f-g;x>0&&(s.beginPath(),v(m-Math.floor(a/2),g,a,x,a/2),s.fill(),s.stroke());const _=b-y;_>0&&(s.beginPath(),v(m-Math.floor(a/2),y,a,_,a/2),s.fill(),s.stroke())}}_drawCandles(e,t,i,s,n,o,r){const{context:a}=e,l=this._options?.barSpacing??.8;a.save();for(const e of t){const t=e.endIndex-e.startIndex,c=1!==this._options?.chandelierSize?n*Math.max(1,t+1)-(1-l)*n:n*l,h=e.x*o,p=n*l;if(e.startIndexi.to)continue;const d=Math.min(e.open,e.close)*r,u=Math.max(e.open,e.close)*r,m=d-u,g=(d+u)/2,f=h-p/2,y=f+c,b=f+c/2;switch(a.fillStyle=e.color??this._options?.color??"rgba(255,255,255,1)",a.strokeStyle=e.borderColor??this._options?.borderColor??e.color??"rgba(255,255,255,1)",U(a,e.lineStyle),a.lineWidth=e.lineWidth??1,e.shape){case"Rectangle":default:Us(a,f,y,g,m);break;case"Rounded":zs(a,f,y,g,m,s);break;case"Ellipse":Hs(a,f,y,0,g,m);break;case"Arrow":Xs(a,f,y,b,g,m,e.high*r,e.low*r,e.isUp);break;case"3d":Ws(a,h,e.high*r,e.low*r,e.open*r,e.close*r,p,c,e.color??this._options?.color??"rgba(255,255,255,1)",e.borderColor??this._options?.borderColor??"rgba(255,255,255,1)",e.isUp,l);break;case"Polygon":qs(a,f,y,g,m,e.high*r,e.low*r,e.isUp);break;case"Bar":Js(a,f,y,e.high*r,e.low*r,e.open*r,e.close*r);break;case"Slanted":Ys(a,f,y,g,m,e.isUp)}}a.restore()}}const Mo={...t.customSeriesDefaultOptions,upColor:"#008000",downColor:"#8C0000",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#008000",borderDownColor:"#8C0000",wickColor:"#737375",wickUpColor:"#008000",wickDownColor:"#8C0000",radius:.6,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineWidth:2,enableVolumeOpacity:!0,volumeOpacityMode:"> previous",volumeOpacityPeriod:21,maxOpacity:.3,dynamicCandles:"use Chandelier Size",dynamicTrigger:()=>({newBar:!0})};class Po{_renderer;constructor(){this._renderer=new Eo}priceValueBuilder(e){return[e.high,e.low,e.close]}renderer(){return this._renderer}isWhitespace(e){return void 0===e.close}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Mo}}class To{defaults;constructor(){this.defaults=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.defaults.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){const t=e.toLowerCase();for(const[e,i]of this.defaults)if(e.toLowerCase()===t)return i;return null}getAll(){return this.defaults}}class Io{scripts;constructor(){this.scripts=new Map}set(e,t){let i;if("string"==typeof t)try{i=JSON.parse(t)}catch(s){console.error(`Error parsing JSON string for key "${e}":`,s),i=t}else i=t;this.scripts.set(e,i),console.log(`Default options for key "${e}" set successfully.`),console.log(i)}get(e){return this.scripts.has(e)?this.scripts.get(e):null}getAll(){return this.scripts}getLast(){if(this.scripts.has("cache"))return this.scripts.get("cache");if(0===this.scripts.size)return null;const e=Array.from(this.scripts.values());return e[e.length-1]}}class Ao{_data=null;_options=null;draw(e,t){e.useBitmapCoordinateSpace((e=>{this._drawImpl(e,t)}))}update(e,t){this._data=e,this._options=t}_drawImpl(e,t){const i=this._data?.barSpacing??.8;if(null===this._data||0===this._data.bars.length||null===this._data.visibleRange||null===this._options)return;const{context:s,horizontalPixelRatio:n,verticalPixelRatio:o}=e,{visibleRange:r}=this._data,{color:a,lineWidth:c,lineStyle:h,join:p,shape:d,shapeSize:u,fontSize:m}=this._options,g=this._data.bars.map((e=>({x:e.x*n,y:t(e.originalData.value)*o})));s.save(),s.lineJoin="round",s.strokeStyle=a,s.lineWidth=c*o,U(s,h),s.beginPath();const f=r.from,y=r.to-1;s.moveTo(g[f].x,g[f].y);for(let e=f+1;e<=y;e++)p&&s.lineTo(g[e].x,g[e].y);s.stroke(),s.restore();const b=(u??.8)*i,v={shape:d,shapeSize:b??1,fillColor:l(a,.5),borderColor:a,lineWidth:c,textAlign:"center",textBaseline:"middle",fontSize:(m??1)*i},x=this._data.bars;for(let e=f;e<=y;e++){const r=x[e],a=r.x*n,l=t(r.originalData.value)*o,c=r.originalData.shapeOptions??{},h=c.shapeSize??null,p=null!==h?h*i:b,d={...v,...c,shapeSize:p};this._drawShape(s,a,l,d)}}_drawShape(e,t,i,s){e.save();const{shape:n,shapeSize:o,fillColor:r,borderColor:a,lineWidth:l=1,textAlign:c="center",textBaseline:h="middle",fontSize:p=1}=s;switch(e.fillStyle=r??this._options?.color,e.strokeStyle=a??r??this._options?.color,e.lineWidth=l,e.textAlign=c,e.textBaseline=h,e.font=`${p}px sans-serif`,n){case"circles":e.beginPath(),e.arc(t,i,o/2,0,2*Math.PI),e.fill(),a&&e.stroke();break;case"cross":{const s=o/2,n=o/3;e.beginPath(),e.moveTo(t-n/2,i-s),e.lineTo(t+n/2,i-s),e.lineTo(t+n/2,i-n/2),e.lineTo(t+s,i-n/2),e.lineTo(t+s,i+n/2),e.lineTo(t+n/2,i+n/2),e.lineTo(t+n/2,i+s),e.lineTo(t-n/2,i+s),e.lineTo(t-n/2,i+n/2),e.lineTo(t-s,i+n/2),e.lineTo(t-s,i-n/2),e.lineTo(t-n/2,i-n/2),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleUp":{const s=o/2;e.beginPath(),e.moveTo(t,i-s),e.lineTo(t-s,i+s),e.lineTo(t+s,i+s),e.closePath(),e.fill(),a&&e.stroke();break}case"triangleDown":{const s=o/2;e.beginPath(),e.moveTo(t,i+s),e.lineTo(t-s,i-s),e.lineTo(t+s,i-s),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowUp":{const s=.4*o,n=o/3/2,r=i-o/2,l=r+s,c=i+o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}case"arrowDown":{const s=.4*o,n=o/3/2,r=i+o/2,l=r-s,c=i-o/2;e.beginPath(),e.moveTo(t,r),e.lineTo(t+s,l),e.lineTo(t+n,l),e.lineTo(t+n,c),e.lineTo(t-n,c),e.lineTo(t-n,l),e.lineTo(t-s,l),e.closePath(),e.fill(),a&&e.stroke();break}default:e.fillText(n,t,i,this._data?.barSpacing??.8)}e.restore()}}class Do{_renderer;constructor(){this._renderer=new Ao}priceValueBuilder(e){return[e.value]}isWhitespace(e){return void 0===e.value}renderer(){return this._renderer}update(e,t){this._renderer.update(e,t)}defaultOptions(){return Ps}}M();class Lo{id;commandFunctions=[];static handlers=new Map;seriesOriginMap=new WeakMap;wrapper;div;chart;scale;precision=2;series;volumeSeries;volumeUpColor=null;volumeDownColor=null;legend;_topBar;toolBox;spinner;width=null;height=null;_seriesList=[];seriesMap=new Map;seriesMetadata;colorPicker=null;ContextMenu;currentMouseEventParams=null;defaultsManager;scriptsManager;constructor(e,t,i,s,n){this.reSize=this.reSize.bind(this),this.id=e,this.scale={width:t,height:i},this.defaultsManager=new To,this.scriptsManager=new Io,Lo.handlers.set(e,this),this.wrapper=document.createElement("div"),this.wrapper.classList.add("handler"),this.wrapper.style.float=s,this.div=document.createElement("div"),this.div.style.position="relative",this.wrapper.appendChild(this.div),window.containerDiv.append(this.wrapper),this.chart=this._createChart(),this.ContextMenu=new Co(this,Lo.handlers,(()=>window.MouseEventParams??null)),this.legend=new D(this),this.series=this.createCandlestickSeries(),this.volumeSeries=this.createVolumeSeries(),this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e,window.MouseEventParams=e})),document.addEventListener("keydown",(e=>{for(let t=0;t{window.handlerInFocus=this.id,window.MouseEventParams=this.currentMouseEventParams||null})),this.seriesMetadata=new WeakMap,this.createTopBar(),window.monaco=!1,this.chart.subscribeCrosshairMove((e=>{this.currentMouseEventParams=e})),this.reSize(),n&&window.addEventListener("resize",(()=>this.reSize()))}reSize(){let e=0!==this.scale.height&&this._topBar?._div.offsetHeight||0;this.chart.resize(window.innerWidth*this.scale.width,window.innerHeight*this.scale.height-e),this.wrapper.style.width=100*this.scale.width+"%",this.wrapper.style.height=100*this.scale.height+"%",0===this.scale.height||0===this.scale.width?this.toolBox&&(this.toolBox.div.style.display="none"):this.toolBox&&(this.toolBox.div.style.display="flex")}primitives=new Map;_createChart(){return t.createChart(this.div,{width:window.innerWidth*this.scale.width,height:window.innerHeight*this.scale.height,layout:{textColor:window.pane.color,background:{color:"#000000",type:t.ColorType.Solid},fontSize:12},rightPriceScale:{scaleMargins:{top:.3,bottom:.25}},timeScale:{timeVisible:!0,secondsVisible:!1},crosshair:{mode:t.CrosshairMode.Normal,vertLine:{labelBackgroundColor:"rgb(46, 46, 46)"},horzLine:{labelBackgroundColor:"rgb(55, 55, 55)"}},grid:{vertLines:{color:"rgba(29, 30, 38, 5)"},horzLines:{color:"rgba(29, 30, 58, 5)"}},handleScroll:{vertTouchDrag:!0}})}mergeSeriesOptions(e,t){return{...Is(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{},...t}}createCandlestickSeries(){const e="Candlestick",i={...Is(e),...this.defaultsManager.defaults.get(e.toLowerCase())||{}},s=this.chart.addSeries(t.CandlestickSeries,i);s.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}});const n=Ts(s,this.legend);n.applyOptions({title:"OHLC"}),this._seriesList.push(n),this.seriesMap.set("OHLC",n);const o={name:"OHLC",series:n,colors:[i.upColor,i.downColor],legendSymbol:["⋰","⋱"],seriesType:"Candlestick",group:void 0};return this.legend.addLegendItem(o),n}createVolumeSeries(e){const i=this.chart.addSeries(t.HistogramSeries,{color:"#26a69a",priceFormat:{type:"volume"},priceScaleId:"volume_scale"});i.priceScale().applyOptions({scaleMargins:{top:0,bottom:.2}}),void 0!==e&&i.moveToPane(e);const s=Ts(i,this.legend);return s.applyOptions({title:"Volume"}),s}createLineSeries(e,i,s){const n=this.mergeSeriesOptions("Line",i??{}),o=(()=>{switch(n.lineStyle){case 0:return"―";case 1:return":··";case 2:return"--";case 3:return"- -";case 4:return"· ·";default:return"~"}})(),{group:r,legendSymbol:a=o,...l}=n,c=Ts(this.chart.addSeries(t.LineSeries,l),this.legend);c.applyOptions({title:e}),this._seriesList.push(c),this.seriesMap.set(e,c);const h=c.options().color||"rgba(255,0,0,1)",p={name:e,series:c,colors:[h.startsWith("rgba")?h.replace(/[^,]+(?=\))/,"1"):h],legendSymbol:Array.isArray(a)?a:[a],seriesType:"Line",group:r};return this.legend.addLegendItem(p),void 0!==s&&c.moveToPane(s),{name:e,series:c}}createHistogramSeries(e,i,s){const n=this.mergeSeriesOptions("Histogram",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ts(this.chart.addSeries(t.HistogramSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().color||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Histogram",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createAreaSeries(e,i,s){const n=this.mergeSeriesOptions("Area",i??{}),{group:o,legendSymbol:r="▨",...a}=n,l=Ts(this.chart.addSeries(t.AreaSeries,a),this.legend);this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().lineColor||"rgba(255,0,0,1)",h={name:e,series:l,colors:[c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Area",group:o};return this.legend.addLegendItem(h),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createBarSeries(e,i,s){const n=this.mergeSeriesOptions("Bar",i??{}),{group:o,legendSymbol:r=["┌","└"],...a}=n,l=Ts(this.chart.addSeries(t.BarSeries,a),this.legend);l.applyOptions({title:e}),this._seriesList.push(l),this.seriesMap.set(e,l);const c=l.options().upColor||"rgba(0,255,0,1)",h=l.options().downColor||"rgba(255,0,0,1)",p={name:e,series:l,colors:[c,h],legendSymbol:Array.isArray(r)?r:[r],seriesType:"Bar",group:o};return this.legend.addLegendItem(p),void 0!==s&&l.moveToPane(s),{name:e,series:l}}createCustomOHLCSeries(e,t,i){const s={...Mo,...this.defaultsManager.defaults.get("ohlc")||{},...t,seriesType:"Ohlc"},{group:n,legendSymbol:o=["⑃","⑂"],seriesType:r,chandelierSize:a,...l}=s,c=new Po,h=Ts(this.chart.addCustomSeries(c,{...l,chandelierSize:a,title:e}),this.legend);this._seriesList.push(h),this.seriesMap.set(e,h);const p={name:e,series:h,colors:[s.borderUpColor||s.upColor,s.borderDownColor||s.downColor],legendSymbol:Array.isArray(o)?o:o?[o]:[],seriesType:"Ohlc",group:n};return this.legend.addLegendItem(p),void 0!==i&&h.moveToPane(i),{name:e,series:h}}createSymbolSeries(e,t,i){const s={...Ps,...this.defaultsManager.defaults.get("symbol")||{},...t,seriesType:"Symbol"},n=(()=>{switch(s.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return s.shape}})(),{group:o,legendSymbol:r=n,...a}=s,l=new Do,c=Ts(this.chart.addCustomSeries(l,{...a,title:e}),this.legend);this._seriesList.push(c),this.seriesMap.set(e,c);const h={name:e,series:c,colors:[c.options().color||"rgba(255,0,0,1)"],legendSymbol:Array.isArray(r)?r:r?[r]:[],seriesType:"Symbol",group:o};return this.legend.addLegendItem(h),void 0!==i&&c.moveToPane(i),{name:e,series:c}}createFillArea(e,t,i,s,n){const o=this._seriesList.find((e=>e.options()?.title===t)),r=this._seriesList.find((e=>e.options()?.title===i));if(!o)return void console.warn(`Origin series with title "${t}" not found.`);if(!r)return void console.warn(`Destination series with title "${i}" not found.`);const a=Ns(o,this.legend),l=new _(o,r,{originColor:s||null,destinationColor:n||null,lineWidth:null});return a.attachPrimitive(l,e),l}attachPrimitive(e,t,i,s){let n=i;try{if(s&&!i&&(n=this.seriesMap.get(s)),!n)return void console.warn(`Series with the name "${s}" not found.`);const o=Ns(n,this.legend);let r;if("Tooltip"!==t)return void console.warn(`Unknown primitive type: ${t}`);r=new bn({lineColor:e}),o.attachPrimitive(r,"Tooltip"),this.primitives.set(n,r)}catch(e){console.error(`Failed to attach ${t}:`,e)}}removeSeries(e){let t;if(x(e)){for(const[i,s]of this.seriesMap.entries())if(s===e){t=i;break}}else t=e,e=this.seriesMap.get(e);if(e&&t){e.primitives&&e.primitives.length>0&&e.primitives.forEach((i=>{e.detachPrimitive(i),console.log(`✅ Detached primitive from series "${t}".`)})),this._seriesList=this._seriesList.filter((t=>t!==e)),this.seriesMap.delete(t),console.log(`✅ Series "${t}" removed from internal maps.`);try{const i=this.legend._items.find((t=>t.series===e));i?(i.primitives&&i.primitives.length>0&&i.primitives.forEach((e=>{this.legend.removeLegendPrimitive(e),console.log(`✅ Removed primitive from legend for series "${t}".`)})),this.legend.deleteLegendEntry(i.name,i.group??void 0),console.log(`✅ Removed series "${t}" from legend.`)):console.warn(`⚠️ Legend item for series "${t}" not found.`)}catch(e){console.error(`⚠️ Error removing legend entry for "${t}":`,e)}this.chart.removeSeries(e),console.log(`✅ Series "${t}" successfully removed.`)}else console.warn(`❌ Series "${e}" does not exist and cannot be removed.`)}createToolBox(){this.toolBox=new ue(this,this.id,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new cn(this),this.wrapper.prepend(this._topBar._div),this._topBar}extractSeriesData(e){const t=e.data();return Array.isArray(t)?t.map((e=>[e.time,e.value||e.close||0])):(console.warn("Failed to extract data: series data is not in array format."),[])}static syncCharts(e,t,i=!1){function s(e,t){t?(e.chart.setCrosshairPosition(t.value||t.close,t.time,e.series),e.legend.legendHandler(t,!0)):e.chart.clearCrosshairPosition()}function n(e,t){return t.time&&t.seriesData.get(e)||null}const o=e.chart.timeScale(),r=t.chart.timeScale(),a=e=>{e&&o.setVisibleLogicalRange(e)},l=e=>{e&&r.setVisibleLogicalRange(e)},c=i=>{s(t,n(e.series,i))},h=i=>{s(e,n(t.series,i))};let p=t;function d(e,t,s,n,o,r){e.wrapper.addEventListener("mouseover",(()=>{p!==e&&(p=e,t.chart.unsubscribeCrosshairMove(s),e.chart.subscribeCrosshairMove(n),i||(t.chart.timeScale().unsubscribeVisibleLogicalRangeChange(o),e.chart.timeScale().subscribeVisibleLogicalRangeChange(r)))}))}d(t,e,c,h,l,a),d(e,t,h,c,a,l),t.chart.subscribeCrosshairMove(h);const u=r.getVisibleLogicalRange();u&&o.setVisibleLogicalRange(u),i||t.chart.timeScale().subscribeVisibleLogicalRangeChange(a)}static makeSearchBox(e){const t=document.createElement("div");t.classList.add("searchbox"),t.style.display="none";const i=document.createElement("div");i.innerHTML='';const s=document.createElement("input");return s.type="text",t.appendChild(i),t.appendChild(s),e.div.appendChild(t),e.commandFunctions.push((i=>!1===window.monaco&&!1===window.menu&&(window.handlerInFocus===e.id&&!window.textBoxFocused&&("none"===t.style.display?!!/^[a-zA-Z0-9]$/.test(i.key)&&(t.style.display="flex",s.focus(),!0):("Enter"===i.key||"Escape"===i.key)&&("Enter"===i.key&&window.callbackFunction(`search${e.id}_~_${s.value}`),t.style.display="none",s.value="",!0))))),s.addEventListener("input",(()=>s.value=s.value.toUpperCase())),{window:t,box:s}}static makeSpinner(e){e.spinner=document.createElement("div"),e.spinner.classList.add("spinner"),e.wrapper.appendChild(e.spinner);let t=0;!function i(){e.spinner&&(t+=10,e.spinner.style.transform=`translate(-50%, -50%) rotate(${t}deg)`,requestAnimationFrame(i))}()}static _styleMap={"--bg-color":"backgroundColor","--hover-bg-color":"hoverBackgroundColor","--click-bg-color":"clickBackgroundColor","--active-bg-color":"activeBackgroundColor","--muted-bg-color":"mutedBackgroundColor","--border-color":"borderColor","--color":"color","--active-color":"activeColor"};static setRootStyles(e){const t=document.documentElement.style;for(const[i,s]of Object.entries(this._styleMap))t.setProperty(i,e[s])}toJSON(){return{id:this.id,options:this.chart.options(),scale:this.scale,precision:this.precision}}fromJSON(e){e?(e.options&&this.chart.applyOptions(e.options),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.precision&&(this.precision=e.precision)):console.warn("No JSON data provided for handler deserialization.")}_type="chart";title="chart"}return e.Box=Z,e.CodeEditor=on,e.FillArea=_,e.Handler=Lo,e.HorizontalLine=se,e.Legend=D,e.RayLine=ne,e.Table=class{_div;callbackName;borderColor;borderWidth;table;rows={};headings;widths;alignments;footer;header;constructor(e,t,i,s,n,o,r=!1,a,l,c,h,p){this._div=document.createElement("div"),this.callbackName=null,this.borderColor=l,this.borderWidth=c,r?(this._div.style.position="absolute",this._div.style.cursor="move"):(this._div.style.position="relative",this._div.style.float=o),this._div.style.zIndex="2000",this.reSize(e,t),this._div.style.display="flex",this._div.style.flexDirection="column",this._div.style.borderRadius="5px",this._div.style.color="white",this._div.style.fontSize="12px",this._div.style.fontVariantNumeric="tabular-nums",this.table=document.createElement("table"),this.table.style.width="100%",this.table.style.borderCollapse="collapse",this._div.style.overflow="hidden",this.headings=i,this.widths=s.map((e=>100*e+"%")),this.alignments=n;let d=this.table.createTHead().insertRow();for(let e=0;e0?p[e]:a,t.style.color=h[e],d.appendChild(t)}let u,m,g=document.createElement("div");if(g.style.overflowY="auto",g.style.overflowX="hidden",g.style.backgroundColor=a,g.appendChild(this.table),this._div.appendChild(g),window.containerDiv.appendChild(this._div),!r)return;let f=e=>{this._div.style.left=e.clientX-u+"px",this._div.style.top=e.clientY-m+"px"},y=()=>{document.removeEventListener("mousemove",f),document.removeEventListener("mouseup",y)};this._div.addEventListener("mousedown",(e=>{u=e.clientX-this._div.offsetLeft,m=e.clientY-this._div.offsetTop,document.addEventListener("mousemove",f),document.addEventListener("mouseup",y)}))}divToButton(e,t){e.addEventListener("mouseover",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)")),e.addEventListener("mouseout",(()=>e.style.backgroundColor="transparent")),e.addEventListener("mousedown",(()=>e.style.backgroundColor="rgba(60, 60, 60)")),e.addEventListener("click",(()=>window.callbackFunction(t))),e.addEventListener("mouseup",(()=>e.style.backgroundColor="rgba(60, 60, 60, 0.6)"))}newRow(e,t=!1){let i=this.table.insertRow();i.style.cursor="default";for(let s=0;s{e&&(window.cursor=e),document.body.style.cursor=window.cursor},e}({},LightweightCharts,monaco);
+var Lib=function(e,t,i){"use strict";function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var s=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n,o=s(i);function r(e){if(void 0===e)throw new Error("Value is undefined");return e}class a{_chart=void 0;_series=void 0;requestUpdate(){this._requestUpdate&&this._requestUpdate()}_requestUpdate;attached({chart:e,series:t,requestUpdate:i}){this._chart=e,this._series=t,this._series.subscribeDataChanged(this._fireDataUpdated),this._requestUpdate=i,this.requestUpdate()}detached(){this._chart=void 0,this._series=void 0,this._requestUpdate=void 0}get chart(){return r(this._chart)}get series(){return r(this._series)}_fireDataUpdated(e){this.dataUpdated&&this.dataUpdated(e)}toJSON(){return{}}fromJSON(e){}}function l(e,t){if(e.startsWith("#"))return function(e,t){if(e=e.replace(/^#/,""),!/^([0-9A-F]{3}){1,2}$/i.test(e))throw new Error("Invalid hex color format.");const[i,s,n]=3===(o=e).length?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];var o;return`rgba(${i}, ${s}, ${n}, ${t})`}(e,t);{const i=/^rgb(a)?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:,\s*([\d.]+))?\)/i,s=e.match(i);if(s){const e=s[2],i=s[3],n=s[4],o=s[1]?s[5]??"1":"1";return`rgba(${e}, ${i}, ${n}, ${t??o})`}throw new Error("Unsupported color format. Use hex, rgb, or rgba.")}}function c(e,t=.2){let[i,s,n,o=1]=e.startsWith("#")?[...(r=e,3===(r=r.replace(/^#/,"")).length?[parseInt(r[0]+r[0],16),parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16)]:[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),1]:e.match(/\d+(\.\d+)?/g).map(Number);var r;return i=Math.max(0,Math.min(255,i*(1-t))),s=Math.max(0,Math.min(255,s*(1-t))),n=Math.max(0,Math.min(255,n*(1-t))),e.startsWith("#")?`#${((1<<24)+(Math.round(i)<<16)+(Math.round(s)<<8)+Math.round(n)).toString(16).slice(1)}`:`rgba(${Math.round(i)}, ${Math.round(s)}, ${Math.round(n)}, ${o})`}function h(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?h(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}function p(e){if(e.length>100)return 1;let t=1;const i=/^rgba\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(\d?\.?\d+)\s*$/i.exec(e),s=/^hsla\s*\d{1,3}(?:\.\d+)?\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(\d?\.?\d+)\s*$/i.exec(e);return i?t=parseFloat(i[1]):s&&(t=parseFloat(s[1])),isNaN(t)?1:Math.max(0,Math.min(1,t))}class d{numbers;cache;constructor(e){this.numbers=e,this.cache=new Map}findClosestIndex(e,t){const i=`${e}:${t}`;if(this.cache.has(i))return this.cache.get(i);const s=this._performSearch(e,t);return this.cache.set(i,s),s}_performSearch(e,t){let i=0,s=this.numbers.length-1;if(e<=this.numbers[0].time)return 0;if(e>=this.numbers[s].time)return s;for(;i<=s;){const t=Math.floor((i+s)/2),n=this.numbers[t].time;if(n===e)return t;n>e?s=t-1:i=t+1}return"left"===t?i:s}}function u(e){switch(e.trim().toLowerCase()){case"rectangle":return n.Rectangle;case"rounded":return n.Rounded;case"ellipse":return n.Ellipse;case"arrow":return n.Arrow;case"3d":return n.Cube;case"polygon":return n.Polygon;case"bar":return n.Bar;case"slanted":return n.Slanted;default:return console.warn(`Unknown CandleShape: ${e}`),n.Rectangle}}function m(e){return e.type===t.ColorType.Solid}function g(e){return e.type===t.ColorType.VerticalGradient}function f(e){return"value"in e}function y(e){return"close"in e&&"open"in e&&"high"in e&&"low"in e}function b(e){return!(!e||"object"!=typeof e)&&("time"in e&&!("value"in e||"open"in e||"close"in e||"high"in e||"low"in e))}function v(e){const t=e.options();return"lineColor"in t||"color"in t}function x(e){return"object"==typeof e&&null!==e&&"function"==typeof e.data&&"function"==typeof e.options}!function(e){e.Rectangle="Rectangle",e.Rounded="Rounded",e.Ellipse="Ellipse",e.Arrow="Arrow",e.Cube="3d",e.Polygon="Polygon",e.Bar="Bar",e.Slanted="Slanted"}(n||(n={}));class _ extends a{static type="Fill Area";_paneViews;_originSeries;_destinationSeries;_bandsData=[];options;_timeIndices;constructor(e,t,i){super();const s=l("#0000FF",.25),n=l("#FF0000",.25),o=v(e)?l(e.options().color||s,.3):l(s,.3),r=v(t)?l(t.options().color||n,.3):l(n,.3);this.options={...S,...i,originColor:i.originColor??o,destinationColor:i.destinationColor??r},this._paneViews=[new C(this)],this._timeIndices=new d([]),this._originSeries=e,this._destinationSeries=t,this._originSeries.subscribeDataChanged((()=>{console.log("Origin series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()})),this._destinationSeries.subscribeDataChanged((()=>{console.log("Destination series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()}))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}applyOptions(e){this.options={...this.options,...e},this.calculateBands(),this.updateAllViews(),super.requestUpdate(),console.log("FillArea options updated:",this.options)}paneViews(){return this._paneViews}attached(e){super.attached(e),this.dataUpdated("full")}dataUpdated(e){if(this.calculateBands(),"full"===e){const e=this._originSeries.data();this._timeIndices=new d([...e])}}calculateBands(){const e=this._originSeries.data(),t=this._destinationSeries.data(),i=this._alignDataLengths([...e],[...t]),s=[];for(let e=0;es){const e=t[s-1];for(;t.lengthi){const t=e[i-1];for(;e.lengthe.lower)).slice(o,r+1)),maxValue:Math.max(...this._bandsData.map((e=>e.upper)).slice(o,r+1))};return{priceRange:{minValue:a.minValue,maxValue:a.maxValue}}}}class w{_viewData;_options;constructor(e){this._viewData=e,this._options=e.options}draw(){}drawBackground(e){const t=this._viewData.data,i=this._options;t.length<2||e.useBitmapCoordinateSpace((e=>{const s=e.context;s.scale(e.horizontalPixelRatio,e.verticalPixelRatio);let n=!1,o=0;for(let e=0;e=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill()}s.beginPath(),s.moveTo(r.x,r.origin),s.fillStyle=r.isOriginAbove?i.originColor||"rgba(0, 0, 0, 0)":i.destinationColor||"rgba(0, 0, 0, 0)",o=e,n=!0}if(s.lineTo(a.x,a.origin),e===t.length-2||a.isOriginAbove!==r.isOriginAbove){for(let i=e+1;i>=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill(),n=!1}}i.lineWidth&&(s.lineWidth=i.lineWidth,s.strokeStyle=i.originColor||"rgba(0, 0, 0, 0)",s.stroke())}))}}class C{_source;_data;constructor(e){this._source=e,this._data={data:[],options:this._source.options}}update(){const e=this._source.chart.timeScale();this._data.data=this._source._bandsData.map((t=>({x:e.timeToCoordinate(t.time),origin:this._source._originSeries.priceToCoordinate(t.origin),destination:this._source._destinationSeries.priceToCoordinate(t.destination),isOriginAbove:t.origin>t.destination}))),this._data.options=this._source.options}renderer(){return new w(this._data)}zOrder(){return"bottom"}}const S={originColor:null,destinationColor:null,lineWidth:null};function k(e,t){let i,s;if(void 0!==e.close){i=e.close}else void 0!==e.value&&(i=e.value);if(void 0!==t.close){s=t.close}else void 0!==t.value&&(s=t.value);if(void 0!==i&&void 0!==s){if(i{e&&(window.cursor=e),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}const P='\n\n',T='\n\n';class I{contextMenu;handler;constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler}populateLegendMenu(e,t){this.contextMenu.clearMenu();void 0!==e.seriesList?this.populateGroupMenu(e,t):this.populateSeriesMenu(e,t),this.contextMenu.separator(),this.contextMenu.addMenuItem("Close Menu",(()=>this.contextMenu.hideMenu())),this.contextMenu.showMenu(t)}populateGroupMenu(e,t){if(this.contextMenu.addMenuItem("Rename",(()=>{const t=prompt("Enter new group name:",e.name);t&&""!==t.trim()&&this.renameGroup(e,t.trim())}),!1),this.contextMenu.addMenuItem("Remove",(()=>{confirm(`Are you sure you want to remove the group "${e.name}"? This will also remove all contained series.`)&&(e.seriesList.forEach((e=>{this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series)})),this.removeGroup(e))})),this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeries(e)})),e.seriesList&&e.seriesList.length>0){const t=e.seriesList[0].series.getPane().paneIndex(),i=this.handler.chart.panes(),s=`Pane ${t}`,n=()=>{0===t?i.length>1?(e.seriesList.forEach((e=>{e.series.moveToPane(1)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to pane 1.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to a new pane at index ${i.length}.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(0)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} back to main pane (0).`))},o=[];for(let t=0;t{e.seriesList.forEach((e=>{e.series.moveToPane(t)})),console.log(`Moved group "${e.name}" series to existing pane ${t}.`)}});o.push({name:"New Pane",action:()=>{e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Moved group "${e.name}" series to a new pane at index ${i.length}.`)}}),this.contextMenu.addMenuInput(this.contextMenu.div,{type:"hybrid",label:"Move to",sublabel:s,value:s,onChange:e=>{const t=o.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:n,options:o.map((e=>({name:e.name,action:e.action})))}})}this.contextMenu.showMenu(t)}populateSeriesMenu(e,t){this.contextMenu.addMenuItem("Open Series Menu",(()=>{this.contextMenu.populateSeriesMenu(e.series,t)}),!1),this.contextMenu.addMenuItem("Move to Group ▸",(()=>{this.populateMoveToGroupMenu(e)}),!1),this.contextMenu.addMenuItem("Remove Series",(()=>{confirm(`Are you sure you want to remove the series "${e.name}"?`)&&(this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series))})),e.primitives&&this.contextMenu.addMenuItem("Remove Primitives",(()=>{this.removePrimitivesFromSeries(e)})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)})),this.contextMenu.showMenu(t)}populateMoveToGroupMenu(e){this.contextMenu.clearMenu();this.handler.legend._groups.forEach((t=>{this.contextMenu.addMenuItem(t.name,(()=>{this.handler.legend.moveSeriesToGroup(e,t)}))})),this.contextMenu.addMenuItem("Create New Group...",(()=>{const t=prompt("Enter new group name:","New Group");t&&""!==t.trim()&&this.createNewGroup(e,t.trim())})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)}))}renameGroup(e,t){e.name=t,e.seriesList.forEach((e=>{e.group=t}));const i=e.row.querySelector(".group-header span");i&&(i.textContent=t),console.log(`Group renamed to: ${t}`)}removeGroup(e){this.handler.legend.removeLegendGroup(e),this.handler.legend._groups=this.handler.legend._groups.filter((t=>t!==e)),console.log(`Group "${e.name}" removed along with its series.`)}createNewGroup(e,t){this.handler.legend.deleteLegendEntry(e),e.group=t,this.handler.legend.addLegendItem(e)}ungroupSeriesFromGroup(e){this.handler.legend.getGroupOfSeries(e.series)&&(this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)),console.log(`Series "${e.name}" removed from its group and is now standalone.`)}removePrimitivesFromSeries(e){e.series.primitives&&(Object.values(e.series.primitives).forEach((t=>{e.series.detachPrimitive(t),console.log(`Primitive removed from series "${e.name}".`)})),e.primitives=void 0),console.log(`All primitives removed from series "${e.name}".`)}ungroupSeries(e){e.seriesList.forEach((e=>{this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)})),this.removeGroup(e),console.log(`All series in group "${e.name}" have been ungrouped and are now standalone.`)}}function A(e){return e.data()[e.data().length-1]}class D{handler;div;seriesContainer;legendMenu;linesEnabled=!1;contextMenu;text;_items=[];_lines=[];_groups=[];constructor(e){this.handler=e,this.div=document.createElement("div"),this.div.classList.add("legend"),this.seriesContainer=document.createElement("div"),this.text=document.createElement("span"),this.contextMenu=this.handler.ContextMenu,this.legendMenu=new I({contextMenu:this.contextMenu,handler:e}),this.setupLegend(),this.legendHandler=this.legendHandler.bind(this),e.chart.subscribeCrosshairMove(this.legendHandler)}setupLegend(){this.div.style.maxWidth=100*this.handler.scale.width-8+"vw",this.div.style.display="none";const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="row",this.seriesContainer.classList.add("series-container"),this.text.style.lineHeight="1.8",e.appendChild(this.seriesContainer),this.div.appendChild(this.text),this.div.appendChild(e),this.handler.div.appendChild(this.div)}legendItemFormat(e,t){return"number"!=typeof e||isNaN(e)?"-":e.toFixed(t).toString().padStart(8," ")}shorthandFormat(e){const t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(1)+"M":t>=1e3?(e/1e3).toFixed(1)+"K":e.toString().padStart(8," ")}createSvgIcon(e){const t=document.createElement("div");t.innerHTML=e.trim();return t.querySelector("svg")}addLegendItem(e){const t=this.mapToSeries(e);if(t.group)return this.addItemToGroup(t,t.group);{const e=this.makeSeriesRow(t,this.seriesContainer);return this._lines.push(t),this._items.push(t),e}}addLegendPrimitive(e,t,i){const s=i||t.constructor.name,n=this._lines.find((t=>t.series===e));if(!n)return void console.warn(`Parent series not found in legend for primitive: ${s}`);n.primitives||(n.primitives=[]);let o=this.seriesContainer.querySelector(`[data-series-id="${n.name}"] .primitives-container`);o||(o=document.createElement("div"),o.classList.add("primitives-container"),o.style.display="none",o.style.marginLeft="20px",o.style.flexDirection="column",n.row.insertAdjacentElement("afterend",o));const r=Array.from(o.children).find((e=>e.getAttribute("data-primitive-type")===s));if(r)return console.warn(`Primitive "${s}" already exists under the parent series.`),r;const a=document.createElement("div");a.classList.add("legend-primitive-row"),a.setAttribute("data-primitive-type",s),a.style.display="flex",a.style.justifyContent="space-between",a.style.marginTop="4px";const l=document.createElement("span");l.innerText=s;const c=document.createElement("div");c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center";const h=this.createSvgIcon(P),p=this.createSvgIcon(T);c.appendChild(h.cloneNode(!0));let d=!0;c.addEventListener("click",(()=>{d=!d,c.innerHTML="",c.appendChild(d?h.cloneNode(!0):p.cloneNode(!0)),this.togglePrimitive(t,d)})),a.appendChild(l),a.appendChild(c),o.appendChild(a),o.children.length>0&&(o.style.display="block");const u={name:s,primitive:t,row:a};return this._items.push(u),n.primitives.push(u),a}togglePrimitive(e,t){const i=e.options||e._options;if(!i)return void console.warn("Primitive has no options to update.");const s={};if("visible"in i)return s.visible=t,console.log(`Toggling visible option for primitive: ${e.constructor.name} to ${t}`),void e.applyOptions(s);const n="_originalColors";e[n]||(e[n]={});const o=e[n];for(const e of Object.keys(i))e.toLowerCase().includes("color")&&(t?s[e]=o[e]||i[e]:(o[e]||(o[e]=i[e]),s[e]="rgba(0,0,0,0)"));Object.keys(s).length>0&&(console.log(`Updating visibility for primitive: ${e.constructor.name}`),e.applyOptions(s),t&&delete e[n])}findLegendPrimitive(e,t){const i=this._lines.find((t=>t.series===e));if(!i||!i.primitives)return null;return i.primitives.find((e=>e.primitive===t))||null}mapToSeries(e){return{name:e.name,series:e.series,group:e.group||void 0,legendSymbol:e.legendSymbol||[],colors:e.colors||["#000"],seriesType:e.seriesType||"Line",div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div"),extraData:e.extraData||null}}addItemToGroup(e,t){let i=this._groups.find((e=>e.name===t));return i?(i.seriesList.push(e),this.makeSeriesRow(e,i.div),i.row):this.makeSeriesGroup(t,[e])}makeSeriesGroup(e,t){let i=this._groups.find((t=>t.name===e));if(i)return i.seriesList.push(...t),t.forEach((e=>this.makeSeriesRow(e,i.div))),i.row;{const i={name:e,seriesList:t,subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")};return this._groups.push(i),this.renderGroup(i,this.seriesContainer),i.row}}makeSeriesRow(e,t){const i=document.createElement("div");i.classList.add("legend-series-row"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.marginBottom="4px";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Series Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("div");n.classList.add("series-info"),n.style.flex="1";if(["Bar","Candlestick","Ohlc"].includes(e.seriesType||"")){const t="-",i="-",s=e.legendSymbol[0]||"▨",o=e.legendSymbol[1]||s,r=e.colors[0]||"#00FF00",a=e.colors[1]||"#FF0000";n.innerHTML=`\n ${s}\n ${o}\n ${e.name}: O ${t}, \n C ${i}\n `}else n.innerHTML=e.legendSymbol.map(((t,i)=>`${t}`)).join(" ")+` ${e.name}`;const o=document.createElement("div");o.classList.add("legend-toggle-switch"),o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center";const r=this.createSvgIcon(P),a=this.createSvgIcon(T);o.appendChild(r.cloneNode(!0));let l=!0;o.addEventListener("click",(t=>{l=!l,e.series.applyOptions({visible:l}),o.innerHTML="",o.appendChild(l?r.cloneNode(!0):a.cloneNode(!0)),o.setAttribute("aria-pressed",l.toString()),o.classList.toggle("inactive",!l),t.stopPropagation()})),o.setAttribute("role","button"),o.setAttribute("aria-label",`Toggle visibility for ${e.name}`),o.setAttribute("aria-pressed",l.toString()),i.appendChild(s),i.appendChild(n),i.appendChild(o),t.appendChild(i),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)}));const c={...e,div:n,row:i,toggle:o};return this._lines.push(c),this._items.push(c),i}isLegendPrimitive(e){return void 0!==e.primitive&&void 0!==e.row}deleteLegendEntry(e,t){if(t&&!e){const e=this._groups.findIndex((e=>e.name===t));if(-1!==e){const i=this._groups[e];this.seriesContainer.removeChild(i.row),this._groups.splice(e,1),this._items=this._items.filter((e=>e!==i)),console.log(`Group "${t}" removed.`)}else console.warn(`Legend group with name "${t}" not found.`)}else if(e){let i=!1;if(t){const s=this._groups.find((e=>e.name===t));if(s){const n=s.seriesList.findIndex((t=>t.name===e));-1!==n&&(s.seriesList.splice(n,1),0===s.seriesList.length?(this.seriesContainer.removeChild(s.row),this._groups=this._groups.filter((e=>e!==s)),this._items=this._items.filter((e=>e!==s)),console.log(`Group "${t}" is empty and has been removed.`)):this.renderGroup(s,this.seriesContainer),i=!0,console.log(`Series "${e}" removed from group "${t}".`))}else console.warn(`Legend group with name "${t}" not found.`)}if(!i){const t=this._lines.findIndex((t=>t.name===e));if(-1!==t){const s=this._lines[t];this.seriesContainer.removeChild(s.row),this._lines.splice(t,1),this._items=this._items.filter((e=>e!==s)),i=!0,console.log(`Series "${e}" removed.`)}}i||console.warn(`Legend item with name "${e}" not found.`)}else console.warn("No seriesName or groupName provided for deletion.")}removeLegendGroup(e){this.seriesContainer.contains(e.row)&&this.seriesContainer.removeChild(e.row);const t=this._groups.indexOf(e);-1!==t&&this._groups.splice(t,1),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed from legend.`)}findSeriesAnywhere(e){const t=this._lines.find((t=>t.series===e));if(t)return t;for(const t of this._groups){const i=this.findSeriesInGroup(t,e);if(i)return i}}findSeriesInGroup(e,t){const i=e.seriesList.find((e=>e.series===t));if(i)return i;for(const i of e.subGroups){const e=this.findSeriesInGroup(i,t);if(e)return e}}removeSeriesFromGroupDOM(e,t){if(!e.div||!t.row)return console.warn(`⚠️ Cannot remove series "${t.name}" – missing group div or series row.`),!1;if(e.div.contains(t.row))try{return e.div.removeChild(t.row),console.log(`✅ Removed series "${t.name}" from group "${e.name}".`),!0}catch(i){return console.warn(`⚠️ Error removing series "${t.name}" from group "${e.name}":`,i),!1}return e.subGroups.some((e=>this.removeSeriesFromGroupDOM(e,t)))}removeLegendSeries(e){let t;if(t=x(e)?this.findSeriesAnywhere(e):e,t){if(this._lines=this._lines.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),t.group){const e=this.findGroup(t.group);if(e){if(e.seriesList=e.seriesList.filter((e=>e!==t)),t.row&&e.div.contains(t.row))try{e.div.removeChild(t.row),console.log(`✅ Removed "${t.name}" from group "${e.name}".`)}catch(i){console.warn(`⚠️ Error removing "${t.name}" from group "${e.name}":`,i)}0===e.seriesList.length&&this.removeGroupCompletely(e)}}else if(t.row?.parentElement)try{t.row.parentElement.removeChild(t.row),console.log(`✅ Removed row for standalone series: ${t.name}`)}catch(e){console.warn("⚠️ Error removing standalone series row:",e)}}else console.warn("⚠️ LegendSeries not found in legend.")}removeGroupCompletely(e){if(e.row.parentElement)try{e.row.parentElement.removeChild(e.row)}catch(t){console.warn(`Error removing group "${e.name}":`,t)}this._groups=this._groups.filter((t=>t!==e)),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed as it became empty.`)}removeLegendPrimitive(e){let t;if(t=this.isLegendPrimitive(e)?e:this._items.find((t=>this.isLegendPrimitive(t)&&t.primitive===e)),!t)return void console.warn("❌ LegendPrimitive not found in legend.");t.row&&t.row.parentElement?t.row.parentElement.removeChild(t.row):console.warn("❌ LegendPrimitive row not found in the DOM.");const i=this._lines.find((e=>e.primitives?.includes(t)));if(i&&(i.primitives=i.primitives.filter((e=>e!==t)),console.log(`✅ Removed primitive "${t.name}" from series "${i.name}".`)),this._items=this._items.filter((e=>e!==t)),t.primitive)try{console.log(`Detaching underlying chart primitive for "${t.name}".`),i?.series.detachPrimitive(t.primitive)}catch(e){console.warn(`⚠️ Failed to detach primitive "${t.name}":`,e)}console.log(`✅ LegendPrimitive "${t.name}" removed from legend.`)}getGroupOfSeries(e){for(const t of this._groups){const i=this.findGroupOfSeriesRecursive(t,e);if(i)return i}}findGroupOfSeriesRecursive(e,t){for(const i of e.seriesList)if(i.series===t)return e.name;for(const i of e.subGroups){const e=this.findGroupOfSeriesRecursive(i,t);if(e)return e}}moveSeriesToGroup(e,t){let i=this._lines.findIndex((t=>t.name===e)),s=null;if(-1!==i)s=this._lines[i];else for(const t of this._groups){const i=t.seriesList.findIndex((t=>t.name===e));if(-1!==i){s=t.seriesList[i],t.seriesList.splice(i,1),0===t.seriesList.length?(this.seriesContainer.removeChild(t.row),this._groups=this._groups.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),console.log(`Group "${t.name}" is empty and has been removed.`)):this.renderGroup(t,this.seriesContainer);break}}if(!s)return void console.warn(`Series "${e}" not found in legend.`);-1!==i?(this.seriesContainer.removeChild(s.row),this._lines.splice(i,1),this._items=this._items.filter((e=>e!==s))):this._items=this._items.filter((e=>e!==s));let n=this.findGroup(t);n?(n.seriesList.push(s),this.makeSeriesRow(s,n.div)):(n={name:t,seriesList:[s],subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")},this._groups.push(n),this.renderGroup(n,this.seriesContainer)),this._items.push(s),console.log(`Series "${e}" moved to group "${t}".`)}renderGroup(e,t){e.row.innerHTML="",e.row.style.display="flex",e.row.style.flexDirection="column",e.row.style.width="100%";const i=document.createElement("div");i.classList.add("group-header"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.cursor="pointer";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Group Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("span");n.style.fontWeight="bold",n.innerHTML=e.seriesList.map((e=>e.legendSymbol.map(((t,i)=>`${t}`)).join(" "))).join(" ")+` ${e.name}`;const o=document.createElement("span");o.classList.add("toggle-button"),o.style.marginLeft="auto",o.style.fontSize="1.2em",o.style.cursor="pointer",o.innerHTML="⌲",o.setAttribute("aria-expanded","true"),o.addEventListener("click",(t=>{t.stopPropagation(),"none"===e.div.style.display?(e.div.style.display="block",o.innerHTML="⌲",o.setAttribute("aria-expanded","true")):(e.div.style.display="none",o.innerHTML="☰",o.setAttribute("aria-expanded","false"))})),i.appendChild(s),i.appendChild(n),i.appendChild(o),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)})),e.row.appendChild(i),e.div=document.createElement("div"),e.div.style.display="block",e.div.style.marginLeft="10px";for(const t of e.seriesList)this.makeSeriesRow(t,e.div);for(const t of e.subGroups){const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="column",i.style.paddingLeft="5px",this.renderGroup(t,i),e.div.appendChild(i)}e.row.appendChild(e.div),t.contains(e.row)||t.appendChild(e.row),e.row.oncontextmenu=e=>{e.preventDefault()}}legendHandler(e,t=!1){this.updateGroupDisplay(e,null,t),this.updateSeriesDisplay(e,null,t)}updateSeriesDisplay(e,t,i){this._lines&&this._lines.length?this._lines.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.series.options().priceFormat;if("Line"===s||"Area"===s||"Histogram"===s||"Symbol"==s){const e=i;if(null==e.value)return;const s=this.legendItemFormat(e.value,n.precision);t.div.innerHTML=`\n ${t.legendSymbol[0]||"▨"} \n ${t.name}: ${s}`}else if("Bar"===s||"Candlestick"===s||"Ohlc"===s){const{open:e,close:s}=i;if(null==e||null==s)return;const o=this.legendItemFormat(e,n.precision),r=this.legendItemFormat(s,n.precision),a=s>e,l=a?t.colors[0]:t.colors[1],c=a?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${c||"▨"}\n ${t.name}: \n O ${o}, \n C ${r}`}})):console.error("No lines available to update legend.")}updateGroupDisplay(e,t,i){this._groups.forEach((t=>{this.linesEnabled?(t.row.style.display="flex",t.seriesList.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.name,o=t.series.options().priceFormat;if(["Bar","Candlestick","Ohlc"].includes(s)){const{open:e,close:s,high:r,low:a}=i;if(null==e||null==s||null==r||null==a)return;const l=this.legendItemFormat(e,o.precision),c=this.legendItemFormat(s,o.precision),h=s>e,p=h?t.colors[0]:t.colors[1],d=h?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${d||"▨"}\n ${n}: \n O ${l}, \n C ${c}\n `}else{const e="value"in i?i.value:void 0;if(null==e)return;const s=this.legendItemFormat(e,o.precision),r=t.colors[0],a=t.legendSymbol[0]||"▨";t.div.innerHTML=`\n ${a}\n ${n}: ${s}\n `}}))):t.row.style.display="none"}))}findGroup(e,t=this._groups){for(const i of t){if(i.name===e)return i;const t=this.findGroup(e,i.subGroups);if(t)return t}}}const L={lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:4};var N;!function(e){e[e.NONE=0]="NONE",e[e.HOVERING=1]="HOVERING",e[e.DRAGGING=2]="DRAGGING",e[e.DRAGGINGP1=3]="DRAGGINGP1",e[e.DRAGGINGP2=4]="DRAGGINGP2",e[e.DRAGGINGP3=5]="DRAGGINGP3",e[e.DRAGGINGP4=6]="DRAGGINGP4"}(N||(N={}));class O extends a{_paneViews=[];_options;_points=[];_state=N.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(e){super(),this._options={...L,...e}}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}applyOptions(e){this._options={...this._options,...e},this.requestUpdate()}updatePoints(...e){for(let t=0;ti.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,O._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverDrawing(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),O.hoveredObject=O.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),O.hoveredObject===this&&(O.hoveredObject=null)}}static _eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}static _getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_handleMouseDownInteraction=()=>{O._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{O._mouseIsDown=!1,this._moveToState(N.HOVERING)};_handleDragInteraction(e){if(this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1&&this._state!=N.DRAGGINGP2&&this._state!=N.DRAGGINGP3&&this._state!=N.DRAGGINGP4)return;const t=O._eventToPoint(e,this.series);if(!t)return;this._startDragPoint=this._startDragPoint||t;const i=O._getDiff(t,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=t}}class V extends O{_paneViews=[];_hovered=!1;linkedObjects=[];constructor(e,t,i){super(),this.points.push(e),this.points.push(t),this._options={...L,...i}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}_mouseIsOverObjects(e){for(const t of this.linkedObjects)for(const i in t){if(i.includes("mouseIsOver")&&"function"==typeof t[i]&&t[i](e))return!0;if(i.includes("_hovered")&&"function"==typeof t[i]&&t[i]())return!0}return!1}_mouseIsOverDrawing(e){const t=this._mouseIsOverTwoPointDrawing(e),i=this._mouseIsOverObjects(e),s=t||i;return console.debug("Mouse over check",{selfResult:t,objectsResult:i,finalResult:s}),s}detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}get p1(){return this.points[0]}get p2(){return this.points[1]}get hovered(){return this._hovered}}class R extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s){super(),this.points.push(e),this.points.push(t),this.points.push(i),this._options={...L,...s}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get hovered(){return this._hovered}}class B extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s,n){super(),this.points.push(e),this.points.push(t),this.points.push(i),this.points.push(s),this._options={...L,...n}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}setFourthPoint(e){this.updatePoints(null,null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get p4(){return this.points[3]}get hovered(){return this._hovered}}class F{_chart;_series;_finishDrawingCallback=null;_drawings=[];_activeDrawing=null;_isDrawing=!1;_drawingType=null;_tempStartPoint=null;_tempSecondPoint=null;_clickCount=0;constructor(e,t,i=null){this._chart=e,this._series=t,this._finishDrawingCallback=i,this._chart.subscribeClick(this._clickHandler),this._chart.subscribeCrosshairMove(this._moveHandler)}_clickHandler=e=>this._onClick(e);_moveHandler=e=>this._onMouseMove(e);beginDrawing(e){this._drawingType=e,this._isDrawing=!0,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}stopDrawing(){this._isDrawing=!1,this._activeDrawing=null,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}get drawings(){return this._drawings}addNewDrawing(e){this._series.attachPrimitive(e),this._drawings.push(e)}delete(e){if(null==e)return;const t=this._drawings.indexOf(e);-1!=t&&(this._drawings.splice(t,1),e.detach())}clearDrawings(){for(const e of this._drawings)e.detach();this._drawings=[]}repositionOnTime(){for(const e of this.drawings){const t=[];for(const i of e.points){if(!i){t.push(i);continue}const e=i.time?this._chart.timeScale().coordinateToLogical(this._chart.timeScale().timeToCoordinate(i.time)||0):i.logical;t.push({time:i.time,logical:e,price:i.price})}e.updatePoints(...t)}}_onClick(e){if(!this._isDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;let i;if(this._drawingType)if(i=this._drawingType.prototype instanceof B?4:this._drawingType.prototype instanceof R?3:(this._drawingType.prototype,2),3===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=2,void(this._tempStartPoint=null));2===this._clickCount&&(this._activeDrawing.setThirdPoint(t),this._clickCount=3,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else if(4===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):null==this._tempSecondPoint?(this._tempSecondPoint=t,void(this._clickCount=2)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,this._tempSecondPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=3,this._tempStartPoint=null,void(this._tempSecondPoint=null));3===this._clickCount&&(this._activeDrawing.setFourthPoint(t),this._clickCount=4,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else null==this._activeDrawing?(this._activeDrawing=new this._drawingType(t,t),this._series.attachPrimitive(this._activeDrawing),this._clickCount=1):(this._activeDrawing.setSecondPoint(t),this._clickCount=2,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}_onMouseMove(e){if(!e)return;for(const t of this._drawings)t._handleHoverInteraction(e);if(!this._isDrawing||!this._activeDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;const i=this._drawingType&&this._drawingType.prototype instanceof R;this._drawingType&&this._drawingType.prototype instanceof B?2===this._clickCount?this._activeDrawing.updatePoints(null,null,t,null):3===this._clickCount&&this._activeDrawing.updatePoints(null,null,null,t):i?2===this._clickCount&&this._activeDrawing.updatePoints(null,null,t):this._activeDrawing.setSecondPoint(t)}}class ${_options;constructor(e){this._options=e}}class G extends ${_p1;_p2;_hovered;constructor(e,t,i,s){super(i),this._p1=e,this._p2=t,this._hovered=s}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}class j extends ${_p1;_p2;_p3;_hovered;constructor(e,t,i,s,n){super(s),this._p1=e,this._p2=t,this._p3=i,this._hovered=n}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio),x3:Math.round(this._p3.x*e.horizontalPixelRatio),y3:Math.round(this._p3.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){e.context.fillStyle="#000",e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}function U(e,i){const s={[t.LineStyle.Solid]:[],[t.LineStyle.Dotted]:[e.lineWidth,e.lineWidth],[t.LineStyle.Dashed]:[2*e.lineWidth,2*e.lineWidth],[t.LineStyle.LargeDashed]:[6*e.lineWidth,6*e.lineWidth],[t.LineStyle.SparseDotted]:[e.lineWidth,4*e.lineWidth]}[i];e.setLineDash(s)}class z extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y)return;const t=e.context,i=this._getScaledCoordinates(e);i&&(t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.stroke(),this._hovered&&(this._drawEndCircle(e,i.x1,i.y1),this._drawEndCircle(e,i.x2,i.y2)))}))}}class H{_source;constructor(e){this._source=e}}class W extends H{_p1={x:null,y:null};_p2={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=this._getX(this._source.p1),n=this._getX(this._source.p2);this._p1={x:s,y:t},this._p2={x:n,y:i}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class q extends H{_p1={x:null,y:null};_p2={x:null,y:null};_p3={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2||!this._source.p3)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=e.priceToCoordinate(this._source.p3.price),n=this._getX(this._source.p1),o=this._getX(this._source.p2),r=this._getX(this._source.p3);this._p1={x:n,y:t},this._p2={x:o,y:i},this._p3={x:r,y:s}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class X extends W{constructor(e){super(e)}renderer(){return new z(this._p1,this._p2,this._source._options,this._source.hovered)}}class J extends V{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new X(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<10&&Math.abs(e.y-t.y)<10?this._moveToState(N.DRAGGINGP1):Math.abs(e.x-i.x)<10&&Math.abs(e.y-i.y)<10?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this._paneViews[0]._p1.x,s=this._paneViews[0]._p1.y,n=this._paneViews[0]._p2.x,o=this._paneViews[0]._p2.y;if(!(i&&n&&s&&o))return!1;const r=e.point.x,a=e.point.y;if(r<=Math.min(i,n)-t||r>=Math.max(i,n)+t)return!1;return Math.abs((o-s)*r-(n-i)*a+n*s-o*i)/Math.sqrt((o-s)**2+(n-i)**2)<=t}}class Y extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}}class K extends W{constructor(e){super(e)}renderer(){return new Y(this._p1,this._p2,this._source._options,this._source.hovered)}}const Q={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...L};class Z extends V{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...Q,...i},this._paneViews=[new K(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a{if(null==this._point.y)return;const t=e.context,i=Math.round(this._point.y*e.verticalPixelRatio),s=this._point.x?this._point.x*e.horizontalPixelRatio:0;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(s,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class te extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;"RayLine"==this._source._type&&(this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new ee(this._point,this._source._options)}}class ie{_source;_y=null;_price=null;constructor(e){this._source=e}update(){if(!this._source.series||!this._source._point)return;this._y=this._source.series.priceToCoordinate(this._source._point.price);const e=this._source.series.options().priceFormat.precision;this._price=this._source._point.price.toFixed(e).toString()}visible(){return!0}tickVisible(){return!0}coordinate(){return this._y??0}text(){return this._source._options.text||this._price||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class se extends O{_type="HorizontalLine";_paneViews;_point;_callbackName;_priceAxisViews;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._point.time=null,this._paneViews=[new te(this)],this._priceAxisViews=[new ie(this)],this._callbackName=i}get points(){return[this._point]}updatePoints(...e){for(const t of e)t&&(this._point.price=t.price);this.requestUpdate()}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._priceAxisViews.forEach((e=>e.update()))}priceAxisViews(){return this._priceAxisViews}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,0,e.price),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price);return!!i&&Math.abs(i-e.point.y){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ne extends se{_type="RayLine";constructor(e,t){super({...e},t),this._point.time=e.time}updatePoints(...e){for(const t of e)t&&(this._point=t);this.requestUpdate()}_onDrag(e){this._addDiffToPoint(this._point,e.logical,e.price),this.requestUpdate()}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price),s=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!s)&&(Math.abs(i-e.point.y)s-t)}}class oe extends ${_point={x:null,y:null};constructor(e,t){super(t),this._point=e}draw(e){e.useBitmapCoordinateSpace((e=>{if(null==this._point.x)return;const t=e.context,i=this._point.x*e.horizontalPixelRatio;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class re extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new oe(this._point,this._source._options)}}class ae{_source;_x=null;constructor(e){this._source=e}update(){if(!this._source.chart||!this._source._point)return;const e=this._source._point,t=this._source.chart.timeScale();this._x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)}visible(){return!!this._source._options.text}tickVisible(){return!0}coordinate(){return this._x??0}text(){return this._source._options.text||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class le extends O{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new re(this)],this._callbackName=i,this._timeAxisViews=[new ae(this)]}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._timeAxisViews.forEach((e=>e.update()))}timeAxisViews(){return this._timeAxisViews}updatePoints(...e){for(const t of e)t&&(!t.time&&t.logical&&(t.time=this.series.dataByIndex(t.logical)?.time||null),this._point=t);this.requestUpdate()}get points(){return[this._point]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,e.logical,0),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.chart.timeScale();let s;return s=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!s&&Math.abs(s-e.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ce extends j{options;variant;width;constructor(e,t,i,s,n,o){super(e,t,i,s,n),this.options=s,this.variant=s.variant??"standard",this.width=o}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y)return;const i=e.context,s=this._getScaledCoordinates(e);if(!s)return;const{x1:n,y1:o,x2:r,y2:a,x3:l,y3:c}=s,h=(r+l)/2,p=(a+c)/2;let d,u,m,g,f,y;const b=this.width-Math.max(this._p1.x,this._p2.x);if("inside"===this.variant){d=h,u=p;const e=(n+r)/2-l,t=(o+a)/2-c;let i=Math.atan2(t,e);Math.cos(i)<0&&(i+=Math.PI),m=d+b*Math.cos(i),g=u+b*Math.sin(i)}else{const{anchorX:e,anchorY:t}=this._computeAnchorPoint(this.variant,n,o,r,a),i=this._lineIntersection(n,o,r,a,h,p,e,t);i?[d,u]=i:(d=n,u=o);const s=h-d;m=d+b,g=u+(Math.abs(s)>1e-9?(p-u)/s:0)*b}if(f=m-d,y=g-u,i.lineWidth=this.options.width,i.strokeStyle=this.options.lineColor,U(i,this.options.lineStyle),U(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(r,a),i.lineTo(l,c),i.stroke(),U(i,this.options.lineStyle),i.beginPath(),i.moveTo(n,o),i.lineTo(r,a),i.stroke(),i.beginPath(),i.moveTo(d,u),i.lineTo(m,g),i.stroke(),i.beginPath(),i.moveTo(r,a),i.lineTo(r+f,a+y),i.stroke(),i.beginPath(),i.moveTo(l,c),i.lineTo(l+f,c+y),i.stroke(),this.options.forkLines&&this.options.forkLines.length>0){const e=this.options.forkLines;for(let t=0;tMath.max(i,n,r)+t)return!1;const h=this._distanceFromSegment(i,s,n,o,l,c),p=this._distanceFromSegment(n,o,r,a,l,c),d=this._distanceFromSegment(i,s,r,a,l,c);return h<=t||p<=t||d<=t}_distanceFromSegment(e,t,i,s,n,o){const r=i-e,a=s-t,l=r*r+a*a;let c,h,p=0!==l?((n-e)*r+(o-t)*a)/l:-1;p<0?(c=e,h=t):p>1?(c=i,h=s):(c=e+p*r,h=t+p*a);const d=n-c,u=o-h;return Math.sqrt(d*d+u*u)}fromJSON(e){if(e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}}toJSON(){return{options:this._options}}title="PitchFork"}class ue extends G{series;chart;constructor(e,t,i,s,n,o){super(i,s,n,o),this.series=e,this.chart=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);if(t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._p1&&this._p2&&void 0!==this._p1.y&&void 0!==this._p2.y&&void 0!==this._p1.x&&void 0!==this._p2.x){const e=this.series.coordinateToPrice(this._p1.y),i=this.series.coordinateToPrice(this._p2.y),a=this.chart.timeScale().coordinateToTime(this._p1.x),l=this.chart.timeScale().coordinateToTime(this._p2.x),c=(i-e)/e*100;console.log(e),console.log(i);const h=`Price: ${c.toFixed(2)}%`,p=Math.abs(l-a),d=`Time: ${this._formatTimeDifference(p)}`;t.font="12px Arial",t.fillStyle="white",t.textAlign="center",t.textBaseline="middle";const u=s+o/2,m=n-10,g=n+r+10;t.fillText(h,u,m),t.fillText(d,u,g)}this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}_formatTimeDifference(e){const t=Math.floor(e),i=Math.floor(t/60),s=Math.floor(i/60),n=Math.floor(s/24);return n>0?`${n}d ${s%24}h`:s>0?`${s}h ${i%60}m`:i>0?`${i}m ${t%60}s`:`${t}s`}}class me extends W{constructor(e){super(e)}renderer(){return new ue(this._source._series,this._source._chart,this._p1,this._p2,this._source._options,this._source.hovered)}}const ge={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.0)",lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:1};class fe extends V{_type="Measure";constructor(e,t,i){super(e,t,i),this._options={...ge,...i},this._paneViews=[new me(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a',horz:'',ray:'',box:'',vert:'',pitch:'',measure:''};div;activeIcon=null;buttons=[];_commandFunctions;_handlerID;_drawingTool;constructor(e,t,i,s,n=!0){this.handler=e,this._handlerID=this.handler.id,this._commandFunctions=s,this._drawingTool=new F(t,i,(()=>this.removeActiveAndSave())),s.push((e=>{if((e.metaKey||e.ctrlKey)&&"KeyZ"===e.code){const e=this._drawingTool.drawings.pop();return e&&this._drawingTool.delete(e),!0}return!1}));const o=n?"toggle":"static";this.div=this._createToolBox(e,o),e.ContextMenu.setupDrawingTools(this.saveDrawings,this._drawingTool),s.push((e=>{if(this.handler.id!==window.handlerInFocus)return!1;if(e.altKey)for(const[t,i]of Object.keys(ye.ICONS).entries()){const i=["M","T","H","R","B","V","P"][t];if(e.code===`Key${i}`)return e.preventDefault(),this.buttons[t].click(),!0}return!1}))}_createToolBox(e,t){return"toggle"===t?this._makeToggleToolBox():this._makeToolBox()}_makeToolBox(){const e=document.createElement("div");return e.classList.add("toolbox"),this._registerIcon(e,"measure"),this._registerIcon(e,"trend"),this._registerIcon(e,"horz"),this._registerIcon(e,"ray"),this._registerIcon(e,"box"),this._registerIcon(e,"vert",!0),this._registerIcon(e,"pitch"),e}_makeToggleToolBox(){const e=document.createElement("div");e.classList.add("flyout-toolbox"),Object.assign(e.style,{position:"absolute",top:"0",left:"50%",transform:"translateX(-50%)",overflow:"hidden",transition:"height 0.3s ease",zIndex:"1000"});const t=document.createElement("div");t.classList.add("toolbox-content"),Object.assign(t.style,{display:"none",inlineFlex:"row",padding:"5px",backgroundColor:"rgba(0,0,0,0.5)"}),this._registerIcon(t,"measure"),this._registerIcon(t,"trend"),this._registerIcon(t,"horz"),this._registerIcon(t,"ray"),this._registerIcon(t,"box"),this._registerIcon(t,"vert",!0),this._registerIcon(t,"pitch"),e.appendChild(t);const i=document.createElement("div");i.textContent="▼",Object.assign(i.style,{width:"15px",height:"15px",textAlign:"center",lineHeight:"15px",cursor:"pointer",color:"#fff",background:"transparent"});let s=!1;return e.style.height="15px",i.onclick=()=>{if(s=!s,s){t.style.display="inline-flex";const s=t.scrollHeight;e.style.height=`${s+15}px`,i.textContent="▲"}else t.style.display="none",e.style.height="15px",i.textContent="▼"},e.appendChild(i),e}static TOOL_CLASSES={measure:fe,trend:J,horz:se,ray:ne,box:Z,vert:le,pitch:de};_registerIcon(e,t,i=!1){const s="http://www.w3.org/2000/svg",n=document.createElement("div");n.classList.add("toolbox-button");const o=document.createElementNS(s,"svg");o.setAttribute("width","28"),o.setAttribute("height","28"),o.setAttribute("viewBox","0 0 28 28");const r=document.createElementNS(s,"g");r.innerHTML=ye.ICONS[t],o.appendChild(r),i&&(o.style.transform="rotate(90deg)",o.style.transformBox="fill-box",o.style.transformOrigin="center"),n.appendChild(o),e.appendChild(n);const a={div:n,group:r,type:ye.TOOL_CLASSES[t]};n.addEventListener("click",(()=>this._onIconClick(a))),this.buttons.push(n)}_onIconClick(e){if(this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this._drawingTool.stopDrawing(),this.activeIcon===e))return this.activeIcon=null,void window.setCursor("default");this.activeIcon=e,e.div.classList.add("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool.beginDrawing(e.type)}removeActiveAndSave(){window.setCursor("default"),this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this.activeIcon=null),this.saveDrawings()}addNewDrawing(e){this._drawingTool.addNewDrawing(e)}clearDrawings(){this._drawingTool.clearDrawings()}saveDrawings=()=>{const e=[];for(const t of this._drawingTool.drawings)e.push({type:t._type,points:t.points,options:t._options});const t=JSON.stringify(e);window.callbackFunction(`save_drawings${this._handlerID}_~_${t}`)};loadDrawings(e){e.forEach((e=>{switch(e.type){case"Box":this._drawingTool.addNewDrawing(new Z(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new J(e.points[0],e.points[1],e.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new se(e.points[0],e.options));break;case"RayLine":this._drawingTool.addNewDrawing(new ne(e.points[0],e.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new le(e.points[0],e.options));break;case"PitchFork":this._drawingTool.addNewDrawing(new de(e.points[0],e.points[1],e.points[2],e.options));break;case"Measure":this._drawingTool.addNewDrawing(new fe(e.points[0],e.points[1],e.options))}}))}}var be=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],ve=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],xe="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ꟑꟑꟓꟕ-ꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",_e={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},we="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",Ce={5:we,"5module":we+" export import",6:we+" const class extends export import super"},Se=/^in(stanceof)?$/,ke=new RegExp("["+xe+"]"),Ee=new RegExp("["+xe+"·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・]");function Me(e,t){for(var i=65536,s=0;se)return!1;if((i+=t[s+1])>=e)return!0}return!1}function Pe(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&ke.test(String.fromCharCode(e)):!1!==t&&Me(e,ve)))}function Te(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Ee.test(String.fromCharCode(e)):!1!==t&&(Me(e,ve)||Me(e,be)))))}var Ie=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function Ae(e,t){return new Ie(e,{beforeExpr:!0,binop:t})}var De={beforeExpr:!0},Le={startsExpr:!0},Ne={};function Oe(e,t){return void 0===t&&(t={}),t.keyword=e,Ne[e]=new Ie(e,t)}var Ve={num:new Ie("num",Le),regexp:new Ie("regexp",Le),string:new Ie("string",Le),name:new Ie("name",Le),privateId:new Ie("privateId",Le),eof:new Ie("eof"),bracketL:new Ie("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Ie("]"),braceL:new Ie("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Ie("}"),parenL:new Ie("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Ie(")"),comma:new Ie(",",De),semi:new Ie(";",De),colon:new Ie(":",De),dot:new Ie("."),question:new Ie("?",De),questionDot:new Ie("?."),arrow:new Ie("=>",De),template:new Ie("template"),invalidTemplate:new Ie("invalidTemplate"),ellipsis:new Ie("...",De),backQuote:new Ie("`",Le),dollarBraceL:new Ie("${",{beforeExpr:!0,startsExpr:!0}),eq:new Ie("=",{beforeExpr:!0,isAssign:!0}),assign:new Ie("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Ie("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Ie("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:Ae("||",1),logicalAND:Ae("&&",2),bitwiseOR:Ae("|",3),bitwiseXOR:Ae("^",4),bitwiseAND:Ae("&",5),equality:Ae("==/!=/===/!==",6),relational:Ae(">/<=/>=",7),bitShift:Ae("<>>/>>>",8),plusMin:new Ie("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:Ae("%",10),star:Ae("*",10),slash:Ae("/",10),starstar:new Ie("**",{beforeExpr:!0}),coalesce:Ae("??",1),_break:Oe("break"),_case:Oe("case",De),_catch:Oe("catch"),_continue:Oe("continue"),_debugger:Oe("debugger"),_default:Oe("default",De),_do:Oe("do",{isLoop:!0,beforeExpr:!0}),_else:Oe("else",De),_finally:Oe("finally"),_for:Oe("for",{isLoop:!0}),_function:Oe("function",Le),_if:Oe("if"),_return:Oe("return",De),_switch:Oe("switch"),_throw:Oe("throw",De),_try:Oe("try"),_var:Oe("var"),_const:Oe("const"),_while:Oe("while",{isLoop:!0}),_with:Oe("with"),_new:Oe("new",{beforeExpr:!0,startsExpr:!0}),_this:Oe("this",Le),_super:Oe("super",Le),_class:Oe("class",Le),_extends:Oe("extends",De),_export:Oe("export"),_import:Oe("import",Le),_null:Oe("null",Le),_true:Oe("true",Le),_false:Oe("false",Le),_in:Oe("in",{beforeExpr:!0,binop:7}),_instanceof:Oe("instanceof",{beforeExpr:!0,binop:7}),_typeof:Oe("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Oe("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Oe("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Re=/\r\n?|\n|\u2028|\u2029/,Be=new RegExp(Re.source,"g");function Fe(e){return 10===e||13===e||8232===e||8233===e}function $e(e,t,i){void 0===i&&(i=e.length);for(var s=t;s>10),56320+(1023&e)))}var Ke=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Qe=function(e,t){this.line=e,this.column=t};Qe.prototype.offset=function(e){return new Qe(this.line,this.column+e)};var Ze=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function et(e,t){for(var i=1,s=0;;){var n=$e(e,s,t);if(n<0)return new Qe(i,t-s);++i,s=n}}var tt={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},it=!1;function st(e){var t={};for(var i in tt)t[i]=e&&We(e,i)?e[i]:tt[i];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!it&&"object"==typeof console&&console.warn&&(it=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),qe(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}return qe(t.onComment)&&(t.onComment=function(e,t){return function(i,s,n,o,r,a){var l={type:i?"Block":"Line",value:s,start:n,end:o};e.locations&&(l.loc=new Ze(this,r,a)),e.ranges&&(l.range=[n,o]),t.push(l)}}(t,t.onComment)),t}var nt=256;function ot(e,t){return 2|(e?4:0)|(t?8:0)}var rt=function(e,t,i){this.options=e=st(e),this.sourceFile=e.sourceFile,this.keywords=Je(Ce[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var s="";!0!==e.allowReserved&&(s=_e[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(s+=" await")),this.reservedWords=Je(s);var n=(s?s+" ":"")+_e.strict;this.reservedWordsStrict=Je(n),this.reservedWordsStrictBind=Je(n+" "+_e.strictBind),this.input=String(t),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf("\n",i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Re).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=Ve.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},at={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};rt.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},at.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},at.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},at.inAsync.get=function(){return(4&this.currentVarScope().flags)>0&&!this.currentVarScope().inClassFieldInit},at.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&nt)return!1;if(2&t.flags)return(4&t.flags)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},at.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(64&t)>0||i||this.options.allowSuperOutsideMethod},at.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},at.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},at.allowNewDotTarget.get=function(){var e=this.currentThisScope(),t=e.flags,i=e.inClassFieldInit;return(258&t)>0||i},at.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&nt)>0},rt.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var i=this,s=0;s=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(s+1))}e+=t[0].length,je.lastIndex=e,e+=je.exec(this.input)[0].length,";"===this.input[e]&&e++}},lt.eat=function(e){return this.type===e&&(this.next(),!0)},lt.isContextual=function(e){return this.type===Ve.name&&this.value===e&&!this.containsEsc},lt.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},lt.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},lt.canInsertSemicolon=function(){return this.type===Ve.eof||this.type===Ve.braceR||Re.test(this.input.slice(this.lastTokEnd,this.start))},lt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},lt.semicolon=function(){this.eat(Ve.semi)||this.insertSemicolon()||this.unexpected()},lt.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},lt.expect=function(e){this.eat(e)||this.unexpected()},lt.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var ht=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};lt.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var i=t?e.parenthesizedAssign:e.parenthesizedBind;i>-1&&this.raiseRecoverable(i,t?"Assigning to rvalue":"Parenthesized pattern")}},lt.checkExpressionErrors=function(e,t){if(!e)return!1;var i=e.shorthandAssign,s=e.doubleProto;if(!t)return i>=0||s>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),s>=0&&this.raiseRecoverable(s,"Redefinition of __proto__ property")},lt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320)return!0;if(Pe(s,!0)){for(var n=i+1;Te(s=this.input.charCodeAt(n),!0);)++n;if(92===s||s>55295&&s<56320)return!0;var o=this.input.slice(i,n);if(!Se.test(o))return!0}return!1},pt.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;je.lastIndex=this.pos;var e,t=je.exec(this.input),i=this.pos+t[0].length;return!(Re.test(this.input.slice(this.pos,i))||"function"!==this.input.slice(i,i+8)||i+8!==this.input.length&&(Te(e=this.input.charCodeAt(i+8))||e>55295&&e<56320))},pt.parseStatement=function(e,t,i){var s,n=this.type,o=this.startNode();switch(this.isLet(e)&&(n=Ve._var,s="let"),n){case Ve._break:case Ve._continue:return this.parseBreakContinueStatement(o,n.keyword);case Ve._debugger:return this.parseDebuggerStatement(o);case Ve._do:return this.parseDoStatement(o);case Ve._for:return this.parseForStatement(o);case Ve._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(o,!1,!e);case Ve._class:return e&&this.unexpected(),this.parseClass(o,!0);case Ve._if:return this.parseIfStatement(o);case Ve._return:return this.parseReturnStatement(o);case Ve._switch:return this.parseSwitchStatement(o);case Ve._throw:return this.parseThrowStatement(o);case Ve._try:return this.parseTryStatement(o);case Ve._const:case Ve._var:return s=s||this.value,e&&"var"!==s&&this.unexpected(),this.parseVarStatement(o,s);case Ve._while:return this.parseWhileStatement(o);case Ve._with:return this.parseWithStatement(o);case Ve.braceL:return this.parseBlock(!0,o);case Ve.semi:return this.parseEmptyStatement(o);case Ve._export:case Ve._import:if(this.options.ecmaVersion>10&&n===Ve._import){je.lastIndex=this.pos;var r=je.exec(this.input),a=this.pos+r[0].length,l=this.input.charCodeAt(a);if(40===l||46===l)return this.parseExpressionStatement(o,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===Ve._import?this.parseImport(o):this.parseExport(o,i);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(o,!0,!e);var c=this.value,h=this.parseExpression();return n===Ve.name&&"Identifier"===h.type&&this.eat(Ve.colon)?this.parseLabeledStatement(o,c,h,e):this.parseExpressionStatement(o,h)}},pt.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(Ve.semi)||this.insertSemicolon()?e.label=null:this.type!==Ve.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var s=0;s=6?this.eat(Ve.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},pt.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(dt),this.enterScope(0),this.expect(Ve.parenL),this.type===Ve.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===Ve._var||this.type===Ve._const||i){var s=this.startNode(),n=i?"let":this.value;return this.next(),this.parseVar(s,!0,n),this.finishNode(s,"VariableDeclaration"),(this.type===Ve._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===s.declarations.length?(this.options.ecmaVersion>=9&&(this.type===Ve._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,s)):(t>-1&&this.unexpected(t),this.parseFor(e,s))}var o=this.isContextual("let"),r=!1,a=this.containsEsc,l=new ht,c=this.start,h=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===Ve._in||(r=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===Ve._in&&this.unexpected(t),e.await=!0):r&&this.options.ecmaVersion>=8&&(h.start!==c||a||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),o&&r&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,l),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},pt.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,gt|(i?0:ft),!1,t)},pt.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(Ve._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},pt.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(Ve.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},pt.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(Ve.braceL),this.labels.push(ut),this.enterScope(0);for(var i=!1;this.type!==Ve.braceR;)if(this.type===Ve._case||this.type===Ve._default){var s=this.type===Ve._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),s?t.test=this.parseExpression():(i&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),i=!0,t.test=null),this.expect(Ve.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},pt.parseThrowStatement=function(e){return this.next(),Re.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var mt=[];pt.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(Ve.parenR),e},pt.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===Ve._catch){var t=this.startNode();this.next(),this.eat(Ve.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(Ve._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},pt.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},pt.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(dt),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},pt.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},pt.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},pt.parseLabeledStatement=function(e,t,i,s){for(var n=0,o=this.labels;n=0;a--){var l=this.labels[a];if(l.statementStart!==e.start)break;l.statementStart=this.start,l.kind=r}return this.labels.push({name:t,kind:r,statementStart:this.start}),e.body=this.parseStatement(s?-1===s.indexOf("label")?s+"label":s:"label"),this.labels.pop(),e.label=i,this.finishNode(e,"LabeledStatement")},pt.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},pt.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(Ve.braceL),e&&this.enterScope(0);this.type!==Ve.braceR;){var s=this.parseStatement(null);t.body.push(s)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},pt.parseFor=function(e,t){return e.init=t,this.expect(Ve.semi),e.test=this.type===Ve.semi?null:this.parseExpression(),this.expect(Ve.semi),e.update=this.type===Ve.parenR?null:this.parseExpression(),this.expect(Ve.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},pt.parseForIn=function(e,t){var i=this.type===Ve._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!i||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(Ve.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},pt.parseVar=function(e,t,i,s){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(Ve.eq)?n.init=this.parseMaybeAssign(t):s||"const"!==i||this.type===Ve._in||this.options.ecmaVersion>=6&&this.isContextual("of")?s||"Identifier"===n.id.type||t&&(this.type===Ve._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(Ve.comma))break}return e},pt.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var gt=1,ft=2;function yt(e,t){var i=t.key.name,s=e[i],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===s&&"iset"===n||"iset"===s&&"iget"===n||"sget"===s&&"sset"===n||"sset"===s&&"sget"===n?(e[i]="true",!1):!!s||(e[i]=n,!1)}function bt(e,t){var i=e.computed,s=e.key;return!i&&("Identifier"===s.type&&s.name===t||"Literal"===s.type&&s.value===t)}pt.parseFunction=function(e,t,i,s,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(this.type===Ve.star&&t&ft&&this.unexpected(),e.generator=this.eat(Ve.star)),this.options.ecmaVersion>=8&&(e.async=!!s),t>&&(e.id=4&t&&this.type!==Ve.name?null:this.parseIdent(),!e.id||t&ft||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var o=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(ot(e.async,e.generator)),t>||(e.id=this.type===Ve.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,i,!1,n),this.yieldPos=o,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(e,t>?"FunctionDeclaration":"FunctionExpression")},pt.parseFunctionParams=function(e){this.expect(Ve.parenL),e.params=this.parseBindingList(Ve.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},pt.parseClass=function(e,t){this.next();var i=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var s=this.enterClassBody(),n=this.startNode(),o=!1;for(n.body=[],this.expect(Ve.braceL);this.type!==Ve.braceR;){var r=this.parseClassElement(null!==e.superClass);r&&(n.body.push(r),"MethodDefinition"===r.type&&"constructor"===r.kind?(o&&this.raiseRecoverable(r.start,"Duplicate constructor in the same class"),o=!0):r.key&&"PrivateIdentifier"===r.key.type&&yt(s,r)&&this.raiseRecoverable(r.key.start,"Identifier '#"+r.key.name+"' has already been declared"))}return this.strict=i,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},pt.parseClassElement=function(e){if(this.eat(Ve.semi))return null;var t=this.options.ecmaVersion,i=this.startNode(),s="",n=!1,o=!1,r="method",a=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(Ve.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===Ve.star?a=!0:s="static"}if(i.static=a,!s&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==Ve.star||this.canInsertSemicolon()?s="async":o=!0),!s&&(t>=9||!o)&&this.eat(Ve.star)&&(n=!0),!s&&!o&&!n){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?r=l:s=l)}if(s?(i.computed=!1,i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),i.key.name=s,this.finishNode(i.key,"Identifier")):this.parseClassElementName(i),t<13||this.type===Ve.parenL||"method"!==r||n||o){var c=!i.static&&bt(i,"constructor"),h=c&&e;c&&"method"!==r&&this.raise(i.key.start,"Constructor can't have get/set modifier"),i.kind=c?"constructor":r,this.parseClassMethod(i,n,o,h)}else this.parseClassField(i);return i},pt.isClassElementNameStart=function(){return this.type===Ve.name||this.type===Ve.privateId||this.type===Ve.num||this.type===Ve.string||this.type===Ve.bracketL||this.type.keyword},pt.parseClassElementName=function(e){this.type===Ve.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},pt.parseClassMethod=function(e,t,i,s){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method")):e.static&&bt(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var o=e.value=this.parseMethod(t,i,s);return"get"===e.kind&&0!==o.params.length&&this.raiseRecoverable(o.start,"getter should have no params"),"set"===e.kind&&1!==o.params.length&&this.raiseRecoverable(o.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===o.params[0].type&&this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},pt.parseClassField=function(e){if(bt(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&bt(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(Ve.eq)){var t=this.currentThisScope(),i=t.inClassFieldInit;t.inClassFieldInit=!0,e.value=this.parseMaybeAssign(),t.inClassFieldInit=i}else e.value=null;return this.semicolon(),this.finishNode(e,"PropertyDefinition")},pt.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==Ve.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},pt.parseClassId=function(e,t){this.type===Ve.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},pt.parseClassSuper=function(e){e.superClass=this.eat(Ve._extends)?this.parseExprSubscripts(null,!1):null},pt.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},pt.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,i=e.used;if(this.options.checkPrivateFields)for(var s=this.privateNameStack.length,n=0===s?null:this.privateNameStack[s-1],o=0;o=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==Ve.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},pt.parseExport=function(e,t){if(this.next(),this.eat(Ve.star))return this.parseExportAllDeclaration(e,t);if(this.eat(Ve._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==Ve.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var i=0,s=e.specifiers;i=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},pt.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},pt.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},pt.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},pt.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===Ve.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(Ve.comma)))return e;if(this.type===Ve.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(Ve.braceL);!this.eat(Ve.braceR);){if(t)t=!1;else if(this.expect(Ve.comma),this.afterTrailingComma(Ve.braceR))break;e.push(this.parseImportSpecifier())}return e},pt.parseWithClause=function(){var e=[];if(!this.eat(Ve._with))return e;this.expect(Ve.braceL);for(var t={},i=!0;!this.eat(Ve.braceR);){if(i)i=!1;else if(this.expect(Ve.comma),this.afterTrailingComma(Ve.braceR))break;var s=this.parseImportAttribute(),n="Identifier"===s.key.type?s.key.name:s.key.value;We(t,n)&&this.raiseRecoverable(s.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(s)}return e},pt.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===Ve.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(Ve.colon),this.type!==Ve.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},pt.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===Ve.string){var e=this.parseLiteral(this.value);return Ke.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},pt.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var vt=rt.prototype;vt.toAssignable=function(e,t,i){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var s=0,n=e.properties;s=6)switch(this.type){case Ve.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(Ve.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case Ve.braceL:return this.parseObj(!0)}return this.parseIdent()},vt.parseBindingList=function(e,t,i,s){for(var n=[],o=!0;!this.eat(e);)if(o?o=!1:this.expect(Ve.comma),t&&this.type===Ve.comma)n.push(null);else{if(i&&this.afterTrailingComma(e))break;if(this.type===Ve.ellipsis){var r=this.parseRestBinding();this.parseBindingListItem(r),n.push(r),this.type===Ve.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(e);break}n.push(this.parseAssignableListItem(s))}return n},vt.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},vt.parseBindingListItem=function(e){return e},vt.parseMaybeDefault=function(e,t,i){if(i=i||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(Ve.eq))return i;var s=this.startNodeAt(e,t);return s.left=i,s.right=this.parseMaybeAssign(),this.finishNode(s,"AssignmentPattern")},vt.checkLValSimple=function(e,t,i){void 0===t&&(t=0);var s=0!==t;switch(e.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(s?"Binding ":"Assigning to ")+e.name+" in strict mode"),s&&(2===t&&"let"===e.name&&this.raiseRecoverable(e.start,"let is disallowed as a lexically bound name"),i&&(We(i,e.name)&&this.raiseRecoverable(e.start,"Argument name clash"),i[e.name]=!0),5!==t&&this.declareName(e.name,t,e.start));break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":s&&this.raiseRecoverable(e.start,"Binding member expression");break;case"ParenthesizedExpression":return s&&this.raiseRecoverable(e.start,"Binding parenthesized expression"),this.checkLValSimple(e.expression,t,i);default:this.raise(e.start,(s?"Binding":"Assigning to")+" rvalue")}},vt.checkLValPattern=function(e,t,i){switch(void 0===t&&(t=0),e.type){case"ObjectPattern":for(var s=0,n=e.properties;s=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},wt.updateContext=function(e){var t,i=this.type;i.keyword&&e===Ve.dot?this.exprAllowed=!1:(t=i.updateContext)?t.call(this,e):this.exprAllowed=i.beforeExpr},wt.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},Ve.parenR.updateContext=Ve.braceR.updateContext=function(){if(1!==this.context.length){var e=this.context.pop();e===_t.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr}else this.exprAllowed=!0},Ve.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?_t.b_stat:_t.b_expr),this.exprAllowed=!0},Ve.dollarBraceL.updateContext=function(){this.context.push(_t.b_tmpl),this.exprAllowed=!0},Ve.parenL.updateContext=function(e){var t=e===Ve._if||e===Ve._for||e===Ve._with||e===Ve._while;this.context.push(t?_t.p_stat:_t.p_expr),this.exprAllowed=!0},Ve.incDec.updateContext=function(){},Ve._function.updateContext=Ve._class.updateContext=function(e){!e.beforeExpr||e===Ve._else||e===Ve.semi&&this.curContext()!==_t.p_stat||e===Ve._return&&Re.test(this.input.slice(this.lastTokEnd,this.start))||(e===Ve.colon||e===Ve.braceL)&&this.curContext()===_t.b_stat?this.context.push(_t.f_stat):this.context.push(_t.f_expr),this.exprAllowed=!1},Ve.colon.updateContext=function(){"function"===this.curContext().token&&this.context.pop(),this.exprAllowed=!0},Ve.backQuote.updateContext=function(){this.curContext()===_t.q_tmpl?this.context.pop():this.context.push(_t.q_tmpl),this.exprAllowed=!1},Ve.star.updateContext=function(e){if(e===Ve._function){var t=this.context.length-1;this.context[t]===_t.f_expr?this.context[t]=_t.f_expr_gen:this.context[t]=_t.f_gen}this.exprAllowed=!0},Ve.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==Ve.dot&&("of"===this.value&&!this.exprAllowed||"yield"===this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var Ct=rt.prototype;function St(e){return"Identifier"===e.type||"ParenthesizedExpression"===e.type&&St(e.expression)}function kt(e){return"MemberExpression"===e.type&&"PrivateIdentifier"===e.property.type||"ChainExpression"===e.type&&kt(e.expression)||"ParenthesizedExpression"===e.type&&kt(e.expression)}Ct.checkPropClash=function(e,t,i){if(!(this.options.ecmaVersion>=9&&"SpreadElement"===e.type||this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var s,n=e.key;switch(n.type){case"Identifier":s=n.name;break;case"Literal":s=String(n.value);break;default:return}var o=e.kind;if(this.options.ecmaVersion>=6)"__proto__"===s&&"init"===o&&(t.proto&&(i?i.doubleProto<0&&(i.doubleProto=n.start):this.raiseRecoverable(n.start,"Redefinition of __proto__ property")),t.proto=!0);else{var r=t[s="$"+s];if(r)("init"===o?this.strict&&r.init||r.get||r.set:r.init||r[o])&&this.raiseRecoverable(n.start,"Redefinition of property");else r=t[s]={init:!1,get:!1,set:!1};r[o]=!0}}},Ct.parseExpression=function(e,t){var i=this.start,s=this.startLoc,n=this.parseMaybeAssign(e,t);if(this.type===Ve.comma){var o=this.startNodeAt(i,s);for(o.expressions=[n];this.eat(Ve.comma);)o.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(o,"SequenceExpression")}return n},Ct.parseMaybeAssign=function(e,t,i){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var s=!1,n=-1,o=-1,r=-1;t?(n=t.parenthesizedAssign,o=t.trailingComma,r=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new ht,s=!0);var a=this.start,l=this.startLoc;this.type!==Ve.parenL&&this.type!==Ve.name||(this.potentialArrowAt=this.start,this.potentialArrowInForAwait="await"===e);var c=this.parseMaybeConditional(e,t);if(i&&(c=i.call(this,c,a,l)),this.type.isAssign){var h=this.startNodeAt(a,l);return h.operator=this.value,this.type===Ve.eq&&(c=this.toAssignable(c,!1,t)),s||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=c.start&&(t.shorthandAssign=-1),this.type===Ve.eq?this.checkLValPattern(c):this.checkLValSimple(c),h.left=c,this.next(),h.right=this.parseMaybeAssign(e),r>-1&&(t.doubleProto=r),this.finishNode(h,"AssignmentExpression")}return s&&this.checkExpressionErrors(t,!0),n>-1&&(t.parenthesizedAssign=n),o>-1&&(t.trailingComma=o),c},Ct.parseMaybeConditional=function(e,t){var i=this.start,s=this.startLoc,n=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return n;if(this.eat(Ve.question)){var o=this.startNodeAt(i,s);return o.test=n,o.consequent=this.parseMaybeAssign(),this.expect(Ve.colon),o.alternate=this.parseMaybeAssign(e),this.finishNode(o,"ConditionalExpression")}return n},Ct.parseExprOps=function(e,t){var i=this.start,s=this.startLoc,n=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||n.start===i&&"ArrowFunctionExpression"===n.type?n:this.parseExprOp(n,i,s,-1,e)},Ct.parseExprOp=function(e,t,i,s,n){var o=this.type.binop;if(null!=o&&(!n||this.type!==Ve._in)&&o>s){var r=this.type===Ve.logicalOR||this.type===Ve.logicalAND,a=this.type===Ve.coalesce;a&&(o=Ve.logicalAND.binop);var l=this.value;this.next();var c=this.start,h=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,n),c,h,o,n),d=this.buildBinary(t,i,e,p,l,r||a);return(r&&this.type===Ve.coalesce||a&&(this.type===Ve.logicalOR||this.type===Ve.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(d,t,i,s,n)}return e},Ct.buildBinary=function(e,t,i,s,n,o){"PrivateIdentifier"===s.type&&this.raise(s.start,"Private identifier can only be left side of binary expression");var r=this.startNodeAt(e,t);return r.left=i,r.operator=n,r.right=s,this.finishNode(r,o?"LogicalExpression":"BinaryExpression")},Ct.parseMaybeUnary=function(e,t,i,s){var n,o=this.start,r=this.startLoc;if(this.isContextual("await")&&this.canAwait)n=this.parseAwait(s),t=!0;else if(this.type.prefix){var a=this.startNode(),l=this.type===Ve.incDec;a.operator=this.value,a.prefix=!0,this.next(),a.argument=this.parseMaybeUnary(null,!0,l,s),this.checkExpressionErrors(e,!0),l?this.checkLValSimple(a.argument):this.strict&&"delete"===a.operator&&St(a.argument)?this.raiseRecoverable(a.start,"Deleting local variable in strict mode"):"delete"===a.operator&&kt(a.argument)?this.raiseRecoverable(a.start,"Private fields can not be deleted"):t=!0,n=this.finishNode(a,l?"UpdateExpression":"UnaryExpression")}else if(t||this.type!==Ve.privateId){if(n=this.parseExprSubscripts(e,s),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var c=this.startNodeAt(o,r);c.operator=this.value,c.prefix=!1,c.argument=n,this.checkLValSimple(n),this.next(),n=this.finishNode(c,"UpdateExpression")}}else(s||0===this.privateNameStack.length)&&this.options.checkPrivateFields&&this.unexpected(),n=this.parsePrivateIdent(),this.type!==Ve._in&&this.unexpected();return i||!this.eat(Ve.starstar)?n:t?void this.unexpected(this.lastTokStart):this.buildBinary(o,r,n,this.parseMaybeUnary(null,!1,!1,s),"**",!1)},Ct.parseExprSubscripts=function(e,t){var i=this.start,s=this.startLoc,n=this.parseExprAtom(e,t);if("ArrowFunctionExpression"===n.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd))return n;var o=this.parseSubscripts(n,i,s,!1,t);return e&&"MemberExpression"===o.type&&(e.parenthesizedAssign>=o.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=o.start&&(e.parenthesizedBind=-1),e.trailingComma>=o.start&&(e.trailingComma=-1)),o},Ct.parseSubscripts=function(e,t,i,s,n){for(var o=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.potentialArrowAt===e.start,r=!1;;){var a=this.parseSubscript(e,t,i,s,o,r,n);if(a.optional&&(r=!0),a===e||"ArrowFunctionExpression"===a.type){if(r){var l=this.startNodeAt(t,i);l.expression=a,a=this.finishNode(l,"ChainExpression")}return a}e=a}},Ct.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(Ve.arrow)},Ct.parseSubscriptAsyncArrow=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!0,s)},Ct.parseSubscript=function(e,t,i,s,n,o,r){var a=this.options.ecmaVersion>=11,l=a&&this.eat(Ve.questionDot);s&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var c=this.eat(Ve.bracketL);if(c||l&&this.type!==Ve.parenL&&this.type!==Ve.backQuote||this.eat(Ve.dot)){var h=this.startNodeAt(t,i);h.object=e,c?(h.property=this.parseExpression(),this.expect(Ve.bracketR)):this.type===Ve.privateId&&"Super"!==e.type?h.property=this.parsePrivateIdent():h.property=this.parseIdent("never"!==this.options.allowReserved),h.computed=!!c,a&&(h.optional=l),e=this.finishNode(h,"MemberExpression")}else if(!s&&this.eat(Ve.parenL)){var p=new ht,d=this.yieldPos,u=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var g=this.parseExprList(Ve.parenR,this.options.ecmaVersion>=8,!1,p);if(n&&!l&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=d,this.awaitPos=u,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,i,g,r);this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=u||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var f=this.startNodeAt(t,i);f.callee=e,f.arguments=g,a&&(f.optional=l),e=this.finishNode(f,"CallExpression")}else if(this.type===Ve.backQuote){(l||o)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var y=this.startNodeAt(t,i);y.tag=e,y.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(y,"TaggedTemplateExpression")}return e},Ct.parseExprAtom=function(e,t,i){this.type===Ve.slash&&this.readRegexp();var s,n=this.potentialArrowAt===this.start;switch(this.type){case Ve._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),s=this.startNode(),this.next(),this.type!==Ve.parenL||this.allowDirectSuper||this.raise(s.start,"super() call outside constructor of a subclass"),this.type!==Ve.dot&&this.type!==Ve.bracketL&&this.type!==Ve.parenL&&this.unexpected(),this.finishNode(s,"Super");case Ve._this:return s=this.startNode(),this.next(),this.finishNode(s,"ThisExpression");case Ve.name:var o=this.start,r=this.startLoc,a=this.containsEsc,l=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!a&&"async"===l.name&&!this.canInsertSemicolon()&&this.eat(Ve._function))return this.overrideContext(_t.f_expr),this.parseFunction(this.startNodeAt(o,r),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(Ve.arrow))return this.parseArrowExpression(this.startNodeAt(o,r),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===Ve.name&&!a&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(Ve.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(o,r),[l],!0,t)}return l;case Ve.regexp:var c=this.value;return(s=this.parseLiteral(c.value)).regex={pattern:c.pattern,flags:c.flags},s;case Ve.num:case Ve.string:return this.parseLiteral(this.value);case Ve._null:case Ve._true:case Ve._false:return(s=this.startNode()).value=this.type===Ve._null?null:this.type===Ve._true,s.raw=this.type.keyword,this.next(),this.finishNode(s,"Literal");case Ve.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),p;case Ve.bracketL:return s=this.startNode(),this.next(),s.elements=this.parseExprList(Ve.bracketR,!0,!0,e),this.finishNode(s,"ArrayExpression");case Ve.braceL:return this.overrideContext(_t.b_expr),this.parseObj(!1,e);case Ve._function:return s=this.startNode(),this.next(),this.parseFunction(s,0);case Ve._class:return this.parseClass(this.startNode(),!1);case Ve._new:return this.parseNew();case Ve.backQuote:return this.parseTemplate();case Ve._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},Ct.parseExprAtomDefault=function(){this.unexpected()},Ct.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===Ve.parenL&&!e)return this.parseDynamicImport(t);if(this.type===Ve.dot){var i=this.startNodeAt(t.start,t.loc&&t.loc.start);return i.name="import",t.meta=this.finishNode(i,"Identifier"),this.parseImportMeta(t)}this.unexpected()},Ct.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(Ve.parenR)?e.options=null:(this.expect(Ve.comma),this.afterTrailingComma(Ve.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(Ve.parenR)||(this.expect(Ve.comma),this.afterTrailingComma(Ve.parenR)||this.unexpected())));else if(!this.eat(Ve.parenR)){var t=this.start;this.eat(Ve.comma)&&this.eat(Ve.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},Ct.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},Ct.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},Ct.parseParenExpression=function(){this.expect(Ve.parenL);var e=this.parseExpression();return this.expect(Ve.parenR),e},Ct.shouldParseArrow=function(e){return!this.canInsertSemicolon()},Ct.parseParenAndDistinguishExpression=function(e,t){var i,s=this.start,n=this.startLoc,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var r,a=this.start,l=this.startLoc,c=[],h=!0,p=!1,d=new ht,u=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==Ve.parenR;){if(h?h=!1:this.expect(Ve.comma),o&&this.afterTrailingComma(Ve.parenR,!0)){p=!0;break}if(this.type===Ve.ellipsis){r=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===Ve.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var g=this.lastTokEnd,f=this.lastTokEndLoc;if(this.expect(Ve.parenR),e&&this.shouldParseArrow(c)&&this.eat(Ve.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=m,this.parseParenArrowList(s,n,c,t);c.length&&!p||this.unexpected(this.lastTokStart),r&&this.unexpected(r),this.checkExpressionErrors(d,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?((i=this.startNodeAt(a,l)).expressions=c,this.finishNodeAt(i,"SequenceExpression",g,f)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(s,n);return y.expression=i,this.finishNode(y,"ParenthesizedExpression")}return i},Ct.parseParenItem=function(e){return e},Ct.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,s)};var Et=[];Ct.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===Ve.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var i=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),i&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var s=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),s,n,!0,!1),this.eat(Ve.parenL)?e.arguments=this.parseExprList(Ve.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Et,this.finishNode(e,"NewExpression")},Ct.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===Ve.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),i.tail=this.type===Ve.backQuote,this.finishNode(i,"TemplateElement")},Ct.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var i=this.startNode();this.next(),i.expressions=[];var s=this.parseTemplateElement({isTagged:t});for(i.quasis=[s];!s.tail;)this.type===Ve.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(Ve.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(Ve.braceR),i.quasis.push(s=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},Ct.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===Ve.name||this.type===Ve.num||this.type===Ve.string||this.type===Ve.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===Ve.star)&&!Re.test(this.input.slice(this.lastTokEnd,this.start))},Ct.parseObj=function(e,t){var i=this.startNode(),s=!0,n={};for(i.properties=[],this.next();!this.eat(Ve.braceR);){if(s)s=!1;else if(this.expect(Ve.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(Ve.braceR))break;var o=this.parseProperty(e,t);e||this.checkPropClash(o,n,t),i.properties.push(o)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")},Ct.parseProperty=function(e,t){var i,s,n,o,r=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(Ve.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===Ve.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===Ve.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(n=this.start,o=this.startLoc),e||(i=this.eat(Ve.star)));var a=this.containsEsc;return this.parsePropertyName(r),!e&&!a&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(r)?(s=!0,i=this.options.ecmaVersion>=9&&this.eat(Ve.star),this.parsePropertyName(r)):s=!1,this.parsePropertyValue(r,e,i,s,n,o,t,a),this.finishNode(r,"Property")},Ct.parseGetterSetter=function(e){e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var t="get"===e.kind?0:1;if(e.value.params.length!==t){var i=e.value.start;"get"===e.kind?this.raiseRecoverable(i,"getter should have no params"):this.raiseRecoverable(i,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},Ct.parsePropertyValue=function(e,t,i,s,n,o,r,a){(i||s)&&this.type===Ve.colon&&this.unexpected(),this.eat(Ve.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,r),e.kind="init"):this.options.ecmaVersion>=6&&this.type===Ve.parenL?(t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(i,s)):t||a||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===Ve.comma||this.type===Ve.braceR||this.type===Ve.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((i||s)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),e.kind="init",t?e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key)):this.type===Ve.eq&&r?(r.shorthandAssign<0&&(r.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.shorthand=!0):this.unexpected():((i||s)&&this.unexpected(),this.parseGetterSetter(e))},Ct.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(Ve.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(Ve.bracketR),e.key;e.computed=!1}return e.key=this.type===Ve.num||this.type===Ve.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},Ct.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Ct.parseMethod=function(e,t,i){var s=this.startNode(),n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.initFunction(s),this.options.ecmaVersion>=6&&(s.generator=e),this.options.ecmaVersion>=8&&(s.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|ot(t,s.generator)|(i?128:0)),this.expect(Ve.parenL),s.params=this.parseBindingList(Ve.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(s,!1,!0,!1),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(s,"FunctionExpression")},Ct.parseArrowExpression=function(e,t,i,s){var n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.enterScope(16|ot(i,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!i),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,s),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(e,"ArrowFunctionExpression")},Ct.parseFunctionBody=function(e,t,i,s){var n=t&&this.type!==Ve.braceL,o=this.strict,r=!1;if(n)e.body=this.parseMaybeAssign(s),e.expression=!0,this.checkParams(e,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);o&&!a||(r=this.strictDirective(this.end))&&a&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var l=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(e,!o&&!r&&!t&&!i&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,r&&!o),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=l}this.exitScope()},Ct.isSimpleParamList=function(e){for(var t=0,i=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t){this.currentScope().lexical.push(e)}else if(3===t){var o=this.currentScope();s=this.treatFunctionsAsVar?o.lexical.indexOf(e)>-1:o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var r=this.scopeStack.length-1;r>=0;--r){var a=this.scopeStack[r];if(a.lexical.indexOf(e)>-1&&!(32&a.flags&&a.lexical[0]===e)||!this.treatFunctionsAsVarInScope(a)&&a.functions.indexOf(e)>-1){s=!0;break}if(a.var.push(e),this.inModule&&1&a.flags&&delete this.undefinedExports[e],259&a.flags)break}s&&this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")},Pt.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},Pt.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},Pt.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags)return t}},Pt.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(259&t.flags&&!(16&t.flags))return t}};var It=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new Ze(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},At=rt.prototype;function Dt(e,t,i,s){return e.type=t,e.end=i,this.options.locations&&(e.loc.end=s),this.options.ranges&&(e.range[1]=i),e}At.startNode=function(){return new It(this,this.start,this.startLoc)},At.startNodeAt=function(e,t){return new It(this,e,t)},At.finishNode=function(e,t){return Dt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},At.finishNodeAt=function(e,t,i,s){return Dt.call(this,e,t,i,s)},At.copyNode=function(e){var t=new It(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};var Lt="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",Nt=Lt+" Extended_Pictographic",Ot=Nt+" EBase EComp EMod EPres ExtPict",Vt={9:Lt,10:Nt,11:Nt,12:Ot,13:Ot,14:Ot},Rt={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Bt="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Ft="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",$t=Ft+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Gt=$t+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",jt=Gt+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ut=jt+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",zt={9:Ft,10:$t,11:Gt,12:jt,13:Ut,14:Ut+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},Ht={};function Wt(e){var t=Ht[e]={binary:Je(Vt[e]+" "+Bt),binaryOfStrings:Je(Rt[e]),nonBinary:{General_Category:Je(Bt),Script:Je(zt[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var qt=0,Xt=[9,10,11,12,13,14];qt=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Ht[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Qt(e){return 105===e||109===e||115===e}function Zt(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function ei(e){return e>=65&&e<=90||e>=97&&e<=122}Kt.prototype.reset=function(e,t,i){var s=-1!==i.indexOf("v"),n=-1!==i.indexOf("u");this.start=0|e,this.source=t+"",this.flags=i,s&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Kt.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Kt.prototype.at=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return-1;var n=i.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=s)return n;var o=i.charCodeAt(e+1);return o>=56320&&o<=57343?(n<<10)+o-56613888:n},Kt.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return s;var n,o=i.charCodeAt(e);return!t&&!this.switchU||o<=55295||o>=57344||e+1>=s||(n=i.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Kt.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Kt.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Kt.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Kt.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Kt.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var i=this.pos,s=0,n=e;s-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===r&&(s=!0),"v"===r&&(n=!0)}this.options.ecmaVersion>=15&&s&&n&&this.raise(e.start,"Invalid regular expression flag")},Jt.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Jt.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,i=e.backReferenceNames;t=16;for(t&&(e.branchID=new Yt(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Jt.regexp_alternative=function(e){for(;e.pos=9&&(i=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!i,!0}return e.pos=t,!1},Jt.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Jt.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Jt.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(s=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var i=this.regexp_eatModifiers(e),s=e.eat(45);if(i||s){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(s){var r=this.regexp_eatModifiers(e);i||r||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var a=0;a-1||i.indexOf(l)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Jt.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Jt.regexp_eatModifiers=function(e){for(var t="",i=0;-1!==(i=e.current())&&Qt(i);)t+=Ye(i),e.advance();return t},Jt.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Jt.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Jt.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Zt(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!Zt(i);)e.advance();return e.pos!==t},Jt.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},Jt.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,i=e.groupNames[e.lastStringValue];if(i)if(t)for(var s=0,n=i;s=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Pe(e,!0)||36===e||95===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,i=this.options.ecmaVersion>=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Te(e,!0)||36===e||95===e||8204===e||8205===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Jt.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU)return i>e.maxBackReference&&(e.maxBackReference=i),!0;if(i<=e.numCapturingParens)return!0;e.pos=t}return!1},Jt.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Jt.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Jt.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Jt.regexp_eatZero=function(e){return 48===e.current()&&!si(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Jt.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Jt.regexp_eatControlLetter=function(e){var t=e.current();return!!ei(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var i,s=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(n&&o>=55296&&o<=56319){var r=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343)return e.lastIntValue=1024*(o-55296)+(a-56320)+65536,!0}e.pos=r,e.lastIntValue=o}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&((i=e.lastIntValue)>=0&&i<=1114111))return!0;n&&e.raise("Invalid unicode escape"),e.pos=s}return!1},Jt.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};function ti(e){return ei(e)||95===e}function ii(e){return ti(e)||si(e)}function si(e){return e>=48&&e<=57}function ni(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function oi(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function ri(e){return e>=48&&e<=55}Jt.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var i=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((i=80===t)||112===t)){var s;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(s=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return i&&2===s&&e.raise("Invalid property name"),s;e.raise("Invalid property name")}return 0},Jt.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,i,s),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Jt.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){We(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},Jt.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Jt.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";ti(t=e.current());)e.lastStringValue+=Ye(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";ii(t=e.current());)e.lastStringValue+=Ye(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Jt.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),i=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===i&&e.raise("Negated character class may contain strings"),!0}return!1},Jt.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Jt.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;!e.switchU||-1!==t&&-1!==i||e.raise("Invalid character class"),-1!==t&&-1!==i&&t>i&&e.raise("Range out of order in character class")}}},Jt.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var i=e.current();(99===i||ri(i))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var s=e.current();return 93!==s&&(e.lastIntValue=s,e.advance(),!0)},Jt.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Jt.regexp_classSetExpression=function(e){var t,i=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(i=2);for(var s=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(i=1):e.raise("Invalid character in character class");if(s!==e.pos)return i;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(s!==e.pos)return i}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return i;2===t&&(i=2)}},Jt.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;return-1!==i&&-1!==s&&i>s&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Jt.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Jt.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var i=e.eat(94),s=this.regexp_classContents(e);if(e.eat(93))return i&&2===s&&e.raise("Negated character class may contain strings"),s;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Jt.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var i=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return i}else e.raise("Invalid escape");e.pos=t}return null},Jt.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Jt.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Jt.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var i=e.current();return!(i<0||i===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(i))&&(!function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(i)&&(e.advance(),e.lastIntValue=i,!0))},Jt.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!si(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Jt.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;si(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},Jt.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;ni(i=e.current());)e.lastIntValue=16*e.lastIntValue+oi(i),e.advance();return e.pos!==t},Jt.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*i+e.lastIntValue:e.lastIntValue=8*t+i}else e.lastIntValue=t;return!0}return!1},Jt.regexp_eatOctalDigit=function(e){var t=e.current();return ri(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Jt.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length?this.finishToken(Ve.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},li.readToken=function(e){return Pe(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},li.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},li.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(-1===i&&this.raise(this.pos-2,"Unterminated comment"),this.pos=i+2,this.options.locations)for(var s=void 0,n=t;(s=$e(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=s;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,i),t,this.pos,e,this.curPosition())},li.skipLineComment=function(e){for(var t=this.pos,i=this.options.onComment&&this.curPosition(),s=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&Ge.test(String.fromCharCode(e))))break e;++this.pos}}},li.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var i=this.type;this.type=e,this.value=t,this.updateContext(i)},li.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(Ve.ellipsis)):(++this.pos,this.finishToken(Ve.dot))},li.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(Ve.assign,2):this.finishOp(Ve.slash,1)},li.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,s=42===e?Ve.star:Ve.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,s=Ve.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(Ve.assign,i+1):this.finishOp(s,i)},li.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Ve.assign,3);return this.finishOp(124===e?Ve.logicalOR:Ve.logicalAND,2)}return 61===t?this.finishOp(Ve.assign,2):this.finishOp(124===e?Ve.bitwiseOR:Ve.bitwiseAND,1)},li.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(Ve.assign,2):this.finishOp(Ve.bitwiseXOR,1)},li.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!Re.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(Ve.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(Ve.assign,2):this.finishOp(Ve.plusMin,1)},li.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),i=1;return t===e?(i=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+i)?this.finishOp(Ve.assign,i+1):this.finishOp(Ve.bitShift,i)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(i=2),this.finishOp(Ve.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},li.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(Ve.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(Ve.arrow)):this.finishOp(61===e?Ve.eq:Ve.prefix,1)},li.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57)return this.finishOp(Ve.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Ve.assign,3);return this.finishOp(Ve.coalesce,2)}}return this.finishOp(Ve.question,1)},li.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,Pe(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(Ve.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Ye(e)+"'")},li.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(Ve.parenL);case 41:return++this.pos,this.finishToken(Ve.parenR);case 59:return++this.pos,this.finishToken(Ve.semi);case 44:return++this.pos,this.finishToken(Ve.comma);case 91:return++this.pos,this.finishToken(Ve.bracketL);case 93:return++this.pos,this.finishToken(Ve.bracketR);case 123:return++this.pos,this.finishToken(Ve.braceL);case 125:return++this.pos,this.finishToken(Ve.braceR);case 58:return++this.pos,this.finishToken(Ve.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(Ve.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(Ve.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Ye(e)+"'")},li.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},li.readRegexp=function(){for(var e,t,i=this.pos;;){this.pos>=this.input.length&&this.raise(i,"Unterminated regular expression");var s=this.input.charAt(this.pos);if(Re.test(s)&&this.raise(i,"Unterminated regular expression"),e)e=!1;else{if("["===s)t=!0;else if("]"===s&&t)t=!1;else if("/"===s&&!t)break;e="\\"===s}++this.pos}var n=this.input.slice(i,this.pos);++this.pos;var o=this.pos,r=this.readWord1();this.containsEsc&&this.unexpected(o);var a=this.regexpState||(this.regexpState=new Kt(this));a.reset(i,n,r),this.validateRegExpFlags(a),this.validateRegExpPattern(a);var l=null;try{l=new RegExp(n,r)}catch(e){}return this.finishToken(Ve.regexp,{pattern:n,flags:r,value:l})},li.readInt=function(e,t,i){for(var s=this.options.ecmaVersion>=12&&void 0===t,n=i&&48===this.input.charCodeAt(this.pos),o=this.pos,r=0,a=0,l=0,c=null==t?1/0:t;l=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;a=h,r=r*e+p}}return s&&95===a&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===o||null!=t&&this.pos-o!==t?null:r},li.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);return null==i&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(i=ci(this.input.slice(t,this.pos)),++this.pos):Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Ve.num,i)},li.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var i=this.pos-t>=2&&48===this.input.charCodeAt(t);i&&this.strict&&this.raise(t,"Invalid number");var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&110===s){var n=ci(this.input.slice(t,this.pos));return++this.pos,Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Ve.num,n)}i&&/[89]/.test(this.input.slice(t,this.pos))&&(i=!1),46!==s||i||(++this.pos,this.readInt(10),s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(43!==(s=this.input.charCodeAt(++this.pos))&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),Pe(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,r=(o=this.input.slice(t,this.pos),i?parseInt(o,8):parseFloat(o.replace(/_/g,"")));return this.finishToken(Ve.num,r)},li.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},li.readString=function(e){for(var t="",i=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var s=this.input.charCodeAt(this.pos);if(s===e)break;92===s?(t+=this.input.slice(i,this.pos),t+=this.readEscapedChar(!1),i=this.pos):8232===s||8233===s?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Fe(s)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(Ve.string,t)};var hi={};li.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==hi)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},li.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw hi;this.raise(e,t)},li.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var i=this.input.charCodeAt(this.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==Ve.template&&this.type!==Ve.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(Ve.template,e)):36===i?(this.pos+=2,this.finishToken(Ve.dollarBraceL)):(++this.pos,this.finishToken(Ve.backQuote));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(Fe(i)){switch(e+=this.input.slice(t,this.pos),++this.pos,i){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(i)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},li.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(s,8);return n>255&&(s=s.slice(0,-1),n=parseInt(s,8)),this.pos+=s.length-1,t=this.input.charCodeAt(this.pos),"0"===s&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return Fe(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},li.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},li.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},bi=17,vi={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:bi,ClassExpression:bi,FunctionExpression:bi,ObjectExpression:bi,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function xi(e,t){const{generator:i}=e;if(e.write("("),null!=t&&t.length>0){i[t[0].type](t[0],e);const{length:s}=t;for(let n=1;n0){e.write(s);for(let t=1;t0){i.VariableDeclarator(s[0],e);for(let t=1;t0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const{length:a}=r;for(let e=0;e0){for(;o0&&t.write(", ");const e=i[o],s=e.type[6];if("D"===s)t.write(e.local.name,e),o++;else{if("N"!==s)break;t.write("* as "+e.local.name,e),o++}}if(o0){t.write(" with { ");for(let e=0;e0)for(let e=0;;){const n=i[e],{name:o}=n.local;if(t.write(o,n),o!==n.exported.name&&t.write(" as "+n.exported.name),!(++e0){t.write(" with { ");for(let i=0;i0){t.write(" with { ");for(let i=0;i "),"O"===e.body.type[0]?(t.write("("),this.ObjectExpression(e.body,t),t.write(")")):this[e.body.type](e.body,t)},ThisExpression(e,t){t.write("this",e)},Super(e,t){t.write("super",e)},RestElement:Pi=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:Pi,YieldExpression(e,t){t.write(e.delegate?"yield*":"yield"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t))},AwaitExpression(e,t){t.write("await ",e),wi(t,e.argument,e)},TemplateLiteral(e,t){const{quasis:i,expressions:s}=e;t.write("`");const{length:n}=s;for(let e=0;e0){const{elements:i}=e,{length:s}=i;for(let e=0;;){const n=i[e];if(null!=n&&this[n.type](n,t),!(++e0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const r=","+s,{properties:a}=e,{length:l}=a;for(let e=0;;){const i=a[e];if(n&&null!=i.comments&&Si(t,i.comments,o,s),t.write(o),this[i.type](i,t),!(++e0){const{properties:i}=e,{length:s}=i;for(let e=0;this[i[e].type](i[e],t),++e1)&&("U"!==n[0]||"n"!==n[1]&&"p"!==n[1]||!s.prefix||s.operator[0]!==i||"+"!==i&&"-"!==i)||t.write(" "),o?(t.write(i.length>1?" (":"("),this[n](s,t),t.write(")")):this[n](s,t)}else this[e.argument.type](e.argument,t),t.write(e.operator)},UpdateExpression(e,t){e.prefix?(t.write(e.operator),this[e.argument.type](e.argument,t)):(this[e.argument.type](e.argument,t),t.write(e.operator))},AssignmentExpression(e,t){this[e.left.type](e.left,t),t.write(" "+e.operator+" "),this[e.right.type](e.right,t)},AssignmentPattern(e,t){this[e.left.type](e.left,t),t.write(" = "),this[e.right.type](e.right,t)},BinaryExpression:Ti=function(e,t){const i="in"===e.operator;i&&t.write("("),wi(t,e.left,e,!1),t.write(" "+e.operator+" "),wi(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:Ti,ConditionalExpression(e,t){const{test:i}=e,s=t.expressionsPrecedence[i.type];s===bi||s<=t.expressionsPrecedence.ConditionalExpression?(t.write("("),this[i.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ? "),this[e.consequent.type](e.consequent,t),t.write(" : "),this[e.alternate.type](e.alternate,t)},NewExpression(e,t){t.write("new ");const i=t.expressionsPrecedence[e.callee.type];i===bi||i0&&(this.lineEndSize>0&&(1===s.length?e[i-1]===s:e.endsWith(s))?(this.line+=this.lineEndSize,this.column=0):this.column+=i)}toString(){return this.output}}var Oi=Object.defineProperty,Vi=(e,t,i)=>((e,t,i)=>t in e?Oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Ri{constructor(){Vi(this,"scopes",[]),Vi(this,"scopeTypes",[]),Vi(this,"scopeCounts",new Map),Vi(this,"contextBoundVars",new Set),Vi(this,"arrayPatternElements",new Set),Vi(this,"rootParams",new Set),Vi(this,"varKinds",new Map),Vi(this,"loopVars",new Set),Vi(this,"loopVarNames",new Map),Vi(this,"paramIdCounter",0),Vi(this,"cacheIdCounter",0),Vi(this,"tempVarCounter",0),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`'p${this.paramIdCounter++}'`}}get nextCacheIdArg(){return{type:"Identifier",name:`'cache_${this.cacheIdCounter++}'`}}pushScope(e){this.scopes.push(new Map),this.scopeTypes.push(e),this.scopeCounts.set(e,(this.scopeCounts.get(e)||0)+1)}popScope(){this.scopes.pop(),this.scopeTypes.pop()}getCurrentScopeType(){return this.scopeTypes[this.scopeTypes.length-1]}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addContextBoundVar(e,t=!1){this.contextBoundVars.add(e),t&&this.rootParams.add(e)}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,t){this.loopVars.add(e),this.loopVarNames.set(e,t)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addVariable(e,t){if(this.isContextBound(e))return e;const i=this.scopes[this.scopes.length-1],s=this.scopeTypes[this.scopeTypes.length-1],n=`${s}${this.scopeCounts.get(s)||1}_${e}`;return i.set(e,n),this.varKinds.set(n,t),n}getVariable(e){if(this.loopVars.has(e)){const t=this.loopVarNames.get(e);if(t)return[t,"let"]}if(this.isContextBound(e))return[e,"let"];for(let t=this.scopes.length-1;t>=0;t--){const i=this.scopes[t];if(i.has(e)){const t=i.get(e);return[t,this.varKinds.get(t)||"let"]}}return[e,"let"]}generateTempVar(){return"temp_"+ ++this.tempVarCounter}}//!!!Warning!!! this code is not clean, it was initially written as a PoC then used as transpiler for PineTS
+const Bi="$",Fi={type:"Identifier",name:"undefined"};function $i(e,t){if(e.computed&&"Identifier"===e.property.type){if(t.isLoopVariable(e.property.name))return;if(!t.isContextBound(e.property.name)){const[i,s]=t.getVariable(e.property.name);e.property={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.property={type:"MemberExpression",object:e.property,property:{type:"Literal",value:0},computed:!0}}}if(e.computed&&"Identifier"===e.object.type){if(t.isLoopVariable(e.object.name))return;if(!t.isContextBound(e.object.name)){const[i,s]=t.getVariable(e.object.name);e.object={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if("MemberExpression"===e.property.type){const i=e.property;i._indexTransformed||($i(i,t),i._indexTransformed=!0)}}}function Gi(e,t,i){if(e.object&&"Identifier"===e.object.type&&"Math"===e.object.name)return;const s="if"==i.getCurrentScopeType(),n="els"==i.getCurrentScopeType(),o="for"==i.getCurrentScopeType();!s&&!n&&!o&&e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)||e._indexTransformed||($i(e,i),e._indexTransformed=!0)}function ji(e,t){e.declarations.forEach((i=>{"na"==i.init.name&&(i.init.name="NaN");const s=i.init&&"MemberExpression"===i.init.type&&i.init.object&&("context"===i.init.object.name||i.init.object.name===Bi||"context2"===i.init.object.name),n=i.init&&"MemberExpression"===i.init.type&&i.init.object?.object&&("context"===i.init.object.object.name||i.init.object.object.name===Bi||"context2"===i.init.object.object.name),o=i.init&&"ArrowFunctionExpression"===i.init.type;if(s)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.name=Bi);if(n)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.object.name=Bi);o&&i.init.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name)}));const r=t.addVariable(i.id.name,e.kind),a=e.kind;i.init&&!o&&("CallExpression"===i.init.type&&"MemberExpression"===i.init.callee.type&&i.init.callee.object&&"Identifier"===i.init.callee.object.type&&t.isContextBound(i.init.callee.object.name)?Ki(i.init,t):di(i.init,{parent:i.init},{Identifier(e,i){e.parent=i.parent,Ui(e,t);const s=e.parent&&"BinaryExpression"===e.parent.type,n=e.parent&&"ConditionalExpression"===e.parent.type;"Identifier"===e.type&&(s||n)&&Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Literal",value:0},computed:!0})},CallExpression(e,i,s){"Identifier"===e.callee.type&&(e.callee.parent=e),e.arguments.forEach((t=>{"Identifier"===t.type&&(t.parent=e)})),Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e})))},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},MemberExpression(e,i,s){"Identifier"===e.object.type&&(e.object.parent=e),"Identifier"===e.property.type&&(e.property.parent=e),$i(e,t),e.object&&s(e.object,{parent:e})}}));const l={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:a},computed:!1},property:{type:"Identifier",name:r},computed:!1},c=t.isArrayPatternElement(i.id.name),h=!c&&i.init&&"MemberExpression"===i.init.type&&i.init.computed&&i.init.property&&("Literal"===i.init.property.type||"MemberExpression"===i.init.property.type);"MemberExpression"===i.init?.property?.type&&(i.init.property._indexTransformed||($i(i.init.property,t),i.init.property._indexTransformed=!0));const p={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:l,right:i.init?o||c?i.init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:h?[l,i.init.object,i.init.property]:[l,i.init]}:{type:"Identifier",name:"undefined"}}};if(c){p.expression.right.object.property.name+=`?.[0][${i.init.property.value}]`;const e=p.expression.right.object;p.expression.right={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:[l,e]}}o&&(t.pushScope("fn"),di(i.init.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},IfStatement(e,t,i){t.pushScope("if"),i(e.consequent,t),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope()),t.popScope()},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},AssignmentExpression(e,t){zi(e,t)}}),t.popScope()),Object.assign(e,p)}))}function Ui(e,t){if(e.name!==Bi){if("Math"===e.name||"NaN"===e.name||"undefined"===e.name||"Infinity"===e.name||"null"===e.name||e.name.startsWith("'")&&e.name.endsWith("'")||e.name.startsWith('"')&&e.name.endsWith('"')||e.name.startsWith("`")&&e.name.endsWith("`")||t.isLoopVariable(e.name)||t.isContextBound(e.name)&&!t.isRootParam(e.name))return;const i=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&t.isContextBound(e.name),s=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&"param"===e.parent.callee.property.name;e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left;const n=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&t.isContextBound(e.parent.callee.object.name),o=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed,r=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.property===e&&e.parent.parent&&"CallExpression"===e.parent.parent.type&&e.parent.parent.callee&&"MemberExpression"===e.parent.parent.callee.type&&t.isContextBound(e.parent.parent.callee.object.name),a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e;if(i||s||n||r||a){if(a)return;const[i,s]=t.getVariable(e.name);return void Object.assign(e,{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1})}const[l,c]=t.getVariable(e.name),h={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:c},computed:!1},property:{type:"Identifier",name:l},computed:!1};e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e||o?Object.assign(e,h):Object.assign(e,{type:"MemberExpression",object:h,property:{type:"Literal",value:0},computed:!0})}}function zi(e,t){if("Identifier"===e.left.type){const[i,s]=t.getVariable(e.left.name),n={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1};e.left={type:"MemberExpression",object:n,property:{type:"Literal",value:0},computed:!0}}di(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,s){"na"==e.name&&(e.name="NaN"),e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type,o=e.parent&&"ConditionalExpression"===e.parent.type,r=t.isContextBound(e.name)&&!t.isRootParam(e.name),a=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,l=e.parent&&e.parent._isParamCall,c=e.parent&&"MemberExpression"===e.parent.type,h="NaN"===e.name;(r||o||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&!c&&!a&&!l&&!h&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}})}function Hi(e,t){const i=t.getCurrentScopeType();if(e.argument){if("ArrayExpression"===e.argument.type)e.argument.elements=e.argument.elements.map((e=>{if("Identifier"===e.type){if(t.isContextBound(e.name)&&!t.isRootParam(e.name))return{type:"MemberExpression",object:e,property:{type:"Literal",value:0},computed:!0};const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},property:{type:"Literal",value:0},computed:!0}}return"MemberExpression"===e.type?(e.computed&&"Identifier"===e.object.type&&t.isContextBound(e.object.name)&&!t.isRootParam(e.object.name)||Gi(e,0,t),e):e})),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("BinaryExpression"===e.argument.type)di(e.argument,t,{Identifier(e,t){Ui(e,t),"Identifier"===e.type&&Qi(e)},MemberExpression(e){Gi(e,0,t)}});else if("ObjectExpression"===e.argument.type)e.argument.properties=e.argument.properties.map((e=>{if(e.shorthand){const[i,s]=t.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}));else if("Identifier"===e.argument.type){const[i,s]=t.getVariable(e.argument.name);e.argument={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.argument={type:"MemberExpression",object:e.argument,property:{type:"Literal",value:0},computed:!0}}"fn"===i&&(e.argument={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"precision"}},arguments:[e.argument]})}}function Wi(e,t){if("Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(t.isLoopVariable(e.name))return e;if(t.isRootParam(e.name)){const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if(t.isContextBound(e.name))return e;const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}return e}function qi(e,t,i){const s=Xi(e.argument,t,i);return{type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:s,start:e.start,end:e.end}}function Xi(e,t,i=""){switch(e.type){case"BinaryExpression":return Ji(e,t,i);case"MemberExpression":return{type:"MemberExpression",object:"Identifier"===e.object.type?Wi(e.object,t):e.object,property:e.property,computed:e.computed};case"Identifier":return t.isLoopVariable(e.name)||e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e?e:{type:"MemberExpression",object:Wi(e,t),property:{type:"Literal",value:0},computed:!0};case"UnaryExpression":return qi(e,t,i)}return e}function Ji(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"BinaryExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)},MemberExpression(e){Gi(e,0,t)}}),o}function Yi(e,t,i){switch(e?.type){case"BinaryExpression":e=Ji(e,i,t);break;case"LogicalExpression":e=function(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"LogicalExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)}}),o}(e,i,t);break;case"ConditionalExpression":return function(e,t,i){return di(e,{parent:e,inNamespaceCall:!1},{Identifier(e,i,s){if("NaN"==e.name)return;if("na"==e.name)return void(e.name="NaN");e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}}),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"param"}},arguments:[e,Fi,t.nextParamIdArg],_transformed:!0,_isParamCall:!0}}(e,i,t);case"UnaryExpression":e=qi(e,i,t)}if("MemberExpression"===e.type&&e.computed&&e.property){return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)?e.object:Wi(e.object,i),"Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name)?e.property:Wi(e.property,i),i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}if("ObjectExpression"===e.type&&(e.properties=e.properties.map((e=>{if(e.value.name){const[t,s]=i.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:t},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}))),"Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(i.isContextBound(e.name)&&!i.isRootParam(e.name))return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:[e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}return"CallExpression"===e?.type&&Ki(e,i),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.type?Wi(e,i):e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}function Ki(e,t,i){if(!e._transformed){if(e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&(t.isContextBound(e.callee.object.name)||"math"===e.callee.object.name||"ta"===e.callee.object.name)){const i=e.callee.object.name;e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,i,t))),e._transformed=!0}else e.callee&&"Identifier"===e.callee.type&&(e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,Bi,t))),e._transformed=!0);e.arguments.forEach((e=>{di(e,t,{Identifier(e,i,s){e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},CallExpression(e,t,i){e._transformed||Ki(e,t)},MemberExpression(e,i,s){Gi(e,0,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})}})}))}}function Qi(e,t){Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name,start:e.start,end:e.end},property:{type:"Literal",value:0},computed:!0,_indexTransformed:!0})}function Zi(e,t,i){if(e.init&&"VariableDeclaration"===e.init.type){const i=e.init.declarations[0],s=i.id.name;t.addLoopVariable(s,s),e.init={type:"VariableDeclaration",kind:e.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:i.init}]},i.init&&di(i.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}})}e.test&&di(e.test,t,{Identifier(e,i){!t.isLoopVariable(e.name)&&!e.computed&&(t.pushScope("for"),Ui(e,i),"Identifier"===e.type&&(e.computed=!0,Qi(e)),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}}),e.update&&di(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())}}),t.pushScope("for"),i(e.body,t),t.popScope()}function es(e,t,i){e.test&&(t.pushScope("if"),function(e,t){di(e,t,{MemberExpression(e){Gi(e,0,t)},CallExpression(e,t){Ki(e,t)},Identifier(e,i){Ui(e,i);const s="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&s&&Qi(e)}})}(e.test,t),t.popScope()),t.pushScope("if"),i(e.consequent,t),t.popScope(),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope())}function ts(e){let t="function"==typeof e?e.toString():e;const i=(s=t.trim(),rt.parse(s,{ecmaVersion:"latest",sourceType:"module"}));var s;!function(e){di(e,null,{VariableDeclaration(e,t,i){e.declarations&&e.declarations.length>0&&e.declarations.forEach((t=>{if(t.init&&"ArrowFunctionExpression"===t.init.type&&0!==t.init.start){const i={type:"FunctionDeclaration",id:t.id,params:t.init.params,body:"BlockStatement"===t.init.body.type?t.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t.init.body}]},async:t.init.async,generator:!1};Object.assign(e,i)}})),e.body&&e.body.body&&e.body.body.forEach((e=>i(e,t)))}})}(i);const n=new Ri;let o;(function(e,t){pi(e,{VariableDeclaration(e){e.declarations.forEach((e=>{const i=e.init&&"MemberExpression"===e.init.type&&e.init.object&&("context"===e.init.object.name||e.init.object.name===Bi||"context2"===e.init.object.name),s=e.init&&"MemberExpression"===e.init.type&&e.init.object?.object&&("context"===e.init.object.object.name||e.init.object.object.name===Bi||"context2"===e.init.object.object.name);(i||s)&&(e.id.name&&t.addContextBoundVar(e.id.name),e.id.properties&&e.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})))}))}})})(i,n),pi(i,{FunctionDeclaration(e){!function(e,t){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,!1)})),e.body&&"BlockStatement"===e.body.type&&(t.pushScope("fn"),di(e.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t),e.arguments.forEach((e=>{"BinaryExpression"===e.type&&di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}))},MemberExpression(e){Gi(e,0,t)},AssignmentExpression(e,t){zi(e,t)},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)},BinaryExpression(e,t,i){di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}}),t.popScope())}(e,n)},ArrowFunctionExpression(e){const t=0===e.start;t&&e.params&&e.params.length>0&&(o=e.params[0].name,e.params[0].name=Bi),function(e,t,i=!1){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,i)}))}(e,n,t)},VariableDeclaration(e){e.declarations.forEach((t=>{if("ArrayPattern"===t.id.type){const i=n.generateTempVar(),s={type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:i},init:t.init}]};t.id.elements?.forEach((e=>{"Identifier"===e.type&&n.addArrayPatternElement(e.name)}));const o=t.id.elements.map(((t,s)=>({type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:t,init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Literal",value:s},computed:!0}}]})));Object.assign(e,{type:"BlockStatement",body:[s,...o]})}}))},ForStatement(e){}}),di(i,n,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,n)},AssignmentExpression(e,t){zi(e,t)},FunctionDeclaration(e,t){},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)}});const r=function(e,t){const i=new Ni(t);return i.generator[e.type](e,i),i.output}(i);return new Function("",`return ${r}`)(this)}var is=Object.defineProperty,ss=(e,t,i)=>((e,t,i)=>t in e?is(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ns{constructor(e,t,i,s,n,o,r){this.source=e,this.tickerId=t,this.timeframe=i,this.limit=s,this.sDate=n,this.eDate=o,this.title=r,ss(this,"data",[]),ss(this,"open",[]),ss(this,"high",[]),ss(this,"low",[]),ss(this,"close",[]),ss(this,"volume",[]),ss(this,"hl2",[]),ss(this,"hlc3",[]),ss(this,"ohlc4",[]),ss(this,"openTime",[]),ss(this,"closeTime",[]),ss(this,"_periods"),ss(this,"pineTSCode"),ss(this,"fn"),ss(this,"_readyPromise",null),ss(this,"_ready",!1),this._readyPromise=new Promise((a=>{this.loadMarketData(e,t,i,s,n,o,r).then((e=>{const t=e.reverse();this._periods=t.length,this.data=t;const i=t.map((e=>e.open)),s=t.map((e=>e.close)),n=t.map((e=>e.high)),o=t.map((e=>e.low)),r=t.map((e=>e.volume)),l=t.map((e=>(e.high+e.low+e.close)/3)),c=t.map((e=>(e.high+e.low)/2)),h=t.map((e=>(e.high+e.low+e.open+e.close)/4)),p=t.map((e=>e.openTime)),d=t.map((e=>e.closeTime));this.open=i,this.close=s,this.high=n,this.low=o,this.volume=r,this.hl2=c,this.hlc3=l,this.ohlc4=h,this.openTime=p,this.closeTime=d,this._ready=!0,a(!0)}))}))}get periods(){return this._periods}async loadMarketData(e,t,i,s,n,o,r){return Array.isArray(e)?e:e.getMarketData(t,i,s,n,o,r)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw new Error("PineTS is not ready");return this._readyPromise}updateData(e){if(!e)throw new Error("Invalid data: newData must be a valid object.");this.data=[e,...this.data],this._periods=this.data.length,this.open=[e.open,...this.open],this.close=[e.close,...this.close],this.high=[e.high,...this.high],this.low=[e.low,...this.low],this.volume=[e.volume,...this.volume],this.hl2=[(e.high+e.low)/2,...this.hl2],this.hlc3=[(e.high+e.low+e.close)/3,...this.hlc3],this.ohlc4=[(e.high+e.low+e.open+e.close)/4,...this.ohlc4],this.openTime=[e.openTime,...this.openTime],this.closeTime=[e.closeTime,...this.closeTime]}async run(e,t,i){if(await this.ready(),t||(t=this._periods),!this.pineTSCode&&!e)throw new Error("Invalid PineTS Code: No pineTSCode supplied/stored.");e=e||this.pineTSCode;const s=new Es({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,title:this.title});if(s.pineTSCode=e,s.useTACache=i,!this.fn||e&&this.pineTSCode!==e){const t=ts.bind(this);this.fn=t(e),this.pineTSCode=e}const n=this.fn,o=["const","var","let","params"];for(let e=this._periods-t,i=t-1;e((e,t,i)=>t in e?os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class as{constructor(e){this.context=e,rs(this,"script"),rs(this,"pane",0),rs(this,"color",{param:(e,t=0)=>Array.isArray(e)?e[t]:e,rgb:(e,t,i,s)=>s?`rgba(${e}, ${t}, ${i}, ${s})`:`rgb(${e}, ${t}, ${i})`,new:(e,t)=>{if(e&&e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return t?`rgba(${s}, ${n}, ${o}, ${t})`:`rgb(${s}, ${n}, ${o})`}return t?`rgba(${e}, ${t})`:e},white:"white",lime:"lime",green:"green",red:"red",maroon:"maroon",black:"black",gray:"gray",blue:"blue"})}extractPlotOptions(e){const t={};for(let i in e)Array.isArray(e[i])?t[i]=e[i][0]:t[i]=e[i];return t}indicator(e,t,i){this.script=e??t??"PineTS Script",i&&(this.pane=i.overlay?0:1)}plotchar(e,t,i){this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:{...this.extractPlotOptions(i),style:"char"}})}plot(e,t,i){this.script&&(i.group=this.script),this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t,pane:this.pane}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:this.extractPlotOptions(i)})}na(e){return Array.isArray(e)?isNaN(e[0]):isNaN(e)}nz(e,t=0){const i=Array.isArray(e)?e[0]:e,s=Array.isArray(e)?t[0]:t;return isNaN(i)?s:i}plotcandle(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.candles[n]||(this.context.candles[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.candles[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}plotbar(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.bars[n]||(this.context.bars[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.bars[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}fill(e,t,i){this.context.fills[e]||(this.context.fills[e]={plot1:e,plot2:t,options:this.extractPlotOptions(i)})}hline(e,t,i){const s=this.extractPlotOptions(i),n=Array.isArray(e)?e[0]:e;this.context.hlines[t]?(this.context.hlines[t].price=n,this.context.hlines[t].options=s):this.context.hlines[t]={price:n,options:s,pane:this.pane}}}class ls{constructor(e){this.context=e}param(e,t=0){return Array.isArray(e)?[e[t]]:[e]}any(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}int(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}float(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}bool(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}string(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}timeframe(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}time(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}price(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}session(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}source(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}symbol(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}text_area(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}enum(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}color(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}}var cs=Object.defineProperty,hs=(e,t,i)=>((e,t,i)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ps{constructor(e){this.context=e,hs(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?t?(this.context.params[i]=e.slice(t),this.context.params[i].length=e.length,this.context.params[i]):(this.context.params[i]=e.slice(0),this.context.params[i]):(this.context.params[i][0]=e,this.context.params[i])}abs(e){return Math.abs(e[0])}pow(e,t){return Math.pow(e[0],t[0])}sqrt(e){return Math.sqrt(e[0])}log(e){return Math.log(e[0])}ln(e){return Math.log(e[0])}exp(e){return Math.exp(e[0])}floor(e){return Math.floor(e[0])}ceil(e){return Math.ceil(e[0])}round(e){return Math.round(e[0])}random(){return Math.random()}max(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.max(...t)}min(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.min(...t)}sum(e,t){const i=Array.isArray(t)?t[0]:t;return Array.isArray(e)?e.slice(0,i).reduce(((e,t)=>e+t),0):e}sin(e){return Math.sin(e[0])}cos(e){return Math.cos(e[0])}tan(e){return Math.tan(e[0])}acos(e){return Math.acos(e[0])}asin(e){return Math.asin(e[0])}atan(e){return Math.atan(e[0])}avg(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return t.reduce(((e,t)=>(Array.isArray(e)?e[0]:e)+(Array.isArray(t)?t[0]:t)),0)/t.length}}var ds=Object.defineProperty,us=(e,t,i)=>((e,t,i)=>t in e?ds(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);const ms=["1","3","5","15","30","45","60","120","180","240","D","W","M"];class gs{constructor(e){this.context=e,us(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?(this.context.params[i]=t?e.slice(t):e.slice(0),[e[t],i]):(this.context.params[i][0]=e,[e,i])}async security(e,t,i,s=!1,n=!1,o=!1,r=null,a=null){const l=e[0],c=t[0],h=i[0],p=i[1],d=ms.indexOf(this.context.timeframe),u=ms.indexOf(c);if(-1==d||-1==u)throw new Error("Invalid timeframe");if(d>u)throw new Error("Only higher timeframes are supported for now");if(d===u)return h;const m=this.context.data.openTime[0],g=this.context.data.closeTime[0];if(this.context.cache[p]){const e=this.context.cache[p],t=this._findSecContextIdx(m,g,e.data.openTime,e.data.closeTime,n);return-1==t?NaN:e.params[p][t]}const f=await new ns(this.context.source,l,c,this.context.limit||1e3,this.context.sDate,this.context.eDate).run(this.context.pineTSCode);this.context.cache[p]=f;const y=this._findSecContextIdx(m,g,f.data.openTime,f.data.closeTime,n);return-1==y?NaN:f.params[p][y]}_findSecContextIdx(e,t,i,s,n=!1){for(let o=0;o2*e-n[t])),r=Math.floor(Math.sqrt(t));return vs(o,r)}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}rma(e,t){const i=Array.isArray(t)?t[0]:t,s=function(e,t){const i=new Array(e.length).fill(NaN),s=1/t;let n=0;for(let i=0;i0?i:0,n[t]=i<0?-i:0}let o=0,r=0;for(let e=1;e<=t;e++)o+=s[e],r+=n[e];o/=t,r/=t,i[t]=0===r?100:100-100/(1+o/r);for(let a=t+1;ae-t)),o=Math.floor(t/2);i[s]=t%2==0?(n[o-1]+n[o])/2:n[o]}return i}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}stdev(e,t,i=!0){const s=Array.isArray(t)?t[0]:t,n=Array.isArray(i)?i[0]:i,o=function(e,t,i=!0){const s=new Array(e.length).fill(NaN),n=bs(e,t);for(let o=t-1;op?c[e]=t:c[e]=p;let s=h[e];s>d||i[e-1]c[e]?(a[e]=1,r[e]=h[e]):(a[e]=-1,r[e]=c[e]):i[e]e+t),0)/t,n=p.reduce(((e,t)=>e+t*t),0)/t-i*i,l=Math.sqrt(n);r[d]=o[d]+s*l,a[d]=o[d]-s*l}return l?[o,r,a]:o}(e,this.context.data.volume,t,i),n=this.context.idx;if(void 0!==i&&Array.isArray(s)){const[e,t,i]=s;return[this.context.precision(e[n]),this.context.precision(t[n]),this.context.precision(i[n])]}return this.context.precision(s[n])}swma(e){const t=function(e){const t=e.length,i=new Array(t).fill(NaN);for(let s=3;s((e,t,i)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ws{constructor(e){this.array=e}}class Cs{constructor(e){this.context=e,_s(this,"_cache",{})}param(e,t=0){return Array.isArray(e)?e[t]:e}get(e,t){return e.array[t]}set(e,t,i){e.array[t]=i}push(e,t){e.array.push(t)}sum(e){return e.array.reduce(((e,t)=>e+(isNaN(t)?0:t)),0)}avg(e){return this.sum(e)/e.array.length}min(e,t=0){return[...e.array].sort(((e,t)=>e-t))[t]??this.context.NA}max(e,t=0){return[...e.array].sort(((e,t)=>t-e))[t]??this.context.NA}size(e){return e.array.length}new_bool(e,t=!1){return new ws(Array(e).fill(t))}new_float(e,t=NaN){return new ws(Array(e).fill(t))}new_int(e,t=0){return new ws(Array(e).fill(Math.round(t)))}new_string(e,t=""){return new ws(Array(e).fill(t))}new(e,t){return new ws(Array(e).fill(t))}slice(e,t,i){const s=void 0!==i?i+1:void 0;return new ws(e.array.slice(t,s))}reverse(e){e.array.reverse()}includes(e,t){return e.array.includes(t)}indexof(e,t){return e.array.indexOf(t)}lastindexof(e,t){return e.array.lastIndexOf(t)}stdev(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return Math.sqrt(this.sum(new ws(s))/n)}variance(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return this.sum(new ws(s))/n}covariance(e,t,i=!0){if(e.array.length!==t.array.length||e.array.length<2)return NaN;const s=i?e.array.length:e.array.length-1,n=this.avg(e),o=this.avg(t);let r=0;for(let i=0;i0?e.array[0]:this.context.NA}last(e){return e.array.length>0?e.array[e.array.length-1]:this.context.NA}clear(e){e.array.length=0}join(e,t=","){return e.array.join(t)}abs(e){return new ws(e.array.map((e=>Math.abs(e))))}concat(e,t){return e.array.push(...t.array),e}copy(e){return new ws([...e.array])}every(e,t){return e.array.every(t)}fill(e,t,i=0,s){const n=e.array.length,o=void 0!==s?Math.min(s,n):n;for(let s=i;s=0&&t"asc"===t?e-i:i-e))}sort_indices(e,t){const i=e.array.map(((e,t)=>t));return i.sort(((i,s)=>{const n=e.array[i],o=e.array[s];return t?t(n,o):n-o})),new ws(i)}standardize(e){const t=this.avg(e),i=this.stdev(e);return new ws(0===i?e.array.map((()=>0)):e.array.map((e=>(e-t)/i)))}unshift(e,t){e.array.unshift(t)}some(e,t){return e.array.some(t)}}var Ss=Object.defineProperty,ks=(e,t,i)=>((e,t,i)=>t in e?Ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Es{constructor({marketData:e,source:t,tickerId:i,timeframe:s,limit:n,sDate:o,eDate:r,title:a}){ks(this,"data",{open:[],high:[],low:[],close:[],volume:[],hl2:[],hlc3:[],ohlc4:[]}),ks(this,"cache",{}),ks(this,"useTACache",!1),ks(this,"NA",NaN),ks(this,"math"),ks(this,"ta"),ks(this,"input"),ks(this,"request"),ks(this,"array"),ks(this,"core"),ks(this,"lang"),ks(this,"idx",0),ks(this,"params",{}),ks(this,"const",{}),ks(this,"var",{}),ks(this,"let",{}),ks(this,"result"),ks(this,"plots",{}),ks(this,"candles",{}),ks(this,"bars",{}),ks(this,"fills",{}),ks(this,"hlines",{}),ks(this,"marketData"),ks(this,"source"),ks(this,"tickerId"),ks(this,"timeframe",""),ks(this,"limit"),ks(this,"sDate"),ks(this,"eDate"),ks(this,"group"),ks(this,"pineTSCode"),this.marketData=e,this.source=t,this.tickerId=i,this.timeframe=s,this.limit=n,this.sDate=o,this.eDate=r,this.group=a,this.math=new ps(this),this.ta=new fs(this),this.input=new ls(this),this.request=new gs(this),this.array=new Cs(this);const l=new as(this);this.core={color:l.color,indicator:l.indicator.bind(l),na:l.na.bind(l),nz:l.nz.bind(l),plot:l.plot.bind(l),plotbar:l.plotbar.bind(l),plotchar:l.plotchar.bind(l),plotcandle:l.plotcandle.bind(l),fill:l.fill.bind(l),hline:l.hline.bind(l)}}init(e,t,i=0){return e?!Array.isArray(t)||Array.isArray(t[0])?e[0]=Array.isArray(t?.[0])?t[0]:this.precision(t):e[0]=this.precision(t[t.length-this.idx-1+i]):e=Array.isArray(t)?[this.precision(t[t.length-this.idx-1+i])]:[this.precision(t)],e}precision(e,t=10){return"number"!=typeof e||isNaN(e)?e:Number(e.toFixed(t))}param(e,t,i){return"string"==typeof e||!Array.isArray(e)&&"object"==typeof e?e:(this.params[i]||(this.params[i]=[]),Array.isArray(e)?t?(this.params[i]=e.slice(t),this.params[i].length=e.length,this.params[i]):(this.params[i]=e.slice(0),this.params[i]):(this.params[i][0]=e,this.params[i]))}}var Ms=Object.defineProperty,Ps=(e,t,i)=>((e,t,i)=>t in e?Ms(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const Ts={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",45:null,60:"1h",120:"2h",180:null,240:"4h","4H":"4h","1D":"1d",D:"1d","1W":"1w",W:"1w","1M":"1M",M:"1M"};class Is{constructor(e=3e5){Ps(this,"cache"),Ps(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t}`)).join("|")}get(e){const t=this.generateKey(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.cacheDuration?(this.cache.delete(t),null):i.data:null}set(e,t){const i=this.generateKey(e);this.cache.set(i,{data:t,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){const e=Date.now();for(const[t,i]of this.cache.entries())e-i.timestamp>this.cacheDuration&&this.cache.delete(t)}}function As(e){let t;if("string"==typeof e){if(t=parseInt(e,10),isNaN(t)){const t=new Date(e);return Math.floor(t.getTime()/1e3)}}else t=e;return t.toString().length>=13?Math.floor(t/1e3):t}new class{constructor(){Ps(this,"cacheManager"),this.cacheManager=new Is(3e5)}async getMarketDataInterval(e,t,i,s){try{const n=Ts[t.toUpperCase()];if(!n)return console.error(`Unsupported timeframe: ${t}`),[];let o=[],r=i;const a=s,l={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6}[n];if(!l)return console.error(`Duration not defined for interval: ${n}`),[];for(;r({openTime:parseInt(e[0]),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),closeTime:parseInt(e[6]),quoteAssetVolume:parseFloat(e[7]),numberOfTrades:parseInt(e[8]),takerBuyBaseAssetVolume:parseFloat(e[9]),takerBuyQuoteAssetVolume:parseFloat(e[10]),ignore:e[11]})));return this.cacheManager.set(o,h),h}catch(e){return console.error("Error in binance.klines:",e),[]}}};const Ds={...t.customSeriesDefaultOptions,color:"#049981",lineWidth:1,lineStyle:t.LineStyle.Solid,shapeSize:.3,shape:"circles",join:!1,fontSize:.8};function Ls(e,t){if(e._isDecorated)return console.warn("Series is already decorated. Skipping decoration."),e;e._isDecorated=!0;const i=e.setData.bind(e),s=[];let n=null;const o=e.detachPrimitive?.bind(e),r=e.attachPrimitive?.bind(e),a=e.data?.bind(e),l=e.applyOptions?.bind(e),c=e.seriesType(),h=e.options().title;function p(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),n===e&&(n=null),o&&o(e),t&&(t.removeLegendPrimitive(e),console.log(`Removed primitive of type "${e.constructor.name}" from legend.`)))}function d(){for(console.log("Detaching all primitives.");s.length>0;){p(s.pop())}console.log("All primitives detached.")}return Object.assign(e,{applyOptions:i=>{if(l&&l(i),t&&void 0!==t._lines){const s=e.seriesType(),n=t._lines.find((t=>t.series===e));if(n&&("Candlestick"===s||"Bar"===s||"Custom"===s&&("upColor"in i||"downColor"in i)?(void 0!==i.upColor&&(n.colors[0]=i.upColor),void 0!==i.downColor&&(n.colors[1]=i.downColor)):"Line"===s||"Histogram"===s||"Custom"===s&&"color"in i?void 0!==i.color&&(n.colors[0]=i.color):"Area"===s&&void 0!==i.lineColor&&(n.colors[0]=i.lineColor),"shape"in i)){const e=(()=>{switch(i.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return i.shape}})();n.legendSymbol=e}}},setData:function(t){if(t&&Array.isArray(t)||(t=[...e.data()]),!t||0===t.length)return void i(t);const s=e.seriesType();if("Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!=s&&"Custom"!=s||!("value"in t[0])){if(("Bar"===s||"Candlestick"===s||"Custom"===s||"Ohlc"===s)&&"open"in t[0]&&t.every((e=>y(e))))return void i(t)}else if(t.every((e=>f(e))))return void i(t);let n;n="Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!==s||!("open"in t[0])?("Bar"!==s&&"Candlestick"!==s&&"Ohlc"!==s||t[0],t.map(((e,i)=>Os(t,s,i)))):t.map(((e,i)=>Os(t,s,i))),i(n)},dataType:function(t){const i=e.data()[0];if(b(i))return null;let s=f(i),n=y(i);if(!s&&!n&&"open"in i&&"high"in i&&"low"in i&&"close"in i&&(n=!0),t){const e=t.data()[0];if(b(e))return!1;let i=f(e),o=y(e);return!i&&!o&&"open"in e&&"high"in e&&"low"in e&&"close"in e&&(o=!0),s&&i||n&&o}return s||n?i:null},dataTransform:function(){const t=e.data();if(!t||0===t.length)return[];const i=t[0];let s;if(y(i)||"open"in i&&"high"in i&&"low"in i&&"close"in i)s="Line";else{if(!f(i))return[...t];s="Candlestick"}return t.map(((t,i)=>Os(e,s,i)))},primitives:s,sync:function(e){const t=e.options().seriesType??"Line",i=a();if(!i)return void console.warn("Source data is missing for synchronization.");const s=[...e.data()];for(let n=s.length;n{const i=[...a()];if(!i||0===i.length)return void console.warn("Source data is missing for synchronization.");const s=e.data().slice(-1)[0],n=i.length-1;if(!s||i[n].time>=s.time){const i=Os(e,t,n);i&&(e.update(i),console.log(`Updated/added bar via "update()" for series type ${e.seriesType}`))}}))},attachPrimitive:function(i,o,a=!0,l=!1){const c=i.constructor.type||i.constructor.name;if(a)d();else{const e=s.findIndex((e=>e.constructor.type===c));-1!==e&&p(s[e])}r&&r(i),s.push(i),n=i,console.log(`Primitive of type "${c}" attached.`),t&&l&&t.addLegendPrimitive(e,i,o)},detachPrimitive:p,detachPrimitives:d,decorated:!0,_type:c,title:h,get primitive(){return n},toJSON:()=>({options:e.options(),data:a()}),fromJSON(t){if(t.data&&i(t.data),t.options){const i=t.options;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const s=t;e.applyOptions({[s]:i[s]})}}}})}function Ns(e){const t={};switch(e){case"Line":return{...t,title:e,color:"#195200",lineWidth:2,crosshairMarkerVisible:!0};case"Histogram":return{...t,title:e,color:"#9ACF01",base:0};case"Area":return{...t,title:e,lineColor:"#021698",topColor:"rgba(9, 32, 210, 0.4)",bottomColor:"rgba(0, 0, 0, 0.5)"};case"Bar":return{...t,title:e,upColor:"#006721",downColor:"#6E0000",borderUpColor:"#006721",borderDownColor:"#6E0000"};case"Candlestick":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000"};case"Ohlc":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000",shape:"Rounded",chandelierSize:1,barSpacing:.777,lineStyle:0,lineWidth:1};case"Symbol":return{...t,...Ds,title:e};default:throw new Error(`Unsupported series type: ${e}`)}}function Os(e,t,i){let s;if(Array.isArray(e))s=e;else{if(!e||"function"!=typeof e.data)return console.warn("Invalid source provided to convertDataItem; expected an array or series object."),null;s=[...e.data()]}if(!s||0===s.length)return console.warn("No data available in the source series."),null;const n=s[i];switch(t){case"Line":case"Histogram":case"Area":case"Symbol":if(y(n))return{time:n.time,value:n.close};if(f(n))return{time:n.time,value:n.value};if(b(n))return{time:n.time};break;case"Bar":case"Candlestick":case"Ohlc":if(y(n))return{time:n.time,open:n.open,high:n.high,low:n.low,close:n.close};if(f(n))return{time:n.time,open:n.value,high:n.value,low:n.value,close:n.value};if(b(n))return{time:n.time};break;default:return console.error(`Unsupported target type: ${t}`),{time:n.time}}return console.warn("Could not convert data to the target type."),null}function Vs(e,t,i){const s=e.options(),n=t.split(".");let o=s;for(let e=0;evoid 0!==e.primitives)(e)?e:(console.log("Decorating the series dynamically."),Ls(e,t))}function Fs(e,t){const i={...e.paramMap,...t},s=[...e.sourceSeries.data()];if(!s||!Array.isArray(s)||0===s.length)return;let n;n=s.every(y)?s:s.map($s);e.indicator.calc(n,i).forEach((t=>{const i=e.figures.get(t.key);if(i&&(i.setData(t.data),i.applyOptions({title:t.title}),t.pane&&i.getPane()===e.sourceSeries.getPane())){const e=i.getPane().paneIndex();i.moveToPane(e+t.pane)}})),e.paramMap=i}function $s(e){return{time:e.time,open:e.value,high:e.value,low:e.value,close:e.value}}function Gs(e,t,i,s="Line",n="overwrite"){const{data:o,group:r,options:a,pane:l}=i,c={...js(a)};r&&(c.group=r),t&&(c.title=t);const h="circles"===c.style||"cross"===c.style?"Symbol":s;let p={...Ns(h)||{},...e.defaultsManager.get(h)||{},...c};p.style&&"line"!==p.style&&(p.shape=p.style,delete p.style);const d=o.map((e=>({...e,time:"number"==typeof e.time?As(e.time):e.time}))),u=e.seriesMap.get(t);if(u&&("overwrite"===n||"update"===n))return"update"===n?(u.update(d[d.length-1]),p={...p,...u.options()}):(u.detachPrimitives(),u.setData(d)),void u.applyOptions(p);let m=null;"Line"===s?m="line"!==c.style?e.createSymbolSeries(t,{...p,shape:c.style},l):e.createLineSeries(t,p,l):"Bar"===s?m=e.createBarSeries(t,p,l):"Candlestick"===s||"Ohlc"===s||"Custom"===s&&void 0!==o[0]?.open?m=e.createCustomOHLCSeries?e.createCustomOHLCSeries(t,p):e.createBarSeries(t,p,l):"Histogram"===s?m=e.createHistogramSeries(t,p,l):"Area"===s?m=e.createAreaSeries(t,p,l):(console.warn(`Unsupported series type: ${s}. Defaulting to Line.`),m=e.createLineSeries(t,p,l)),m.series.setData(d),e.legend&&!m.series.decorated&&(m.series=Ls(m.series,e.legend)),e.seriesMap.set(t,m.series)}function js(e){const t={};for(const i in e){const s=Array.isArray(e[i])?e[i][0]:e[i];"linewidth"===i.toLowerCase()?t.lineWidth=s:t[i]=s}return t}function Us(e,t){const{plot1:i,plot2:s,options:n}=t,o=S,r=e.seriesMap.get(i),a=e.seriesMap.get(s);if(!r)return void console.warn(`Origin series with title "${i}" not found.`);if(!a)return void console.warn(`Destination series with title "${s}" not found.`);const l=a.options().title;let c=null;r.primitives[l]?c=r.primitives[l]:(c=new _(r,a,o),r.primitives[l]=c,r.attachPrimitive(c,`Fill ➣ ${a.options().title}`,!1,!0))}function zs(e,t){const i=e.split("."),s={};let n=s;for(let e=0;ee.toUpperCase()))}function Ws(e,i,s){const n=i.timeScale(),o=s??i.addSeries(t.LineSeries);if(!o)return console.warn("No series found. Cannot perform y-axis conversions."),null;if("logical"in e){const t=e,i=n.logicalToCoordinate(t.logical),s=o.priceToCoordinate(t.price);return null===i||null===s?null:{x:i,y:s}}{const t=e,i=n.coordinateToLogical(t.x),s=n.coordinateToTime(t.x),r=o.coordinateToPrice(t.y);return null===i||null===r?null:{time:s,logical:i,price:r}}}function qs(e,t,i,s,n){const o=s-n/2,r=s+n/2;e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),e.lineTo(i,r),e.lineTo(i,o),e.closePath(),e.fill(),e.stroke()}function Xs(e,t,i,s,n,o){const r=i-t,a=o*Math.min(Math.abs(r),Math.abs(n)),l=Math.abs(Math.min(a,r/2,n/2)),c=s-n/2;e.beginPath(),"function"==typeof e.roundRect?e.roundRect(t,c,r,n,l):(e.moveTo(t+l,c),e.lineTo(i-l,c),e.quadraticCurveTo(i,c,i,c+l),e.lineTo(i,c+n-l),e.quadraticCurveTo(i,c+n,i-l,c+n),e.lineTo(t+l,c+n),e.quadraticCurveTo(t,c+n,t,c+n-l),e.lineTo(t,c+l),e.quadraticCurveTo(t,c,t+l,c)),e.closePath(),e.fill(),e.stroke()}function Js(e,t,i,s,n,o){const r=t+(i-t)/2,a=i-t;e.beginPath(),e.ellipse(r,n,Math.abs(a/2),Math.abs(o/2),0,0,2*Math.PI),e.fill(),e.stroke()}function Ys(e,t,i,s,n,o,r,a,l,h,p,d){const u=-Math.max(a,1)*(1-d),m=c(l,.666),g=c(l,.333),f=c(l,.2),y=t-r/2,b=y+a+u,v=y-u,x=b-u;let _,w,C,S;p?(_=n,w=s,C=i,S=o):(_=n,w=i,C=s,S=o),e.fillStyle=g,e.strokeStyle=h,e.beginPath(),e.rect(v,C,a+u-r/2,S-C),e.fill(),e.stroke(),e.fillStyle=f,p?(e.fillStyle=m,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke()):(e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke())}function Ks(e,t,i,s,n,o,r,a){const l=s+n/2,c=s-n/2;e.save(),e.beginPath(),a?(e.moveTo(t,l),e.lineTo(i,o),e.lineTo(i,c),e.lineTo(t,r)):(e.moveTo(t,o),e.lineTo(i,l),e.lineTo(i,r),e.lineTo(t,c)),e.closePath(),e.stroke(),e.fill(),e.restore()}function Qs(e,t,i,s,n,o,r,a,l){e.save(),e.beginPath(),l?(e.moveTo(t,a),e.lineTo(t,n+o/2),e.lineTo(s,r),e.lineTo(i,n+o/2),e.lineTo(i,a),e.lineTo(s,n-o/2),e.lineTo(t,a)):(e.moveTo(t,r),e.lineTo(t,n-o/2),e.lineTo(s,a),e.lineTo(i,n-o/2),e.lineTo(i,r),e.lineTo(s,n+o/2),e.lineTo(t,r)),e.closePath(),e.fill(),e.stroke(),e.restore()}function Zs(e,t,i,s,n,o,r){const a=(t+i)/2;e.beginPath(),e.moveTo(a,s),e.lineTo(a,n),e.stroke(),e.beginPath(),e.moveTo(t,o),e.lineTo(a,o),e.stroke(),e.beginPath(),e.moveTo(a,r),e.lineTo(i,r),e.stroke()}function en(e,t,i,s,n,o){const r=s-n/2,a=s+n/2,l=.9*Math.abs(i-t);e.save(),e.beginPath(),o?(e.moveTo(t,r),e.lineTo(t+l,r),e.lineTo(i,a),e.lineTo(i-l,a)):(e.moveTo(i-l,r),e.lineTo(i,r),e.lineTo(t+l,a),e.lineTo(t,a)),e.closePath(),e.fill(),e.stroke(),e.restore()}!function(e){e.Line="Line",e.Histogram="Histogram",e.Area="Area",e.Bar="Bar",e.Candlestick="Candlestick",e.Ohlc="Ohlc",e.Symbol="Symbol",e.Custom="Custom"}(Rs||(Rs={}));const tn={visible:!0,autoScale:!1,xScaleLock:!1,yScaleLock:!1,color:"#737375",lineWidth:1,upColor:"rgba(0,255,0,.25)",downColor:"rgba(255,0,0,.25)",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#1c9d1c",borderDownColor:"#d5160c",wickColor:"#737375",wickUpColor:"#1c9d1c",wickDownColor:"#d5160c",radius:100,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineColor:"#ffffff",width:1};class sn{handler;get data(){return this.convertAndAggregateDataPoints()}get sourceData(){return this._originalData}_originalP1;_originalP2;_barWidth=.8;p1;p2;_options;series;_originalData=[];_originalSlice=[];offset;onComplete;get spatial(){return this.recalculateSpatial()}transform={scale:{x:1,y:1},shift:{x:0,y:0}};constructor(e,t,i,s,n,o){let r,a;this.handler=e,this._options={...n,...tn},Math.min(i.logical,s.logical)===i.logical?(r=i,a=s):(r=s,a=i),this._originalP1={...r},this._originalP2={...a},this.offset=o??0,this.p1=i,this.p2=s,x(t)?(this.series=t,this._originalData=this.series.data().map(((e,t)=>({...e,x1:t,x2:t+1})))):(this.series=this.handler.series||this.handler._seriesList[0],this._originalData=t._originalData);const l=Math.min(this._originalP1.logical,this._originalP2.logical),c=Math.max(this._originalP1.logical,this._originalP2.logical);o&&o>0?(this._originalSlice=this._originalData.slice(c,Math.min(this.series.data().length-1,c+1+o)),console.log("Data Sliced with Offset",l,c,o,"Offset Point:",Math.min(this.series.data().length-1,c+1+o))):(this._originalSlice=this._originalData.slice(l,c+1),console.log("Data Sliced:",l,c)),o&&o>0&&(this._originalSlice=this._originalSlice.map((e=>({...e,x1:e.x1+o,x2:e.x2+o}))),console.log("Adjusted originalSlice with pOffset:",o)),this.transform=this.recalculateSpatial(),this.p1&&this.p2&&this.setPoints(this.p1,this.p2)}setData(e){this._originalSlice=e}setPoints(e,t){let i,s;Math.min(e.logical,t.logical)===e.logical?(i=e,s=t):(i=t,s=e),null===this._originalP1?(this._originalP1={...i},console.log("First point (p1) set:",this._originalP1)):null===this._originalP2&&(this._originalP2={...s},console.log("Second point (p2) set:",this._originalP2)),this.p1=i,this.p2=s,this.recalculateSpatial(),this.processSequence()}updatePoint(e,t){1===e?this.p1=t:2===e&&(this._originalP2||(this._originalP2=t),this.p2=t),this.recalculateSpatial(),this.processSequence()}recalculateSpatial(){if(!(this.p1&&this.p2&&this._originalP1&&this._originalP2))return console.warn("Cannot recalc spatial without valid p1/p2."),{scale:{x:1,y:1},shift:{x:0,y:0}};const e=Math.abs(this._originalP1.logical-this._originalP2.logical),t=Math.abs(this._originalP1.price-this._originalP2.price);if(0===e||0===t)return console.warn("Cannot recalc scale if original points are zero difference."),{scale:{x:1,y:1},shift:{x:0,y:0}};const i=Math.abs(this.p1.logical-this.p2.logical)/e,s=((this._originalP2.price>this._originalP1.price?this.p2.price:this.p1.price)-(this._originalP2.price>this._originalP1.price?this.p1.price:this.p2.price))/t;this._options.xScaleLock||(this.transform.scale.x=i),this._options.yScaleLock||(this.transform.scale.y=s),this._options.autoScale&&i>-1&&i<1&&(this._options.chandelierSize=Math.abs(Math.ceil(1/i)));const n={scale:{x:0!==i?Math.round(100*i)/100:1,y:0!==s?Math.round(100*s)/100:1},shift:{x:this._originalP1.logical-this.p1.logical,y:this._originalP1.price-this.p1.price}};return this._barWidth=Math.abs(this.p1.logical-this.p2.logical)/this._originalData.length,console.log("Spatial recalculated:","scaleX=",n.scale.x,"scaleY=",n.scale.y,"shiftX=",n.shift.x,"shiftY=",n.shift.y),0===n.scale.x||0===n.scale.y?(console.warn("Scale factors cannot be zero."),{scale:{x:1,y:1},shift:{x:0,y:0}}):n}processSequence(){this.p1&&this.p2?(this.convertAndAggregateDataPoints(),this.onComplete&&this.onComplete()):console.warn("Cannot process sequence without valid p1/p2.")}convertAndAggregateDataPoints(){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;const i={...this.spatial};this._originalSlice.forEach((i=>{const s=[];void 0!==i.open&&s.push(i.open),void 0!==i.high&&s.push(i.high),void 0!==i.low&&s.push(i.low),void 0!==i.close&&s.push(i.close),void 0!==i.value&&s.push(i.value);for(const i of s)it&&(t=i)}));const s=t===e?1:t-e,n=this.p1.logical,o=this._originalSlice.map(((t,o)=>{const r=n+o;function a(t,i){if(void 0===t)return;const n=(t-e)/s;return e-i.shift.y+n*i.scale.y*s}const c=a(t.open,i),h=a(t.close,i),p=a(t.high,i),d=a(t.low,i),u=a(t.value,i);if(void 0!==c||void 0!==h||void 0!==p||void 0!==d){const e=(h??0)>(c??0),i=e?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",s=e?this._options.borderUpColor||l(i,1):this._options.borderDownColor||l(i,1),n=e?this._options.wickUpColor||s:this._options.wickDownColor||s;return{open:c,close:h,high:p,low:d,isUp:e,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:{...t,x1:o},barSpacing:this._barWidth,color:i,borderColor:s,wickColor:n,lineStyle:this._options.lineStyle,lineWidth:this._options.lineWidth,shape:this._options.shape??"Rounded"}}return{value:u,isUp:void 0,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:t,barSpacing:this._options.barSpacing??.8}})),r=this._options.chandelierSize??1;if(r<=1)return o;const a=[];for(let e=0;eMath.max(e,t.high||0)),0),a=e.reduce(((e,t)=>Math.min(e,t.low||1/0)),1/0),c=o>i,h=c?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",p=c?this._options.borderUpColor||l(h,1):this._options.borderDownColor||l(h,1),d=c?this._options.wickUpColor||p:this._options.wickDownColor||p,u=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),m=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return{open:i,high:r,low:a,close:o,isUp:c,x1:s,x2:n,isInProgress:t,color:h,borderColor:p,wickColor:d,shape:this._options.shape??"Rounded",lineStyle:u,lineWidth:m}}{const t=e[0].value??0,i=(e[e.length-1].value??0)>t,o=i?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)";i?this._options.borderUpColor||l(o,1):this._options.borderDownColor||l(o,1);i?this._options.wickUpColor:this._options.wickDownColor;const r=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),a=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return this._options.shape,{value:t,isUp:i,x1:s,x2:n,color:o,lineStyle:r,lineWidth:a}}}applyOptions(e){this._options={...this._options,...e},this.processSequence()}}class nn extends a{_type="TrendTrace";_paneViews;_sequence;_options;_state=N.NONE;_handler;_source;_originalP1=null;_originalP2=null;p1=null;p2=null;_points=[];title="";static _type="Trend-Trace";_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];_hovered=!1;constructor(e,t,i,s,n,o){super(),this._handler=e,this._source=t,this._originalP1={...i},this._originalP2={...s};const r=this._source.options(),a=function(e,t){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=t[s]);return i}(tn,r);this._options={...a,...n},this._sequence=this._createSequence({p1:i,p2:s},this._options,o),this.p1=this._sequence.p1,this.p2=this._sequence.p2,this._subscribeEvents(),this._paneViews=[new on(this)]}toJSON(){return{data:this._sequence.data,p1:this._sequence._originalP1,p2:this._sequence._originalP2,options:this._sequence._options}}fromJSON(e){if(e.data&&this._sequence.setData(e.data),e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}e.p1&&(this.p1=e.p1),e.p2&&(this.p2=e.p2)}attached(e){super.attached(e),this._originalP1&&this._originalP2&&this._createSequence({p1:this._originalP1,p2:this._originalP2}),this._source=Bs(e.series,this._handler.legend),this.title=e.series.options().title;const i=new(t.defaultHorzScaleBehavior());return{chart:e.chart,series:e.series,requestUpdate:e.requestUpdate,horzScaleBehavior:i}}paneViews(){return this._paneViews}detached(){super.detached(),this._listeners.forEach((({name:e,listener:t})=>{document.body.removeEventListener(e,t)})),this._listeners=[],this._handler?.chart&&(this._handler.chart.unsubscribeCrosshairMove(this._handleMouseMove),this._handler.chart.unsubscribeClick(this._handleMouseDownOrUp)),this._paneViews=[],this._sequence=null,this._options=null,this._source=null,this._originalP1=null,this._originalP2=null,this.p1=null,this.p2=null,console.log("✅ All listeners and references successfully detached.")}_createSequence(e,t,i){let s;return"p1"in e&&"p2"in e?(s=new sn(this._handler,this._source,e.p1,e.p2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s):(s=new sn(this._handler,e.data,e.data._originalP1,e.data._originalP2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s)}applyOptions(e){this._options={...this._options,...e},this._sequence&&this._sequence.applyOptions(this._options),this.requestUpdate()}_pendingUpdate=!1;updateViewFromSequence(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),console.log("Updating view with sequence data:",this._sequence?.data),this._pendingUpdate=!1})))}getOptions(){return this._options}_subscribeEvents(){this._handler.chart.subscribeCrosshairMove(this._handleMouseMove),this._handler.chart.subscribeClick(this._handleMouseDownOrUp)}_subscribe(e,t){document.body.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.body.removeEventListener(e,t);const i=this._listeners.find((i=>i.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,nn._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),nn.hoveredObject=nn.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),nn.hoveredObject===this&&(nn.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(nn._mouseIsDown=!nn._mouseIsDown,nn._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,nn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPoint(e,1)||this._mouseIsOverPoint(e,2)||this._mouseIsOverSequence(e)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_onMouseUp(){nn._mouseIsDown=!1,this.chart.applyOptions({handleScroll:!0}),this._moveToState(N.HOVERING),this._startDragPoint=null}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e,this.series);if(!t||!this._startDragPoint)return;const i=this._getDiff(t,this._startDragPoint);this._onDrag(i),this._startDragPoint=t,this.requestUpdate()}_mouseIsOverPoint(e,t){const i=1===t?{x:this._paneViews[0]._p1.x,y:this._paneViews[0]._p1.y}:{x:this._paneViews[0]._p2.x,y:this._paneViews[0]._p2.y};return!!this.chart&&function(e,t,i,s){const n=function(e){if(!e)return null;const t=e.paneSize();return{width:t.width,height:t.height}}(s);if(!n)return!1;const o=n.width,r=n.height,a=o*i,l=r*i,c=function(e){if(e instanceof MouseEvent)return(t=e)?{x:t.x,y:t.y}:null;var t;if("point"in e&&e.point)return e.point;return null}(e);if(!c||null==c.x||null==c.y||null==t.x||null==t.y)return!1;const h=Math.abs(t.x-c.x),p=Math.abs(t.y-c.y);return h<=a&&p<=l}(e,i,.05,this.chart)}_mouseIsOverSequence(e){if(!e.logical||!e.point)return console.warn("Invalid MouseEventParams: Missing logical or point."),!1;const t=this._source.coordinateToPrice?.(e.point.y);if(null==t)return console.warn("Mouse price could not be determined."),!1;let i=e.time?this._sequence.data.find((t=>t.time===e.time)):void 0;if(i||(i=this._sequence.data.find((t=>Math.round(t.x1)===Math.round(e.logical)))),!i)return console.warn("No matching bar found for the given parameters."),!1;if(null!=i.low&&null!=i.high){const e=.05*(i.high-i.low);return t>=i.low-e&&t<=i.high+e}if(null!=i.value){const e=.05*i.value;return t>=i.value-e&&t<=i.value+e}return console.warn("Bar lacks price information."),!1}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this._sequence.p1,this._options.xScaleLock&&this._state==N.DRAGGINGP1?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP1?0:e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this._sequence.p2,this._options.xScaleLock&&this._state==N.DRAGGINGP2?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP2?0:e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<20&&Math.abs(e.y-t.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP1)):Math.abs(e.x-i.x)<20&&Math.abs(e.y-i.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP2)):(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGING))}_handleMouseDownInteraction=()=>{this._onMouseDown()};_handleMouseUpInteraction=()=>{this._onMouseUp()};_getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}}class on{_p1={x:null,y:null};_p2={x:null,y:null};_plugin;constructor(e){this._plugin=e}renderer(){if(!this._plugin._sequence)throw new Error("No sequence available for rendering.");return new rn(this._plugin,this._plugin._options,!1)}}class rn extends G{_source;_options;constructor(e,t,i){super(Ws(e._sequence.p1,e.chart,e._source),Ws(e._sequence.p2,e.chart,e._source),t,i),this._source=e,this._options=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,{chart:i}=this._source;t.save();const{horizontalPixelRatio:s}=e,n=this._source._sequence.data,o=this._source.chart.timeScale(),r=this._source._source,a=i.timeScale().getVisibleLogicalRange(),l=i.options().width/((a?.to??n.length)-(a?.from??0));if(console.log("barSpace:",l),!r||!o||0===n.length)return void t.restore();const c=n[0].x1,h=n[n.length-1].x2,p=i.timeScale().logicalToCoordinate(c)??0,d=i.timeScale().logicalToCoordinate(h)??p,u=p*s,m=d*s,g=this._source._sequence._originalP2.logical>this._source._sequence._originalP1.logical&&this._source._sequence.p2.logical>this._source._sequence.p1.logical||this._source._sequence._originalP2.logical{const i=u+(g?1:-1)*(t*((m-u)/n.length)*this._source._sequence.spatial.scale.x),s=(t+1)*((m-u)/n.length)*this._source._sequence.spatial.scale.x-(1-(this._options.barSpacing??.8))*(m-u)/n.length/(this._options.chandelierSize??1),o=e.isUp?g?this._options.upColor:this._options.downColor:g?this._options.downColor:this._options.upColor,r=e.isUp?g?this._options.borderUpColor:this._options.borderDownColor:g?this._options.borderDownColor:this._options.borderUpColor,a=e.isUp?g?this._options.wickUpColor:this._options.wickDownColor:g?this._options.wickDownColor:this._options.wickUpColor;return{...e,scaledX1:i,scaledX2:s,color:o,borderColor:r,wickColor:a}})).filter((e=>null!==e));console.log("Scaled bars:",f),this.isOHLCData(n)?(this._options.wickVisible&&this._drawWicks(e,f,l),this._drawCandles(e,f,l)):this.isSingleValueData(n)&&this._drawSingleValueData(e,f),t.restore()}))}_drawSingleValueData(e,t){const{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e;i.lineWidth=this._options.lineWidth??1,U(i,this._options.lineStyle??1),i.strokeStyle=this._options.visible?this._options.lineColor??"#ffffff":"rgba(0,0,0,0)",i.beginPath(),t.forEach((e=>{if(null===e.x1||void 0===e.x1)return;const t=e.scaledX1*s,o=(this._source._source?.priceToCoordinate(e.value??0)??0)*n;i.lineTo(t,o),i.stroke()}))}_drawWicks(e,t,i){const{context:s,verticalPixelRatio:n}=e;this._source._sequence._originalP2.price>this._source._sequence._originalP1.price&&this._source._sequence.p2.price>this._source._sequence.p1.price||this._source._sequence._originalP2.pricethis._source._sequence._originalP1.logical&&this._source._sequence.p2.price>this._source._sequence.p1.price;t[0].scaledX1,t[t.length-1].scaledX2;t.length;const r=Math.abs(i);t.forEach(((e,i)=>{const a=(this._options.barSpacing??.8)*r,l=r-a;let c=e.scaledX1,h=c+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*r-l;if(i{const o=(this._options.barSpacing??.8)*a,l=a-o;if(!e)return;const c=(this._source.series.priceToCoordinate(e.open)??0)*r,h=(this._source.series.priceToCoordinate(e.close)??0)*r,p=(this._source.series.priceToCoordinate(e.high)??0)*r,d=(this._source.series.priceToCoordinate(e.low)??0)*r,u=h>=c,m=Math.min(c,h),g=Math.max(c,h),f=m-g,y=(m+g)/2;let b=e.scaledX1-.5*a,v=b+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*a-l;if(ivoid 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))}isSingleValueData(e){return e.every((e=>void 0!==e.value))}}function an(e){let t=0;for(const i of e){if(!i||!Number.isNaN(i.value))break;t++}return t}const ln={color:"white",border:"none",padding:"5px 10px",cursor:"pointer",borderRadius:"12px",boxShadow:"0 2px 4px rgba(0,0,0,0.2)",transition:"transform 0.2s ease-in-out"};class cn{container;header;editorDiv;resizer;editorInstance=null;closeButton;isResizing=!1;startY=0;startHeight=0;MIN_HEIGHT=100;MAX_HEIGHT=window.innerHeight-50;scripts={};handler;_dataChangeHandlers=new Map;selectedSeries=null;selectedVolumeSeries=null;constructor(e){this.handler=e,this.selectedSeries=this.handler.series,this.selectedVolumeSeries=this.handler.volumeSeries??null,this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"0",width:"100%",height:"300px",backgroundColor:"#000000",borderTop:"2px solid #222",zIndex:"10000",display:"none",flexDirection:"column"}),this.resizer=document.createElement("div"),Object.assign(this.resizer.style,{height:"5px",width:"100%",backgroundColor:"#111",cursor:"ns-resize",userSelect:"none"}),this.resizer.addEventListener("mousedown",this.onDragStart.bind(this)),document.addEventListener("mousemove",this.onDrag.bind(this)),document.addEventListener("mouseup",this.onDragEnd.bind(this)),this.container.appendChild(this.resizer),this.header=document.createElement("div"),Object.assign(this.header.style,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px",backgroundColor:"#000"});const t=document.createElement("div");t.style.display="flex",t.style.alignItems="center",t.style.gap="10px";const i=document.createElement("span");i.innerText="PineTS Script Editor ",i.style.color="white",t.appendChild(i);const s=document.createElement("div");s.style.display="flex",s.style.gap="10px";const n=document.createElement("button");n.innerText="Execute",Object.assign(n.style,ln,{backgroundColor:"#2A8D08"}),n.onmouseover=()=>{n.style.transform="scale(1.05)"},n.onmouseout=()=>{n.style.transform="scale(1)"},n.onclick=()=>{this.executePineTS()},s.appendChild(n);const o=document.createElement("div");Object.assign(o.style,{display:"inline-flex",border:"1px solid #0A42FA",borderRadius:"8px",overflow:"hidden",position:"relative"});const r=document.createElement("button");r.innerText="Save",Object.assign(r.style,ln,{backgroundColor:"#0A42FA",borderRadius:"0px"}),r.onmouseover=()=>{r.style.transform="scale(1.05)"},r.onmouseout=()=>{r.style.transform="scale(1)"},r.onclick=()=>{this.saveScript()},o.appendChild(r);const a=document.createElement("button");a.innerText="🛠",Object.assign(a.style,ln,{backgroundColor:"#0A42FA",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),a.onmouseover=()=>{a.style.transform="scale(1.05)"},a.onmouseout=()=>{a.style.transform="scale(1)"},a.onclick=e=>{const t=document.getElementById("save-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="save-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#0A42FA",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Save As",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.saveToFile(),i.remove()},i.appendChild(s);const n=o.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},o.appendChild(a),s.appendChild(o);const l=document.createElement("div");Object.assign(l.style,{display:"inline-flex",border:"1px solid #AC0202",borderRadius:"8px",overflow:"hidden",position:"relative"});const c=document.createElement("button");c.innerText="Script",Object.assign(c.style,ln,{backgroundColor:"#AC0202",borderRadius:"0px"}),c.onmouseover=()=>{c.style.transform="scale(1.05)"},c.onmouseout=()=>{c.style.transform="scale(1)"},c.onclick=()=>{console.log("Current script: "+c.innerText)},l.appendChild(c);const h=document.createElement("button");h.innerText="🗄",Object.assign(h.style,ln,{backgroundColor:"#AC0202",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),h.onmouseover=()=>{h.style.transform="scale(1.05)"},h.onmouseout=()=>{h.style.transform="scale(1)"},h.onclick=e=>{const t=document.getElementById("script-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="script-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#AC0202",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});Object.keys(this.scripts).forEach((e=>{const t=document.createElement("div");t.innerText=e,t.style.padding="5px 10px",t.style.cursor="pointer",t.onclick=()=>{this.scripts[e]&&this.scripts[e].code&&(this.setValue(this.scripts[e].code),c.innerText=e,console.log(`Loaded script "${e}" from memory.`)),i.remove()},i.appendChild(t)}));const s=document.createElement("div");s.innerText="Open...",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.openScriptFromFile(),i.remove()},i.appendChild(s);const n=l.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},l.appendChild(h),s.appendChild(l);const p=document.createElement("div");Object.assign(p.style,{display:"inline-flex",border:"1px solid #696969",borderRadius:"8px",overflow:"hidden",position:"relative"});const d=document.createElement("button");d.innerText="Select Main Series",Object.assign(d.style,ln,{backgroundColor:"#696969",borderRadius:"0px"}),d.onmouseover=()=>{d.style.transform="scale(1.05)"},d.onmouseout=()=>{d.style.transform="scale(1)"},d.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)}))},p.appendChild(d);const u=document.createElement("button");u.innerText="∿",Object.assign(u.style,ln,{backgroundColor:"#696969",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),u.onmouseover=()=>{u.style.transform="scale(1.05)"},u.onmouseout=()=>{u.style.transform="scale(1)"},u.onclick=e=>{const t=document.getElementById("series-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="series-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#696969",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Select Main Series",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)})),i.remove()},i.appendChild(s);const n=document.createElement("div");n.innerText="Select Volume Series",n.style.padding="5px 10px",n.style.cursor="pointer",n.onclick=e=>{this.populateVolumeSeriesSelectMenu(e,(e=>{this.selectedVolumeSeries=e,console.log("Selected Volume Series:",e)})),i.remove()},i.appendChild(n);const o=p.getBoundingClientRect();i.style.left=o.left+"px",i.style.top=o.bottom+"px",document.body.appendChild(i)},p.appendChild(u),s.appendChild(p),t.appendChild(s),this.closeButton=document.createElement("button"),this.closeButton.innerText="Close",Object.assign(this.closeButton.style,ln,{backgroundColor:"#ff0000"}),this.closeButton.onmouseover=()=>{this.closeButton.style.transform="scale(1.05)"},this.closeButton.onmouseout=()=>{this.closeButton.style.transform="scale(1)"},this.closeButton.onclick=()=>this.close(),this.header.appendChild(t),this.header.appendChild(this.closeButton),this.container.appendChild(this.header),this.editorDiv=document.createElement("div"),Object.assign(this.editorDiv.style,{flex:"1",height:"calc(100% - 45px)"}),this.container.appendChild(this.editorDiv),document.body.appendChild(this.container),this.initializeMonaco(),this.loadInitialScript()}initializeMonaco(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e||(e="\n\n\n// * @EsIstJosh\n// * This feature implements a variation of PineTS, source : and is \n// * licensed under the GNU AGPL v3.0. V\n// * The original AGPL license text is included in the AGPL_LICENSE file in the repository.\n// * \n// * Note: This file imports modules that remain under the MIT license \n// * The original MIT license text is included in the MIT_LICENSE file in the repository.\n// *\n// * For the full text of the GNU AGPL v3.0, see .\n\n\n// * //-----------------Work in Progress...-------------------//\n// * EXAMPLE SCRIPT CONVERSION // \n// * PINE SCRIPT ⥵ //PINE TS \n// * \n// * //@version=5 ⥵ // @version=5\n// * indicator('Simple EMA','EMA', overlay=true) ⥵ indicator('Simple EMA','EMA', {overlay=true}) \n// * ⥵ \n// * ema9 = ta.ema(close, 9); ⥵ const ema9 = ta.ema(close, 9) \n// * ema18 = ta.ema(close, 18); ⥵ const ema18 = ta.ema(close, 18)\n// * plot(ema9,'EMA9', color= #ff0000, linewidth= 2, style = plot.style_line) ⥵ plot(ema9,'EMA9',{ style: 'line', color: '#ff0000', linewidth: 2 })\n// * plot(ema18,'EMA18', color= #ff7700, linewidth= 2, style = plot.style_line) ⥵ plot(ema18,'EMA18',{ style: 'line', color: '#ff7700', linewidth: 2 })\n\n\n\n indicator('Title', 'TA', { overlay : true })\n // \n const ema1 = ta.ema(close,16)\n const ema2 = ta.ema(close,32)\n const ema3 = ta.ema(close,48)\n const ema4 = ta.ema(close,64)\n const ema5 = ta.ema(close,96)\n const ema6 = ta.ema(close,128)\n plot(ema1,'EMA1',{ style: 'line', color: '#ff0000', linewidth: 2 })\n plot(ema2,'EMA2',{ style: 'cross', color: '#ff7700', linewidth: 2 })\n plot(ema3,'EMA3',{ style: 'circles', color: '#ffee00', linewidth: 2 })\n plot(ema4,'EMA4',{ style: '❖', color: '#00ff00', linewidth: 2 })\n plot(ema5,'EMA5',{ style: 'triangleUp', color: '#0050ff', linewidth: 2 })\n plot(ema6,'EMA6',{ style: 'arrowDown', color: '#ffffff', linewidth: 2 })\n\n fill('EMA1','EMA2')\n fill('EMA2','EMA3')\n fill('EMA3','EMA4')\n fill('EMA4','EMA5')\n fill('EMA5','EMA6')\n\n\n "),this.editorInstance=o.editor.create(this.editorDiv,{value:e,language:"javascript",theme:"vs-dark",automaticLayout:!0}),console.log("Monaco Editor initialized in pane with initial code.")}loadInitialScript(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e?(this.setValue(e),console.log("Loaded most recent script from scriptsManager.")):console.log("No saved scripts available in scriptsManager; editor value remains unchanged.")}open(){this.container.style.display="flex",this.editorInstance?.layout(),window.monaco=!0}close(){this.container.style.display="none",window.monaco=!1}setValue(e){this.editorInstance?.setValue(e)}getValue(){return this.editorInstance?.getValue()||""}async executePineTS(){try{const e=this.getValue(),t=/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m,i=e.match(t),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";console.log("Extracted script key:",s);const n=(this.selectedSeries??this.handler.series).options().title,o=(this.selectedVolumeSeries??this.handler.volumeSeries)?.options?.()?.title||"",r=function(e,t=[]){return e.map(((e,i)=>hn(e,t[i]))).filter((e=>null!==e))}([...(this.selectedSeries??this.handler.series).data()],[...this.selectedVolumeSeries?this.selectedVolumeSeries.data():[]]),a=new ns(r,this.handler.series.options().title,"1D"),l=`(context) => { \n \nconst { close, open, high, low, hlc3, volume, hl2, ohlc4 } = context.data;\nconst { plotchar, plot, na, indicator, nz, plotcandle, plotbar, fill} = context.core;\nconst ta = context.ta;\nconst math = context.math;\nconst input = context.input;\n\n${e}\n }`,{plots:c,candles:h,bars:p,fills:d,ta:u}=await a.run(l,void 0,!1);console.log("Plots:",c),console.log("Candles:",h),console.log("Bars:",p);let m=0;if(c)for(const e in c)if(c.hasOwnProperty(e)){Gs(this.handler,e,c[e],void 0,"overwrite");const t=c[e].data;if(Array.isArray(t)){const e=an(t);e>m&&(m=e)}}if(h)for(const e in h)h.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Candlestick","overwrite");if(p)for(const e in p)p.hasOwnProperty(e)&&Gs(this.handler,e,p[e],"Bar","overwrite");if(d)for(const e in d)d.hasOwnProperty(e)&&Us(this.handler,d[e]);this.scripts[s]={pineTSInstance:a,ohlc:n,volume:o,code:e,n:m+1};this.handler.seriesMap.get(n);this.replaceScript(s)}catch(e){console.error("Error executing PineTS code:",e)}}replaceScript(e){const t=this.scripts[e];if(!t||!t.ohlc)return void console.warn(`No series information found for script key: ${e}`);const i=t.ohlc,s=this.handler.seriesMap.get(i);if(!s)return void console.warn(`Series with title "${i}" not found.`);const n=s.data().length;if(this._dataChangeHandlers.has(e))try{const t=this._dataChangeHandlers.get(e);s.unsubscribeDataChanged(t),console.log("Unsubscribing old Data Change Handler.... Data Length:",n),this._dataChangeHandlers.delete(e)}catch(t){console.warn(`Error unsubscribing from data changes for script "${e}":`,t)}const o=t=>{try{console.log("Data Changed, updating.... Data Length:",n),this.executeSavedScript(e)}catch(t){console.error(`Error executing saved script for "${e}":`,t)}};this._dataChangeHandlers.set(e,o),s.subscribeDataChanged(o)}async executeSavedScript(e){try{const t=this.scripts[e]?.ohlc,i=this.scripts[e]?.volume,s=this.scripts[e]?.n??void 0;console.log(s);const n=t?this.handler.seriesMap.get(t):null,o=i?this.handler.seriesMap.get(i):null;if(!n)return void console.warn(`Main series with title "${n}" not found.`);const r=hn(n.dataByIndex(n.data().length-1),o?o.dataByIndex(o.data().length-1):void 0),a=this.scripts[e]?.pineTSInstance;if(!a)return void console.warn(`No saved PineTS instance found for key: ${e}`);a.updateData(r);const{plots:l,candles:c,bars:h,fills:p,ta:d}=await a.run(void 0,s,!0);if(console.log("Plots:",l),console.log("Candles:",c),console.log("Bars:",h),l)for(const e in l)l.hasOwnProperty(e)&&Gs(this.handler,e,l[e],void 0,"update");if(c)for(const e in c)l.hasOwnProperty(e)&&Gs(this.handler,e,c[e],"Candlestick","update");if(h)for(const e in h)l.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Bar","update")}catch(e){console.error("Error executing PineTS code:",e)}}saveScript(e){const t=this.getValue(),i=t.match(/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";this.scripts[s]?this.scripts[s].code=t:this.scripts[s]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script "${s}" updated in memory.`);const n=this.scripts[s],o=JSON.stringify(n,null,2),r=`save_script_~_${s};;;${o}`;window.callbackFunction(r),console.log(`Script "${s}" sent via callback.`);const a=`save_script_~_cache;;;${o}`;window.callbackFunction(a),console.log('Cache script sent via callback under the name "cache".')}async saveToFile(e){const t=this.getValue(),i=prompt("Enter a new script name/title:","MyNewScript");if(!i)return void console.warn("Save To File canceled or no name provided.");this.scripts[i]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script saved as "${i}" in memory.`);const s=JSON.stringify(this.scripts[i],null,2),n=`${i}.json`;this.downloadJson(s,n);const o=JSON.stringify(this.scripts[i],null,2);this.downloadJson(o,"cache.json")}openScriptFromFile(){const e=document.createElement("input");e.type="file",e.accept=".json",e.style.display="none",e.onchange=e=>{const t=e.target;if(t.files&&t.files.length>0){const e=t.files[0],i=new FileReader;i.onload=e=>{try{const t=e.target?.result;if("string"==typeof t){const e=JSON.parse(t);e&&e.code?(this.setValue(e.code),console.log("Loaded script from file.")):console.error("The selected file does not contain a valid script with a 'code' property.")}}catch(e){console.error("Error parsing JSON file:",e)}},i.readAsText(e)}},document.body.appendChild(e),e.click(),e.remove()}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s),console.log(`Downloaded ${t}`)}catch(e){console.error("Failed to download data: "+e)}}onDragStart(e){this.isResizing=!0,this.startY=e.clientY,this.startHeight=parseInt(window.getComputedStyle(this.container).height,10),e.preventDefault()}onDrag(e){if(!this.isResizing)return;const t=this.startHeight+(this.startY-e.clientY),i=Math.min(Math.max(t,this.MIN_HEIGHT),this.MAX_HEIGHT);this.container.style.height=`${i}px`,this.editorInstance?.layout()}onDragEnd(e){this.isResizing&&(this.isResizing=!1)}populateMainSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&n.push({label:"Volume",value:this.handler.volumeSeries}),n.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const o=document.createElement("li");o.innerText="Cancel",o.style.cursor="pointer",o.style.padding="5px",o.onclick=()=>{document.body.removeChild(i)},s.appendChild(o),i.appendChild(s),document.body.appendChild(i)}populateVolumeSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=document.createElement("li");n.innerText="None",n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(null),document.body.removeChild(i)},s.appendChild(n);const o=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&o.push({label:"Volume",value:this.handler.volumeSeries}),o.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const r=document.createElement("li");r.innerText="Cancel",r.style.cursor="pointer",r.style.padding="5px",r.onclick=()=>{document.body.removeChild(i)},s.appendChild(r),i.appendChild(s),document.body.appendChild(i)}}function hn(e,t){let i;return i="number"==typeof e.time?e.time:new Date(e.time).getTime(),isNaN(i)?(console.warn(`Invalid time format: ${e.time}`),null):{...e,openTime:i,closeTime:i+86399,volume:void 0!==e.volume?Number(e.volume):void 0!==t?Number(t.value):0}}class pn{makeButton;callbackName;div;isOpen=!1;widget;constructor(e,t,i,s,n,o){this.makeButton=e,this.callbackName=o,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");let e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";let t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{let t=this.makeButton(e,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(t.elem.innerText)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),this.widget.elem.innerText=e[0]+" ↓"}_clickHandler(e){this.widget.elem.innerText=e+" ↓",window.callbackFunction(`${this.callbackName??"undefined"}_~_${e}`),this.div.style.display="none",this.isOpen=!1}}class dn{makeButton;div;isOpen=!1;widget;globalCallback;constructor(e,t,i,s,n,o,r){this.makeButton=e,this.globalCallback=r,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");const e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";const t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{const t=this.makeButton(e.label,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(e)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),e.length>0&&(this.widget.elem.innerText=e[0].label+" ↓")}_clickHandler(e){this.widget.elem.innerText=e.label+" ↓",e.callback?e.callback():this.globalCallback?this.globalCallback(e.label):window.callbackFunction(`${e.label}`),this.div.style.display="none",this.isOpen=!1}}class un{_handler;_div;left;right;codeEditor;constructor(e){this._handler=e,this._div=document.createElement("div"),this._div.classList.add("topbar");const t=e=>{const t=document.createElement("div");return t.classList.add("topbar-container"),t.style.justifyContent=e,this._div.appendChild(t),t};this.left=t("flex-start"),this.right=t("flex-end"),this.codeEditor=new cn(this._handler),this.makeChartMenu([{label:"Add Series",callback:()=>this.openCSVFile("add")},{label:"Edit Series",callback:()=>this.openCSVFile("edit")}],"Add Series",!0,"left"),this.makeButton("{}=> ƒ",!0,!0,"right",!1,void 0,(()=>this.codeEditor.open()))}makeSwitcher(e,t,i,s="left"){const n=document.createElement("div");let o;n.style.margin="4px 12px";const r={elem:n,callbackName:i,intervalElements:e.map((e=>{const i=document.createElement("button");i.classList.add("topbar-button"),i.classList.add("switcher-button"),i.style.margin="0px 2px",i.innerText=e,e==t&&(o=i,i.classList.add("active-switcher-button"));const s=un.getClientWidth(i);return i.style.minWidth=s+1+"px",i.addEventListener("click",(()=>r.onItemClicked(i))),n.appendChild(i),i})),onItemClicked:e=>{e!=o&&(o.classList.remove("active-switcher-button"),e.classList.add("active-switcher-button"),o=e,window.callbackFunction(`${r.callbackName}_~_${e.innerText}`))}};return this.appendWidget(n,s,!0),r}makeTextBoxWidget(e,t="left",i=null){if(i){const s=document.createElement("input");return s.classList.add("topbar-textbox-input"),s.value=e,s.style.width=`${s.value.length+2}ch`,s.addEventListener("focus",(()=>{window.textBoxFocused=!0})),s.addEventListener("input",(e=>{e.preventDefault(),s.style.width=`${s.value.length+2}ch`})),s.addEventListener("keydown",(e=>{"Enter"==e.key&&(e.preventDefault(),s.blur())})),s.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${s.value}`),window.textBoxFocused=!1})),this.appendWidget(s,t,!0),s}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=e,this.appendWidget(i,t,!0),i}}makeMenu(e,t,i,s,n){return new pn(this.makeButton.bind(this),e,t,i,s,n)}makeChartMenu(e,t,i,s,n,o){return new dn(this.makeButton.bind(this),e,t,i,s,n,o)}makeButton(e,t,i=!0,s="left",n=!1,o,r){let a=document.createElement("button");a.classList.add("topbar-button"),a.innerText=e,document.body.appendChild(a),a.style.minWidth=`${a.clientWidth+1}px`,document.body.removeChild(a);let l=!1;return a.addEventListener("click",(()=>{n?(l=!l,a.style.backgroundColor=l?"var(--active-bg-color)":"",a.style.color=l?"var(--active-color)":"",o&&window.callbackFunction(`${o}_~_${l}`)):o&&window.callbackFunction(`${o}_~_${a.innerText}`),r&&r()})),i&&this.appendWidget(a,s,t),{elem:a,callbackName:o}}makeSliderWidget(e,t,i,s,n,o="left"){const r=document.createElement("div");r.classList.add("topbar-slider-container"),r.style.display="flex",r.style.alignItems="center",r.style.margin="4px 12px";const a=document.createElement("span");a.classList.add("topbar-slider-label"),a.style.marginRight="8px",a.innerText=s.toString();const l=document.createElement("input");return l.classList.add("topbar-slider"),l.type="range",l.min=e.toString(),l.max=t.toString(),l.step=i.toString(),l.value=s.toString(),l.style.cursor="pointer",l.addEventListener("input",(()=>{a.innerText=l.value,window.callbackFunction(`${n}_~_${l.value}`)})),r.appendChild(a),r.appendChild(l),this.appendWidget(r,o,!0),r}makeSeparator(e="left"){const t=document.createElement("div");t.classList.add("topbar-seperator");("left"==e?this.left:this.right).appendChild(t)}appendWidget(e,t,i){const s="left"==t?this.left:this.right;i?("left"==t&&s.appendChild(e),this.makeSeparator(t),"right"==t&&s.appendChild(e)):s.appendChild(e),this._handler.reSize()}openCSVFile(e){const t=document.createElement("input");t.type="file",t.accept=".csv",t.style.display="none",t.addEventListener("change",(t=>{const i=t.target;if(i.files&&i.files.length>0){const t=i.files[0],s=new FileReader;s.onload=i=>{const s=i.target?.result,n=this.parseCSV(s);if(0===n.length)return void alert("The CSV file is empty.");const o=["time","open","high","low","close"],r=Object.keys(n[0]);if(o.every((e=>r.includes(e))))try{if("edit"===e)this._handler.series.setData(n),console.log("Series data updated successfully.");else if("add"===e){const e=t.name.replace(/\.[^/.]+$/,"");this._handler.createCustomOHLCSeries(e,{}).series.setData(n),console.log("New series added successfully.")}}catch(e){console.error("Error updating chart data:",e)}else alert("The selected CSV does not contain all required OHLCV columns: "+o.join(", "))},s.readAsText(t)}})),document.body.appendChild(t),t.click(),document.body.removeChild(t)}parseCSV(e){const t=e.split(/\r?\n/).filter((e=>e.trim().length>0));if(0===t.length)return[];let i=t[0].split(",").map((e=>e.trim()));const s=i.map((e=>e.toLowerCase()));if(!s.includes("time"))if(s.includes("date")){const e=s.indexOf("date");i[e]="time"}else i[0]="time";return t.slice(1).map((e=>{const t=e.split(",").map((e=>e.trim())),s={};return i.forEach(((e,i)=>{const n=Number(t[i]);s[e]=isNaN(n)?t[i]:n})),s}))}static getClientWidth(e){document.body.appendChild(e);const t=e.clientWidth;return document.body.removeChild(e),t}}const mn={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class gn{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...mn,...t},this._chart=e;const i=document.createElement("div");yn(i,{display:"flex","flex-direction":"column","align-items":"center",position:"absolute",transform:"translate(calc(0px - 50%), 0px)",opacity:"0",left:"0%",top:"0","z-index":"100","background-color":"white","border-radius":"4px",padding:"5px 10px","font-family":"-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif","font-size":"12px","font-weight":"400","box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.2)","line-height":"16px","pointer-events":"none",color:"#131722"});const s=document.createElement("div");yn(s,{"font-size":"12px","line-height":"24px","font-weight":"590"}),fn(s,this._options.title),i.appendChild(s);const n=document.createElement("div");yn(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),fn(n,""),i.appendChild(n);const o=document.createElement("div");yn(o,{color:"#787B86"}),fn(o,""),i.appendChild(o);const r=document.createElement("div");yn(r,{color:"#787B86"}),fn(r,""),i.appendChild(r),this._element=i,this._titleElement=s,this._priceElement=n,this._dateElement=o,this._timeElement=r;const a=this._chart.chartElement();a.appendChild(this._element);const l=a.parentElement;if(!l)return void console.error("Chart Element is not attached to the page.");const c=getComputedStyle(l).position;"relative"!==c&&"absolute"!==c&&console.error("Chart Element position is expected be `relative` or `absolute`.")}destroy(){this._chart&&this._element&&this._chart.chartElement().removeChild(this._element)}applyOptions(e){this._options={...this._options,...e}}options(){return this._options}updateTooltipContent(e){if(!this._element)return void console.warn("Tooltip element not found.");const t=this._element.getBoundingClientRect();this._lastTooltipWidth=t.width,void 0!==e.title&&this._titleElement?(console.log(`Setting title: ${e.title}`),fn(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),fn(this._priceElement,e.price),fn(this._dateElement,e.date),fn(this._timeElement,e.time)}updatePosition(e){if(!this._chart||!this._element)return;if(this._element.style.opacity=e.visible?"1":"0",!e.visible)return;const t=this._calculateXPosition(e,this._chart),i=this._calculateYPosition(e);this._element.style.transform=`translate(${t}, ${i})`}_calculateXPosition(e,t){const i=e.paneX+t.priceScale("left").width(),s=this._lastTooltipWidth?Math.ceil(this._lastTooltipWidth/2):this._options.horizontalDeadzoneWidth;return`calc(${Math.min(Math.max(s,i),t.timeScale().width()-s)}px - 50%)`}_calculateYPosition(e){if("top"==this._options.followMode)return`${this._options.topOffset}px`;const t=e.paneY,i=t<=this._options.verticalSpacing+this._options.verticalDeadzoneHeight;return`calc(${t+(i?1:-1)*this._options.verticalSpacing}px${i?"":" - 100%"})`}}function fn(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function yn(e,t){for(const[i,s]of Object.entries(t))e.style.setProperty(i,s)}function bn(e,t,i=1,s){const n=Math.round(t*e),o=Math.round(i*t),r=function(e){return Math.floor(.5*e)}(o);return{position:n-r,length:o}}class vn{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=bn(this._data.x,e.horizontalPixelRatio,1);t.fillStyle=this._data.color,t.fillRect(i.position,this._data.topMargin*e.verticalPixelRatio,i.length,e.bitmapSize.height)}))}}class xn{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new vn(this._data)}zOrder(){return"bottom"}}const _n={lineColor:"rgba(0, 0, 0, 0.2)",priceExtractor:e=>void 0!==e.value?e.value.toFixed(2):void 0!==e.close?e.close.toFixed(2):""};class wn{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={..._n,...e},this._data.color=this._options.lineColor,this._paneViews=[new xn(this._data)]}attached(e){this._attachedParams=e;const t=this.series();if(t){const e=t.options(),i=e.lineColor||e.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i})}this._setCrosshairMode(),e.chart.subscribeCrosshairMove(this._moveHandler),this._createTooltipElement()}detached(){const e=this.chart();e&&e.unsubscribeCrosshairMove(this._moveHandler),this._hideCrosshair(),this._hideTooltip()}paneViews(){return this._paneViews}updateAllViews(){this._paneViews.forEach((e=>e.update(this._data)))}setData(e){this._data=e,this.updateAllViews(),this._attachedParams?.requestUpdate()}currentColor(){return this._options.lineColor}chart(){return this._attachedParams?.chart}series(){return this._attachedParams?.series}applyOptions(e){this._options={...this._options,...e},e.lineColor&&this.setData({...this._data,color:e.lineColor}),this._tooltip&&this._tooltip.applyOptions({...this._options.tooltip}),this._attachedParams?.requestUpdate()}_setCrosshairMode(){const e=this.chart();if(!e)throw new Error("Unable to change crosshair mode because the chart instance is undefined");e.applyOptions({crosshair:{mode:t.CrosshairMode.Magnet,vertLine:{visible:!1,labelVisible:!1},horzLine:{visible:!1,labelVisible:!1}}})}_moveHandler=e=>this._onMouseMove(e);switch(e){if(this.series()===e)return void console.log("Tooltip is already attached to this series.");this._hideCrosshair(),e.attachPrimitive(this,"Tooltip",!0,!1);const t=e.options(),i=t.lineColor||t.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i}),console.log("Switched tooltip to the new series.")}_hideCrosshair(){this._hideTooltip(),this.setData({x:0,visible:!1,color:this._options.lineColor,topMargin:0})}_hideTooltip(){this._tooltip&&(this._tooltip.updateTooltipContent({title:"",price:"",date:"",time:""}),this._tooltip.updatePosition({paneX:0,paneY:0,visible:!1}))}_onMouseMove(e){const t=this.chart(),i=this.series(),s=e.logical;if(!s||!t||!i)return void this._hideCrosshair();const n=e.seriesData.get(i);if(!n)return void this._hideCrosshair();const o=this._options.priceExtractor(n),r=t.timeScale().logicalToCoordinate(s),[a,l]=function(e){if(!e)return["",""];const t=new Date(e),i=t.getFullYear(),s=t.toLocaleString("default",{month:"short"});return[`${t.getDate().toString().padStart(2,"0")} ${s} ${i}`,`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`]}(e.time?As(e.time):void 0);if(this._tooltip){const t=i.options()?.title||"Unknown Series",s=this._tooltip.options(),n="top"===s.followMode?s.topOffset+10:0;this.setData({x:r??0,visible:null!==r,color:this._options.lineColor,topMargin:n}),this._tooltip.updateTooltipContent({title:t,price:o,date:a,time:l}),this._tooltip.updatePosition({paneX:e.point?.x??0,paneY:e.point?.y??0,visible:!0})}}_createTooltipElement(){const e=this.chart();if(!e)throw new Error("Unable to create Tooltip element. Chart not attached");this._tooltip=new gn(e,{...this._options.tooltip})}}let Cn=class e{colorOption;static colors=["#EBB0B0","#E9CEA1","#E5DF80","#ADEB97","#A3C3EA","#D8BDED","#E15F5D","#E1B45F","#E2D947","#4BE940","#639AE1","#D7A0E8","#E42C2A","#E49D30","#E7D827","#3CFF0A","#3275E4","#B06CE3","#F3000D","#EE9A14","#F1DA13","#2DFC0F","#1562EE","#BB00EF","#B50911","#E3860E","#D2BD11","#48DE0E","#1455B4","#6E009F","#7C1713","#B76B12","#8D7A13","#479C12","#165579","#51007E"];_div;saveDrawings;opacity=0;_opacitySlider;_opacityLabel;rgba;constructor(t,i){this.colorOption=i,this.saveDrawings=t,this._div=document.createElement("div"),this._div.classList.add("color-picker");let s=document.createElement("div");s.style.margin="10px",s.style.display="flex",s.style.flexWrap="wrap",e.colors.forEach((e=>s.appendChild(this.makeColorBox(e))));let n=document.createElement("div");n.style.backgroundColor=window.pane.borderColor,n.style.height="1px",n.style.width="130px";let o=document.createElement("div");o.style.margin="10px";let r=document.createElement("div");r.style.color="lightgray",r.style.fontSize="12px",r.innerText="Opacity",this._opacityLabel=document.createElement("div"),this._opacityLabel.style.color="lightgray",this._opacityLabel.style.fontSize="12px",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%",this._opacitySlider.oninput=()=>{this._opacityLabel.innerText=this._opacitySlider.value+"%",this.opacity=parseInt(this._opacitySlider.value)/100,this.updateColor()},o.appendChild(r),o.appendChild(this._opacitySlider),o.appendChild(this._opacityLabel),this._div.appendChild(s),this._div.appendChild(n),this._div.appendChild(o),window.containerDiv.appendChild(this._div)}_updateOpacitySlider(){this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%"}makeColorBox(t){const i=document.createElement("div");i.style.width="18px",i.style.height="18px",i.style.borderRadius="3px",i.style.margin="3px",i.style.boxSizing="border-box",i.style.backgroundColor=t,i.addEventListener("mouseover",(()=>i.style.border="2px solid lightgray")),i.addEventListener("mouseout",(()=>i.style.border="none"));const s=e.extractRGBA(t);return i.addEventListener("click",(()=>{this.rgba=s,this.updateColor()})),i}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number);if(!s)return[];let n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}updateColor(){if(!O.lastHoveredObject||!this.rgba)return;const e=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;O.lastHoveredObject.applyOptions({[this.colorOption]:e}),this.saveDrawings()}openMenu(t){O.lastHoveredObject&&(this.rgba=e.extractRGBA(O.lastHoveredObject._options[this.colorOption]),this.opacity=this.rgba[3],this._updateOpacitySlider(),this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="flex",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10))}closeMenu(){document.body.removeEventListener("click",this.closeMenu),this._div.style.display="none"}};class Sn{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;customColors;constructor(e,t,i){this.applySelection=t,this.rgba=Sn.extractRGBA(e),this.opacity=this.rgba[3],this.container=document.createElement("div"),this.container.classList.add("color-picker"),this.container.style.display="flex",this.container.style.flexDirection="column",this.container.style.width="200px",this.container.style.height="350px",this.container.style.position="relative";const s=this.createColorGrid(),n=this.createOpacityUI();this.exitButton=this.createExitButton(),this.customColors=i??void 0,this.container.appendChild(s),this.container.appendChild(this.createSeparator()),this.customColors&&0!==this.customColors.length&&this.createCustomColorSection(),this.container.appendChild(this.createSeparator()),this.container.appendChild(n),this.container.appendChild(this.exitButton)}createCustomColorSection(){if(!this.customColors||0===this.customColors.length)return null;const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center",e.style.margin="8px 0";const t=document.createElement("div");t.innerText="Custom Colors",t.style.fontSize="14px",t.style.color="white",e.appendChild(t);const i=document.createElement("div");i.style.display="flex",i.style.flexWrap="wrap",i.style.justifyContent="center",i.style.gap="5px";const s=e=>{const t=document.createElement("div");return t.style.width="20px",t.style.height="20px",t.style.borderRadius="4px",t.style.cursor="pointer",t.style.border="1px solid #999",t.style.backgroundColor=e,t.title=e,t.addEventListener("click",(()=>{this.updateTargetColor()})),t};this.customColors.forEach((e=>{i.appendChild(s(e))}));const n=document.createElement("div");return n.style.width="20px",n.style.height="20px",n.style.borderRadius="4px",n.style.cursor="pointer",n.style.border="1px solid #999",n.style.backgroundColor="rgba(0,0,0,0)",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",n.style.color="#999",n.style.fontSize="16px",n.innerText="+",n.title="Add custom color",n.addEventListener("click",(e=>{const t=document.createElement("input");t.type="color",t.value=this.color,t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.addEventListener("input",(()=>{this.color=t.value,this.updateTargetColor(),this.customColors.includes(this.color)||(this.customColors.push(this.color),i.appendChild(s(this.color)),this.saveColors()),document.body.removeChild(t)}),{once:!0}),t.click()})),i.appendChild(n),e.appendChild(i),e}saveColors(){const e=`save_defaults_colors_~_${JSON.stringify(this.customColors,null,2)}`;window.callbackFunction(e)}createExitButton(){const e=document.createElement("div");return e.innerText="✕",e.title="Close",e.style.position="absolute",e.style.bottom="5px",e.style.right="5px",e.style.width="20px",e.style.height="20px",e.style.cursor="pointer",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center",e.style.fontSize="16px",e.style.backgroundColor="#ccc",e.style.borderRadius="50%",e.style.color="#000",e.style.boxShadow="0 1px 3px rgba(0,0,0,0.3)",e.addEventListener("mouseover",(()=>{e.style.backgroundColor="#e74c3c",e.style.color="#fff"})),e.addEventListener("mouseout",(()=>{e.style.backgroundColor="#ccc",e.style.color="#000"})),e.addEventListener("click",(()=>{this.closeMenu()})),e}createColorGrid(){const e=document.createElement("div");e.style.display="grid",e.style.gridTemplateColumns="repeat(7, 1fr)",e.style.gap="5px",e.style.overflowY="auto",e.style.flex="1";return Sn.generateFullSpectrumColors(9).forEach((t=>{const i=this.createColorBox(t);e.appendChild(i)})),e}createColorBox(e){const t=document.createElement("div");return t.style.aspectRatio="1",t.style.borderRadius="6px",t.style.backgroundColor=e,t.style.cursor="pointer",t.addEventListener("click",(()=>{this.rgba=Sn.extractRGBA(e),this.updateTargetColor()})),t}static generateFullSpectrumColors(e){const t=[];for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(255, ${i}, 0, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, 255, 0, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(0, 255, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(0, ${i}, 255, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(${i}, 0, 255, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(255, 0, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, ${i}, ${i}, 1)`);return t}createOpacityUI(){const e=document.createElement("div");e.style.margin="10px",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center";const t=document.createElement("div");return t.style.color="lightgray",t.style.fontSize="12px",t.innerText="Opacity",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.min="0",this._opacitySlider.max="100",this._opacitySlider.value=(100*this.opacity).toString(),this._opacitySlider.style.width="80%",this._opacity_label=document.createElement("div"),this._opacity_label.style.color="lightgray",this._opacity_label.style.fontSize="12px",this._opacity_label.innerText=`${this._opacitySlider.value}%`,this._opacitySlider.oninput=()=>{this._opacity_label.innerText=`${this._opacitySlider.value}%`,this.opacity=parseInt(this._opacitySlider.value)/100,this.updateTargetColor()},e.appendChild(t),e.appendChild(this._opacitySlider),e.appendChild(this._opacity_label),e}createSeparator(){const e=document.createElement("div");return e.style.height="1px",e.style.width="100%",e.style.backgroundColor="#ccc",e.style.margin="5px 0",e}openMenu(e,t,i){this.applySelection=i,this.container.style.display="block",document.body.appendChild(this.container);const s=this.container.offsetWidth||150,n=this.container.offsetHeight||250,o=e.clientX,r=e.clientY,a=window.innerWidth,l=window.innerHeight;let c=o+t;const h=c+s>a?o-s:c,p=r+n>l?l-n-10:r;this.container.style.left=`${h}px`,this.container.style.top=`${p}px`,this.container.style.display="flex",this.container.style.position="absolute",this.exitButton.style.bottom="5px",this.exitButton.style.right="5px";const d=e=>{const t=this.container.getBoundingClientRect(),i=t.left-s,o=t.right+s,r=t.top-n,a=t.bottom+n;(e.clientXo||e.clientYa)&&(this.closeMenu(),document.removeEventListener("mousemove",d))};this.container.addEventListener("mouseenter",(()=>{document.addEventListener("mousemove",d)})),this.container.addEventListener("mouseleave",(()=>{document.removeEventListener("mousemove",d),this.closeMenu()})),document.addEventListener("mousedown",this._handleOutsideClick.bind(this),{once:!0})}closeMenu(){this.container.style.display="none",document.removeEventListener("mousedown",this._handleOutsideClick)}_handleOutsideClick(e){this.container.contains(e.target)||this.closeMenu()}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number)||[0,0,0],n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}getElement(){return this.container}update(e,t){this.rgba=Sn.extractRGBA(e),this.opacity=this.rgba[3],this.applySelection=t,this.updateTargetColor()}updateTargetColor(){this.color=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`,this.applySelection(this.color)}}class kn{static _styles=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];_div;_saveDrawings;constructor(e){this._saveDrawings=e,this._div=document.createElement("div"),this._div.classList.add("context-menu"),kn._styles.forEach((e=>{this._div.appendChild(this._makeTextBox(e.name,e.var))})),window.containerDiv.appendChild(this._div)}_makeTextBox(e,t){const i=document.createElement("span");return i.classList.add("context-menu-item"),i.innerText=e,i.addEventListener("click",(()=>{O.lastHoveredObject?.applyOptions({lineStyle:t}),this._saveDrawings()})),i}openMenu(e){this._div.style.top=e.top-30+"px",this._div.style.left=e.right+"px",this._div.style.display="block",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10)}closeMenu(){document.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}const En={visible:!0,sections:0,upColor:void 0,downColor:void 0,borderUpColor:void 0,borderDownColor:void 0,rightSide:!0,width:0,lineColor:"#ffffff",lineStyle:t.LineStyle.Solid,drawGrid:!0,gridWidth:1,gridColor:"rgba(255, 255, 255, 0.125)",gridLineStyle:t.LineStyle.SparseDotted};class Mn extends a{p1;p2;_listeners=[];visibleRange=null;_originalData;_currentSlice=null;_vpData;_paneViews;_options;_pendingUpdate=!1;_state=N.NONE;_latestHoverPoint=null;_startDragPoint=null;static _mouseIsDown=!1;_hovered=!1;chart_;series_;constructor(e,t=En,i,s){super(),this.chart_=e.chart,this.series_=e.series;const n=this.series_.data(),o=e.volumeSeries.data(),r=this.chart_.timeScale();this.visibleRange=r.getVisibleLogicalRange(),i&&s?(this.p1=i,this.p2=s):(this.p1={time:null,logical:this.visibleRange?.from??0,price:0},this.p2={time:null,logical:this.visibleRange?.to??this.series.data().length-1,price:0}),this._options={...En,...t},o.length>0&&o.every((e=>"value"in e))?this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:o[t]?.value||0}))):(console.warn('[ProfileProcessor] volumeData is empty or missing "value" property.'),this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:0})))),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this._paneViews=[new Pn(this)],this._subscribeEvents(),this.update()}_handleDomMouseDown=()=>{};_handleDomMouseUp=()=>{this._onMouseUp()};_subscribe(e,t){document.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.removeEventListener(e,t);const i=this._listeners.findIndex((i=>i.name===e&&i.listener===t));-1!==i&&this._listeners.splice(i,1)}_subscribeEvents(){this.p1&&this.p2&&this.p1.time&&this.p2.time?(this.chart_.subscribeCrosshairMove(this._handleMouseMove),this.chart_.subscribeClick(this._handleMouseDownOrUp),this._listeners.push({name:"crosshairMove",listener:this._handleMouseMove},{name:"click",listener:this._handleMouseDownOrUp})):(this.chart_.timeScale().subscribeVisibleLogicalRangeChange(this._handleVisibleLogicalRangeChange),this._listeners.push({name:"visibleLogicalRangeChange",listener:this._handleVisibleLogicalRangeChange}))}_handleVisibleLogicalRangeChange=()=>{const e=this.chart_.timeScale();if(this.visibleRange=e.getVisibleLogicalRange(),!this.visibleRange||!this.series_)return void console.warn("[VolumeProfile] Visible range or source series is undefined.");this.p1={time:null,logical:this.visibleRange.from??0,price:0},this.p2={time:null,logical:this.visibleRange.to??this.series_.data().length-1,price:0},this.sliceData();const t=this.calculateVolumeProfile();t?(this._vpData=t,this.updateAllViews(),this.requestUpdate()):console.warn("[VolumeProfile] Failed to process Volume Profile data on visible range change.")};_handleMouseMove=e=>{const t=this._eventToPoint(e);this._latestHoverPoint=t,Mn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPointCanvas(e,1)||this._mouseIsOverPointCanvas(e,2)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_handleMouseDownOrUp=()=>{Mn._mouseIsDown=!Mn._mouseIsDown,Mn._mouseIsDown?this._onMouseDown():this._onMouseUp(),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()};_onMouseDown(){if(this._startDragPoint=this._latestHoverPoint,!this._startDragPoint||!this.p1||!this.p2)return;const e=this._mouseIsOverPointRaw(this._startDragPoint,this.p1),t=this._mouseIsOverPointRaw(this._startDragPoint,this.p2);e?this._moveToState(N.DRAGGINGP1):t?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_onMouseUp(){Mn._mouseIsDown=!1,this._startDragPoint=null,this._moveToState(N.HOVERING),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e);if(!t||!this._startDragPoint)return;const i={logical:t.logical-this._startDragPoint.logical,price:t.price-this._startDragPoint.price};this._onDrag(i),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update(),this._startDragPoint=t}_onDrag(e){this.p1&&this.p2&&(this._state===N.DRAGGING?(this._addDiffToPoint(this.p1,e.logical,e.price),this._addDiffToPoint(this.p2,e.logical,e.price)):this._state===N.DRAGGINGP1?this._addDiffToPoint(this.p1,e.logical,e.price):this._state===N.DRAGGINGP2&&this._addDiffToPoint(this.p2,e.logical,e.price),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update())}_addDiffToPoint(e,t,i){e.logical=e.logical+t,e.price=e.price+i}_mouseIsOverPointRaw(e,t){if(!e)return!1;return Math.abs(e.logical-t.logical)<1&&Math.abs(e.price-t.price)<1}_mouseIsOverPointCanvas(e,t){if(!e.point||!this.p1||!this.p2)return!1;const i=Ws(1===t?this.p1:this.p2,this.chart_,this.series_),s=e.point.x-i.x,n=e.point.y-i.y;return s*s+n*n<100}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._subscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.DRAGGING:case N.DRAGGINGP1:case N.DRAGGINGP2:document.body.style.cursor="grabbing",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._subscribe("mouseup",this._handleDomMouseUp)}this._state=e,this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_eventToPoint(e){if(!e.point||null==e.logical)return null;const t=this.series_.coordinateToPrice(e.point.y);return null==t?null:{time:e.time??null,logical:e.logical,price:t.valueOf()}}sliceData(){if(!this.p1||!this.p2)return;const e=Math.min(this.p1.logical,this.p2.logical),t=Math.max(this.p1.logical,this.p2.logical);this._currentSlice=this._originalData.slice(Math.max(0,e),Math.min(t+1,this._originalData.length-1))}calculateDynamicSections(e,t,i){if(e<=0||i<=t)return 10;const s=e/20,n=(i-t)/5,o=2*Math.max(1,Math.floor(Math.max(s,n)));return Math.max(5,o)}calculateVolumeProfile(){const e=Math.min(this.visibleRange.to,this._originalData.length-1)-Math.max(this.visibleRange.from,0);let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const s=[];let n;if(this._currentSlice&&this._currentSlice.length>0){for(const e of this._currentSlice){const s=e.close??e.open;void 0!==s&&(t=Math.min(t,s),i=Math.max(i,s))}t!==Number.POSITIVE_INFINITY&&i!==Number.NEGATIVE_INFINITY||(t=0,i=1);let o=void 0!==this._options.sections&&this._options.sections>0?this._options.sections:this.calculateDynamicSections(e,t,i);const r=(i===t?1:i-t)/o;for(let e=0;e=i&&t=(e.open??0),i=e.volume||0;t?o+=i:a+=i}}const c=o>=a,h=c?this._options.upColor??l(this.series_.options().upColor,.1)??"rgba(0,128,0,0.1)":this._options.downColor??l(this.series_.options().downColor,.1)??"rgba(128,0,0,0.1)",p=c?this._options.borderUpColor??l(this.series_.options().upColor,.5)??"rgba(0,128,0,0.66)":this._options.borderDownColor??l(this.series_.options().downColor,.5)??"rgba(128,0,0,0.66)";s.push({price:i,upData:o,downData:a,color:this._options.visible?h:"rgba(0,0,0,0)",borderColor:this._options.visible?p:"rgba(0,0,0,0)",minPrice:i,maxPrice:n})}n=this._options.rightSide?this._currentSlice[this._currentSlice.length-1].time:this._currentSlice[0].time}else n=Date.now().toString();return this.update(),{time:n,profile:s,width:this._options.width??20,visibleRange:this.visibleRange}}update(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),this.updateAllViews(),console.log("VolumeProfile updated p1=",this.p1,"p2=",this.p2),this._pendingUpdate=!1})))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}autoscaleInfo(){return this._vpData.profile.length?{priceRange:{minValue:this._vpData.profile[0].minPrice,maxValue:this._vpData.profile[this._vpData.profile.length-1].maxPrice}}:null}applyOptions(e){this._options={...this._options,...e},this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}}class Pn{_source;_x=null;_width=0;_items=[];_maxVolume;visibleRange=null;_p1={x:null,y:null};_p2={x:null,y:null};constructor(e){this._source=e,this._maxVolume=this._source._vpData.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0)}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source._vpData,t=this._source.chart_,i=this._source.series_,s=t.timeScale();this._x=s.timeToCoordinate(e.time)??null;const n=s.options().barSpacing??1,o=Math.max(0,Math.min(this._source.p1.logical,this._source.p2.logical)),r=Math.min(Math.max(this._source.p1.logical,this._source.p2.logical),this._source._originalData.length-1);if(this._width=(e.width&&0!==e.width?e.width:(r-o)/3)*n,this._p1=Ws(this._source.p1,t,i),this._p2=Ws(this._source.p2,t,i),this._items=[],e.profile.length){this._maxVolume=e.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0);for(const t of e.profile){const e=i.priceToCoordinate(t.maxPrice),s=i.priceToCoordinate(t.minPrice);if(null==e||null==s){this._items.push({y1:null,y2:null,combinedWidth:0,upWidth:0,downWidth:0,color:t.color,borderColor:t.borderColor});continue}const n=t.upData+t.downData,o=this._maxVolume>0?this._width*(n/this._maxVolume):0;let r=0,a=0;n>0&&(r=t.upData/n*o,a=t.downData/n*o),this._items.push({y1:e,y2:s,combinedWidth:o,upWidth:r,downWidth:a,color:t.color,borderColor:t.borderColor})}}}renderer(){return new Tn({x:this._x,width:this._width,items:this._items,visibleRange:{from:this._source.chart.timeScale().logicalToCoordinate(Math.max(0,this._source.visibleRange.from)),to:this._source.chart.timeScale().logicalToCoordinate(Math.min(this._source.series.data().length-1,this._source.visibleRange.to))},maxVolume:this._maxVolume,maxBars:this._source.series.data().length},this._p1,this._p2,this._source._options,!1)}zOrder(){return"bottom"}}class Tn extends G{_data;options;p1;p2;constructor(e,t,i,s,n){super(t,i,s,n),this._data=e,this.options=s,this.p1=t,this.p2=i}draw(){}drawBackground(e){console.log(`[VolumeProfileRenderer] draw() called with rightSide: ${this.options.rightSide}`),e.useBitmapCoordinateSpace((e=>{let t=e.context;this._drawGrid(t,e),U(t,this.options.lineStyle),this._data.items.forEach((i=>{if(null===i.y1||null===i.y2)return;if(null===this._data.x)return;const s=Math.min(i.y1,i.y2)*e.verticalPixelRatio,n=Math.abs(i.y2-i.y1)*e.verticalPixelRatio,o=i.upWidth+i.downWidth,r=o*e.horizontalPixelRatio;let a;a=this.options.rightSide?(this._data.x-o)*e.horizontalPixelRatio:this._data.x*e.horizontalPixelRatio;const l=Math.min(Math.max(.25*n,2),25);if(n>0){t.beginPath(),this._drawRoundedRect(t,a,s,r,n,l),t.strokeStyle=i.borderColor,t.lineWidth=1,t.stroke();const c=Math.max(i.upWidth,i.downWidth)*e.horizontalPixelRatio;let h;h=this.options.rightSide?a+(o-c):a,t.beginPath(),this._drawRoundedRect(t,h,s,c,n,l),t.fillStyle=i.color,t.fill()}}))}))}_drawGrid(e,i){const{items:s,x:n}=this._data;if(!s||0===s.length||null===n)return;if(!this.options.drawGrid)return;let o;o=void 0!==this.options.gridWidth&&1!==this.options.gridWidth?this.options.gridWidth*i.horizontalPixelRatio:(this._data.visibleRange.to-this._data.visibleRange.from)*i.horizontalPixelRatio,e.strokeStyle=this.options.visible?this.options.gridColor||"rgba(255, 255, 255, 0.2)":"rgba(0,0,0,0)",U(e,this.options.gridLineStyle||t.LineStyle.Solid),s.forEach((t=>{if(null===t.y1||null===t.y2)return;const s=(t.upWidth+t.downWidth)*i.horizontalPixelRatio;let r,a;this.options.rightSide?(r=n-o,a=n-s):(r=n+s,a=n+o);const l=t.y1*i.verticalPixelRatio,c=t.y2*i.verticalPixelRatio;e.beginPath(),e.moveTo(r,l),e.lineTo(a,l),e.stroke(),e.beginPath(),e.moveTo(r,c),e.lineTo(a,c),e.stroke()}))}_drawRoundedRect(e,t,i,s,n,o){const r=Math.abs(Math.min(o,s/2,n/2));e.beginPath(),s>0&&o>0&&(this.options.rightSide?(e.moveTo(t+r,i),e.lineTo(t+s,i),e.lineTo(t+s,i+n),e.lineTo(t+r,i+n),e.arcTo(t,i+n,t,i+n-r,r),e.lineTo(t,i+r),e.arcTo(t,i,t+r,i,r)):(e.moveTo(t,i),e.lineTo(t+s-r,i),e.arcTo(t+s,i,t+s,i+r,r),e.lineTo(t+s,i+n-r),e.arcTo(t+s,i+n,t+s-r,i+n,r),e.lineTo(t,i+n),e.lineTo(t,i)),e.closePath())}}function In(e,t){if(e.length0){let t=e[0];s[0]=t;for(let n=1;n0===i?0:t-e[i-1])),s=i.map((e=>Math.max(e,0))),n=i.map((e=>Math.max(-e,0))),o=An(s,t),r=An(n,t);return 0===r?100:0===o?0:100-100/(1+o/r)}function Ln(e,t,i){for(let s=0;s=o?t:i}}function Nn(e,t,i){const s=e&&t in e?e[t]:i;return Array.isArray(s)?s.map((e=>Number(e))):[Number(s)]}function On(e,t){return t{if(o1?`_${t+1}`:""),d="ALMA"+i+(l>1?` #${t+1}`:"");c.push({key:p,title:d,type:"line",data:h})}return c}},Rn=(e,t)=>{let i=0;return e.forEach((e=>{const s=e.close-t;i+=s*s})),Math.sqrt(i/e.length)},Bn={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=Nn(t,"multiplier",this.paramMap.multiplier.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(l+=t.close,i>=r-1){const s=l/r,n=e.slice(i-(r-1),i+1),o=Rn(n,s);c.push({time:t.time,value:s+a*o}),h.push({time:t.time,value:s}),p.push({time:t.time,value:s-a*o}),l-=e[i-(r-1)].close}else c.push({time:t.time,value:NaN}),h.push({time:t.time,value:NaN}),p.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:`boll_up${d}`,title:`BOLL_UP${r}${d}`,type:"line",data:c}),o.push({key:`boll_mid${d}`,title:`BOLL_MID${r}${d}`,type:"line",data:h}),o.push({key:`boll_dn${d}`,title:`BOLL_DN${r}${d}`,type:"line",data:p})}return o}},Fn={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[];e.forEach(((i,s)=>{if(r+=i.close,s===t-1)o=r/t;else if(s>t-1){const e=2/(t+1);o=(i.close-o)*e+o}s>=t-1?(a.push({time:i.time,value:o}),r-=e[s-(t-1)].close):a.push({time:i.time,value:NaN})}));const l="ema"+(i.length>1?`_${n+1}`:""),c="EMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},$n={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="HH"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Gn={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=e.map((e=>e.close)),n=[];return i.forEach(((t,o)=>{const r=[];e.forEach(((e,i)=>{if(ie+t),0),r=(s*i.reduce(((e,t,i)=>e+i*t),0)-n*o)/(s*(s*(s-1)*(2*s-1)/6)-n*n);return(o-r*n)/s+r*(s-1)}(s.slice(i-(t-1),i+1),t,0);r.push({time:e.time,value:n})}));const a="linreg"+(i.length>1?`_${o+1}`:""),l="LINREG"+t+(i.length>1?` #${o+1}`:"");n.push({key:a,title:l,type:"line",data:r})})),n}},jn={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="LL"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Un={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close));n.sort(((e,t)=>e-t));const r=Math.floor(n.length/2),a=n.length%2==0?(n[r-1]+n[r])/2:n[r];o.push({time:i.time,value:a})}));const r="median"+(i.length>1?`_${n+1}`:""),a="Median"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},zn={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;e.forEach(((i,s)=>{if(r+=i.close,s>=t-1){const n=r/t;o.push({time:i.time,value:n}),r-=e[s-(t-1)].close}else o.push({time:i.time,value:NaN})}));const a="ma"+(i.length>1?`_${n+1}`:""),l="MA"+t+(i.length>1?` #${n+1}`:"");s.push({key:a,title:l,type:"line",data:o})})),s}},Hn={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=1/t;let r=0;const a=[];e.forEach(((e,t)=>{r=0===t?e.close:o*e.close+(1-o)*r,a.push({time:e.time,value:r})}));const l="rma"+(i.length>1?`_${n+1}`:""),c="RMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},Wn={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Nn(t,"n",this.paramMap.n.defaultValue),s=Nn(t,"k",this.paramMap.k.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{l+=t.close,i>=r-1?(c=i===r-1?l/r:(t.close*a+c*(r-a))/r,l-=e[i-(r-1)].close,h.push({time:t.time,value:c})):h.push({time:t.time,value:NaN})}));const p="sma"+(n>1?`_${t+1}`:""),d="SMA"+r+","+a+(n>1?` #${t+1}`:"");o.push({key:p,title:d,type:"line",data:h})}return o}},qn={name:"Stop and Reverse",shortName:"SAR",shouldOhlc:!0,paramMap:{accStart:{defaultValue:[.02],type:"numberArray"},accStep:{defaultValue:[.02],type:"numberArray"},accMax:{defaultValue:[.2],type:"numberArray"}},calc(e,t){const i=Nn(t,"accStart",this.paramMap.accStart.defaultValue),s=Nn(t,"accStep",this.paramMap.accStep.defaultValue),n=Nn(t,"accMax",this.paramMap.accMax.defaultValue),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{0!==i?(1===i&&(u=t.close>e[0].close,p=u?t.high:t.low,d=u?e[0].low:e[0].high,m.push({time:e[0].time,value:d})),d+=h*(p-d),u?t.lowp&&(p=t.high,h=Math.min(h+l,c)):t.high>d?(u=!0,d=p,h=a,p=t.high):t.low1?`_${t+1}`:""),f="SAR"+a+","+l+","+c+(o>1?` #${t+1}`:"");r.push({key:g,title:f,type:"line",data:m})}return r}},Xn={name:"Super Trend",shortName:"SuperTrend",shouldOhlc:!0,paramMap:{factor:{defaultValue:[3],type:"numberArray"},atrPeriod:{defaultValue:[10],type:"numberArray"}},calc(e,t){const i=Nn(t,"factor",this.paramMap.factor.defaultValue),s=Nn(t,"atrPeriod",this.paramMap.atrPeriod.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(id||e[i-1].closep?m:p),u=isNaN(h)?1:h===p?t.close>m?-1:1:t.close1?`_${t+1}`:"";o.push({key:"superTrend"+m,title:"SuperTrend"+r+(n>1?` #${t+1}`:""),type:"line",data:l}),o.push({key:"direction"+m,title:"Direction"+(n>1?` #${t+1}`:""),type:"line",data:c})}return o}},Jn={name:"Symmetrically Weighted Moving Average",shortName:"SWMA",shouldOhlc:!1,paramMap:{window:{defaultValue:[4],type:"numberArray"}},calc(e,t){const i=Nn(t,"window",this.paramMap.window.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="SWMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Yn={name:"TRIX",shortName:"TRIX",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},m:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Nn(t,"n",this.paramMap.n.defaultValue),s=Nn(t,"m",this.paramMap.m.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{p+=e.close,t===r-1?l=p/r:t>r-1&&(l=(2*e.close+(r-1)*l)/(r+1)),t>=r-1&&(t===2*r-2?c=l:t>2*r-2&&(c=(2*l+(r-1)*c)/(r+1)));let i=NaN;if(t>=2*r-2)if(t===3*r-3)h=c;else if(t>3*r-3){const e=h;h=(2*c+(r-1)*e)/(r+1),i=(h-e)/e*100}if(d.push({time:e.time,value:i}),g.push(i),m+=isNaN(i)?0:i,g.length>a){const e=g[g.length-1-a];m-=isNaN(e)?0:e}const s=g.length>=a&&!isNaN(i)?m/a:NaN;u.push({time:e.time,value:s})}));const f=n>1?`_${t+1}`:"";o.push({key:"trix"+f,title:"TRIX"+r+(n>1?` #${t+1}`:""),type:"line",data:d}),o.push({key:"maTrix"+f,title:n>1?`MATRIX #${t+1}`:"MATRIX",type:"line",data:u})}return o}},Kn={name:"Volume Weighted Average Price",shortName:"VWAP",shouldOhlc:!0,paramMap:{anchorInterval:{defaultValue:[1],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwap",title:"VWAP",type:"line",data:[]}];const s=Nn(t,"anchorInterval",this.paramMap.anchorInterval.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((e,s)=>{s%t==0&&(r=0,a=0);const n=i[s]?.value??0,o=(e.high+e.low+e.close)/3;a+=o*n,r+=n;const c=0!==r?a/r:NaN;l.push({time:e.time,value:c})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwap"+c,title:"VWAP"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Qn={name:"Volume Weighted Moving Average",shortName:"VWMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"}},calc(e,t,i){if(!i)return[{key:"vwma",title:"VWMA",type:"line",data:[]}];const s=Nn(t,"length",this.paramMap.length.defaultValue),n=[];return s.forEach(((t,o)=>{let r=0,a=0;const l=[];e.forEach(((s,n)=>{const o=i[n]?.value??0;if(r+=s.close*o,a+=o,n>=t-1){const o=0!==a?r/a:NaN;l.push({time:s.time,value:o});const c=i[n-(t-1)].value??0;r-=e[n-(t-1)].close*c,a-=c}else l.push({time:s.time,value:NaN})}));const c=s.length>1?`_${o+1}`:"";n.push({key:"vwma"+c,title:"VWMA"+t+(s.length>1?` #${o+1}`:""),type:"line",data:l})})),n}},Zn={name:"Weighted Moving Average",shortName:"WMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[9],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"wma"+r,title:"WMA"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o})})),s}},eo={name:"High & Low",shortName:"HHLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Nn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[],r=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"hh"+a,title:"HH"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o}),s.push({key:"ll"+a,title:"LL"+t+(i.length>1?` #${n+1}`:""),type:"line",data:r})})),s}},to=[Vn,Bn,Fn,$n,eo,Gn,jn,Un,zn,Hn,Wn,qn,Xn,Jn,Yn,Kn,Qn,Zn],io={name:"Awesome Oscillator",shortName:"AO",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:[5],type:"numberArray",min:1,max:100},longPeriod:{defaultValue:[34],type:"numberArray",min:1,max:200}},calc(e,t){const i=Nn(t,"shortPeriod",[5]),s=Nn(t,"longPeriod",[34]),n=Math.max(i.length,s.length),o=[];for(let r=0;r{const s=(t.high+t.low)/2;h+=s,p+=s;let n=NaN,o=NaN;if(i>=a-1){n=h/a;const t=(e[i-(a-1)].high+e[i-(a-1)].low)/2;h-=t}if(i>=l-1){o=p/l;const t=(e[i-(l-1)].high+e[i-(l-1)].low)/2;p-=t}let r=NaN;i>=c-1&&(r=n-o),d.push({time:t.time,value:r})}));const u="ao"+(n>1?`_${r+1}`:""),m="AO"+On(i,r)+(n>1?` #${r+1}`:"");Ln(d,t?.upColor??"green",t?.downColor??"red"),o.push({key:u,title:m,type:"histogram",data:d,pane:1})}return o}},so={name:"Average True Range",shortName:"ATR",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;const a=[];e.forEach(((i,s)=>{if(0===s)return void o.push({time:i.time,value:NaN});const n=e[s-1].close,l=Math.max(i.high-i.low,Math.abs(i.high-n),Math.abs(i.low-n));a.push(l),r+=l,a.length>t&&(r-=a.shift());const c=a.length>=t?r/t:NaN;o.push({time:i.time,value:c})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"atr"+l,title:"ATR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},no={name:"Bias",shortName:"BIAS",shouldOhlc:!0,paramMap:{period1:{defaultValue:[6],type:"numberArray",min:1,max:999},period2:{defaultValue:[12],type:"numberArray",min:1,max:999},period3:{defaultValue:[24],type:"numberArray",min:1,max:999}},calc(e,t){const i=Nn(t,"period1",[6]),s=Nn(t,"period2",[12]),n=Nn(t,"period3",[24]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t0)),c=a.map(((e,i)=>({key:`bias${i+1}`+(o>1?`_${t+1}`:""),title:`BIAS${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{const s=t.close;a.forEach(((n,o)=>{if(l[o]+=s,i>=n-1){const r=l[o]/n,a=(s-r)/r*100;c[o].data.push({time:t.time,value:a}),l[o]-=e[i-(n-1)].close}else c[o].data.push({time:t.time,value:NaN})}))})),r.push(...c)}return r}},oo={name:"Buy-Ratio Analysis",shortName:"BRAR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0,a=0,l=0;const c=[],h=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i;if(a+=i.high-i.open,l+=i.open-i.low,o+=i.high-n.close,r+=n.close-i.low,s>=t-1){const n=0!==r?o/r*100:0,p=0!==l?a/l*100:0;c.push({time:i.time,value:n}),h.push({time:i.time,value:p});const d=e[s-(t-1)],u=s-t>=0?e[s-t]:d;o-=d.high-u.close,r-=u.close-d.low,a-=d.high-d.open,l-=d.open-d.low}else c.push({time:i.time,value:NaN}),h.push({time:i.time,value:NaN})}));const p=i.length>1?`_${n+1}`:"";s.push({key:"br"+p,title:"BR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1}),s.push({key:"ar"+p,title:"AR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:h,pane:1})})),s}},ro={name:"Bull and Bear Index",shortName:"BBI",shouldOhlc:!0,paramMap:{p1:{defaultValue:[3],type:"numberArray",min:1},p2:{defaultValue:[6],type:"numberArray",min:1},p3:{defaultValue:[12],type:"numberArray",min:1},p4:{defaultValue:[24],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[3]),s=Nn(t,"p2",[6]),n=Nn(t,"p3",[12]),o=Nn(t,"p4",[24]),r=Math.max(i.length,s.length,n.length,o.length),a=[];for(let t=0;t{const s=t.close;if(d.forEach(((t,n)=>{u[n]+=s,i>=t-1&&(m[n]=u[n]/t,u[n]-=e[i-(t-1)].close)})),i>=Math.max(...d)-1){const e=(m[0]+m[1]+m[2]+m[3])/4;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}));const f=r>1?`_${t+1}`:"";a.push({key:"bbi"+f,title:"BBI"+[l,c,h,p].join(",")+(r>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return a}},ao={name:"Commodity Channel Index",shortName:"CCI",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[20]),s=[];return i.forEach(((t,n)=>{let o=0;const r=[],a=[];e.forEach(((i,s)=>{const n=(i.high+i.low+i.close)/3;if(o+=n,r.push(n),s>=t-1){const l=o/t;let c=0;for(let e=s-(t-1);e<=s;e++)c+=Math.abs(r[e]-l);const h=c/t,p=0!==h?(n-l)/(.015*h):0;a.push({time:i.time,value:p});const d=(e[s-(t-1)].high+e[s-(t-1)].low+e[s-(t-1)].close)/3;o-=d}else a.push({time:i.time,value:NaN})}));const l=i.length>1?`_${n+1}`:"";s.push({key:"cci"+l,title:"CCI"+t+(i.length>1?` #${n+1}`:""),type:"line",data:a,pane:1})})),s}},lo={name:"Current Ratio",shortName:"CR",shouldOhlc:!0,paramMap:{length:{defaultValue:[26],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"length",[26]),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[],l=[],c=[];e.forEach(((i,s)=>{const n=s-1>=0?e[s-1]:i,h=(n.high+n.low)/2,p=Math.max(0,i.high-h),d=Math.max(0,h-i.low);o+=p,r+=d,a.push(p),l.push(d);let u=NaN;s>=t-1&&(u=0!==r?o/r*100:0,o-=a[s-(t-1)],r-=l[s-(t-1)]),c.push({time:i.time,value:u})}));const h=i.length>1?`_${n+1}`:"";s.push({key:"cr"+h,title:"CR"+t+(i.length>1?` #${n+1}`:""),type:"line",data:c,pane:1})})),s}},co={name:"Difference of Moving Average",shortName:"DMA",shouldOhlc:!0,paramMap:{n1:{defaultValue:[10],type:"numberArray",min:1},n2:{defaultValue:[50],type:"numberArray",min:1},m:{defaultValue:[10],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n1",[10]),s=Nn(t,"n2",[50]),n=Nn(t,"m",[10]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{p+=t.close,d+=t.close;let s=NaN,n=NaN;if(i>=a-1&&(s=p/a,p-=e[i-(a-1)].close),i>=l-1&&(n=d/l,d-=e[i-(l-1)].close),i>=h-1){const e=s-n;if(f.push(e),m.push({time:t.time,value:e}),u+=e,f.length>c){u-=f[f.length-1-c];const e=u/c;g.push({time:t.time,value:e})}else g.push({time:t.time,value:NaN})}else m.push({time:t.time,value:NaN}),g.push({time:t.time,value:NaN})}));const y=o>1?`_${t+1}`:"";r.push({key:"dma"+y,title:"DMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1}),r.push({key:"ama"+y,title:"AMA"+a+"-"+l+(o>1?` #${t+1}`:""),type:"line",data:g,pane:1})}return r}},ho={name:"Directional Movement Index",shortName:"DMI",shouldOhlc:!0,paramMap:{n:{defaultValue:[14],type:"numberArray",min:1},mm:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[14]),s=Nn(t,"mm",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.high-s.high,o=s.low-t.low,y=Math.max(t.high-t.low,Math.abs(t.high-s.close),Math.abs(s.close-t.low));let b=0,v=0;n>0&&n>o&&(b=n),o>0&&o>n&&(v=o),0===i?(l=y,c=b,h=v):(l=(l*(r-1)+y)/r,c=(c*(r-1)+b)/r,h=(h*(r-1)+v)/r);let x=NaN,_=NaN;0!==l&&(x=c/l*100,_=h/l*100),u.push({time:t.time,value:x}),m.push({time:t.time,value:_});let w=NaN;if(isNaN(x)||isNaN(_)||x+_===0||(w=Math.abs(_-x)/(_+x)*100),i1?`_${t+1}`:"";o.push({key:"pdi"+y,title:"PDI"+r+(n>1?` #${t+1}`:""),type:"line",data:u,pane:1}),o.push({key:"mdi"+y,title:"MDI"+r+(n>1?` #${t+1}`:""),type:"line",data:m,pane:1}),o.push({key:"adx"+y,title:"ADX"+r+(n>1?` #${t+1}`:""),type:"line",data:g,pane:1}),o.push({key:"adxr"+y,title:"ADXR"+r+(n>1?` #${t+1}`:""),type:"line",data:f,pane:1})}return o}},po={name:"Momentum",shortName:"MTM",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r],n=t.close-s.close;l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"mtm"+d,title:"MTM"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maMtm"+d,title:"MAMTM"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},uo={name:"Psychological Line",shortName:"PSY",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{const s=i-1>=0?e[i-1]:t,n=t.close>s.close?1:0;if(c.push(n),l+=n,i>=r-1){const e=l/r*100;p.push({time:t.time,value:e}),u.push(e),h+=e,u.length>a&&(h-=u[u.length-1-a]);const s=u.length>=a?h/a:NaN;d.push({time:t.time,value:s}),l-=c[i-(r-1)]}else p.push({time:t.time,value:NaN}),d.push({time:t.time,value:NaN})}));const m=n>1?`_${t+1}`:"";o.push({key:"psy"+m,title:"PSY"+r+(n>1?` #${t+1}`:""),type:"line",data:p,pane:1}),o.push({key:"maPsy"+m,title:"MAPSY"+r+(n>1?` #${t+1}`:""),type:"line",data:d,pane:1})}return o}},mo={name:"Rate of Change",shortName:"ROC",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray",min:1},m:{defaultValue:[6],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[12]),s=Nn(t,"m",[6]),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(i>=r){const s=e[i-r].close;let n=0;0!==s&&(n=(t.close-s)/s*100),l.push({time:t.time,value:n}),p.push(n),h+=n,p.length>a&&(h-=p[p.length-1-a]);const o=p.length>=a?h/a:NaN;c.push({time:t.time,value:o})}else l.push({time:t.time,value:NaN}),c.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:"roc"+d,title:"ROC"+r+(n>1?` #${t+1}`:""),type:"line",data:l,pane:1}),o.push({key:"maRoc"+d,title:"MAROC"+r+(n>1?` #${t+1}`:""),type:"line",data:c,pane:1})}return o}},go={name:"RSI + SMA",shortName:"RSI_SMA",shouldOhlc:!0,paramMap:{p1:{defaultValue:[14],type:"numberArray",min:1},p2:{defaultValue:[21],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[14]),s=Nn(t,"p2",[10]),n=Math.max(i.length,s.length),o=e.map((e=>e.close)),r=[];for(let t=0;t{const i=Dn(o.slice(0,t+1),a);c.push(i);const s=In(c,l);h.push({time:e.time,value:i}),p.push({time:e.time,value:s})}));const d=n>1?`_${t+1}`:"",u={key:`rsi${d}`,title:`RSI(${a})${d}`,type:"line",data:h,pane:1},m={key:`smaOfRsi${d}`,title:`SMA(${l}) of RSI(${a})${d}`,type:"line",data:p,pane:1};r.push(u,m)}return r}},fo={name:"Stochastic",shortName:"KDJ",shouldOhlc:!0,paramMap:{n:{defaultValue:[9],type:"numberArray",min:1},kPeriod:{defaultValue:[3],type:"numberArray",min:1},dPeriod:{defaultValue:[3],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"n",[9]),s=Nn(t,"kPeriod",[3]),n=Nn(t,"dPeriod",[3]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{if(ie.high))),o=Math.min(...s.map((e=>e.low))),r=n===o?100:(t.close-o)/(n-o)*100,g=((l-1)*h+r)/l,f=((c-1)*p+g)/c,y=3*g-2*f;d.push({time:t.time,value:g}),u.push({time:t.time,value:f}),m.push({time:t.time,value:y}),h=g,p=f}));const g=o>1?`_${t+1}`:"";r.push({key:"k"+g,title:"K"+a+(o>1?` #${t+1}`:""),type:"line",data:d,pane:1}),r.push({key:"d"+g,title:"D"+a+(o>1?` #${t+1}`:""),type:"line",data:u,pane:1}),r.push({key:"j"+g,title:"J"+a+(o>1?` #${t+1}`:""),type:"line",data:m,pane:1})}return r}},yo={name:"Variance",shortName:"Variance",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length;o.push({time:i.time,value:a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"variance"+r,title:"Variance"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},bo={name:"Williams %R",shortName:"WR",shouldOhlc:!0,paramMap:{p1:{defaultValue:[6],type:"numberArray",min:1},p2:{defaultValue:[10],type:"numberArray",min:1},p3:{defaultValue:[14],type:"numberArray",min:1}},calc(e,t){const i=Nn(t,"p1",[6]),s=Nn(t,"p2",[10]),n=Nn(t,"p3",[14]),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t({key:`wr${i+1}`+(o>1?`_${t+1}`:""),title:`WR${e}`+(o>1?` #${t+1}`:""),type:"line",data:[],pane:1})));e.forEach(((t,i)=>{a.forEach(((s,n)=>{if(i>=s-1){let o=-1/0,r=1/0;for(let t=i-(s-1);t<=i;t++)o=Math.max(o,e[t].high),r=Math.min(r,e[t].low);const a=o!==r?(t.close-o)/(o-r)*100:0;l[n].data.push({time:t.time,value:a})}else l[n].data.push({time:t.time,value:NaN})}))})),r.push(...l)}return r}},vo={name:"Change",shortName:"Change",shouldOhlc:!0,paramMap:{length:{defaultValue:[1],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[1]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:"";s.push({key:"change"+r,title:"Change"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},xo={name:"Range",shortName:"Range",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.high))),a=Math.min(...n.map((e=>e.low)));o.push({time:i.time,value:r-a})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"range"+r,title:"Range"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},_o={name:"Standard Deviation",shortName:"StdDev",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray",min:1,max:100}},calc(e,t){const i=Nn(t,"length",[14]),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close)),r=n.reduce(((e,t)=>e+t),0)/n.length,a=n.reduce(((e,t)=>e+Math.pow(t-r,2)),0)/n.length,l=Math.sqrt(a);o.push({time:i.time,value:l})}));const r=i.length>1?`_${n+1}`:"";s.push({key:"stdDev"+r,title:"StdDev"+t+(i.length>1?` #${n+1}`:""),type:"line",data:o,pane:1})})),s}},wo={name:"Moving Average Convergence Divergence",shortName:"MACD",shouldOhlc:!0,paramMap:{shortPeriod:{defaultValue:12,type:"number",min:1},longPeriod:{defaultValue:26,type:"number",min:1},signalPeriod:{defaultValue:9,type:"number",min:1}},calc(e,t){const i=function(e,t){const i={};for(const[s,n]of Object.entries(e.paramMap)){const e=t?.[s]??n.defaultValue;i[s]=e}return i}(this,t),s=i.shortPeriod,n=i.longPeriod,o=i.signalPeriod;let r=0,a=0,l=0,c=0,h=0;const p=[],d=[],u=[];let m=0;e.forEach(((e,t)=>{m+=e.close,t===s-1?r=m/s:t>s-1&&(r=(2*e.close+(s-1)*r)/(s+1)),t===n-1?a=m/n:t>n-1&&(a=(2*e.close+(n-1)*a)/(n+1)),t>=Math.max(s,n)-1?(l=r-a,p.push({time:e.time,value:l}),h+=l,p.length===o?c=h/o:p.length>o&&(c=(2*l+(o-1)*c)/(o+1)),p.length>=o?(d.push({time:e.time,value:c}),u.push({time:e.time,value:2*(l-c)})):(d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))):(p.push({time:e.time,value:NaN}),d.push({time:e.time,value:NaN}),u.push({time:e.time,value:NaN}))}));return Ln(u,t?.upColor??"green",t?.downColor??"red"),[{key:"dif",title:"DIF",type:"line",data:p,pane:1},{key:"dea",title:"DEA",type:"line",data:d,pane:1},{key:"macd",title:"MACD",type:"histogram",data:u,pane:1}]}},Co=[...to,...[io,so,no,oo,ro,ao,lo,co,ho,po,wo,uo,mo,go,fo,yo,bo,vo,xo,_o]];class So{contextMenu;handler;container;currentTab="options";constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler,this.container=this.contextMenu.div}openMenu(e,t,i){const s={type:i||e._type||e.constructor.name,object:e.toJSON(),title:e.title},n=JSON.stringify(s,null,2);let o={};e instanceof Ro?o=e.chart.options():void 0!==e.options?o="function"==typeof e.options?e.options():e.options:void 0!==e._options&&(o=e._options);const r={...o},a=JSON.stringify(r,null,2),l=document.createElement("div");l.style.position="fixed",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.backgroundColor="rgba(0, 0, 0, 0.5)",l.style.display="flex",l.style.justifyContent="center",l.style.alignItems="center",l.style.zIndex="1000";const c=e=>{"Escape"===e.key&&this.close(l,c)};document.addEventListener("keydown",c);const h=document.createElement("div");h.style.backgroundColor="#333",h.style.color="#fff",h.style.padding="20px",h.style.borderRadius="8px",h.style.width="80%",h.style.maxWidth="800px",h.style.maxHeight="90%",h.style.overflowY="auto",h.style.boxShadow="0 2px 10px rgba(0,0,0,0.5)",h.setAttribute("tabindex","-1"),h.focus();const p=document.createElement("div");p.style.display="flex",p.style.borderBottom="1px solid #555",p.style.marginBottom="10px";const d=document.createElement("button");d.textContent="Options",d.style.flex="1",d.style.padding="10px",d.style.cursor="pointer",d.style.border="none",d.style.backgroundColor="options"===this.currentTab?"#555":"#333",d.onclick=()=>{this.currentTab="options",d.style.backgroundColor="#555",u.style.backgroundColor="#333",g.value=a,v.style.display="flex",f.style.display="none"};const u=document.createElement("button");u.textContent="Full",u.style.flex="1",u.style.padding="10px",u.style.cursor="pointer",u.style.border="none",u.style.backgroundColor="full"===this.currentTab?"#555":"#333",u.onclick=()=>{this.currentTab="full",u.style.backgroundColor="#555",d.style.backgroundColor="#333",g.value=n,f.style.display="flex",v.style.display="none"},p.appendChild(d),p.appendChild(u),h.appendChild(p);const m=document.createElement("h2");m.textContent=`Export/Import ${e.title} Data`,h.appendChild(m);const g=document.createElement("textarea");g.value="full"===this.currentTab?n:a,g.style.width="100%",g.style.height="400px",g.style.marginTop="10px",g.style.marginBottom="10px",g.style.resize="vertical",g.style.backgroundColor="#444",g.style.color="#fff",g.setAttribute("aria-label","JSON Data Editor"),h.appendChild(g);const f=document.createElement("div");f.style.display="full"===this.currentTab?"flex":"none",f.style.flexWrap="wrap",f.style.justifyContent="flex-end",f.style.gap="10px";const y=document.createElement("button");y.textContent="Export",y.style.padding="8px 12px",y.style.cursor="pointer",y.style.backgroundColor="#f44336",y.style.color="#fff",y.style.border="none",y.style.borderRadius="4px",y.onclick=()=>{this.downloadJson(n,`${e.title}_full.json`)},f.appendChild(y);const b=document.createElement("button");b.textContent="Import",b.style.padding="8px 12px",b.style.cursor="pointer",b.style.backgroundColor="#4CAF50",b.style.color="#fff",b.style.border="none",b.style.borderRadius="4px",b.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.object)throw new Error("Invalid structure: missing 'object'.");e.fromJSON(t.object),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Whole data imported successfully.","success")}catch(e){this.showNotification("Failed to import whole data: "+e.message,"error")}},f.appendChild(b);const v=document.createElement("div");v.style.display="options"===this.currentTab?"flex":"none",v.style.flexWrap="wrap",v.style.justifyContent="flex-end",v.style.gap="10px";const x=document.createElement("button");x.textContent="Export Options",x.style.padding="8px 12px",x.style.cursor="pointer",x.style.backgroundColor="#f44336",x.style.color="#fff",x.style.border="none",x.style.borderRadius="4px",x.onclick=()=>{this.downloadJson(a,`${e.title}_options.json`)},v.appendChild(x);const _=document.createElement("button");_.textContent="Import Options",_.style.padding="8px 12px",_.style.cursor="pointer",_.style.backgroundColor="#4CAF50",_.style.color="#fff",_.style.border="none",_.style.borderRadius="4px",_.onclick=()=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.style.display="none",t.addEventListener("change",(()=>{if(t.files&&t.files.length>0){const i=t.files[0],s=new FileReader;s.onload=()=>{try{const t=s.result;if("string"!=typeof t)throw new Error("File content is not a string.");g.value=t;const i=JSON.parse(t);if("object"!=typeof i||!i.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(i.options),"function"==typeof e.updateView&&e.updateView(),this.showNotification("Options imported successfully.","success")}catch(e){this.showNotification("Failed to import options: "+e.message,"error")}},s.readAsText(i)}})),t.click()},v.appendChild(_);const w=document.createElement("button");w.textContent="Save",w.style.padding="8px 12px",w.style.cursor="pointer",w.style.backgroundColor="#008CBA",w.style.color="#fff",w.style.border="none",w.style.borderRadius="4px",w.onclick=()=>{try{const t=JSON.parse(g.value);if("object"!=typeof t||!t.options)throw new Error("Invalid structure: missing 'options'.");e.fromJSON(t),"function"==typeof e.updateView&&e.updateView();JSON.stringify(t,null,2);this.showNotification("Options applied and exported successfully.","success")}catch(e){this.showNotification("Failed to save options: "+e.message,"error")}};const C=document.createElement("button");C.textContent="Save as Default",C.style.padding="8px 12px",C.style.cursor="pointer",C.style.backgroundColor="#008CBA",C.style.color="#fff",C.style.border="none",C.style.borderRadius="4px",C.onclick=()=>{let t={};e instanceof Ro?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2);let s;if(e._type&&"custom/custom"===e._type.toLowerCase()){if(s=prompt("Enter save key (e.g., area, line, candlestick):",e.title.toLowerCase())||"",!s)return}else s=e._type?e._type.toLowerCase():e.title.toLowerCase();const n=`save_defaults_~_${s};;;${i}`;window.callbackFunction(n)},this.container.appendChild(C);const S=document.createElement("div");S.style.display="flex",S.style.flexDirection="column",S.style.gap="10px",S.appendChild(f),S.appendChild(v),S.appendChild(w),S.appendChild(C),h.appendChild(S),l.appendChild(h),this.container.appendChild(l)}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s)}catch(e){this.showNotification("Failed to download data: "+e,"error")}}addSaveDefaultButton(e){const t=document.createElement("button");t.textContent="Save as Default",t.style.padding="8px 12px",t.style.cursor="pointer",t.style.backgroundColor="#008CBA",t.style.color="#fff",t.style.border="none",t.style.borderRadius="4px",t.onclick=()=>{let t={};e instanceof Ro?t=e.chart.options():"function"==typeof e.options?t=e.options():void 0!==e.options?t=e.options:void 0!==e._options&&(t=e._options);const i=JSON.stringify(t,null,2),s=prompt("Enter save key (area, line, trend-trace, candlestick etc):",e.title.toLowerCase());if(!s)return;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n)},this.container.appendChild(t)}close(e,t){e.parentElement&&e.parentElement.removeChild(e),document.removeEventListener("keydown",t)}showNotification(e,t){const i=document.createElement("div");i.textContent=e,i.style.position="fixed",i.style.bottom="20px",i.style.right="20px",i.style.padding="10px 20px",i.style.borderRadius="4px",i.style.color="#fff",i.style.backgroundColor="success"===t?"#4CAF50":"#f44336",i.style.boxShadow="0 2px 6px rgba(0,0,0,0.2)",i.style.zIndex="1001",i.style.opacity="0",i.style.transition="opacity 0.5s ease-in-out",this.container.appendChild(i),setTimeout((()=>{i.style.opacity="1"}),100),setTimeout((()=>{i.style.opacity="0",setTimeout((()=>{i.parentElement&&i.parentElement.removeChild(i)}),500)}),3e3)}openDefaultOptions(e){const t=this.handler.defaultsManager;if(!t)return void this.showNotification("No defaults manager found.","error");const i=t.get(e);if(!i)return void this.showNotification(`No default config found for key: "${e}"`,"error");JSON.stringify(i,null,2);const s=document.createElement("div");Object.assign(s.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",display:"flex",justifyContent:"center",alignItems:"center",zIndex:"1000"});const n=e=>{"Escape"===e.key&&this.close(s,n)};document.addEventListener("keydown",n);const o=document.createElement("div");Object.assign(o.style,{backgroundColor:"#333",color:"#fff",padding:"20px",borderRadius:"8px",width:"80%",maxWidth:"800px",maxHeight:"90%",overflowY:"auto",boxShadow:"0 2px 10px rgba(0,0,0,0.5)"}),o.setAttribute("tabindex","-1"),o.focus();const r=document.createElement("h2");r.textContent=`Edit Default Options - "${e}"`,o.appendChild(r);const a=document.createElement("textarea");a.value=JSON.stringify(i,null,2),Object.assign(a.style,{width:"100%",height:"400px",resize:"vertical",backgroundColor:"#444",color:"#fff",border:"none",margin:"10px 0",padding:"10px"}),o.appendChild(a);const l=document.createElement("div");Object.assign(l.style,{display:"flex",flexWrap:"wrap",gap:"10px",justifyContent:"flex-end"});const c=document.createElement("button");c.textContent="Export",Object.assign(c.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#f44336",color:"#fff",border:"none",borderRadius:"4px"}),c.onclick=()=>{this.downloadJson(a.value,`${e}_defaults.json`)},l.appendChild(c);const h=document.createElement("button");h.textContent="Import",Object.assign(h.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#4CAF50",color:"#fff",border:"none",borderRadius:"4px"}),h.onclick=()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.style.display="none",e.addEventListener("change",(()=>{if(e.files&&e.files.length>0){const t=e.files[0],i=new FileReader;i.onload=()=>{try{if("string"!=typeof i.result)throw new Error("File content is not a string.");a.value=i.result}catch(e){this.showNotification("Failed to read defaults file: "+e.message,"error")}},i.readAsText(t)}})),e.click()},l.appendChild(h);const p=document.createElement("button");p.textContent="Save",Object.assign(p.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#008CBA",color:"#fff",border:"none",borderRadius:"4px"}),p.onclick=()=>{try{const t=JSON.parse(a.value),i=JSON.stringify(t,null,2);let s=e;const n=`save_defaults_${s}_~_${i}`;window.callbackFunction(n),this.showNotification(`Defaults for "${s}" saved successfully.`,"success")}catch(e){this.showNotification("Failed to save defaults: "+e.message,"error")}},l.appendChild(p);const d=document.createElement("button");d.textContent="Cancel",Object.assign(d.style,{padding:"8px 12px",cursor:"pointer",backgroundColor:"#444",color:"#fff",border:"none",borderRadius:"4px"}),d.onclick=()=>{this.close(s,n)},l.appendChild(d),o.appendChild(l),s.appendChild(o),this.container.appendChild(s)}}class ko{container;backdrop;isOpen=!1;categories=[];contentArea;activeCategoryId="";handler;colorPicker=null;_originalOpacities={};constructor(e){this.handler=e;const t=Array.isArray(this.handler.defaultsManager.get("colors"))?[...this.handler.defaultsManager.get("colors")]:[];this.colorPicker=new Sn("#ff0000",(()=>null),t&&0!==t.length?t:void 0),this.backdrop=document.createElement("div"),Object.assign(this.backdrop.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.5)",opacity:"0",transition:"opacity 0.3s ease",zIndex:"9998",display:"none"}),this.backdrop.addEventListener("click",(e=>{e.target===this.backdrop&&this.close(!1)})),document.body.appendChild(this.backdrop),this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"700px",maxWidth:"90%",height:"500px",maxHeight:"90%",backgroundColor:"#1E1E1E",color:"#FFF",borderRadius:"6px",boxShadow:"0 2px 10px rgba(0,0,0,0.8)",zIndex:"9999",opacity:"0",display:"none",transition:"opacity 0.3s ease, transform 0.3s ease"}),document.body.appendChild(this.container);const i=document.createElement("div");Object.assign(i.style,{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #3C3C3C",backgroundColor:"#2B2B2B"});const s=document.createElement("div");Object.assign(s.style,{fontSize:"16px",fontWeight:"bold"}),s.innerText="Settings",i.appendChild(s);const n=document.createElement("div");Object.assign(n.style,{fontSize:"20px",cursor:"pointer",userSelect:"none"}),n.innerText="×",n.onclick=()=>this.close(!1),i.appendChild(n),this.container.appendChild(i);const o=document.createElement("div");Object.assign(o.style,{display:"flex",flex:"1 1 auto",height:"calc(100% - 50px)",backgroundColor:"#1E1E1E"}),this.container.appendChild(o);const r=document.createElement("div");Object.assign(r.style,{width:"180px",borderRight:"1px solid #3C3C3C",display:"flex",flexDirection:"column",backgroundColor:"#2B2B2B"}),o.appendChild(r),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",padding:"16px",overflowY:"auto"}),o.appendChild(this.contentArea);const a=document.createElement("div");Object.assign(a.style,{borderTop:"1px solid #3C3C3C",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",backgroundColor:"#2B2B2B"});const l=document.createElement("button");Object.assign(l.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),l.innerText="Template ▾",a.appendChild(l);const c=document.createElement("div");Object.assign(c.style,{display:"flex",gap:"8px"});const h=document.createElement("button");Object.assign(h.style,{backgroundColor:"#444",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),h.innerText="Cancel",h.onclick=()=>this.close(!1),c.appendChild(h);const p=document.createElement("button");Object.assign(p.style,{backgroundColor:"#008CBA",color:"#FFF",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:"pointer",fontSize:"14px"}),p.innerText="Ok",p.onclick=()=>this.close(!0),c.appendChild(p),a.appendChild(c),this.container.appendChild(a),this.categories=[{id:"series-colors",label:"Series Colors",buildContent:()=>this.buildSeriesColorsTab()},{id:"primitive-colors",label:"Primitives Colors",buildContent:()=>this.buildPrimitivesTab()},{id:"layout-options",label:"Layout Options",buildContent:()=>this.buildLayoutOptionsTab()},{id:"grid-options",label:"Grid Options",buildContent:()=>this.buildGridOptionsTab()},{id:"crosshair-options",label:"Crosshair Options",buildContent:()=>this.buildCrosshairOptionsTab()},{id:"time-scale-options",label:"Time Scale",buildContent:()=>this.buildTimeScaleOptionsTab()},{id:"price-scale-options",label:"Price Scale",buildContent:()=>this.buildPriceScaleOptionsTab()},{id:"defaults-list",label:"Defaults",buildContent:()=>this.buildDefaultsListTab()},{id:"source-code",label:"source-code",buildContent:()=>this.buildSourceCodeTab()}],this.categories.forEach((e=>{const t=document.createElement("div");t.innerText=e.label,Object.assign(t.style,{padding:"12px 16px",cursor:"pointer",borderBottom:"1px solid #3C3C3C",userSelect:"none",transition:"background-color 0.2s"}),t.addEventListener("mouseenter",(()=>{t.style.backgroundColor="#3A3A3A"})),t.addEventListener("mouseleave",(()=>{t.style.backgroundColor=""})),t.addEventListener("click",(()=>this.switchCategory(e.id))),r.appendChild(t)})),this.categories.length>0&&(this.buildSeriesColorsTab(),this.switchCategory(this.categories[0].id))}open(){this.isOpen||(this.isOpen=!0,this.backdrop.style.display="block",setTimeout((()=>{this.backdrop.style.opacity="1"}),10),this.container.style.display="block",setTimeout((()=>{this.container.style.opacity="1",this.container.style.transform="translate(-50%, -50%) scale(1)"}),10),this.buildSeriesColorsTab())}close(e){e?console.log("Settings Modal: OK clicked. Save changes here."):console.log("Settings Modal: Cancel clicked."),this.isOpen=!1,this.backdrop.style.opacity="0",this.container.style.opacity="0",this.container.style.transform="translate(-50%, -50%) scale(0.95)",setTimeout((()=>{this.isOpen||(this.backdrop.style.display="none",this.container.style.display="none")}),300)}switchCategory(e){this.activeCategoryId=e,this.contentArea.innerHTML="";const t=this.categories.find((t=>t.id===e));t&&t.buildContent()}buildLayoutOptionsTab(){const e=document.createElement("div");e.innerText="Layout Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("layout.textColor")||"#000000";this.addColorPicker("Text Color",i,(e=>{this.handler.chart.applyOptions({layout:{textColor:e}})}));const s=this.handler.chart.options().layout?.background;if(s&&"solid"===s.type){const e=s.color||"#FFFFFF";this.addColorPicker("Background Color",e,(e=>{this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.Solid,color:e}}})}))}else if(s&&s.type===t.ColorType.VerticalGradient){let e=s.topColor||"rgba(255,0,0,0.33)",i=s.bottomColor||"rgba(0,255,0,0.33)";this.addColorPicker("Top Color",e,(e=>{i=s.bottomColor||"rgba(0,255,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})})),this.addColorPicker("Bottom Color",i,(i=>{e=s.topColor||"rgba(255,0,0,0.33)",this.handler.chart.applyOptions({layout:{background:{type:t.ColorType.VerticalGradient,topColor:e,bottomColor:i}}})}))}else console.warn("Unknown background type.");const n=document.createElement("button");n.innerText="Switch Background Type",n.style.marginTop="12px",n.onclick=()=>this.toggleBackgroundType(),this.contentArea.appendChild(n)}buildGridOptionsTab(){const e=document.createElement("div");e.innerText="Grid Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.getCurrentOptionValue("grid.vertLines.color")||"#D6DCDE";this.addColorPicker("Vertical Line Color",i,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{color:e}}})}));const s=this.getCurrentOptionValue("grid.horzLines.color")||"#D6DCDE";this.addColorPicker("Horizontal Line Color",s,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{color:e}}})}));const n={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted};this.addDropdown("Vertical Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{vertLines:{style:t}}})})),this.addDropdown("Horizontal Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=n[e];this.handler.chart.applyOptions({grid:{horzLines:{style:t}}})}));const o=!1!==this.getCurrentOptionValue("grid.vertLines.visible");this.addCheckbox("Show Vertical Lines",o,(e=>{this.handler.chart.applyOptions({grid:{vertLines:{visible:e}}})}));const r=!1!==this.getCurrentOptionValue("grid.horzLines.visible");this.addCheckbox("Show Horizontal Lines",r,(e=>{this.handler.chart.applyOptions({grid:{horzLines:{visible:e}}})}))}buildCrosshairOptionsTab(){const e=document.createElement("div");e.innerText="Crosshair Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i={Solid:t.LineStyle.Solid,Dotted:t.LineStyle.Dotted,Dashed:t.LineStyle.Dashed,LargeDashed:t.LineStyle.LargeDashed,SparseDotted:t.LineStyle.SparseDotted},s=this.getCurrentOptionValue("crosshair.vertLine.style")||"Solid",n=this.getCurrentOptionValue("crosshair.horzLine.style")||"Solid",o=this.getCurrentOptionValue("crosshair.mode")||"Normal";this.addDropdown("Crosshair Mode",["Normal","Magnet","Hidden"],(e=>{this.handler.chart.applyOptions({crosshair:{mode:e}})}),o);const r=Array.from({length:10},((e,t)=>(t+1).toString())),a=(this.getCurrentOptionValue("crosshair.vertLine.width")||"1").toString();this.addDropdown("Vertical Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{vertLine:{width:t}}})}),a),this.addDropdown("Vertical Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{vertLine:{style:t}}})}),s);const l=this.getCurrentOptionValue("crosshair.vertLine.color")||"#C3BCDB44";this.addColorPicker("Vertical Line Color",l,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{color:e}}})}));const c=this.getCurrentOptionValue("crosshair.vertLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Vertical Label Background",c,(e=>{this.handler.chart.applyOptions({crosshair:{vertLine:{labelBackgroundColor:e}}})})),(this.getCurrentOptionValue("crosshair.horzLine.width")||"1").toString(),this.addDropdown("Horizontal Line Width",r,(e=>{const t=parseInt(e,10);this.handler.chart.applyOptions({crosshair:{horzLine:{width:t}}})})),this.addDropdown("Horizontal Crosshair Line Style",["Solid","Dashed","Dotted","LargeDashed"],(e=>{const t=i[e];this.handler.chart.applyOptions({crosshair:{horzLine:{style:t}}})}),n);const h=this.getCurrentOptionValue("crosshair.horzLine.color")||"#9B7DFF";this.addColorPicker("Horizontal Line Color",h,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{color:e}}})}));const p=this.getCurrentOptionValue("crosshair.horzLine.labelBackgroundColor")||"#9B7DFF";this.addColorPicker("Horizontal Label Background",p,(e=>{this.handler.chart.applyOptions({crosshair:{horzLine:{labelBackgroundColor:e}}})}))}buildTimeScaleOptionsTab(){const e=document.createElement("div");e.innerText="Time Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const t=this.getCurrentOptionValue("timeScale.rightOffset")||0;this.addNumberField("Right Offset",t,(e=>{this.handler.chart.applyOptions({timeScale:{rightOffset:e}})}));const i=this.getCurrentOptionValue("timeScale.barSpacing")||10;this.addNumberField("Bar Spacing",i,(e=>{this.handler.chart.applyOptions({timeScale:{barSpacing:e}})}));const s=this.getCurrentOptionValue("timeScale.minBarSpacing")||.1;this.addNumberField("Min Bar Spacing",s,(e=>{this.handler.chart.applyOptions({timeScale:{minBarSpacing:e}})}));const n=this.getCurrentOptionValue("timeScale.fixLeftEdge")||!1;this.addCheckbox("Fix Left Edge",n,(e=>{this.handler.chart.applyOptions({timeScale:{fixLeftEdge:e}})}));const o=this.getCurrentOptionValue("timeScale.fixRightEdge")||!1;this.addCheckbox("Fix Right Edge",o,(e=>{this.handler.chart.applyOptions({timeScale:{fixRightEdge:e}})}));const r=this.getCurrentOptionValue("timeScale.lockVisibleTimeRangeOnResize")||!1;this.addCheckbox("Lock Visible Range on Resize",r,(e=>{this.handler.chart.applyOptions({timeScale:{lockVisibleTimeRangeOnResize:e}})}));const a=this.getCurrentOptionValue("timeScale.visible");this.addCheckbox("Time Scale Visible",!1!==a,(e=>{this.handler.chart.applyOptions({timeScale:{visible:e}})}));const l=this.getCurrentOptionValue("timeScale.borderVisible");this.addCheckbox("Border Visible",!1!==l,(e=>{this.handler.chart.applyOptions({timeScale:{borderVisible:e}})}));const c=this.getCurrentOptionValue("timeScale.borderColor")||"#000000";this.addColorPicker("Border Color",c,(e=>{this.handler.chart.applyOptions({timeScale:{borderColor:e}})}))}buildPriceScaleOptionsTab(){const e=document.createElement("div");e.innerText="Price Scale Options",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="8px",this.contentArea.appendChild(e);const i=this.handler.chart.priceScale("right");i.options().mode||t.PriceScaleMode.Normal;const s=[{label:"Normal",value:t.PriceScaleMode.Normal},{label:"Logarithmic",value:t.PriceScaleMode.Logarithmic},{label:"Percentage",value:t.PriceScaleMode.Percentage},{label:"Indexed To 100",value:t.PriceScaleMode.IndexedTo100}],n=s.map((e=>e.label));this.addDropdown("Price Scale Mode",n,(e=>{const t=s.find((t=>t.label===e));t&&i.applyOptions({mode:t.value})}));const o=void 0===i.options().autoScale||i.options().autoScale;this.addCheckbox("Auto Scale",o,(e=>{i.applyOptions({autoScale:e})}));const r=i.options().invertScale||!1;this.addCheckbox("Invert Scale",r,(e=>{i.applyOptions({invertScale:e})}));const a=void 0===i.options().alignLabels||i.options().alignLabels;this.addCheckbox("Align Labels",a,(e=>{i.applyOptions({alignLabels:e})}));const l=void 0===i.options().borderVisible||i.options().borderVisible;this.addCheckbox("Border Visible",l,(e=>{i.applyOptions({borderVisible:e})}));const c=i.options().ticksVisible||!1;this.addCheckbox("Ticks Visible",c,(e=>{i.applyOptions({ticksVisible:e})}))}buildCloneSeriesTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Clone Series - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Clone Series logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildVisibilityOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Visibility Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Visibility Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildStyleOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Style Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Style Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildWidthOptionsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Width Options - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Width Options logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildPrimitivesTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Primitives",Object.assign(e.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(e),this.handler._seriesList.forEach((e=>{if(e.primitives&&Array.isArray(e.primitives)&&e.primitives.length>0){let t="Unnamed Series";const i=e.options();i&&i.title&&(t=i.title);const s=document.createElement("div");Object.assign(s.style,{border:"2px solid #666",marginBottom:"12px",padding:"8px",borderRadius:"4px"});const n=document.createElement("div");n.innerText=`Series: ${t}`,Object.assign(n.style,{fontSize:"18px",fontWeight:"bold",marginBottom:"8px"}),s.appendChild(n),e.primitives.forEach(((e,t)=>{let i;if("function"==typeof e.options?i=e.options():e._options?i=e._options:e.options&&(i=e.options),!i)return;const n=document.createElement("div");Object.assign(n.style,{border:"1px solid #444",marginBottom:"8px",padding:"8px",borderRadius:"4px"});const o=document.createElement("div");o.innerText=`Primitive ${t+1}: ${e.name||"Unnamed"}`,Object.assign(o.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"6px"}),n.appendChild(o),this.buildPrimitiveColorOptions(i,n,(t=>{e.applyOptions(t)})),s.appendChild(n)})),this.contentArea.appendChild(s)}}))}buildIndicatorsTab(e){this.contentArea.innerHTML="";const t=document.createElement("div");t.innerText=`Indicators - ${e.options().title||"Untitled"}`,Object.assign(t.style,{fontSize:"16px",fontWeight:"bold",marginBottom:"12px"}),this.contentArea.appendChild(t);const i=document.createElement("div");i.innerText="(Indicators logic not yet implemented.)",i.style.color="#ccc",i.style.marginBottom="12px",this.contentArea.appendChild(i),this.addButton("⤝ Back",(()=>this.buildSeriesMenuTab(e)),{backgroundColor:"#444"})}buildSourceCodeTab(){this.contentArea.innerHTML="";const e=document.createElement("div");e.innerText="Source Code & Licensing",e.style.fontSize="16px",e.style.fontWeight="bold",e.style.marginBottom="12px",this.contentArea.appendChild(e);const t=document.createElement("div");t.style.marginBottom="12px",t.style.fontSize="16px",t.innerHTML='\n \n This project is a derivative work that incorporates components from the following repositories:\n
\n \n