pine2profit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +243 -2
- package/build/.gitkeep +0 -0
- package/build/index.cjs +1152 -0
- package/build/index.mjs +1142 -0
- package/build/modules/frontend/build/.nojekyll +0 -0
- package/build/modules/frontend/build/404/index.html +1 -0
- package/build/modules/frontend/build/404.html +1 -0
- package/build/modules/frontend/build/_next/static/chunks/11.78c5bec5897e1148.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/195.64632be71175c993.js +63 -0
- package/build/modules/frontend/build/_next/static/chunks/204.008bcbcf48844ee2.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/255-da04dc9178303a31.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/2738385b.306f7750ad5b8be4.js +372 -0
- package/build/modules/frontend/build/_next/static/chunks/338-31711140cb6d61e5.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/4bd1b696-c023c6e3521b1417.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/50e49f97.75feacc2b3cc7709.js +433 -0
- package/build/modules/frontend/build/_next/static/chunks/554.dd4ac9a0aff9b782.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/570-33c81efca66c4bc9.js +3 -0
- package/build/modules/frontend/build/_next/static/chunks/5957d0c3.7b96612772854e2d.js +2 -0
- package/build/modules/frontend/build/_next/static/chunks/619-f09bc47e24909021.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/7589b812.60f2b16513f3aa42.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/771.5c62ba94f930669e.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/796.4b04b2b64c066b03.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/897-b727cc7229802490.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/app/_not-found/page-b6d9300903c2ab41.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/app/layout-0da8bd54f47c9e1b.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/app/page-7ab911a70ef48cfe.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/app/run/page-42836fc705c46a59.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/c525c9ef.018edb9552a70fc2.js +143 -0
- package/build/modules/frontend/build/_next/static/chunks/e1865c21-8d63eb0f5b25cb0c.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/framework-28b60818f5cffd83.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/main-45ecedd1f28e3a74.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/main-app-4ff0bbe1b367fcb5.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/pages/_app-7d307437aca18ad4.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/pages/_error-cb2a52f75f2162e2.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
- package/build/modules/frontend/build/_next/static/chunks/webpack-bb5ccf34ea47f1d7.js +1 -0
- package/build/modules/frontend/build/_next/static/css/91363587ff8467b5.css +1 -0
- package/build/modules/frontend/build/_next/static/media/29b98dbfba401fa9-s.p.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/313510e2713fb214-s.p.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/558ca1a6aa3cb55e-s.p.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/64d784ea54a4acde-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/6d831b18ae5b01dc-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/8048a25e80cc4179-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/851c4691abdf3def-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/87bc17f7c8b98e48-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/982ceffe7b733b3b-s.p.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/a6c19694cd327cd4-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/a8a8dd7277bab4cf-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/ac0e76ddaeeb7981-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/b8bfb68ab9ab617c-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/d76fe899475ae4d7-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/e546cf32c9d4702c-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/edc640959b0c7826-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/media/ff71da380fbe67dd-s.woff2 +0 -0
- package/build/modules/frontend/build/_next/static/vHsenj52Jy0T31oXW8dJX/_buildManifest.js +1 -0
- package/build/modules/frontend/build/_next/static/vHsenj52Jy0T31oXW8dJX/_ssgManifest.js +1 -0
- package/build/modules/frontend/build/icon.svg +1 -0
- package/build/modules/frontend/build/index.html +1 -0
- package/build/modules/frontend/build/index.txt +23 -0
- package/build/modules/frontend/build/run/index.html +1 -0
- package/build/modules/frontend/build/run/index.txt +23 -0
- package/package.json +93 -4
- package/types.d.ts +124 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[203],{29:(e,t,r)=>{r.r(t),r.d(t,{PineEngine:()=>eM,PineWorkerEngine:()=>eI});var i=r(9338),n=r(8592),a=r(3678),s="Study";function o(e){return"string"==typeof e?e:void 0}function l(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function u(e){let t=e??{},r=t.fullContext??t;return Object.keys({...r.indicator,...r.strategy?.config}).length>0}function c(e){let t=e??{},r=t.fullContext??t,i={...r.indicator,...r.strategy?.config},n=o(i.title),a={title:void 0===n?"Indicator":n.trim()?n:s,overlay:function e(t){return"boolean"==typeof t?t:"object"==typeof t&&null!==t&&Array.isArray(t.data)?e(t.data[t.offset??0]):void 0}(i.overlay)??!1,precision:l(i.precision),shorttitle:o(i.shorttitle),format:o(i.format)},u=Object.entries(r.plots??{}).map(([e,t])=>{let r=t??{},i=r.options??{};return{key:e,title:o(r.title),style:o(i.style),options:i,data:Array.isArray(r.data)?function(e){let t=new Map,r=!1;for(let i=0;i<e.length;i+=1){let n=e[i].time;t.has(n)&&(r=!0),t.set(n,i)}if(!r)return e;let i=new Set(t.values());return e.filter((e,t)=>i.has(t))}(r.data):[],plot1:o(r.plot1)??o(i.plot1),plot2:o(r.plot2)??o(i.plot2)}}),c=r.strategy?function(e){let t=[];for(let r of[...Array.isArray(e.closedtrades)?e.closedtrades:[],...Array.isArray(e.opentrades)?e.opentrades:[]]){let e=r??{},i=l(e.entry_price),n=l(e.entry_time),a=l(e.size);void 0!==i&&void 0!==n&&void 0!==a&&0!==a&&t.push({id:o(e.id)??`trade_${t.length}`,entry_id:o(e.entry_id)??"",entry_price:i,entry_time:n,entry_comment:o(e.entry_comment),exit_id:o(e.exit_id),exit_price:l(e.exit_price),exit_time:l(e.exit_time),exit_comment:o(e.exit_comment),size:a,status:"closed"===e.status?"closed":"open"})}return t}(r.strategy):void 0;return{meta:a,plots:u,...c?{trades:c}:{}}}var h=e=>l(e)??0,p=(e,t)=>{let r=l(t);return void 0===r?{}:{[e]:r}};function d(e){try{return structuredClone(e)}catch{return}}function m(e,t){if(e)for(let[r,i]of Object.entries(e)){if(r.startsWith("_"))continue;let e=function(e){let t=Array.isArray(e)?e:null!=e&&"object"==typeof e&&Array.isArray(e.data)?e.data:null;return d(t?t[t.length-1]:e)}(i);void 0!==e&&(t[r.replace(/^glb\d+_/,"")]=e)}}function f(e,t,r){let i=e??{},n=i.fullContext??i,a=e=>!r||r.includes(e),s=a("meta")||a("plots")?c(e):null,u={};if(s&&a("plots"))for(let e of s.plots)e.key.startsWith("__")||(u[e.key]=e.data.map(e=>({time:e.time,value:d(e.value)??null})));let f={};a("variables")&&(m(n.const,f),m(n.var,f),m(n.let,f));let y=a("strategy")?function(e){if(null!=e&&"object"==typeof e)return{position:h(e.position_size),avgPrice:h(e.position_avg_price),equity:h(e.equity),openPnl:h(e.openprofit),netPnl:h(e.netprofit),grossProfit:h(e.grossprofit),grossLoss:h(e.grossloss),wins:h(e.wintrades),losses:h(e.losstrades),even:h(e.eventrades),maxDrawdown:h(e.max_drawdown),maxRunup:h(e.max_runup),initialCapital:h(e.initial_capital),...p("cagr",e.cagr),...p("sharpe",e.sharpe_ratio),...p("sortino",e.sortino_ratio),...p("buyHoldPnl",e.buy_and_hold_pnl),...p("buyHoldPct",e.buy_and_hold_per_gain),...p("outperformance",e.strategy_outperformance)}}(n.strategy):void 0,g=a("trades")&&n.strategy?function(e){if(null==e||"object"!=typeof e)return[];let t=[];for(let r of[...Array.isArray(e.closedtrades)?e.closedtrades:[],...Array.isArray(e.opentrades)?e.opentrades:[]]){let e=r??{},i=l(e.entry_price),n=l(e.entry_time),a=l(e.size);if(void 0===i||void 0===n||void 0===a||0===a)continue;let s=l(e.exit_price),u=l(e.exit_time);t.push({id:o(e.id)??`trade_${t.length}`,side:a>0?"long":"short",qty:Math.abs(a),entry:{id:o(e.entry_id)??"",time:n,price:i,...void 0!==o(e.entry_comment)?{comment:o(e.entry_comment)}:{}},...void 0!==s&&void 0!==u?{exit:{id:o(e.exit_id)??"",time:u,price:s,...void 0!==o(e.exit_comment)?{comment:o(e.exit_comment)}:{}}}:{},open:"closed"!==e.status,...p("pnl",e.profit),...p("commission",e.commission),...p("maxDrawdown",e.max_drawdown),...p("maxRunup",e.max_runup)})}return t}(n.strategy):void 0;return{language:"pine",phase:t,barIndex:"number"==typeof n.idx?n.idx:"number"==typeof n.length?n.length-1:-1,meta:s&&a("meta")?{title:s.meta.title,overlay:s.meta.overlay,precision:s.meta.precision,shorttitle:s.meta.shorttitle}:{title:"",overlay:!1},plots:u,variables:f,...y?{strategy:y}:{},...g&&g.length>0?{trades:g}:{},warnings:a("warnings")?(n.warnings??[]).map(e=>({message:String(e.message??""),method:"string"==typeof e.method?e.method:void 0,bar:Number(e.bar??0)})):[]}}var y={line:"line",style_line:"line",style_linebr:"line",style_area:"area",style_areabr:"area",style_stepline:"step",style_steplinebr:"step",style_stepline_diamond:"step",style_histogram:"histogram",style_columns:"columns",style_circles:"circles",style_cross:"cross",shape:"markers",char:"markers",bar:"bar",candle:"candle",background:"background",barcolor:"barcolor",hline:"hline",fill:"fill",drawing_line:"drawing_line",drawing_box:"drawing_box",label:"label",drawing_polyline:"drawing_polyline",linefill:"linefill",table:"table"};function g(e){if("string"!=typeof e)return!1;let t=e.trim();if(!t)return!1;let r=t.toLowerCase();if("na"===r||"nan"===r)return!1;let i=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})$/.exec(t);return!(i&&0===parseInt(i[1]??"ff",16)||/^rgba\([^)]*,\s*0(?:\.0+)?\s*\)$/i.test(t))}function _(e,t){return g(e)?e.trim():t}var b=class{ordinals=new Map;next(e,t,r){let i=`${t}:${r.trim().toLowerCase()}`,a=this.ordinals.get(i)??0;return this.ordinals.set(i,a+1),(0,n.uZt)({instanceId:e,kind:t,title:r,ordinal:a})}};function x(e){let t=e.data;if(0===t.length)return[];let r=t[t.length-1]?.value;return Array.isArray(r)?r:[]}function v(e){if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(e&&"object"==typeof e&&Array.isArray(e.data)){let t="number"==typeof e.offset?e.offset:0,r=e.data[e.data.length-1-t];return"number"==typeof r&&Number.isFinite(r)?r:void 0}}function w(e){let t=(o(e)??"").toLowerCase();return"bt"===t||t.includes("time")?"bar_time":"bar_index"}function S(e){let t=(o(e)??"none").toLowerCase();return"b"===t||"both"===t?"both":"l"===t||"left"===t?"left":"r"===t||"right"===t?"right":"none"}function E(e){let t=(o(e)??"").toLowerCase();return t.includes("dot")?"dotted":t.includes("dash")?"dashed":"solid"}function k(e){if(void 0===e)return{invisible:!1};if(null===e||"number"==typeof e)return{invisible:!0};if("string"==typeof e){if(""===e)return{invisible:!1};let t=_(e);return t?{color:t,invisible:!1}:{invisible:!0}}return{invisible:!0}}function A(e,t){let r=v(e.x1),i=v(e.y1),n=v(e.x2),a=v(e.y2);if(void 0===r||void 0===i||void 0===n||void 0===a)return null;let s=(o(e.style)??"").toLowerCase(),{color:l,invisible:u}=k(e.color);return{id:t,paneId:"unrouted",xloc:w(e.xloc),x1:r,y1:i,x2:n,y2:a,extend:S(e.extend),color:l,invisible:u,width:Math.max(1,v(e.width)??1),style:E(e.style),arrowLeft:"style_arrow_left"===s||"style_arrow_both"===s,arrowRight:"style_arrow_right"===s||"style_arrow_both"===s,overlay:!0===e.force_overlay}}function N(e){return e<=0?"auto":e<=9?"tiny":e<=12?"small":e<=17?"normal":e<=28?"large":"huge"}function C(e){let t=(o(e)??"").toLowerCase();return"left"===t||"right"===t?t:"center"}function T(e){let t=(o(e)??"").toLowerCase();return"top"===t||"bottom"===t?t:"center"}function M(e){return(o(e)??"").toLowerCase().includes("mono")?"monospace":"default"}var I=["label_up","label_down","label_left","label_right","label_center","label_lower_left","label_lower_right","label_upper_left","label_upper_right","circle","square","diamond","flag","arrowup","arrowdown","triangleup","triangledown","cross","xcross","text_outline","none"];function P(e){if("number"==typeof e&&Number.isFinite(e))return N(e);let t=(o(e)??"").toLowerCase();return"auto"===t||"tiny"===t||"small"===t||"large"===t||"huge"===t?t:"normal"}var D=["top_left","top_center","top_right","middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"];function O(e){let t=v(e);return void 0!==t&&t>0?t:void 0}var R=a.bg,F={pane:!0,priceScale:!0,legend:!0,dataWindow:!0},L={pane:"pane",data_window:"dataWindow",status_line:"legend",price_scale:"priceScale"},B=["all","none","pane","data_window","status_line","price_scale"];function j(e){if("string"!=typeof e)return{...F};let t={pane:!1,priceScale:!1,legend:!1,dataWindow:!1};for(let r=0;r<e.length;){let i=B.find(t=>e.startsWith(t,r));if(!i||"all"===i)return{...F};"none"!==i&&(t[L[i]]=!0),r+=i.length}return t}function V(e){return j(e).pane}function $(e,t){return void 0===t||t<=0?0:Math.max(0,e-Math.floor(t))}function z(e){let t=[];for(let r=1;r<e.length;r+=1){let i=e[r].time-e[r-1].time;i>0&&t.push(i)}return 0===t.length?0:(t.sort((e,t)=>e-t),t[t.length>>1]??0)}function q(e,t,r){if(t<0)return e[0].time+t*r;let i=e.length-1;return t<=i?e[t].time:e[i].time+(t-i)*r}function U(e){for(let t of e.data)if("string"==typeof t.options?.color&&t.options.color)return t.options.color;return o(e.options.color)}function W(e){let t=o(e)?.replace(/^(hline\.style_|plot\.linestyle_|linestyle_|style_)/,"");return"solid"===t||"dashed"===t||"dotted"===t?t:void 0}var H={aqua:"#00BCD4",black:"#363A45",blue:"#2196F3",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#F23645",silver:"#B2B5BE",teal:"#089981",white:"#FFFFFF",yellow:"#FDD835"};function K(e,t){return"bool"===t?!!e:"int"===t||"float"===t?"number"==typeof e?e:Number(e)||0:"string"==typeof e?e:null==e?"":String(e)}var G=!1;function Y(){if(G)return;G=!0;let e=i.ob.prototype,t=e.bindContextObject;"function"==typeof t&&(e.bindContextObject=function(e,r,i){if(t.call(this,e,r,i),"table"!==i)return;let n=this.pine.table;if(!n||"function"==typeof n.cell_set_text_formatting||"function"!=typeof e._setCellProp)return;let a=(t,r,i,n)=>e._setCellProp(t,r,i,"text_formatting",n);n.cell_set_text_formatting=(e,t,r,i)=>a(e,t,r,i);let s=n.cell;"function"==typeof s&&(n.cell=(...e)=>{let t,r,i=e[e.length-1],n=i&&"object"==typeof i&&!Array.isArray(i)&&"text_formatting"in i?i:null;if(!n&&e.length<14)return s(...e);let o=n?e.slice(0,-1):e.slice(0,13);if(n){let{text_formatting:e,...i}=n;t=e,r=Object.keys(i).length>0?[...o,i]:o}else t=e[13],r=o;let l=s(...r),u=n??{},c=o.length>1?o[1]:u.column??0,h=o.length>2?o[2]:u.row??0;return a(o[0],c,h,t),l})})}var Z=["plotshape","plotchar","plotarrow"],X=!1;function J(){if(X)return;X=!0;let e=i.ob.prototype,t=e.bindContextObject;"function"==typeof t&&(e.bindContextObject=function(e,r,i){if(t.call(this,e,r,i),void 0!==i||!Z.some(e=>r.includes(e)))return;let n={idx:void 0,n:0,len:0};for(let e of Z){let t=this.pine[e];"function"==typeof t&&(this.pine[e]=(...e)=>{let r=e[e.length-1];if(!(null!==r&&"object"==typeof r&&"__callsiteId"in r)){let t=this.idx;0===n.len&&void 0!==n.idx&&t!==n.idx&&(n.len=n.n,n.n=0),n.idx=t;let r=n.len>0?n.n%n.len:n.n;n.n+=1,e.push({__callsiteId:`~m${r}`})}return t(...e)})}})}function Q(e,t){let r=new Map,i=!1,n=0,a=!1;return{ask(s,o,l){let u=`${s}\0${o}`;return i||!e.onChange||r.has(u)||r.set(u,e.onChange(s,o,()=>void(!i&&(n>0?a=!0:t())))),e(s,o,l)},runStarted(e=!1){n=e?1:n+1,e&&(a=!1)},runEnded(){0!==n&&((n-=1)>0||!a||i||(a=!1,t()))},stop(){for(let e of(i=!0,r.values()))e();r.clear()}}}function ee(e,t,r,i){return e?{getFootprintData:(n,a,s,o,l)=>{let u=et(n??t()),c=a??r(),h=null!=s&&u===et(t())&&c===r();return e(u,c,{from:o,to:l??(h?i?.():void 0),limit:s})}}:{}}function et(e){return e.split(";")[0]??e}var er=/^[ \t]*import[ \t]+[^\s/]+\/[^\s/]+\/\d+/m;async function ei(e,t){if(!t||!er.test(e))return;let r="function"==typeof t?t:(e,r)=>t.resolve(e,r),n=await (0,i.TU)(e,r);return Object.keys(n).length>0?n:void 0}var en=new WeakMap;function ea(e){let t=en.get(e);return t||(t=new i.yD({libraries:e}),en.set(e,t)),t}async function es(e,t,r,n="all",a){let s=await ei(e,a);if(!s)return function(e,t,r,n="all"){return eo(i.C1.from(e),e,t,r,n,void 0)}(e,t,r,n);let o=i.C1.from(e);return await o.resolveImports(ea(s)),eo(o,e,t,r,n,s)}function eo(e,t,r,i,n,a){let o=e.getInputsMeta().map((e,t)=>{let r=("string"===e.type||null==e.type)&&void 0!==function(e){if("string"!=typeof e)return;let t=/^color\.([a-z]+)$/i.exec(e.trim());return t?H[t[1].toLowerCase()]:void 0}(e.defval)?"color":function(e){switch(e){case"int":return"int";case"float":return"float";case"bool":return"bool";case"source":return"source";case"color":return"color";case"price":return"price";case"time":return"time";case"session":return"session";case"timeframe":return"timeframe";case"symbol":return"symbol";case"text_area":return"text_area";default:return"string"}}(e.type);return{key:e.varId??e.title??`input${t}`,title:e.title??e.varId??`Input ${t+1}`,type:r,defval:function(e,t){if("bool"===t)return!!e;if("int"===t||"float"===t||"price"===t||"time"===t)return"number"==typeof e?e:Number(e)||0;let r="string"==typeof e?e:null==e?"":String(e);return"color"===t?H[r.trim().toLowerCase().replace(/^color\./,"")]??r:r}(e.defval,r),min:e.minval,max:e.maxval,step:e.step,options:Array.isArray(e.options)?e.options.map(e=>String(e)):void 0,group:e.group,inline:e.inline,tooltip:e.tooltip}}),l=function(e,t,r){if("none"===r||"strategy"===r&&"strategy"!==e.getDeclarationType())return[];let i=function(e,t){let r=e.getPropsMeta(),i=e.prop;return r.filter(e=>e.mutable&&e.name).map(e=>{let r=e.name,n=function(e){switch(e){case"int":return"int";case"float":return"float";case"bool":return"bool";default:return"string"}}(e.type),a=K(e.defval,n),s=K(i[r]??e.defval,n),o=t?.[r],l=s!==a?s:void 0!==o?K(o,n):a;return{key:r,title:function(e){let t=e.replace(/_/g," ");return t.charAt(0).toUpperCase()+t.slice(1)}(r),type:n,defval:l,min:e.minval,max:e.maxval,options:Array.isArray(e.options)?e.options.map(e=>String(e)):void 0}})}(e,t);if("string"==typeof r)return i;let n=new Map(i.map(e=>[e.key,e]));return r.map(e=>n.get(e)).filter(e=>void 0!==e)}(e,i,n),u=e.prop.overlay,c="boolean"==typeof u?u:void 0,h=c??/(?<![\w.$])overlay\s*[:=]\s*true/.test(t),p=/^\s*(?:indicator|strategy)\s*\(\s*(?:title\s*=\s*)?(["'])((?:\\.|(?!\1).)*)\1/m.exec(t)?.[2],d=void 0===p?"Indicator":p.replace(/\\(.)/g,"$1").trim()||s,m=/chart\.(left|right)_visible_bar(_time)?\b/.test(t),f={source:t,instanceId:r,...void 0!==c?{declaredOverlay:c}:{},...a?{libraries:a}:{}};return{language:"pine",inputs:o,...l.length>0?{props:l}:{},meta:{title:d,overlay:h},reactsToViewport:m,token:f}}function el(e,t,r,n={}){let a=JSON.stringify([r,n]);if(e.lastKey!==a||!e.lastInd){let s=new i.C1(t,r);for(let[e,t]of Object.entries(n))try{s.prop[e]=t}catch(t){console.warn(`[vela-pinets] prop "${e}" rejected:`,t instanceof Error?t.message:t)}e.lastInd=s,e.lastKey=a}return e.lastInd}async function eu(e){let{ind:t,bars:r,market:n,visibleRange:a,prepared:s,instanceId:o,inputs:l,props:c,fetchSeries:h,footprints:p}=e;Y(),J();let d=ey(r,n.timeframe,n.symbolInfo,Date.now()),m={getMarketData:(e,t,r,i,a)=>eb(e,t,n)?Promise.resolve(d):ex(h,e,t,r,i,a,ev(n,e)),getSymbolInfo:async e=>ev(n,e),...ee(p,()=>n.symbol,()=>n.timeframe,()=>e_(d,n.timeframe))},f=new i.k6(m,eg(n),n.timeframe,d.length),y=s.token.libraries;y&&f.setImportResolver(ea(y)),await f.ready(),a&&f.setVisibleRange(a.left,a.right);let g=await f.run(t),_="function"==typeof f.usesVisibleRange&&f.usesVisibleRange();return{model:u(g)?ec(g,o,s,l,c??{},r[0]?.time):null,alerts:(g.alerts??[]).map(eE),warnings:(g.warnings??[]).map(ek),reactsToViewport:_,ctx:g}}function ec(e,t,r,i,n,s){let{model:u}=function(e,t){let r=new b,i=[],n=[],s=[],u=[],c=[],h=[],p=[],d=[],m=[],f=[],F=[],L=[],B=new Map,H=new Set,K=[];for(let i of e.plots){var G;let e=null==(G=i.style)||""===G?"line":y[G]??"line",s=i.title??i.key;switch(e){case"skip":break;case"barcolor":{if(!V(i.options.display))break;let e=$(i.data.length,l(i.options.show_last));for(let t=e;t<i.data.length;t+=1){let e=i.data[t],r=_(e.options?.color);r&&L.push({time:e.time,color:r})}break}case"fill":V(i.options.display)&&K.push(i);break;case"hline":{let e=function(e,t,r,i){let n;if(!V(e.options.display))return null;for(let t of e.data)if("number"==typeof t.value&&Number.isFinite(t.value)){n=t.value;break}return void 0===n?null:{id:i.next(r,"hline",t),paneId:"unrouted",price:n,color:_(e.options.color),lineStyle:W(e.options.linestyle)??"dashed",title:t,width:l(e.options.linewidth)}}(i,s,t,r);e&&c.push(e);break}case"background":V(i.options.display)&&u.push(...function(e,t,r,i){let n=[],a=!0===e.options.force_overlay?{overlay:!0}:{},s=e.data,o=s.length>1?(s[1]?.time??0)-(s[0]?.time??0):0,u=$(s.length,l(e.options.show_last));for(;u<s.length;){let e=s[u],l=_(e.options?.color);if(!0===e.value&&l){let c=e.time,h=e.time,p=u;for(;p+1<s.length;){let e=s[p+1];if(!0===e.value&&_(e.options?.color)===l)h=e.time,p+=1;else break}n.push({id:i.next(r,"background",t),paneId:"unrouted",from:c,to:h+o,color:l,...a}),u=p+1}else u+=1}return n}(i,s,t,r));break;case"drawing_line":h.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=A(n,r.next(t,"line",String(n.id??i.length)));e&&i.push(e)}return i}(i,t,r));break;case"drawing_box":p.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=v(n.left),a=v(n.top),s=v(n.right),l=v(n.bottom);if(void 0===e||void 0===a||void 0===s||void 0===l)continue;let u=(o(n.text_formatting)??"").toLowerCase(),c=o(n.text);i.push({id:r.next(t,"box",String(n.id??i.length)),paneId:"unrouted",xloc:w(n.xloc),left:e,top:a,right:s,bottom:l,extend:S(n.extend),bgColor:_(n.bgcolor),borderColor:_(n.border_color),borderWidth:Math.max(0,v(n.border_width)??1),borderStyle:E(n.border_style),text:c&&c.length>0?c:void 0,textColor:_(n.text_color),textSize:function(e){if("number"==typeof e&&Number.isFinite(e))return N(e);let t=(o(e)??"").toLowerCase();return"tiny"===t||"small"===t||"normal"===t||"large"===t||"huge"===t?t:"auto"}(n.text_size),hAlign:C(n.text_halign),vAlign:T(n.text_valign),wrap:(o(n.text_wrap)??"").toLowerCase().includes("auto"),fontFamily:M(n.text_font_family),bold:u.includes("bold"),italic:u.includes("italic"),overlay:!0===n.force_overlay})}return i}(i,t,r));break;case"label":d.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=v(n.x),a=function(e){let t=(o(e)??"").toLowerCase();return"ab"===t||t.includes("above")?"abovebar":"bl"===t||t.includes("below")?"belowbar":"price"}(n.yloc),s=v(n.y);if(void 0===e||"price"===a&&void 0===s)continue;let l=o(n.text),u=o(n.tooltip),{color:c,invisible:h}=k(n.color);i.push({id:r.next(t,"label",String(n.id??i.length)),paneId:"unrouted",xloc:w(n.xloc),x:e,y:s??0,yloc:a,text:l&&l.length>0?l:void 0,style:function(e){let t=(o(e)??"").toLowerCase().replace(/^style_/,"");return I.includes(t)?t:"label_down"}(n.style),color:c,noFill:h,textColor:_(n.textcolor),size:P(n.size),textAlign:C(n.textalign),tooltip:u&&u.length>0?u:void 0,fontFamily:M(n.text_font_family),overlay:!0===n.force_overlay})}return i}(i,t,r));break;case"drawing_polyline":m.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=Array.isArray(n.points)?n.points:[],a=w(n.xloc),s=[];for(let t of e){let e,r,i=v(t.price),n=v(t.index),o=v(t.time),l="bar_time"===a?o:n,u="bar_time"===a?n:o;if(void 0!==l)e=l,r=a;else{if(void 0===u)continue;e=u,r="bar_time"===a?"bar_index":"bar_time"}void 0!==i&&s.push({xloc:r,x:e,price:i})}if(s.length<2)continue;let l=(o(n.line_style)??"").toLowerCase();i.push({id:r.next(t,"polyline",String(n.id??i.length)),paneId:"unrouted",points:s,curved:!0===n.curved,closed:!0===n.closed,lineColor:_(n.line_color),fillColor:_(n.fill_color),lineWidth:Math.max(1,v(n.line_width)??1),lineStyle:E(n.line_style),arrowLeft:"style_arrow_left"===l||"style_arrow_both"===l,arrowRight:"style_arrow_right"===l||"style_arrow_both"===l,overlay:!0===n.force_overlay})}return i}(i,t,r));break;case"linefill":f.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=n.line1,a=n.line2;if(!e||!a)continue;let s=r.next(t,"linefill",String(n.id??i.length)),o=A(e,`${s}:a`),l=A(a,`${s}:b`);o&&l&&i.push({id:s,paneId:"unrouted",line1:o,line2:l,color:_(n.color),overlay:!0===n.force_overlay})}return i}(i,t,r));break;case"table":F.push(...function(e,t,r){let i=[];for(let n of x(e)){if(!0===n._deleted)continue;let e=(Array.isArray(n.cells)?n.cells:[]).map(e=>(Array.isArray(e)?e:[]).map(e=>(function(e){var t;if(!e||"object"!=typeof e)return null;let r=o(e.text),i=o(e.tooltip),n=(o(e.text_formatting)??"").toLowerCase();return{text:r&&r.length>0?r:void 0,textColor:_(e.text_color),bgColor:_(e.bgcolor),hAlign:C(e.text_halign),vAlign:T(e.text_valign),textSize:"number"==typeof(t=e.text_size)&&Number.isFinite(t)&&t>0?t:P(t),fontFamily:M(e.text_font_family),tooltip:i&&i.length>0?i:void 0,bold:n.includes("bold"),italic:n.includes("italic"),width:O(e.width),height:O(e.height),merged:!0===e._merged}})(e))),a=function(e){if(!Array.isArray(e))return[];let t=[],r=new Set;for(let i of e){if(!i||"object"!=typeof i)continue;let e=v(i.startCol??i.start_column??i.startColumn),n=v(i.startRow??i.start_row),a=v(i.endCol??i.end_column??i.endColumn),s=v(i.endRow??i.end_row);if(void 0===e||void 0===n||void 0===a||void 0===s)continue;let o={startCol:Math.min(Math.round(e),Math.round(a)),startRow:Math.min(Math.round(n),Math.round(s)),endCol:Math.max(Math.round(e),Math.round(a)),endRow:Math.max(Math.round(n),Math.round(s))},l=`${o.startCol}:${o.startRow}:${o.endCol}:${o.endRow}`;r.has(l)||(r.add(l),t.push(o))}return t}(n.merges);for(let t of a){let r=e[t.startRow]?.[t.startCol];r?.merged&&(r.merged=!1)}i.push({id:r.next(t,"table",String(n.id??i.length)),paneId:"unrouted",position:function(e){let t=(o(e)??"").toLowerCase();return D.includes(t)?t:"top_right"}(n.position),columns:Math.max(0,Math.round(v(n.columns)??0)),rows:Math.max(0,Math.round(v(n.rows)??0)),bgColor:_(n.bgcolor),frameColor:_(n.frame_color),frameWidth:Math.max(0,v(n.frame_width)??0),borderColor:_(n.border_color),borderWidth:Math.max(0,v(n.border_width)??0),cells:e,merges:a,overlay:!0===n.force_overlay})}return i}(i,t,r));break;case"markers":V(i.options.display)&&d.push(...function(e,t,r){let i=Math.trunc(l(e.options.offset)??0),n=i?z(e.data):0,s="char"===e.style||void 0!==e.options.char,u=!s&&!("shape"in e.options)&&e.data.some(e=>void 0!==e.options&&"height"in e.options),c=u?function(e){let t=0;for(let r of e.data)"number"==typeof r.value&&Number.isFinite(r.value)&&(t=Math.max(t,Math.abs(r.value)));return{maxAbs:t,minH:l(e.options.minheight)??5,maxH:l(e.options.maxheight)??100}}(e):null,h=!0===e.options.force_overlay?{overlay:!0}:{},p=[],d=$(e.data.length,l(e.options.show_last));for(let l=d;l<e.data.length;l+=1){let d=e.data[l],m=d.value,f="number"==typeof m&&Number.isFinite(m);if(!0!==m&&!f||u&&(!f||0===m))continue;let y=d.options??e.options,b=void 0!==y.color?y.color:e.options.color;if(void 0!==b&&!g(b))continue;let x=o(y.text)??o(e.options.text),v=x&&x.trim().length>0?x:void 0,w=u?f&&m>0?a.cr:a.TV:void 0,S=_(y.color)??_(e.options.color)??w??R,E=s?o(y.char)??o(e.options.char)??"★":void 0;p.push({id:r.next(t,"label",`${e.key}#${p.length}`),paneId:"unrouted",xloc:"bar_time",x:i?q(e.data,l+i,n):d.time,y:f?m:0,yloc:function(e){let t=(e??"").toLowerCase();return"absolute"===t?"price":"top"===t?"top":"bottom"===t?"bottom":t.includes("below")?"belowbar":"abovebar"}(o(y.location)??o(e.options.location)),text:void 0!==E?void 0!==v?`${E}
|
|
2
|
+
${v}`:E:v,style:void 0!==E?"none":function(e){switch((e??"").toLowerCase().replace(/^shape_/,"").replace(/_/g,"")){case"diamond":return"diamond";case"triangleup":return"triangleup";case"triangledown":return"triangledown";case"labelup":return"label_up";case"labeldown":return"label_down";case"arrowup":return"arrowup";case"arrowdown":return"arrowdown";case"square":return"square";case"cross":return"cross";case"xcross":return"xcross";case"flag":return"flag";default:return"circle"}}(o(y.shape)??o(e.options.shape)),color:S,textColor:_(y.textcolor)??_(e.options.textcolor)??(void 0!==E?S:void 0),size:null!==c&&f?function(e,t){let r=t.maxAbs>0?e/t.maxAbs:1,i=t.minH+r*(t.maxH-t.minH);return i<=12?"tiny":i<=24?"small":i<=44?"normal":i<=72?"large":"huge"}(Math.abs(m),c):function(e){let t=(e??"").toLowerCase();return"tiny"===t||"small"===t||"large"===t||"huge"===t||"normal"===t?t:"small"}(o(y.size)??o(e.options.size)),textAlign:"center",fontFamily:"default",...h})}return p}(i,t,r));break;default:{let a=r.next(t,e,s);B.set(i.key,a),!0===i.options.force_overlay&&H.add(i.key),n.push(function(e,t,r,i){let n=l(t.options.show_last),a=!0===t.options.force_overlay?{overlay:!0}:{},s=j(t.options.display);if("candle"===e||"bar"===e){let o={id:r,title:i,paneId:"unrouted",kind:e,bars:function(e,t=0){let r=t>0?Array(e.data.length):[];for(let i=t;i<e.data.length;i+=1){let n=e.data[i],a=n.value;if(!Array.isArray(a)||a.length<4)continue;let s={time:n.time,open:a[0]??0,high:a[1]??0,low:a[2]??0,close:a[3]??0};t>0?r[i]=s:r.push(s)}return r}(t,$(t.data.length,n)),visible:s.pane,display:s,...a},l=function(e){let t=!1,r=e.data.map(e=>{let r=e.options??{},i=_(r.color),n=_(r.wickcolor),a=_(r.bordercolor);return i||n||a?(t=!0,{color:i,wickColor:n,borderColor:a}):null});return t?r:void 0}(t);return l&&(o.barColors=l),o}let o=_(U(t)),u={...s,pane:s.pane&&!!o},c=l(t.options.linewidth)??1,h=function(e,t){let r=Math.trunc(t??0);if(!r||0===e.length)return e;let i=z(e),n=e.length+Math.max(0,r),a=Array(n);for(let t=0;t<n;t+=1){let n=q(e,t,i),s=e[t-r];a[t]=s?{...s,time:n}:{time:n,value:null}}return a}(function(e,t,r){let i=$(e.length,t);return(r&&(i-=1),i<=0)?e:e.map((e,t)=>t<i?{...e,value:null}:e)}(function(e){let t=e.data.some(e=>g(e.options?.color));return e.data.map(e=>{let r="number"==typeof e.value&&Number.isFinite(e.value)?e.value:null,i=_(e.options?.color);return i?{time:e.time,value:r,color:i}:t?{time:e.time,value:r,color:"#00000000"}:{time:e.time,value:r}})}(t),n,"line"===e||"step"===e||"area"===e),l(t.options.offset)),p={color:o??R,width:c,lineStyle:W(t.options.linestyle)??"solid"},d=l(t.options.histbase);return void 0!==d&&("histogram"===e||"columns"===e||"area"===e)&&(p.base=d),{id:r,title:i,paneId:"unrouted",kind:e,points:h,style:p,visible:u.pane,display:u,...a}}(e,i,a,s));let o=function(e,t,r,i){if(!0!==e.options.trackprice)return null;for(let n=e.data.length-1;n>=0;n-=1){let a=e.data[n];if("number"==typeof a.value&&Number.isFinite(a.value))return{id:i.next(r,"hline",t),paneId:"unrouted",price:a.value,color:_(a.options?.color)??_(U(e)),lineStyle:"dotted",width:l(e.options.linewidth),title:t}}return null}(i,s,t,r);o&&c.push(o)}}}for(let e of K){let n=e.plot1?B.get(e.plot1):void 0,a=e.plot2?B.get(e.plot2):void 0;if(!n||!a){i.push(`fill "${e.key}" references unknown plots (${e.plot1??"?"}/${e.plot2??"?"})`);continue}let o=H.has(e.plot1)&&H.has(e.plot2);s.push({id:r.next(t,"fill",e.title??e.key),paneId:"unrouted",fromSeriesId:n,toSeriesId:a,...function(e){if(!0===e.options.gradient||e.data.some(e=>e.options&&("string"==typeof e.options.top_color||"string"==typeof e.options.bottom_color)))return{gradient:e.data.map(e=>{let t=e.options??{},r=l(t.top_value),i=l(t.bottom_value),n="string"==typeof t.top_color?t.top_color:void 0,a="string"==typeof t.bottom_color?t.bottom_color:void 0;return void 0!==r&&void 0!==i&&(n||a)?{topValue:r,bottomValue:i,topColor:n??"rgba(0,0,0,0)",bottomColor:a??"rgba(0,0,0,0)"}:null})};let t=e.data.map(e=>_(e.options?.color)??null),r=new Set(t.filter(e=>null!==e)),i=t.some(e=>null===e);return 0===r.size?{color:_(e.options.color)}:1!==r.size||i?{colors:t}:{color:[...r][0]}}(e),...o?{overlay:!0}:{}})}let Y=e.trades?function(e){let t=new Map,r=e=>{let r=`${e.time}|${e.side}|${e.label??""}`,i=t.get(r);if(!i)return void t.set(r,e);i.qty=(i.qty??0)+(e.qty??0),"entry"===e.kind&&"exit"===i.kind&&(i.kind="entry",i.price=e.price,i.tradeId=e.tradeId)};for(let t of e){let e=t.size>0,i=Math.abs(t.size);r({time:t.entry_time,price:t.entry_price,side:e?"buy":"sell",kind:"entry",label:t.entry_comment??t.entry_id,qty:i,tradeId:t.id}),"closed"===t.status&&null!=t.exit_time&&null!=t.exit_price&&r({time:t.exit_time,price:t.exit_price,side:e?"sell":"buy",kind:"exit",label:t.exit_comment??t.exit_id,qty:i,tradeId:t.id})}return[...t.values()].sort((e,t)=>e.time-t.time)}(e.trades):[];return{model:{id:t,title:e.meta.title,...e.meta.shorttitle?.trim()?{shorttitle:e.meta.shorttitle}:{},overlay:e.meta.overlay,paneHint:e.meta.overlay?"price":"new",series:n,fills:s,backgrounds:u,priceLines:c,lines:h,boxes:p,labels:d,polylines:m,linefills:f,tables:F,barColors:L.length?L:void 0,trades:Y.length?Y:void 0,inputs:[],inputValues:{}},warnings:i}}(c(e),t),h="boolean"==typeof n.overlay?n.overlay:r.token.declaredOverlay;return void 0!==h&&(u.overlay=h,u.paneHint=h?"price":"new"),u.inputs=r.inputs,u.inputValues={...eS(r.inputs),...i},r.props&&(u.props=r.props,u.propValues={...eS(r.props),...n}),null!=s&&(u.anchorTime=s),u}function eh(e){if("string"!=typeof e)return null;let t=/^(\d{2})(\d{2})-(\d{2})(\d{2})$/.exec(e);return t?{start:60*Number(t[1])+Number(t[2]),end:60*Number(t[3])+Number(t[4])}:null}var ep=(e,t)=>t.start<=t.end?e>=t.start&&e<t.end:e>=t.start||e<t.end,ed=new Map;function em(e,t){let r=`${t}:${Math.floor(e/36e5)}`,i=ed.get(r);if(null==i){try{let r=new Intl.DateTimeFormat("en-US",{timeZone:t,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=e=>Number(r.find(t=>t.type===e)?.value??NaN);i=Math.round((Date.UTC(n("year"),n("month")-1,n("day"),n("hour")%24,n("minute"))-e)/6e4)}catch{i=NaN}ed.size>1e5&&ed.clear(),ed.set(r,i)}return Number.isNaN(i)?null:((Math.floor(e/6e4)+i)%1440+1440)%1440}function ef(e){return null==e?null:/^\d+$/.test(e)?Number(e):/^1?D$/i.test(e)?1440:null}function ey(e,t,r,i){let n=function(e){if(null==e)return!1;let t=/^(\d*)\s*[tT]$/.exec(e.trim());return!!t&&(""===t[1]||parseInt(t[1],10)>=1)}(t),a=n?null:function(e,t,r){let i="object"==typeof r&&null!=r?r:null,n=ef(t),a=eh(i?.session),s="string"==typeof i?.timezone?i.timezone:null;if(null==n||null==a||null==s||0===e.length)return null;let o=eh(i?.session_extended),l=a;if(o)for(let t of e){let e=em(t.time,s);if(null!=e&&!ep(e,a)&&ep(e,o)){l=o;break}}return e=>{let t=em(e,s);return null!=t&&ep(t,l)?e+6e4*Math.min(n,(l.end-t+1440)%1440||1440):null}}(e,t,r);return e.map((t,r)=>{let s,o={openTime:t.time,open:t.open,high:t.high,low:t.low,close:t.close,volume:t.volume??0};if(n){let t=e[r+1];t&&(s=null!=i?Math.min(t.time,i):t.time)}else s=a?.(t.time);return null!=s&&(o.closeTime=s),o})}function eg(e){return"heikinashi"===e.chartStyle?`${e.symbol};heikinashi`:e.symbol}function e_(e,t){let r=e[e.length-1];if(!r)return;if(null!=r.closeTime)return r.closeTime;let i=ef(t);return null==i||null==r.openTime?void 0:r.openTime+6e4*i}function eb(e,t,r){return(null==e||e===eg(r))&&(null==t||t===r.timeframe)}async function ex(e,t,r,i,n,a,s){return e&&t&&r?ey(await e(t,r,{from:n,to:a,limit:i}),r,s,Date.now()):[]}function ev(e,t){let r=t?t.split(";")[0]:t;return r&&r!==e.symbol?ew({symbol:r,timeframe:e.timeframe}):ew(e)}function ew(e){if(e.symbolInfo){var t=e.symbolInfo;let r="string"==typeof t.volumetype&&""!==t.volumetype;return!1!==t.volume||r?t:{...t,volumetype:"n/a"}}let r=e.symbol,i=r.replace(/(USDT|USDC|USD|PERP|BUSD)$/i,"")||r;return{ticker:r,tickerid:r,main_tickerid:r,description:r,prefix:"",root:r,type:"crypto",basecurrency:i,currency:"USD",timezone:"UTC",session:"regular",mintick:.01,minmove:1,pointvalue:1,pricescale:100}}function eS(e){let t={};for(let r of e)t[r.key]=r.defval;return t}function eE(e){return{id:String(e.id??""),message:String(e.message??""),title:e.title,time:Number(e.time??0),barIndex:Number(e.bar_index??0),freq:e.freq}}function ek(e){return{message:String(e.message??""),method:e.method,bar:Number(e.bar??0)}}var eA="DataUnavailableError",eN=["symbol","timeframe","finest","default"];function eC(e){return"object"==typeof e&&null!==e&&e.name===eA&&"string"==typeof e.reason&&"string"==typeof e.message&&eN.every(t=>void 0===e[t]||"string"==typeof e[t])}function eT(e){let t={reason:e.reason};for(let r of eN)void 0!==e[r]&&(t[r]=e[r]);return t}var eM=class{language="pine";capabilities={streaming:!0,visibleRange:!0,inputs:!0,props:!0};defaultProps;propsVisibility;footprints;importResolver;constructor(e={}){this.defaultProps=e.defaultProps,this.propsVisibility=e.props??"all",this.footprints=e.footprints,this.importResolver=e.importResolver}prepare(e,t){return es(e,t,this.defaultProps,this.propsVisibility,this.importResolver)}execute(e,t){let r=e.prepared.token,n=e.getBars??(()=>e.bars),a={...e.inputs??{}},s={...e.props??{}},o=e.visibleRange,l=!1,c=function(e){if(!e)return;let t=new Map;return async(r,i,n)=>{let a=`${r}\0${i}`,s=t.get(a);if(s)throw s;try{return await e(r,i,n)}catch(e){throw eC(e)&&t.set(a,e),e}}}(e.fetchSeries),h=()=>{},p=this.footprints?Q(this.footprints,()=>h()):void 0,d=p?(e,t,r)=>p.ask(e,t,r):void 0;if("live"===e.mode&&this.capabilities.streaming){let m=null,y=!1,g=()=>{y=!0,m?.stop(),p?.runStarted(!0),m=function(e){var t,r,n,a;let s,o,l=e.bars();Y(),J();let c=el(e.cache,e.token.source,e.inputs,e.props??{}),h=l[0]?.time,p=Math.max(1,l.length),d=(t=e.bars,r=e.market,n=e.fetchSeries,a=e.footprints,s="",o=!1,{...ee(a,()=>r().symbol,()=>r().timeframe,()=>{let e=r();return e_(ey(t(),e.timeframe,e.symbolInfo),e.timeframe)}),markDirty:()=>{o=!0},getMarketData:async(e,i,a,l,u)=>{let c=r();if(!eb(e,i,c))return ex(n,e,i,a,l,u,ev(c,e));let h=ey(t(),c.timeframe,c.symbolInfo,Date.now());if(null==l)return h;let p=h.filter(e=>(e.openTime??0)>=l),d=p[p.length-1],m=d?`${p.length}|${d.openTime}|${d.close}|${d.high}|${d.low}|${d.volume}`:"";return o||m!==s?(o=!1,s=m,p):[]},getSymbolInfo:async e=>ev(r(),e)}),m=new i.k6(d,eg(e.market()),e.market().timeframe,p);e.token.libraries&&m.setImportResolver(ea(e.token.libraries)),e.visibleRange&&m.setVisibleRange(e.visibleRange.left,e.visibleRange.right);let f=m.stream(c,{live:!0,interval:1e3,pageSize:p}),y=!1,g=null;return f.on("data",t=>{if(!y&&(g=t,u(t)))try{e.onModel(ec(t,e.token.instanceId,e.prepared,e.inputs,e.props??{},h))}catch(t){e.onError?.(t instanceof Error?t:Error(String(t)))}}),f.on("alert",t=>e.onAlert?.(eE(t))),f.on("warning",t=>e.onWarning?.(ek(t))),f.on("error",t=>e.onError?.(t instanceof Error?t:Error(String(t)))),{stop:()=>{y=!0,f.stop()},setVisibleRange:(e,t)=>{m.setVisibleRange(e,t),d.markDirty()},markDirty:()=>d.markDirty(),lastCtx:()=>g}}({token:r,cache:r,prepared:e.prepared,inputs:a,props:s,bars:n,market:()=>e.market,fetchSeries:c,footprints:d,visibleRange:o,onModel:e=>{l||t.onModel(e),p?.runEnded()},onAlert:e=>t.onAlert?.(e),onWarning:e=>t.onWarning?.(e),onError:e=>{t.onError?.(e),p?.runEnded()}})};return h=()=>{y&&!l&&g()},"backfill"!==e.historyState&&g(),{getContext:e=>{let t=m?.lastCtx()??null;return Promise.resolve(null===t?null:f(t,l?"idle":"streaming",e))},stop:()=>{l=!0,p?.stop(),m?.stop()},update:(e,t)=>{a={...a,...e},t&&(s={...s,...t}),y&&g()},setVisibleRange:e=>{o=e,y&&m?.setVisibleRange(e.left,e.right)},notifyBars:e=>{if("backfill"!==e){if("complete"===e)return void g();y&&m?.markDirty()}}}}let m="backfill"===e.historyState,y=null,g=!1,_=async()=>{if(!l){g=!0,p?.runStarted();try{let i=await eu({ind:el(r,r.source,a,s),bars:n(),market:e.market,visibleRange:o,prepared:e.prepared,instanceId:r.instanceId,inputs:a,props:s,fetchSeries:c,footprints:d});if(l)return;for(let r of(y=i.ctx,g=!1,e.prepared.reactsToViewport=i.reactsToViewport,i.alerts))t.onAlert?.(r);for(let e of i.warnings)t.onWarning?.(e);i.model&&t.onModel(i.model),t.onDone?.()}catch(e){t.onError?.(e instanceof Error?e:Error(String(e)))}finally{p?.runEnded()}}};return h=()=>{l||m||_()},m||_(),{getContext:e=>Promise.resolve(null===y?null:f(y,g?"computing":"idle",e)),stop:()=>{l=!0,p?.stop()},update:(e,t)=>{a={...a,...e},t&&(s={...s,...t}),m||_()},setVisibleRange:e=>{o=e,m||_()},notifyBars:e=>{"backfill"!==e&&("complete"===e&&(m=!1),m||_())}}}},eI=class{language="pine";capabilities={streaming:!0,visibleRange:!0,inputs:!0,props:!0};worker=null;spawn;defaultProps;propsVisibility;footprints;importResolver;prepares=new Map;sessions=new Map;reqId=0;contextWaits=new Map;sessionId=0;constructor(e={}){this.spawn=e.createWorker??(()=>(function(e){if(e)return new Worker(e);let t=URL.createObjectURL(new Blob(['"use strict";(()=>{var K0=Object.defineProperty;var Y0=(t,e,n)=>e in t?K0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Zh=(t,e,n)=>Y0(t,typeof e!="symbol"?e+"":e,n);function X0(t){return e=>new Q(e.array.map(n=>Math.abs(n)),e.type,t)}function Z0(t){return e=>{let n=0,r=0;for(let i of e.array){let s=Number(i);isNaN(s)||(r++,n+=(s-n)/r)}return r===0?NaN:t.precision(n)}}var J0=Object.defineProperty,Q0=(t,e,n)=>e in t?J0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,e_=(t,e,n)=>Q0(t,typeof e!="symbol"?e+"":e,n),Cn=class t{constructor(e,n,r){this._definition=e,this.context=n,e_(this,"_udt");for(let i in e)this[i]=e[i];this._udt=r}get __def__(){return this._definition}copy(){return new t(this._fieldValues(),this.context,this._udt)}_fieldValues(){let e=new Set([...this._udt?._definitionKeys??[],...Object.keys(this._definition)]),n={};for(let r of e)Object.prototype.hasOwnProperty.call(this,r)&&(n[r]=this[r]);return n}toString(){let e={};for(let n in this.__def__){let r=this[n];r!=null&&typeof r=="object"&&typeof r.toString=="function"&&!(r instanceof Array)?e[n]=r.toString():e[n]=r}try{return JSON.stringify(e)}catch{return"{"+Object.keys(e).map(n=>`"${n}":${String(e[n])}`).join(",")+"}"}}},t_=Object.defineProperty,n_=(t,e,n)=>e in t?t_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Jh=(t,e,n)=>n_(t,typeof e!="symbol"?e+"":e,n),_=class t{constructor(e,n=0){this.data=e,this.offset=n,Jh(this,"beforeStart",NaN),Jh(this,"varip")}get(e){(e==null||Number.isNaN(e))&&(e=0);let n=this.offset+e;Number.isInteger(n)||(n=Math.trunc(n));let r=this.data.length-1-n;return r<0?this.beforeStart:r>=this.data.length?NaN:this.data[r]}set(e,n){let r=this.data.length-1-(this.offset+e);r>=0&&r<this.data.length&&(this.data[r]=n)}get length(){return this.data.length}toArray(){return this.data}static from(e){if(e instanceof t)return e;if(Array.isArray(e))return new t(e);if(e!=null&&typeof e=="object"&&"__value"in e){let n=e.__value;if(n instanceof t)return n;if(n===null||typeof n!="object")return new t([n])}return new t([e])}};function r_(t){if(!t||typeof t!="string")return null;if(t.startsWith("#")){let n=t.slice(1);return n.length===6?[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16),1]:n.length===8?[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16),parseInt(n.slice(6,8),16)/255]:null}let e=t.match(/rgba?\\(\\s*(\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*([\\d.]+))?\\s*\\)/);return e?[parseInt(e[1]),parseInt(e[2]),parseInt(e[3]),e[4]?parseFloat(e[4]):1]:null}function i_(t,e,n,r){let i=Math.round(Math.max(0,Math.min(255,t))).toString(16).padStart(2,"0"),s=Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0"),a=Math.round(Math.max(0,Math.min(255,n))).toString(16).padStart(2,"0");if(r>=1)return`#${i}${s}${a}`.toUpperCase();let o=Math.round(Math.max(0,Math.min(255,r*255))).toString(16).padStart(2,"0");return`#${i}${s}${a}${o}`.toUpperCase()}var Qe={aqua:"#00BCD4",black:"#363A45",blue:"#2962FF",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#F23645",silver:"#B2B5BE",teal:"#089981",white:"#FFFFFF",yellow:"#FDD835"};function Li(t){if(typeof t!="string")return null;let e=t.trim(),n=e.startsWith("color.")?e.slice(6):e;return Object.prototype.hasOwnProperty.call(Qe,n)&&(e=Qe[n]),r_(e)}function fa(t,e,n,r){let i=s=>Math.round(Math.max(0,Math.min(255,s))).toString(16).padStart(2,"0");return`#${i(t)}${i(e)}${i(n)}${i(r*255)}`.toUpperCase()}function s_(t){let e=Li(t);return e?fa(e[0],e[1],e[2],e[3]):t}function Zn(t){return typeof t=="function"&&(t=t()),t&&typeof t=="object"&&Array.isArray(t.data)&&typeof t.get=="function"&&(t=t.get(0)),t}var Jn=t=>t==null||typeof t=="number"&&isNaN(t),Hs=(t,e,n)=>Math.min(n,Math.max(e,t)),el="#00000000";function ui(t){if(t=Zn(t),Jn(t))return[0,0,0,0];let e=Li(t);return e?[e[0],e[1],e[2],Math.round(e[3]*255)/255]:null}var Cl=class{constructor(e){this.context=e}any(e){let n=_.from(e).get(0);return typeof n=="number"&&isNaN(n)?null:n}param(e,n=0){return _.from(e).get(n)}new(e,n){if(e=Zn(e),n=Zn(n),n===void 0||(n=Jn(n)?100:Hs(Math.trunc(n),0,100),Jn(e)&&(e="#000000"),typeof e!="string"))return e;let r=Math.round(255*(100-n)/100).toString(16).padStart(2,"0").toUpperCase();if(e.startsWith("#")){let a=e.slice(1);return`#${a.length===8?a.slice(0,6):a}${r}`}let i=Qe[e];if(i)return`#${i.slice(1)}${r}`;let s=e.match(/rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)/);if(s){let[a,o,l]=[s[1],s[2],s[3]].map(c=>parseInt(c).toString(16).padStart(2,"0"));return`#${a}${o}${l}${r}`}return`rgba(${e}, ${(100-n)/100})`}rgb(e,n,r,i){let s=u=>(u=Zn(u),Jn(u)?0:Hs(Math.trunc(u),0,255)),[a,o,l]=[s(e),s(n),s(r)];if(i=Zn(i),i===void 0)return`rgb(${a}, ${o}, ${l})`;let c=Jn(i)?100:Hs(i,0,100);return`rgba(${a}, ${o}, ${l}, ${(100-c)/100})`}from_gradient(e,n,r,i,s){if(e=Zn(e),n=Zn(n),r=Zn(r),Jn(e)||Jn(n)||Jn(r)||r===n)return el;if(r<n)return i=Zn(i),Jn(i)?el:i;let a=ui(i)??[0,0,0,0],o=ui(s)??[0,0,0,0],l=1-Hs((e-n)/(r-n),0,1),c=1-l,u=a[3]*l+o[3]*c;if(u===0)return el;let h=p=>Math.trunc((a[p]*a[3]*l+o[p]*o[3]*c)/u);return i_(h(0),h(1),h(2),Math.trunc(u*255)/255)}r(e){return ui(e)?.[0]??NaN}g(e){return ui(e)?.[1]??NaN}b(e){return ui(e)?.[2]??NaN}t(e){let n=ui(e);return n?Math.round((1-n[3])*100):NaN}aqua(){return Qe.aqua}black(){return Qe.black}blue(){return Qe.blue}fuchsia(){return Qe.fuchsia}gray(){return Qe.gray}green(){return Qe.green}lime(){return Qe.lime}maroon(){return Qe.maroon}navy(){return Qe.navy}olive(){return Qe.olive}orange(){return Qe.orange}purple(){return Qe.purple}red(){return Qe.red}silver(){return Qe.silver}teal(){return Qe.teal}white(){return Qe.white}yellow(){return Qe.yellow}},qn=(t=>(t[t.ascending=1]="ascending",t[t.descending=0]="descending",t))(qn||{}),su=(t=>(t.AED="AED",t.ARS="ARS",t.AUD="AUD",t.BDT="BDT",t.BHD="BHD",t.BRL="BRL",t.BTC="BTC",t.CAD="CAD",t.CHF="CHF",t.CLP="CLP",t.CNY="CNY",t.COP="COP",t.CZK="CZK",t.DKK="DKK",t.EGP="EGP",t.ETH="ETH",t.EUR="EUR",t.GBP="GBP",t.HKD="HKD",t.HUF="HUF",t.IDR="IDR",t.ILS="ILS",t.INR="INR",t.ISK="ISK",t.JPY="JPY",t.KES="KES",t.KRW="KRW",t.KWD="KWD",t.LKR="LKR",t.MAD="MAD",t.MXN="MXN",t.MYR="MYR",t.NGN="NGN",t.NOK="NOK",t.NONE="NONE",t.NZD="NZD",t.PEN="PEN",t.PHP="PHP",t.PKR="PKR",t.PLN="PLN",t.QAR="QAR",t.RON="RON",t.RSD="RSD",t.RUB="RUB",t.SAR="SAR",t.SEK="SEK",t.SGD="SGD",t.THB="THB",t.TND="TND",t.TRY="TRY",t.TWD="TWD",t.USD="USD",t.USDT="USDT",t.VES="VES",t.VND="VND",t.ZAR="ZAR",t))(su||{}),au=(t=>(t[t.sunday=1]="sunday",t[t.monday=2]="monday",t[t.tuesday=3]="tuesday",t[t.wednesday=4]="wednesday",t[t.thursday=5]="thursday",t[t.friday=6]="friday",t[t.saturday=7]="saturday",t))(au||{}),ou=(t=>(t.all="all",t.data_window="data_window",t.none="none",t.pane="pane",t.price_scale="price_scale",t.status_line="status_line",t))(ou||{}),ma=["pane","data_window","status_line","price_scale"],a_=[...ma,"all","none"];function ya(t){let e=new Set;if(typeof t!="string")return e;for(let n=0;n<t.length;){let r=a_.find(i=>t.startsWith(i,n));if(!r)break;if(r==="all")return new Set(ma);r!=="none"&&e.add(r),n+=r.length}return e}function $d(t){let e=ma.filter(n=>t.has(n));return e.length===ma.length?"all":e.length===0?"none":e.join("")}function zd(t,e){return $d(new Set([...ya(t),...ya(e)]))}function jd(t,e){let n=ya(t);for(let r of ya(e))n.delete(r);return $d(n)}var lu=(t=>(t.flag="shape_flag",t.arrowdown="shape_arrow_down",t.arrowup="shape_arrow_up",t.circle="shape_circle",t.cross="shape_cross",t.diamond="shape_diamond",t.labeldown="shape_label_down",t.labelup="shape_label_up",t.square="shape_square",t.triangledown="shape_triangle_down",t.triangleup="shape_triangle_up",t.xcross="shape_xcross",t))(lu||{}),cu=(t=>(t.abovebar="AboveBar",t.belowbar="BelowBar",t.absolute="Absolute",t.bottom="Bottom",t.top="Top",t))(cu||{}),uu=(t=>(t.auto="auto",t.tiny="tiny",t.small="small",t.normal="normal",t.large="large",t.huge="huge",t))(uu||{}),hu=(t=>(t.inherit="inherit",t.mintick="mintick",t.percent="percent",t.price="price",t.volume="volume",t))(hu||{}),qd=(t=>(t.linestyle_dashed="linestyle_dashed",t.linestyle_dotted="linestyle_dotted",t.linestyle_solid="linestyle_solid",t.style_area="style_area",t.style_areabr="style_areabr",t.style_circles="style_circles",t.style_columns="style_columns",t.style_cross="style_cross",t.style_histogram="style_histogram",t.style_line="style_line",t.style_linebr="style_linebr",t.style_stepline="style_stepline",t.style_stepline_diamond="style_stepline_diamond",t.style_steplinebr="style_steplinebr",t))(qd||{}),pu=(t=>(t.gaps_on="gaps_on",t.gaps_off="gaps_off",t.lookahead_on="lookahead_on",t.lookahead_off="lookahead_off",t))(pu||{}),du=(t=>(t.bar_index="bi",t.bar_time="bt",t))(du||{}),fu=(t=>(t.price="pr",t.abovebar="ab",t.belowbar="bl",t))(fu||{}),mu=(t=>(t.left="l",t.right="r",t.both="b",t.none="n",t))(mu||{}),yu=(t=>(t.align_bottom="bottom",t.align_top="top",t.align_left="left",t.align_center="center",t.align_right="right",t.wrap_auto="auto",t.wrap_none="none",t.format_bold="bold",t.format_italic="italic",t.format_none="none",t))(yu||{}),gu=(t=>(t.family_default="default",t.family_monospace="monospace",t))(gu||{}),_u=(t=>(t.none="none",t.splits="splits",t.dividends="dividends",t))(_u||{}),bu=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(bu||{}),xu=(t=>(t.actual="earnings_actual",t.estimate="earnings_estimate",t.standardized="earnings_standardized",t.future_eps="earnings_future_eps",t.future_period_end_time="earnings_future_period_end_time",t.future_revenue="earnings_future_revenue",t.future_time="earnings_future_time",t))(xu||{}),vu=(t=>(t.gross="dividends_gross",t.net="dividends_net",t.future_amount="dividends_future_amount",t.future_ex_date="dividends_future_ex_date",t.future_pay_date="dividends_future_pay_date",t))(vu||{}),wu=(t=>(t.denominator="splits_denominator",t.numerator="splits_numerator",t))(wu||{}),Su=(t=>(t.top_left="top_left",t.top_center="top_center",t.top_right="top_right",t.middle_left="middle_left",t.middle_center="middle_center",t.middle_right="middle_right",t.bottom_left="bottom_left",t.bottom_center="bottom_center",t.bottom_right="bottom_right",t))(Su||{}),Eu=(t=>(t.left="left",t.none="none",t.right="right",t))(Eu||{}),ku=(t=>(t.inherit="inherit",t.off="off",t.on="on",t))(ku||{}),Ud={order:qn,currency:su,dayofweek:au,display:{...ou,__union:zd,__minus:jd},shape:lu,location:cu,size:uu,format:hu,barmerge:pu,xloc:du,yloc:fu,extend:mu,text:yu,font:gu,adjustment:_u,backadjustment:bu,earnings:xu,dividends:vu,splits:wu,position:Su,scale:Eu,settlement_as_close:ku},o_=Object.freeze({__proto__:null,order:qn,currency:su,dayofweek:au,display:ou,displayUnion:zd,displayMinus:jd,shape:lu,location:cu,size:uu,format:hu,plot:qd,barmerge:pu,xloc:du,yloc:fu,extend:mu,text:yu,font:gu,adjustment:_u,backadjustment:bu,earnings:xu,dividends:vu,splits:wu,position:Su,scale:Eu,settlement_as_close:ku,default:Ud}),l_=Object.defineProperty,c_=(t,e,n)=>e in t?l_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,u_=(t,e,n)=>c_(t,typeof e!="symbol"?e+"":e,n),fe=class extends Error{constructor(e,n){super(e),u_(this,"method"),this.name="PineRuntimeError",this.method=n}};function ze(t){return t==null||typeof t=="number"&&isNaN(t)}var h_=/^(#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?|rgba?\\(.*\\))$/;function ga(t){if(typeof t!="string"||!h_.test(t))return null;let e=Li(t);return e?fa(e[0],e[1],e[2],e[3]):null}function Qh(t,e){if(typeof t=="number"&&typeof e=="number")return Math.abs(t-e)<=1e-10;if(t===e)return!0;if(typeof t=="string"&&typeof e=="string"){let n=ga(t);return n!==null&&n===ga(e)}return!1}function Au(t,e){if(t.type===Z.string){let n=ze(e)?"":e;return r=>Qh(ze(r)?"":r,n)}return ze(e)?t.type===Z.color&&!(t.context?.pineVersion>=6)?ze:()=>!1:n=>!ze(n)&&Qh(n,e)}function Fi(t,e){let n;for(let i=0;i<t.length;i++)if(t[i]instanceof Cn){n=t[i];break}if(!n)return null;let r;return typeof e=="string"?r=e:r=(n._udt?._definitionKeys??Object.keys(n.__def__))[e??0],i=>i instanceof Cn?i[r]:NaN}function Wd(t,e,n){let r=ze(t),i=ze(e);return r||i?r&&i?0:(r?1:-1)*(n?-1:1):n?t<e?-1:t>e?1:0:t-e}function Tu(t,e=qn.ascending){let n=t.some(i=>typeof i=="string"),r=t.map((i,s)=>s);return r.sort((i,s)=>Wd(t[i],t[s],n)||i-s),e!==qn.ascending&&r.reverse(),r}function p_(t,e=qn.ascending){let n=t.some(r=>typeof r=="string");return t.sort((r,i)=>Wd(r,i,n)),e!==qn.ascending&&t.reverse(),t}function Kr(t,e,n){throw new fe(`Index ${t} is out of bounds, array size is ${e}.`,n)}function lo(t){throw new fe(`Cannot call \\`${t}()\\` if array is empty.`,`array.${t}`)}function Hd(t,e){if(t<0||t>100)throw new fe(`Invalid value of the \'percentage\' argument (${t}) in the \'${e}\' function. It must be in the range [0..100].`,e)}function d_(t){return t.every(e=>typeof e=="number")?t.every(e=>Number.isInteger(e))?Z.int:Z.float:t.every(e=>typeof e=="string")?Z.string:t.every(e=>typeof e=="boolean")?Z.bool:Z.any}function Un(t){return typeof t=="number"?Number.isInteger(t)?Z.int:Z.float:typeof t=="string"?Z.string:typeof t=="boolean"?Z.bool:Z.any}function Cs(t,e){if(t===void 0||typeof t=="number"&&isNaN(t)||e===Z.any)return!0;switch(e){case Z.int:return Number.isInteger(t)||isNaN(t);case Z.float:return typeof t=="number";case Z.string:return typeof t=="string";case Z.bool:return typeof t=="boolean";case Z.box:case Z.label:case Z.line:case Z.linefill:case Z.table:case Z.color:return t===null||typeof t=="object"||typeof t=="string"}return!1}function f_(t){return(e,n,r)=>{let i=e.array,s=Fi(i,r)??(l=>l),a=0,o=i.length-1;for(;a<=o;){let l=Math.floor((a+o)/2),c=s(i[l]);if(c===n)return l;c<n?a=l+1:o=l-1}return-1}}function m_(t){return(e,n,r)=>{let i=e.array,s=Fi(i,r)??(l=>l),a=0,o=i.length;for(;a<o;){let l=Math.floor((a+o)/2);s(i[l])<n?a=l+1:o=l}return a<i.length&&s(i[a])===n?a:Math.max(a-1,0)}}function y_(t){return(e,n,r)=>{let i=e.array,s=Fi(i,r)??(l=>l),a=0,o=i.length;for(;a<o;){let l=Math.floor((a+o)/2);s(i[l])<=n?a=l+1:o=l}return a>0&&s(i[a-1])===n?a-1:a}}function g_(t){return e=>{e.array.length=0}}function __(t){return(e,n)=>(e.array.push(...n.array),e)}function b_(t){return e=>new Q([...e.array],e.type,t)}function x_(t){return(e,n,r=!0)=>{let i=e.array,s=n.array;if(i.length!==s.length)return NaN;let a=0,o=0,l=0,c=[];for(let f=0;f<i.length;f++){let m=Number(i[f]),y=Number(s[f]);!isNaN(m)&&m!==null&&m!==void 0&&!isNaN(y)&&y!==null&&y!==void 0&&(a+=m,o+=y,l++,c.push(f))}if(l===0)return NaN;let u=a/l,h=o/l,p=0;for(let f of c){let m=Number(i[f]),y=Number(s[f]);p+=(m-u)*(y-h)}let d=r?l:l-1;return d<=0?NaN:t.precision(p/d)}}function v_(t){return e=>e.array.length===0?!1:e.array.every(n=>!isNaN(n)&&n)}function w_(t){return(e,n,r=0,i)=>{let s=e.array.length,a=ze(r)?0:r,o=i===void 0||ze(i)?s:i;if((a<0||a>=s)&&Kr(a,s,"array.fill"),(o<0||o>s)&&Kr(o,s,"array.fill"),!Cs(n,e.type))throw new Error(`Cannot call \'array.fill\' with argument \'value\'=\'${n}\'. An argument of \'literal ${typeof n}\' type was used but a \'${e.type}\' is expected.`);let l=typeof n=="number"?t.precision(n):n;for(let c=a;c<o;c++)e.array[c]=l}}function S_(t){return e=>(e.array.length===0&&lo("first"),e.array[0])}function E_(t){return(e,n)=>{let r=n<0?e.array.length+n:n;if(r<0||r>=e.array.length)throw new fe(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.get");return e.array[r]}}function k_(t){return(e,n)=>e.array.some(Au(e,n))}function A_(t){return(e,n)=>e.array.findIndex(Au(e,n))}function T_(t){return(e,n,r)=>{if(!Cs(r,e.type))throw new Error(`Cannot call \'array.insert\' with argument \'value\'=\'${r}\'. An argument of \'literal ${typeof r}\' type was used but a \'${e.type}\' is expected.`);let i=n<0?e.array.length+n:n;if(i<0||i>e.array.length)throw new fe(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.insert");e.array.splice(i,0,r)}}function _a(t,e=0){let n=String(t).match(/^(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/);if(!n)return[String(t),""];let r=n[1]+(n[2]??""),i=n[1].length+Number(n[3]??0)+e;return i<=0&&(r="0".repeat(1-i)+r,i=1),i>r.length&&(r+="0".repeat(i-r.length)),[r.slice(0,i),r.slice(i)]}function N_(t,e,n){let r=new DataView(new ArrayBuffer(8));r.setFloat64(0,t);let i=r.getBigUint64(0),s=Number(i>>52n&0x7ffn),a=i&(1n<<52n)-1n,o;s===0?o=-1074:(a|=1n<<52n,o=s-1075);let l=a*10n**BigInt(n.length),c=BigInt(e+n||"0");return o>=0?l<<=BigInt(o):c<<=BigInt(-o),l>c?1:l<c?-1:0}function ba(t,e,n,r,i){if(n.length<=r)return[e,n];let s=e+n.slice(0,r),a=Number(n[r]),o=n.slice(r+1),l;if(a!==5||/[1-9]/.test(o))l=a>=5;else if(i==="halfUp")l=!0;else if(!/[1-9]/.test(s))l=!1;else{let u=N_(t,e,n);l=u>0||u===0&&Number(s[s.length-1])%2===1}if(l){let u=s.split(""),h=u.length-1;for(;h>=0&&u[h]==="9";)u[h--]="0";h>=0?u[h]=String(Number(u[h])+1):u.unshift("1"),s=u.join("")}let c=s.length-r;return[s.slice(0,c),s.slice(c)]}function C_(t){let e=0,n=!1,r=o=>{let l="",c=!1;for(;e<t.length;){let u=t[e];if(u==="\'"){if(t[e+1]==="\'"){l+="\'",e+=2;continue}c=!c,e++;continue}if(!c&&o(u))break;!c&&u==="%"&&(n=!0),l+=u,e++}return l},i=r(o=>/[#0,.]/.test(o)),s="";for(;e<t.length&&/[#0,.]/.test(t[e]);)s+=t[e++];let a=r(()=>!1);return{prefix:i,number:s,suffix:a,percent:n}}function bi(t,e,n){if(!Number.isFinite(t))return String(t);let{prefix:r,number:i,suffix:s,percent:a}=C_(e),[o,l=""]=i.split(".");if(!/[#0]/.test(i)){let[N]=ba(Math.abs(t),..._a(Math.abs(t)),0,n);return(t<0?"-":"")+r+s+(N.replace(/^0+(?=\\d)/,"")||"0")}let c=a?100:1,u=(o.match(/0/g)??[]).length,h=o.lastIndexOf(","),p=h>=0?o.length-h-1:0,d=(l.match(/0/g)??[]).length,f=l.length,m=Math.abs(t),[y,g]=_a(m,c===100?2:0),[w,k]=ba(m*c,y,g,f,n),S=!/[1-9]/.test(w+k),E=w.replace(/^0+/,""),T=k.padEnd(f,"0");for(;T.length>d&&T.endsWith("0");)T=T.slice(0,-1);return E.length<u&&(E=E.padStart(u,"0")),!E&&d===0&&(E="0"),p>0&&(E=E.replace(new RegExp(`\\\\B(?=(\\\\d{${p}})+(?!\\\\d))`,"g"),",")),(t<0&&(n==="halfEven"||!S)?"-":"")+r+E+(T?"."+T:"")+s}function Gd(t){if(!Number.isFinite(t))return String(t);let e=Math.abs(t),n=t<0?"-":"";if(e>=1e21){let[o,l]=e.toExponential().split("e"),[c,u]=ba(e,o.split(".")[0],o.split(".")[1]??"",10,"halfUp"),h=Number(l);return c.length>1&&(u=c.slice(1)+u,c=c[0],h++),u=u.replace(/0+$/,""),n+c+(u?"."+u:"")+"E"+h}let[r,i]=ba(e,..._a(e),10,"halfEven"),s=i.replace(/0+$/,""),a=r.replace(/^0+(?=\\d)/,"");return/[1-9]/.test(a+s)?n+a+(s?"."+s:""):"0"}function I_(t){if(Number.isNaN(t))return"NaN";if(!Number.isFinite(t))return t>0?"Infinity":"-Infinity";if(t===0)return"0.0";let e=Math.abs(t),n=t<0?"-":"";if(e>=.001&&e<1e7){let[o,l]=_a(e);return n+o+"."+(l||"0")}let[r,i]=e.toExponential().split("e"),[s,a]=r.split(".");return n+s+"."+(a||"0")+"E"+Number(i)}var M_=[[1e12,"T"],[1e9,"B"],[1e6,"M"],[1e3,"K"]];function P_(t){if(!Number.isFinite(t))return String(t);let e=Math.abs(t),n=M_.find(([s])=>e>=s),r=n?e/n[0]:e,i=bi(r,n?"#.###":"#","halfUp");return(t<0&&i!=="0"?"-":"")+i+(n?n[1]:"")}var ep=t=>t==null||typeof t=="number"&&Number.isNaN(t);function Kd(t,e,n){return t.type==="string"?ep(e)?"":String(e):typeof e=="number"?n(e):ep(e)?"NaN":String(e)}function D_(t){return Array.from(t.array,e=>Kd(t,e,Gd))}function Yd(t){let e=t.type==="float"||t.type!=="int"&&t.array.some(n=>typeof n=="number"&&!Number.isInteger(n)&&!Number.isNaN(n));return Array.from(t.array,n=>Kd(t,n,r=>Number.isNaN(r)?"NaN":e?I_(r):String(r)))}function O_(t){return(e,n="")=>Yd(e).join(n)}function R_(t){return e=>(e.array.length===0&&lo("last"),e.array[e.array.length-1])}function L_(t){return(e,n)=>{let r=e.array,i=Au(e,n);for(let s=r.length-1;s>=0;s--)if(i(r[s]))return s;return-1}}function F_(t){return(e,n=0)=>{let r=e.array,i=r.length;if(i===0)return t.NA;if(ze(n)&&(n=0),(n<0||n>=i)&&Kr(n,i,"array.max"),n===0){let a=NaN;for(let o=0;o<i;o++){let l=r[o];!ze(l)&&!(l<=a)&&(a=l)}return a}let s=r.filter(a=>!ze(a)).sort((a,o)=>o-a);return s.length?s[Math.min(n,s.length-1)]:t.NA}}function B_(t){return e=>{let n=e.array.filter(i=>!ze(i)).sort((i,s)=>i-s);if(n.length===0)return NaN;let r=Math.floor(n.length/2);return n.length%2!==0?n[r]:(n[r-1]+n[r])/2}}function V_(t){return(e,n=0)=>{let r=e.array,i=r.length;if(i===0)return t.NA;if(ze(n)&&(n=0),(n<0||n>=i)&&Kr(n,i,"array.min"),n===0){let a=NaN;for(let o=0;o<i;o++){let l=r[o];!ze(l)&&!(l>=a)&&(a=l)}return a}let s=r.filter(a=>!ze(a)).sort((a,o)=>a-o);return s.length?s[Math.min(n,s.length-1)]:t.NA}}function $_(t){return e=>{let n=new Map,r=0;for(let s of e.array){if(ze(s))continue;let a=(n.get(s)||0)+1;n.set(s,a),a>r&&(r=a)}let i=[];for(let[s,a]of n)a===r&&i.push(s);return i.sort((s,a)=>typeof s=="number"&&typeof a=="number"?s-a:typeof s=="string"&&typeof a=="string"?s<a?-1:s>a?1:0:0),i.length?i[0]:NaN}}var z_="array.percentile_linear_interpolation";function j_(t){return(e,n)=>{if(ze(n))return NaN;Hd(n,z_);let r=e.array,i=r.length;if(i===0)return NaN;let s=[];for(let u=0;u<i;u++){let h=r[u];ze(h)||s.push(Number(h))}let a=s.length<i;for(s.sort((u,h)=>u-h);s.length<i;)s.push(NaN);let o=n*i/100-.5;if(o<=0)return t.precision(s[0]);if(o>=i-1)return t.precision(s[i-1]);let l=Math.floor(o),c=o-l;return c===0?t.precision(s[l]):a?NaN:t.precision(s[l]*(1-c)+s[l+1]*c)}}function q_(t){return(e,n)=>{if(ze(n))return NaN;Hd(n,"array.percentile_nearest_rank");let r=e.array,i=r.length;if(i===0)return NaN;let s=new Array;for(let o=0;o<i;o++){let l=Number(r[o]);!isNaN(l)&&l!==null&&l!==void 0&&s.push(l)}if(s.length===0)return NaN;s.sort((o,l)=>o-l);let a=Math.ceil(n/100*i);return a<=0?s[0]:a>s.length?NaN:s[a-1]}}function U_(t){return(e,n)=>{let r=e.array.length;if(r===0)return NaN;(n<0||n>=r)&&Kr(n,r,"array.percentrank");let i=e.array[Math.floor(n)];if(ze(i))return NaN;let s=0;for(let o of e.array)!ze(o)&&o<=i&&s++;let a=r-1;return a<=0?NaN:(s-1)/a*100}}function W_(t){return e=>(e.array.length===0&&lo("pop"),e.array.pop())}function H_(t){return(e,n)=>{if(!Cs(n,e.type))throw new Error(`Cannot call \'array.push\' with argument \'value\'=\'${n}\'. An argument of \'literal ${typeof n}\' type was used but a \'${e.type}\' is expected.`);e.array.push(typeof n=="number"?t.precision(n):n)}}function G_(t){return e=>t.precision(t.pine.array.max(e)-t.pine.array.min(e))}function K_(t){return(e,n)=>{let r=n<0?e.array.length+n:n;if(r<0||r>=e.array.length)throw new fe(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.remove");return e.array.splice(r,1)[0]}}function Y_(t){return e=>{e.array.reverse()}}function X_(t){return(e,n,r)=>{if(!Cs(r,e.type))throw new Error(`Cannot call \'array.set\' with argument \'value\'=\'${r}\'. An argument of \'literal ${typeof r}\' type was used but a \'${e.type}\' is expected.`);let i=n<0?e.array.length+n:n;if(i<0||i>=e.array.length)throw new fe(`Index ${n} is out of bounds, array size is ${e.array.length}.`,"array.set");e.array[i]=typeof r=="number"?t.precision(r):r}}function Z_(t){return e=>(e.array.length===0&&lo("shift"),e.array.shift())}function J_(t){return e=>e.array.length}function Xi(t){if(typeof t!="string"||!/^(0|[1-9]\\d*)$/.test(t))return-1;let e=Number(t);return e<=4294967294?e:-1}function Q_(t,e,n){let r=[];r.length=n;let i=s=>{let a=r.length;s<a?t.splice(e+s,a-s):s>a&&t.splice(e+a,0,...new Array(s-a)),r.length=s};return new Proxy(r,{get(s,a,o){let l=Xi(a);return l!==-1?l<s.length?t[e+l]:void 0:Reflect.get(s,a,o)},set(s,a,o,l){if(a==="length")return i(Number(o)),!0;let c=Xi(a);return c!==-1?(c>=s.length&&i(c+1),t[e+c]=o,!0):Reflect.set(s,a,o,l)},has(s,a){let o=Xi(a);return o!==-1?o<s.length:Reflect.has(s,a)},deleteProperty(s,a){let o=Xi(a);return o!==-1?(o<s.length&&(t[e+o]=void 0),!0):Reflect.deleteProperty(s,a)},ownKeys(s){let a=[];for(let o=0;o<s.length;o++)a.push(String(o));return a.concat(Reflect.ownKeys(s))},getOwnPropertyDescriptor(s,a){let o=Xi(a);return o!==-1?o>=s.length?void 0:{value:t[e+o],writable:!0,enumerable:!0,configurable:!0}:Reflect.getOwnPropertyDescriptor(s,a)}})}function eb(t){return(e,n=0,r)=>{let i=e.array.length,s=ze(n)?0:n,a=r===void 0||ze(r)?i:r;if((s<0||s>=i)&&Kr(s,i,"array.slice"),(a<0||a>i)&&Kr(a,i,"array.slice"),s>a)throw new fe("Index \'from\' should be less than index \'to\'.","array.slice");return new Q(Q_(e.array,s,a-s),e.type,t)}}function tb(t){return e=>e.array.some(n=>!isNaN(n)&&n)}function nb(t){return(e,n=qn.ascending,r)=>{let i=e.array,s=Array.from(i),a=Fi(s,r),o=a?Tu(s.map(a),n).map(l=>s[l]):p_(s,n);for(let l=0;l<o.length;l++)i[l]=o[l]}}function rb(t){return(e,n=qn.ascending,r)=>{let i=Array.from(e.array),s=Fi(i,r);return new Q(Tu(s?i.map(s):i,n),Z.int,t)}}function ib(t){return e=>{let n=t.array.avg(e),r=t.array.stdev(e);return isNaN(r)?new Q(e.array.map(()=>NaN),Z.float,t):r===0?new Q(e.array.map(()=>1),Z.float,t):new Q(e.array.map(i=>(i-n)/r),Z.float,t)}}function sb(t){return(e,n=!0)=>{let r=e.array,i=r.length;if(i===0)return NaN;let s=0,a=0,o=0;for(let u=0;u<i;u++){let h=Number(r[u]);!isNaN(h)&&h!==null&&h!==void 0&&(s+=h,a+=h*h,o++)}if(o===0)return NaN;let l=s/o,c=a/o-l*l;return c<0?NaN:(!n&&o>1&&(c=c*o/(o-1)),!n&&o===1?NaN:t.precision(Math.sqrt(c)))}}function ab(t){return e=>{let n=0,r=0;for(let i of e.array){let s=Number(i);isNaN(s)||(n+=s,r++)}return r===0?NaN:t.precision(n)}}function ob(t){return(e,n)=>{if(!Cs(n,e.type))throw new Error(`Cannot call \'array.unshift\' with argument \'value\'=\'${n}\'. An argument of \'literal ${typeof n}\' type was used but a \'${e.type}\' is expected.`);e.array.unshift(typeof n=="number"?t.precision(n):n)}}function lb(t){return(e,n=!0)=>{let r=0,i=0;for(let l of e.array){let c=Number(l);!isNaN(c)&&c!==null&&c!==void 0&&(r+=c,i++)}if(i===0)return NaN;let s=r/i,a=0;for(let l of e.array){let c=Number(l);!isNaN(c)&&c!==null&&c!==void 0&&(a+=(c-s)*(c-s))}let o=n?i:i-1;return o<=0?NaN:t.precision(a/o)}}var cb=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype;function M(t,e,n=0){if(!e)return t;let r=t.length;for(;r>0&&t[r-1]===void 0;)r--;let i=t[r-1];if(!cb(i))return t;let s=Object.keys(i);if(!s.some(o=>e.indexOf(o)>=n))return t;let a=t.slice(0,r-1);for(let o of s){let l=e.indexOf(o)-n;l>=0&&(a[l]=i[o]instanceof _?i[o].get(0):i[o])}return a}function P(t,e){return e?(...n)=>t(...M(n,e)):t}var re=["id"],Ue=t=>["id",t],q={abs:re,avg:re,binary_search:["id","val","sort_field"],binary_search_leftmost:["id","val","sort_field"],binary_search_rightmost:["id","val","sort_field"],clear:re,concat:["id1","id2"],copy:re,covariance:["id1","id2","biased"],every:re,fill:["id","value","index_from","index_to"],first:re,get:Ue("index"),includes:Ue("value"),indexof:Ue("value"),insert:["id","index","value"],join:Ue("separator"),last:re,lastindexof:Ue("value"),max:Ue("nth"),median:re,min:Ue("nth"),mode:re,percentile_linear_interpolation:Ue("percentage"),percentile_nearest_rank:Ue("percentage"),percentrank:Ue("index"),pop:re,push:Ue("value"),range:re,remove:Ue("index"),reverse:re,set:["id","index","value"],shift:re,size:re,slice:["id","index_from","index_to"],some:re,sort:["id","order","sort_field"],sort_indices:["id","order","sort_field"],standardize:re,stdev:Ue("biased"),sum:re,unshift:Ue("value"),variance:Ue("biased")},F={add_col:["id","column","array_id"],add_row:["id","row","array_id"],avg:re,col:Ue("column"),columns:re,concat:["id1","id2"],copy:re,det:re,diff:["id1","id2"],eigenvalues:re,eigenvectors:re,elements_count:re,fill:["id","value","from_row","to_row","from_column","to_column"],get:["id","row","column"],inv:re,is_antidiagonal:re,is_antisymmetric:re,is_binary:re,is_diagonal:re,is_identity:re,is_square:re,is_stochastic:re,is_symmetric:re,is_triangular:re,is_zero:re,kron:["id1","id2"],max:re,median:re,min:re,mode:re,mult:["id1","id2"],pinv:re,pow:Ue("power"),rank:re,remove_col:Ue("column"),remove_row:Ue("row"),reshape:["id","rows","columns"],reverse:re,row:Ue("row"),rows:re,set:["id","row","column","value"],sort:["id","column","order","sort_field"],submatrix:["id","from_row","to_row","from_column","to_column"],sum:["id1","id2"],swap_columns:["id","column1","column2"],swap_rows:["id","row1","row2"],trace:re,transpose:re},et={clear:re,contains:Ue("key"),copy:re,get:Ue("key"),keys:re,put:["id","key","value"],put_all:["id","id2"],remove:Ue("key"),size:re,values:re},ub=Object.defineProperty,hb=(t,e,n)=>e in t?ub(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,he=(t,e,n)=>hb(t,typeof e!="symbol"?e+"":e,n),Z=(t=>(t.any="",t.box="box",t.bool="bool",t.color="color",t.float="float",t.int="int",t.label="label",t.line="line",t.linefill="linefill",t.string="string",t.table="table",t))(Z||{}),Q=class{constructor(e,n,r){this.array=e,this.type=n,this.context=r,he(this,"_abs"),he(this,"_avg"),he(this,"_binary_search"),he(this,"_binary_search_leftmost"),he(this,"_binary_search_rightmost"),he(this,"_clear"),he(this,"_concat"),he(this,"_copy"),he(this,"_covariance"),he(this,"_every"),he(this,"_fill"),he(this,"_first"),he(this,"_get"),he(this,"_includes"),he(this,"_indexof"),he(this,"_insert"),he(this,"_join"),he(this,"_last"),he(this,"_lastindexof"),he(this,"_max"),he(this,"_median"),he(this,"_min"),he(this,"_mode"),he(this,"_percentile_linear_interpolation"),he(this,"_percentile_nearest_rank"),he(this,"_percentrank"),he(this,"_pop"),he(this,"_push"),he(this,"_range"),he(this,"_remove"),he(this,"_reverse"),he(this,"_set"),he(this,"_shift"),he(this,"_size"),he(this,"_slice"),he(this,"_some"),he(this,"_sort"),he(this,"_sort_indices"),he(this,"_standardize"),he(this,"_stdev"),he(this,"_sum"),he(this,"_unshift"),he(this,"_variance"),this._abs=X0(this.context),this._avg=Z0(this.context),this._binary_search=f_(this.context),this._binary_search_leftmost=m_(this.context),this._binary_search_rightmost=y_(this.context),this._clear=g_(this.context),this._concat=__(this.context),this._copy=b_(this.context),this._covariance=x_(this.context),this._every=v_(this.context),this._fill=w_(this.context),this._first=S_(this.context),this._get=E_(this.context),this._includes=k_(this.context),this._indexof=A_(this.context),this._insert=T_(this.context),this._join=O_(this.context),this._last=R_(this.context),this._lastindexof=L_(this.context),this._max=F_(this.context),this._median=B_(this.context),this._min=V_(this.context),this._mode=$_(this.context),this._percentile_linear_interpolation=j_(this.context),this._percentile_nearest_rank=q_(this.context),this._percentrank=U_(this.context),this._pop=W_(this.context),this._push=H_(this.context),this._range=G_(this.context),this._remove=K_(this.context),this._reverse=Y_(this.context),this._set=X_(this.context),this._shift=Z_(this.context),this._size=J_(this.context),this._slice=eb(this.context),this._some=tb(this.context),this._sort=nb(this.context),this._sort_indices=rb(this.context),this._standardize=ib(this.context),this._stdev=sb(this.context),this._sum=ab(this.context),this._unshift=ob(this.context),this._variance=lb(this.context)}get length(){return this.array.length}toString(){return"["+D_(this).join(", ")+"]"}[Symbol.iterator](){return this.array[Symbol.iterator]()}abs(...e){return this._abs(this,...M(e,q.abs,1))}avg(...e){return this._avg(this,...M(e,q.avg,1))}binary_search(...e){return this._binary_search(this,...M(e,q.binary_search,1))}binary_search_leftmost(...e){return this._binary_search_leftmost(this,...M(e,q.binary_search_leftmost,1))}binary_search_rightmost(...e){return this._binary_search_rightmost(this,...M(e,q.binary_search_rightmost,1))}clear(...e){return this._clear(this,...M(e,q.clear,1))}concat(...e){return this._concat(this,...M(e,q.concat,1))}copy(...e){return this._copy(this,...M(e,q.copy,1))}covariance(...e){return this._covariance(this,...M(e,q.covariance,1))}every(...e){return this._every(this,...M(e,q.every,1))}fill(...e){return this._fill(this,...M(e,q.fill,1))}first(...e){return this._first(this,...M(e,q.first,1))}get(...e){return this._get(this,...M(e,q.get,1))}includes(...e){return this._includes(this,...M(e,q.includes,1))}indexof(...e){return this._indexof(this,...M(e,q.indexof,1))}insert(...e){return this._insert(this,...M(e,q.insert,1))}join(...e){return this._join(this,...M(e,q.join,1))}last(...e){return this._last(this,...M(e,q.last,1))}lastindexof(...e){return this._lastindexof(this,...M(e,q.lastindexof,1))}max(...e){return this._max(this,...M(e,q.max,1))}median(...e){return this._median(this,...M(e,q.median,1))}min(...e){return this._min(this,...M(e,q.min,1))}mode(...e){return this._mode(this,...M(e,q.mode,1))}percentile_linear_interpolation(...e){return this._percentile_linear_interpolation(this,...M(e,q.percentile_linear_interpolation,1))}percentile_nearest_rank(...e){return this._percentile_nearest_rank(this,...M(e,q.percentile_nearest_rank,1))}percentrank(...e){return this._percentrank(this,...M(e,q.percentrank,1))}pop(...e){return this._pop(this,...M(e,q.pop,1))}push(...e){return this._push(this,...M(e,q.push,1))}range(...e){return this._range(this,...M(e,q.range,1))}remove(...e){return this._remove(this,...M(e,q.remove,1))}reverse(...e){return this._reverse(this,...M(e,q.reverse,1))}set(...e){return this._set(this,...M(e,q.set,1))}shift(...e){return this._shift(this,...M(e,q.shift,1))}size(...e){return this._size(this,...M(e,q.size,1))}slice(...e){return this._slice(this,...M(e,q.slice,1))}some(...e){return this._some(this,...M(e,q.some,1))}sort(...e){return this._sort(this,...M(e,q.sort,1))}sort_indices(...e){return this._sort_indices(this,...M(e,q.sort_indices,1))}standardize(...e){return this._standardize(this,...M(e,q.standardize,1))}stdev(...e){return this._stdev(this,...M(e,q.stdev,1))}sum(...e){return this._sum(this,...M(e,q.sum,1))}unshift(...e){return this._unshift(this,...M(e,q.unshift,1))}variance(...e){return this._variance(this,...M(e,q.variance,1))}};function pb(t){return(...e)=>{let n=d_(e);return new Q([...e],n===Z.int?Z.float:n,t)}}var tp=1e5;function jt(t,e){if(!Number.isFinite(t)||t>tp)throw new fe(`The requested size exceeds the ${tp} element limit.`,e)}var db=40;function Xd(t,e){if(t.secondaryContextCount=(t.secondaryContextCount||0)+1,t.secondaryContextCount>db)throw new fe("The script executes too many request.*() function calls.",e)}var Zd=1e5;function fb(t){return(e,n)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;if(jt(r,"array.new"),n===void 0){let i=r?Array(r).fill(NaN):[];return new Q(i,Z.any,t)}return new Q(Array(r).fill(t.precision(n||0)),Un(n||0),t)}}function mb(t){return(e=0,n)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;jt(r,"array.new");let i=n===void 0?t.pineVersion>=6?!1:NaN:n;return new Q(Array(r).fill(i),Z.bool,t)}}function yb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.box,t)}}function gb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.color,t)}}function _b(t){return(e=0,n=NaN)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(t.precision(n)),Z.float,t)}}function bb(t){return(e=0,n=NaN)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(t.precision(n)),Z.int,t)}}function xb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.label,t)}}function vb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.line,t)}}function wb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.linefill,t)}}function Sb(t){return(e=0,n="")=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.string,t)}}function Eb(t){return(e=0,n=null)=>{let r=typeof e=="number"&&e>0&&!isNaN(e)?Math.floor(e):0;return jt(r,"array.new"),new Q(Array(r).fill(n),Z.table,t)}}function kb(t){return(e,n=0)=>_.from(e).get(n)}function Ab(t){return(...e)=>new Q([...e],Z.int,t)}var Il=class{constructor(e){this.context=e,this.abs=P((n,...r)=>n.abs(...r),q.abs),this.avg=P((n,...r)=>n.avg(...r),q.avg),this.binary_search=P((n,...r)=>n.binary_search(...r),q.binary_search),this.binary_search_leftmost=P((n,...r)=>n.binary_search_leftmost(...r),q.binary_search_leftmost),this.binary_search_rightmost=P((n,...r)=>n.binary_search_rightmost(...r),q.binary_search_rightmost),this.clear=P((n,...r)=>n.clear(...r),q.clear),this.concat=P((n,...r)=>n.concat(...r),q.concat),this.copy=P((n,...r)=>n.copy(...r),q.copy),this.covariance=P((n,...r)=>n.covariance(...r),q.covariance),this.every=P((n,...r)=>n.every(...r),q.every),this.fill=P((n,...r)=>n.fill(...r),q.fill),this.first=P((n,...r)=>n.first(...r),q.first),this.from=pb(e),this.get=P((n,...r)=>n.get(...r),q.get),this.includes=P((n,...r)=>n.includes(...r),q.includes),this.indexof=P((n,...r)=>n.indexof(...r),q.indexof),this.insert=P((n,...r)=>n.insert(...r),q.insert),this.join=P((n,...r)=>n.join(...r),q.join),this.last=P((n,...r)=>n.last(...r),q.last),this.lastindexof=P((n,...r)=>n.lastindexof(...r),q.lastindexof),this.max=P((n,...r)=>n.max(...r),q.max),this.median=P((n,...r)=>n.median(...r),q.median),this.min=P((n,...r)=>n.min(...r),q.min),this.mode=P((n,...r)=>n.mode(...r),q.mode),this.new=fb(e),this.new_bool=mb(e),this.new_box=yb(e),this.new_color=gb(e),this.new_float=_b(e),this.new_int=bb(e),this.new_label=xb(e),this.new_line=vb(e),this.new_linefill=wb(e),this.new_string=Sb(e),this.new_table=Eb(e),this.param=kb(),this.percentile_linear_interpolation=P((n,...r)=>n.percentile_linear_interpolation(...r),q.percentile_linear_interpolation),this.percentile_nearest_rank=P((n,...r)=>n.percentile_nearest_rank(...r),q.percentile_nearest_rank),this.percentrank=P((n,...r)=>n.percentrank(...r),q.percentrank),this.pop=P((n,...r)=>n.pop(...r),q.pop),this.push=P((n,...r)=>n.push(...r),q.push),this.range=P((n,...r)=>n.range(...r),q.range),this.remove=P((n,...r)=>n.remove(...r),q.remove),this.reverse=P((n,...r)=>n.reverse(...r),q.reverse),this.set=P((n,...r)=>n.set(...r),q.set),this.shift=P((n,...r)=>n.shift(...r),q.shift),this.size=P((n,...r)=>n.size(...r),q.size),this.slice=P((n,...r)=>n.slice(...r),q.slice),this.some=P((n,...r)=>n.some(...r),q.some),this.sort=P((n,...r)=>n.sort(...r),q.sort),this.sort_indices=P((n,...r)=>n.sort_indices(...r),q.sort_indices),this.standardize=P((n,...r)=>n.standardize(...r),q.standardize),this.stdev=P((n,...r)=>n.stdev(...r),q.stdev),this.sum=P((n,...r)=>n.sum(...r),q.sum),this.unshift=P((n,...r)=>n.unshift(...r),q.unshift),this.variance=P((n,...r)=>n.variance(...r),q.variance),this.__from_int=Ab(e)}};function Tb(t){return e=>{e.map.clear()}}function Is(t,e){if(t.has(e))return e;let n=ga(e);if(n===null)return e;for(let r of t.keys())if(ga(r)===n)return r;return e}function Nb(t){return(e,n)=>e.map.has(Is(e.map,n))}function Cb(t){return e=>{let n=new fs(t);return n.map=new Map(e.map),n.valueType=e.valueType,n}}function Ib(t){return(e,n)=>{let r=e.map.get(Is(e.map,n));return r===void 0?e.valueType==="string"?"":NaN:r}}function Mb(t){return e=>{let n=Array.from(e.map.keys()),r=Un(n[0]);return new Q(n,r,t)}}function Pb(t){return(e,n,r)=>{let i=Is(e.map,n),s=e.map.get(i);return e.map.set(i,r),s===void 0?NaN:s}}function Db(t){return(e,n)=>{for(let[r,i]of n.map)e.map.set(Is(e.map,r),i)}}function Ob(t){return(e,n)=>{let r=Is(e.map,n),i=e.map.get(r);return e.map.delete(r)?i:NaN}}function Rb(t){return e=>e.map.size}function Lb(t){return e=>{let n=Array.from(e.map.values()),r=Un(n[0]);return new Q(n,r,t)}}var Fb=Object.defineProperty,Bb=(t,e,n)=>e in t?Fb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tn=(t,e,n)=>Bb(t,typeof e!="symbol"?e+"":e,n),fs=class{constructor(e){this.context=e,tn(this,"map"),tn(this,"valueType"),tn(this,"_clear"),tn(this,"_contains"),tn(this,"_copy"),tn(this,"_get"),tn(this,"_keys"),tn(this,"_put"),tn(this,"_put_all"),tn(this,"_remove"),tn(this,"_size"),tn(this,"_values"),this.map=new Map,this._clear=Tb(this.context),this._contains=Nb(this.context),this._copy=Cb(this.context),this._get=Ib(this.context),this._keys=Mb(this.context),this._put=Pb(this.context),this._put_all=Db(this.context),this._remove=Ob(this.context),this._size=Rb(this.context),this._values=Lb(this.context)}toString(){return`PineMapObject(${this.map.size})`}clear(...e){return this._clear(this,...M(e,et.clear,1))}contains(...e){return this._contains(this,...M(e,et.contains,1))}copy(...e){return this._copy(this,...M(e,et.copy,1))}get(...e){return this._get(this,...M(e,et.get,1))}keys(...e){return this._keys(this,...M(e,et.keys,1))}put(...e){return this._put(this,...M(e,et.put,1))}put_all(...e){return this._put_all(this,...M(e,et.put_all,1))}remove(...e){return this._remove(this,...M(e,et.remove,1))}size(...e){return this._size(this,...M(e,et.size,1))}values(...e){return this._values(this,...M(e,et.values,1))}};function Vb(t){return e=>{let n=new fs(t);return e==="string"&&(n.valueType=e),n}}function $b(t){return(e,n=0)=>_.from(e).get(n)}var Ml=class{constructor(e){this.context=e,this.clear=P((n,...r)=>n.clear(...r),et.clear),this.contains=P((n,...r)=>n.contains(...r),et.contains),this.copy=P((n,...r)=>n.copy(...r),et.copy),this.get=P((n,...r)=>n.get(...r),et.get),this.keys=P((n,...r)=>n.keys(...r),et.keys),this.new=Vb(e),this.param=$b(),this.put=P((n,...r)=>n.put(...r),et.put),this.put_all=P((n,...r)=>n.put_all(...r),et.put_all),this.remove=P((n,...r)=>n.remove(...r),et.remove),this.size=P((n,...r)=>n.size(...r),et.size),this.values=P((n,...r)=>n.values(...r),et.values)}};function zb(t){return(e,n,r)=>{let i=e.matrix.length,s=[];if(r&&(r instanceof Q?s=r.array:Array.isArray(r)?s=r:s=[r]),i===0){for(let l=0;l<s.length;l++){let c=s[l];c instanceof _&&(c=c.get(0)),e.matrix.push([c])}return}let a=e.matrix[0].length,o=n!==void 0?n:a;for(let l=0;l<i;l++){let c=l<s.length?s[l]:NaN;c instanceof _&&(c=c.get(0)),e.matrix[l].splice(o,0,c)}}}function jb(t){return(e,n,r)=>{let i=e.matrix.length,s=[];if(r)if(r instanceof Q)s=r.array;else if(Array.isArray(r))s=r;else if(r instanceof _){let c=r.get(0);Array.isArray(c)?s=c:s=[c]}else s=[r];let a=i>0?e.matrix[0].length:s.length,o=n!==void 0?n:i,l=[];for(let c=0;c<a;c++)if(c<s.length){let u=s[c];u instanceof _&&(u=u.get(0)),l.push(u)}else l.push(NaN);e.matrix.splice(o,0,l)}}function qb(t){return e=>{let n=e.matrix.length;if(n===0)return NaN;let r=e.matrix[0].length;if(r===0)return NaN;let i=0,s=0;for(let a=0;a<n;a++)for(let o=0;o<r;o++){let l=e.matrix[a][o];isNaN(l)||(i+=l,s++)}return s===0?NaN:i/s}}function Ub(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n<0||n>=i)throw new fe(`Column index ${n} is out of bounds, matrix has ${i} columns.`,"matrix.col");let s=[];for(let o=0;o<r;o++)s.push(e.matrix[o][n]);let a=Un(s[0]);return new Q(s,a,t)}}function Wb(t){return e=>e.matrix.length===0?0:e.matrix[0].length}function Hb(t){return(e,n)=>{let r=e.matrix.length,i=n.matrix.length;if(r===0){for(let o=0;o<i;o++)e.matrix.push([...n.matrix[o]]);return}let s=e.matrix[0].length,a=i>0?n.matrix[0].length:0;if(s!==a&&i>0){console.error(`matrix.concat: Column count mismatch ${s} vs ${a}`);return}for(let o=0;o<i;o++)e.matrix.push([...n.matrix[o]])}}function Gb(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0,i=new be(n,r,NaN,t);return i.matrix=e.matrix.map(s=>[...s]),i}}function Kb(t){let e=t.length;if(e===0)return 0;if(e===1)return t[0][0];if(e===2)return t[0][0]*t[1][1]-t[0][1]*t[1][0];let n=t.map(i=>[...i]),r=1;for(let i=0;i<e;i++){let s=i;for(;s<e&&n[s][i]===0;)s++;if(s===e)return 0;s!==i&&([n[i],n[s]]=[n[s],n[i]],r*=-1),r*=n[i][i];for(let a=i+1;a<e;a++){let o=n[a][i]/n[i][i];for(let l=i;l<e;l++)n[a][l]-=o*n[i][l]}}return r}function Yb(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;return n!==r?NaN:Kb(e.matrix)}}function Xb(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new be(0,0,NaN,t);let i=e.matrix[0].length,s=new be(r,i,NaN,t);if(n instanceof be)for(let a=0;a<r;a++)for(let o=0;o<i;o++){let l=e.matrix[a][o],c=n.matrix[a]&&n.matrix[a][o]!==void 0?n.matrix[a][o]:NaN;s.matrix[a][o]=l-c}else{let a=n;for(let o=0;o<r;o++)for(let l=0;l<i;l++)s.matrix[o][l]=e.matrix[o][l]-a}return s}}function Zb(t){let e=t.length;if(e!==2)return Array(e).fill(NaN);let n=t[0][0],r=t[0][1],i=t[1][0],s=t[1][1],a=n+s,o=n*s-r*i,l=a*a-4*o;if(l<0)return[NaN,NaN];let c=(a+Math.sqrt(l))/2,u=(a-Math.sqrt(l))/2;return[c,u]}function Jb(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r){let a=Un(e.matrix[0][0]);return new Q([],a,t)}let i=Zb(e.matrix),s=Un(i[0]);return new Q(i,s,t)}}function Qb(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new be(0,0,NaN,t);let i=new be(n,r,0,t);for(let s=0;s<n;s++)i.matrix[s][s]=1;return i}}function ex(t){return e=>{let n=e.matrix.length;return n===0?0:n*e.matrix[0].length}}function tx(t){return(e,n,r,i,s,a)=>{let o=e.matrix.length;if(o===0)return;let l=e.matrix[0].length,c=r!==void 0?r:0,u=i!==void 0?i:o,h=s!==void 0?s:0,p=a!==void 0?a:l;for(let d=c;d<u&&!(d>=o);d++)for(let f=h;f<p&&!(f>=l);f++)e.matrix[d][f]=n}}function nx(t){return(e,n,r)=>{let i=e.matrix.length,s=i>0?e.matrix[0].length:0;if(n<0||n>=i)throw new fe(`Row index ${n} is out of bounds, matrix has ${i} rows.`,"matrix.get");if(r<0||r>=s)throw new fe(`Column index ${r} is out of bounds, matrix has ${s} columns.`,"matrix.get");let a=e.matrix[n][r];return a===void 0?NaN:a}}function oa(t){let e=t.length;if(e===0)return[];let n=new Array(e);for(let i=0;i<e;i++){n[i]=new Array(2*e);for(let s=0;s<e;s++)n[i][s]=t[i][s];for(let s=0;s<e;s++)n[i][e+s]=i===s?1:0}for(let i=0;i<e;i++){let s=Math.abs(n[i][i]),a=i;for(let l=i+1;l<e;l++){let c=Math.abs(n[l][i]);c>s&&(s=c,a=l)}if(s<1e-14)return t.map(l=>l.map(()=>NaN));if(a!==i){let l=n[i];n[i]=n[a],n[a]=l}let o=n[i][i];for(let l=i;l<2*e;l++)n[i][l]/=o;for(let l=0;l<e;l++){if(l===i)continue;let c=n[l][i];if(c!==0)for(let u=i;u<2*e;u++)n[l][u]-=c*n[i][u]}}let r=new Array(e);for(let i=0;i<e;i++){r[i]=new Array(e);for(let s=0;s<e;s++)r[i][s]=n[i][e+s]}return r}function rx(t){return e=>{let n=e.matrix.length,r=n>0?e.matrix[0].length:0;if(n!==r)return new be(n,r,NaN,t);let i=oa(e.matrix),s=new be(n,r,NaN,t);return s.matrix=i,s}}function ix(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;for(let i=0;i<n;i++)for(let s=0;s<r;s++)if(i+s!==n-1&&e.matrix[i][s]!==0)return!1;return!0}}function sx(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;for(let i=0;i<n;i++)for(let s=0;s<r;s++)if(e.matrix[s][i]!==-e.matrix[i][s])return!1;return!0}}function ax(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;for(let i=0;i<n;i++)for(let s=0;s<r;s++){let a=e.matrix[i][s];if(a!==0&&a!==1)return!1}return!0}}function ox(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;for(let i=0;i<n;i++)for(let s=0;s<r;s++)if(i!==s&&e.matrix[i][s]!==0)return!1;return!0}}function lx(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;for(let i=0;i<n;i++)for(let s=0;s<r;s++)if(i===s){if(e.matrix[i][s]!==1)return!1}else if(e.matrix[i][s]!==0)return!1;return!0}}function cx(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;return n===r}}function ux(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;for(let i=0;i<n;i++){let s=0;for(let a=0;a<r;a++){let o=e.matrix[i][a];if(o<0)return!1;s+=o}if(Math.abs(s-1)>1e-10)return!1}return!0}}function hx(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;for(let i=0;i<n;i++)for(let s=0;s<i;s++)if(e.matrix[i][s]!==e.matrix[s][i])return!1;return!0}}function px(t){return e=>{let n=e.matrix.length;if(n===0)return!1;let r=e.matrix[0].length;if(n!==r)return!1;let i=!0,s=!0;for(let a=0;a<n;a++)for(let o=0;o<r;o++)a>o&&e.matrix[a][o]!==0&&(i=!1),a<o&&e.matrix[a][o]!==0&&(s=!1);return i||s}}function dx(t){return e=>{let n=e.matrix.length;if(n===0)return!0;let r=e.matrix[0].length;for(let i=0;i<n;i++)for(let s=0;s<r;s++)if(e.matrix[i][s]!==0)return!1;return!0}}function fx(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0,s=n.matrix.length,a=s>0?n.matrix[0].length:0,o=r*s,l=i*a,c=new be(o,l,NaN,t);for(let u=0;u<r;u++)for(let h=0;h<i;h++){let p=e.matrix[u][h];for(let d=0;d<s;d++)for(let f=0;f<a;f++){let m=n.matrix[d][f];c.matrix[u*s+d][h*a+f]=p*m}}return c}}function mx(t){return e=>{let n=e.matrix.length;if(n===0)return NaN;let r=e.matrix[0].length,i=-1/0,s=!1;for(let a=0;a<n;a++)for(let o=0;o<r;o++){let l=e.matrix[a][o];isNaN(l)||(l>i&&(i=l),s=!0)}return s?i:NaN}}function yx(t){return e=>{let n=e.matrix.length;if(n===0)return NaN;let r=e.matrix[0].length,i=[];for(let a=0;a<n;a++)for(let o=0;o<r;o++){let l=e.matrix[a][o];isNaN(l)||i.push(l)}if(i.length===0)return NaN;i.sort((a,o)=>a-o);let s=Math.floor(i.length/2);return i.length%2!==0?i[s]:(i[s-1]+i[s])/2}}function gx(t){return e=>{let n=e.matrix.length;if(n===0)return NaN;let r=e.matrix[0].length,i=1/0,s=!1;for(let a=0;a<n;a++)for(let o=0;o<r;o++){let l=e.matrix[a][o];isNaN(l)||(l<i&&(i=l),s=!0)}return s?i:NaN}}function _x(t){return e=>{let n=e.matrix.length;if(n===0)return NaN;let r=e.matrix[0].length,i=new Map,s=0,a=NaN;for(let o=0;o<n;o++)for(let l=0;l<r;l++){let c=e.matrix[o][l];if(!isNaN(c)){let u=(i.get(c)||0)+1;i.set(c,u),u>s?(s=u,a=c):u===s&&c<a&&(a=c)}}return a}}function bx(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(n instanceof be){let s=n.matrix.length,a=s>0?n.matrix[0].length:0;if(i!==s)return new be(0,0,NaN,t);let o=new be(r,a,0,t);for(let l=0;l<r;l++)for(let c=0;c<a;c++){let u=0;for(let h=0;h<i;h++)u+=e.matrix[l][h]*n.matrix[h][c];o.matrix[l][c]=u}return o}else if(n instanceof Q||Array.isArray(n.array||n)){let s=n.array||n;if(i!==s.length)return new Q([],"float",t);let a=[];for(let o=0;o<r;o++){let l=0;for(let c=0;c<i;c++)l+=e.matrix[o][c]*s[c];a.push(l)}return new Q(a,"float",t)}else{let s=n,a=new be(r,i,NaN,t);for(let o=0;o<r;o++)for(let l=0;l<i;l++)a.matrix[o][l]=e.matrix[o][l]*s;return a}}}function xx(t){return e=>{let n=e.matrix.length;if(n===0)return new be(0,0,NaN,t);let r=e.matrix[0].length;if(n===r){let u=oa(e.matrix),h=new be(n,r,NaN,t);return h.matrix=u,h}let i=u=>{let h=u.length,p=u[0].length,d=new Array(p);for(let f=0;f<p;f++){d[f]=new Array(h);for(let m=0;m<h;m++)d[f][m]=u[m][f]}return d},s=(u,h)=>{let p=u.length,d=u[0].length,f=h[0].length,m=new Array(p);for(let y=0;y<p;y++){m[y]=new Array(f).fill(0);for(let g=0;g<d;g++){let w=u[y][g];if(w!==0)for(let k=0;k<f;k++)m[y][k]+=w*h[g][k]}}return m},a=e.matrix,o=i(a),l;if(n>r){let u=s(o,a),h=oa(u);l=s(h,o)}else{let u=s(a,o),h=oa(u);l=s(o,h)}let c=new be(r,n,NaN,t);return c.matrix=l,c}}function vx(t){return(e,n)=>{let r=e.matrix.length,i=r>0?e.matrix[0].length:0;if(r!==i)return new be(0,0,NaN,t);let s=new be(r,i,0,t);for(let l=0;l<r;l++)s.matrix[l][l]=1;let a=new be(r,i,NaN,t);for(let l=0;l<r;l++)a.matrix[l]=[...e.matrix[l]];let o=Math.floor(n);if(!Number.isFinite(o)||o<0)return new be(r,i,NaN,t);for(;o>0;){if(o%2===1){let c=new be(r,i,0,t);for(let u=0;u<r;u++)for(let h=0;h<i;h++){let p=0;for(let d=0;d<r;d++)p+=s.matrix[u][d]*a.matrix[d][h];c.matrix[u][h]=p}s=c}let l=new be(r,i,0,t);for(let c=0;c<r;c++)for(let u=0;u<i;u++){let h=0;for(let p=0;p<r;p++)h+=a.matrix[c][p]*a.matrix[p][u];l.matrix[c][u]=h}a=l,o=Math.floor(o/2)}return s}}function wx(t){return e=>{let n=e.matrix.length;if(n===0)return 0;let r=e.matrix[0].length,i=e.matrix.map(a=>[...a]),s=0;for(let a=0;a<r&&s<n;a++){let o=s;for(;o<n&&Math.abs(i[o][a])<1e-10;)o++;if(o<n){[i[s],i[o]]=[i[o],i[s]];let l=i[s][a];for(let c=a;c<r;c++)i[s][c]/=l;for(let c=0;c<n;c++)if(c!==s){let u=i[c][a];for(let h=a;h<r;h++)i[c][h]-=u*i[s][h]}s++}}return s}}function Sx(t){return(e,n)=>{let r=e.matrix.length;if(r===0){let a=Un(e.matrix[0][0]);return new Q([],a,t)}let i=[];for(let a=0;a<r;a++){let o=e.matrix[a].splice(n,1);i.push(o[0])}let s=Un(i[0]);return new Q(i,s,t)}}function Ex(t){return(e,n)=>{let r=e.matrix.splice(n,1),i=Un(r[0][0]);return new Q(r[0]||[],i,t)}}function kx(t){return(e,n,r)=>{let i=e.matrix.length,s=i>0?e.matrix[0].length:0,a=n*r,o=[];for(let u=0;u<i;u++)for(let h=0;h<s;h++)o.push(e.matrix[u][h]);for(;o.length<a;)o.push(NaN);o.length>a&&(o.length=a);let l=[],c=0;for(let u=0;u<n;u++){let h=[];for(let p=0;p<r;p++)h.push(o[c++]);l.push(h)}e.matrix=l}}function Ax(t){return e=>{e.matrix.reverse();for(let n of e.matrix)n.reverse()}}function Tx(t){return(e,n)=>{let r=e.matrix.length;if(n<0||n>=r)throw new fe(`Row index ${n} is out of bounds, matrix has ${r} rows.`,"matrix.row");let i=Un(e.matrix[n][0]);return new Q([...e.matrix[n]],i,t)}}function Nx(t){return e=>e.matrix.length}function Cx(t){return(e,n,r,i)=>{let s=e.matrix.length,a=s>0?e.matrix[0].length:0;if(n<0||n>=s)throw new fe(`Row index ${n} is out of bounds, matrix has ${s} rows.`,"matrix.set");if(r<0||r>=a)throw new fe(`Column index ${r} is out of bounds, matrix has ${a} columns.`,"matrix.set");e.matrix[n][r]=i}}function Ix(t){return(e,n=0,r=qn.ascending,i)=>{if(e.matrix.length===0)return;let s=e.matrix.map(l=>l[n]),a=Fi(s,i),o=Tu(a?s.map(a):s,r).map(l=>e.matrix[l]);e.matrix.splice(0,o.length,...o)}}function Mx(t){return(e,n,r,i,s)=>{let a=r-n,o=s-i,l=new be(a,o,NaN,t);for(let c=0;c<a;c++){let u=n+c;if(u>=e.matrix.length)break;for(let h=0;h<o;h++){let p=i+h;if(p>=e.matrix[u].length)break;l.matrix[c][h]=e.matrix[u][p]}}return l}}function Px(t){return(e,n)=>{let r=e.matrix.length;if(r===0)return new be(0,0,NaN,t);let i=e.matrix[0].length,s=new be(r,i,NaN,t);if(n instanceof be)for(let a=0;a<r;a++)for(let o=0;o<i;o++){let l=e.matrix[a][o],c=n.matrix[a]&&n.matrix[a][o]!==void 0?n.matrix[a][o]:NaN;s.matrix[a][o]=l+c}else{let a=n;for(let o=0;o<r;o++)for(let l=0;l<i;l++)s.matrix[o][l]=e.matrix[o][l]+a}return s}}function Dx(t){return(e,n,r)=>{let i=e.matrix.length;for(let s=0;s<i;s++){let a=e.matrix[s][n];e.matrix[s][n]=e.matrix[s][r],e.matrix[s][r]=a}}}function Ox(t){return(e,n,r)=>{let i=e.matrix[n];e.matrix[n]=e.matrix[r],e.matrix[r]=i}}function Rx(t){return e=>{let n=e.matrix.length;if(n===0)return 0;let r=e.matrix[0].length,i=Math.min(n,r),s=0;for(let a=0;a<i;a++)s+=e.matrix[a][a];return s}}function Lx(t){return e=>{let n=e.matrix.length;if(n===0)return new be(0,0,NaN,t);let r=e.matrix[0].length,i=new be(r,n,NaN,t);for(let s=0;s<n;s++)for(let a=0;a<r;a++)i.matrix[a][s]=e.matrix[s][a];return i}}var Fx=Object.defineProperty,Bx=(t,e,n)=>e in t?Fx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ie=(t,e,n)=>Bx(t,typeof e!="symbol"?e+"":e,n),be=class{constructor(e=0,n=0,r=NaN,i){if(this.context=i,ie(this,"matrix"),ie(this,"_add_col"),ie(this,"_add_row"),ie(this,"_avg"),ie(this,"_col"),ie(this,"_columns"),ie(this,"_concat"),ie(this,"_copy"),ie(this,"_det"),ie(this,"_diff"),ie(this,"_eigenvalues"),ie(this,"_eigenvectors"),ie(this,"_elements_count"),ie(this,"_fill"),ie(this,"_get"),ie(this,"_inv"),ie(this,"_is_antidiagonal"),ie(this,"_is_antisymmetric"),ie(this,"_is_binary"),ie(this,"_is_diagonal"),ie(this,"_is_identity"),ie(this,"_is_square"),ie(this,"_is_stochastic"),ie(this,"_is_symmetric"),ie(this,"_is_triangular"),ie(this,"_is_zero"),ie(this,"_kron"),ie(this,"_max"),ie(this,"_median"),ie(this,"_min"),ie(this,"_mode"),ie(this,"_mult"),ie(this,"_pinv"),ie(this,"_pow"),ie(this,"_rank"),ie(this,"_remove_col"),ie(this,"_remove_row"),ie(this,"_reshape"),ie(this,"_reverse"),ie(this,"_row"),ie(this,"_rows"),ie(this,"_set"),ie(this,"_sort"),ie(this,"_submatrix"),ie(this,"_sum"),ie(this,"_swap_columns"),ie(this,"_swap_rows"),ie(this,"_trace"),ie(this,"_transpose"),this.matrix=[],e>0&&n>0)for(let s=0;s<e;s++)this.matrix.push(Array(n).fill(r));this._add_col=zb(this.context),this._add_row=jb(this.context),this._avg=qb(this.context),this._col=Ub(this.context),this._columns=Wb(this.context),this._concat=Hb(this.context),this._copy=Gb(this.context),this._det=Yb(this.context),this._diff=Xb(this.context),this._eigenvalues=Jb(this.context),this._eigenvectors=Qb(this.context),this._elements_count=ex(this.context),this._fill=tx(this.context),this._get=nx(this.context),this._inv=rx(this.context),this._is_antidiagonal=ix(this.context),this._is_antisymmetric=sx(this.context),this._is_binary=ax(this.context),this._is_diagonal=ox(this.context),this._is_identity=lx(this.context),this._is_square=cx(this.context),this._is_stochastic=ux(this.context),this._is_symmetric=hx(this.context),this._is_triangular=px(this.context),this._is_zero=dx(this.context),this._kron=fx(this.context),this._max=mx(this.context),this._median=yx(this.context),this._min=gx(this.context),this._mode=_x(this.context),this._mult=bx(this.context),this._pinv=xx(this.context),this._pow=vx(this.context),this._rank=wx(this.context),this._remove_col=Sx(this.context),this._remove_row=Ex(this.context),this._reshape=kx(this.context),this._reverse=Ax(this.context),this._row=Tx(this.context),this._rows=Nx(this.context),this._set=Cx(this.context),this._sort=Ix(this.context),this._submatrix=Mx(this.context),this._sum=Px(this.context),this._swap_columns=Dx(this.context),this._swap_rows=Ox(this.context),this._trace=Rx(this.context),this._transpose=Lx(this.context)}toString(){let e="";for(let n=0;n<this.matrix.length;n++)e+=e===""?"":`\n`,e+="["+this.matrix[n].join(", ")+"]";return e}add_col(...e){return this._add_col(this,...M(e,F.add_col,1))}add_row(...e){return this._add_row(this,...M(e,F.add_row,1))}avg(...e){return this._avg(this,...M(e,F.avg,1))}col(...e){return this._col(this,...M(e,F.col,1))}columns(...e){return this._columns(this,...M(e,F.columns,1))}concat(...e){return this._concat(this,...M(e,F.concat,1))}copy(...e){return this._copy(this,...M(e,F.copy,1))}det(...e){return this._det(this,...M(e,F.det,1))}diff(...e){return this._diff(this,...M(e,F.diff,1))}eigenvalues(...e){return this._eigenvalues(this,...M(e,F.eigenvalues,1))}eigenvectors(...e){return this._eigenvectors(this,...M(e,F.eigenvectors,1))}elements_count(...e){return this._elements_count(this,...M(e,F.elements_count,1))}fill(...e){return this._fill(this,...M(e,F.fill,1))}get(...e){return this._get(this,...M(e,F.get,1))}inv(...e){return this._inv(this,...M(e,F.inv,1))}is_antidiagonal(...e){return this._is_antidiagonal(this,...M(e,F.is_antidiagonal,1))}is_antisymmetric(...e){return this._is_antisymmetric(this,...M(e,F.is_antisymmetric,1))}is_binary(...e){return this._is_binary(this,...M(e,F.is_binary,1))}is_diagonal(...e){return this._is_diagonal(this,...M(e,F.is_diagonal,1))}is_identity(...e){return this._is_identity(this,...M(e,F.is_identity,1))}is_square(...e){return this._is_square(this,...M(e,F.is_square,1))}is_stochastic(...e){return this._is_stochastic(this,...M(e,F.is_stochastic,1))}is_symmetric(...e){return this._is_symmetric(this,...M(e,F.is_symmetric,1))}is_triangular(...e){return this._is_triangular(this,...M(e,F.is_triangular,1))}is_zero(...e){return this._is_zero(this,...M(e,F.is_zero,1))}kron(...e){return this._kron(this,...M(e,F.kron,1))}max(...e){return this._max(this,...M(e,F.max,1))}median(...e){return this._median(this,...M(e,F.median,1))}min(...e){return this._min(this,...M(e,F.min,1))}mode(...e){return this._mode(this,...M(e,F.mode,1))}mult(...e){return this._mult(this,...M(e,F.mult,1))}pinv(...e){return this._pinv(this,...M(e,F.pinv,1))}pow(...e){return this._pow(this,...M(e,F.pow,1))}rank(...e){return this._rank(this,...M(e,F.rank,1))}remove_col(...e){return this._remove_col(this,...M(e,F.remove_col,1))}remove_row(...e){return this._remove_row(this,...M(e,F.remove_row,1))}reshape(...e){return this._reshape(this,...M(e,F.reshape,1))}reverse(...e){return this._reverse(this,...M(e,F.reverse,1))}row(...e){return this._row(this,...M(e,F.row,1))}rows(...e){return this._rows(this,...M(e,F.rows,1))}set(...e){return this._set(this,...M(e,F.set,1))}sort(...e){return this._sort(this,...M(e,F.sort,1))}submatrix(...e){return this._submatrix(this,...M(e,F.submatrix,1))}sum(...e){return this._sum(this,...M(e,F.sum,1))}swap_columns(...e){return this._swap_columns(this,...M(e,F.swap_columns,1))}swap_rows(...e){return this._swap_rows(this,...M(e,F.swap_rows,1))}trace(...e){return this._trace(this,...M(e,F.trace,1))}transpose(...e){return this._transpose(this,...M(e,F.transpose,1))}};function yn(t){return(e,n,r)=>{let i=typeof e=="number"&&e>0?e:0,s=typeof n=="number"&&n>0?n:0;return jt(i*s,"matrix.new"),new be(e,n,r,t)}}function Vx(t){return(e,n=0)=>_.from(e).get(n)}var Pl=class{constructor(e){this.context=e,this.add_col=P((n,...r)=>n.add_col(...r),F.add_col),this.add_row=P((n,...r)=>n.add_row(...r),F.add_row),this.avg=P((n,...r)=>n.avg(...r),F.avg),this.col=P((n,...r)=>n.col(...r),F.col),this.columns=P((n,...r)=>n.columns(...r),F.columns),this.concat=P((n,...r)=>n.concat(...r),F.concat),this.copy=P((n,...r)=>n.copy(...r),F.copy),this.det=P((n,...r)=>n.det(...r),F.det),this.diff=P((n,...r)=>n.diff(...r),F.diff),this.eigenvalues=P((n,...r)=>n.eigenvalues(...r),F.eigenvalues),this.eigenvectors=P((n,...r)=>n.eigenvectors(...r),F.eigenvectors),this.elements_count=P((n,...r)=>n.elements_count(...r),F.elements_count),this.fill=P((n,...r)=>n.fill(...r),F.fill),this.get=P((n,...r)=>n.get(...r),F.get),this.inv=P((n,...r)=>n.inv(...r),F.inv),this.is_antidiagonal=P((n,...r)=>n.is_antidiagonal(...r),F.is_antidiagonal),this.is_antisymmetric=P((n,...r)=>n.is_antisymmetric(...r),F.is_antisymmetric),this.is_binary=P((n,...r)=>n.is_binary(...r),F.is_binary),this.is_diagonal=P((n,...r)=>n.is_diagonal(...r),F.is_diagonal),this.is_identity=P((n,...r)=>n.is_identity(...r),F.is_identity),this.is_square=P((n,...r)=>n.is_square(...r),F.is_square),this.is_stochastic=P((n,...r)=>n.is_stochastic(...r),F.is_stochastic),this.is_symmetric=P((n,...r)=>n.is_symmetric(...r),F.is_symmetric),this.is_triangular=P((n,...r)=>n.is_triangular(...r),F.is_triangular),this.is_zero=P((n,...r)=>n.is_zero(...r),F.is_zero),this.kron=P((n,...r)=>n.kron(...r),F.kron),this.max=P((n,...r)=>n.max(...r),F.max),this.median=P((n,...r)=>n.median(...r),F.median),this.min=P((n,...r)=>n.min(...r),F.min),this.mode=P((n,...r)=>n.mode(...r),F.mode),this.mult=P((n,...r)=>n.mult(...r),F.mult),this.new=yn(e),this.param=Vx(),this.pinv=P((n,...r)=>n.pinv(...r),F.pinv),this.pow=P((n,...r)=>n.pow(...r),F.pow),this.rank=P((n,...r)=>n.rank(...r),F.rank),this.remove_col=P((n,...r)=>n.remove_col(...r),F.remove_col),this.remove_row=P((n,...r)=>n.remove_row(...r),F.remove_row),this.reshape=P((n,...r)=>n.reshape(...r),F.reshape),this.reverse=P((n,...r)=>n.reverse(...r),F.reverse),this.row=P((n,...r)=>n.row(...r),F.row),this.rows=P((n,...r)=>n.rows(...r),F.rows),this.set=P((n,...r)=>n.set(...r),F.set),this.sort=P((n,...r)=>n.sort(...r),F.sort),this.submatrix=P((n,...r)=>n.submatrix(...r),F.submatrix),this.sum=P((n,...r)=>n.sum(...r),F.sum),this.swap_columns=P((n,...r)=>n.swap_columns(...r),F.swap_columns),this.swap_rows=P((n,...r)=>n.swap_rows(...r),F.swap_rows),this.trace=P((n,...r)=>n.trace(...r),F.trace),this.transpose=P((n,...r)=>n.transpose(...r),F.transpose),this.new_float=yn(e),this.new_int=yn(e),this.new_string=yn(e),this.new_bool=yn(e),this.new_color=yn(e),this.new_line=yn(e),this.new_label=yn(e),this.new_box=yn(e),this.new_linefill=yn(e),this.new_table=yn(e)}},$x=Object.defineProperty,zx=(t,e,n)=>e in t?$x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jx=(t,e,n)=>zx(t,typeof e!="symbol"?e+"":e,n),Dl=class{constructor(e){this.context=e,jx(this,"_live",!1)}setLive(){this._live=!0}get isnew(){return!this._live}get islast(){return this.context.idx===this.context.length-1}get isfirst(){return this.context.idx===0}get ishistory(){return this.context.idx<this.context.length-1}get isrealtime(){return this.context.idx===this.context.length-1}get isconfirmed(){return this.context.data.closeTime.data[this.context.idx]<=Date.now()}get islastconfirmedhistory(){let e=this.context.idx,n=this.context.length;if(e===n-1)return this.context.data.closeTime.data[e]<=Date.now();if(e===n-2){let r=this.context.marketData?.[n-1]?.closeTime;return r!==void 0?r>Date.now():!1}return!1}},qx=Object.defineProperty,Ux=(t,e,n)=>e in t?qx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tl=(t,e,n)=>Ux(t,typeof e!="symbol"?e+"":e,n),vt=class t{constructor(e,n,r){tl(this,"time"),tl(this,"index"),tl(this,"price"),this.time=e,this.index=n,this.price=r}copy(){return new t(this.time,this.index,this.price)}toString(){return JSON.stringify({time:this.time,index:this.index,price:this.price})}};function Wx(t){return typeof t=="object"&&t&&(t.title!==void 0||t._plotKey!==void 0)&&t.data!==void 0&&t.options!==void 0}function xa(t){return t!==null&&typeof t=="object"&&"__value"in t&&(t.__value===null||typeof t.__value!="object")}var Ol={series:t=>t instanceof _||typeof t=="number"||typeof t=="string"||typeof t=="boolean"||xa(t),string:t=>typeof t=="string",color:t=>typeof t=="string"||t===null||typeof t=="number"&&isNaN(t)||t instanceof _,number:t=>typeof t=="number",size:t=>typeof t=="string"||typeof t=="number",boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>typeof t=="object",point:t=>t instanceof vt,primitive:t=>typeof t===null||typeof t!="object"&&typeof t!="function",function:t=>typeof t=="function",undefined:t=>t===void 0,null:t=>t===null,NaN:t=>isNaN(t),any:()=>!0,remaining_options:t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof _)&&!(t instanceof vt)&&!Wx(t)&&!xa(t)},Hx=new Set(["number","string","boolean","size"]);function Jd(t){return Ol.remaining_options(t)}function cn(t){let e=t[t.length-1];if(e&&typeof e=="object"&&"__callsiteId"in e)return t.pop().__callsiteId}function Te(t,e,n,r){Array.isArray(e)&&typeof e[0]=="string"&&(e=[e]);let i={},s={},a=u=>u instanceof _||xa(u),o=(u,h)=>Hx.has(h)&&a(u)?_.from(u).get(0):u,l=(u,h)=>h!==void 0&&h!=="series"&&h!=="any"&&a(u)?_.from(u).get(0):u,c=new Array(e.length).fill(!0);for(let u=0;u<t.length;u++){let h=t[u];if(h===void 0)continue;if(Ol.remaining_options(h)){s={};for(let d of Object.keys(h))s[d]=l(h[d],n[d]);break}let p=e.map((d,f)=>c[f]?d[u]:void 0);for(let d=0;d<p.length;d++){let f=p[d];if(f===void 0){c[d]=!1;continue}let m=n[f];if(typeof h=="number"&&isNaN(h)&&(m==="number"||m==="series"))i[f]=h;else{let y=Ol[n[f]],g=typeof y=="function"&&!y(h)?o(h,m):h;typeof y=="function"&&y(g)?i[f]=g:c[d]=!1}}}return{...i,...s,...r}}var Gx=/^(\\d{2})(\\d{2})-(\\d{2})(\\d{2})$/;function Qd(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;if(e==="24x7")return{windows:[{start:0,end:1440}],days:new Set([1,2,3,4,5,6,7])};let n=e.split(":");if(n.length>2)return null;let r=new Set;if(n.length===2){if(!/^[1-7]+$/.test(n[1]))return null;for(let s of n[1])r.add(parseInt(s,10))}else for(let s=1;s<=7;s++)r.add(s);let i=[];for(let s of n[0].split(",")){let a=s.match(Gx);if(!a)return null;let o=parseInt(a[1],10),l=parseInt(a[2],10),c=parseInt(a[3],10),u=parseInt(a[4],10);if(o>23||l>59||c>23||u>59)return null;let h=o*60+l,p=c===0&&u===0?1440:c*60+u;i.push({start:h,end:p})}return{windows:i,days:r}}function Kx(t,e,n){let r=n+1,i=r%7+1;for(let{start:s,end:a}of t.windows)if(s<a){if(e>=s&&e<a&&t.days.has(r))return!0}else if(e>=s&&t.days.has(i)||e<a&&t.days.has(r))return!0;return!1}var nl=new Map;function pt(t){if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;if(nl.has(t))return nl.get(t);let e=Yx(t.trim());return nl.set(t,e),e}function Yx(t){let e=/^(\\d*)([a-zA-Z]?)$/.exec(t);if(!e||t==="")return null;let n=e[1],r=e[2],i=n===""?1:parseInt(n,10);if(!(i>=1))return null;let s;switch(r){case"":s={unit:"",multiplier:i};break;case"S":case"s":s={unit:"S",multiplier:i};break;case"D":case"d":s={unit:"D",multiplier:i};break;case"W":case"w":s={unit:"W",multiplier:i};break;case"M":s={unit:"M",multiplier:i};break;case"m":s=n===""?{unit:"M",multiplier:1}:{unit:"",multiplier:i};break;case"H":case"h":s={unit:"",multiplier:i*60};break;default:s=null}return s&&s.unit===""&&s.multiplier>1440?null:s}function Ni(t,e=!1){return t.unit===""?String(t.multiplier):t.unit==="S"?`${t.multiplier}S`:t.multiplier===1&&!e?t.unit:`${t.multiplier}${t.unit}`}function Rl(t){let e=pt(t);return e?Ni(e):null}function Vt(t){switch(t.unit){case"S":return t.multiplier;case"":return t.multiplier*60;case"D":return t.multiplier*86400;case"W":return t.multiplier*604800;case"M":return t.multiplier*2628003}}function Xx(t){return t>=365*86400?"12M":t<=30?`${[1,5,10,15,30].find(e=>t<=e)}S`:t<86400?String(Math.ceil(t/60)):t%604800===0?`${t/604800}W`:t%2628003===0?`${t/2628003}M`:`${Math.ceil(t/86400)}D`}function ef(t){let e=Date.UTC(t,0,1),n=new Date(e).getUTCDay();return e+(8-n)%7*864e5}function ms(t,e){let n=e.multiplier,r=new Date(t),i=r.getUTCFullYear();switch(e.unit){case"S":case"":{let s=Vt(e)*1e3,a=Math.floor(t/864e5)*864e5;return a+Math.floor((t-a)/s)*s}case"D":{let s=Date.UTC(i,0,1),a=Math.floor((t-s)/864e5);return s+Math.floor(a/n)*n*864e5}case"W":{let s=Math.floor(t/864e5)*864e5-(r.getUTCDay()+6)%7*864e5,a=ef(new Date(s).getUTCFullYear()),o=Math.round((s-a)/6048e5);return a+Math.floor(o/n)*n*6048e5}case"M":return Date.UTC(i,Math.floor(r.getUTCMonth()/n)*n,1)}}function Zx(t,e){let n=e.multiplier,r=new Date(t),i=r.getUTCFullYear();switch(e.unit){case"S":case"":{let s=(Math.floor(t/864e5)+1)*864e5;return Math.min(t+Vt(e)*1e3,s)}case"D":return Math.min(t+n*864e5,Date.UTC(i+1,0,1));case"W":return Math.min(t+n*6048e5,ef(i+1));case"M":return Math.min(Date.UTC(i,r.getUTCMonth()+n,1),Date.UTC(i+1,0,1))}}var Jx={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6};function is(t,e,n=1){if(e==="month"){let i=new Date(t);return Date.UTC(i.getUTCFullYear(),i.getUTCMonth()+n,1,i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds())}let r={second:1e3,minute:6e4,hour:36e5,day:864e5,week:7*864e5};return t+n*r[e]}function An(t,e,n){let[r,i,s]=t.split("-").map(Number),[a,o]=e.split(":").map(Number),l=Date.UTC(r,i-1,s,a,o,0,0),c=new Intl.DateTimeFormat("en-US",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(l)),u=g=>parseInt(c.find(w=>w.type===g).value,10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),y=Date.UTC(h,p-1,d,f,m,0,0)-l;return l-y}function np(t,e,n,r,i=1){if(e==="24x7")return is(t,r,i);let s=e.split("-")[1];if(!s||s.length!==4)return is(t,r,i);let a=s.slice(0,2),o=s.slice(2,4),l=`${a}:${o}`,c=rp(t,n);if(r==="second"||r==="minute"||r==="hour"){let u=t+i*{second:1e3,minute:6e4,hour:36e5}[r],h=An(c,l,n);return Math.min(u,h)}if(r==="day")return An(c,l,n);if(r==="week"){let u=new Date(t).getUTCDay(),h=u<=5?5-u:5-u+7,p=t+h*864e5,d=rp(p,n);return An(d,l,n)}if(r==="month"){let u=new Date(t),h=u.getUTCFullYear(),p=u.getUTCMonth()+i,d=new Date(Date.UTC(h,p,1)),f=new Date(d.getTime()-864e5);for(;f.getUTCDay()===0||f.getUTCDay()===6;)f.setUTCDate(f.getUTCDate()-1);let m=f.toISOString().split("T")[0];return An(m,l,n)}return is(t,r,i)}function rp(t,e){return new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(t))}function Qx(t){for(let e=0;e<t.length-1;e++)t[e].closeTime=t[e+1].openTime;t.length>0&&(t[t.length-1].closeTime=t[t.length-1].closeTime+1)}var tf=864e5,e1=4096,ip=new Map;function nf(t){let e=t??"",n=ip.get(e);if(!n){let r=Qd(e)?.windows[0];n=r?{open:r.start%1440,overnight:r.start>=r.end&&r.end<1440}:{open:0,overnight:!1},ip.set(e,n)}return n}var sp=new Map,ap=new Map,rf=(t,e,n)=>(t.size>=e1&&t.clear(),t.set(e,n),n);function t1(t,e,n){let r=`${e}|${n}|${t}`,i=sp.get(r);if(i!==void 0)return i;let s=Ir(t,e),a=Date.UTC(s.year,s.month-1,s.day),{open:o,overnight:l}=nf(n);return rf(sp,r,l&&s.hour*60+s.minute>=o?a+tf:a)}function Ll(t,e,n,r){return e.unit!=="D"&&e.unit!=="W"&&e.unit!=="M"?ms(t,e):ms(t1(t,n,r),e)}function n1(t,e,n,r){if(e.unit!=="D"&&e.unit!=="W"&&e.unit!=="M")return ms(t,e);let i=Ll(t,e,n,r),s=`${n}|${r}|${i}`,a=ap.get(s);if(a!==void 0)return a;let{open:o,overnight:l}=nf(r),c=new Date(l?i-tf:i).toISOString().slice(0,10),u=`${String(Math.floor(o/60)).padStart(2,"0")}:${String(o%60).padStart(2,"0")}`;return rf(ap,s,An(c,u,n))}var r1=Object.defineProperty,i1=(t,e,n)=>e in t?r1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,xi=(t,e,n)=>i1(t,typeof e!="symbol"?e+"":e,n);function sf(t){let e=r=>r instanceof _?r.get(0):r,n=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype;return t.map(r=>n(r)?Object.fromEntries(Object.entries(r).map(([i,s])=>[i,e(s)])):e(r))}function Ir(t,e){let n=e.trim();if(n==="UTC"||n==="GMT"||n==="Etc/UTC"){let i=new Date(t);return{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),hour:i.getUTCHours(),minute:i.getUTCMinutes(),second:i.getUTCSeconds(),dayOfWeek:i.getUTCDay()}}let r=n.match(/^(?:UTC|GMT)([+-])(\\d{1,2})(?::(\\d{2}))?$/i);if(r){let i=r[1]==="+"?1:-1,s=parseInt(r[2],10),a=parseInt(r[3]||"0",10),o=i*(s*60+a)*60*1e3,l=new Date(t+o);return{year:l.getUTCFullYear(),month:l.getUTCMonth()+1,day:l.getUTCDate(),hour:l.getUTCHours(),minute:l.getUTCMinutes(),second:l.getUTCSeconds(),dayOfWeek:l.getUTCDay()}}try{let i=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",weekday:"short",hour12:!1}).formatToParts(new Date(t)),s=c=>parseInt(i.find(u=>u.type===c)?.value||"0",10),a=s("hour");a===24&&(a=0);let o=i.find(c=>c.type==="weekday")?.value||"Sun",l={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};return{year:s("year"),month:s("month"),day:s("day"),hour:a,minute:s("minute"),second:s("second"),dayOfWeek:l[o]??0}}catch{let i=new Date(t);return{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),hour:i.getUTCHours(),minute:i.getUTCMinutes(),second:i.getUTCSeconds(),dayOfWeek:i.getUTCDay()}}}function s1(t,e,n){let r=new Date(Date.UTC(t,e-1,n)),i=r.getUTCDay()||7;r.setUTCDate(r.getUTCDate()+4-i);let s=new Date(Date.UTC(r.getUTCFullYear(),0,1));return Math.ceil(((r.getTime()-s.getTime())/864e5+1)/7)}var a1=[["timeframe"],["timeframe","bars_back"],["timeframe","session","bars_back"],["timeframe","session","bars_back","timeframe_bars_back"],["timeframe","session","timezone","bars_back","timeframe_bars_back"]],o1={timeframe:"string",session:"string",timezone:"string",bars_back:"number",timeframe_bars_back:"number"},va=class{constructor(e,n="openTime"){xi(this,"context"),xi(this,"dataField"),this.context=e,this.dataField=n}get __value(){return this.context.data[this.dataField]}param(e,n=0){return _.from(e).get(n)}any(...e){let n=sf(e),r=Te(n,a1,o1),i=r.bars_back??0,s=r.timeframe||"",a=this.context.data[this.dataField],o=_.from(a).get(i);if(isNaN(o)||o==null)return NaN;let l;if(!s||Rl(s)===Rl(this.context.timeframe))l=o;else{let c=pt(s);if(!c)throw new fe(`Cannot parse resolution \'${s}\'. - Invalid format`,"time");let u=this.context.pine?.syminfo;l=n1(o,c,u?.timezone||"UTC",u?.session)}if(r.session!==void 0&&r.session!==""){let c=r.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._isInSession(l,r.session,c)?l:NaN}return l}_isInSession(e,n,r){let i=Qd(n);if(!i)throw new fe(`Invalid session specification: "${n}"`,"time");let s=Ir(e,r),a=s.hour*60+s.minute;return Kx(i,a,s.dayOfWeek)}},l1=[[],["time"],["time","timezone"]],c1={time:"number",timezone:"string"},Rn=class{constructor(e,n){xi(this,"context"),xi(this,"extractor"),xi(this,"_cache",[]),xi(this,"_cacheTimezone",null),this.context=e,this.extractor=n}get __value(){let e=this.context.data.openTime,n=e instanceof _?e.data:Array.isArray(e)?e:[],r=this.context.pine?.syminfo?.timezone||"UTC";r!==this._cacheTimezone&&(this._cache=[],this._cacheTimezone=r);let i=this._cache;i.length>n.length&&(i.length=n.length);for(let s=i.length;s<n.length;s++){let a=n[s];i.push(a==null||isNaN(a)?NaN:this.extractor(Ir(a,r)))}return new _(i,e instanceof _?e.offset:0)}param(e,n=0){return _.from(e).get(n)}any(...e){let n=sf(e);if(n.length===0)return this.__value.get(0);let r=Te(n,l1,c1),i=r.time;if(i===void 0||isNaN(i))return NaN;let s=r.timezone||this.context.pine?.syminfo?.timezone||"UTC",a=Ir(i,s);return this.extractor(a)}},mr={dayofmonth:t=>t.day,dayofweek:t=>t.dayOfWeek===0?1:t.dayOfWeek+1,hour:t=>t.hour,minute:t=>t.minute,month:t=>t.month,second:t=>t.second,weekofyear:t=>s1(t.year,t.month,t.day),year:t=>t.year},u1=Object.defineProperty,h1=(t,e,n)=>e in t?u1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,op=(t,e,n)=>h1(t,typeof e!="symbol"?e+"":e,n),Fl=class{constructor(e){this.context=e,op(this,"regular","regular"),op(this,"extended","extended")}get _timezone(){return this.context.pine?.syminfo?.timezone||"UTC"}_dayKey(e){let n=Ir(e,this._timezone);return`${n.year}-${n.month}-${n.day}`}get isfirstbar(){let e=this.context.idx,n=this.context.marketData;return!Array.isArray(n)||!n[e]?!1:e===0?!0:this._dayKey(n[e].openTime)!==this._dayKey(n[e-1].openTime)}get islastbar(){let e=this.context.idx,n=this.context.marketData;return!Array.isArray(n)||!n[e]?!1:e===n.length-1?!0:this._dayKey(n[e].openTime)!==this._dayKey(n[e+1].openTime)}get isfirstbar_regular(){return this.isfirstbar}get islastbar_regular(){return this.islastbar}get ismarket(){return!0}get ispremarket(){return!1}get ispostmarket(){return!1}};function R(t,e,n){let r=n.value;return typeof r!="function"||(n.value=function(...i){return this&&this.context&&this.context.isSecondaryContext?null:r.apply(this,i)}),n}var af=Object.defineProperty,p1=Object.getOwnPropertyDescriptor,d1=(t,e,n)=>e in t?af(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,of=(t,e,n,r)=>{for(var i=r>1?void 0:r?p1(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&af(e,n,i),i},wi=(t,e,n)=>d1(t,typeof e!="symbol"?e+"":e,n),f1=[["dateString"],["year","month","day","hour","minute","second"],["timezone","year","month","day","hour","minute","second"]],m1={dateString:"string",timezone:"string",year:"number",month:"number",day:"number",hour:"number",minute:"number",second:"number"},y1=["title","shorttitle","overlay","format","precision","scale","max_bars_back","timeframe","timeframe_gaps","explicit_plot_zorder","max_lines_count","max_labels_count","max_boxes_count","calc_bars_count","max_polylines_count","dynamic_requests","behind_chart"],g1={title:"string",shorttitle:"string",overlay:"boolean",format:"string",precision:"number",scale:"string",max_bars_back:"number",timeframe:"string",timeframe_gaps:"boolean",explicit_plot_zorder:"boolean",max_lines_count:"number",max_labels_count:"number",max_boxes_count:"number",calc_bars_count:"number",max_polylines_count:"number",dynamic_requests:"boolean",behind_chart:"boolean"};function _1(t){return Te(t,y1,g1)}var b1=["title","overlay","dynamic_requests"],x1={title:"string",overlay:"boolean",dynamic_requests:"boolean"},$t=class t{get __value(){return NaN}param(e,n=0){return _.from(e).get(n)}any(e){if(e instanceof t)return!0;let n=_.from(e).get(0);return n instanceof t||n==null?!0:typeof n=="number"?n!==n:n===""||typeof n=="object"&&n._deleted===!0}},hi={freq_all:"all",freq_once_per_bar:"once_per_bar",freq_once_per_bar_close:"once_per_bar_close"},v1=["message","freq"],w1=["condition","title","message"],wa=class{constructor(e){this.context=e,wi(this,"_firedKeys",new Set),wi(this,"_fallbackCounter",0),wi(this,"_fallbackLastExecTick",-1)}get freq_all(){return hi.freq_all}get freq_once_per_bar(){return hi.freq_once_per_bar}get freq_once_per_bar_close(){return hi.freq_once_per_bar_close}param(e,n,r){return _.from(e).get(0)}any(...e){let n=cn(e),[r,i]=M(e,v1),s=_.from(r).get(0),a=i?_.from(i).get(0):hi.freq_once_per_bar,o=typeof a=="string"&&a.startsWith("alert.freq_")?a.slice(11):a,l;if(n)l=n;else{let p=this.context._execTick||0;p!==this._fallbackLastExecTick&&(this._fallbackCounter=0,this._fallbackLastExecTick=p),l=`alert_${this._fallbackCounter++}`}let c=this.context.idx,u=this.context.pine?.barstate?.isrealtime??c===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!u)return;let h=`${l}:${c}`;if(o===hi.freq_once_per_bar){if(this._firedKeys.has(h))return;this._firedKeys.add(h)}else if(o===hi.freq_once_per_bar_close){if(!(this.context.pine?.barstate?.isconfirmed??!0)||this._firedKeys.has(h))return;this._firedKeys.add(h)}this.context.alerts.push({type:"alert",id:l,message:s,freq:o,bar_index:c,time:this.context.data.openTime?.data?.[c]??0})}};of([R],wa.prototype,"any",1);var Sa=class{constructor(e){this.context=e,wi(this,"_acCounter",0),wi(this,"_acLastExecTick",-1),wi(this,"_acFiredKeys",new Set)}extractPlotOptions(e){let n={};for(let r in e)n[r]=_.from(e[r]).get(0);return n}indicator(...e){let n=e.map(s=>s instanceof _?s.get(0):s),r=_1(n),i={title:"",shorttitle:"",overlay:!1,format:"inherit",precision:10,scale:"points",max_bars_back:0,timeframe:"",timeframe_gaps:!0,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,calc_bars_count:0,max_polylines_count:50,dynamic_requests:!1,behind_chart:!0};return this.context.indicator={...i,...r,...this.context._propOverrides??{}},this.context.indicator}library(...e){let n=e.map(r=>r instanceof _?r.get(0):r);return this.indicator(Te(n,b1,x1))}get bar_index(){return this.context.idx}na(e){let n=_.from(e).get(0);return n==null||n===""||typeof n=="number"&&isNaN(n)||typeof n=="object"&&n._deleted===!0}nz(e,n=0){let r=_.from(e).get(0),i=_.from(n).get(0);return r==null||typeof r=="number"&&isNaN(r)?i:r}fixnan(e){let n=_.from(e);for(let r=0;r<n.length;r++){let i=n.get(r);if(i!=null&&!(typeof i=="number"&&isNaN(i)))return i}return NaN}alertcondition(...e){let[n,r,i]=M(e,w1),s=_.from(n).get(0),a=this.context.idx,o=this.context._execTick||0;o!==this._acLastExecTick&&(this._acCounter=0,this._acLastExecTick=o);let l=`alertcondition_${this._acCounter++}`;if(!s)return;let c=this.context.pine?.barstate?.isrealtime??a===this.context.length-1;if((this.context._alertMode||"realtime")==="realtime"&&!c)return;let u=`${l}:${a}`;if(this._acFiredKeys.has(u))return;this._acFiredKeys.add(u);let h=r?_.from(r).get(0):"",p=i?_.from(i).get(0):"";this.context.alerts.push({type:"alertcondition",id:l,title:h,message:p,bar_index:a,time:this.context.data.openTime?.data?.[a]??0})}error(...e){console.error("error called but is currently not implemented",e)}max_bars_back(e,n){}timestamp(...e){let n=e.map(i=>i instanceof _?i.get(0):i),r=Te(n,f1,m1);if(r.year!==void 0){let i=r.year,s=r.month,a=r.day,o=r.hour||0,l=r.minute||0,c=r.second||0,u=r.timezone||this.context.pine?.syminfo?.timezone||"UTC";return this._timestampFromComponents(u,i,s,a,o,l,c)}if(r.dateString!==void 0){let i=r.dateString.trim();if(/[Zz]$/.test(i)||/[+-]\\d{2}:?\\d{2}$/.test(i))return new Date(i).getTime();let s=i.includes("T")?i+"Z":i.replace(/\\s+/,"T")+"Z",a=new Date(s);if(isNaN(a.getTime())&&(a=new Date(`${i} UTC`)),!isNaN(a.getTime())){let o=this.context.pine?.syminfo?.timezone||"UTC";return this._timestampFromComponents(o,a.getUTCFullYear(),a.getUTCMonth()+1,a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds())}return new Date(i).getTime()}return NaN}_timestampFromComponents(e,n,r,i,s,a,o){let l=new Date(Date.UTC(n,r-1,i,s,a,o));n>=0&&n<100&&l.setUTCFullYear(n);let c=e.trim();if(c==="UTC"||c==="GMT"||c==="Etc/UTC")return l.getTime();let u=c.match(/^(?:UTC|GMT)([+-])(\\d{1,2})(?::(\\d{2}))?$/i);if(u){let h=u[1]==="+"?1:-1,p=parseInt(u[2],10),d=parseInt(u[3]||"0",10),f=h*(p*60+d)*60*1e3;return l.getTime()-f}try{return this._timestampFromIANA(e,n,r,i,s,a,o)}catch{return l.getTime()}}_timestampFromIANA(e,n,r,i,s,a,o){let l=new Date(Date.UTC(n,r-1,i,s,a,o));n>=0&&n<100&&l.setUTCFullYear(n);let c=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(l),u=k=>parseInt(c.find(S=>S.type===k)?.value||"0",10),h=u("year"),p=u("month"),d=u("day"),f=u("hour");f===24&&(f=0);let m=u("minute"),y=u("second"),g=new Date(Date.UTC(h,p-1,d,f,m,y));h>=0&&h<100&&g.setUTCFullYear(h);let w=g.getTime()-l.getTime();return l.getTime()-w}bool(e){let n=_.from(e).get(0);return typeof n=="boolean"?n:n!=null&&!isNaN(n)&&n!==0}int(e){let n=_.from(e).get(0);if(typeof n!="number")throw new Error(`Cannot call "int" with argument "x"="${n}". An argument of "literal string" type was used but a "simple int" is expected.`);return Math.trunc(n)}float(e){let n=_.from(e).get(0);if(typeof n!="number")throw new Error(`Cannot call "float" with argument "x"="${n}". An argument of "literal string" type was used but a "const float" is expected.`);return n}string(e){let n=_.from(e).get(0);return n==null||typeof n=="number"&&isNaN(n)?"":n.toString()}Type(e,n){let r=Object.keys(e),i={},s={},a=this.context?.pineVersion;for(let l of r){let c=e[l];c instanceof _&&(c=c.data),Array.isArray(c)?(i[l]=c[0],s[l]=c[1]):i[l]=c}let o={__name__:n,new:function(...l){let c={},u=null;if(l.length>0){let h=l[l.length-1];if(h&&typeof h=="object"&&!(h instanceof _)&&!Array.isArray(h)&&!(h instanceof Cn)){let p=Object.keys(h);p.length>0&&p.some(d=>r.includes(d))&&(u=h,l=l.slice(0,-1))}}for(let h=0;h<r.length;h++){let p=r[h];if(u&&p in u?c[p]=u[p]:h<l.length?c[p]=l[h]:p in s&&(c[p]=_.from(s[p]).get(0)),/(^|\\s)string$/.test(i[p]??"")){let d=c[p];(d==null||typeof d=="number"&&isNaN(d))&&(c[p]="")}if(a>=6&&/(^|\\s)bool$/.test(i[p]??"")){let d=c[p];(d==null||typeof d=="number"&&isNaN(d))&&(c[p]=!1)}}return new Cn(c,this.context,o)},copy:function(l){return new Cn(l._fieldValues(),this.context,o)},_fieldDefaults:s,_definitionKeys:r};return o}};of([R],Sa.prototype,"alertcondition",1);var co=new Set(["open","high","low","close","hl2","hlc3","ohlc4","hlcc4","volume"]);function lf(t,e){if(!co.has(e))return;let n=t?.data?.[e];if(n!=null)return _.from(n).get(0)}var S1=[["defval","title","tooltip","inline","group","display"],["defval","title","tooltip","group","confirm","display"],["defval","title","tooltip","inline","group","confirm","display"],["defval","title","options","tooltip","inline","group","confirm","display"],["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display"]],E1={defval:"primitive",title:"string",tooltip:"string",inline:"string",group:"string",display:"string",confirm:"boolean",options:"array",minval:"number",maxval:"number",step:"number"},cf=t=>!!t&&typeof t=="object"&&(Object.prototype.hasOwnProperty.call(t,"__varId")||Object.prototype.hasOwnProperty.call(t,"__inputId"));function Ea(t){let e,n;for(;t.length&&cf(t[t.length-1]);){let i=t[t.length-1];i.__inputId!==void 0?e=i.__varId??e:e??(e=i.__varId),n??(n=i.__inputId),t=t.slice(0,-1)}let r=Te(t,S1,E1);return e!==void 0&&(r.__varId=e),n!==void 0&&(r.__inputId=n),r}function qt(t,e){return e.__inputId&&t.inputs&&t.inputs[e.__inputId]!==void 0?t.inputs[e.__inputId]:e.__varId&&t.inputs&&t.inputs[e.__varId]!==void 0?t.inputs[e.__varId]:e.title&&t.inputs&&t.inputs[e.title]!==void 0?t.inputs[e.title]:e.defval}function pn(t,e){let n;for(let s=e.length-1;s>=0&&cf(e[s]);s--)n??(n=e[s].__inputId);if(n===void 0)return Ea(e);let r=t._inputOptionsCache??(t._inputOptionsCache=new Map),i=r.get(n);return i||(i=Ea(e),r.set(n,i)),i}function k1(t){return(...e)=>{let n=Ea(e),r=qt(t,n);if(typeof r=="string"&&typeof n.defval=="number"){let i=lf(t,r);if(i!==void 0)return i}return r}}function A1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function T1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function N1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function C1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function I1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function M1(t){return(e,n=0)=>_.from(e).get(n)}function P1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function D1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function O1(t){return(...e)=>{let n=Ea(e),r=qt(t,n);if(typeof r=="string"){let i=lf(t,r);return i!==void 0?i:n.defval}return r}}function R1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function L1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function F1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function B1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}function V1(t){return(...e)=>{let n=pn(t,e);return qt(t,n)}}var $1=Object.defineProperty,z1=(t,e,n)=>e in t?$1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Et=(t,e,n)=>z1(t,typeof e!="symbol"?e+"":e,n),j1={any:k1,bool:A1,color:T1,enum:N1,float:C1,int:I1,param:M1,price:P1,session:D1,source:O1,string:R1,symbol:L1,text_area:F1,time:B1,timeframe:V1},Bl=class{constructor(e){this.context=e,Et(this,"any"),Et(this,"bool"),Et(this,"color"),Et(this,"enum"),Et(this,"float"),Et(this,"int"),Et(this,"param"),Et(this,"price"),Et(this,"session"),Et(this,"source"),Et(this,"string"),Et(this,"symbol"),Et(this,"text_area"),Et(this,"time"),Et(this,"timeframe"),Object.entries(j1).forEach(([n,r])=>{this[n]=r(e)})}};function q1(t){return e=>Math.abs(_.from(e).get(0))}function U1(t){return e=>Math.acos(_.from(e).get(0))}function W1(t){return e=>Math.asin(_.from(e).get(0))}function H1(t){return e=>Math.atan(_.from(e).get(0))}function G1(t){return(...e)=>{let n=e.map(r=>_.from(r).get(0));return n.reduce((r,i)=>r+i,0)/n.length}}function K1(t){return e=>Math.ceil(_.from(e).get(0))}function Y1(t){return e=>Math.cos(_.from(e).get(0))}function X1(t){return()=>Math.E}function Z1(t){return e=>Math.exp(_.from(e).get(0))}function J1(t){return e=>Math.floor(_.from(e).get(0))}function Q1(t){return e=>Math.log(_.from(e).get(0))}function ev(t){return e=>Math.log(_.from(e).get(0))}function tv(t){return e=>Math.log10(_.from(e).get(0))}function nv(t){return(...e)=>{let n=e.map(r=>_.from(r).get(0));return Math.max(...n)}}function rv(t){return(...e)=>{let n=e.map(r=>_.from(r).get(0));return Math.min(...n)}}function iv(t){return(e,n,r)=>typeof e=="string"?e:e instanceof _?n?new _(e.data,e.offset+n):e:!Array.isArray(e)&&typeof e=="object"?e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new _(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new _(t.params[r],n||0)))}function sv(t){return()=>1.618033988749895}function av(t){return()=>Math.PI}function ov(t){return(e,n)=>Math.pow(_.from(e).get(0),_.from(n).get(0))}var uf=0x5deece66dn,lv=0xbn,hf=(1n<<48n)-1n,lp=t=>(BigInt(Math.trunc(t))^uf)&hf,cp=t=>t*uf+lv&hf;function cv(t){let e=cp(t),n=cp(e),r=Number(e>>22n),i=Number(n>>21n);return[(r*2**27+i)/2**53,n]}function uv(t){return(...e)=>{let n=typeof e[e.length-1]=="string"?e.pop():void 0,r=e[0]!==void 0?_.from(e[0]).get(0):0,i=e[1]!==void 0?_.from(e[1]).get(0):1,s=e[2]!==void 0?_.from(e[2]).get(0):NaN,a;if(!s||Number.isNaN(s))a=Math.random();else{t.taState||(t.taState={});let o=n||`random_${s}`;t.taState[o]||(t.taState[o]={bar:t.idx,committed:lp(s),tentative:lp(s)});let l=t.taState[o];t.idx!==l.bar&&(l.committed=l.tentative,l.bar=t.idx),[a,l.tentative]=cv(l.tentative)}return r+(i-r)*a}}var up=t=>Number.isNaN(t)?NaN:Math.sign(t)*Math.round(Math.abs(t));function hv(t){return(e,n)=>{let r=_.from(e).get(0),i=n==null?0:_.from(n).get(0);if(!i)return up(r);let s=10**i,a=Math.abs(r)*s*s;return!Number.isFinite(a)||a>=Number.MAX_SAFE_INTEGER?up(r*s)/s:Math.sign(r)*Math.round(Math.round(a)/s)/s}}var pv=10n**10n-2n,dv=2n*10n**10n;function fv(t){let e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t);let n=e.getBigUint64(0),r=Number(n>>52n&0x7ffn),i=n&(1n<<52n)-1n;return r===0?[i,-1074]:[i|1n<<52n,r-1075]}function pf(t){let[e,n]=String(t).split("e"),[r,i=""]=e.split("."),s=i.length-Number(n??0),a=BigInt(r+i);return s>=0?[a,s]:[a*10n**BigInt(-s),0]}function mv(t,e){let n=t/e,r=Math.floor(n);if(Math.abs(n-r-.5)>1e-6+n*1e-12||!Number.isSafeInteger(r))return Math.round(n);let[i,s]=fv(t),[a,o]=pf(e),l=i*10n**BigInt(o),c=a;s>=0?l<<=BigInt(s):c<<=BigInt(-s);let u=BigInt(r);return dv*(l-u*c)>=pv*c?r+1:r}function yv(t,e){let[n,r]=pf(e),i=t*Number(n);return Number.isSafeInteger(i)&&r<=22?i/10**r:t*e}function gv(t){return e=>{let n=_.from(e).get(0),r=t.pine.syminfo.mintick;if(!Number.isFinite(n)||!(r>0)||n===0)return t.precision(Math.round(n/r)*r);let i=mv(Math.abs(n),r);return t.precision(Math.sign(n)*yv(i,r))}}function _v(t){return()=>.6180339887498948}function bv(t){return e=>Math.sign(_.from(e).get(0))}function xv(t){return e=>Math.sin(_.from(e).get(0))}function vv(t){return e=>Math.sqrt(_.from(e).get(0))}var wv=Object.defineProperty,Sv=(t,e,n)=>e in t?wv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ht=(t,e,n)=>Sv(t,typeof e!="symbol"?e+"":e,n),ka=class t{constructor(e=8){ht(this,"buf"),ht(this,"head",0),ht(this,"mask"),ht(this,"size",0);let n=8;for(;n<e;)n*=2;this.buf=new Array(n),this.mask=n-1}static from(e){let n=new t(e.length+1);for(let r=e.length-1;r>=0;r--)n.push(e[r]);return n}push(e){this.size===this.buf.length&&this.grow(),this.buf[this.head+this.size&this.mask]=e,this.size++}shift(){let e=this.buf[this.head];return this.head=this.head+1&this.mask,this.size--,e}at(e){return this.buf[this.head+this.size-1-e&this.mask]}oldest(){return this.buf[this.head]}toArray(){let e=new Array(this.size);for(let n=0;n<this.size;n++)e[n]=this.at(n);return e}grow(){let e=this.buf.length,n=new Array(e*2);for(let r=0;r<this.size;r++)n[r]=this.buf[this.head+r&this.mask];this.buf=n,this.head=0,this.mask=e*2-1}};function uo(t,e){let n=0,r=t.length;for(;n<r;){let i=n+r>>>1;t[i]<e?n=i+1:r=i}return n}function Ms(t,e){let n=0,r=t.length;for(;n<r;){let i=n+r>>>1;t[i]<=e?n=i+1:r=i}return n}function hp(t,e){t.splice(Ms(t,e),0,e)}function pp(t,e){t.splice(uo(t,e),1)}var Vl=class{constructor(){ht(this,"counts",new Map),ht(this,"byCount",new Map),ht(this,"maxCount",0)}add(e){let n=this.counts.get(e)||0;n>0&&pp(this.byCount.get(n),e),this.counts.set(e,n+1);let r=this.byCount.get(n+1);r||this.byCount.set(n+1,r=[]),hp(r,e),n+1>this.maxCount&&(this.maxCount=n+1)}remove(e){let n=this.counts.get(e),r=this.byCount.get(n);pp(r,e),n>1?(this.counts.set(e,n-1),hp(this.byCount.get(n-1),e)):this.counts.delete(e),n===this.maxCount&&r.length===0&&this.maxCount--}mode(){return this.maxCount===0?NaN:this.byCount.get(this.maxCount)[0]}},Ev={},kv={backfill:(t,e,n,r)=>{let i=_.from(n);for(;t.length<r;)t.push(i.get(t.length))}},Ci=class{constructor(e=!1){this.carry=e,ht(this,"lastIdx",-1),ht(this,"ring",new ka),ht(this,"calls",0),ht(this,"cap",NaN),ht(this,"t",null),ht(this,"agg"),ht(this,"tAgg"),ht(this,"tCalls",0),ht(this,"fast",{rebuilt:!1,x:void 0,evict:!1,cap:NaN}),ht(this,"scratch",[])}begin(e){if(e<=this.lastIdx)return;let n=this.t;if(n){if(n.rebuilt)this.ring=ka.from(n.values),this.cap=n.cap,this.rebuilt();else{this.ring.push(n.x);let i=n.evict?this.ring.shift():void 0,s=this.cap===n.cap;this.cap=n.cap,this.pushed(n.x,n.evict,i,s)}this.calls=this.tCalls;let r=this.agg;this.agg=this.tAgg,this.tAgg=r,this.t=null}if(this.carry&&this.lastIdx>=0&&this.ring.size>0){let r=Math.min(e-this.lastIdx-1,this.cap);for(let i=0;i<r;i++){let s=this.ring.at(0);this.ring.push(s);let a=this.ring.size>this.cap;this.pushed(s,a,a?this.ring.shift():void 0,!0)}}this.lastIdx=e}push(e,n,r,i=Ev,s){let a=this.calls+1;this.tCalls=a;let o=this.ring.size,l=!!i.backfill&&Math.min(o+1,r)<r&&(a>=r||e>=r-1);if(o<=r&&!l){let u=o+1>r;u&&i.dropped&&i.dropped(this.ring.oldest(),this);let h=this.fast;h.x=n,h.evict=u,h.cap=r,this.t=h;return}let c=this.ring.toArray();if(c.unshift(n),i.trimOnce){if(c.length>r){let u=c.pop();i.dropped&&i.dropped(u,this)}}else for(;c.length>r;){let u=c.pop();i.dropped&&i.dropped(u,this)}l&&i.backfill(c,this,s,r),this.t={rebuilt:!0,values:c,cap:r}}set(e,n){this.tCalls=this.calls+1,this.t={rebuilt:!0,values:e,cap:n}}get size(){let e=this.t;return e?e.rebuilt?e.values.length:this.ring.size+(e.evict?0:1):this.ring.size}at(e){let n=this.t;return n?n.rebuilt?n.values[e]:e===0?n.x:this.ring.at(e-1):this.ring.at(e)}evicted(){return this.ring.oldest()}values(e){let n=this.t;if(n&&n.rebuilt)return n.values;let r=this.scratch;r.length=e;let i=0;n&&(r[i++]=n.x);let s=this.ring;for(let a=0;i<e;i++,a++)r[i]=s.at(a);return r}pushed(e,n,r,i){}rebuilt(){}},Av=Object.defineProperty,Tv=(t,e,n)=>e in t?Av(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ie=(t,e,n)=>Tv(t,typeof e!="symbol"?e+"":e,n),$l=5e3,Aa=t=>Number.isNaN(t),dp=134217729;function Nv(t,e){return t*e}function fp(t,e,n){let r=dp*t,i=r-(r-t),s=t-i;r=dp*e;let a=r-(r-e),o=e-a;return i*a-n+i*o+s*a+s*o}var ys=class{constructor(e=0){Ie(this,"v",new Float64Array(64)),Ie(this,"nan",new Int32Array(65)),Ie(this,"ph"),Ie(this,"pl"),Ie(this,"qh"),Ie(this,"ql"),Ie(this,"off",0),Ie(this,"start",0),Ie(this,"end",0),Ie(this,"keep",$l),this.ph=e>=1?new Float64Array(65):null,this.pl=e>=1?new Float64Array(65):null,this.qh=e>=2?new Float64Array(65):null,this.ql=e>=2?new Float64Array(65):null}get size(){return this.end-this.start}keepFor(e){2*e>this.keep&&(this.keep=2*e)}grow(){let e=this.v.length*2,n=(i,s)=>{let a=new Float64Array(s);return a.set(i),a};this.v=n(this.v,e);let r=new Int32Array(e+1);r.set(this.nan),this.nan=r,this.ph&&(this.ph=n(this.ph,e+1),this.pl=n(this.pl,e+1)),this.qh&&(this.qh=n(this.qh,e+1),this.ql=n(this.ql,e+1))}push(e){let n=this.off+this.end-this.start;n>=this.v.length&&(this.grow(),n=this.off+this.end-this.start),this.v[n]=e;let r=Aa(e);this.nan[n+1]=this.nan[n]+(r?1:0);let i=r?0:e;if(this.ph){let s=this.ph[n],a=s+i,o=a-s,l=s-(a-o)+(i-o)+this.pl[n],c=a+l;this.ph[n+1]=c,this.pl[n+1]=l-(c-a)}if(this.qh){let s=this.end,a=Nv(s,i),o=fp(s,i,a),l=this.qh[n],c=l+a,u=c-l,h=l-(c-u)+(a-u)+o+this.ql[n],p=c+h;this.qh[n+1]=p,this.ql[n+1]=h-(p-c)}this.end++}truncate(e){this.end=e}compact(){let e=this.size-this.keep;if(e<=0||this.off+this.size<this.v.length*.75)return;let n=this.size-e,r=this.off+e;this.v.copyWithin(0,r,r+n),this.nan.copyWithin(0,r,r+n+1),this.ph&&(this.ph.copyWithin(0,r,r+n+1),this.pl.copyWithin(0,r,r+n+1)),this.qh&&(this.qh.copyWithin(0,r,r+n+1),this.ql.copyWithin(0,r,r+n+1)),this.off=0,this.start+=e}get(e){return this.v[this.off+e-this.start]}at(e){let n=this.end-1-e;return n>=this.start?this.v[this.off+n-this.start]:NaN}view(e){let n=this.off+this.end-this.start;return this.v.subarray(n-e,n)}nas(e){let n=this.off+this.end-this.start;return this.nan[n]-this.nan[n-e]}diff(e,n,r){let i=this.off+this.end-this.start,s=e[i],a=-e[i-r],o=s+a,l=o-s,c=s-(o-l)+(a-l)+(n[i]-n[i-r]),u=o+c;return[u,c-(u-o)]}sum(e){let[n,r]=this.diff(this.ph,this.pl,e);return n+r}wsum(e){let[n,r]=this.diff(this.qh,this.ql,e),[i,s]=this.diff(this.ph,this.pl,e),a=this.end-e-1,o=a*i,l=fp(a,i,o)+a*s,c=-o,u=n+c,h=u-n,p=n-(u-h)+(c-h)+(r-l);return u+p}},Ta=class{constructor(){Ie(this,"lo",0),Ie(this,"hi",0),Ie(this,"savedLo",0),Ie(this,"savedHi",0),Ie(this,"log",[])}commit(){this.log.length=0,this.savedLo=this.lo,this.savedHi=this.hi}rollback(){for(let e=this.log.length-1;e>=0;e--){let[n,r]=this.log[e];n?this.remove(r):this.add(r)}this.log.length=0,this.lo=this.savedLo,this.hi=this.savedHi}doAdd(e){Aa(e)||(this.add(e),this.log.push([!0,e]))}doRemove(e){Aa(e)||(this.remove(e),this.log.push([!1,e]))}sync(e,n,r=0){let i=e.end-r,s=Math.max(e.start,i-n);if(s>=this.hi||i<=this.lo){for(;this.lo<this.hi;)this.doRemove(e.get(this.lo++));this.lo=this.hi=s}for(;this.hi>i;)this.doRemove(e.get(--this.hi));for(;this.lo<s;)this.doRemove(e.get(this.lo++));for(;this.hi<i;)this.doAdd(e.get(this.hi++));for(;this.lo>s;)this.doAdd(e.get(--this.lo))}},Na=class extends Ta{constructor(){super(...arguments),Ie(this,"sorted",[])}add(e){this.sorted.splice(Ms(this.sorted,e),0,e)}remove(e){this.sorted.splice(uo(this.sorted,e),1)}},zl=class extends Ta{constructor(){super(...arguments),Ie(this,"counts",new Vl)}add(e){this.counts.add(e)}remove(e){this.counts.remove(e)}},Ca=class{constructor(e,n=!1){this.max=e,this.newest=n,Ie(this,"idx",[]),Ie(this,"val",[]),Ie(this,"head",0),Ie(this,"lastNa",-1),Ie(this,"synced",0),Ie(this,"popped",[]),Ie(this,"pushedCount",0),Ie(this,"saved",{head:0,lastNa:-1,synced:0})}commit(e){for(;this.head<this.idx.length&&this.idx[this.head]<e.start;)this.head++;this.head>1024&&this.head*2>this.idx.length&&(this.idx.splice(0,this.head),this.val.splice(0,this.head),this.head=0),this.popped.length=0,this.pushedCount=0,this.saved={head:this.head,lastNa:this.lastNa,synced:this.synced}}rollback(){this.idx.length-=this.pushedCount,this.val.length-=this.pushedCount;for(let e=this.popped.length-1;e>=0;e--)this.idx.push(this.popped[e][0]),this.val.push(this.popped[e][1]);this.popped.length=0,this.pushedCount=0,this.head=this.saved.head,this.lastNa=this.saved.lastNa,this.synced=this.saved.synced}sync(e){for(this.synced<e.start&&(this.synced=e.start);this.synced<e.end;this.synced++){let n=this.synced,r=e.get(n);if(Aa(r)){this.lastNa=n;continue}for(;this.idx.length>this.head;){let i=this.val[this.val.length-1];if(!(this.max?i<r||this.newest&&i===r:i>r||this.newest&&i===r))break;this.pushedCount>0?this.pushedCount--:this.popped.push([this.idx[this.idx.length-1],i]),this.idx.pop(),this.val.pop()}this.idx.push(n),this.val.push(r),this.pushedCount++}}find(e,n){let r=Math.max(e.end-n,this.lastNa+1,e.start),i=this.head,s=this.idx.length;for(;i<s;){let a=i+s>>1;this.idx[a]<r?i=a+1:s=a}return i<this.idx.length?this.idx[i]:-1}},hn=class{constructor(e=0,n,r=!0){this.fill=n,this.backfill=r,Ie(this,"h"),Ie(this,"lastIdx",-1),Ie(this,"savedEnd",0),Ie(this,"newBar",!1),this.h=new ys(e)}write(e){let n=this.h;n.push(this.fill?this.fill(e,n.size?n.at(0):NaN):e)}push(e,n,r,i){this.visit(e,r,i),this.write(n==null?NaN:Number(n))}visit(e,n,r){let i=this.h;if(i.keepFor(n+1),e!==this.lastIdx){if(this.newBar=!0,this.lastIdx<0){if(this.backfill&&r)for(let s=Math.max(0,e-Math.max($l,2*(n+1)));s<e;s++){let a=r.get(e-s);this.write(a==null?NaN:Number(a))}}else{i.compact();let s=Math.min(e-this.lastIdx-1,Math.max($l,2*(n+1)));if(i.size)for(let a=0;a<s;a++)i.push(i.at(0))}this.savedEnd=i.end,this.lastIdx=e}else this.newBar=!1,i.truncate(this.savedEnd)}},Cv=Object.defineProperty,Iv=(t,e,n)=>e in t?Cv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gn=(t,e,n)=>Iv(t,typeof e!="symbol"?e+"":e,n),zn=t=>t==null||typeof t=="number"&&Number.isNaN(t),mp=(t,e)=>typeof t=="function"?t(e):t.get(e),Mv=5e3,jl=class{constructor(e){gn(this,"h",new ys(1)),gn(this,"lastIdx",-1),gn(this,"savedEnd",0),gn(this,"sorted"),gn(this,"counts"),gn(this,"hi"),gn(this,"lo"),gn(this,"bars"),gn(this,"length",0),gn(this,"sum",NaN),gn(this,"scratch",[]),this.sorted=e==="sorted"?new Na:null,this.counts=e==="counts"?new zl:null,this.hi=e==="extremes"?new Ca(!0,!0):null,this.lo=e==="extremes"?new Ca(!1,!0):null,this.bars=e==="extremes"?new ys:null}push(e,n){this.h.push(e),this.bars?.push(n)}max(){return this.h.get(this.hi.find(this.h,this.length))}min(){return this.h.get(this.lo.find(this.h,this.length))}maxBar(){return this.bars.get(this.hi.find(this.h,this.length))}minBar(){return this.bars.get(this.lo.find(this.h,this.length))}at(e){return this.h.at(e)}values(){let e=this.length,n=this.scratch;n.length=e;let r=this.h.view(e);for(let i=0;i<e;i++)n[i]=r[e-1-i];return n}kth(e){return this.sorted.sorted[e]}mode(){return this.counts.counts.mode()}};function Re(t,e,n,r,i=!1,s,a="values"){t.taState||(t.taState={});let o=t.taState[e];o||(o=t.taState[e]=new jl(i));let l=o.h;if(!(r>=1))return;if(l.keepFor(r),o.bars?.keepFor(r),t.idx!==o.lastIdx){if(o.lastIdx<0)for(let h=Math.min(t.idx,Mv+2*r);h>=1;h--){let p=mp(n,h);zn(p)||o.push(p,t.idx-h)}else l.compact(),o.bars?.compact();o.savedEnd=l.end,o.sorted?.commit(),o.counts?.commit(),o.hi?.commit(l),o.lo?.commit(l),o.lastIdx=t.idx}else l.truncate(o.savedEnd),o.bars?.truncate(o.savedEnd),o.sorted?.rollback(),o.counts?.rollback(),o.hi?.rollback(),o.lo?.rollback();let c=s===void 0?mp(n,0):s;zn(c)||o.push(c,t.idx),o.hi?.sync(l),o.lo?.sync(l);let u=r;if(a==="bars"){if(t.idx<r-1||l.size===0)return;u=Math.min(r,l.size)}else if(l.size<r)return;return o.sorted?.sync(l,u),o.counts?.sync(l,u),o.length=u,o.sum=l.sum(u),o}function Pv(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e);if(r&&i>=1&&Number.isInteger(i)){let l=Re(t,r,s,i);return l?l.sum:NaN}let a=0,o=0;for(let l=0;o<i&&l<=t.idx;l++){let c=s.get(l);c==null||Number.isNaN(c)||(a+=c,o++)}return o<i?NaN:a}}function Dv(t){return e=>Math.tan(_.from(e).get(0))}function Ov(t){return e=>{let n=_.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(180/Math.PI)}}function Rv(t){return e=>{let n=_.from(e).get(0);return n==null||Number.isNaN(n)?NaN:n*(Math.PI/180)}}function Lv(t){return(e,n)=>e&&n}function Fv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)<1e-10:r===i}}function Bv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)<1e-10?!0:r>i:r>=i}}function Vv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)<1e-10?!1:r>i:r>i}}function $v(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r!="number"||typeof i!="number"?r/i:isNaN(r)||isNaN(i)?NaN:Math.trunc(r/i)}}function zv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)<1e-10?!0:r<i:r<=i}}function jv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)<1e-10?!1:r<i:r<i}}function qv(t){return(e,n)=>{let r=_.from(e).get(0),i=_.from(n).get(0);return typeof r=="number"&&typeof i=="number"?isNaN(r)||isNaN(i)?NaN:Math.abs(r-i)>=1e-10:r!==i}}function Uv(t){return(e,n)=>e||n}var Wv=Object.defineProperty,Hv=(t,e,n)=>e in t?Wv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pe=(t,e,n)=>Hv(t,typeof e!="symbol"?e+"":e,n),Gv={abs:q1,acos:U1,asin:W1,atan:H1,avg:G1,ceil:K1,cos:Y1,e:X1,exp:Z1,floor:J1,ln:Q1,log:ev,log10:tv,max:nv,min:rv,param:iv,phi:sv,pi:av,pow:ov,random:uv,round:hv,round_to_mintick:gv,rphi:_v,sign:bv,sin:xv,sqrt:vv,sum:Pv,tan:Dv,todegrees:Ov,toradians:Rv,__and:Lv,__eq:Fv,__ge:Bv,__gt:Vv,__idiv:$v,__le:zv,__lt:jv,__neq:qv,__or:Uv},ql=class{constructor(e){this.context=e,pe(this,"_cache",{}),pe(this,"abs"),pe(this,"acos"),pe(this,"asin"),pe(this,"atan"),pe(this,"avg"),pe(this,"ceil"),pe(this,"cos"),pe(this,"e"),pe(this,"exp"),pe(this,"floor"),pe(this,"ln"),pe(this,"log"),pe(this,"log10"),pe(this,"max"),pe(this,"min"),pe(this,"param"),pe(this,"phi"),pe(this,"pi"),pe(this,"pow"),pe(this,"random"),pe(this,"round"),pe(this,"round_to_mintick"),pe(this,"rphi"),pe(this,"sign"),pe(this,"sin"),pe(this,"sqrt"),pe(this,"sum"),pe(this,"tan"),pe(this,"todegrees"),pe(this,"toradians"),pe(this,"__and"),pe(this,"__eq"),pe(this,"__ge"),pe(this,"__gt"),pe(this,"__idiv"),pe(this,"__le"),pe(this,"__lt"),pe(this,"__neq"),pe(this,"__or"),Object.entries(Gv).forEach(([n,r])=>{this[n]=r(e)})}};function Rr(t,e){let n=`__unsupportedRequest_${e}`;return t.cache[n]||(t.cache[n]=!0,t.warn(`request.${e}() is not supported by PineTS: it returns na`,`request.${e}`)),NaN}function yp(t){let e=Array.isArray(t)&&t.length===2&&typeof t[1]=="string"?t[0]:t;return e instanceof _?e.get(0):e}function Kv(t){return(...e)=>{let n=yp(e[0]),r=yp(e[1]);return typeof n=="string"&&n!==""&&n.toUpperCase()===String(r).toUpperCase()?1:Rr(t,"currency_rate")}}function Yv(t){return(...e)=>Rr(t,"dividends")}function Xv(t){return(...e)=>Rr(t,"earnings")}function Zv(t){return(...e)=>Rr(t,"economic")}function Jv(t){return(...e)=>Rr(t,"financial")}function Qv(t){return t!=null&&!Array.isArray(t)&&typeof t.getFootprintData=="function"}var ew=Object.defineProperty,tw=(t,e,n)=>e in t?ew(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,yr=(t,e,n)=>tw(t,typeof e!="symbol"?e+"":e,n),Ia=class{constructor(e){yr(this,"downPrice"),yr(this,"upPrice"),yr(this,"buyVolume"),yr(this,"sellVolume"),yr(this,"totalVolume"),yr(this,"deltaVolume"),yr(this,"buyImbalance"),yr(this,"sellImbalance"),this.downPrice=e.downPrice,this.upPrice=e.upPrice,this.buyVolume=e.buyVolume,this.sellVolume=e.sellVolume,this.totalVolume=e.totalVolume,this.deltaVolume=e.delta,this.buyImbalance=e.buyImbalance,this.sellImbalance=e.sellImbalance}up_price(){return this.upPrice}down_price(){return this.downPrice}buy_volume(){return this.buyVolume}sell_volume(){return this.sellVolume}total_volume(){return this.totalVolume}delta(){return this.deltaVolume}has_buy_imbalance(){return this.buyImbalance}has_sell_imbalance(){return this.sellImbalance}};function Nu(t){return t instanceof $t?NaN:t instanceof _?t.get(0):typeof t=="function"?t():t}var nw=Object.defineProperty,rw=(t,e,n)=>e in t?nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_n=(t,e,n)=>rw(t,typeof e!="symbol"?e+"":e,n),Zi=1e-10,iw=.01,sw=2e3;function aw(t){return Math.floor(t+1e-6)}function df(t,e){return Math.floor(t/e)}function gp(t,e,n){return df(Math.round(t/e),n)}var Ma=class t{constructor(e,n,r,i,s,a,o){_n(this,"rowList"),_n(this,"buyVolume"),_n(this,"sellVolume"),_n(this,"totalVolume"),_n(this,"deltaVolume"),_n(this,"pocIndex"),_n(this,"vahIndex"),_n(this,"valIndex"),_n(this,"_rowSize"),_n(this,"_firstRowIndex"),_n(this,"_context"),this._context=e,this.rowList=n,this._rowSize=r,this._firstRowIndex=i,this.buyVolume=s.buy,this.sellVolume=s.sell,this.totalVolume=s.total,this.deltaVolume=s.delta,this.pocIndex=a,this.valIndex=o.lo,this.vahIndex=o.hi}static build(e,n,r,i){let s=I=>e.precision(I),{ticksPerRow:a,mintick:o}=r,l=a*o,c=new Map,u=new Map,h=1/0,p=-1/0;for(let I of n){if(!I||!Number.isFinite(I.price))continue;let V=Number.isFinite(I.buyVolume)?I.buyVolume:0,ee=Number.isFinite(I.sellVolume)?I.sellVolume:0,oe=gp(I.price,o,a);c.set(oe,(c.get(oe)??0)+V),u.set(oe,(u.get(oe)??0)+ee),oe<h&&(h=oe),oe>p&&(p=oe)}if(!Number.isFinite(h))return null;i&&Number.isFinite(i.low)&&Number.isFinite(i.high)&&i.low<=i.high&&(h=Math.min(h,gp(i.low,o,a)),p=Math.max(p,h,df(Math.round(i.high/o)-1,a)));let d=p-h+1;if(d>sw)return null;let f=new Array(d),m=new Array(d),y=new Array(d),g=0,w=0;for(let I=0;I<d;I++){let V=c.get(h+I)??0,ee=u.get(h+I)??0;f[I]=V,m[I]=ee,y[I]=V+ee,g+=V,w+=ee}let k=y[0];for(let I=1;I<d;I++)y[I]>k&&(k=y[I]);let S=(d-1)/2,E=-1;for(let I=0;I<d;I++)y[I]+Zi<k||(E<0||Math.abs(I-S)<Math.abs(E-S)-Zi)&&(E=I);let T=g+w,N=Number.isNaN(r.vaPercent)?0:r.vaPercent,$=T>0?T*N/100+iw:0,z=E,H=E,C=y[E];for(;z>0||H<d-1;){let I=H<d-1,V=z>0,ee=I?y[H+1]:-1/0,oe=V?y[z-1]:-1/0,L;V?I?Math.abs(ee-oe)<=Zi?L=H+1-E<=E-(z-1):L=ee>oe:L=!1:L=!0;let le=L?ee:oe;if(C+le>$)break;C+=le,L?H++:z--}let ae=Math.max(r.imbalancePercent/100,1),te=new Array(d);for(let I=0;I<d;I++){let V=f[I],ee=m[I],oe=I>0&&V>0&&V+Zi>=ae*m[I-1],L=I<d-1&&ee>0&&ee+Zi>=ae*f[I+1],le=s((h+I)*l),$e=s((h+I+1)*l);te[I]=new Ia({downPrice:le,upPrice:$e,buyVolume:s(V),sellVolume:s(ee),totalVolume:s(V+ee),delta:s(V-ee),buyImbalance:oe,sellImbalance:L})}return new t(e,te,l,h,{buy:s(g),sell:s(w),total:s(T),delta:s(g-w)},E,{lo:z,hi:H})}buy_volume(){return this.buyVolume}sell_volume(){return this.sellVolume}total_volume(){return this.totalVolume}delta(){return this.deltaVolume}poc(){return this.rowList[this.pocIndex]}vah(){return this.rowList[this.vahIndex]}val(){return this.rowList[this.valIndex]}rows(){return new Q([...this.rowList],Z.any,this._context)}get_row_by_price(...e){let n=Nu(M(e,["price"])[0]);if(typeof n!="number"||!Number.isFinite(n))return NaN;let r=aw(n/this._rowSize)-this._firstRowIndex;return r<0||r>=this.rowList.length?NaN:this.rowList[r]}},ow=[["ticks_per_row"],["ticks_per_row","va_percent"],["ticks_per_row","va_percent","imbalance_percent"]],lw={ticks_per_row:"series",va_percent:"series",imbalance_percent:"series"},cw=70,uw=300;function ff(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"?t[0]:t}function rl(t){let e=ff(t);return e instanceof _?e.get(0):typeof e=="number"?e:NaN}function hw(t){return t.cache.__footprint||(t.cache.__footprint={bars:new Map,built:new Map,requestKey:null,loadedVersion:-1,warned:!1}),t.cache.__footprint}function il(t,e){if(e<0)throw new fe(`Invalid value of the \'${t}\' argument (${e}) in the \'request.footprint\' function. It must be >= 0.`,"request.footprint")}function Ul(t,e,n){e.warned||(e.warned=!0,t.warn(n,"request.footprint"))}async function _p(t,e,n){let r=t.marketData??[],i=r[0],s=r[r.length-1],a=n===void 0,o=a?i?.openTime:n,l=a?s?.closeTime??t.eDate:void 0,c=a?r.length:void 0,u=[];try{u=await t.source.getFootprintData(t.tickerId,t.timeframe,c,o,l)??[]}catch(h){Ul(t,e,`request.footprint(): footprint data could not be loaded (${h instanceof Error?h.message:String(h)})`)}for(let h of u)!h||!Number.isFinite(h.openTime)||(e.bars.set(h.openTime,h),e.built.delete(h.openTime));e.loadedVersion=t.dataVersion}function pw(t){return async(...e)=>{let n=Te(e.map(ff),ow,lw),r=Math.trunc(rl(n.ticks_per_row)),i=n.va_percent===void 0?cw:rl(n.va_percent),s=n.imbalance_percent===void 0?uw:rl(n.imbalance_percent),a=hw(t),o=`${r}|${i}|${s}`;if(a.requestKey===null)a.requestKey=o;else if(a.requestKey!==o)throw new fe("The script executes too many `request.footprint()` function calls.","request.footprint");if(il("ticks_per_row",r),il("va_percent",i),il("imbalance_percent",s),!(r>0))return NaN;if(!Qv(t.source))return Ul(t,a,"request.footprint(): the market data source does not provide footprint data \\u2014 returning na"),NaN;let l=t.pine?.syminfo?.mintick;if(!(typeof l=="number"&&l>0))return Ul(t,a,"request.footprint(): syminfo.mintick is unavailable, so rows cannot be sized \\u2014 returning na"),NaN;let c=_.from(t.data.openTime).get(0);a.loadedVersion===-1?await _p(t,a,void 0):t.dataVersion>a.loadedVersion&&await _p(t,a,c);let u=a.bars.get(c);if(!u)return NaN;if(!a.built.has(c)){let h={low:_.from(t.data.low).get(0),high:_.from(t.data.high).get(0)};a.built.set(c,Ma.build(t,u.levels??[],{ticksPerRow:r,mintick:l,vaPercent:Math.min(i,100),imbalancePercent:s},h))}return a.built.get(c)??NaN}}function dw(t){return(e,n,r)=>{t.params[r]||(t.params[r]=[]);let i;if(e instanceof _)i=e.get(n||0);else if(Array.isArray(e)){let s=e.some(o=>o instanceof _),a=e.every(o=>!(o instanceof _)&&!Array.isArray(o));(s||a)&&e.length>=1?i=e.map(o=>o instanceof _?o.get(0):o):i=_.from(e).get(n||0)}else i=e;return t.params[r].length===0?t.params[r].push(i):t.params[r][t.params[r].length-1]=i,t._requestParamSources||(t._requestParamSources={}),t._requestParamSources[r]=e,[i,r]}}function fw(t){return(...e)=>Rr(t,"quandl")}var mw=new Set(["heikinashi","standard"]);function ss(t){if(typeof t=="string"&&t.startsWith("={"))try{let{symbol:e,...n}=JSON.parse(t.slice(1));if(typeof e=="string")return{symbol:e,modifiers:n}}catch{}return{symbol:t,modifiers:{}}}function sl(t,e){let n=Object.keys(e).filter(i=>e[i]!==void 0);if(n.length===0)return t;let r=n.map(i=>[i,e[i]]);return r.push(["symbol",t]),r.sort(([i],[s])=>i<s?-1:i>s?1:0),"="+JSON.stringify(Object.fromEntries(r))}function Yr(t){if(typeof t!="string")return{symbol:t,modifier:null};let e=t.lastIndexOf(";");if(e<=0||e===t.length-1)return{symbol:ss(t).symbol,modifier:null};let n=t.slice(e+1).toLowerCase();return mw.has(n)?{symbol:ss(t.slice(0,e)).symbol,modifier:n}:{symbol:ss(t).symbol,modifier:null}}function mf(t){if(typeof t!="string")return t;let{symbol:e,modifier:n}=Yr(t);return n?`${e};${n}`:e}function Tr(t){return Yr(t).symbol}function yf(t,e){let{modifier:n}=Yr(t);return`${n?t.slice(0,t.lastIndexOf(";")):t};${e}`}function bp(t,e,n,r,i=!1,s=!1){for(let a=0;a<n.length;a++)if(n[a]<=t&&t<r[a])return i||s||e>=r[a]?a:a-1;return-1}function xp(t,e,n,r,i=!1,s,a=!1){for(let o=n.length-1;o>=0;o--){if(r[o]<=e&&n[o]>=t){if(i){let l=o;for(;l>0&&n[l-1]>=t;)l--;return l}return o}if(r[o]<t)break}return-1}async function gf(t,e,n){let r=typeof n=="string"?n:"",i=r.match(/p\\d+$/)?.[0]??r,s=t._ltfTruncatedBodies?.[i];return e.runPretranspiled(s??t.transpiledFn,t.inputs)}var vp=[["symbol","timeframe","expression"],["symbol","timeframe","expression","gaps"],["symbol","timeframe","expression","gaps","lookahead"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency"],["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency","calc_bars_count"]],yw={symbol:"series",timeframe:"series",expression:"any",gaps:"series",lookahead:"series",ignore_invalid_symbol:"series",currency:"series",calc_bars_count:"series"};function Cu(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function gw(t,e){return t.map(n=>Cu(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function zr(t){return Cu(t)?t[0]:t}function _w(t,e,n,r){let i=e[e.length-1].indexOf(t);if(i>=0&&i<n.length&&n[i]!==void 0)return n[i];if(Cu(r))return r[1]}function Wl(t){return t==null||typeof t!="object"?t:"__value"in t?t.__value:t instanceof _?t.get(0):Array.isArray(t)?t.map(Wl):t}function bw(t){return async(...e)=>{let n=[],r=gw(e,n),i=Te(r,vp,yw),s=zr(i.symbol),a=zr(i.timeframe),o=zr(i.expression),l=zr(i.gaps),c=zr(i.lookahead),u=s instanceof _?s.get(0):s,h=typeof t.tickerId=="string"&&t.tickerId.includes(":")?t.tickerId.split(":")[1]:t.tickerId,p=typeof h=="string"?Yr(h):{symbol:h,modifier:null},d=p.modifier==="standard"?null:p.modifier,f=mf(u===""?t.tickerId:u),m=typeof f=="string"&&f.includes(":")?f.split(":")[1]:f,y=a instanceof _?a.get(0):a,g=y===""?t.timeframe:typeof y=="string"?y:String(y??""),w=o,k=_w("expression",vp,n,i.expression),S=l,E=c,T=S===!0||S==="gaps_on",N=E===!0||E==="lookahead_on",$=zr(i.ignore_invalid_symbol)===!0,z=(()=>{let He=zr(i.calc_bars_count);return typeof He=="number"&&He>0?Math.min(He,Zd):void 0})();if(t.isSecondaryContext){let He=Wl(w);return Array.isArray(He)?[He]:He}let H=pt(t.timeframe),C=pt(g);if(!H||!C)throw new Error(`Invalid value of the \'timeframe\' argument (\'${C?t.timeframe:g}\') in the \'security\' function.`);let ae=Vt(H),te=Vt(C),I=typeof m=="string"?Yr(m):{symbol:m,modifier:null},V=I.modifier==="standard"?null:I.modifier,ee=!m||m===""||I.symbol===p.symbol&&V===d;if(Ni(H)===Ni(C)&&ee){let He=Wl(w);return Array.isArray(He)?[He]:He}let oe=ae>te,L=_.from(t.data.openTime).get(0),le=_.from(t.data.closeTime).get(0),$e=t.idx===t.length-1&&le>Date.now(),Ee=`${m}_${g}_${k}`,O=`${Ee}_prevIdx`;if(t.cache[Ee]){let He=t.cache[Ee];if(He.failed)return NaN;t.dataVersion>He.dataVersion&&(await He.pineTS.updateTail(He.context),He.dataVersion=t.dataVersion);let Yi=He.context,Ws=oe?xp(L,le,Yi.data.openTime.data,Yi.data.closeTime.data,N,t.eDate,T):bp(L,le,Yi.data.openTime.data,Yi.data.closeTime.data,N,$e);if(Ws==-1)return NaN;let ci=Yi.params[k][Ws];if(!oe&&T){let Xh=t.cache[O];return Xh!==void 0&&Xh===Ws?NaN:(t.cache[O]=Ws,Array.isArray(ci)?[ci]:ci)}return Array.isArray(ci)?[ci]:ci}let ve=Math.max(1e3*60*60*24*30,2*te*1e3),St=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),Dn=z?void 0:St?St-ve:void 0,$r=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now();Xd(t,"request.security");let li=new Or(t.source,m,g,z,Dn,$r);li.markAsSecondary(t);let Gt;try{Gt=await gf(t,li,k)}catch(He){if(!$)throw He;return t.cache[Ee]={failed:!0},t.warn(`request.security(${m}, ${g}) returns na: ${He?.message??He}`,"request.security"),NaN}t.cache[Ee]={pineTS:li,context:Gt,dataVersion:t.dataVersion};let en=oe?xp(L,le,Gt.data.openTime.data,Gt.data.closeTime.data,N,t.eDate,T):bp(L,le,Gt.data.openTime.data,Gt.data.closeTime.data,N,$e);if(en==-1)return NaN;let Qo=Gt.params[k][en];return!oe&&T?(t.cache[O]=en,NaN):Array.isArray(Qo)?[Qo]:Qo}}var wp=[["symbol","timeframe","expression"],["symbol","timeframe","expression","ignore_invalid_symbol"],["symbol","timeframe","expression","ignore_invalid_symbol","currency"],["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe"],["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe","calc_bars_count"]],xw={symbol:"series",timeframe:"series",expression:"any",ignore_invalid_symbol:"series",currency:"series",ignore_invalid_timeframe:"series",calc_bars_count:"series"};function Iu(t){return Array.isArray(t)&&t.length===2&&typeof t[1]=="string"}function vw(t,e){return t.map(n=>Iu(n)?(e.push(n[1]),n[0]):(e.push(void 0),n))}function pi(t){return Iu(t)?t[0]:t}function ww(t,e,n,r){let i=e[e.length-1].indexOf(t);if(i>=0&&i<n.length&&n[i]!==void 0)return n[i];if(Iu(r))return r[1]}function di(t){return typeof t=="number"?Z.float:typeof t=="boolean"?Z.bool:typeof t=="string"?Z.string:Z.any}var _f={open:t=>t.open,high:t=>t.high,low:t=>t.low,close:t=>t.close,volume:t=>t.volume,hl2:t=>(t.high+t.low)/2,hlc3:t=>(t.high+t.low+t.close)/3,ohlc4:t=>(t.high+t.low+t.open+t.close)/4,hlcc4:t=>(t.high+t.low+t.close+t.close)/4,time:t=>t.openTime,openTime:t=>t.openTime,closeTime:t=>t.closeTime};function Hl(t,e){if(!(t instanceof _))return null;let n=e?.data;if(!n)return null;for(let r of Object.keys(_f))if(t===n[r])return r;return null}function Sw(t,e){if(t instanceof _&&(t=t.get(0)),!(t instanceof Cn))return null;let n=t._udt;if(!n||!n._fieldDefaults||!Array.isArray(n._definitionKeys))return null;let r=n._definitionKeys;if(r.length===0)return null;let i=[];for(let s of r){if(!(s in n._fieldDefaults))return null;let a=n._fieldDefaults[s],o=Hl(a,e);if(o===null)return null;i.push(o)}return{kind:"udt",builtinNames:i,fieldNames:r,udt:n}}function Ew(t,e){if(t===void 0)return null;if(Array.isArray(t)){let r=[];for(let i of t){let s=Hl(i,e);if(s===null)return null;r.push(s)}return r.length>0?{kind:"tuple",builtinNames:r}:null}let n=Hl(t,e);return n!==null?{kind:"series",builtinNames:[n]}:Sw(t,e)}async function Sp(t,e,n,r,i,s){let a=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),o=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),l=new Or(t.source,e,n,r,a,o);l.markAsSecondary(t),await l.ready();let c=l.openTime,u=l.closeTime,h=l.data,p=i.builtinNames.map(f=>_f[f]),d;if(i.kind==="series")d=h.map(f=>p[0](f));else if(i.kind==="tuple")d=h.map(f=>p.map(m=>m(f)));else{let f=i.fieldNames,m=i.udt;d=h.map(y=>{let g={};for(let w=0;w<f.length;w++)g[f[w]]=p[w](y);return new Cn(g,t,m)})}return{data:{openTime:{data:c},closeTime:{data:u}},params:{[s]:d}}}function kw(t){return async(...e)=>{let n=[],r=vw(e,n),i=Te(r,wp,xw),s=pi(i.symbol),a=pi(i.timeframe),o=pi(i.expression),l=s instanceof _?s.get(0):s,c=mf(l===""?t.tickerId:l),u=typeof c=="string"&&c.includes(":")?c.split(":")[1]:c,h=a instanceof _?a.get(0):a,p=h===""?t.timeframe:typeof h=="string"?h:String(h??""),d=o,f=ww("expression",wp,n,i.expression);pi(i.ignore_invalid_symbol);let m=pi(i.ignore_invalid_timeframe),y=(()=>{let V=pi(i.calc_bars_count);return typeof V=="number"&&V>0?Math.min(V,Zd):void 0})();if(t.isSecondaryContext)return Array.isArray(d)?[d.map(V=>new Q([V],di(V),t))]:new Q([d],di(d),t);let g=pt(t.timeframe),w=pt(p);if(!g||!w){if(m)return NaN;throw new Error(`Invalid value of the \'timeframe\' argument (\'${w?t.timeframe:p}\') in the \'security_lower_tf\' function.`)}let k=Vt(g);if(Vt(w)>k){if(m)return NaN;throw new Error(`Timeframe ${p} is not lower than or equal to chart timeframe ${t.timeframe}`)}if(Ni(w)===Ni(g))return Array.isArray(d)?[d.map(V=>new Q([V],di(V),t))]:new Q([d],di(d),t);let S=`${u}_${p}_${f}_lower`,E=t._requestParamSources?.[f],T=Ew(E,t);if(!t.cache[S])if(Xd(t,"request.security_lower_tf"),T!==null){let V=await Sp(t,u,p,y,T,f);t.cache[S]={pineTS:null,context:V,dataVersion:t.dataVersion,_fastPath:!0,_fastPathArgs:{builtinExpr:T}}}else{let V=t.sDate||(t.marketData?.length>0?t.marketData[0].openTime:void 0),ee=(t.marketData?.length>0?t.marketData[t.marketData.length-1].closeTime:0)||t.eDate||Date.now(),oe=new Or(t.source,u,p,y,V,ee);oe.markAsSecondary(t);let L=await gf(t,oe,f);t.cache[S]={pineTS:oe,context:L,dataVersion:t.dataVersion}}let N=t.cache[S];if(t.dataVersion>N.dataVersion)if(N._fastPath){let V=await Sp(t,u,p,y,N._fastPathArgs.builtinExpr,f);N.context=V,N.dataVersion=t.dataVersion}else await N.pineTS.updateTail(N.context),N.dataVersion=t.dataVersion;let $=N.context,z=_.from(t.data.openTime).get(0),H=_.from(t.data.closeTime).get(0),C=$.data.openTime.data,ae=$.data.closeTime.data,te=$.params[f];if(!te)return Array.isArray(d)?[d.map(()=>new Q([],Z.float,t))]:new Q([],Z.float,t);let I=[];for(let V=0;V<C.length;V++){let ee=C[V];if(!(ae[V]<=z)){if(ee>=H)break;ee>=z&&ee<H&&I.push(te[V])}}if(I.length>0&&Array.isArray(I[0])){let V=I[0].length,ee=[];for(let oe=0;oe<V;oe++){let L=I.map($e=>$e[oe]),le=L.length>0?di(L[0]):Z.float;ee.push(new Q(L,le,t))}return[ee]}else{let V=I.length>0?di(I[0]):Z.float;return new Q(I,V,t)}}}function Aw(t){return(...e)=>Rr(t,"seed")}function Tw(t){return(...e)=>Rr(t,"splits")}var Nw=Object.defineProperty,Cw=(t,e,n)=>e in t?Nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kt=(t,e,n)=>Cw(t,typeof e!="symbol"?e+"":e,n),Iw={currency_rate:Kv,dividends:Yv,earnings:Xv,economic:Zv,financial:Jv,footprint:pw,param:dw,quandl:fw,security:bw,security_lower_tf:kw,seed:Aw,splits:Tw},Gl=class{constructor(e){this.context=e,Kt(this,"_cache",{}),Kt(this,"currency_rate"),Kt(this,"dividends"),Kt(this,"earnings"),Kt(this,"economic"),Kt(this,"financial"),Kt(this,"footprint"),Kt(this,"param"),Kt(this,"quandl"),Kt(this,"security"),Kt(this,"security_lower_tf"),Kt(this,"seed"),Kt(this,"splits"),Object.entries(Iw).forEach(([n,r])=>{this[n]=r(e)})}};function Mw(t){return e=>{t.taState||(t.taState={});let n=e||"accdist";t.taState[n]||(t.taState[n]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=t.taState[n];t.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=t.idx);let i=t.get(t.data.close,0),s=t.get(t.data.high,0),a=t.get(t.data.low,0),o=t.get(t.data.volume,0);if(isNaN(i)||isNaN(s)||isNaN(a)||isNaN(o))return r.currentCumulativeSum=r.prevCumulativeSum,t.precision(r.prevCumulativeSum);let l=s-a,c=0;l!==0&&(c=(i-a-(s-i))/l*o);let u=r.prevCumulativeSum+c;return r.currentCumulativeSum=u,t.precision(u)}}function Pw(t){return(e,n,r,i,...s)=>{let a=typeof s[s.length-1]=="string"?s.pop():void 0,o=_.from(n).get(0),l=_.from(r).get(0),c=_.from(i).get(0),u=s.length>0&&!!_.from(s[0]).get(0);t.taState||(t.taState={});let h=a||`alma_${o}_${l}_${c}_${u}`;t.taState[h]||(t.taState[h]={carry:new hn,weightsKey:"",weights:[]});let p=t.taState[h],d=p.carry,f=`${o}_${l}_${c}_${u}`;if(p.weightsKey!==f){let S=u?Math.floor(l*(o-1)):l*(o-1),E=o/c,T=[],N=0;for(let $=0;$<o;$++){let z=Math.exp(-Math.pow($-S,2)/(2*E*E));T.push(z),N+=z}for(let $=0;$<T.length;$++)T[$]/=N;p.weights=T,p.weightsKey=f}let m=_.from(e);d.push(t.idx,m.get(0),o,m);let y=d.h;if(!(o>=1)||y.size<o)return NaN;let g=p.weights,w=0,k=y.view(o);for(let S=0;S<o;S++)w+=g[S]*k[S];return t.precision(w)}}function Dw(t){return(e,n)=>{let r=_.from(e).get(0);t.taState||(t.taState={});let i=n||`atr_${r}`;t.taState[i]||(t.taState[i]={lastIdx:-1,prevAtr:null,prevInitSum:0,prevInitCount:0,currentAtr:null,currentInitSum:0,currentInitCount:0});let s=t.taState[i];t.idx>s.lastIdx&&(s.lastIdx>=0&&(s.prevAtr=s.currentAtr,s.prevInitSum=s.currentInitSum,s.prevInitCount=s.currentInitCount),s.lastIdx=t.idx);let a=t.get(t.data.high,0),o=t.get(t.data.low,0),l=t.get(t.data.close,0);if(isNaN(a)||isNaN(o)||isNaN(l))return NaN;let c=t.idx>0?t.get(t.data.close,1):null,u;if(c!==null&&!isNaN(c)){let m=a-o,y=Math.abs(a-c),g=Math.abs(o-c);u=Math.max(m,y,g)}else u=a-o;let h=s.prevInitCount,p=s.prevInitSum,d=s.prevAtr;if(h<r){if(p+=u,h++,s.currentInitSum=p,s.currentInitCount=h,h===r){let m=p/r;return s.currentAtr=m,t.precision(m)}return NaN}let f=(d*(r-1)+u)/r;return s.currentAtr=f,t.precision(f)}}function Ow(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"barssince";t.taState[r]||(t.taState[r]={lastIdx:-1,prevLastTrueIndex:null,currentLastTrueIndex:null});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevLastTrueIndex=i.currentLastTrueIndex),i.lastIdx=t.idx);let s=_.from(e).get(0),a=i.prevLastTrueIndex;return s&&(a=t.idx),i.currentLastTrueIndex=a,a===null?NaN:t.idx-a}}function Rw(t){return(e,n,r,i)=>{let s=_.from(n).get(0),a=_.from(r).get(0);t.taState||(t.taState={});let o=i||`bb_${s}_${a}`,l=Re(t,o,_.from(e),s);if(!l)return[[NaN,NaN,NaN]];let c=l.sum/s,u=l.values(),h=0;for(let m=0;m<s;m++)h+=Math.pow(u[m]-c,2);let p=Math.sqrt(h/s),d=c+a*p,f=c-a*p;return[[t.precision(c),t.precision(d),t.precision(f)]]}}function Lw(t){return(e,n,r,i)=>{let s=_.from(n).get(0),a=_.from(r).get(0);t.taState||(t.taState={});let o=i||`bbw_${s}_${a}`,l=Re(t,o,_.from(e),s);if(!l)return NaN;let c=l.sum/s,u=l.values(),h=0;for(let y=0;y<s;y++){let g=u[y]-c;h+=g*g}let p=h/s,d=Math.sqrt(p),f=a*d;if(c===0)return t.precision(0);let m=2*f/c*100;return t.precision(m)}}function Fw(t){return(e,n,r)=>{var i;let s=_.from(n).get(0),a=_.from(e);t.taState||(t.taState={});let o=r||`cci_${s}`,l=(i=t.taState)[o]??(i[o]=new hn),c=a.get(0);l.push(t.idx,c,s,a);let u=Re(t,`${o}_mean`,a,s);if(!u||l.h.size<s)return NaN;let h=u.sum/s,p=l.h.view(s),d=0;for(let y=0;y<s;y++)d+=Math.abs(p[s-1-y]-h);let f=d/s;if(f===0)return 0;let m=(c-h)/(.015*f);return t.precision(m)}}function Bw(t){return(e,n=1,r)=>{var i;typeof n=="string"&&(r=n,n=1);let s=_.from(n).get(0);t.taState||(t.taState={});let a=r||`change_${s}`,o=(i=t.taState)[a]??(i[a]=new hn),l=_.from(e),c=l.get(0);if(o.push(t.idx,c,s,l),!(s>=0)||o.h.size<=s)return NaN;let u=c-o.h.at(s);return t.precision(u)}}var Vw=Object.defineProperty,$w=(t,e,n)=>e in t?Vw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zw=(t,e,n)=>$w(t,typeof e!="symbol"?e+"":e,n),Pa=class{constructor(e){this.up=e,zw(this,"series")}get(e){let n=this.series.get(e)-this.series.get(e+1);return this.up?n>=0?n:0:n>=0?0:-n}};function jw(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e);t.taState||(t.taState={});let a=r||`cmo_${i}`;t.taState[a]||(t.taState[a]={prev:new Ci,up:new Pa(!0),down:new Pa(!1)});let o=t.taState[a],l=o.prev;l.begin(t.idx),o.up.series=o.down.series=s;let c=s.get(0),u=l.ring.size?l.ring.at(0):s.get(1);l.push(t.idx,c,1);let h=c-u,p=Re(t,`${a}_up`,o.up,i,!1,h>=0?h:0),d=Re(t,`${a}_down`,o.down,i,!1,h>=0?0:-h);if(!p||!d)return NaN;let f=p.sum+d.sum;if(f===0)return t.precision(0);let m=100*(p.sum-d.sum)/f;return t.precision(m)}}function qw(t){return(e,n,r)=>{var i;let s=_.from(n).get(0),a=_.from(e),o=0,l=0;if(r&&s>=1){t.taState||(t.taState={});let u=(i=t.taState)[r]??(i[r]=new hn(2));u.push(t.idx,a.get(0),s,a);let h=Re(t,`${r}_sum`,a,s),p=u.h;if(!h||p.size<s||p.nas(s)>0)return NaN;o=h.sum,l=(s+1)*p.sum(s)-p.wsum(s)}else for(let u=0;u<s;u++){let h=a.get(u);if(isNaN(h))return NaN;o+=h,l+=h*(u+1)}if(o===0)return NaN;let c=-l/o;return t.precision(c)}}function Uw(t){return(e,n,r,i)=>{let s=_.from(r).get(0),a=_.from(e),o=_.from(n),l=i||`correlation_${s}`,c=(g,w)=>{let k=Re(t,`${l}_${g}`,w,s);if(!k)return NaN;let S=k.values(),E=0;for(let T=0;T<s;T++)E+=S[T];return E/s},u=c("x",g=>a.get(g)),h=c("y",g=>o.get(g)),p=c("xy",g=>a.get(g)*o.get(g)),d=c("xx",g=>a.get(g)*a.get(g)),f=c("yy",g=>o.get(g)*o.get(g));if([u,h,p,d,f].some(g=>Number.isNaN(g)))return NaN;let m=d-u*u,y=f-h*h;return m<=0||y<=0?t.precision(0):t.precision((p-u*h)/Math.sqrt(m*y))}}function bf(t,e,n){if(!e)return;t.taState||(t.taState={});let r=t.taState[e];r||(r=t.taState[e]={lastIdx:-1,shared:!1,prev:n(),current:n(),tick:-1});let i=t._execTick??0;return t.idx>r.lastIdx?(r.lastIdx>=0&&(r.prev={...r.current}),r.lastIdx=t.idx):r.current.callIdx===t.idx&&r.tick===i&&(r.shared=!0),r.tick=i,r.shared?void 0:r}function xf(t,e,n,r,i){let s=(l,c)=>i?l>c:l<c,a=bf(t,e,()=>({count:0,callIdx:-1,length:NaN})),o;if(a&&a.prev.callIdx===t.idx-1&&a.prev.length===r){let l=n.get(0),c=n.get(1);o=zn(l)||zn(c)?a.prev.count:s(l,c)?a.prev.count+1:0}else{o=0;for(let l=0;l<t.idx&&o<r;l++){let c=n.get(l),u=n.get(l+1);if(!(zn(c)||zn(u))){if(!s(c,u))break;o++}}}return a&&(a.current={count:o,callIdx:t.idx,length:r}),o>=r}function Mu(t,e,n,r){let i=n.get(0),s=r.get(0),a=bf(t,e,()=>({a:NaN,b:NaN,callIdx:-1})),o=NaN,l=NaN;if(a)a.prev.callIdx>=0&&(o=a.prev.a,l=a.prev.b);else for(let c=1;c<=t.idx;c++){let u=n.get(c),h=r.get(c);if(!zn(u)&&!zn(h)){o=u,l=h;break}}if(a){let c=!zn(i)&&!zn(s);a.current={a:c?i:o,b:c?s:l,callIdx:t.idx}}return[i,s,o,l]}function Ww(t){return(e,n,r)=>{let[i,s,a,o]=Mu(t,r,_.from(e),_.from(n));if(isNaN(i)||isNaN(s)||isNaN(a)||isNaN(o))return!1;let l=i>s&&a<=o,c=i<s&&a>=o;return l||c}}function Hw(t){return(e,n,r)=>{let[i,s,a,o]=Mu(t,r,_.from(e),_.from(n));return a<=o&&i>s}}function Gw(t){return(e,n,r)=>{let[i,s,a,o]=Mu(t,r,_.from(e),_.from(n));return a>=o&&i<s}}function Kw(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"cum";t.taState[r]||(t.taState[r]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevCumulativeSum=i.currentCumulativeSum),i.lastIdx=t.idx);let s=_.from(e).get(0);if(isNaN(s))return i.currentCumulativeSum=i.prevCumulativeSum,NaN;let a=i.prevCumulativeSum+s;return i.currentCumulativeSum=a,t.precision(a)}}function Yw(t){return(e,n,r)=>{var i;let s=_.from(n).get(0),a=_.from(e);t.taState||(t.taState={});let o=r||`dev_${s}`,l=(i=t.taState)[o]??(i[o]=new hn);l.push(t.idx,a.get(0),s,a);let c=Re(t,`${o}_mean`,a,s);if(!c||l.h.size<s)return NaN;let u=c.sum/s,h=l.h.view(s),p=0;for(let f=0;f<s;f++)p+=Math.abs(h[s-1-f]-u);let d=p/s;return t.precision(d)}}function Xw(t){return(e,n,r)=>{let i=_.from(e).get(0),s=_.from(n).get(0);t.taState||(t.taState={});let a=r||`dmi_${i}_${s}`;t.taState[a]||(t.taState[a]={lastIdx:-1,prevTrInitSum:0,prevPlusInitSum:0,prevMinusInitSum:0,prevInitCount:0,prevSmoothedTR:NaN,prevSmoothedPlus:NaN,prevSmoothedMinus:NaN,prevDxInitSum:0,prevAdxInitCount:0,prevADX:NaN,currentTrInitSum:0,currentPlusInitSum:0,currentMinusInitSum:0,currentInitCount:0,currentSmoothedTR:NaN,currentSmoothedPlus:NaN,currentSmoothedMinus:NaN,currentDxInitSum:0,currentAdxInitCount:0,currentADX:NaN});let o=t.taState[a];t.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevTrInitSum=o.currentTrInitSum,o.prevPlusInitSum=o.currentPlusInitSum,o.prevMinusInitSum=o.currentMinusInitSum,o.prevInitCount=o.currentInitCount,o.prevSmoothedTR=o.currentSmoothedTR,o.prevSmoothedPlus=o.currentSmoothedPlus,o.prevSmoothedMinus=o.currentSmoothedMinus,o.prevDxInitSum=o.currentDxInitSum,o.prevAdxInitCount=o.currentAdxInitCount,o.prevADX=o.currentADX),o.lastIdx=t.idx);let l=t.get(t.data.high,0),c=t.get(t.data.low,0),u=t.get(t.data.close,0);if(isNaN(l)||isNaN(c)||isNaN(u))return[[NaN,NaN,NaN]];let h=t.idx>0?t.get(t.data.high,1):NaN,p=t.idx>0?t.get(t.data.low,1):NaN,d=t.idx>0?t.get(t.data.close,1):NaN;if(isNaN(h))return[[NaN,NaN,NaN]];let f=Math.max(l-c,Math.abs(l-d),Math.abs(c-d)),m=l-h,y=p-c,g=m>y&&m>0?m:0,w=y>m&&y>0?y:0,k=o.prevInitCount,S=o.prevTrInitSum,E=o.prevPlusInitSum,T=o.prevMinusInitSum,N=o.prevSmoothedTR,$=o.prevSmoothedPlus,z=o.prevSmoothedMinus;if(k++,k<=i)S+=f,E+=g,T+=w,k===i&&(N=S/i,$=E/i,z=T/i);else{let L=1/i;N=L*f+(1-L)*N,$=L*g+(1-L)*$,z=L*w+(1-L)*z}if(o.currentInitCount=k,o.currentTrInitSum=S,o.currentPlusInitSum=E,o.currentMinusInitSum=T,o.currentSmoothedTR=N,o.currentSmoothedPlus=$,o.currentSmoothedMinus=z,k<i)return[[NaN,NaN,NaN]];let H=N===0?0:100*$/N,C=N===0?0:100*z/N,ae=H+C,te=ae===0?0:100*Math.abs(H-C)/ae,I=o.prevAdxInitCount,V=o.prevDxInitSum,ee=o.prevADX,oe=NaN;if(I++,I<=s)V+=te,I===s&&(ee=V/s,oe=ee);else{let L=1/s;ee=L*te+(1-L)*ee,oe=ee}return o.currentAdxInitCount=I,o.currentDxInitSum=V,o.currentADX=ee,[[t.precision(H),t.precision(C),t.precision(oe)]]}}function Zw(t){return(e,n,r)=>{let i=_.from(n).get(0);t.taState||(t.taState={});let s=r||`ema_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevEma:null,prevInitSum:0,prevInitCount:0,currentEma:null,currentInitSum:0,currentInitCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevEma=a.currentEma,a.prevInitSum=a.currentInitSum,a.prevInitCount=a.currentInitCount),a.lastIdx=t.idx);let o=_.from(e).get(0);if(o==null||isNaN(o))return NaN;let l=a.prevInitCount,c=a.prevInitSum,u=a.prevEma;if(l<i){if(c+=o,l++,a.currentInitSum=c,a.currentInitCount=l,l===i){let d=c/i;return a.currentEma=d,t.precision(d)}return NaN}let h=2/(i+1),p=o*h+u*(1-h);return a.currentEma=p,t.precision(p)}}function Jw(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e);return xf(t,r,s,i,!1)}}function Qw(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.high);let i=_.from(n).get(0),s=_.from(e),a=Re(t,r||`highest_${i}`,s,i,"extremes",void 0,"bars");return a?t.precision(a.max()):NaN}}var eS=t=>t===void 0||isNaN(t);function vf(t,e,n,r,i){if(!e)return tS(n,r,i,t.idx);let s=Re(t,e,n,r,"extremes",void 0,"bars");if(!s)return NaN;let a=i?s.maxBar():s.minBar();return a===t.idx?-0:a-t.idx}function tS(t,e,n,r){let i=NaN,s=NaN,a=0;for(let o=0;a<e&&o<=r;o++){let l=t.get(o);eS(l)||(a++,(isNaN(s)||(n?l>i:l<i))&&(i=l,s=-o))}return r<e-1||a===0?NaN:s}function nS(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.high);let i=_.from(n).get(0),s=_.from(e),a=vf(t,r,s,i,!0);return t.idx<i-1?NaN:a}}function rS(t){return(e,n,r)=>{let i=_.from(n).get(0),s=Math.floor(i/2),a=Math.floor(Math.sqrt(i)),o=t.pine.ta.wma,l=o(e,s,r?`${r}_wma1`:void 0),c=o(e,i,r?`${r}_wma2`:void 0),u=isNaN(l)||isNaN(c),h=2*l-c;t.taState||(t.taState={});let p=r?`${r}_hma_final`:`hma_final_${i}`;t.taState[p]||(t.taState[p]=new Ci(!0));let d=t.taState[p];if(d.begin(t.idx),u)return d.ring.size?(d.push(t.idx,d.ring.at(0),a),NaN):NaN;if(d.push(t.idx,h,a),d.size<a)return NaN;let f=0,m=0;for(let g=0;g<a;g++){let w=a-g;f+=d.at(g)*w,m+=w}let y=f/m;return t.precision(y)}}function iS(t){return e=>{let n=t.get(t.data.close,0),r=t.get(t.data.high,0),i=t.get(t.data.low,0),s=t.get(t.data.volume,0);if(isNaN(n)||isNaN(r)||isNaN(i)||isNaN(s))return NaN;let a=r-i;if(a===0)return t.precision(0);let o=(2*n-r-i)/a*s;return t.precision(o)}}function sS(t){return(e,n,r,i,s)=>{let a=_.from(n).get(0),o=_.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=_.from(i).get(0));let c,u=t.get(t.data.high,0),h=t.get(t.data.low,0);if(l){let S=t.get(t.data.close,1);isNaN(S)?c=NaN:c=Math.max(u-h,Math.abs(u-S),Math.abs(h-S))}else c=u-h;let p=_.from(e).get(0);t.taState||(t.taState={});let d=s||`kc_${a}_${o}_${l}`;t.taState[d]||(t.taState[d]={lastIdx:-1,basisState:{prevEma:null,initSum:0,initCount:0},rangeState:{prevEma:null,initSum:0,initCount:0},currentBasisState:{prevEma:null,initSum:0,initCount:0},currentRangeState:{prevEma:null,initSum:0,initCount:0}});let f=t.taState[d];t.idx>f.lastIdx&&(f.lastIdx>=0&&(f.basisState={...f.currentBasisState},f.rangeState={...f.currentRangeState}),f.lastIdx=t.idx);let m=(S,E,T,N)=>{if(isNaN(T))return Object.assign(E,S),NaN;let $=S.initCount,z=S.initSum,H=S.prevEma;if($<N){if(z+=T,$++,E.initSum=z,E.initCount=$,E.prevEma=H,$===N){let te=z/N;return E.prevEma=te,te}return NaN}let C=2/(N+1),ae=T*C+H*(1-C);return E.prevEma=ae,E.initSum=z,E.initCount=$,ae},y=m(f.basisState,f.currentBasisState,p,a),g=m(f.rangeState,f.currentRangeState,c,a);if(isNaN(y)||isNaN(g))return[[NaN,NaN,NaN]];let w=y+g*o,k=y-g*o;return[[t.precision(y),t.precision(w),t.precision(k)]]}}function aS(t){return(e,n,r,i,s)=>{let a=_.from(n).get(0),o=_.from(r).get(0),l=!0;typeof i=="string"?s=i:i!==void 0&&(l=_.from(i).get(0)),t.taState||(t.taState={});let c=s||`kcw_${a}_${o}_${l}`;t.taState[c]||(t.taState[c]={lastIdx:-1,basisState:{prevEma:null,initSum:0,initCount:0},rangeState:{prevEma:null,initSum:0,initCount:0},currentBasisState:{prevEma:null,initSum:0,initCount:0},currentRangeState:{prevEma:null,initSum:0,initCount:0}});let u=t.taState[c];t.idx>u.lastIdx&&(u.lastIdx>=0&&(u.basisState={...u.currentBasisState},u.rangeState={...u.currentRangeState}),u.lastIdx=t.idx);let h=(k,S,E,T)=>{if(isNaN(E))return Object.assign(S,k),NaN;let N=k.initCount,$=k.initSum,z=k.prevEma;if(N<T){if($+=E,N++,S.initSum=$,S.initCount=N,S.prevEma=z,N===T){let ae=$/T;return S.prevEma=ae,ae}return NaN}let H=2/(T+1),C=E*H+z*(1-H);return S.prevEma=C,S.initSum=$,S.initCount=N,C},p,d=t.get(t.data.high,0),f=t.get(t.data.low,0);if(l){let k=t.get(t.data.close,1);isNaN(k)?p=NaN:p=Math.max(d-f,Math.abs(d-k),Math.abs(f-k))}else p=d-f;let m=_.from(e).get(0),y=h(u.basisState,u.currentBasisState,m,a),g=h(u.rangeState,u.currentRangeState,p,a);if(isNaN(y)||isNaN(g))return NaN;if(y===0)return t.precision(0);let w=2*g*o/y;return t.precision(w)}}var oS=Object.defineProperty,lS=(t,e,n)=>e in t?oS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lt=(t,e,n)=>lS(t,typeof e!="symbol"?e+"":e,n),Da=class{constructor(e){this.length=e,lt(this,"size"),lt(this,"vals"),lt(this,"bars"),lt(this,"byCall"),this.size=e+1,this.vals=new Array(this.size).fill(0),this.bars=new Array(this.size).fill(-1),this.byCall=new Array(this.size).fill(!1)}slot(e){return(e%this.size+this.size)%this.size}write(e,n){let r=this.slot(e);this.vals[r]=n,this.bars[r]=e,this.byCall[r]=!0}prefill(e,n){for(let r=Math.max(0,e-this.length);r<e;r++){let i=this.slot(r);this.vals[i]=n.get(e-r),this.bars[i]=r,this.byCall[i]=!1}}read(e){if(e<0)return NaN;let n=this.slot(e);return this.byCall[n]||this.bars[n]===e?this.vals[n]:0}readSlot(e,n){return this.byCall[e]||this.bars[e]===n?this.vals[e]:0}stalePrefill(e,n){return!this.byCall[e]&&this.bars[e]>=0&&this.bars[e]!==n}valueOf(e){return this.vals[e]}},Ii=t=>Number.isInteger(t)&&t>=1,Kl=class{constructor(){lt(this,"ring",null),lt(this,"lastCall",-1),lt(this,"S",0),lt(this,"N",0),lt(this,"ok",!1),lt(this,"steps",0),lt(this,"savedFor",-1),lt(this,"saved",[-1,0,0,!1,0])}step(e,n,r,i){if(!Ii(r))return;(!this.ring||this.ring.length!==r)&&(this.ring=new Da(r),this.ring.prefill(e,i),this.lastCall=-1,this.ok=!1,this.savedFor=-1),e===this.savedFor?[this.lastCall,this.S,this.N,this.ok,this.steps]=this.saved:(this.savedFor=e,this.saved=[this.lastCall,this.S,this.N,this.ok,this.steps]);let s=this.ring,a=this.ok&&this.lastCall===e-1&&this.steps+1<r,o=a?s.read(e-r):NaN;if(s.write(e,n),this.lastCall=e,a&&!Number.isNaN(n)&&!Number.isNaN(o))return this.N=this.N-this.S+r*n,this.S=this.S-o+n,this.steps++,[this.S,this.N];let l=0,c=0;for(let u=0;u<r;u++){let h=s.read(e-u);c+=h*(r-u),l+=h}return this.S=l,this.N=c,this.steps=0,this.ok=!Number.isNaN(l+c),this.ok?[l,c]:void 0}},Yl=class{constructor(){lt(this,"slots",new Kl),lt(this,"carry",new hn(2)),lt(this,"firstLength",NaN),lt(this,"seriesForm",!1),lt(this,"committedLine",null),lt(this,"line",null)}step(e,n,r,i){if(this.carry.push(e,n,Ii(r)?r:1,i),this.carry.newBar&&(this.committedLine=this.line),this.line=this.committedLine,Number.isNaN(this.firstLength)?this.firstLength=r:r!==this.firstLength&&(this.seriesForm=!0),!this.seriesForm)return this.slots.step(e,n,r,i);let s=this.carry.h;if(!(!Ii(r)||s.size<r||s.nas(r)>0))return[s.sum(r),s.wsum(r)]}};function cS(t){return(e,n,r,i)=>{let s=_.from(n).get(0),a=_.from(r).get(0);t.taState||(t.taState={});let o=i||`linreg_${s}_${a}`;t.taState[o]||(t.taState[o]=new Yl);let l=t.taState[o],c=_.from(e),u=l.step(t.idx,c.get(0),s,c);if(!u)return NaN;let h=s,p=h*(h-1)/2,d=(h-1)*h*(2*h-1)/6,f=u[0],m=u[1]-u[0],y=h*d-p*p;if(y===0)return l.line?t.precision(l.line[1]+l.line[0]*(s-1-a)):NaN;let g=(h*m-p*f)/y,w=(f-g*p)/h;l.line=[g,w];let k=w+g*(s-1-a);return t.precision(k)}}function uS(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.low);let i=_.from(n).get(0),s=_.from(e),a=Re(t,r||`lowest_${i}`,s,i,"extremes",void 0,"bars");return a?t.precision(a.min()):NaN}}function hS(t){return(e,n,r)=>{typeof n=="string"&&r===void 0&&(r=n,n=e,e=t.data.low);let i=_.from(n).get(0),s=_.from(e),a=vf(t,r,s,i,!1);return t.idx<i-1?NaN:a}}function pS(t){return(e,n,r,i,s)=>{let a=_.from(n).get(0),o=_.from(r).get(0),l=_.from(i).get(0),c=s||`macd_${a}_${o}_${l}`,u=`${c}_fast`,h=`${c}_slow`,p=`${c}_signal`,d=t.pine.ta.ema(e,a,u),f=t.pine.ta.ema(e,o,h),m=NaN;!isNaN(d)&&!isNaN(f)&&(m=d-f);let y=NaN;isNaN(m)||(y=t.pine.ta.ema(m,l,p));let g=NaN;return!isNaN(m)&&!isNaN(y)&&(g=m-y),[[t.precision(m),t.precision(y),t.precision(g)]]}}function dS(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"max";t.taState[r]||(t.taState[r]={lastIdx:-1,prevMax:NaN,currentMax:NaN});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevMax=i.currentMax),i.lastIdx=t.idx);let s=_.from(e).get(0),a;return isNaN(s)?a=i.prevMax:isNaN(i.prevMax)?a=s:a=Math.max(i.prevMax,s),i.currentMax=a,t.precision(a)}}function fS(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e),a=Re(t,r||`median_${i}`,s,i,"sorted");if(!a)return NaN;let o=Math.floor(i/2),l=i%2===0?(a.kth(o-1)+a.kth(o))/2:a.kth(o);return t.precision(l)}}var mS=Object.defineProperty,yS=(t,e,n)=>e in t?mS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ep=(t,e,n)=>yS(t,typeof e!="symbol"?e+"":e,n),Oa=class{constructor(e){this.up=e,Ep(this,"series"),Ep(this,"volume")}get(e){let n=this.series.get(e),r=n-this.series.get(e+1);return this.volume.get(e)*(this.up?r<=0?0:n:r>=0?0:n)}};function gS(t){return(e,n,r)=>{let i=_.from(n).get(0);t.taState||(t.taState={});let s=r||`mfi_${i}`;t.taState[s]||(t.taState[s]={prev:new Ci,up:new Oa(!0),down:new Oa(!1)});let a=t.taState[s],o=a.prev;o.begin(t.idx);let l=_.from(e),c=_.from(t.data.volume),u=l.get(0),h=o.ring.size?o.ring.at(0):l.get(1);o.push(t.idx,u,1);let p=u-h,d=c.get(0);a.up.series=a.down.series=l,a.up.volume=a.down.volume=c;let f=Re(t,`${s}_up`,a.up,i,!1,d*(p<=0?0:u)),m=Re(t,`${s}_down`,a.down,i,!1,d*(p>=0?0:u));if(!f||!m)return NaN;let y=f.sum,g=m.sum;if(g===0)return t.precision(100);if(y===0)return t.precision(0);let w=100-100/(1+y/g);return t.precision(w)}}function _S(t){return(e,n)=>{t.taState||(t.taState={});let r=n||"min";t.taState[r]||(t.taState[r]={lastIdx:-1,prevMin:NaN,currentMin:NaN});let i=t.taState[r];t.idx>i.lastIdx&&(i.lastIdx>=0&&(i.prevMin=i.currentMin),i.lastIdx=t.idx);let s=_.from(e).get(0),a;return isNaN(s)?a=i.prevMin:isNaN(i.prevMin)?a=s:a=Math.min(i.prevMin,s),i.currentMin=a,t.precision(a)}}function bS(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e),a=Re(t,r||`mode_${i}`,s,i,"counts");return a&&t.idx>=i-1?a.mode():NaN}}function xS(t){return(e,n,r)=>{let i=_.from(n).get(0);return t.pine.ta.change(e,i,r)}}function vS(t){return e=>{t.taState||(t.taState={});let n=e||"nvi";t.taState[n]||(t.taState[n]={lastIdx:-1,committedNVI:1,tentativeNVI:1});let r=t.taState[n];t.idx>r.lastIdx&&(r.lastIdx>=0&&(r.committedNVI=r.tentativeNVI),r.lastIdx=t.idx);let i=t.get(t.data.close,0),s=t.get(t.data.close,1),a=t.get(t.data.volume,0),o=t.get(t.data.volume,1),l=isNaN(i)?0:i,c=isNaN(s)?0:s,u=isNaN(a)?0:a,h=isNaN(o)?0:o,p=r.committedNVI;if(!(l===0||c===0)&&u<h){let d=(l-c)/c;p=p+d*p}return r.tentativeNVI=p,t.precision(p)}}function wS(t){return()=>{t.taState||(t.taState={});let e="obv";t.taState[e]||(t.taState[e]={lastIdx:-1,committedOBV:0,tentativeOBV:0});let n=t.taState[e];t.idx>n.lastIdx&&(n.lastIdx>=0&&(n.committedOBV=n.tentativeOBV),n.lastIdx=t.idx);let r=t.get(t.data.close,0),i=t.get(t.data.volume,0),s=t.get(t.data.close,1);if(isNaN(s))return n.tentativeOBV=0,t.precision(0);let a=n.committedOBV;return r>s?a+=i:r<s&&(a-=i),n.tentativeOBV=a,t.precision(a)}}function SS(t){return(e,n,r)=>e instanceof _?n?new _(e.data,e.offset+n):e:(t.params[r]||(t.params[r]=[]),Array.isArray(e)?new _(e,n||0):(t.params[r].length===0?t.params[r].push(e):t.params[r][t.params[r].length-1]=e,new _(t.params[r],n||0)))}var ES=Object.defineProperty,kS=(t,e,n)=>e in t?ES(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jr=(t,e,n)=>kS(t,typeof e!="symbol"?e+"":e,n),gr=t=>Number.isNaN(t),Ra=class{constructor(){jr(this,"arr",[]),jr(this,"nan",0),jr(this,"held",[]),jr(this,"head",0),jr(this,"carry",new hn),jr(this,"undoLog",[]),jr(this,"lastTick")}step(e,n,r,i,s){let a=n==null?NaN:Number(n);for(this.carry.push(e,a,r,i),this.carry.newBar?this.commit():(s===void 0||s!==this.lastTick)&&this.rollback(),this.lastTick=s,this.insert(a),this.held.push(a),this.undoLog.push(()=>this.held.pop());this.held.length-this.head>r;){let l=this.held[this.head++];this.undoLog.push(()=>this.head--),this.removeValue(l)}let o=this.carry.h;for(;this.held.length-this.head<r&&o.size>this.held.length-this.head;){let l=o.at(this.held.length-this.head);if(this.head>0){let c=this.held[--this.head];this.held[this.head]=l,this.undoLog.push(()=>{this.held[this.head]=c,this.head++})}else this.held.unshift(l),this.undoLog.push(()=>this.held.shift());this.insert(l)}return this.held.length-this.head<r?void 0:this.arr}commit(){this.undoLog.length=0,this.head>1024&&this.head*2>this.held.length&&(this.held=this.held.slice(this.head),this.head=0)}rollback(){for(let e=this.undoLog.length-1;e>=0;e--)this.undoLog[e]();this.undoLog.length=0}insert(e){let n=this.insertAt(e);this.arr.splice(n,0,e),gr(e)&&this.nan++,this.undoLog.push(()=>{this.arr.splice(n,1),gr(e)&&this.nan--})}removeValue(e){let n=this.indexOf(e);n<0||(this.arr.splice(n,1),gr(e)&&this.nan--,this.undoLog.push(()=>{this.arr.splice(n,0,e),gr(e)&&this.nan++}))}insertAt(e){let n=this.arr;if(this.nan===0&&!gr(e))return Ms(n,e);let r=0;for(;r<n.length&&!(e<n[r]);)r++;return r}indexOf(e){let n=this.arr;if(this.nan===0&&!gr(e)){let r=uo(n,e);return n[r]===e?r:-1}if(gr(e)){for(let r=0;r<n.length;r++)if(gr(n[r]))return r;return-1}return n.indexOf(e)}};function AS(t,e){let n=t.length,r=Math.min(Math.max(Math.ceil(e/100*n)-1,0),n-1);return t[r]}function TS(t,e){let n=t.length,r=Math.min(Math.max(e/100*n-.5,0),n-1),i=Math.floor(r);return i>=n-1?t[n-1]:t[i]+(r-i)*(t[i+1]-t[i])}function NS(t){return(e,n,r,i)=>{var s;let a=_.from(n).get(0),o=_.from(r).get(0),l=_.from(e);if(!Ii(a))return NaN;t.taState||(t.taState={});let c=i||`pli_${a}_${o}`,u=((s=t.taState)[c]??(s[c]=new Ra)).step(t.idx,l.get(0),a,l,t._execTick);return!u||t.idx<a-1?NaN:t.precision(TS(u,o))}}function CS(t){return(e,n,r,i)=>{var s;let a=_.from(n).get(0),o=_.from(r).get(0),l=_.from(e);if(!Ii(a))return NaN;t.taState||(t.taState={});let c=i||`pnr_${a}_${o}`,u=((s=t.taState)[c]??(s[c]=new Ra)).step(t.idx,l.get(0),a,l,t._execTick);return!u||t.idx<a-1?NaN:t.precision(AS(u,o))}}var IS=t=>t==null||Number.isNaN(t);function MS(t){return(e,n,r)=>{var i;let s=_.from(n).get(0),a=_.from(e),o=a.get(0),l=0;if(r){t.taState||(t.taState={});let c=(i=t.taState)[r]??(i[r]={carry:new hn,prev:new Na}),u=c.carry,h=c.prev;if(u.push(t.idx,o,s,a),u.newBar?h.commit():h.rollback(),h.sync(u.h,s,1),t.idx<s)return NaN;IS(o)||(l=Ms(h.sorted,o))}else{if(t.idx<s)return NaN;if(o!=null)for(let c=1;c<=s;c++){let u=a.get(c);u!=null&&u<=o&&l++}}return t.precision(l/s*100)}}function PS(t,e,n,r,i){let s=e-r,a=t[s];if(!(s>=0)||a===void 0||a===null||isNaN(a))return NaN;if(e<n+r)return NaN;let o=0;for(let l=e;l>=0&&o<n+r+1;l--){let c=t[l];if(!(c==null||isNaN(c))&&(o++,l!==s&&(i?c>a||l>s&&c===a:c<a||l>s&&c===a)))return NaN}return a}function wf(t,e,n,r,i,s){if(!e)return PS(_.from(n).toArray(),t.idx,r,i,s);let a=Re(t,e,_.from(n),r+i+1,"extremes",void 0,"bars");return!a||!(i>=0)?NaN:(s?a.maxBar():a.minBar())===t.idx-i?s?a.max():a.min():NaN}function DS(t){return(e,n,r,i)=>{typeof r=="string"&&(i=r,r=n,n=e,e=t.data.high);let s=_.from(n).get(0),a=_.from(r).get(0);return t.precision(wf(t,i,e,s,a,!0))}}function OS(t){return(e,n,r,i)=>{typeof r=="string"&&(i=r,r=n,n=e,e=t.data.low);let s=_.from(n).get(0),a=_.from(r).get(0);return t.precision(wf(t,i,e,s,a,!1))}}var RS=["Traditional","Fibonacci","Woodie","Classic","DM","Camarilla"];function kp(t,{high:e,low:n,close:r},i){let s=e-n,a=(e+n+r)/3;switch(t){case"Traditional":return[a,a*2-n,a*2-e,a+s,a-s,a*2+(e-2*n),a*2-(2*e-n),a*3+(e-3*n),a*3-(3*e-n),a*4+(e-4*n),a*4-(4*e-n)];case"Fibonacci":return[a,a+.382*s,a-.382*s,a+.618*s,a-.618*s,a+s,a-s,NaN,NaN,NaN,NaN];case"Woodie":{let o=(e+n+2*i)/4,l=e+2*(o-n),c=n-2*(e-o);return[o,2*o-n,2*o-e,o+s,o-s,l,c,l+s,c-s,NaN,NaN]}case"Classic":return[a,2*a-n,2*a-e,a+s,a-s,a+2*s,a-2*s,a+3*s,a-3*s,NaN,NaN];case"DM":{let o=r<i?e+2*n+r:r>i?2*e+n+r:e+n+2*r;return[o/4,o/2-n,o/2-e,NaN,NaN,NaN,NaN,NaN,NaN,NaN,NaN]}case"Camarilla":{let o=e/n*r;return[a,r+s*1.1/12,r-s*1.1/12,r+s*1.1/6,r-s*1.1/6,r+s*1.1/4,r-s*1.1/4,r+s*1.1/2,r-s*1.1/2,o,r-(o-r)]}}return new Array(11).fill(NaN)}function LS(t){return(e,n,...r)=>{let i=typeof r[r.length-1]=="string"?r.pop():void 0,s=_.from(e).get(0),a=_.from(n).get(0)===!0,o=r.length>0&&_.from(r[0]).get(0)===!0;if(!RS.includes(s))throw new fe(`Invalid argument \'${s}\' for \'type\' in the \'ta.pivot_point_levels\' function. Possible values: [\'Camarilla\', \'Traditional\', \'DM\', \'Classic\', \'Fibonacci\', \'Woodie\']`,"ta.pivot_point_levels");if(o&&s==="Woodie")throw new fe(\'The `developing` parameter of the `ta.pivot_point_levels()` cannot be `true` when `type` is "Woodie".\',"ta.pivot_point_levels");t.taState||(t.taState={});let l=i||`pivot_point_levels_${s}_${o}`;t.taState[l]||(t.taState[l]={lastIdx:-1,prev:{period:null,levels:null},current:{period:null,levels:null}});let c=t.taState[l];t.idx>c.lastIdx&&(c.lastIdx>=0&&(c.prev=c.current),c.lastIdx=t.idx);let u={open:_.from(t.data.open).get(0),high:_.from(t.data.high).get(0),low:_.from(t.data.low).get(0),close:_.from(t.data.close).get(0)},h=c.prev.period,p=c.prev.levels;a||!h?(a&&h&&(p=kp(s,h,s==="Woodie"?u.open:h.open)),h={...u}):h={open:h.open,high:Math.max(h.high,u.high),low:Math.min(h.low,u.low),close:u.close},c.current={period:h,levels:p};let d=o?kp(s,h,h.open):p??new Array(11).fill(NaN);return new Q(d.map(f=>t.precision(f)),Z.float,t)}}function FS(t){return e=>{t.taState||(t.taState={});let n=e||"pvi";t.taState[n]||(t.taState[n]={lastIdx:-1,committedPVI:1,tentativePVI:1});let r=t.taState[n];t.idx>r.lastIdx&&(r.lastIdx>=0&&(r.committedPVI=r.tentativePVI),r.lastIdx=t.idx);let i=t.get(t.data.close,0),s=t.get(t.data.close,1),a=t.get(t.data.volume,0),o=t.get(t.data.volume,1),l=isNaN(i)?0:i,c=isNaN(s)?0:s,u=isNaN(a)?0:a,h=isNaN(o)?0:o,p=r.committedPVI;if(!(l===0||c===0)&&u>h){let d=(l-c)/c;p=p+d*p}return r.tentativePVI=p,t.precision(p)}}function BS(t){return e=>{t.taState||(t.taState={});let n=e||"pvt";t.taState[n]||(t.taState[n]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=t.taState[n];t.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=t.idx);let i=t.get(t.data.close,0),s=t.get(t.data.close,1),a=t.get(t.data.volume,0),o=r.prevCumulativeSum;if(!isNaN(i)&&!isNaN(s)&&!isNaN(a)&&s!==0){let l=(i-s)/s*a;o+=l}return r.currentCumulativeSum=o,t.precision(o)}}function VS(t){return(e,n,r)=>{let i=_.from(n).get(0);if(!(i>=1))return NaN;let s=_.from(e),a=Re(t,r||`range_${i}`,s,i,"extremes");if(!a)return NaN;let o=a.max();return t.precision((o>Number.MIN_VALUE?o:Number.MIN_VALUE)-a.min())}}var $S=Object.defineProperty,zS=(t,e,n)=>e in t?$S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,al=(t,e,n)=>zS(t,typeof e!="symbol"?e+"":e,n),Xl=class{constructor(e,n,r){this.length=e,al(this,"ring"),al(this,"vals",[]),al(this,"slots",[]),this.ring=new Da(e),this.ring.prefill(n,r);for(let i=0;i<this.ring.size;i++)this.insert(this.ring.valueOf(i),i)}write(e,n){let r=this.ring.slot(e);this.remove(this.ring.valueOf(r),r),this.ring.write(e,n),this.insert(n,r)}insert(e,n){if(Number.isNaN(e))return;let r=Ms(this.vals,e);this.vals.splice(r,0,e),this.slots.splice(r,0,n)}remove(e,n){if(Number.isNaN(e))return;let r=uo(this.vals,e);for(;this.slots[r]!==n;)r++;this.vals.splice(r,1),this.slots.splice(r,1)}};function jS(t,e){let n=t.map((l,c)=>c).sort((l,c)=>t[l]-t[c]),r=new Array(e);for(let l=0;l<e;){let c=l;for(;c+1<e&&t[n[c+1]]===t[n[l]];)c++;let u=(l+c)/2+1;for(let h=l;h<=c;h++)r[n[h]]=u;l=c+1}let i=(e+1)/2,s=0,a=0,o=0;for(let l=0;l<e;l++){let c=l+1-i,u=r[l]-i;s+=c*u,a+=c*c,o+=u*u}return o===0?NaN:s/Math.sqrt(a*o)*100}function qS(t){return(e,n,r)=>{let i=_.from(n).get(0);if(!Ii(i))return NaN;t.taState||(t.taState={});let s=r||`rci_${i}`,a=_.from(e),o=t.taState[s];(!o||o.length!==i)&&(o=t.taState[s]=new Xl(i,t.idx,a));let l=t.idx,c=a.get(0);if(o.write(l,c??NaN),i<2||l<i)return NaN;let u=o.ring,h=u.size,p=u.slot(l),d=!1;for(let E=0;E<i;E++){let T=(p-E+h)%h,N=u.readSlot(T,l-E);if(Number.isNaN(N)||l-E<0)return NaN;u.stalePrefill(T,l-E)&&(d=!0)}if(d){let E=[];for(let N=i-1;N>=0;N--)E.push(u.read(l-N));let T=jS(E,i);return Number.isNaN(T)?NaN:t.precision(T)}let f=(p+1)%h,m=(i+1)/2,y=0,g=0,w=0;for(let E=0;E<i;E++){let T=E+1-m;g+=T*T}let k=o.vals,S=o.slots;for(let E=0,T=0;E<k.length;){let N=E,$=S[E]===f?0:1;for(;N+1<k.length&&k[N+1]===k[E];)N++,S[N]!==f&&$++;let z=T+($-1)/2+1-m;for(let H=E;H<=N;H++){if(S[H]===f)continue;let C=(p-S[H]+h)%h;y+=(i-C-m)*z,w+=z*z}T+=$,E=N+1}return w===0?NaN:t.precision(y/Math.sqrt(g*w)*100)}}function US(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e);return xf(t,r,s,i,!0)}}function WS(t){return(e,n,r)=>{let i=_.from(n).get(0);t.taState||(t.taState={});let s=r||`rma_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevRma:null,prevInitSum:0,prevInitCount:0,currentRma:null,currentInitSum:0,currentInitCount:0});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevRma=a.currentRma,a.prevInitSum=a.currentInitSum,a.prevInitCount=a.currentInitCount),a.lastIdx=t.idx);let o=_.from(e).get(0);if(o==null||Number.isNaN(o))return a.currentRma=a.prevRma,a.currentInitSum=a.prevInitSum,a.currentInitCount=a.prevInitCount,NaN;let l=a.prevInitCount,c=a.prevInitSum,u=a.prevRma;if(l<i){if(c+=o,l++,a.currentInitSum=c,a.currentInitCount=l,l===i){let d=c/i;return a.currentRma=d,t.precision(d)}return NaN}let h=1/i,p=o*h+u*(1-h);return a.currentRma=p,t.precision(p)}}function HS(t){return(e,n,r)=>{var i;let s=_.from(n).get(0);t.taState||(t.taState={});let a=r||`roc_${s}`,o=(i=t.taState)[a]??(i[a]=new hn),l=_.from(e),c=l.get(0);if(o.push(t.idx,c,s,l),!(s>=0)||o.h.size<=s)return NaN;let u=o.h.at(s),h=(c-u)/u*100;return t.precision(h)}}function GS(t){return(e,n,r)=>{let i=_.from(n).get(0);t.taState||(t.taState={});let s=r||`rsi_${i}`;t.taState[s]||(t.taState[s]={lastIdx:-1,prevPrevValue:null,prevAvgGain:0,prevAvgLoss:0,initGains:[],initLosses:[],currentPrevValue:null,currentAvgGain:0,currentAvgLoss:0,currentInit:null});let a=t.taState[s];t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevPrevValue=a.currentPrevValue,a.prevAvgGain=a.currentAvgGain,a.prevAvgLoss=a.currentAvgLoss,a.currentInit&&(a.initGains.push(a.currentInit[0]),a.initLosses.push(a.currentInit[1]))),a.currentInit=null,a.lastIdx=t.idx);let o=_.from(e).get(0);if(o==null||isNaN(o))return a.currentPrevValue=NaN,a.currentInit=null,a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let l=a.prevPrevValue;if(l===null||isNaN(l))return a.currentPrevValue=o,a.currentInit=null,a.currentAvgGain=a.prevAvgGain,a.currentAvgLoss=a.prevAvgLoss,NaN;let c=a.prevAvgGain,u=a.prevAvgLoss,h=o-l,p=h>0?h:0,d=h<0?-h:0;if(a.initGains.length<i){if(a.currentInit=[p,d],a.currentPrevValue=o,a.initGains.length+1===i){c=(a.initGains.reduce((y,g)=>y+g,0)+p)/i,u=(a.initLosses.reduce((y,g)=>y+g,0)+d)/i,a.currentAvgGain=c,a.currentAvgLoss=u;let m=u===0?100:100-100/(1+c/u);return t.precision(m)}return NaN}a.currentInit=null,c=(c*(i-1)+p)/i,u=(u*(i-1)+d)/i,a.currentAvgGain=c,a.currentAvgLoss=u,a.currentPrevValue=o;let f=u===0?100:100-100/(1+c/u);return t.precision(f)}}function KS(t){return(e,n,r,i)=>{let s=_.from(e).get(0),a=_.from(n).get(0),o=_.from(r).get(0);t.taState||(t.taState={});let l=i||`sar_${s}_${a}_${o}`;t.taState[l]||(t.taState[l]={lastIdx:-1,prevResult:NaN,prevMaxMin:NaN,prevAcceleration:NaN,prevIsBelow:!1,prevBarIndex:0,currentResult:NaN,currentMaxMin:NaN,currentAcceleration:NaN,currentIsBelow:!1,currentBarIndex:0});let c=t.taState[l];t.idx>c.lastIdx&&(c.lastIdx>=0&&(c.prevResult=c.currentResult,c.prevMaxMin=c.currentMaxMin,c.prevAcceleration=c.currentAcceleration,c.prevIsBelow=c.currentIsBelow,c.prevBarIndex=c.currentBarIndex),c.lastIdx=t.idx);let u=c.prevResult,h=c.prevMaxMin,p=c.prevAcceleration,d=c.prevIsBelow,f=c.prevBarIndex,m=t.get(t.data.high,0),y=t.get(t.data.low,0),g=t.get(t.data.close,0),w=t.get(t.data.close,1),k=t.get(t.data.high,1),S=t.get(t.data.low,1),E=t.get(t.data.high,2),T=t.get(t.data.low,2);if(isNaN(m)||isNaN(y)||isNaN(g))return c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,NaN;let N=!1;return f===1&&(g>w?(d=!0,h=m,u=S):(d=!1,h=y,u=k),N=!0,p=s),f>=1&&(u=u+p*(h-u),d?u>y&&(N=!0,d=!1,u=Math.max(m,h),h=y,p=s):u<m&&(N=!0,d=!0,u=Math.min(y,h),h=m,p=s),N||(d?m>h&&(h=m,p=Math.min(p+a,o)):y<h&&(h=y,p=Math.min(p+a,o))),d?(u=Math.min(u,S),f>1&&(u=Math.min(u,T))):(u=Math.max(u,k),f>1&&(u=Math.max(u,E)))),f++,c.currentResult=u,c.currentMaxMin=h,c.currentAcceleration=p,c.currentIsBelow=d,c.currentBarIndex=f,f<=1?NaN:t.precision(u)}}function YS(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e),a=Re(t,r||`sma_${i}`,s,i);return a?t.precision(a.sum/i):NaN}}function XS(t){return(e,n,...r)=>{let i=typeof r[r.length-1]=="string"?r.pop():void 0,s=_.from(n).get(0),a=r.length===0||!!_.from(r[0]).get(0),o=_.from(e),l=Re(t,i||`stdev_${s}_${a}`,o,s);if(!l)return NaN;let c=l.sum/s,u=0,h=l.values();for(let f=0;f<s;f++)u+=Math.pow(h[f]-c,2);let p=a?s:s-1,d=Math.sqrt(u/p);return t.precision(d)}}var ZS=Object.defineProperty,JS=(t,e,n)=>e in t?ZS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ol=(t,e,n)=>JS(t,typeof e!="symbol"?e+"":e,n),Zl=class{constructor(){ol(this,"lastIdx",-1),ol(this,"prev",NaN),ol(this,"cur",NaN)}};function ll(t,e,n){return Number.isNaN(n)?(e.cur=e.prev,e.prev):(e.cur=n,t.precision(n))}function QS(t){return(e,n,r,i,s)=>{var a;let o=_.from(i).get(0);t.taState||(t.taState={});let l=s||`stoch_${o}`,c=(a=t.taState)[l]??(a[l]=new Zl),u=_.from(e).get(0),h=_.from(n).get(0),p=_.from(r).get(0);t.idx!==c.lastIdx&&(c.prev=c.cur,c.lastIdx=t.idx);let d=Re(t,`${l}_h`,_.from(n),o,"extremes",h,"bars"),f=Re(t,`${l}_l`,_.from(r),o,"extremes",p,"bars");if(!d||!f)return ll(t,c,NaN);let m=d.max(),y=f.min(),g=m-y;return g===0?u===y?ll(t,c,NaN):(c.cur=NaN,NaN):ll(t,c,100*(u-y)/g)}}function eE(t){return(e,n,r)=>{let i=_.from(n).get(0);t.taState||(t.taState={});let s=r||`supertrend_${_.from(e).get(0)}_${i}`;t.taState[s]||(t.taState[s]={factor:_.from(e).get(0),lastIdx:-1,prevTrSum:0,prevAtrValue:NaN,prevAtrCount:0,prevLowerBand:NaN,prevUpperBand:NaN,prevSuperTrend:NaN,prevDirection:NaN,currentTrSum:0,currentAtrValue:NaN,currentAtrCount:0,currentLowerBand:NaN,currentUpperBand:NaN,currentSuperTrend:NaN,currentDirection:NaN});let a=t.taState[s],o=a.factor;t.idx>a.lastIdx&&(a.lastIdx>=0&&(a.prevTrSum=a.currentTrSum,a.prevAtrValue=a.currentAtrValue,a.prevAtrCount=a.currentAtrCount,a.prevLowerBand=a.currentLowerBand,a.prevUpperBand=a.currentUpperBand,a.prevSuperTrend=a.currentSuperTrend,a.prevDirection=a.currentDirection),a.lastIdx=t.idx);let l=t.get(t.data.high,0),c=t.get(t.data.low,0),u=t.get(t.data.close,0);if(isNaN(l)||isNaN(c)||isNaN(u))return[[NaN,NaN]];let h=(l+c)/2,p=t.idx>0?t.get(t.data.close,1):NaN,d;isNaN(p)?d=l-c:d=Math.max(l-c,Math.abs(l-p),Math.abs(c-p));let f=a.prevAtrCount,m=a.prevTrSum,y=a.prevAtrValue;f++,f<=i?(m+=d,f===i&&(y=m/i)):y=(y*(i-1)+d)/i;let g=y;if(a.currentAtrCount=f,a.currentTrSum=m,a.currentAtrValue=y,isNaN(g))return[[NaN,NaN]];let w=h+o*g,k=h-o*g,S=isNaN(a.prevLowerBand)?0:a.prevLowerBand,E=isNaN(a.prevUpperBand)?0:a.prevUpperBand;isNaN(a.prevLowerBand)||k>S||p<S||(k=S),isNaN(a.prevUpperBand)||w<E||p>E||(w=E);let T,N,$=a.prevSuperTrend;return f===i?T=1:$===a.prevUpperBand?T=u>w?-1:1:T=u<k?1:-1,N=T===-1?k:w,a.currentLowerBand=k,a.currentUpperBand=w,a.currentSuperTrend=N,a.currentDirection=T,[[t.precision(N),T]]}}function tE(t){return(e,n)=>{let r=[1,2,2,1],i=6;t.taState||(t.taState={});let s=n||"swma";t.taState[s]||(t.taState[s]=new Ci(!0));let a=t.taState[s];a.begin(t.idx),a.push(t.idx,_.from(e).get(0),4,kv,e);let o=a.values(a.size);if(o.length<4)return NaN;let l=0;for(let c=0;c<4;c++)l+=r[c]*o[3-c];return l/=i,t.precision(l)}}function nE(t){return(e,n)=>{let r=!0;typeof e=="string"||e!==void 0&&(r=_.from(e).get(0));let i=t.get(t.data.high,0),s=t.get(t.data.low,0),a=t.get(t.data.close,1);if(isNaN(a))return r?t.precision(i-s):NaN;let o=Math.max(i-s,Math.abs(i-a),Math.abs(s-a));return t.precision(o)}}function rE(t){return(e,n,r,i)=>{let s=_.from(n).get(0),a=_.from(r).get(0);t.taState||(t.taState={});let o=i||`tsi_${s}_${a}`;t.taState[o]||(t.taState[o]={lastIdx:-1,prevSource:NaN,prevEma1PcValue:NaN,prevEma1PcCount:0,prevEma1PcSum:0,prevEma2PcValue:NaN,prevEma2PcCount:0,prevEma2PcSum:0,prevEma1AbsValue:NaN,prevEma1AbsCount:0,prevEma1AbsSum:0,prevEma2AbsValue:NaN,prevEma2AbsCount:0,prevEma2AbsSum:0,currentSource:NaN,currentEma1PcValue:NaN,currentEma1PcCount:0,currentEma1PcSum:0,currentEma2PcValue:NaN,currentEma2PcCount:0,currentEma2PcSum:0,currentEma1AbsValue:NaN,currentEma1AbsCount:0,currentEma1AbsSum:0,currentEma2AbsValue:NaN,currentEma2AbsCount:0,currentEma2AbsSum:0});let l=t.taState[o];t.idx>l.lastIdx&&(l.lastIdx>=0&&(l.prevSource=l.currentSource,l.prevEma1PcValue=l.currentEma1PcValue,l.prevEma1PcCount=l.currentEma1PcCount,l.prevEma1PcSum=l.currentEma1PcSum,l.prevEma2PcValue=l.currentEma2PcValue,l.prevEma2PcCount=l.currentEma2PcCount,l.prevEma2PcSum=l.currentEma2PcSum,l.prevEma1AbsValue=l.currentEma1AbsValue,l.prevEma1AbsCount=l.currentEma1AbsCount,l.prevEma1AbsSum=l.currentEma1AbsSum,l.prevEma2AbsValue=l.currentEma2AbsValue,l.prevEma2AbsCount=l.currentEma2AbsCount,l.prevEma2AbsSum=l.currentEma2AbsSum),l.lastIdx=t.idx);let c=_.from(e).get(0);if(isNaN(c))return l.currentSource=NaN,NaN;let u=isNaN(l.prevSource)?NaN:c-l.prevSource;if(l.currentSource=c,isNaN(u))return NaN;let h=Math.abs(u),p=2/(a+1),d=2/(s+1),f=2/(a+1),m=2/(s+1),y=l.prevEma1PcCount,g=l.prevEma1PcSum,w=l.prevEma1PcValue;y++,y<=a?(g+=u,y===a&&(w=g/a)):w=u*p+w*(1-p);let k=l.prevEma1AbsCount,S=l.prevEma1AbsSum,E=l.prevEma1AbsValue;if(k++,k<=a?(S+=h,k===a&&(E=S/a)):E=h*f+E*(1-f),isNaN(w)||isNaN(E))return l.currentEma1PcCount=y,l.currentEma1PcSum=g,l.currentEma1PcValue=w,l.currentEma1AbsCount=k,l.currentEma1AbsSum=S,l.currentEma1AbsValue=E,NaN;let T=l.prevEma2PcCount,N=l.prevEma2PcSum,$=l.prevEma2PcValue;T++,T<=s?(N+=w,T===s&&($=N/s)):$=w*d+$*(1-d);let z=l.prevEma2AbsCount,H=l.prevEma2AbsSum,C=l.prevEma2AbsValue;if(z++,z<=s?(H+=E,z===s&&(C=H/s)):C=E*m+C*(1-m),l.currentEma1PcCount=y,l.currentEma1PcSum=g,l.currentEma1PcValue=w,l.currentEma1AbsCount=k,l.currentEma1AbsSum=S,l.currentEma1AbsValue=E,l.currentEma2PcCount=T,l.currentEma2PcSum=N,l.currentEma2PcValue=$,l.currentEma2AbsCount=z,l.currentEma2AbsSum=H,l.currentEma2AbsValue=C,isNaN($)||isNaN(C))return NaN;if(C===0)return t.precision(0);let ae=$/C;return t.precision(ae)}}function iE(t){return(e,n,r,i)=>{t.taState||(t.taState={});let s=i||"valuewhen";t.taState[s]||(t.taState[s]={lastIdx:-1,values:[],pending:!1,pendingValue:void 0});let a=t.taState[s];t.idx>a.lastIdx&&(a.pending&&a.values.push(a.pendingValue),a.pending=!1,a.lastIdx=t.idx);let o=_.from(e).get(0),l=_.from(n).get(0),c=_.from(r).get(0);if(a.pending=!!o,a.pendingValue=l,isNaN(c)||c<0)return NaN;let u=a.values,h;if(a.pending)if(c===0)h=l;else{let p=u.length-c;if(p<0)return NaN;h=u[p]}else{let p=u.length-1-c;if(p<0)return NaN;h=u[p]}return typeof h=="number"?t.precision(h):h}}function sE(t){return(e,n,...r)=>{let i=typeof r[r.length-1]=="string"?r.pop():void 0,s=_.from(n).get(0),a=r.length===0||!!_.from(r[0]).get(0),o=_.from(e),l=Re(t,i||`variance_${s}_${a}`,o,s);if(!l)return NaN;let c=0,u=0,h=l.values();for(let m=0;m<s;m++){let y=h[m];c+=y,u+=y*y}let p=c/s,d=u/s-p*p,f=a?d:d*s/(s-1);return t.precision(f)}}function aE(t){return(...e)=>{let n=typeof e[e.length-1]=="string"?e.pop():void 0,r=e.length>0?e[0]:t.data.hlc3,i=e.length>=2,s=e.length>=3;t.taState||(t.taState={});let a=n||`vwap_${e.length}`;t.taState[a]||(t.taState[a]={lastIdx:-1,prevCumulativePV:0,prevCumulativeVolume:0,prevCumulativePPV:0,prevStarted:!1,prevLastSessionDate:null,currentCumulativePV:0,currentCumulativeVolume:0,currentCumulativePPV:0,currentStarted:!1,currentLastSessionDate:null});let o=t.taState[a];t.idx>o.lastIdx&&(o.lastIdx>=0&&(o.prevCumulativePV=o.currentCumulativePV,o.prevCumulativeVolume=o.currentCumulativeVolume,o.prevCumulativePPV=o.currentCumulativePPV,o.prevStarted=o.currentStarted,o.prevLastSessionDate=o.currentLastSessionDate),o.lastIdx=t.idx);let l=_.from(r).get(0),c=_.from(t.data.volume).get(0),u=o.prevCumulativePV,h=o.prevCumulativeVolume,p=o.prevCumulativePPV,d=o.prevStarted,f=o.prevLastSessionDate,m;if(i)m=!!_.from(e[1]).get(0);else{let S=_.from(t.data.openTime).get(0),E=t.pine?.syminfo?.timezone||"UTC",T=Ir(S,E),N=`${T.year}-${String(T.month).padStart(2,"0")}-${String(T.day).padStart(2,"0")}`;m=f!==N,f=N}m&&(u=0,h=0,p=0,d=!0),d&&(u+=l*c,h+=c,p+=l*l*c),o.currentCumulativePV=u,o.currentCumulativeVolume=h,o.currentCumulativePPV=p,o.currentStarted=d,o.currentLastSessionDate=f;let y=d&&h!==0?u/h:NaN;if(!s)return isNaN(y)?NaN:t.precision(y);let g=_.from(e[2]).get(0),w=p/h-y*y,k=Math.sqrt(Math.max(w,0));return[[t.precision(y),t.precision(y+g*k),t.precision(y-g*k)]]}}function oE(t){return(e,n,r)=>{let i=_.from(n).get(0),s=_.from(e),a=_.from(t.data.volume),o=r||`vwma_${i}`,l=Re(t,`${o}_sv`,u=>s.get(u)*a.get(u),i),c=Re(t,`${o}_v`,a,i);return!l||!c?NaN:t.precision(l.sum/c.sum)}}function lE(t){return e=>{t.taState||(t.taState={});let n=e||"wad";t.taState[n]||(t.taState[n]={lastIdx:-1,prevCumulativeSum:0,currentCumulativeSum:0});let r=t.taState[n];t.idx>r.lastIdx&&(r.lastIdx>=0&&(r.prevCumulativeSum=r.currentCumulativeSum),r.lastIdx=t.idx);let i=t.get(t.data.close,0),s=t.get(t.data.high,0),a=t.get(t.data.low,0),o=t.get(t.data.close,1);if(isNaN(i)||isNaN(s)||isNaN(a))return r.currentCumulativeSum=r.prevCumulativeSum,t.precision(r.prevCumulativeSum);let l=0;if(!isNaN(o)){let u=Math.max(s,o),h=Math.min(a,o),p=i-o;p>0?l=i-h:p<0&&(l=i-u)}let c=r.prevCumulativeSum+l;return r.currentCumulativeSum=c,t.precision(c)}}var cE=Object.defineProperty,uE=(t,e,n)=>e in t?cE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gs=(t,e,n)=>uE(t,typeof e!="symbol"?e+"":e,n),hE=(t,e)=>Number.isNaN(t)?e:t,cl=t=>t==null||Number.isNaN(t),Jl=class{constructor(){Gs(this,"carry",new hn(2,hE)),Gs(this,"savedSeen",0),Gs(this,"seen",0),Gs(this,"started",!1)}};function pE(t){return(e,n,r)=>{var i;let s=_.from(n).get(0);if(!(s>=1))return NaN;t.taState||(t.taState={});let a=r||`wma_${s}`,o=(i=t.taState)[a]??(i[a]=new Jl),l=o.carry,c=_.from(e),u=c.get(0);if(l.push(t.idx,u,s,c),o.started)l.newBar?o.savedSeen=o.seen:o.seen=o.savedSeen;else{o.started=!0;for(let p=1;p<=t.idx&&o.seen<s;p++)cl(c.get(p))||o.seen++;o.savedSeen=o.seen}if(cl(u)||o.seen++,cl(u))return NaN;let h=l.h;return o.seen<s||h.size<s||h.nas(s)>0?NaN:t.precision(h.wsum(s)/(s*(s+1)/2))}}function dE(t){return(e,n)=>{let r=_.from(e).get(0);t.taState||(t.taState={});let i=n||`wpr_${r}`,s=t.get(t.data.high,0),a=t.get(t.data.low,0),o=t.get(t.data.close,0),l=isNaN(s)||isNaN(a)||isNaN(o),c=Re(t,`${i}_h`,t.data.high,r,"extremes",l?NaN:s,"bars"),u=Re(t,`${i}_l`,t.data.low,r,"extremes",l?NaN:a,"bars");if(l||!c||!u)return NaN;let h=c.max(),p=u.min(),d=h-p;if(d===0)return t.precision(0);let f=(h-o)/d*-100;return t.precision(f)}}function fE(t){return e=>{let n=t.get(t.data.close,0),r=t.get(t.data.open,0),i=t.get(t.data.high,0),s=t.get(t.data.low,0),a=t.get(t.data.volume,0);if(isNaN(n)||isNaN(r)||isNaN(i)||isNaN(s)||isNaN(a))return NaN;let o=i-s;if(o===0)return t.precision(0);let l=(n-r)/o*a;return t.precision(l)}}var mE=Object.defineProperty,yE=(t,e,n)=>e in t?mE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G=(t,e,n)=>yE(t,typeof e!="symbol"?e+"":e,n),gE={accdist:Mw,alma:Pw,atr:Dw,barssince:Ow,bb:Rw,bbw:Lw,cci:Fw,change:Bw,cmo:jw,cog:qw,correlation:Uw,cross:Ww,crossover:Hw,crossunder:Gw,cum:Kw,dev:Yw,dmi:Xw,ema:Zw,falling:Jw,highest:Qw,highestbars:nS,hma:rS,iii:iS,kc:sS,kcw:aS,linreg:cS,lowest:uS,lowestbars:hS,macd:pS,max:dS,median:fS,mfi:gS,min:_S,mode:bS,mom:xS,nvi:vS,obv:wS,param:SS,percentile_linear_interpolation:NS,percentile_nearest_rank:CS,percentrank:MS,pivothigh:DS,pivotlow:OS,pivot_point_levels:LS,pvi:FS,pvt:BS,range:VS,rci:qS,rising:US,rma:WS,roc:HS,rsi:GS,sar:KS,sma:YS,stdev:XS,stoch:QS,supertrend:eE,swma:tE,tr:nE,tsi:rE,valuewhen:iE,variance:sE,vwap:aE,vwma:oE,wad:lE,wma:pE,wpr:dE,wvad:fE},Ql=class{constructor(e){this.context=e,G(this,"accdist"),G(this,"alma"),G(this,"atr"),G(this,"barssince"),G(this,"bb"),G(this,"bbw"),G(this,"cci"),G(this,"change"),G(this,"cmo"),G(this,"cog"),G(this,"correlation"),G(this,"cross"),G(this,"crossover"),G(this,"crossunder"),G(this,"cum"),G(this,"dev"),G(this,"dmi"),G(this,"ema"),G(this,"falling"),G(this,"highest"),G(this,"highestbars"),G(this,"hma"),G(this,"iii"),G(this,"kc"),G(this,"kcw"),G(this,"linreg"),G(this,"lowest"),G(this,"lowestbars"),G(this,"macd"),G(this,"max"),G(this,"median"),G(this,"mfi"),G(this,"min"),G(this,"mode"),G(this,"mom"),G(this,"nvi"),G(this,"obv"),G(this,"param"),G(this,"percentile_linear_interpolation"),G(this,"percentile_nearest_rank"),G(this,"percentrank"),G(this,"pivothigh"),G(this,"pivotlow"),G(this,"pivot_point_levels"),G(this,"pvi"),G(this,"pvt"),G(this,"range"),G(this,"rci"),G(this,"rising"),G(this,"rma"),G(this,"roc"),G(this,"rsi"),G(this,"sar"),G(this,"sma"),G(this,"stdev"),G(this,"stoch"),G(this,"supertrend"),G(this,"swma"),G(this,"tr"),G(this,"tsi"),G(this,"valuewhen"),G(this,"variance"),G(this,"vwap"),G(this,"vwma"),G(this,"wad"),G(this,"wma"),G(this,"wpr"),G(this,"wvad"),Object.entries(gE).forEach(([n,r])=>{this[n]=r(e)})}},Ap=["title","shorttitle","overlay","format","precision","scale","pyramiding","calc_on_order_fills","calc_on_every_tick","max_bars_back","backtest_fill_limits_assumption","default_qty_type","default_qty_value","initial_capital","currency","slippage","commission_type","commission_value","process_orders_on_close","close_entries_rule","margin_long","margin_short","explicit_plot_zorder","max_lines_count","max_labels_count","max_boxes_count","calc_bars_count","risk_free_rate","use_bar_magnifier","fill_orders_on_standard_ohlc","max_polylines_count","dynamic_requests","behind_chart","calc_on_every_history_tick"];function _E(t){let e=r=>r instanceof _?r.get(0):r,n={};return t.forEach((r,i)=>{if(Jd(r))for(let s of Object.keys(r))n[s]=e(r[s]);else i<Ap.length&&r!==void 0&&(n[Ap[i]]=e(r))}),n}function La(t,e,n){let r=t+e*n;if(!n||n<=0)return r;let i=t/n+e,s=Math.round(i);return Math.abs(i-s)>1e-6?r:Ps(s,n)}function Ps(t,e){let n=String(e),r=n.includes("e-")?Number(n.split("e-")[1])+(n.split("e-")[0].split(".")[1]?.length??0):n.split(".")[1]?.length??0;return Number((t*e).toFixed(r))}function Er(t,e){return!e||e<=0||!Number.isFinite(t)?t:Ps(Math.round(t/e),e)}function Pu(t,e){return t._fillsOnTickGrid?Er(e,t.pine?.syminfo?.mintick):e}function Du(t){let e=t.pine?.syminfo?.mintick;if(!t._fillsOnTickGrid||!e)return;let n=t._rawBar;if(!n)return{peakAt:a=>a};let r=Er(n.high,e),i=Er(n.low,e),s=Er(n.open,e);return{peakAt:a=>a===r?n.high:a===i?n.low:a===s?n.open:a}}function Tp(t,e,n){if(!n||n<=0||!Number.isFinite(t)||t===e)return t;let r=t/n,i=1e-4;return Ps(t>e?Math.ceil(r-i):Math.floor(r+i),n)}function gs(t,e,n,r){if(!r||r<=0||!Number.isFinite(t))return t;let i=t/r,s=1e-4;return Ps(n==="stop"==(e===1)?Math.ceil(i-s):Math.floor(i+s),r)}function ho(t,e){let n=t._entry_commission??(t.status==="open"?t.commission??0:(t.commission??0)/2);return Math.abs(t.size)*t.entry_price*e+n}function Si(t,e,n,r){return Math.abs(t)*e*r*n/100}function Zr(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of Bu(n)){let a=s.dir===1?e-s.entry_price:s.entry_price-e;i+=a*s.qty*r}return n.initial_capital+n.netprofit+i}function bE(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of n.opentrades){let a=Math.sign(s.size)===1?n.config.margin_long??100:n.config.margin_short??100;i+=Si(s.size,e,a,r)}return i}function Ou(t,e,n,r,i=!0,s=!1){let a=t.strategy,o=a.config.default_qty_type||"fixed",l=a.config.default_qty_value??1;if(typeof o=="function"&&(o=o()),typeof l=="function"&&(l=l()),e!=null&&!Number.isNaN(e))return Nr(t,Math.abs(e));let c=t.pine?.syminfo?.pointvalue??1;i&&(r=Mr(t,n,r));let u;switch(o){case"fixed":u=l;break;case"cash":u=l/(r*c);break;case"percent_of_equity":{let h=Number(n===-1?a.config.margin_short:a.config.margin_long)===0?Math.min(l,100):l,p=a.equity*h/100,d=r*c,f=a.config.commission_type??"percent",m=Number(a.config.commission_value??0)||0;f==="cash_per_contract"?u=p/(d+m):f==="cash_per_order"?u=(p-m)/d:u=p/(d*(1+m/100));break}default:u=l}return s&&u<0?-Nr(t,-u):Nr(t,u)}function Sf(t,e,n,r){let i=s=>typeof s=="number"&&Number.isFinite(s);return i(t)?(r===1?n>=t:n<=t)?n:t:i(e)?(r===1?n<=e:n>=e)?n:e:n}function po(t){let e=Number(t.strategy?.config?.backtest_fill_limits_assumption??0);return!Number.isFinite(e)||e<=0?0:e*(t.pine?.syminfo?.mintick??.01)}function We(t){return t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:typeof t=="function"?t():t instanceof _?t.get(0):Array.isArray(t)?t[t.length-1]:typeof t=="object"&&t.get!==void 0?t.get(0):t}function ec(t){return typeof t=="number"&&Number.isNaN(t)||typeof t=="object"&&t!==null&&"__value"in t}function Jr(t){if(t.when===void 0)return!1;let e=We(t.when);return!e||ec(e)}function Ef(t){let e=t.pine?.syminfo?.mincontract;return typeof e=="number"&&e>0?e:1e-6}function Nr(t,e){if(!Number.isFinite(e)||e<=0)return 0;let n=Ef(t),r=Math.floor(e/n*(1+1e-10)),i=Math.min(10,Math.max(0,Math.ceil(-Math.log10(n))));return Number((r*n).toFixed(i))}function fo(t,e,n){let r=Ef(t);return Math.min(e,Math.max(r,Nr(t,e*n/100)))}function jn(t,e,n,r){return Math.abs(e-t)<=Math.abs(t-n)?[t,e,n,r]:[t,n,e,r]}function Wn(t,e,n){if(n?t[0]>=e:t[0]<=e)return 0;for(let r=0;r<3;r++){let i=t[r],s=t[r+1];if(n?i<=e&&s>=e:i>=e&&s<=e)return r+(s===i?0:(e-i)/(s-i))}}function Ru(t,e,n){let{dir:r,mintick:i}=n,s=h=>r*h,a=h=>{let p=La(h,-r*n.offset,i);if(!n.offGrid||!i)return p;let d=p/i;return Ps(r===1?Math.floor(d+1e-6):Math.ceil(d-1e-6),i)},o=n.offGrid?.peakAt??(h=>h),l=n.armed,c=n.peak,u=[e];for(let h=Math.floor(e.at)+1;h<t.length;h++)u.push({at:h,price:t[h]});if(l&&s(e.price)<=s(a(c)))return{fill:{price:e.price,at:e.at,level:a(c)},armed:l,peak:c};if(l&&s(o(e.price))>s(c)&&(c=o(e.price),s(e.price)<=s(a(c))))return{fill:{price:e.price,at:e.at,level:a(c)},armed:l,peak:c};if(!l&&n.armPrice!==void 0&&s(e.price)>=s(n.armPrice)&&(l=!0,c=o(e.price),n.offset<=0&&e.at>0))return{fill:{price:e.price,at:e.at,level:e.price},armed:l,peak:c};for(let h=0;h+1<u.length;h++){let p=u[h],d=u[h+1],f=m=>p.price===d.price?p.at:p.at+(m-p.price)/(d.price-p.price)*(d.at-p.at);if(s(d.price)>s(p.price)){if(!l&&n.armPrice!==void 0&&s(d.price)>=s(n.armPrice)&&(l=!0,c=n.armPrice,n.offset<=0))return{fill:{price:n.armPrice,at:f(n.armPrice),level:n.armPrice},armed:l,peak:c};l&&s(o(d.price))>s(c)&&(c=o(d.price))}else if(l&&s(d.price)<s(p.price)){let m=a(c);if(s(d.price)<=s(m))return{fill:{price:m,at:f(m),level:m},armed:l,peak:c}}}return{armed:l,peak:c}}function Ds(t,e,n,r){let i=t.profit!==void 0?La(e,n*t.profit,r):void 0,s=t.loss!==void 0?La(e,-n*t.loss,r):void 0,a=(o,l,c)=>o===void 0?l:l===void 0||t._priceLegsWin?o:c(o,l);return{tp:a(t.limit,i,n===1?Math.min:Math.max),sl:a(t.stop,s,n===1?Math.max:Math.min)}}function mo(t,e,n,r){let i=t.trail_points!==void 0?La(e,n*t.trail_points,r):void 0;return t.trail_price===void 0?i:i===void 0||t._priceLegsWin?t.trail_price:n===1?Math.min(t.trail_price,i):Math.max(t.trail_price,i)}function kf(t,e,n){let r=e._intrabarEntry?.bar===t.idx?e._intrabarEntry:void 0;if(r){let i=r.type==="limit"!=(r.dir===1),s=Wn(n,r.level,i);if(s!==void 0)return{at:s,price:r.level}}return{at:0,price:n[0]}}function xE(t,e,n=!1){let r;for(let i of Af(t,e,n))(r===void 0||i.at<r)&&(r=i.at);return r}function Af(t,e,n){let r=t.strategy,i=Math.sign(r.position_size),s=[];if(i===0)return s;let a=t.pine?.syminfo?.mintick??.01,o=po(t);for(let l of r.pending_orders)if(!(l.status!=="pending"||(l.category??"entry")!=="exit"||l.bar>=t.idx))for(let c of r.opentrades){if(l.from_entry&&c.entry_id!==l.from_entry||c._exits_filled?.has(l.id))continue;let u=(f,m)=>{f!==void 0&&s.push({at:f,level:m,order:l,trade:c})},h=c._bracket_entry??c.entry_price,{tp:p,sl:d}=Ds(l,h,i,a);if(p!==void 0&&u(Wn(e,p+i*o,i===1),p),d!==void 0&&u(Wn(e,d,i!==1),d),n&&l.trail_offset!==void 0&&(l.trail_price!==void 0||l.trail_points!==void 0)){let f=mo(l,h,i,a),m=l._trailByTrade?.[c.id]??{armed:!1,peak:NaN},y=Ru(e,kf(t,c,e),{...m,armPrice:f,offset:l.trail_offset,dir:i,mintick:a,offGrid:Du(t)}).fill;y&&u(y.at,y.level)}}return s}function Lu(t,e){let n=t;e._placed=n._placeCount=(n._placeCount??0)+1,t.pending_orders.push(e)}function ul(t){return!!t.oca_name&&(t.oca_type==="cancel"||t.oca_type==="reduce")}function hl(t,e,n){let r=Ke(t.direction);if(t.type==="market")return 0;let i=t.type==="limit"?t.limit:t.stop;if(i===void 0)return;let s=t.type==="limit"?r===-1:r===1;return Wn(n,e??i,s)}function Fu(t,e,n,r){let i=n??Math.abs(e._base_qty??e.qty);for(let s of t.pending_orders)s===e||s.status!=="pending"||s.oca_name!==e.oca_name||s.oca_type!==e.oca_type||(e.oca_type==="cancel"?s.status="cancelled":r?.(s)||(s.category??"entry")==="exit"&&!(s.qty>0)||(s.qty=Math.max(0,s.qty-i),s._base_qty!==void 0&&(s._base_qty=Math.max(0,s._base_qty-i)),s.qty<=1e-9&&(s.status="cancelled")))}function vE(t){if(!t.strategy||t.strategy.position_size===0)return!1;let e=_.from(t.data.open).get(0),n=_.from(t.data.high).get(0),r=_.from(t.data.low).get(0),i=_.from(t.data.close).get(0),s=xE(t,jn(e,n,r,i));return s!==void 0&&s<1}function wE(t,e,n){if(Hr(e))return 0;let r=t.strategy,i=t.pine?.syminfo?.mintick??.01,s=po(t),a=1/0;for(let o of r.opentrades){if(e.from_entry&&o.entry_id!==e.from_entry)continue;let l=Math.sign(o.size),c=o._bracket_entry??o.entry_price,{tp:u,sl:h}=Ds(e,c,l,i);if(u!==void 0&&(a=Math.min(a,Wn(n,u+l*s,l===1)??1/0)),h!==void 0&&(a=Math.min(a,Wn(n,h,l!==1)??1/0)),e.trail_offset!==void 0&&(e.trail_price!==void 0||e.trail_points!==void 0)){let p=mo(e,c,l,i),d=e._trailByTrade?.[o.id]??{armed:!1,peak:NaN},f=Ru(n,{at:0,price:n[0]},{...d,armPrice:p,offset:e.trail_offset,dir:l,mintick:i,offGrid:Du(t)});f.fill&&(a=Math.min(a,f.fill.at))}}return a}function SE(t,e,n){if(Hr(e))return;let r=t.pine?.syminfo?.mintick??.01,i;for(let s of t.strategy.opentrades){if(e.from_entry&&s.entry_id!==e.from_entry)continue;let a=Math.sign(s.size),{tp:o,sl:l}=Ds(e,s._bracket_entry??s.entry_price,a,r);o!==void 0&&a*(n-o)>=0&&(i=Math.min(i??1/0,Math.abs(n-o))),l!==void 0&&a*(l-n)>=0&&(i=Math.min(i??1/0,Math.abs(n-l)))}return i}function EE(t){let e=t.strategy;if(!e||!e.pending_orders.some(i=>i._deferredPastExits===t.idx))return;let n=new Set(e.opentrades.map(i=>i.id));Tf(t,!0);let r=new Set(e.opentrades.filter(i=>!n.has(i.id)).map(i=>i.id));r.size>0&&Va(t,"intrabar",r)}function Tf(t,e=!1){if(!t.strategy)return;let n=t.strategy,{pending_orders:r}=n,i=_.from(t.data.open).get(0),s=_.from(t.data.high).get(0),a=_.from(t.data.low).get(0),o=_.from(t.data.close).get(0),l=_.from(t.data.openTime).get(0);Pi(t,i);let c=po(t),u=jn(i,s,a,o),h=y=>{if((y.category??"entry")==="exit"||y.status!=="pending"||y.bar>=t.idx||y.type==="market")return 0;let g=Ke(y.direction),w=y.type==="limit"?y.limit:y.stop;return w===void 0?0:Wn(u,w,y.type==="limit"?g===-1:g===1)??1/0},p=(y,g)=>g===0&&y.type==="market"&&(y.category??"entry")!=="exit"?Ke(y.direction)===1?0:1:0,d=y=>(y.category??"entry")==="exit"||y.type==="market"?0:y.type==="limit"?2:1,f=(y,g)=>{if(g!==0||y.type==="market"||(y.category??"entry")==="exit")return 0;let w=y.type==="limit"?y.limit:y.stop;return w===void 0?0:Math.abs(w-i)},m=r.map((y,g)=>({o:y,i:g,at:h(y)})).sort((y,g)=>y.at-g.at||d(y.o)-d(g.o)||f(y.o,y.at)-f(g.o,g.at)||p(y.o,y.at)-p(g.o,g.at)||y.i-g.i).map(y=>y.o);e||(n._preFillSize={idx:t.idx,size:n.position_size});for(let y of m){if(y.status!=="pending"||(y.category??"entry")==="exit"||e&&y._deferredPastExits!==t.idx||y.bar>=t.idx)continue;let g=!1,w=i;switch(y.type){case"market":g=!0,w=i;break;case"limit":if(y.limit!==void 0){let S=Ke(y.direction);S===1&&a<=y.limit-c?(g=!0,w=i<=y.limit-c?i:y.limit):S===-1&&s>=y.limit+c&&(g=!0,w=i>=y.limit+c?i:y.limit)}break;case"stop":if(y.stop!==void 0){let S=Ke(y.direction);S===1&&s>=y.stop?(g=!0,w=Math.max(i,y.stop)):S===-1&&a<=y.stop&&(g=!0,w=Math.min(i,y.stop))}break;case"stop-limit":if(y.stop!==void 0&&y.limit!==void 0){let S=Ke(y.direction),E;y._stopTriggered?E=i:(S===1?s>=y.stop:a<=y.stop)&&(y._stopTriggered=!0,E=S===1?Math.max(i,y.stop):Math.min(i,y.stop)),E!==void 0&&((S===1?E<=y.limit:E>=y.limit)?(g=!0,w=E):(S===1?a<=y.limit-c:s>=y.limit+c)&&(g=!0,w=y.limit))}break}e&&y._deferredFillPrice!==void 0&&(g=!0,w=y._deferredFillPrice,y._deferredFillPrice=void 0);let k=[];if(g&&!e&&(y.type==="limit"||y.type==="stop"||y.type==="stop-limit")){let S=Ke(y.direction),E=Math.sign(n.position_size);if(E!==0&&E!==S){let T=jn(i,s,a,o),N=Wn(T,w,y.type==="limit"?S===-1:S===1),$=N===void 0?[]:Af(t,T,!0),z=y.type==="limit"?y.limit:y.stop,H=I=>Math.abs(I.at-N)<=1e-9&&I.trade.entry_bar_index<t.idx,C=new Map;for(let I of $){if(!H(I))continue;let V=`${I.order._placed}:${I.trade.id}`;C.set(V,Math.max(C.get(V)??0,Math.abs(I.level-i)))}let ae=Math.abs(z-i);if($.some(I=>{if(I.at<N-1e-9)return!0;if(!H(I))return!1;let V=C.get(`${I.order._placed}:${I.trade.id}`);return N===0&&Math.abs(V-ae)>1e-9?V<ae:(I.order._placed??0)<(y._placed??0)})){y._deferredPastExits=t.idx,y._deferredFillPrice=w;continue}let te=new Set;for(let I of $){let V=`${I.order._placed}:${I.trade.id}`;H(I)&&!te.has(V)&&(te.add(V),k.push({order:I.order,trade:I.trade}))}}}if(g&&ul(y)){let S=jn(i,s,a,o),E=hl(y,w,S);if(r.some(T=>T!==y&&T.status==="pending"&&T.oca_name===y.oca_name&&T.oca_type===y.oca_type&&ul(T)&&(T.category??"entry")!=="exit"&&T.bar<t.idx&&(hl(T,void 0,S)??1/0)<(E??1/0)))continue}if(g){let S=k.map(({trade:E})=>Math.abs(E.size));if(tr(t,y.type==="market"?0:hl(y,w,u)??0),t._fillOnVertex=y.type==="market"||w===i,tc(t,y,w,l,i),t._fillOnVertex=void 0,y.status==="filled"&&k.forEach(({order:E,trade:T},N)=>{if(n.opentrades.includes(T)||!(S[N]>1e-9))return;let $={id:E.id,comment:E.comment,direction:-Math.sign(T.size),qty:S[N],type:E.stop!==void 0||E.loss!==void 0?"stop":"limit",bar:t.idx,time:l,status:"pending"};tc(t,$,w,l,i)}),y.status==="filled"&&ul(y)){let E=T=>T.type==="stop"&&T.stop!==void 0&&T.bar<t.idx&&(T.category??"entry")!=="exit"&&(Ke(T.direction)===1?i>=T.stop:i<=T.stop);Fu(n,y,void 0,E(y)?E:void 0)}if(y.status==="filled"&&y.type!=="market"&&w!==i){let E=y.type==="limit"||y.type==="stop-limit"&&w===y.limit?"limit":"stop";for(let T of n.opentrades)T.entry_id===y.id&&T.entry_bar_index===t.idx&&!T._intrabarEntry&&(T._intrabarEntry={bar:t.idx,level:w,type:E,dir:Ke(y.direction)})}}}n.pending_orders=r.filter(y=>y.status==="pending"),Pi(t,o),Rf(t)}function tc(t,e,n,r,i){let s=t.strategy;if(IE(t,e)){e.status="cancelled";return}if(e.category==="entry"&&Math.sign(s.position_size)===Ke(e.direction)&&Cf(s,Ke(e.direction))){e.status="cancelled";return}let a=Ke(e.direction);(e.type==="market"||e.type==="stop")&&(n=Mr(t,a,n));let o=s.risk_rules??{};if(e.category==="entry"){let c=s.position_size,u=o.allow_entry_in==="long"?1:o.allow_entry_in==="short"?-1:0;if(u!==0&&a!==u){if(Math.sign(c)===u){er(t,Math.abs(c),n,r,{exitId:e.id,exitComment:e.comment}),e.status="filled",e.fill_price=n,e.fill_bar=t.idx,e.fill_time=r,Wr(t,n);return}let h=e._isReversalEntry&&e._base_qty!==void 0?e.qty-e._base_qty:0;if(c!==0||!(h>1e-9)){e.status="cancelled";return}e.qty=h,e._base_qty=h}if(o.max_position_size!==void 0){let h=Number(o.max_position_size),p=c!==0&&Math.sign(c)!==a,d=p?Math.abs(c):0,f=p?0:Math.abs(c),m=Math.max(0,e.qty-d),y=Nr(t,Math.max(0,h-f));if(m>y+1e-9){if(y<=0&&d===0){e.status="cancelled";return}e.qty=d+y,e._base_qty!==void 0&&(e._base_qty=y)}}}let l=a===1?s.config.margin_long??100:s.config.margin_short??100;{let c=s.position_size,u=Math.sign(c),h=u!==0&&u!==a,p=s._preFillSize,d=p&&p.idx===t.idx?p.size:c,f=h&&Math.sign(d)===u,m=f?Math.max(0,e.qty-Math.abs(c)):e.qty;if(m>0&&l>0&&!e._risk){let y=t.pine?.syminfo?.pointvalue??1,g=(t._pathAt??0)>0&&(t._pathAt??0)<3,w=s._placement,k=e.type==="market"&&t._pathAt===0&&w?.idx===t.idx?w:void 0,S=0;u===a&&(S=bE(t,g?n:k?k.price:i));let E=(k?k.equity:g&&c!==0?Zr(t,n):s.equity)-S,T=c===0&&e._isReversalEntry&&!e._reversesPending&&e.type!=="market"&&e._base_qty!==void 0,N=T?Math.min(e._base_qty,m):m,$=Si(N,n,l,y),z=e._base_qty,H=Math.min(z,e.qty-z),C=te=>Si(te,n,l,y)<=E,ae=$>E&&e._reversesPending&&c===0&&H>0&&!C(e.qty-H)&&C(H);if(ae&&(e.qty=H),$>E&&T&&e.qty-z>1e-9)e.qty-=z;else if($>E&&!ae){let te=Math.min(Math.abs(c),e.qty),I=k&&Si(m,k.price,l,y)<=E;f&&te>0&&!I?(er(t,te,n,r,{exitId:e.id,exitComment:e.comment}),e.status="filled",e.fill_price=n,e.fill_bar=t.idx,e.fill_time=r,Wr(t,n)):e.status="cancelled";return}}}DE(t,e,n,r),e.status="filled",e.fill_price=n,e.fill_bar=t.idx,e.fill_time=r,Wr(t,n)}function kE(t){let e=t.strategy;if(!e||e.pending_orders.length===0)return;let n=e.config.process_orders_on_close===!0,r=_.from(t.data.close).get(0),i=_.from(t.data.openTime).get(0);tr(t,3);let s=a=>a.category==="exit"&&a.type==="market"&&a.profit===void 0&&a.loss===void 0&&a.limit===void 0&&a.stop===void 0&&a.trail_price===void 0&&a.trail_points===void 0;for(let[a,o]of e.pending_orders.entries())if(!(o.status!=="pending"||o.bar!==t.idx))if(s(o)){if(!n&&!o.immediately)continue;let l=e.opentrades.filter(p=>!o.from_entry||p.entry_id===o.from_entry);if(o._intended_trade_ids){let p=new Set(o._intended_trade_ids);l=l.filter(d=>p.has(d.id))}if(l.length===0){o.status="cancelled";continue}if(!n){let p=Math.sign(l[0].size);if(e.pending_orders.slice(0,a).some(d=>d.status==="pending"&&d.bar===t.idx&&(d.category??"entry")==="entry"&&d.type==="market"&&Ke(d.direction)===-p)){o.status="cancelled";continue}}let c=l.reduce((p,d)=>p+Math.abs(d.size),0),u=c;o.qty&&o.qty>0?u=Math.min(o.qty,c):o.qty_percent&&o.qty_percent>0&&(u=fo(t,c,o.qty_percent));let h=Mr(t,-Math.sign(l[0].size),r);Ba(t,o.from_entry,u,h,i,{exitId:o.id,exitComment:o.comment}),o.status="filled",o.fill_price=h,o.fill_bar=t.idx,o.fill_time=i,Wr(t,h)}else n&&(o.category??"entry")==="entry"&&o.type==="market"||n&&(o.category??"entry")!=="exit"&&AE(o,r)?(Pi(t,r),tc(t,o,r,i,r)):n&&(o.category??"entry")==="exit"&&TE(t,o,r,i);e.pending_orders=e.pending_orders.filter(a=>a.status==="pending"),Pi(t,r),Rf(t)}function AE(t,e){let n=Ke(t.direction),r=t.limit===void 0||(n===1?e<=t.limit:e>=t.limit),i=t.stop===void 0||(n===1?e>=t.stop:e<=t.stop);return(t.type==="limit"||t.type==="stop"||t.type==="stop-limit")&&r&&i}function TE(t,e,n,r){let i=t.strategy,s=t.pine?.syminfo?.mintick??.01,a=i.opentrades.filter(p=>!e.from_entry||p.entry_id===e.from_entry);if(a.length===0)return;let o=Math.sign(a[0].size),l=Of(t,e,a),c=l.total,u=!1;for(let p of a){if(c<=1e-9)break;if(p._exits_filled?.has(e.id)||!((l.perTrade.get(p)??0)>1e-9))continue;let d=p._bracket_entry??p.entry_price,{tp:f,sl:m}=Ds(e,d,o,s),y=m!==void 0&&(o===1?n<=m:n>=m),g=!y&&f!==void 0&&(o===1?n>=f:n<=f);if(!y&&!g)continue;let w=Math.min(l.perTrade.get(p)??0,c),k=y?"loss":"profit",S=k==="loss"?Mr(t,-o,n):n,E=k==="profit"?e.comment_profit??e.comment:e.comment_loss??e.comment;Ba(t,e.from_entry,w,S,r,{triggerKind:k,exitId:e.id,exitComment:E},p.id),e.oca_name&&e.oca_type==="reduce"&&Fu(i,e,w),(p._exits_filled??(p._exits_filled=new Set)).add(e.id),c-=w,u=!0,Wr(t,S)}let h=i.opentrades.some(p=>(!e.from_entry||p.entry_id===e.from_entry)&&!p._exits_filled?.has(e.id));u&&(!h||c<=1e-9)&&(e.status="filled",e.fill_bar=t.idx,e.fill_time=r)}function Ke(t){return typeof t=="number"?t:t==="long"?1:t==="short"?-1:0}function nc(t,e,n,r){let i=e.config.commission_type??"percent",s=e.config.commission_value??0;if(!s||s===0)return 0;let a=t.pine?.syminfo?.pointvalue??1;switch(i){case"percent":return Math.abs(n)*r*a*(s/100);case"cash_per_contract":return Math.abs(n)*s;case"cash_per_order":return s;default:return 0}}function Mr(t,e,n){let r=t.strategy.config.slippage??0;if(!r||r===0)return n;let i=t.pine?.syminfo?.mintick??.01,s=r*i;return e===1?n+s:n-s}function Nf(t,e,n=0,r=NaN,i=!0){let s=t._openFills,a=()=>{let o=_.from(e.data.open).get(0),l=(t.config.slippage??0)*(e.pine?.syminfo?.mintick??.01);return Math.abs(r-o)<=l+1e-9*Math.abs(o)};if(s&&i&&e&&s.idx===e.idx&&e._pathAt===0&&a()){n>0?s.buys+=n:s.sells+=n,s.real.push(t.position_size);return}la(t,t.position_size)}function la(t,e){let n=Math.abs(e);n>t.max_contracts_held_all&&(t.max_contracts_held_all=n),e>t.max_contracts_held_long&&(t.max_contracts_held_long=e),-e>t.max_contracts_held_short&&(t.max_contracts_held_short=-e)}function NE(t){let e=t._openFills;if(t._openFills=void 0,!e||e.real.length===0)return;let n=e.start+e.buys,r=e.start+e.buys+e.sells,i=Math.sign(Math.abs(n)<1e-9?0:n);if(i===0||i===Math.sign(e.start)||i===Math.sign(Math.abs(r)<1e-9?0:r))la(t,n),la(t,Math.abs(r)<1e-9?0:r);else for(let s of e.real)la(t,s)}function Cf(t,e){let n=t.config.pyramiding??1,r=0;for(let i of t.opentrades)Math.sign(i.size)===e&&r++;return r>=n}var Mi={orders:"Close Position (Max number of filled orders in one day)",drawdown:"Close Position (Max Drawdown)",intraday:"Close Position (Max intraday Loss)",consDays:"Close Position (Max consecutive loss days)"};function Bi(t){let e=t.strategy;return e._risk??(e._risk={dayStartEquity:e.initial_capital,dayMaxEquity:e.initial_capital,dayFills:0,prevDayEndEquity:e.initial_capital,consLossDays:0,realizedPeak:e.initial_capital})}var Np=new Map;function CE(t){let e=_.from(t.data.openTime).get(0),n=_.from(t.data.closeTime).get(0);if(Number.isFinite(n)&&n-e>=86399e3)return String(e);let r=t.pine?.syminfo?.timezone||"UTC",i=Np.get(r);if(!i){try{i=new Intl.DateTimeFormat("en-CA",{timeZone:r,year:"numeric",month:"2-digit",day:"2-digit"})}catch{i=new Intl.DateTimeFormat("en-CA",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit"})}Np.set(r,i)}return i.format(new Date(e))}function IE(t,e){let n=t.strategy._risk;return n?n.haltedFrom!==void 0&&e.bar>=n.haltedFrom?!0:n.blockFrom!==void 0&&e.bar>=n.blockFrom&&e.bar<=(n.blockTo??1/0):!1}function Fa(t,e,n,r){let i=t.strategy,s=Bi(t),a=_.from(t.data.openTime).get(0);t._pathAt===0&&!s._closingOut&&(s._closingOut=!0,Va(t,"market"),s._closingOut=!1,tr(t,0)),i.opentrades.length>0&&i.position_size!==0&&er(t,Math.abs(i.position_size),n,a,{exitId:e,exitComment:e,forced:!0});for(let o of i.pending_orders)o.status==="pending"&&(o.status="cancelled");r==="day"?(s.blockedDay=s.day,s.blockFrom=t.idx,s.blockTo=void 0):s.haltedFrom=t.idx}function ME(t){let e=t.strategy,n=e?.risk_rules;if(!n||Object.keys(n).length===0)return;let r=Bi(t),i=CE(t);if(i!==r.day){if(r.blockFrom!==void 0&&r.blockTo===void 0&&(r.blockTo=t.idx-1),r.day!==void 0){let s=e.equity;n.max_cons_loss_days&&r.haltedFrom===void 0&&(r.consLossDays=s<r.prevDayEndEquity-1e-9?r.consLossDays+1:0,r.consLossDays>=n.max_cons_loss_days.count&&(e.position_size!==0&&e.pending_orders.push({id:Mi.consDays,direction:-Math.sign(e.position_size),qty:Math.abs(e.position_size),type:"market",bar:t.idx-1,time:_.from(t.data.openTime).get(0),status:"pending",comment:Mi.consDays,_risk:!0}),r.haltedFrom=t.idx)),r.prevDayEndEquity=s}r.day=i,r.dayStartEquity=e.equity,r.dayMaxEquity=e.equity,r.dayFills=0,r.dayStartBar=t.idx}}function If(t){let e=t.strategy._risk;if(!e||e.dayStartBar!==t.idx||!(t._pathAt===void 0||t._pathAt===0))return!1;let n=t._excSeg;return n&&n.scale>0?!1:(e.dayStartEquity=e.dayMaxEquity=Zr(t,_.from(t.data.open).get(0)),!0)}function Wr(t,e){let n=t.strategy;n&&(n._fillCount=(n._fillCount??0)+1);let r=n?._fillPnl??0;n&&(n._fillPnl=0);let i=n?.risk_rules;if(!i||Object.keys(i).length===0)return;let s=Bi(t);if(s.haltedFrom!==void 0||s._closingOut)return;s.dayFills++;let a=n.initial_capital+n.netprofit;if(s.realizedPeak=Math.max(s.realizedPeak,a),i.max_drawdown&&s.haltedFrom===void 0){let o=s.realizedPeak-a,l=Number(i.max_drawdown.value);if(i.max_drawdown.type==="percent_of_equity"?100*o/s.realizedPeak>=l-1e-12:o>=l-1e-9)return Fa(t,Mi.drawdown,e,"forever")}if(i.max_intraday_filled_orders&&s.dayFills>=Number(i.max_intraday_filled_orders.count))return Fa(t,Mi.orders,e,"day");i.max_intraday_loss&&!If(t)&&Mf(t,e,r)}function Mf(t,e,n=0){let r=t.strategy,i=r.risk_rules.max_intraday_loss;if(!i)return!1;let s=Bi(t);if(s.blockedDay===s.day)return!1;let a=r.position_size!==0?Zr(t,e):r.initial_capital+r.netprofit;s.dayMaxEquity=Math.max(s.dayMaxEquity,a);let o=s.dayStartEquity-(a-n),l=Number(i.value),c=i.type==="percent_of_equity"?l/100*s.dayMaxEquity:l;return o>=c-1e-9?(Fa(t,Mi.intraday,e,"day"),!0):!1}function PE(t,e){let n=t.strategy.risk_rules?.max_drawdown;if(!n)return;let r=Bi(t);if(r.haltedFrom!==void 0)return;let i=r.realizedPeak-Zr(t,e),s=Number(n.value);(n.type==="percent_of_equity"?100*i/r.realizedPeak>=s-1e-12:i>=s-1e-9)&&(r._drawdownAtClose=t.idx)}function Cp(t){let e=t.strategy?._risk;!e||e._drawdownAtClose!==t.idx||(e._drawdownAtClose=void 0,tr(t,3),Fa(t,Mi.drawdown,_.from(t.data.close).get(0),"forever"))}function Ip(t){let e=t.strategy;if(!e?.risk_rules?.max_intraday_loss||e.position_size===0)return;let n=Bi(t);if(n.haltedFrom!==void 0&&n.haltedFrom<=t.idx)return;let r=Math.sign(e.position_size),i=_.from(t.data[r===1?"high":"low"]).get(0);n.dayMaxEquity=Math.max(n.dayMaxEquity,Zr(t,i));let s=_.from(t.data[r===1?"low":"high"]).get(0),a=jn(_.from(t.data.open).get(0),_.from(t.data.high).get(0),_.from(t.data.low).get(0),_.from(t.data.close).get(0));tr(t,a[1]===s?1:2),Mf(t,s)}function Ks(t,e,n,r,i,s,a,o){let l=t.strategy,c=l.opentrades.length+l.closedtrades.length,u=o!==void 0,h=l.config.commission_type??"percent",p=u&&h==="cash_per_order",d=nc(t,l,r,i),f=p?d*o:d,m={id:`trade_${c}`,entry_id:e,entry_comment:a??e,entry_price:i,_bracket_entry:i,entry_bar_index:t.idx,entry_time:s,size:n*r,commission:f,max_drawdown:0,max_runup:0,status:"open"};m._entry_qty=Math.abs(m.size),l.opentrades.push(m),l._first_entry_price===void 0&&(l._first_entry_price=i);let y={entry_id:e,entry_price:i,entry_time:s,entry_bar_index:t.idx,entry_comment:m.entry_comment,qty:r,commission:f};(l._ledger_entries??(l._ledger_entries=[])).push(y),f>0&&(l.netprofit-=f,l.grossloss+=f);let g=t._pathAt??0,w=l._marginFrom;g>0&&!(w?.idx===t.idx&&w.at>=g)&&(l._marginFrom={idx:t.idx,at:g}),y._dir=n,Mp(t,m,n),Mp(t,y,n);let k=t.pine?.syminfo?.pointvalue??1,S=_s(m._fav,m._adv,r,k,f);m.max_runup=S.runup,m.max_drawdown=S.drawdown,Pf(t,{price:i,np:-f,add:{ref:y,dir:n,qty:r,entry:i,comm:f}});let E=l.position_size,T=E+m.size;if(E===0)l.position_size=T,l.position_avg_price=i,l.position_entry_name=e;else if(Math.sign(E)===Math.sign(T)){let N=Math.abs(E)*l.position_avg_price+r*i,$=Math.abs(T);l.position_avg_price=N/$,l.position_size=T}Nf(l,t,m.size,i)}function DE(t,e,n,r){let i=t.strategy,s=Ke(e.direction),a=i.position_size,o=Math.sign(a);if(o===1&&s===-1||o===-1&&s===1){let l=Math.min(Math.abs(a),e.qty),c=e.qty-l,u=c>0;if(er(t,l,n,r,{exitId:e.id,exitComment:e.comment,isImplicitReversal:u,reversalShare:l/e.qty}),c>0){for(let p of i.pending_orders)p.status==="pending"&&(p.category??"entry")==="exit"&&!p.from_entry&&p._placedWithPosition&&p._placedDir===o&&(p.status="cancelled");let h=e._base_qty;h!==void 0&&c>h+1e-9?(Ks(t,e.id,s,h,n,r,e.comment,h/e.qty),Ks(t,e.id,s,c-h,n,r,e.comment,(c-h)/e.qty)):Ks(t,e.id,s,c,n,r,e.comment,c/e.qty)}}else Ks(t,e.id,s,e.qty,n,r,e.comment)}function OE(t,e,n){let r=[],i=n,s=t._ledger_entries??[],a=String(t.config.close_entries_rule??"FIFO").toUpperCase()==="ANY";for(let o of s){if(i<=1e-9)break;if(a&&o.entry_id!==e.entry_id||o.qty<=1e-9)continue;let l=Math.min(o.qty,i),c=o.qty>0?o.commission*(l/o.qty):0;r.push({rec:o,entry_id:o.entry_id,qty:l,entry_price:o.entry_price,entry_time:o.entry_time,entry_bar_index:o.entry_bar_index,entry_comment:o.entry_comment,commission:c}),o.qty-=l,o.commission-=c,i-=l}if(t._ledger_entries=s.filter(o=>o.qty>1e-9),i>1e-9){let o=Math.abs(e.size);r.push({entry_id:e.entry_id,qty:i,entry_price:e.entry_price,entry_time:e.entry_time,entry_bar_index:e.entry_bar_index,entry_comment:e.entry_comment,commission:o>0?(e.commission??0)*(i/o):0})}return r}function pl(t,e,n){let r=e.profit??0;r>0?(t.grossprofit+=n*r,t.wintrades+=n,t.wintrades_total_profit+=n*r):r<0?(t.grossloss+=n*Math.abs(r),t.losstrades+=n,t.losstrades_total_loss+=n*Math.abs(r)):t.eventrades+=n}function er(t,e,n,r,i){let s=t.strategy,a=t.pine?.syminfo?.pointvalue??1,o=e,l=s.netprofit,c=[...s.opentrades];s.opentrades=[];let u=null;for(let f of c){if(o<=0){s.opentrades.push(f);continue}let m=Math.abs(f.size),y=Math.min(m,o),g=Math.sign(f.size),w=k=>{let S=(s.config.commission_type??"percent")==="cash_per_order",E=i?.isImplicitReversal&&S,T=S?nc(t,s,e,n)*(e>0?k/e:1):nc(t,s,k,n),N=E?T*(i?.reversalShare??.5):T,$=OE(s,f,k);for(let z of $){let H=N*(z.qty/k),C=(g===1?n-z.entry_price:z.entry_price-n)*z.qty*a,ae=FE(t,z.rec??f,g,n,i?.exitId),te=_s(ae.fav,ae.adv,z.qty,a,z.commission);Pf(t,{price:n,np:C-H,remove:{ref:z.rec??f,qty:z.qty,comm:z.commission}});let I={id:`trade_${s.opentrades.length+s.closedtrades.length+c.length}`,entry_id:z.entry_id,entry_comment:z.entry_comment,entry_price:z.entry_price,_bracket_entry:f._bracket_entry,entry_bar_index:z.entry_bar_index,entry_time:z.entry_time,size:g*z.qty,commission:z.commission+H,_entry_commission:z.commission,max_drawdown:te.drawdown,max_runup:te.runup,status:"closed",exit_price:n,exit_bar_index:t.idx,exit_time:r,exit_id:i?.exitId??f.exit_id,exit_comment:i?.exitComment??f.exit_comment,profit:C-z.commission-H};if(s.netprofit+=C-H,s.grossloss-=z.commission,z.rec&&u?.rec===z.rec){let V=u.row;pl(s,V,-1),V.size=V.size+I.size,V.commission=(V.commission??0)+(I.commission??0),V.profit=(V.profit??0)+(I.profit??0),V._entry_commission=(V._entry_commission??0)+z.commission;let ee=_s(ae.fav,ae.adv,Math.abs(V.size),a,V._entry_commission??0);V.max_runup=ee.runup,V.max_drawdown=ee.drawdown,pl(s,V,1);continue}pl(s,I,1),s.closedtrades.push(I),u={rec:z.rec,row:I}}};if(y>=m-1e-9)f.status="closed",f.exit_price=n,f.exit_bar_index=t.idx,f.exit_time=r,w(m),o-=y;else{w(y);let k=(f.commission??0)*(y/m);f.size=g*(m-y),f.commission=(f.commission??0)-k,s.opentrades.push(f),o=0}}let h=s.position_size,p=Math.sign(h)*e,d=h-p;if(Math.abs(d)<1e-9&&(d=0),s.position_size=d,Nf(s,t,d-h,n,!i?.forced),i?.isImplicitReversal&&(s._fillPnl=(s._fillPnl??0)+(s.netprofit-l)),d===0)s.position_avg_price=NaN,s.position_entry_name="";else if(s.opentrades.length>0){let f=0,m=0;for(let y of Bu(s))f+=y.qty*y.entry_price,m+=y.qty;s.position_avg_price=f/m,s.position_entry_name=s._ledger_entries?.[0]?.entry_id??s.opentrades[0].entry_id}}function Bu(t){let e=t._ledger_entries??[],n=Math.sign(t.position_size)||1;return e.length>0?e.map(r=>({qty:r.qty,entry_price:r.entry_price,commission:r.commission,dir:n})):t.opentrades.map(r=>({qty:Math.abs(r.size),entry_price:r.entry_price,commission:r.commission??0,dir:Math.sign(r.size)}))}function RE(t){let e=t.strategy;if(!e)return[];let n=e._ledger_entries??[];if(n.length===0)return e.opentrades.slice();let r=t.pine?.syminfo?.pointvalue??1,i=Math.sign(e.position_size)||1;return n.map((s,a)=>{let o=_s(s._fav,s._adv,s.qty,r,s.commission);return{id:`open_${a}`,entry_id:s.entry_id,entry_comment:s.entry_comment,entry_price:s.entry_price,entry_bar_index:s.entry_bar_index,entry_time:s.entry_time,size:(s._dir??i)*s.qty,commission:s.commission,max_runup:o.runup,max_drawdown:o.drawdown,status:"open"}})}function Pi(t,e){let n=t.strategy,r=t.pine?.syminfo?.pointvalue??1,i=0;for(let s of Bu(n)){let a=s.dir===1?e-s.entry_price:s.entry_price-e;i+=a*s.qty*r}n.openprofit=i,n.equity=n.initial_capital+n.netprofit+i}function tr(t,e){let n=t._excSeg;t._pathAt=n?n.offset+e*n.scale:e}function Vu(t,e,n){let r=e*(n-t.entry_price);r<=t._fav||(t._fav=r),-r<=t._adv||(t._adv=-r)}function rc(t,e,n,r,i,s){let a=t._exc?.path;if(a)for(let o=0;o<a.length;o++)o>r+1e-9&&(s?o<=i+1e-9:o<i-1e-9)&&Vu(e,n,a[o])}function _s(t,e,n,r,i){if(!(n>0))return{runup:0,drawdown:0};let s=t===void 0?0:Math.max(0,t*n*r-i),a=e===void 0?0:Math.max(0,e*n*r+i);return{runup:s,drawdown:a}}function LE(t){let e=t._ledger_entries??[],n=Math.sign(t.position_size)||1;return e.length>0?e.map(r=>({ref:r,dir:r._dir??n,qty:r.qty,entry:r.entry_price,comm:r.commission})):t.opentrades.map(r=>({ref:r,dir:Math.sign(r.size),qty:Math.abs(r.size),entry:r.entry_price,comm:r.commission??0}))}function Pf(t,e){var n;let r=t._exc;if(!r||r.bar!==t.idx)return;if(r.finalized){((n=t.strategy)._excPreTicks??(n._excPreTicks=[])).push(e.price);return}let i=t._pathAt??0,s=e.remove?.ref;s?._openBar===t.idx&&Number.isFinite(s._openAt)&&(i=Math.max(i,s._openAt)),r.events.push({at:i,seq:r.events.length,...e})}function Df(t){let e=t.strategy;if(!e)return;let n=jn(_.from(t.data.open).get(0),_.from(t.data.high).get(0),_.from(t.data.low).get(0),_.from(t.data.close).get(0)),r=e;t._exc={bar:t.idx,path:n,events:[],start:{netprofit:e.netprofit,lots:LE(e)},pre:r._excPreTicks??[]},r._excPreTicks=[],t._pathAt=void 0,t._excSeg=void 0;for(let i of e.opentrades)i._obsFrom=-.5;for(let i of r._ledger_entries??[])i._obsFrom=-.5}function Mp(t,e,n){let r=t._pathAt??0;e._fav=void 0,e._adv=void 0,e._openBar=t.idx,e._openAt=r,e._obsFrom=r;let i=t._exc?.bar===t.idx?t._exc.path:void 0,s=t._fillOnVertex??(r===0||r===3);i&&s&&Number.isInteger(r)&&r>=0&&r<i.length&&Vu(e,n,i[r])}function FE(t,e,n,r,i){let s=t._pathAt??3;e._openBar===t.idx&&Number.isFinite(e._openAt)&&(s=Math.max(s,e._openAt));let a={entry_price:e.entry_price,_fav:e._fav,_adv:e._adv};return e._openBar===t.idx&&Math.abs((e._openAt??NaN)-s)<1e-9&&i!==$u?{}:(t._exc?.bar===t.idx&&rc(t,a,n,e._obsFrom??-.5,s,!1),Vu(a,n,r),{fav:a._fav,adv:a._adv})}function BE(t){let e=t.strategy,n=t.pine?.syminfo?.pointvalue??1,r=t._exc,i=r?.bar===t.idx&&!r.finalized;for(let s of e.opentrades){let a=Math.sign(s.size);i&&rc(t,s,a,s._obsFrom??-.5,3,!0),s._obsFrom=3;let o=_s(s._fav,s._adv,Math.abs(s.size),n,s.commission??0);s.max_runup=o.runup,s.max_drawdown=o.drawdown}for(let s of e._ledger_entries??[])i&&rc(t,s,s._dir??Math.sign(e.position_size),s._obsFrom??-.5,3,!0),s._obsFrom=3}function VE(t){let e=t.strategy,n=t._exc;if(!n||n.bar!==t.idx||n.finalized)return;let r=t.pine?.syminfo?.pointvalue??1,i=e,s=new Map;for(let u of n.start.lots)s.set(u.ref,{dir:u.dir,qty:u.qty,entry:u.entry,comm:u.comm});let a=n.start.netprofit,o=u=>{let h=0,p=0;for(let g of s.values())h+=(u-g.entry)*g.dir*g.qty*r,p+=g.comm;let d=e.initial_capital+a+h,f=e.initial_capital+a+p;i.equity_peak=Math.max(i.equity_peak,Math.min(f,d+p)),i.equity_trough=Math.min(i.equity_trough,Math.max(f-p,d));let m=i.equity_peak-d,y=d-i.equity_trough;m>i.max_drawdown&&(i.max_drawdown=m),y>i.max_runup&&(i.max_runup=y),i.equity_peak>0&&(i.max_drawdown_percent_value=Math.max(i.max_drawdown_percent_value,100*m/i.equity_peak)),d>0&&(i.max_runup_percent_value=Math.max(i.max_runup_percent_value,100*y/d))},l=u=>{if(u.add){let h=s.get(u.add.ref);h?(h.entry=(h.entry*h.qty+u.add.entry*u.add.qty)/(h.qty+u.add.qty),h.qty+=u.add.qty,h.comm+=u.add.comm):s.set(u.add.ref,{dir:u.add.dir,qty:u.add.qty,entry:u.add.entry,comm:u.add.comm})}if(u.remove){let h=s.get(u.remove.ref);h&&(h.qty-=u.remove.qty,h.comm-=u.remove.comm,h.qty<=1e-12&&s.delete(u.remove.ref))}a+=u.np};for(let u of n.pre)o(u);let c=[...n.path.map((u,h)=>({at:h,price:u,vertex:!0,seq:-1})),...n.events.map(u=>({...u,vertex:!1}))].sort((u,h)=>u.at-h.at||Number(u.vertex)-Number(h.vertex)||u.seq-h.seq);for(let u of c)u.vertex||l(u),o(u.price)}function Ba(t,e,n,r,i,s,a){let o=t.strategy,l=new Map(o.opentrades.map((f,m)=>[f,m])),c=()=>o.opentrades.sort((f,m)=>(l.get(f)??1/0)-(l.get(m)??1/0));if(a!==void 0){let f=[],m=[];for(let g of o.opentrades)g.id===a?f.push(g):m.push(g);if(f.length===0)return;let y=Math.abs(f[0].size);o.opentrades=[...f,...m],er(t,Math.min(n,y),r,i,s),c();return}if(!e||e===""){er(t,n,r,i,s);return}let u=[],h=[];for(let f of o.opentrades)f.entry_id===e?u.push(f):h.push(f);let p=u.reduce((f,m)=>f+Math.abs(m.size),0);if(p===0)return;let d=Math.min(n,p);o.opentrades=[...u,...h],er(t,d,r,i,s),c()}function $E(t,e,n,r,i,s){let{open:a,high:o,low:l,close:c}=i,u=Math.abs(o-a)<=Math.abs(a-l)?[a,o,l,c]:[a,l,o,c],h=t.type==="limit"==(t.dir===1),p=t.level,d=-1;for(let m=0;m<3;m++){let y=u[m],g=u[m+1];if(h?y>=p&&g<=p:y<=p&&g>=p){d=m;break}}if(d<0)return;if(e!==void 0&&(r?p>=e:p<=e))return{kind:"profit",price:p};if(n!==void 0&&(r?p<=n:p>=n))return{kind:"loss",price:p};let f=[p,...u.slice(d+1)];for(let m=0;m+1<f.length;m++){let y=f[m],g=f[m+1];if(g>y){if(r&&e!==void 0&&g>=e+s)return{kind:"profit",price:e};if(!r&&n!==void 0&&g>=n)return{kind:"loss",price:n}}else if(g<y){if(r&&n!==void 0&&g<=n)return{kind:"loss",price:n};if(!r&&e!==void 0&&g<=e-s)return{kind:"profit",price:e}}}return null}function Of(t,e,n){let r=t.strategy,i=(c,u)=>{let h=new Map,p=c.qty&&c.qty>0?c.qty:1/0;for(let d of u){let f=c.qty_percent&&c.qty_percent>0&&!(c.qty&&c.qty>0)?fo(t,d._entry_qty??Math.abs(d.size),c.qty_percent):p,m=Math.min(f,Math.abs(d.size));h.set(d,m),c.qty&&c.qty>0&&(p-=m)}return h},s=new Map(n.map(c=>[c,Math.abs(c.size)])),a=r.pending_orders.filter(c=>c!==e&&c.status==="pending"&&(c.category??"entry")==="exit"&&!Hr(c)&&(c._seq??1/0)<(e._seq??1/0)).sort((c,u)=>(c._seq??0)-(u._seq??0));for(let c of a){let u=n.filter(h=>(!c.from_entry||h.entry_id===c.from_entry)&&!h._exits_filled?.has(c.id));for(let[h,p]of i(c,u))s.set(h,Math.max(0,(s.get(h)??0)-p))}let o=new Map,l=0;for(let[c,u]of i(e,n)){let h=Math.min(u,s.get(c)??0);o.set(c,h),l+=h}return{total:l,perTrade:o}}function Hr(t){return(t.category??"entry")==="exit"&&t.type==="market"&&t.profit===void 0&&t.loss===void 0&&t.limit===void 0&&t.stop===void 0&&t.trail_price===void 0&&t.trail_points===void 0}function Va(t,e="intrabar",n){if(!t.strategy)return;let r=t.strategy;if(r.pending_orders.length===0)return;let i=_.from(t.data.open).get(0),s=_.from(t.data.high).get(0),a=_.from(t.data.low).get(0),o=_.from(t.data.close).get(0),l=_.from(t.data.openTime).get(0),c=t.pine?.syminfo?.mintick??.01,u=!1,h=po(t),p=jn(_.from(t.data.open).get(0),_.from(t.data.high).get(0),_.from(t.data.low).get(0),_.from(t.data.close).get(0)),d=r.pending_orders.map((g,w)=>({o:g,i:w,at:e==="intrabar"&&(g.category??"entry")==="exit"?wE(t,g,p):0})).sort((g,w)=>g.at-w.at||g.i-w.i),f=d.map((g,w)=>({x:g,slot:w,d:g.at===0&&(g.o.category??"entry")==="exit"?SE(t,g.o,i):void 0})).filter(g=>g.d!==void 0),m=f.map(g=>g.slot);f.sort((g,w)=>g.d-w.d||g.slot-w.slot).forEach((g,w)=>d[m[w]]=g.x);let y=d.map(g=>g.o);for(let g of y){if(g.status!=="pending"||(g.category??"entry")!=="exit"||e==="market"&&!Hr(g))continue;let w=r.opentrades.filter(L=>!g.from_entry||L.entry_id===g.from_entry);if(g._intended_trade_ids){let L=new Set(g._intended_trade_ids);w=w.filter(le=>L.has(le.id))}if(w.length===0){e==="intrabar"&&(g.from_entry&&r.pending_orders.some(L=>L.status==="pending"&&(L.category??"entry")==="entry"&&L.id===g.from_entry)||(g.status="cancelled"));continue}if(n&&(Hr(g)||(w=w.filter(L=>n.has(L.id)),w.length===0)))continue;let k=w.reduce((L,le)=>L+Math.abs(le.size),0),S=Math.sign(w[0].size);if(Hr(g)){if(e==="open"||g.bar>=t.idx)continue;if(e==="market"){if(g.immediately)continue;let $e=r.pending_orders.indexOf(g);if(r.pending_orders.slice(0,$e).some(Ee=>Ee.status==="pending"&&(Ee.category??"entry")==="entry"&&Ee.type==="market"&&Ee.bar<t.idx))continue}let L=g.immediately?o:i;L=Mr(t,-S,L),tr(t,g.immediately?3:0);let le=k;g.qty&&g.qty>0?le=Math.min(g.qty,k):g.qty_percent&&g.qty_percent>0&&(le=fo(t,k,g.qty_percent)),Ba(t,g.from_entry,le,L,l,{exitId:g.id,exitComment:g.comment}),g.status="filled",g.fill_price=L,g.fill_bar=t.idx,g.fill_time=l,Wr(t,L);continue}if(w=w.filter(L=>!L._exits_filled?.has(g.id)),w.length===0){e==="intrabar"&&(g.status="cancelled");continue}k=w.reduce((L,le)=>L+Math.abs(le.size),0);let E=new Map(w.map(L=>[L,Math.abs(L.size)])),T=0;for(let L of w)T+=Math.abs(L.size)*L.entry_price;let N=S===1,$=Math.abs(s-i)<=Math.abs(i-a),z=N?$:!$,H=[],C=[],ae=r._mc_exit_lock,te=ae&&ae.bar===t.idx,I=Of(t,g,w);for(let L of w){if(te&&L.id!==ae.tradeId)continue;let le=L._bracket_entry??L.entry_price,$e=I.perTrade.get(L)??0;if(!($e>1e-9))continue;let{tp:Ee,sl:O}=Ds(g,le,N?1:-1,c),ve=e==="intrabar"&&L._intrabarEntry?.bar===t.idx?L._intrabarEntry:void 0;if(ve&&!te){let en=$E(ve,Ee,O,N,{open:i,high:s,low:a,close:o},h);if(en!==void 0){en&&(en.kind==="profit"?H:C).push({qty:$e,price:en.price,kind:en.kind,tradeId:L.id});continue}}let St=Ee!==void 0&&(e==="open"?N?i>=Ee:i<=Ee:N?s>=Ee+h:a<=Ee-h),Dn=O!==void 0&&(e==="open"?N?i<=O:i>=O:N?a<=O:s>=O),$r=O!==void 0&&(N?i<=O:i>=O),li=Ee!==void 0&&(N?i>=Ee+h:i<=Ee-h);if(Dn&&$r&&!N&&L.entry_bar_index===t.idx){let en=r._preFillSize;if((en?.idx===t.idx?en.size:0)<0){(L._exits_filled??(L._exits_filled=new Set)).add(g.id);continue}}let Gt=null;St&&Dn?Gt=$r?"loss":li||z?"profit":"loss":St?Gt="profit":Dn&&(Gt="loss"),Gt==="loss"&&C.push({qty:$e,price:$r?i:O,kind:"loss",tradeId:L.id}),Gt==="profit"&&H.push({qty:$e,price:li?i:Ee,kind:"profit",tradeId:L.id})}H.sort((L,le)=>N?L.price-le.price:le.price-L.price),C.sort((L,le)=>N?le.price-L.price:L.price-le.price);let V=jn(i,s,a,o),ee=[];if(e==="intrabar"&&!te&&g.trail_offset!==void 0&&(g.trail_price!==void 0||g.trail_points!==void 0)){let L=g._trailByTrade??(g._trailByTrade={});for(let le of w){let $e=kf(t,le,V),Ee=L[le.id]??{armed:!1,peak:NaN},O=mo(g,le._bracket_entry??le.entry_price,N?1:-1,c),ve=Ru(V,$e,{...Ee,armPrice:O,offset:g.trail_offset,dir:N?1:-1,mintick:c,offGrid:Du(t)});L[le.id]={armed:ve.armed,peak:ve.peak};let St=I.perTrade.get(le)??0;ve.fill&&St>1e-9&&ee.push({qty:St,price:ve.fill.price,kind:"trailing",at:ve.fill.at,tradeId:le.id})}}for(let L of H)L.at??(L.at=Wn(V,L.price+(N?h:-h),N)??0);for(let L of C)L.at??(L.at=Wn(V,L.price,!N)??0);let oe=(z?[...H,...C,...ee]:[...C,...ee,...H]).sort((L,le)=>(L.at??0)-(le.at??0));if(oe.length>0){let L=I.total,le=()=>r.opentrades.filter(O=>!g.from_entry||O.entry_id===g.from_entry).reduce((O,ve)=>O+Math.abs(ve.size),0),$e=NaN,Ee=!1;for(let O of oe){if(L<=1e-9)break;let ve=le();if(ve<=1e-9)break;let St=Math.min(O.qty===1/0?ve:O.qty,L,ve),Dn=O.kind==="profit"?O.price:Mr(t,-S,O.price),$r=O.kind==="profit"?g.comment_profit??g.comment:O.kind==="loss"?g.comment_loss??g.comment:g.comment_trailing??g.comment;tr(t,e==="intrabar"?O.at??0:0),Ba(t,g.from_entry,St,Dn,l,{triggerKind:O.kind,exitId:g.id,exitComment:$r},O.tradeId),g.oca_name&&g.oca_type==="reduce"&&Fu(r,g,St),L-=St,$e=Dn,Ee=!0}Ee&&(u=!0,Wr(t,$e)),Ee&&(le()<=1e-9||L<=1e-9)&&(g.status="filled",g.fill_price=$e,g.fill_bar=t.idx,g.fill_time=l);for(let[O,ve]of E)Math.abs(O.size)<ve&&(O._exits_filled??(O._exits_filled=new Set)).add(g.id)}}if(u&&r.opentrades.length===0){let g=new Set(r.closedtrades.filter(w=>w.exit_bar_index===t.idx).map(w=>w.entry_id));for(let w of r.pending_orders)w.status==="pending"&&(w.category??"entry")==="exit"&&w._placedWithPosition&&(!w.from_entry||g.has(w.from_entry))&&(w.status="cancelled")}r.pending_orders=r.pending_orders.filter(g=>g.status==="pending"),Pi(t,o)}var $u="Close position order";function zE(t){let e=t.strategy;if(!e)return;let n=e._pending_close_mc;if(n&&(e._pending_close_mc=null,!(e.opentrades.length===0||Math.sign(e.position_size)!==n.dir)&&(tr(t,-1),er(t,Math.min(n.qty,Math.abs(e.position_size)),Mr(t,-n.dir,n.price),n.time,{exitId:$u,exitComment:"Margin call",forced:!0}),Math.abs(e.position_size)>1e-9))){for(let r of e.pending_orders)r.status==="pending"&&(r.category??"entry")==="entry"&&!r._isReversalEntry&&Ke(r.direction)===n.dir&&(r.status="cancelled");e.pending_orders=e.pending_orders.filter(r=>r.status==="pending")}}function jE(t){let e=t.strategy,n=Math.sign(e?.position_size??0);if(n===0)return!1;let r=_.from(t.data.open).get(0),i=_.from(t.data.high).get(0),s=_.from(t.data.low).get(0),a=Math.abs(i-r)<=Math.abs(r-s);return n===1?!a:a}function ts(t,e="extreme"){let n=t.strategy;if(!n||n.opentrades.length===0)return!1;let r=Math.sign(n.position_size);if(r===0)return!1;let i=r===1?n.config.margin_long??100:n.config.margin_short??100;if(!(i>0)||n._risk?.haltedFrom!==void 0)return!1;let s=_.from(t.data.open).get(0),a=_.from(t.data.high).get(0),o=_.from(t.data.low).get(0),l=_.from(t.data.close).get(0),c=_.from(t.data.openTime).get(0),u=t.pine?.syminfo?.pointvalue??1,h=e==="open"?s:e==="close"?l:e==="favorable"==(r===1)?a:o,p=e==="open"?0:e==="close"?3:jn(s,a,o,l)[1]===h?1:2,d=t._excSeg,f=n._marginFrom;if(f?.idx===t.idx&&(d?d.offset+p*d.scale:p)<f.at-1e-9)return!1;let m=Math.abs(n.position_size),y=Zr(t,h),g=Si(m,h,i,u);if(y<g){let w=g-y,k=i/100,S=Nr(t,w/(h*u*k)),E=S>0?Math.min(m,Number((4*S).toFixed(10))):Math.min(m,1),T=[...n.opentrades],N=T[0],$=Math.abs(N.size),z=N.entry_price;if(tr(t,p),er(t,E,Mr(t,-r,h),c,{exitId:$u,exitComment:"Margin call",forced:!0}),PE(t,h),e==="extreme"&&E>=$-1e-9&&Math.abs(n.position_size)>1e-9){let C=Si($,h,i,u),ae=$*(h-z)*r*u,te=w-C+ae;if(te>0){let I=_.from(t.data.close).get(0),V=(oe=>Math.trunc(oe*1e6)/1e6)(te/(h*u*k)),ee=Math.min(Math.abs(n.position_size),4*V);ee>1e-9&&(n._pending_close_mc={qty:ee,price:I,time:c,dir:r})}}let H=T.find(C=>C.status==="open");return n._mc_exit_lock={bar:t.idx,tradeId:H?.id??null},!0}return!1}function Pp(t){if(t.strategy&&(t.strategy._openFills={idx:t.idx,start:t.strategy.position_size,buys:0,sells:0,real:[]}),t.strategy?.risk_rules?.max_intraday_loss&&If(t),t.strategy){let n=t._excSeg,r=n&&n.scale>0?_.from(t.data.open).get(0):_.from(t.data.close).get(1);Number.isFinite(r)&&(t.strategy._placement={idx:t.idx,price:r,equity:Zr(t,r)})}Va(t,"market"),Tf(t),ts(t,"open");let e=jE(t)&&!vE(t);e&&(Ip(t),ts(t,"extreme")),Va(t,"intrabar"),EE(t),ts(t,"favorable"),e||(Ip(t),ts(t,"extreme")),t.strategy&&NE(t.strategy)}function qE(t){if(!t.strategy)return;let e=t.strategy,n=_.from(t.data.close).get(0);Pi(t,n),t._exc?.bar!==t.idx&&Df(t),BE(t),VE(t),t._exc?.bar===t.idx&&(t._exc.finalized=!0);let r=_.from(t.data.openTime).get(0);if(Number.isFinite(r)){let i=new Date(r),s=i.getUTCFullYear()*12+i.getUTCMonth(),a=e._monthly_equity??(e._monthly_equity=[]);e._last_month_key===s&&a.length>0?a[a.length-1]=e.equity:(a.push(e.equity),e._last_month_key=s)}}function UE(t){let e=t?.strategy;if(!e)return;e.cagr=HE(t),GE(t);let n=e._monthly_equity??[],r=[e.initial_capital,...n],i=[];for(let d=1;d<r.length;d++){let f=r[d-1];f!==0&&Number.isFinite(f)&&Number.isFinite(r[d])&&i.push(r[d]/f-1)}if(i.length<2){e.sharpe_ratio=0,e.sortino_ratio=0;return}let s=(e.config.risk_free_rate??2)/100/12,a=i.length,o=i.reduce((d,f)=>d+f,0)/a,l=o-s,c=i.reduce((d,f)=>d+(f-o)**2,0)/a,u=Math.sqrt(c),h=i.reduce((d,f)=>d+Math.min(0,f-s)**2,0)/a,p=Math.sqrt(h);e.sharpe_ratio=u>0?l/u:0,e.sortino_ratio=p>0?l/p:0}var WE=1440*60*1e3;function HE(t){let e=t?.strategy;if(!e)return NaN;let n=t?.marketData;if(!Array.isArray(n)||n.length===0)return NaN;let r=n[0]?.openTime,i=n[n.length-1]?.openTime;if(!Number.isFinite(r)||!Number.isFinite(i))return NaN;let s=e.initial_capital??0,a=s+(e.netprofit??0),o=(i-r)/WE;if(o<1||!Number.isFinite(s)||!Number.isFinite(a)||s===0)return NaN;let l=o/365;return 100*(Math.pow(a/s,1/l)-1)}function GE(t){let e=t?.strategy;if(!e)return;let n=e._first_entry_price,r=t?.marketData,i=Array.isArray(r)&&r.length>0?r[r.length-1]?.close:NaN;if(!Number.isFinite(n)||!Number.isFinite(i)||n===0){e.buy_and_hold_pnl=NaN,e.buy_and_hold_per_gain=NaN,e.strategy_outperformance=NaN;return}let s=n,a=(i-s)/s;e.buy_and_hold_per_gain=a*100,e.buy_and_hold_pnl=(e.initial_capital??0)*a,e.strategy_outperformance=(e.netprofit??0)-e.buy_and_hold_pnl}function Rf(t){t.strategy}function KE(t,e){let n={title:"",shorttitle:"",overlay:!1,format:"inherit",precision:10,scale:"right",pyramiding:1,calc_on_order_fills:!1,calc_on_every_tick:!1,max_bars_back:0,backtest_fill_limits_assumption:0,default_qty_type:"fixed",default_qty_value:1,initial_capital:1e6,currency:"USD",slippage:0,commission_type:"percent",commission_value:0,margin_long:100,margin_short:100,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,max_polylines_count:50,risk_free_rate:2,use_bar_magnifier:!1,fill_orders_on_standard_ohlc:!1},r={...e,...t._propOverrides??{}},i=t.pineVersion===5?{margin_long:0,margin_short:0}:{},s={...n,...i,...r},a=s.initial_capital,o=r.currency||t.pine?.syminfo?.currency||s.currency||"USD";t.strategy={config:s,opentrades:[],closedtrades:[],pending_orders:[],position_size:0,position_avg_price:NaN,position_entry_name:"",initial_capital:a,account_currency:o,equity:a,netprofit:0,grossprofit:0,grossloss:0,openprofit:0,max_drawdown:0,max_runup:0,equity_peak:a,equity_trough:a,equity_at_runup_peak:a,equity_at_drawdown_peak:a,max_drawdown_percent_value:0,max_runup_percent_value:0,sharpe_ratio:0,sortino_ratio:0,cagr:NaN,buy_and_hold_pnl:NaN,buy_and_hold_per_gain:NaN,strategy_outperformance:NaN,_first_entry_price:void 0,_monthly_equity:[],_last_month_key:-1,wintrades:0,losstrades:0,eventrades:0,wintrades_total_profit:0,losstrades_total_loss:0,max_contracts_held_all:0,max_contracts_held_long:0,max_contracts_held_short:0,risk_rules:{},risk_halted:!1}}function as(t){if(Array.isArray(t))return t.map(as);if(t instanceof Map){let e=new Map;return t.forEach((n,r)=>e.set(r,as(n))),e}if(t!==null&&typeof t=="object"){let e={};for(let n of Object.keys(t))e[n]=as(t[n]);return e}return t}function YE(t){if(!t)return null;let e={};for(let n of Object.keys(t))n==="config"||n==="closedtrades"||(e[n]=as(t[n]));return{fields:e,closedtradesLength:t.closedtrades.length}}function XE(t,e){if(!(!t||!e)){for(let n of Object.keys(t))n==="config"||n==="closedtrades"||Object.prototype.hasOwnProperty.call(e.fields,n)||delete t[n];t.closedtrades.length>e.closedtradesLength&&(t.closedtrades.length=e.closedtradesLength);for(let n of Object.keys(e.fields))t[n]=as(e.fields[n])}}function ZE(t){return(...e)=>{let n=_E(e);return t.strategy?t.strategy.config={...t.strategy.config,...n,...t._propOverrides??{}}:KE(t,n),t.strategy.config}}function Lf(t,e){if(typeof e=="number"&&e<0)throw new fe(`Invalid \\`qty\\` value (${e}) in the \\`${t}()\\` call. Use a positive number less or equal to 1000000000000.`,t)}function Ff(t,e){if(!(typeof e!="number"||Number.isNaN(e))&&(e>100||e<0||e===0&&t==="strategy.exit"))throw new fe(`Invalid \\`qty_percent\\` value (${e}) in the \\`strategy.exit()\\` call. Use a positive value less than or equal to 100 for this parameter.`,t)}function Bf(t,e,n,r){let i=e.pending_orders.find(c=>(c.category==="entry"||c.category===void 0)&&!c._risk&&c.id===n&&c.status==="pending"&&Ke(c.direction)!==r);if(!i)return;let s=i.category==="entry"?"strategy.entry":"strategy.order",a=c=>c===1?"long":"short",o=a(Ke(i.direction)),l=a(r);throw new fe(`The \'${s}\' call already generated an order with the \'${n}\' ID in the \'${o}\' direction, which cannot be changed to \'${l}\'. Cancel the existing \'${n}\' order and create a new order in the desired direction, or specify a different \'id\' for the \'${l}\' order.`,t)}function JE(t){let e=n=>t[n]!==void 0;if(!(["profit","limit","loss","stop"].some(e)||e("trail_offset")&&(e("trail_price")||e("trail_points"))))throw new fe(\'strategy.exit must have at least one of the following parameters: "profit", "limit", "loss", "stop" or one of the following pairs: "trail_offset" and "trail_price" / "trail_points". To close the position at market price, use "strategy.close"\',"strategy.exit")}var QE=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],ek={id:"string",direction:"series",qty:"series",limit:"series",stop:"series",oca_name:"string",oca_type:"string",comment:"string",alert_message:"string",disable_alert:"boolean"};function tk(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.order() called before strategy() declaration");let n=Te(e,QE,ek);if(Jr(n))return;let r=E=>E==null||typeof E=="string"||typeof E=="number"||typeof E=="boolean"?E:typeof E=="function"?E():E instanceof _?E.get(0):Array.isArray(E)?E[E.length-1]:typeof E=="object"&&E.get!==void 0?E.get(0):E,i=E=>typeof E=="number"&&Number.isNaN(E)||typeof E=="object"&&E!==null&&"__value"in E,s=E=>i(E)?void 0:E,a=r(n.id),o=r(n.direction),l=s(r(n.qty)),c=s(r(n.limit)),u=s(r(n.stop)),h=r(n.oca_name),p=r(n.oca_type),d=r(n.comment),f=Ke(o);Lf("strategy.order",l),Bf("strategy.order",t.strategy,a,f);let m=Pu(t,_.from(t.data.close).get(0)),y=t.pine?.syminfo?.mintick??0;c!==void 0&&(c=gs(c,f,"limit",y)),u!==void 0&&(u=gs(u,f,"stop",y));let g=Ou(t,l,f,Sf(u,c,m,f),c===void 0);if(g<=0)return;let w="market";c!==void 0&&u!==void 0?w="stop-limit":c!==void 0?w="limit":u!==void 0&&(w="stop");let k=_.from(t.data.openTime).get(0),S={id:a,direction:f,qty:g,type:w,limit:c,stop:u,bar:t.idx,time:k,status:"pending",oca_name:h,oca_type:p,comment:d};return t.strategy.pending_orders=t.strategy.pending_orders.filter(E=>!((E.category===void 0||E.category==="entry")&&E.id===a&&E.status==="pending")),Lu(t.strategy,S),S}}function nk(t){return(e,n)=>_.from(e).get(n||0)}function rk(t){return()=>{let e=RE(t),n=p=>{let d=Number(p);return e[Number.isNaN(d)?0:d]},r=()=>{let p=t.marketData;return Array.isArray(p)&&t.idx>=0&&t.idx<p.length?Pu(t,p[t.idx]?.close??NaN):NaN},i={__value:e.length,valueOf(){return e.length},toString(){return String(e.length)},[Symbol.toPrimitive](){return e.length}},s=t.pine?.syminfo?.pointvalue??1,a=(p,d)=>{let f=t.strategy?.config,m=f?.commission_type??"percent",y=f?.commission_value??0;if(!y)return 0;let g=Math.abs(p.size);switch(m){case"percent":return g*d*s*(y/100);case"cash_per_contract":return g*y;case"cash_per_order":return y;default:return 0}},o=p=>Math.abs(p.size)*p.entry_price*s+(p.commission??0);i.profit=p=>{let d=n(p);if(!d)return 0;let f=r();return Number.isFinite(f)?(Math.sign(d.size)===1?f-d.entry_price:d.entry_price-f)*Math.abs(d.size)*s-(d.commission??0)-a(d,f):NaN},i.profit_percent=p=>{let d=n(p);if(!d)return 0;let f=i.profit(p);if(!Number.isFinite(f))return NaN;let m=o(d);return m!==0?100*f/m:NaN},i.size=p=>n(p)?.size??0,i.commission=p=>n(p)?.commission??0,i.entry_price=p=>n(p)?.entry_price??NaN,i.entry_bar_index=p=>n(p)?.entry_bar_index??NaN,i.entry_id=p=>n(p)?.entry_id??"",i.entry_comment=p=>n(p)?.entry_comment??n(p)?.entry_id??"",i.entry_time=p=>n(p)?.entry_time??NaN,i.max_drawdown=p=>n(p)?.max_drawdown??0,i.max_drawdown_percent=p=>{let d=n(p);if(!d||!d.max_drawdown)return 0;let f=o(d);return f>0?100*d.max_drawdown/f:0},i.max_runup=p=>n(p)?.max_runup??0,i.max_runup_percent=p=>{let d=n(p);if(!d||!d.max_runup)return 0;let f=o(d);return f>0?100*d.max_runup/f:0};let l=t.strategy,c=l?.config?.margin_long??100,u=l?.config?.margin_short??100,h=Math.sign(l?.position_size??0);if(!l||(h>0?!(c>0):(h<0||!(c>0))&&!(u>0)))i.capital_held=NaN;else{let p=0;for(let d of e)p+=Math.abs(d.size)*d.entry_price*s;i.capital_held=p}return i}}var ik=9e3;function sk(t){return()=>{let e=t.strategy?.closedtrades??[],n=e.length,r=Math.max(0,n-ik),i=l=>{let c=Number(l);return Number.isNaN(c)&&(c=0),c>=r&&c<n?e[c]:void 0},s={__value:n,valueOf(){return n},toString(){return String(n)},[Symbol.toPrimitive](){return n}},a=t.pine?.syminfo?.pointvalue??1,o=l=>ho(l,a);return s.profit=l=>i(l)?.profit??0,s.profit_percent=l=>{let c=i(l);if(!c)return 0;if(c.profit===void 0)return NaN;let u=o(c);return u!==0?100*c.profit/u:NaN},s.size=l=>i(l)?.size??0,s.commission=l=>i(l)?.commission??0,s.entry_price=l=>i(l)?.entry_price??NaN,s.entry_bar_index=l=>i(l)?.entry_bar_index??NaN,s.entry_id=l=>i(l)?.entry_id??"",s.entry_comment=l=>i(l)?.entry_comment??i(l)?.entry_id??"",s.entry_time=l=>i(l)?.entry_time??NaN,s.exit_price=l=>i(l)?.exit_price??NaN,s.exit_bar_index=l=>i(l)?.exit_bar_index??NaN,s.exit_id=l=>i(l)?.exit_id??"",s.exit_comment=l=>i(l)?.exit_comment??i(l)?.exit_id??"",s.exit_time=l=>i(l)?.exit_time??NaN,s.max_drawdown=l=>i(l)?.max_drawdown??0,s.max_drawdown_percent=l=>{let c=i(l);if(!c||!c.max_drawdown)return 0;let u=o(c);return u>0?100*c.max_drawdown/u:0},s.max_runup=l=>i(l)?.max_runup??0,s.max_runup_percent=l=>{let c=i(l);if(!c||!c.max_runup)return 0;let u=o(c);return u>0?100*c.max_runup/u:0},s.first_index=r,s}}function ak(t){return()=>t.strategy?.netprofit??0}function ok(t){return()=>t.strategy?.position_size??0}function lk(t){return()=>{let e=t.strategy;return!e||e.position_size===0?NaN:e.position_avg_price}}function ck(t){return()=>t.strategy?.equity??t.strategy?.config?.initial_capital??1e4}function uk(t){return()=>"long"}function hk(t){return()=>"short"}function pk(t){return()=>"cash"}function dk(t){return()=>"percent_of_equity"}function fk(t){return()=>"fixed"}function mk(t){return()=>t.strategy?.openprofit??0}function yk(t){return()=>{let e=t.strategy;if(!e)return 0;let n=(e.initial_capital??0)+(e.netprofit??0);return n?100*e.openprofit/n:0}}function gk(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.netprofit/e.initial_capital}}function _k(t){return()=>t.strategy?.grossprofit??0}function bk(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossprofit/e.initial_capital}}function xk(t){return()=>t.strategy?.grossloss??0}function vk(t){return()=>{let e=t.strategy;return!e||!e.initial_capital?0:100*e.grossloss/e.initial_capital}}function wk(t){return()=>t.strategy?.wintrades??0}function Sk(t){return()=>t.strategy?.losstrades??0}function Ek(t){return()=>t.strategy?.eventrades??0}function kk(t){return()=>{let e=t.strategy;return!e||!e.closedtrades||e.closedtrades.length===0?NaN:e.netprofit/e.closedtrades.length}}function Ak(t){return()=>{let e=t.strategy;if(!e||!e.closedtrades||e.closedtrades.length===0)return NaN;let n=t.pine?.syminfo?.pointvalue??1,r=0;for(let i of e.closedtrades){let s=ho(i,n);s!==0&&(r+=100*(i.profit??0)/s)}return r/e.closedtrades.length}}function Tk(t){return()=>{let e=t.strategy;return!e||e.wintrades===0?NaN:e.wintrades_total_profit/e.wintrades}}function Nk(t){return()=>{let e=t.strategy;if(!e||e.wintrades===0)return NaN;let n=t.pine?.syminfo?.pointvalue??1,r=0;for(let i of e.closedtrades)if((i.profit??0)>0){let s=ho(i,n);s!==0&&(r+=100*(i.profit??0)/s)}return r/e.wintrades}}function Ck(t){return()=>{let e=t.strategy;return!e||e.losstrades===0?NaN:e.grossloss/e.losstrades}}function Ik(t){return()=>{let e=t.strategy;if(!e||e.losstrades===0)return NaN;let n=t.pine?.syminfo?.pointvalue??1,r=0;for(let i of e.closedtrades)if((i.profit??0)<0){let s=ho(i,n);s!==0&&(r+=100*(i.profit??0)/s)}return r/e.losstrades}}function Mk(t){return()=>t.strategy?.max_drawdown??0}function Pk(t){return()=>{let e=t.strategy;return e?e.max_drawdown_percent_value??0:0}}function Dk(t){return()=>t.strategy?.max_runup??0}function Ok(t){return()=>{let e=t.strategy;return e?e.max_runup_percent_value??0:0}}function Rk(t){return()=>t.strategy?.max_contracts_held_all??0}function Lk(t){return()=>t.strategy?.max_contracts_held_long??0}function Fk(t){return()=>t.strategy?.max_contracts_held_short??0}function Bk(t){return()=>t.strategy?.position_entry_name??""}function Vk(t){return()=>t.strategy?.initial_capital??0}function $k(t){return()=>t.strategy?.account_currency??"USD"}function zk(t){return()=>{let e=t.strategy;if(!e||e.position_size===0)return NaN;let n=e.position_avg_price;if(!Number.isFinite(n))return NaN;let r=Math.sign(e.position_size),i=r===1?e.config.margin_long??100:e.config.margin_short??100;if(!(i>0))return NaN;if(r===1&&i===100)return NaN;let s=Math.abs(e.position_size),a=t.pine?.syminfo?.pointvalue??1,o=((e.initial_capital??0)+(e.netprofit??0))/(a*s)-r*n,l=i/100-r,c=o/l,u=t.pine?.syminfo?.mintick??.01,h=c/u;return r===1?Math.floor(h+1e-6)*u:Math.ceil(h-1e-6)*u}}var jk=[["id","direction","qty","limit","stop","oca_name","oca_type","comment","alert_message","disable_alert"]],qk={id:"string",direction:"series",qty:"series",limit:"series",stop:"series",oca_name:"string",oca_type:"string",comment:"string",alert_message:"string",disable_alert:"boolean"};function Uk(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.entry() called before strategy() declaration");let n=Te(e,jk,qk);if(Jr(n))return;let r=C=>C==null||typeof C=="string"||typeof C=="number"||typeof C=="boolean"?C:typeof C=="function"?C():C instanceof _?C.get(0):Array.isArray(C)?C[C.length-1]:typeof C=="object"&&C.get!==void 0?C.get(0):C,i=C=>typeof C=="number"&&Number.isNaN(C)||typeof C=="object"&&C!==null&&"__value"in C,s=C=>i(C)?void 0:C,a=r(n.id),o=r(n.direction),l=s(r(n.qty)),c=s(r(n.limit)),u=s(r(n.stop)),h=r(n.oca_name),p=r(n.oca_type),d=r(n.comment),f=Ke(o),m=t.strategy;Lf("strategy.entry",l),Bf("strategy.entry",m,a,f);let y=m.position_size;for(let C of m.pending_orders)if(!(C.bar!==t.idx||C.status!=="pending")){if((C.category==="entry"||C.category===void 0)&&C.type==="market")y+=Ke(C.direction)*C.qty;else if(Hr(C)&&y!==0){let ae=m.opentrades.filter(V=>!C.from_entry||V.entry_id===C.from_entry);if(C._intended_trade_ids){let V=new Set(C._intended_trade_ids);ae=ae.filter(ee=>V.has(ee.id))}let te=ae.reduce((V,ee)=>V+Math.abs(ee.size),0),I=te;C.qty&&C.qty>0?I=Math.min(C.qty,te):C.qty_percent&&C.qty_percent>0&&(I=fo(t,te,C.qty_percent)),y-=Math.sign(y)*Math.min(I,Math.abs(y))}}if(Math.sign(y)===f&&y!==0&&Cf(m,f))return;let g=Pu(t,_.from(t.data.close).get(0)),w="market";c!==void 0&&u!==void 0?w="stop-limit":c!==void 0?w="limit":u!==void 0&&(w="stop");let k=t.pine?.syminfo?.mintick??0,S=c!==void 0?gs(c,f,"limit",k):void 0,E=u!==void 0?gs(u,f,"stop",k):void 0,T=Ou(t,l,f,Sf(E,S,g,f),S===void 0),N=y!==0&&Math.sign(y)!==f;if(T<=0&&!N)return;let $=N?Math.abs(y)+T:T,z=_.from(t.data.openTime).get(0),H={id:a,direction:f,qty:$,type:w,limit:S,stop:E,bar:t.idx,time:z,status:"pending",category:"entry",oca_name:h,oca_type:p,comment:d,_isReversalEntry:N,_base_qty:T,_reversesPending:N&&Math.sign(m.position_size)!==Math.sign(y)};m.pending_orders=m.pending_orders.filter(C=>!((C.category==="entry"||C.category===void 0)&&C.id===a&&C.status==="pending")),Lu(m,H)}}var Wk=[["id","from_entry","qty","qty_percent","profit","limit","loss","stop","trail_price","trail_points","trail_offset","oca_name","comment","comment_profit","comment_loss","comment_trailing","alert_message","alert_profit","alert_loss","alert_trailing","disable_alert"]],Hk={id:"string",from_entry:"string",qty:"series",qty_percent:"series",profit:"series",limit:"series",loss:"series",stop:"series",trail_price:"series",trail_points:"series",trail_offset:"series",oca_name:"string",comment:"string",comment_profit:"string",comment_loss:"string",comment_trailing:"string",alert_message:"string",alert_profit:"string",alert_loss:"string",alert_trailing:"string",disable_alert:"boolean"};function Gk(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.exit() called before strategy() declaration");cn(e);let n=Te(e,Wk,Hk);if(Jr(n))return;JE(n);let r=O=>O==null||typeof O=="string"||typeof O=="number"||typeof O=="boolean"?O:typeof O=="function"?O():O instanceof _?O.get(0):Array.isArray(O)?O[O.length-1]:typeof O=="object"&&O.get!==void 0?O.get(0):O,i=r(n.id),s=r(n.from_entry),a=r(n.qty),o=r(n.qty_percent),l=O=>typeof O=="number"&&Number.isNaN(O)||typeof O=="object"&&O!==null&&"__value"in O,c=O=>l(O)?void 0:O,u=O=>typeof O=="number"?Math.ceil(O-1e-9):O,h=O=>typeof O=="number"?Math.trunc(O+Math.sign(O)*1e-9):O,p=u(c(r(n.profit))),d=c(r(n.limit)),f=u(c(r(n.loss))),m=c(r(n.stop)),y=c(r(n.trail_price)),g=c(r(n.trail_points)),w=h(c(r(n.trail_offset))),k=s??"",S=k?t.strategy.pending_orders.find(O=>O.category==="entry"&&O.id===k&&O.status==="pending"):t.strategy.pending_orders.find(O=>O.category==="entry"&&O.status==="pending"),E=!!S?._isReversalEntry;if(k&&!S&&!t.strategy.opentrades.some(O=>O.entry_id===k))return;(a==null||l(a))&&Ff("strategy.exit",o);let T=t.pine?.syminfo?.mintick??0,N=t._fillPointPrice??_.from(t.data.close).get(0),$=t.strategy.opentrades.find(O=>!k||O.entry_id===k),z=$?Math.sign($.size):S?Ke(S.direction):0,H=(O,ve)=>O===void 0?void 0:z?gs(O,-z,ve,T):Tp(O,N,T),C=H(d,"limit"),ae=H(m,"stop"),te=y!==void 0?Tp(y,N,T):void 0,I=i??"exit",V=t.strategy.pending_orders,ee=[];for(let O=V.length-1;O>=0;O--){let ve=V[O];ve.category==="exit"&&ve.id===I&&(ve.from_entry??"")===k&&ve.status==="pending"&&(ee.push(ve),V.splice(O,1))}if([p,C,f,ae,te,g].every(O=>O===void 0))return;let oe={id:I,direction:0,qty:a!=null&&!l(a)?Nr(t,Math.abs(Number(a))):0,qty_percent:l(o)?void 0:o,type:"market",bar:t.idx,time:_.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:k,profit:p,loss:f,limit:C,stop:ae,trail_price:te,_trailPriceRaw:y,trail_points:g,trail_offset:w,oca_name:r(n.oca_name),_priceLegsWin:t.pineVersion===5,oca_type:r(n.oca_name)?"reduce":void 0,comment:r(n.comment),comment_profit:r(n.comment_profit),comment_loss:r(n.comment_loss),comment_trailing:r(n.comment_trailing),alert_message:r(n.alert_message),alert_profit:r(n.alert_profit),alert_loss:r(n.alert_loss),alert_trailing:r(n.alert_trailing),disable_alert:r(n.disable_alert),_attachedAtReversal:E,_placedWithPosition:t.strategy.opentrades.length>0,_placedDir:Math.sign(t.strategy.position_size)},L=ee.find(O=>O._trailByTrade&&O._trailPriceRaw===y&&O.trail_points===g);if(L&&(oe._trailByTrade={...L._trailByTrade}),oe.trail_offset!==void 0&&(te!==void 0||g!==void 0)){let O=t._fillPointPrice??_.from(t.data.close).get(0);for(let ve of t.strategy.opentrades){if(k&&ve.entry_id!==k||oe._trailByTrade?.[ve.id]?.armed)continue;let St=Math.sign(ve.size),Dn=mo(oe,ve._bracket_entry??ve.entry_price,St,T);Number.isFinite(O)&&St*(O-Dn)>=0&&((oe._trailByTrade??(oe._trailByTrade={}))[ve.id]={armed:!0,peak:O})}}let le=t.strategy,$e=le._exit_seqs??(le._exit_seqs=new Map),Ee=`${I}\\0${k}`;$e.has(Ee)||$e.set(Ee,$e.size+1),oe._seq=$e.get(Ee),Lu(t.strategy,oe)}}var Kk=[["id","comment","qty","qty_percent","alert_message","immediately","disable_alert"]],Yk={id:"string",comment:"string",qty:"series",qty_percent:"series",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function Xk(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close() called before strategy() declaration");let n=Te(e,Kk,Yk);if(Jr(n))return;let r=We(n.id),i=We(n.qty),s=We(n.qty_percent),a=ec(i)||i===void 0||i===null?void 0:Nr(t,Math.abs(Number(i))),o=ec(s)?void 0:s;if(r==null||!t.strategy.opentrades.some(p=>p.entry_id===r))return;a===void 0&&Ff("strategy.close",o);let l=p=>(p.category??"entry")==="exit"&&(p.profit!==void 0||p.loss!==void 0||p.limit!==void 0||p.stop!==void 0||p.trail_price!==void 0||p.trail_points!==void 0),c=t.strategy.pending_orders,u=a!==void 0&&Number(a)>0||o!==void 0&&Number(o)>0&&Number(o)<100;for(let p of c)!u&&l(p)&&(p.from_entry??"")===r&&p.status==="pending"&&(p.status="cancelled");t.strategy.pending_orders=c.filter(p=>p.status==="pending");let h={id:`Close entry(s) order ${r}`,direction:0,qty:0,type:"market",bar:t.idx,time:_.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:r,qty_percent:o,comment:We(n.comment),alert_message:We(n.alert_message),immediately:We(n.immediately)===!0,disable_alert:We(n.disable_alert),_intended_trade_ids:t.strategy.opentrades.filter(p=>p.entry_id===r).map(p=>p.id)};a!==void 0&&(h.qty=a),t.strategy.pending_orders.push(h)}}var Zk=[["comment","alert_message","immediately","disable_alert"]],Jk={comment:"string",alert_message:"string",immediately:"boolean",disable_alert:"boolean"};function Qk(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.close_all() called before strategy() declaration");let n=Te(e,Zk,Jk);if(Jr(n)||t.strategy.opentrades.length===0)return;let r=a=>(a.category??"entry")==="exit"&&(a.profit!==void 0||a.loss!==void 0||a.limit!==void 0||a.stop!==void 0||a.trail_price!==void 0||a.trail_points!==void 0),i=t.strategy.pending_orders;for(let a of i)r(a)&&a.status==="pending"&&(a.status="cancelled");t.strategy.pending_orders=i.filter(a=>a.status==="pending");let s={id:"Close position order",direction:0,qty:0,type:"market",bar:t.idx,time:_.from(t.data.openTime).get(0),status:"pending",category:"exit",from_entry:"",comment:We(n.comment),alert_message:We(n.alert_message),immediately:We(n.immediately)===!0,disable_alert:We(n.disable_alert),_intended_trade_ids:t.strategy.opentrades.map(a=>a.id)};t.strategy.pending_orders.push(s)}}var eA=[["id","immediately"]],tA={id:"string",immediately:"boolean"};function nA(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.cancel() called before strategy() declaration");let n=Te(e,eA,tA);if(Jr(n))return;let r=We(n.id);r!=null&&(t.strategy.pending_orders=t.strategy.pending_orders.filter(i=>!(i.status==="pending"&&i.id===r)))}}function rA(t){return(...e)=>{if(!t.strategy)throw new Error("strategy.cancel_all() called before strategy() declaration");Jr(Te(e,[[]],{}))||(t.strategy.pending_orders=t.strategy.pending_orders.filter(n=>n.status!=="pending"))}}function iA(t){return{allow_entry_in:e=>{t.strategy&&(t.strategy.risk_rules.allow_entry_in=We(e))},max_cons_loss_days:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_cons_loss_days={count:Number(We(e)),alert_message:We(n)})},max_drawdown:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_drawdown={value:Number(We(e)),type:We(n)})},max_intraday_filled_orders:(e,n)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_filled_orders={count:Number(We(e)),alert_message:We(n)})},max_intraday_loss:(e,n,r)=>{t.strategy&&(t.strategy.risk_rules.max_intraday_loss={value:Number(We(e)),type:We(n)})},max_position_size:e=>{t.strategy&&(t.strategy.risk_rules.max_position_size=Number(We(e)))}}}function sA(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function aA(t){return e=>{let n=t.strategy,r=t.pine?.syminfo?.currency,i=n?.account_currency??"USD";return r&&r!==i?NaN:e}}function oA(t){return e=>t.strategy?Ou(t,void 0,1,e,!1,!0):0}var lA={any:ZE,order:tk,param:nk,opentrades:rk,closedtrades:sk,netprofit:ak,position_size:ok,position_avg_price:lk,equity:ck,long:uk,short:hk,cash:pk,percent_of_equity:dk,fixed:fk,openprofit:mk,openprofit_percent:yk,netprofit_percent:gk,grossprofit:_k,grossprofit_percent:bk,grossloss:xk,grossloss_percent:vk,wintrades:wk,losstrades:Sk,eventrades:Ek,avg_trade:kk,avg_trade_percent:Ak,avg_winning_trade:Tk,avg_winning_trade_percent:Nk,avg_losing_trade:Ck,avg_losing_trade_percent:Ik,max_drawdown:Mk,max_drawdown_percent:Pk,max_runup:Dk,max_runup_percent:Ok,max_contracts_held_all:Rk,max_contracts_held_long:Lk,max_contracts_held_short:Fk,position_entry_name:Bk,initial_capital:Vk,account_currency:$k,margin_liquidation_price:zk,entry:Uk,exit:Gk,close:Xk,close_all:Qk,cancel:nA,cancel_all:rA,convert_to_account:sA,convert_to_symbol:aA,default_entry_qty:oA},cA={long:"long",short:"short",all:"all"},uA={none:"none",cancel:"cancel",reduce:"reduce"},hA={percent:"percent",cash_per_order:"cash_per_order",cash_per_contract:"cash_per_contract"},ic=class{constructor(e){this.context=e,Object.entries(lA).forEach(([r,i])=>{this[r]=i(e)}),this.direction=()=>cA,this.oca=()=>uA,this.commission=()=>hA;let n=iA(e);this.risk=()=>n}};function pA(t,e){let n=e.trim();if(n==="UTC"||n==="GMT"||n==="Etc/UTC")return 0;let r=n.match(/^(?:UTC|GMT)([+-])(\\d{1,2})(?::(\\d{2}))?$/i);if(r){let a=r[1]==="+"?1:-1,o=parseInt(r[2],10),l=parseInt(r[3]||"0",10);return a*(o*60+l)}let i=Ir(t,e),s=new Date(Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second));return Math.round((s.getTime()-t)/6e4)}function dA(t,e){let n=e>=0?"+":"-",r=s=>String(Math.floor(Math.abs(s))).padStart(2,"0"),i=n+r(e/60)+":"+r(e%60);return`[${new Date(t+e*6e4).toISOString().slice(0,-1)}${i}]`}var sc=class{constructor(e){this.context=e}logFormat(e,...n){return n.length===0?e:this.context.pine.str.format(e,...n)}param(e,n=0,r){return _.from(e).get(n)}_formatTimestamp(){let e=this.context.data.openTime.data[this.context.idx],n=this.context.chartTimezone||this.context.pine?.syminfo?.timezone||"UTC",r=pA(e,n);return dA(e,r)}warning(e,...n){this.context.isSecondaryContext||console.warn(`${this._formatTimestamp()} ${this.logFormat(e,...n)}`)}error(e,...n){this.context.isSecondaryContext||console.error(`${this._formatTimestamp()} ${this.logFormat(e,...n)}`)}info(e,...n){this.context.isSecondaryContext||console.log(`${this._formatTimestamp()} ${this.logFormat(e,...n)}`)}},ac=class{constructor(e){this.context=e}param(e,n=0,r){return _.from(e).get(n)}error(e){let n=_.from(e).get(0);throw new fe(typeof n=="string"?n:String(n??""),"runtime.error")}},fA=`\nACST|Australian Central Standard Time|ACDT|Australian Central Daylight Time=Australia/Adelaide Australia/Broken_Hill Australia/Darwin Australia/North Australia/South Australia/Yancowinna\nACT|Acre Standard Time|ACST|Acre Summer Time=America/Eirunepe America/Porto_Acre America/Rio_Branco Brazil/Acre\nACWST|Australian Central Western Standard Time|ACWDT|Australian Central Western Daylight Time=Australia/Eucla\nAEST|Australian Eastern Standard Time|AEDT|Australian Eastern Daylight Time=Antarctica/Macquarie Australia/ACT Australia/Brisbane Australia/Canberra Australia/Currie Australia/Hobart Australia/Lindeman Australia/Melbourne Australia/NSW Australia/Queensland Australia/Sydney Australia/Tasmania Australia/Victoria\nAFT|Afghanistan Time=Asia/Kabul\nAKST|Alaska Standard Time|AKDT|Alaska Daylight Time=America/Anchorage America/Juneau America/Metlakatla America/Nome America/Sitka America/Yakutat US/Alaska\nALMT|East Kazakhstan Time|ALMST|Alma-Ata Summer Time=Asia/Almaty\nAMT|Amazon Standard Time|AMST|Amazon Summer Time=America/Boa_Vista America/Campo_Grande America/Cuiaba America/Manaus America/Porto_Velho Brazil/West\nAMT|Armenia Standard Time|AMST|Armenia Summer Time=Asia/Yerevan\nANAT|Anadyr Standard Time|ANAST|Anadyr Summer Time=Asia/Anadyr\nAQTT|West Kazakhstan Time|AQTST|Aqtau Summer Time=Asia/Aqtau\nAQTT|West Kazakhstan Time|AQTST|Aqtobe Summer Time=Asia/Aqtobe\nART|Argentina Standard Time|ARST|Argentina Summer Time=America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Buenos_Aires America/Catamarca America/Cordoba America/Jujuy America/Mendoza America/Rosario\nAST|Arabian Standard Time=Asia/Aden Asia/Bahrain Asia/Kuwait Asia/Qatar Asia/Riyadh\nAST|Arabian Standard Time|ADT|Arabian Daylight Time=Asia/Baghdad\nAST|Atlantic Standard Time|ADT|Atlantic Daylight Time=America/Anguilla America/Antigua America/Aruba America/Barbados America/Blanc-Sablon America/Curacao America/Dominica America/Glace_Bay America/Goose_Bay America/Grenada America/Guadeloupe America/Halifax America/Kralendijk America/Lower_Princes America/Marigot America/Martinique America/Moncton America/Montserrat America/Port_of_Spain America/Puerto_Rico America/Santo_Domingo America/St_Barthelemy America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Thule America/Tortola America/Virgin Atlantic/Bermuda Canada/Atlantic\nAWST|Australian Western Standard Time|AWDT|Australian Western Daylight Time=Australia/Perth Australia/West\nAWST|Casey Time=Antarctica/Casey\nAZOT|Azores Standard Time|AZOST|Azores Summer Time=Atlantic/Azores\nAZT|Azerbaijan Standard Time|AZST|Azerbaijan Summer Time=Asia/Baku\nBDT|Bangladesh Standard Time|BDST|Bangladesh Summer Time=Asia/Dacca Asia/Dhaka\nBNT|Brunei Darussalam Time|BNST|Brunei Summer Time=Asia/Brunei\nBOT|Bolivia Time|BOST|Bolivia Summer Time=America/La_Paz\nBRT|Brasilia Standard Time|BRST|Brasilia Summer Time=America/Araguaina America/Bahia America/Belem America/Fortaleza America/Maceio America/Recife America/Santarem America/Sao_Paulo Brazil/East\nBST|Bougainville Standard Time=Pacific/Bougainville\nBTT|Bhutan Time=Asia/Thimbu Asia/Thimphu\nCAT|Central Africa Time=Africa/Blantyre Africa/Bujumbura Africa/Gaborone Africa/Harare Africa/Kigali Africa/Lubumbashi Africa/Lusaka Africa/Maputo\nCAT|Central Africa Time|CAST|Central African Summer Time=Africa/Juba Africa/Khartoum\nCAT|Central Africa Time|WAT|Western African Time=Africa/Windhoek\nCCT|Cocos Islands Time=Indian/Cocos\nCET|Central European Standard Time|CEST|Central European Summer Time=Africa/Algiers Africa/Ceuta Africa/Tunis Arctic/Longyearbyen Atlantic/Jan_Mayen Europe/Amsterdam Europe/Andorra Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Budapest Europe/Busingen Europe/Copenhagen Europe/Gibraltar Europe/Ljubljana Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Monaco Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Rome Europe/San_Marino Europe/Sarajevo Europe/Skopje Europe/Stockholm Europe/Tirane Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Warsaw Europe/Zagreb Europe/Zurich Poland\nCET|Central European Time|CEST|Central European Summer Time=CET\nCHAST|Chatham Standard Time|CHADT|Chatham Daylight Time=NZ-CHAT Pacific/Chatham\nCHOT|Ulaanbaatar Standard Time|CHOST|Ulaanbaatar Summer Time=Asia/Choibalsan\nChST|Chamorro Standard Time|ChDT|Chamorro Daylight Time=Pacific/Guam Pacific/Saipan\nCHUT|Chuuk Time=Pacific/Chuuk Pacific/Truk Pacific/Yap\nCKT|Cook Islands Standard Time|CKHST|Cook Islands Half Summer Time=Pacific/Rarotonga\nCLT|Chile Standard Time|CLST|Chile Summer Time=America/Santiago Chile/Continental\nCLT|Chile Time|CLST|Chile Summer Time=Antarctica/Palmer\nCOT|Colombia Standard Time|COST|Colombia Summer Time=America/Bogota\nCST|Central Standard Time|CDT|Central Daylight Time=America/Bahia_Banderas America/Belize America/Chicago America/Chihuahua America/Costa_Rica America/El_Salvador America/Guatemala America/Indiana/Knox America/Indiana/Tell_City America/Knox_IN America/Managua America/Matamoros America/Menominee America/Merida America/Mexico_City America/Monterrey America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga America/Rainy_River America/Rankin_Inlet America/Regina America/Resolute America/Swift_Current America/Tegucigalpa America/Winnipeg CST6CDT Canada/Central Canada/Saskatchewan Mexico/General US/Central US/Indiana-Starke\nCST|China Standard Time|CDT|China Daylight Time=Asia/Chongqing Asia/Chungking Asia/Harbin Asia/Macao Asia/Macau Asia/Shanghai PRC\nCST|Cuba Standard Time|CDT|Cuba Daylight Time=America/Havana Cuba\nCST|Taipei Standard Time|CDT|Taipei Daylight Time=Asia/Taipei\nCVT|Cape Verde Standard Time|CVST|Cape Verde Summer Time=Atlantic/Cape_Verde\nCXT|Christmas Island Time=Indian/Christmas\nDAVT|Davis Time=Antarctica/Davis\nDDUT|Dumont-d\\u2019Urville Time=Antarctica/DumontDUrville\nEAST|Easter Island Standard Time|EASST|Easter Island Summer Time=Chile/EasterIsland Pacific/Easter\nEAT|East Africa Time=Africa/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Africa/Nairobi Indian/Antananarivo Indian/Comoro Indian/Mayotte\nECT|Ecuador Time|ECST|Ecuador Summer Time=America/Guayaquil\nEET|Eastern European Standard Time|EEST|Eastern European Summer Time=Africa/Cairo Africa/Tripoli Asia/Beirut Asia/Gaza Asia/Hebron Asia/Nicosia Egypt Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kaliningrad Europe/Kiev Europe/Kyiv Europe/Mariehamn Europe/Nicosia Europe/Riga Europe/Sofia Europe/Tallinn Europe/Tiraspol Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye Libya\nEET|Eastern European Time|EEST|Eastern European Summer Time=Asia/Amman Asia/Damascus Asia/Famagusta EET\nEGT|East Greenland Standard Time|EGST|East Greenland Summer Time=America/Scoresbysund\nEST|Eastern Standard Time=America/Atikokan America/Cayman America/Coral_Harbour America/Panama\nEST|Eastern Standard Time|EDT|Eastern Daylight Time=America/Cancun America/Detroit America/Fort_Wayne America/Grand_Turk America/Indiana/Indianapolis America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Iqaluit America/Jamaica America/Kentucky/Louisville America/Kentucky/Monticello America/Louisville America/Montreal America/Nassau America/New_York America/Nipigon America/Pangnirtung America/Port-au-Prince America/Thunder_Bay America/Toronto Canada/Eastern EST5EDT Jamaica US/East-Indiana US/Eastern US/Michigan\nFJT|Fiji Standard Time|FJST|Fiji Summer Time=Pacific/Fiji\nFKT|Falkland Islands Standard Time|FKST|Falkland Islands Summer Time=Atlantic/Stanley\nFNT|Fernando de Noronha Standard Time|FNST|Fernando de Noronha Summer Time=America/Noronha Brazil/DeNoronha\nGALT|Galapagos Time|GALST|Galapagos Summer Time=Pacific/Galapagos\nGAMT|Gambier Time=Pacific/Gambier\nGET|Georgia Standard Time|GEST|Georgia Summer Time=Asia/Tbilisi\nGFT|French Guiana Time=America/Cayenne\nGILT|Gilbert Islands Time=Pacific/Tarawa\nGMT-01:00|GMT-01:00=Etc/GMT+1\nGMT-02:00|GMT-02:00=Etc/GMT+2\nGMT-03:00|Coyhaique Standard Time|GMT-03:00|Coyhaique Daylight Time=America/Coyhaique\nGMT-03:00|GMT-03:00=Etc/GMT+3\nGMT-03:00|Punta Arenas Standard Time=America/Punta_Arenas\nGMT-04:00|GMT-04:00=Etc/GMT+4\nGMT-05:00|GMT-05:00=Etc/GMT+5\nGMT-06:00|GMT-06:00=Etc/GMT+6\nGMT-07:00|GMT-07:00=Etc/GMT+7\nGMT-08:00|GMT-08:00=Etc/GMT+8\nGMT-09:00|GMT-09:00=Etc/GMT+9\nGMT-10:00|GMT-10:00=Etc/GMT+10\nGMT-11:00|GMT-11:00=Etc/GMT+11\nGMT-12:00|GMT-12:00=Etc/GMT+12\nGMT+01:00|GMT+01:00=Etc/GMT-1\nGMT+02:00|GMT+02:00=Etc/GMT-2\nGMT+03:00|GMT+03:00=Etc/GMT-3\nGMT+04:00|Astrakhan Standard Time=Europe/Astrakhan\nGMT+04:00|GMT+04:00=Etc/GMT-4\nGMT+04:00|Saratov Standard Time=Europe/Saratov\nGMT+04:00|Ulyanovsk Standard Time=Europe/Ulyanovsk\nGMT+05:00|GMT+05:00=Etc/GMT-5\nGMT+05:00|West Kazakhstan Time|GMT+05:00|Atyrau Daylight Time=Asia/Atyrau\nGMT+06:00|GMT+06:00=Etc/GMT-6\nGMT+07:00|Barnaul Standard Time|GMT+07:00|Barnaul Daylight Time=Asia/Barnaul\nGMT+07:00|GMT+07:00=Etc/GMT-7\nGMT+07:00|Tomsk Standard Time|GMT+07:00|Tomsk Daylight Time=Asia/Tomsk\nGMT+08:00|GMT+08:00=Etc/GMT-8\nGMT+09:00|GMT+09:00=Etc/GMT-9\nGMT+10:00|GMT+10:00=Etc/GMT-10\nGMT+11:00|GMT+11:00=Etc/GMT-11\nGMT+12:00|GMT+12:00=Etc/GMT-12\nGMT+13:00|GMT+13:00=Etc/GMT-13\nGMT+14:00|GMT+14:00=Etc/GMT-14\nGMT|Greenwich Mean Time=Africa/Abidjan Africa/Accra Africa/Bamako Africa/Banjul Africa/Bissau Africa/Conakry Africa/Dakar Africa/Freetown Africa/Lome Africa/Monrovia Africa/Nouakchott Africa/Ouagadougou Africa/Sao_Tome Africa/Timbuktu America/Danmarkshavn Atlantic/Reykjavik Atlantic/St_Helena Etc/GMT Etc/GMT+0 Etc/GMT-0 Etc/GMT0 Etc/Greenwich GMT0 Greenwich Iceland\nGMT|Greenwich Mean Time|BST|British Summer Time=Europe/Belfast Europe/Guernsey Europe/Isle_of_Man Europe/Jersey Europe/London GB GB-Eire\nGMT|Greenwich Mean Time|CEST|Central European Summer Time=Antarctica/Troll\nGMT|Greenwich Mean Time|IST|Irish Standard Time=Eire Europe/Dublin\nGST|Gulf Standard Time=Asia/Dubai Asia/Muscat\nGST|South Georgia Time=Atlantic/South_Georgia\nGYT|Guyana Time=America/Guyana\nHAST|Hawaii-Aleutian Standard Time|HADT|Hawaii-Aleutian Daylight Time=America/Adak America/Atka Pacific/Johnston US/Aleutian\nHKT|Hong Kong Standard Time|HKST|Hong Kong Summer Time=Asia/Hong_Kong Hongkong\nHOVT|Hovd Standard Time|HOVST|Hovd Summer Time=Asia/Hovd\nHST|Hawaii-Aleutian Standard Time|HDT|Hawaii-Aleutian Daylight Time=Pacific/Honolulu US/Hawaii\nICT|Indochina Time=Asia/Bangkok Asia/Ho_Chi_Minh Asia/Phnom_Penh Asia/Saigon Asia/Vientiane\nIOT|Indian Ocean Time=Indian/Chagos\nIRKT|Irkutsk Standard Time|IRKST|Irkutsk Summer Time=Asia/Irkutsk\nIRST|Iran Standard Time|IRDT|Iran Daylight Time=Asia/Tehran Iran\nIST|India Standard Time|IDT|India Daylight Time=Asia/Calcutta Asia/Colombo Asia/Kolkata\nIST|Israel Standard Time|IDT|Israel Daylight Time=Asia/Jerusalem Asia/Tel_Aviv Israel\nJST|Japan Standard Time|JDT|Japan Daylight Time=Asia/Tokyo Japan\nKGT|Kyrgyzstan Time|KGST|Kirgizstan Summer Time=Asia/Bishkek\nKOST|Kosrae Time=Pacific/Kosrae\nKRAT|Krasnoyarsk Standard Time|KRAST|Krasnoyarsk Summer Time=Asia/Krasnoyarsk Asia/Novokuznetsk\nKST|Korean Standard Time=Asia/Pyongyang\nKST|Korean Standard Time|KDT|Korean Daylight Time=Asia/Seoul ROK\nLHST|Lord Howe Standard Time|LHDT|Lord Howe Daylight Time=Australia/LHI Australia/Lord_Howe\nLINT|Line Islands Time=Pacific/Kiritimati\nMAGT|Magadan Standard Time|MAGST|Magadan Summer Time=Asia/Magadan\nMART|Marquesas Time=Pacific/Marquesas\nMAWT|Mawson Time=Antarctica/Mawson\nMET|Middle Europe Time|MEST|Middle Europe Summer Time=MET\nMHT|Marshall Islands Time=Kwajalein Pacific/Kwajalein Pacific/Majuro\nMMT|Myanmar Time=Asia/Rangoon Asia/Yangon\nMSK|Moscow Standard Time|MSD|Moscow Daylight Time=Europe/Kirov\nMSK|Moscow Standard Time|MSD|Moscow Summer Time=Europe/Minsk Europe/Moscow Europe/Simferopol W-SU\nMSK|Volgograd Standard Time|MSD|Volgograd Summer Time=Europe/Volgograd\nMST|Mexican Pacific Standard Time|MDT|Mexican Pacific Daylight Time=America/Hermosillo America/Mazatlan Mexico/BajaSur\nMST|Mountain Standard Time|MDT|Mountain Daylight Time=America/Boise America/Cambridge_Bay America/Ciudad_Juarez America/Creston America/Dawson_Creek America/Denver America/Edmonton America/Fort_Nelson America/Inuvik America/Phoenix America/Shiprock America/Yellowknife Canada/Mountain MST7MDT Navajo US/Arizona US/Mountain\nMST|Yukon Time|MDT|Mountain Daylight Time=America/Dawson America/Whitehorse Canada/Yukon\nMUT|Mauritius Standard Time|MUST|Mauritius Summer Time=Indian/Mauritius\nMVT|Maldives Time=Indian/Maldives\nMYT|Malaysia Time|MYST|Malaysia Summer Time=Asia/Kuala_Lumpur Asia/Kuching\nNCT|New Caledonia Standard Time|NCST|New Caledonia Summer Time=Pacific/Noumea\nNFT|Norfolk Island Standard Time|NFST|Norfolk Island Daylight Time=Pacific/Norfolk\nNOVT|Novosibirsk Standard Time|NOVST|Novosibirsk Summer Time=Asia/Novosibirsk\nNPT|Nepal Time=Asia/Kathmandu Asia/Katmandu\nNRT|Nauru Time=Pacific/Nauru\nNST|Newfoundland Standard Time|NDT|Newfoundland Daylight Time=America/St_Johns Canada/Newfoundland\nNUT|Niue Time=Pacific/Niue\nNZST|New Zealand Standard Time|NZDT|New Zealand Daylight Time=Antarctica/McMurdo Antarctica/South_Pole NZ Pacific/Auckland\nOMST|Omsk Standard Time|OMSST|Omsk Summer Time=Asia/Omsk\nORAT|West Kazakhstan Time|ORAST|Oral Summer Time=Asia/Oral\nPET|Peru Standard Time|PEST|Peru Summer Time=America/Lima\nPETT|Petropavlovsk-Kamchatski Standard Time|PETST|Petropavlovsk-Kamchatski Summer Time=Asia/Kamchatka\nPGT|Papua New Guinea Time=Pacific/Port_Moresby\nPHOT|Phoenix Islands Time=Pacific/Enderbury Pacific/Kanton\nPKT|Pakistan Standard Time|PKST|Pakistan Summer Time=Asia/Karachi\nPMST|St. Pierre & Miquelon Standard Time|PMDT|St. Pierre & Miquelon Daylight Time=America/Miquelon\nPONT|Ponape Time=Pacific/Pohnpei Pacific/Ponape\nPST|Northwest Mexico Standard Time|PDT|Northwest Mexico Daylight Time=America/Santa_Isabel\nPST|Pacific Standard Time|PDT|Pacific Daylight Time=America/Ensenada America/Los_Angeles America/Tijuana America/Vancouver Canada/Pacific Mexico/BajaNorte PST8PDT US/Pacific\nPST|Philippine Standard Time|PDT|Philippine Summer Time=Asia/Manila\nPST|Pitcairn Time=Pacific/Pitcairn\nPWT|Palau Time=Pacific/Palau\nPYT|Paraguay Standard Time|PYST|Paraguay Summer Time=America/Asuncion\nQOST|East Kazakhstan Time|QOSST|Kostanay Summer Time=Asia/Qostanay\nQYZT|West Kazakhstan Time|QYZST|Qyzylorda Summer Time=Asia/Qyzylorda\nRET|R\\xE9union Time=Indian/Reunion\nROTT|Rothera Time=Antarctica/Rothera\nSAKT|Sakhalin Standard Time|SAKST|Sakhalin Summer Time=Asia/Sakhalin\nSAMT|Samara Standard Time|SAMST|Samara Summer Time=Europe/Samara\nSAST|South Africa Standard Time|SAST|South Africa Summer Time=Africa/Johannesburg Africa/Maseru Africa/Mbabane\nSBT|Solomon Islands Time=Pacific/Guadalcanal\nSCT|Seychelles Time=Indian/Mahe\nSGT|Singapore Standard Time|SGST|Singapore Summer Time=Asia/Singapore Singapore\nSRET|Srednekolymsk Time|SREDT|Srednekolymsk Daylight Time=Asia/Srednekolymsk\nSRT|Suriname Time=America/Paramaribo\nSST|Samoa Standard Time=Pacific/Midway Pacific/Pago_Pago Pacific/Samoa US/Samoa\nSYOT|Syowa Time=Antarctica/Syowa\nTAHT|Tahiti Time=Pacific/Tahiti\nTFT|French Southern & Antarctic Time=Indian/Kerguelen\nTJT|Tajikistan Time|TJST|Tajikistan Summer Time=Asia/Dushanbe\nTKT|Tokelau Time=Pacific/Fakaofo\nTLT|East Timor Time=Asia/Dili\nTMT|Turkmenistan Standard Time|TMST|Turkmenistan Summer Time=Asia/Ashgabat Asia/Ashkhabad\nTOT|Tonga Standard Time|TOST|Tonga Summer Time=Pacific/Tongatapu\nTRT|Turkey Time|TRST|Turkey Summer Time=Asia/Istanbul Europe/Istanbul Turkey\nTVT|Tuvalu Time=Pacific/Funafuti\nULAT|Ulaanbaatar Standard Time|ULAST|Ulaanbaatar Summer Time=Asia/Ulaanbaatar Asia/Ulan_Bator\nUTC|Coordinated Universal Time=Etc/UCT Etc/UTC Etc/Universal Etc/Zulu UCT Universal Zulu\nUYT|Uruguay Standard Time|UYST|Uruguay Summer Time=America/Montevideo\nUZT|Uzbekistan Standard Time|UZST|Uzbekistan Summer Time=Asia/Samarkand Asia/Tashkent\nVET|Venezuela Time=America/Caracas\nVLAT|Vladivostok Standard Time|VLAST|Vladivostok Summer Time=Asia/Ust-Nera Asia/Vladivostok\nVOST|Vostok Time=Antarctica/Vostok\nVUT|Vanuatu Standard Time|VUST|Vanuatu Summer Time=Pacific/Efate\nWAKT|Wake Island Time=Pacific/Wake\nWAT|West Africa Standard Time=Africa/Bangui Africa/Brazzaville Africa/Douala Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Luanda Africa/Malabo Africa/Niamey Africa/Porto-Novo\nWAT|West Africa Standard Time|WAST|West Africa Summer Time=Africa/Ndjamena\nWET|Western European Standard Time|WEST|Western European Summer Time=Atlantic/Canary Atlantic/Faeroe Atlantic/Faroe Atlantic/Madeira Europe/Lisbon Portugal\nWET|Western European Time|WEST|Western European Summer Time=Africa/Casablanca Africa/El_Aaiun WET\nWFT|Wallis & Futuna Time=Pacific/Wallis\nWGT|West Greenland Standard Time|WGST|West Greenland Summer Time=America/Godthab America/Nuuk\nWIB|Western Indonesia Time=Asia/Jakarta Asia/Pontianak\nWIT|Eastern Indonesia Time=Asia/Jayapura\nWITA|Central Indonesia Time=Asia/Makassar Asia/Ujung_Pandang\nWSST|Apia Standard Time|WSDT|Apia Daylight Time=Pacific/Apia\nXJT|Xinjiang Standard Time=Asia/Kashgar Asia/Urumqi\nYAKT|Yakutsk Standard Time|YAKST|Yakutsk Summer Time=Asia/Chita Asia/Khandyga Asia/Yakutsk\nYEKT|Yekaterinburg Standard Time|YEKST|Yekaterinburg Summer Time=Asia/Yekaterinburg\n`,mA=`\nAfrica/Addis_Ababa Africa/Asmara Africa/Asmera Africa/Dar_es_Salaam Africa/Djibouti Africa/Kampala Africa/Mogadishu Africa/Nairobi Indian/Antananarivo Indian/Comoro Indian/Mayotte=-le7s00:-l4hs00\nAfrica/Casablanca=-fkuqo0:-cl6w40\nAfrica/Tunis=-fkt1k0:-f9hhc0 -f1kao0:-eqk5k0\nAfrica/Windhoek=ajtx40:cmzh40 ovois0:\nAmerica/Adak America/Atka America/Nome US/Aleutian=-ek1nw0:-cnomo0 6y2us0:77ss00\nAmerica/Anchorage US/Alaska=-ek1qo0:-cnopg0 6y2s00:77sp80\nAmerica/Anguilla America/Antigua America/Aruba America/Blanc-Sablon America/Curacao America/Dominica America/Grenada America/Guadeloupe America/Kralendijk America/Lower_Princes America/Marigot America/Montserrat America/Port_of_Spain America/Puerto_Rico America/St_Barthelemy America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Tortola America/Virgin=-efsnk0:-cnp640\nAmerica/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Buenos_Aires America/Catamarca America/Cordoba America/Jujuy America/Mendoza America/Rosario=-eq30w0:-eba000 -e6yg00:-dse500 -doj680:-cfvuc0 -c4vgw0:-39hec0\nAmerica/Belize=-ecwso0:-cjqks0\nAmerica/Boise America/Cambridge_Bay America/Denver America/Edmonton America/North_Dakota/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem America/Regina America/Shiprock America/Swift_Current America/Yellowknife Canada/Mountain Canada/Saskatchewan Navajo US/Mountain=-ek1z00:-cnoxs0\nAmerica/Chicago US/Central=-hnqf40:-haev80 -ek21s0:-cnp0k0\nAmerica/Coyhaique=-qs16wr:-qcwsw0 -c6kkw0:-bvifk0\nAmerica/Creston America/Phoenix US/Arizona=-ek1z00:-e3ctc0 -e0u2o0:-dkikmc\nAmerica/Dawson America/Whitehorse America/Yakutat Canada/Yukon=-ek1tg0:-cnos80\nAmerica/Dawson_Creek America/Fort_Nelson America/Los_Angeles America/Metlakatla America/Sitka US/Pacific=-ek1w80:-cnov00\nAmerica/Detroit America/New_York US/Eastern US/Michigan=-ek24k0:-cnp3c0\nAmerica/Ensenada America/Santa_Isabel America/Tijuana Mexico/BajaNorte=-oja5c0:-oik800 -eg90g0:-clbtw0\nAmerica/Fort_Wayne America/Indiana/Indianapolis America/Indiana/Marengo America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Kentucky/Monticello America/Menominee America/Rainy_River America/Winnipeg Canada/Central US/East-Indiana=-ek21s0:-cnp0k0\nAmerica/Glace_Bay America/Halifax America/Moncton Canada/Atlantic=-ek27c0:-cnp640\nAmerica/Goose_Bay America/St_Johns Canada/Newfoundland=-efdvm0:-cnp7i0\nAmerica/Indiana/Knox America/Knox_IN US/Indiana-Starke=-ek21s0:-cnp0k0 -3r1400:-3gy5c0\nAmerica/Indiana/Petersburg=-ek21s0:-cnp0k0 -26hxc0:-1wrxc0\nAmerica/Iqaluit America/Pangnirtung=-eb6ao0:-cnp3c0\nAmerica/Juneau=-ek1w80:-cnov00 5dweg0:5n9fs0\nAmerica/Kentucky/Louisville America/Louisville=-ek21s0:-cnp0k0 -4iy1s0:-4emkk0\nAmerica/Montevideo=-etxya0:-e482c0\nAmerica/Montreal America/Nassau America/Nipigon America/Thunder_Bay America/Toronto Canada/Eastern=-fhlj80:-cnp3c0\nAmerica/Punta_Arenas=-qs16wr:-qcwsw0 -c6kkw0:-bvifk0 ohmt80:ohn4c0\nAmerica/Santiago Chile/Continental=-qs16wr:-qcwsw0 -c6kno0:-bvifk0\nAmerica/Vancouver Canada/Pacific=-ek1w80:-cnov00 tntfo0:\nAntarctica/McMurdo Antarctica/South_Pole NZ Pacific/Auckland=-f9pme0:-ciy9c0\nAntarctica/Palmer=-2lxhc0:-2ivzo0\nArctic/Longyearbyen Atlantic/Jan_Mayen Europe/Berlin Europe/Bratislava Europe/Copenhagen Europe/Oslo Europe/Prague Europe/Stockholm Europe/Vienna=-fizzw0:-e6dzw0\nAsia/Aqtau=64qao0:6e2vc0 b34ac0:bcheg0\nAsia/Aqtobe Asia/Qyzylorda=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 b34ac0:bcheg0\nAsia/Ashgabat Asia/Ashkhabad Asia/Yekaterinburg=b34ac0:bcheg0\nAsia/Atyrau=64qao0:6e2vc0 b34ac0:bcheg0 f99uc0:fkfrs0 hv9940:i6f3s0\nAsia/Barnaul=b344s0:bch8w0 d98v40:dfdjk0\nAsia/Bishkek=b347k0:bazjk0 idzae0:il2ko0\nAsia/Calcutta Asia/Karachi Asia/Kolkata=-e9lba0:-cmya20\nAsia/Chongqing Asia/Chungking Asia/Harbin Asia/Shanghai PRC=-ekjy80:-cp63o0\nAsia/Colombo=-elvwm0:-cmw9u0\nAsia/Dacca Asia/Dhaka=-eqtpow:-ef78q0\nAsia/Dushanbe=b347k0:bbgac0\nAsia/Famagusta=ofoio0:onyo00\nAsia/Gaza Asia/Hebron Asia/Jerusalem Asia/Tel_Aviv Israel=-f765c0:-epbk00 -envpc0:-e6fxc0\nAsia/Ho_Chi_Minh Asia/Saigon=-cxyro0:-cp63o0\nAsia/Hong_Kong Hongkong=-eqtn80:-emgia0\nAsia/Istanbul Europe/Istanbul Turkey=-ehgdk0:-cnaz00 -3wa5k0:-3r1400 -3czk00:-3805o0\nAsia/Jakarta Asia/Pontianak=-asj1c0:-art400\nAsia/Kuala_Lumpur Asia/Singapore Singapore=-jb6gs0:-hquppc\nAsia/Manila=-emx4w0:-ejxt00 -cyj500:-ckjfo0\nAsia/Oral=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 a1b6c0:aaoag0 bi8t40:blud00 hv9940:i6f3s0\nAsia/Qostanay=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0 b34ac0:bcheg0 hv96c0:i6f100\nAsia/Samarkand=5vb0s0:64pu00 64qao0:6e2vc0 6egao0:6nhrc0\nAsia/Tomsk=b344s0:bch8w0 gvea40:h4lu80\nAtlantic/Azores=-1yevk0:-1p1u80\nAtlantic/Cape_Verde=-e9kqg0:-cmxp80\nAtlantic/Madeira=-1yeyc0:-1p1x00\nCET Europe/Amsterdam Europe/Brussels Europe/Luxembourg MET=-fkul40:-e6dzw0\nEET Europe/Athens=-eyqoc0:-e6dzw0\nEurope/Astrakhan=a1b940:aaod80 bcc000:blufs0\nEurope/Belgrade Europe/Ljubljana Europe/Podgorica Europe/Sarajevo Europe/Skopje Europe/Zagreb=-ezayw0:-epbk00 -efyio0:-e6dzw0\nEurope/Budapest=-ezvc80:-epbk00 -egog00:-e6dzw0\nEurope/Chisinau Europe/Tiraspol=-euq8c0:-e6dzw0 -dfqqk0:-d8e5k0\nEurope/Gibraltar=-fkul40:-eyiyk0 -ethh80:-eh8qk0 -earek0:-dyinw0 -drod80:-dfsl80 -d75h80:-cx0nw0 -cro2k0:-cncfs0\nEurope/Guernsey Europe/Isle_of_Man Europe/Jersey=-fkul40:-eyiyk0 -ethh80:-eh8qk0 -earek0:-dyinw0 -drod80:-dfsl80 -d75h80:-cx0nw0 -cro2k0:-cncfs0 -z4ns0:-m6840\nEurope/Kaliningrad=-fizzw0:-e6dzw0 -cx0nw0:-cwm2w0\nEurope/Kiev Europe/Kyiv Europe/Uzhgorod Europe/Zaporozhye=-erdv00:-e6dzw0\nEurope/Kirov=a1b940:aaod80 bcc000:blufs0 bmeyo0:bv7jw0\nEurope/Lisbon Portugal WET=-1yf140:-1p1zs0\nEurope/Madrid=-gki5g0:-gj2dk0 -gb3c80:-gaxmo0 -g17mo0:-fs2000\nEurope/Malta Europe/Rome Europe/San_Marino Europe/Vatican=-ff59g0:-e6dzw0\nEurope/Minsk=-evpf00:-e6dzw0 -dfqqk0:-db2g80\nEurope/Monaco Europe/Paris=-fkul40:-e6dzw0 -d62qs0:-cx0nw0\nEurope/Riga=-fciw80:-e6dzw0\nEurope/Saratov=9il6g0:9ryak0 bcc000:blufs0\nEurope/Simferopol=-ep8300:-e6dzw0 -dfqqk0:-df8g80\nEurope/Tallinn=-fakdc0:-eta5c0 -ern4c0:-e6dzw0 -dfqqk0:-d6wg80\nEurope/Tirane=-ff3es0:-e6dzw0\nEurope/Ulyanovsk=a1b940:aaod80 b34fw0:bchk00\nEurope/Vilnius=-ptj1g0:-poyaw0 -fcmis0:-e6dzw0 -dfqqk0:-d9kqw0\nEurope/Warsaw Poland=-qznjw0:-qrqd80 -feqak0:-e6dzw0\nPacific/Guam Pacific/Saipan=-5hlkw0:-56itc0 -4y8o00:-4nnvo0 -17w8w0:-10d9c0 -ohhc0:-hih6c\nPacific/Honolulu Pacific/Johnston US/Hawaii=-ek1pa0:-cnoo20\n`,yA="yyyy-MM-dd\'T\'HH:mm:ssZ",$a="str.format_time",za=864e5,zu=7*za,Vf=-141427,bs=-22089888e5,gA=21143808e5,_A=18*3600,bA=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],xA=["January","February","March","April","May","June","July","August","September","October","November","December"],vA=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wA=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],SA="GyMdkHmsSEDFwWahKzZYuXL",Dp=["GMT","Greenwich Mean Time"],EA=["UTC","Coordinated Universal Time"],kA=/^(?:GMT|UT)([+-])(?:(\\d{1,2})(?::?(\\d{2}))?|(\\d{2}):(\\d{2}):(\\d{2})|(\\d{2})(\\d{2})(\\d{2}))$/,Cr=(t,e)=>String(t).padStart(e,"0"),ca=(t,e)=>(t%e+e)%e,ft=(t,e)=>t<0?"-"+Cr(-t,e):Cr(t,e),Op=t=>(t<0?"-":"")+Cr(Math.abs(t)%100,2),Rp=t=>new fe(`Invalid \\`format\\` value for the ${$a}() function: \\`${t}\\`.`,$a),AA=t=>new fe(`Incorrect \\`timezone\\` value for the ${$a}() function: "${t}". The value must be a string in either UTC/GMT notation (e.g. "UTC-5", "GMT+0530") or an IANA time zone database name (e.g. "America/New_York").`,$a),Ys=new Map;function TA(t){let e=Ys.get(t);if(e)return e;let n=[],r="",i=!1;for(let s=0;s<t.length;){let a=t[s];if(a==="\'"){t[s+1]==="\'"?(r+="\'",s+=2):(i=!i,s++);continue}if(!i&&(a>="a"&&a<="z"||a>="A"&&a<="Z")){let o=1;for(;t[s+o]===a;)o++;if(!SA.includes(a)||a==="X"&&o>3)throw Rp(t);r&&n.push(r),r="",n.push({letter:a,count:o}),s+=o;continue}r+=a,s++}if(i)throw Rp(t);return r&&n.push(r),Ys.size>=256&&Ys.clear(),Ys.set(t,n),n}var Xs=null;function NA(t){if(!Xs){Xs=new Map;for(let e of fA.split(`\n`)){let n=e.indexOf("=");if(n<0)continue;let r=e.slice(0,n).split("|");for(let i of e.slice(n+1).split(" "))Xs.set(i,r)}}return Xs.get(t)}function $f(t){if(t==="Z")return{fixedMs:0,names:EA};let e=t.startsWith("UTC")?"GMT"+t.slice(3):t;if(e==="GMT"||e==="UT")return{fixedMs:0,names:Dp};let n=NA(e);if(n)return{id:e,names:n};let r=kA.exec(e);if(!r)return null;let i=Number(r[2]??r[4]??r[7]),s=Number(r[3]??r[5]??r[8]??0),a=Number(r[6]??r[9]??0),o=i*3600+s*60+a;if(s>59||a>59||o>_A)return null;if(o===0)return{fixedMs:0,names:Dp};let l=`GMT${r[1]}${Cr(i,2)}:${Cr(s,2)}${a?":"+Cr(a,2):""}`;return{fixedMs:(r[1]==="-"?-1:1)*o*1e3,names:[l,l]}}var Zs=null;function CA(t,e){if(!Zs){Zs=new Map;for(let a of mA.split(`\n`)){let o=a.indexOf("=");if(o<0)continue;let l=a.slice(o+1).split(" ").flatMap(c=>c.split(":").map(u=>u?parseInt(u,36):1/0));for(let c of a.slice(0,o).split(" "))Zs.set(c,l)}}let n=Zs.get(t);if(!n)return!1;let r=Math.floor(e/1e3),i=0,s=n.length/2;for(;i<s;){let a=i+s>>1;n[2*a+1]<=r?i=a+1:s=a}return i<n.length/2&&n[2*i]<=r}var Lp=new Map,Fp=new Map,Bp=new Map,Vp=new Map,$p=new Map,zf={EST5EDT:-5,CST6CDT:-6,MST7MDT:-7,PST8PDT:-8},jf=Date.UTC(1967,0,1),IA=[[1918,3,31,1918,10,27],[1919,3,30,1919,10,26],[1942,2,9,1945,9,30]];function qf(t,e){return IA.some(([n,r,i,s,a,o])=>e>=Date.UTC(n,r-1,i,2)-t*36e5&&e<Date.UTC(s,a-1,o,2)-(t+1)*36e5)}function MA(t,e){let n=zf[t];if(n!==void 0&&e>=bs&&e<jf)return(n+(qf(n,e)?1:0))*36e5;if(e>=bs)return ja(t,e);let r=$p.get(t);if(r===void 0){let i=1/0,s=1/0;for(let a=0;a<53;a++){let o=gA+a*zu,l=ja(t,o);s=Math.min(s,l),Uf(t,o)||(i=Math.min(i,l))}r=i!==1/0?i:s-36e5,$p.set(t,r)}return r}function ja(t,e){let n=Math.max(e,bs),r=Lp.get(t);r||(r=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),Lp.set(t,r));let i={};for(let s of r.formatToParts(n))s.type!=="literal"&&(i[s.type]=Number(s.value));return Wf(i.year,i.month,i.day)*za+i.hour%24*36e5+i.minute*6e4+i.second*1e3-(n-ca(n,1e3))}function zp(t,e,n){let r=t.get(n);return r===void 0&&(r=ja(e,n*zu),t.set(n,r)),r}function PA(t,e){let n=Vp.get(t);n||Vp.set(t,n=new Map);let r=n.get(e);if(!r){let i=Bp.get(t);i||Bp.set(t,i=new Map);let s=1/0,a=1/0;for(let o=1;o<=53;o++)s=Math.min(s,zp(i,t,e-o)),a=Math.min(a,zp(i,t,e+o));n.set(e,r=[s,a])}return r}function Uf(t,e){if(e<bs)return!1;let n=zf[t];return n!==void 0&&e<jf?qf(n,e):DA(t,e)!==CA(t,e)}function DA(t,e){if(e<bs)return!1;let n=Fp.get(t);n||(n=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"long"}),Fp.set(t,n));let r=n.formatToParts(e).find(o=>o.type==="timeZoneName")?.value??"";if(/Daylight|Summer/.test(r)||r==="Irish Standard Time")return!0;if(!/^GMT([+-]|$)/.test(r))return!1;let[i,s]=PA(t,Math.floor(e/zu)),a=ja(t,e);return a>i&&a>s}function Wf(t,e,n){t-=e<=2?1:0;let r=Math.floor(t/400),i=t-r*400,s=Math.floor((153*(e+(e>2?-3:9))+2)/5)+n-1;return r*146097+i*365+Math.floor(i/4)-Math.floor(i/100)+s-719468}function OA(t){let e=t+719468,n=Math.floor(e/146097),r=e-n*146097,i=Math.floor((r-Math.floor(r/1460)+Math.floor(r/36524)-Math.floor(r/146096))/365),s=r-(365*i+Math.floor(i/4)-Math.floor(i/100)),a=Math.floor((5*s+2)/153),o=s-Math.floor((153*a+2)/5)+1,l=a<10?a+3:a-9;return[i+n*400+(l<=2?1:0),l,o]}function RA(t,e,n){let r=Math.floor((14-e)/12),i=t+4800-r,s=e+12*r-3;return n+Math.floor((153*s+2)/5)+365*i+Math.floor(i/4)-32083-2440588}function LA(t){let e=t+2440588+32082,n=Math.floor((4*e+3)/1461),r=e-Math.floor(1461*n/4),i=Math.floor((5*r+2)/153);return[n-4800+Math.floor(i/10),i+3-12*Math.floor(i/10),r-Math.floor((153*i+2)/5)+1]}function dl(t,e,n){let r=Wf(t,e,n);return r>=Vf?r:RA(t,e,n)}function jp(t,e,n){let r=TA(e),i=$f(n);if(!i)throw AA(n);let s=Math.floor(t),a=i.fixedMs??0,o=i.id;if(o)try{a=MA(o,s)}catch{o=void 0}let l=s+a,c=Math.floor(l/za),u=l-c*za,[h,p,d]=c>=Vf?OA(c):LA(c),f=ca(c+4,7),m=Math.floor(u/36e5),y="";for(let g of r){if(typeof g=="string"){y+=g;continue}let{letter:w,count:k}=g;switch(w){case"G":y+=h>0?"AD":"BC";break;case"y":{let S=h>0?h:1-h;y+=k===2?Op(S):ft(S,k);break}case"Y":case"w":{let S=dl(h,1,1),E=c+(6-f)>=dl(h+1,1,1);w==="w"?y+=ft(E?1:Math.floor((c-S+ca(S+4,7))/7)+1,k):y+=k===2?Op(E?h+1:h):ft(E?h+1:h,k);break}case"M":case"L":y+=k>=4?xA[p-1]:k===3?bA[p-1]:ft(p,k);break;case"W":{let S=c-(d-1);y+=ft(Math.floor((d-1+ca(S+4,7))/7)+1,k);break}case"D":y+=ft(c-dl(h,1,1)+1,k);break;case"d":y+=ft(d,k);break;case"F":y+=ft(Math.floor((d-1)/7)+1,k);break;case"E":y+=k>=4?wA[f]:vA[f];break;case"u":y+=ft(f===0?7:f,k);break;case"a":y+=m<12?"AM":"PM";break;case"H":y+=ft(m,k);break;case"k":y+=ft(m===0?24:m,k);break;case"K":y+=ft(m%12,k);break;case"h":y+=ft(m%12===0?12:m%12,k);break;case"m":y+=ft(Math.floor(u/6e4)%60,k);break;case"s":y+=ft(Math.floor(u/1e3)%60,k);break;case"S":y+=ft(u%1e3,k);break;case"z":{let S=o!==void 0&&i.names.length>2&&Uf(o,s);y+=i.names[(S?2:0)+(k>=4?1:0)];break}case"Z":case"X":{let S=Math.trunc(a/6e4);if(w==="X"&&S===0){y+="Z";break}let E=S<0?"-":"+",T=Cr(Math.floor(Math.abs(S)/60),2),N=Cr(Math.abs(S)%60,2);y+=E+T+(w==="Z"||k===2?N:k===3?":"+N:"");break}}}return y}var FA=["time","format","timezone"],BA=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype;function VA(t,e){let n={};t.forEach((r,i)=>{BA(r)?Object.assign(n,r):i<e.length&&(n[e[i]]=r)});for(let r in n)n[r]instanceof _&&(n[r]=n[r].get(0));return n}var Hf={"":"#,##0.###",integer:"#,##0",percent:"#,##0%",currency:"$#,##0.00"},Gf=t=>t==null||typeof t=="number"&&Number.isNaN(t),ke=t=>Gf(t)?"":String(t),$A=/^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)$/;function zA(t){return typeof t=="number"?Number.isNaN(t)?"NaN":bi(t,Hf[""],"halfEven"):t instanceof Q?"["+Yd(t).join(", ")+"]":String(t)}var oc=class{constructor(e){this.context=e}param(e,n=0,r){return _.from(e).get(n)}tostring(e,n){if(typeof e!="number")return typeof e=="string"?e:String(e);if(!n)return Gd(e);if(n==="mintick"){let r=this.context.pine?.syminfo?.mintick||.01,i=Math.max(0,-Math.floor(Math.log10(r)));return bi(e,i?"0."+"0".repeat(i):"0","halfUp")}return n==="percent"?bi(e,"0.00","halfUp")+"%":n==="volume"?P_(e):bi(e,n,"halfUp")}tonumber(e){let n=ke(e).replace(/^[\\u0000-\\u0020]+|[\\u0000-\\u0020]+$/g,"");return $A.test(n)?Number(n):NaN}lower(e){return ke(e).toLowerCase()}upper(e){return ke(e).toUpperCase()}trim(e){return ke(e).trim()}repeat(e,n,r=""){let i=typeof n=="number"&&n>0?Math.floor(n):0;return jt(i*(ke(e).length+ke(r).length),"str.repeat"),Array(n).fill(ke(e)).join(ke(r))}replace_all(e,n,r){return ke(e).replaceAll(ke(n),ke(r))}replace(e,n,r,i=0){let s=ke(e),a=ke(n),o=ke(r),l=Math.floor(Number(i))||0;if(a==="")return s;let c=0,u=0;for(;;){let h=s.indexOf(a,c);if(h===-1)return s;if(u===l)return s.substring(0,h)+o+s.substring(h+a.length);u++,c=h+a.length}}contains(e,n){return ke(e).includes(ke(n))}endswith(e,n){return ke(e).endsWith(ke(n))}startswith(e,n){return ke(e).startsWith(ke(n))}pos(e,n){let r=ke(e).indexOf(ke(n));return r===-1?NaN:r}length(e){return ke(e).length}match(e,n){let r=ke(e).match(new RegExp(ke(n)));return r?r[0]:""}split(e,n){return new Q(ke(e).split(ke(n)),Z.string,this.context)}substring(e,n,r){return ke(e).substring(n,r)}format_time(...e){let{time:n,format:r,timezone:i}=VA(e,FA),s=Gf(n)?0:Number(n),a=r===void 0?yA:ke(r);if(i!==void 0)return jp(s,a,ke(i));let o=this.context.pine?.syminfo?.timezone;return jp(s,a,o&&$f(o)?o:"UTC")}format(e,...n){let r=ke(e),i="",s=!1,a=0;for(;a<r.length;){let o=r[a];if(o==="\'"){r[a+1]==="\'"?(i+="\'",a+=2):(s=!s,a++);continue}if(o!=="{"||s){i+=o,a++;continue}let l=["","",""],c=0,u=0,h=!1,p=a+1;for(;p<r.length;p++){let d=r[p];if(h)l[c]+=d,d==="\'"&&(h=!1);else if(d===","&&c<2)c++;else if(d==="{")u++,l[c]+=d;else if(d==="}"){if(u===0)break;u--,l[c]+=d}else d===" "?(c!==1||l[1].length>0)&&(l[c]+=d):(d==="\'"&&(h=!0),l[c]+=d)}if(p>=r.length)throw new Error("Unmatched braces in the pattern.");i+=this._formatArgument(l,r.slice(a,p+1),n),a=p+1}return i}_formatArgument([e,n,r],i,s){if(!/^[+-]?\\d+$/.test(e))throw new Error(`can\'t parse argument number: ${e}`);let a=Number(e);if(a<0)throw new Error(`negative argument number: ${e}`);let o=n.trim().toLowerCase();if(o!==""&&o!=="number"){if(o==="date"||o==="time"||o==="choice")return i;throw new Error(`unknown format type: ${n}`)}if(a>=s.length||s[a]===void 0)return`{${a}}`;let l=s[a];return o===""||typeof l!="number"?zA(l):Number.isNaN(l)?"NaN":bi(l,Hf[r.trim().toLowerCase()]??r,"halfEven")}},jA=Object.defineProperty,qA=(t,e,n)=>e in t?jA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,UA=(t,e,n)=>qA(t,typeof e!="symbol"?e+"":e,n),qp=t=>typeof t=="function"?t():t instanceof _?t.get(0):t,lc=class{constructor(e){this.context=e,UA(this,"_chart")}param(e,n=0,r){return _.from(e).get(n)}get chart(){return this._chart===void 0&&(this._chart=pt(this.context.timeframe)),this._chart}resolve(e,n,r){let i=qp(e);if(i==null||i===""||typeof i=="number"&&isNaN(i))return this.chart??{unit:"D",multiplier:1};let s=pt(i);if(!s)throw new fe(r(String(i)),n);return s}get periodString(){let e=this.chart;return e?Ni(e,this.context.pineVersion>=6):this.context.timeframe}get main_period(){return this.periodString}get period(){return this.periodString}get multiplier(){return this.chart?.multiplier??1}get isdwm(){let e=this.chart?.unit;return e==="D"||e==="W"||e==="M"}get isdaily(){return this.chart?.unit==="D"}get isweekly(){return this.chart?.unit==="W"}get ismonthly(){return this.chart?.unit==="M"}get isticks(){return!1}get isseconds(){return this.chart?.unit==="S"}get isminutes(){return this.chart?.unit===""}get isintraday(){return!this.isdwm}change(e){let n=this.resolve(e,"timeframe.change",o=>`Cannot parse resolution \'${o}\'. - Invalid format`),r=_.from(this.context.data.openTime).get(0),i=_.from(this.context.data.openTime).get(1);if(isNaN(r)||isNaN(i))return!1;let s=this.context.pine?.syminfo,a=s?.timezone||"UTC";return Ll(r,n,a,s?.session)!==Ll(i,n,a,s?.session)}from_seconds(e){let n=qp(e);return n==null||isNaN(n)?NaN:Xx(n)}in_seconds(e){let n=this.resolve(e,"timeframe.in_seconds",r=>`Invalid value of the \'period\' argument (\'${r}\') in the \'timeframe.in_seconds()\' function.`);return Vt(n)}},WA=Object.defineProperty,HA=Object.getOwnPropertyDescriptor,Ln=(t,e,n,r)=>{for(var i=r>1?void 0:r?HA(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&WA(e,n,i),i},GA=["series","title","color","linewidth","style","trackprice","histbase","offset","join","editable","show_last","display","format","precision","force_overlay","linestyle"],KA=["series","title","char","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],YA={series:"series",title:"string",char:"string",location:"string",color:"color",offset:"number",text:"string",textcolor:"color",editable:"boolean",size:"string",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},XA=["series","title","style","location","color","offset","text","textcolor","editable","size","show_last","display","format","precision","force_overlay"],ZA=["series","title","colorup","colordown","offset","minheight","maxheight","editable","show_last","display","format","precision","force_overlay"],JA=["open","high","low","close","title","color","editable","show_last","display","format","precision","force_overlay"],QA=["open","high","low","close","title","color","wickcolor","editable","show_last","bordercolor","display","format","precision","force_overlay"],Up=["color","offset","editable","show_last","title","display","force_overlay"],eT=["price","title","color","linestyle","linewidth","editable","display"],tT=["plot1","plot2","color","title","editable","show_last","fillgaps","display"],nT=["plot1","plot2","color","title","editable","fillgaps","display"],rT=["plot1","plot2","top_value","bottom_value","top_color","bottom_color","title","display","fillgaps","editable"],iT={plot1:"object",plot2:"object",top_value:"number",bottom_value:"number",top_color:"color",bottom_color:"color",title:"string",display:"string",fillgaps:"boolean",editable:"boolean"},sT=["top_value","bottom_value","top_color","bottom_color"],aT={series:"series",title:"string",color:"color",linewidth:"number",style:"string",trackprice:"boolean",histbase:"number",offset:"number",join:"boolean",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean",linestyle:"string"},oT={series:"series",title:"string",style:"string",location:"string",color:"color",offset:"number",text:"string",textcolor:"color",editable:"boolean",size:"string",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},lT={series:"series",title:"string",colorup:"color",colordown:"color",offset:"number",minheight:"number",maxheight:"number",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},cT={open:"series",high:"series",low:"series",close:"series",title:"string",color:"color",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},uT={open:"series",high:"series",low:"series",close:"series",title:"string",color:"color",wickcolor:"color",bordercolor:"color",editable:"boolean",show_last:"number",display:"string",format:"string",precision:"number",force_overlay:"boolean"},Wp={color:"color",offset:"number",editable:"boolean",show_last:"number",title:"string",display:"string",force_overlay:"boolean"},hT={price:"series",title:"string",color:"color",linestyle:"string",linewidth:"number",editable:"boolean",display:"string"},pT={plot1:"object",plot2:"object",color:"color",title:"string",editable:"boolean",show_last:"number",fillgaps:"boolean",display:"string"},Sn=class{constructor(e){this.context=e}_resolvePlotKey(e,n){if(e){let r=this.context.plots[e];return!r||!n||r._callsiteId===n?e:e+n}return n||"plot"}extractPlotOptions(e){let n={};for(let r in e)n[r]=_.from(e[r]).get(0);return n}get linestyle_dashed(){return"linestyle_dashed"}get linestyle_dotted(){return"linestyle_dotted"}get linestyle_solid(){return"linestyle_solid"}get style_area(){return"style_area"}get style_areabr(){return"style_areabr"}get style_circles(){return"style_circles"}get style_columns(){return"style_columns"}get style_cross(){return"style_cross"}get style_histogram(){return"style_histogram"}get style_line(){return"style_line"}get style_linebr(){return"style_linebr"}get style_stepline(){return"style_stepline"}get style_stepline_diamond(){return"style_stepline_diamond"}get style_steplinebr(){return"style_steplinebr"}param(e,n=0,r){return _.from(e).get(n)}plotchar(...e){let n=cn(e),r=Te(e,KA,YA),{series:i,title:s,...a}=r,o=this.extractPlotOptions(a),l=this._resolvePlotKey(s,n);this.context.plots[l]||(this.context.plots[l]={data:[],options:{...o,style:"char"},title:s,_plotKey:l,_callsiteId:n});let c=_.from(i).get(0);return this.context.plots[l].data.push({title:s,time:this.context.marketData[this.context.idx].openTime,value:c,options:{char:o.char,color:o.color,textcolor:o.textcolor,location:o.location,size:o.size,offset:o.offset}}),this.context.plots[l]}any(...e){let n=cn(e),r=Te(e,GA,aT),{series:i,title:s,...a}=r,o=this.extractPlotOptions(a),l=this._resolvePlotKey(s,n),c="color"in a;if(!this.context.plots[l]){let d=o.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[l]={data:[],options:{...o,overlay:d},title:s,_plotKey:l,_callsiteId:n}}let u=_.from(i).get(0),h=o.color;typeof h=="function"&&(h=h());let p={color:c?typeof h=="string"?h:void 0:h||"#2962ff"};return"offset"in a&&(p.offset=o.offset),this.context.plots[l].data.push({title:s,time:this.context.marketData[this.context.idx].openTime,value:u,options:p}),this.context.plots[l]}plotshape(...e){let n=cn(e),r=Te(e,XA,oT),{series:i,title:s,...a}=r,o=this.extractPlotOptions(a),l=this._resolvePlotKey(s,n);if(!this.context.plots[l]){let u=o.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[l]={data:[],options:{...o,style:"shape",shape:o.style,overlay:u},title:s,_plotKey:l,_callsiteId:n}}let c=_.from(i).get(0);return this.context.plots[l].data.push({title:s,time:this.context.marketData[this.context.idx].openTime,value:c,options:o?.location==="absolute"||c?{text:o.text,textcolor:o.textcolor,color:o.color,offset:o.offset,shape:o.style,location:o.location,size:o.size}:void 0}),this.context.plots[l]}plotarrow(...e){let n=cn(e),r=Te(e,ZA,lT),{series:i,title:s,...a}=r,o=_.from(i).get(0),l=this.extractPlotOptions(a),c=this._resolvePlotKey(s,n);if(!this.context.plots[c]){let u=l.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[c]={data:[],options:{...l,style:"shape",overlay:u},title:s,_plotKey:c,_callsiteId:n}}return this.context.plots[c].data.push({title:s,time:this.context.marketData[this.context.idx].openTime,value:o,options:typeof o=="number"&&!isNaN(o)&&o!==0?{text:void 0,textcolor:void 0,color:o>0?l.colorup:l.colordown,offset:l.offset,shape:o>0?"shape_arrow_up":"shape_arrow_down",location:o>0?"BelowBar":"AboveBar",height:l.maxheight}:void 0}),this.context.plots[c]}plotbar(...e){let n=cn(e),r=Te(e,JA,cT),{open:i,high:s,low:a,close:o,title:l,...c}=r,u=this.extractPlotOptions(c),h=this._resolvePlotKey(l,n);if(!this.context.plots[h]){let d=u.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[h]={data:[],options:{...u,style:"bar",overlay:d},title:l,_plotKey:h,_callsiteId:n}}let p=[_.from(i).get(0),_.from(s).get(0),_.from(a).get(0),_.from(o).get(0)];this.context.plots[h].data.push({title:l,time:this.context.marketData[this.context.idx].openTime,value:p,options:{color:u.color}})}plotcandle(...e){let n=cn(e),r=Te(e,QA,uT),{open:i,high:s,low:a,close:o,title:l,...c}=r,u=this.extractPlotOptions(c),h=this._resolvePlotKey(l,n);if(!this.context.plots[h]){let d=u.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[h]={data:[],options:{...u,style:"candle",overlay:d},title:l,_plotKey:h,_callsiteId:n}}let p=[_.from(i).get(0),_.from(s).get(0),_.from(a).get(0),_.from(o).get(0)];return this.context.plots[h].data.push({title:l,time:this.context.marketData[this.context.idx].openTime,value:p,options:{color:u.color,wickcolor:u.wickcolor,bordercolor:u.bordercolor}}),this.context.plots[h]}bgcolor(...e){let n=cn(e),r=Te(e,Up,Wp),{title:i,...s}=r,a=this.extractPlotOptions(s),o=this._resolvePlotKey(i,n);if(!this.context.plots[o]){let l=a.force_overlay??(this.context?.indicator?.overlay||!1);this.context.plots[o]={data:[],options:{...a,style:"background",overlay:l},title:i,_plotKey:o,_callsiteId:n}}this.context.plots[o].data.push({title:i,time:this.context.marketData[this.context.idx].openTime,value:a.color&&a.color!=="na"&&a?.color.toString()!=="NaN",options:{color:a.color}})}barcolor(...e){let n=cn(e),r=Te(e,Up,Wp),{title:i,...s}=r,a=this.extractPlotOptions(s),o=this._resolvePlotKey(i,n);return this.context.plots[o]||(this.context.plots[o]={data:[],options:{...a,style:"barcolor"},title:i,_plotKey:o,_callsiteId:n}),this.context.plots[o].data.push({title:i,time:this.context.marketData[this.context.idx].openTime,value:a.color&&a.color!=="na"&&a?.color.toString()!=="NaN",options:{color:a.color}}),this.context.plots[o]}};Ln([R],Sn.prototype,"plotchar",1),Ln([R],Sn.prototype,"any",1),Ln([R],Sn.prototype,"plotshape",1),Ln([R],Sn.prototype,"plotarrow",1),Ln([R],Sn.prototype,"plotbar",1),Ln([R],Sn.prototype,"plotcandle",1),Ln([R],Sn.prototype,"bgcolor",1),Ln([R],Sn.prototype,"barcolor",1);var qa=class{constructor(e){this.context=e}get style_dashed(){return"dashed"}get style_solid(){return"solid"}get style_dotted(){return"dotted"}param(e,n=0,r){return _.from(e).get(n)}any(...e){let n=cn(e),r=Te(e,eT,hT),{price:i,title:s,color:a,linestyle:o,linewidth:l,editable:c,display:u}=r,h=[i,{title:s,color:a,linestyle:o,linewidth:l,editable:c,display:u,style:"hline"}];return n&&h.push({__callsiteId:n}),this.context.pine.plot.any(...h)}};Ln([R],qa.prototype,"any",1);var Ua=class{constructor(e){this.context=e}param(e,n=0,r){return _.from(e).get(n)}any(...e){let n=cn(e),r=e.length>0&&Jd(e[e.length-1])?e[e.length-1]:null,i=r?e.length-1:e.length;if(r&&("hline1"in r||"hline2"in r)){let{hline1:s,hline2:a,...o}=r;r={...o,...s!==void 0&&{plot1:s},...a!==void 0&&{plot2:a}},e=[...e.slice(0,-1),r]}if(r!==null&&sT.some(s=>s in r)||i>=4&&typeof e[2]=="number"&&typeof e[3]=="number"){let s=Te(e,rT,iT),{plot1:a,plot2:o,editable:l,fillgaps:c,display:u}=s,h=_.from(s.top_value).get(0),p=_.from(s.bottom_value).get(0),d=_.from(s.top_color).get(0),f=_.from(s.bottom_color).get(0),m=typeof s.title=="string"&&s.title?s.title:void 0,y=a?._plotKey||a?.title,g=o?._plotKey||o?.title,w=m||"fill",k=this.context.plots[w];k&&n&&k._callsiteId!==n&&(w=n),this.context.plots[w]||(this.context.plots[w]={title:m||"Fill",plot1:y,plot2:g,data:[],options:{plot1:y,plot2:g,editable:l,fillgaps:c,display:u,style:"fill",gradient:!0},_plotKey:w,_callsiteId:n}),this.context.plots[w].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{top_value:h,bottom_value:p,top_color:d,bottom_color:f}})}else{let s=_.from(r&&"plot1"in r?r.plot1:e[0]).get(0)?.options?.style==="hline"?nT:tT,a=Te(e,s,pT),{plot1:o,plot2:l,color:c,title:u,editable:h,show_last:p,fillgaps:d,display:f}=a,m=u||"fill",y=this.context.plots[m];y&&n&&y._callsiteId!==n&&(m=n);let g=_.from(c).get(0);if(!this.context.plots[m]){let w=o?._plotKey||o?.title,k=l?._plotKey||l?.title;this.context.plots[m]={title:u||"Fill",plot1:w,plot2:k,data:[],options:{plot1:w,plot2:k,color:g,editable:h,show_last:p,fillgaps:d,display:f,style:"fill"},_plotKey:m,_callsiteId:n}}this.context.plots[m].data.push({time:this.context.marketData[this.context.idx].openTime,value:null,options:{color:g}})}}};Ln([R],Ua.prototype,"any",1);var dT=Object.defineProperty,fT=(t,e,n)=>e in t?dT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mT=(t,e,n)=>fT(t,typeof e!="symbol"?e+"":e,n),cc=class{constructor(e){this.context=e,mT(this,"point");let n=this.context,r=i=>i==null?i:typeof i=="object"&&Array.isArray(i.data)&&typeof i.get=="function"?i.get(0):typeof i=="function"?i():i;this.point={new(i,s,a){return new vt(r(i),r(s),r(a)??NaN)},from_index(i,s){return new vt(void 0,r(i),r(s))},from_time(i,s){return new vt(r(i),void 0,r(s))},copy(i){return i.copy()},now(i){let s=n.idx,a=n.marketData[s]?.openTime;return new vt(a,s,r(i))}}}param(e,n=0,r){return _.from(e).get(n)}bg_color(){return"#1e293b"}fg_color(){return"#d1d4dc"}is_standard(){let e=this.context?.chartStyle;return e==null||e==="standard"}is_heikinashi(){return this.context?.chartStyle==="heikinashi"}is_kagi(){return!1}is_linebreak(){return!1}is_pnf(){return!1}is_range(){return!1}is_renko(){return!1}},yT=Object.defineProperty,gT=(t,e,n)=>e in t?yT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,at=(t,e,n)=>gT(t,typeof e!="symbol"?e+"":e,n),_T=0,Ei=class t{constructor(e,n,r="",i="bi",s="pr",a="",o="style_label_down",l="",c="normal",u="center",h="",p="default",d=!1,f="none"){at(this,"id"),at(this,"x"),at(this,"y"),at(this,"text"),at(this,"xloc"),at(this,"yloc"),at(this,"color"),at(this,"style"),at(this,"textcolor"),at(this,"size"),at(this,"textalign"),at(this,"tooltip"),at(this,"text_font_family"),at(this,"force_overlay"),at(this,"text_formatting"),at(this,"_deleted"),at(this,"_helper"),at(this,"_createdAtBar",-1),this.id=_T++,this.x=e,this.y=n,this.text=r,this.xloc=i,this.yloc=s,this.color=a,this.style=o,this.textcolor=l,this.size=c,this.textalign=u,this.tooltip=h,this.text_font_family=p,this.force_overlay=d,this.text_formatting=f,this._deleted=!1,this._helper=null}set_x(e){this._helper?this._helper.set_x(this,e):this._deleted||(this.x=e)}set_y(e){this._helper?this._helper.set_y(this,e):this._deleted||(this.y=e)}set_xy(e,n){this._helper?this._helper.set_xy(this,e,n):this._deleted||(this.x=e,this.y=n)}set_text(e){this._helper?this._helper.set_text(this,e):this._deleted||(this.text=e)}set_color(e){this._helper?this._helper.set_color(this,e):this._deleted||(this.color=e)}set_textcolor(e){this._helper?this._helper.set_textcolor(this,e):this._deleted||(this.textcolor=e)}set_size(e){this._helper?this._helper.set_size(this,e):this._deleted||(this.size=e)}set_style(e){this._helper?this._helper.set_style(this,e):this._deleted||(this.style=e)}set_textalign(e){this._helper?this._helper.set_textalign(this,e):this._deleted||(this.textalign=e)}set_tooltip(e){this._helper?this._helper.set_tooltip(this,e):this._deleted||(this.tooltip=e)}set_xloc(e,n){this._helper?this._helper.set_xloc(this,e,n):this._deleted||(this.x=e,this.xloc=n)}set_yloc(e){this._helper?this._helper.set_yloc(this,e):this._deleted||(this.yloc=e)}set_point(e){this._helper&&this._helper.set_point(this,e)}set_text_font_family(e){this._helper?this._helper.set_text_font_family(this,e):this._deleted||(this.text_font_family=e)}set_text_formatting(e){this._helper?this._helper.set_text_formatting(this,e):this._deleted||(this.text_formatting=e)}get_x(){return this._deleted?NaN:this.x}get_y(){return this._deleted?NaN:this.y}get_text(){return this._deleted?"":this.text}delete(){this._deleted=!0}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new t(this.x,this.y,this.text,this.xloc,this.yloc,this.color,this.style,this.textcolor,this.size,this.textalign,this.tooltip,this.text_font_family,this.force_overlay,this.text_formatting)}toPlotData(){return{id:this.id,x:this.x,y:this.y,text:this.text,xloc:this.xloc,yloc:this.yloc,color:this.color,style:this.style,textcolor:this.textcolor,size:this.size,textalign:this.textalign,tooltip:this.tooltip,text_font_family:this.text_font_family,force_overlay:this.force_overlay,text_formatting:this.text_formatting,_deleted:this._deleted}}},Js=t=>t!=null&&!(typeof t=="number"&&isNaN(t));function Wa(t,e){return e==="bt"?{x:Js(t.time)?t.time:NaN,xloc:e}:e==="bi"?{x:Js(t.index)?t.index:NaN,xloc:e}:Js(t.index)?{x:t.index,xloc:"bi"}:Js(t.time)?{x:t.time,xloc:"bt"}:{x:0,xloc:"bi"}}var Kf=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,xT=(t,e,n)=>e in t?Kf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ot=(t,e,n,r)=>{for(var i=r>1?void 0:r?bT(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Kf(e,n,i),i},vT=(t,e,n)=>xT(t,typeof e!="symbol"?e+"":e,n),wT=[["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay","text_formatting"],["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay","text_formatting"]],ST={x:"number",y:"number",text:"string",xloc:"string",yloc:"string",color:"color",style:"string",textcolor:"color",size:"size",textalign:"string",tooltip:"string",text_font_family:"string",force_overlay:"boolean",point:"point",text_formatting:"string"},Ze=class{constructor(e){this.context=e,vT(this,"_labels",[])}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__labels__||(this.context.plots.__labels__={title:"__labels__",data:[],options:{style:"label",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._labels=this._labels.filter(s=>!s._deleted);let n=this._labels.map(s=>s.toPlotData()),r=n.filter(s=>!s.force_overlay),i=n.filter(s=>s.force_overlay);this.context.plots.__labels__.data=[{time:e,value:r,options:{style:"label"}}],i.length>0?this.context.plots.__labels_overlay__={title:"__labels_overlay__",data:[{time:e,value:i,options:{style:"label"}}],options:{style:"label",overlay:!0}}:delete this.context.plots.__labels_overlay__}_resolve(e){if(e==null)return e;if(e instanceof $t)return null;if(typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"){let n=e.get(0);return typeof n=="number"&&isNaN(n)?null:n}return typeof e=="function"?e():typeof e=="number"&&isNaN(e)?null:e}_createLabel(e,n,r="",i="bi",s="pr",a="",o="style_label_down",l="",c="normal",u="center",h="",p="default",d=!1,f="none"){let m=new Ei(e,n,this._resolve(r),this._resolve(i),this._resolve(s),this._resolve(a),this._resolve(o),this._resolve(l),this._resolve(c),this._resolve(u),this._resolve(h),this._resolve(p),d,this._resolve(f)||"none");return m._helper=this,m._createdAtBar=this.context.idx,this._labels.push(m),this._enforceMaxCount(),m}_enforceMaxCount(){let e=this.context.indicator?.max_labels_count??50,n=this._labels.filter(r=>!r._deleted);if(n.length>e){let r=n.length-e,i=0;for(let s of this._labels){if(i>=r)break;s._deleted||(s._deleted=!0,i++)}}}new(...e){let n=Te(e,wT,ST),r,i,s=n.xloc;if(n.point instanceof vt){let a=n.point,o=Wa(a,s);r=o.x,s=s||o.xloc,i=a.price}else r=this._resolve(n.x),i=this._resolve(n.y);return this._createLabel(r,i,n.text,s,n.yloc,n.color,n.style,n.textcolor,n.size,n.textalign,n.tooltip,n.text_font_family,n.force_overlay,n.text_formatting)}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof $t||typeof n=="number"&&isNaN(n))return null;if(n instanceof Ei)return n;if(n instanceof _){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Ei)return r}return null}return this.new(...e)}set_x(e,n){e&&!e._deleted&&(e.x=n)}set_y(e,n){e&&!e._deleted&&(e.y=n)}set_xy(e,n,r){e&&!e._deleted&&(e.x=n,e.y=r)}set_text(e,n){e&&!e._deleted&&(e.text=n)}set_color(e,n){e&&!e._deleted&&(e.color=n)}set_textcolor(e,n){e&&!e._deleted&&(e.textcolor=n)}set_size(e,n){e&&!e._deleted&&(e.size=n)}set_style(e,n){e&&!e._deleted&&(e.style=n)}set_textalign(e,n){e&&!e._deleted&&(e.textalign=n)}set_tooltip(e,n){e&&!e._deleted&&(e.tooltip=n)}set_text_font_family(e,n){e&&!e._deleted&&(e.text_font_family=this._resolve(n))}set_text_formatting(e,n){e&&!e._deleted&&(e.text_formatting=this._resolve(n))}set_xloc(e,n,r){e&&!e._deleted&&(e.x=this._resolve(n),e.xloc=this._resolve(r))}set_yloc(e,n){e&&!e._deleted&&(e.yloc=n)}set_point(e,n){e&&!e._deleted&&n&&(e.x=Wa(n,e.xloc).x,e.y=n.price)}get_x(e){return e&&!e._deleted?e.x:NaN}get_y(e){return e&&!e._deleted?e.y:NaN}get_text(e){return e&&!e._deleted?e.text:""}copy(e){if(!e)return;let n=e._clone();return n._helper=this,n._createdAtBar=this.context.idx,this._labels.push(n),this._enforceMaxCount(),n}delete(e){e&&(e._deleted=!0)}get all(){return this._labels.filter(e=>!e._deleted)}rollbackFromBar(e){this._labels=this._labels.filter(n=>n._createdAtBar<e),this.syncToPlot()}get style_label_down(){return"style_label_down"}get style_label_up(){return"style_label_up"}get style_label_left(){return"style_label_left"}get style_label_right(){return"style_label_right"}get style_label_lower_left(){return"style_label_lower_left"}get style_label_lower_right(){return"style_label_lower_right"}get style_label_upper_left(){return"style_label_upper_left"}get style_label_upper_right(){return"style_label_upper_right"}get style_label_center(){return"style_label_center"}get style_circle(){return"style_circle"}get style_square(){return"style_square"}get style_diamond(){return"style_diamond"}get style_flag(){return"style_flag"}get style_arrowup(){return"style_arrowup"}get style_arrowdown(){return"style_arrowdown"}get style_cross(){return"style_cross"}get style_xcross(){return"style_xcross"}get style_triangleup(){return"style_triangleup"}get style_triangledown(){return"style_triangledown"}get style_none(){return"style_none"}get style_text_outline(){return"style_text_outline"}};ot([R],Ze.prototype,"new",1),ot([R],Ze.prototype,"set_x",1),ot([R],Ze.prototype,"set_y",1),ot([R],Ze.prototype,"set_xy",1),ot([R],Ze.prototype,"set_text",1),ot([R],Ze.prototype,"set_color",1),ot([R],Ze.prototype,"set_textcolor",1),ot([R],Ze.prototype,"set_size",1),ot([R],Ze.prototype,"set_style",1),ot([R],Ze.prototype,"set_textalign",1),ot([R],Ze.prototype,"set_tooltip",1),ot([R],Ze.prototype,"set_text_font_family",1),ot([R],Ze.prototype,"set_text_formatting",1),ot([R],Ze.prototype,"set_xloc",1),ot([R],Ze.prototype,"set_yloc",1),ot([R],Ze.prototype,"set_point",1),ot([R],Ze.prototype,"copy",1),ot([R],Ze.prototype,"delete",1);var ET=Object.defineProperty,kT=(t,e,n)=>e in t?ET(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Dt=(t,e,n)=>kT(t,typeof e!="symbol"?e+"":e,n),AT=0,Qn=class t{constructor(e,n,r,i,s="bi",a="none",o="",l="style_solid",c=1,u=!1){Dt(this,"id"),Dt(this,"x1"),Dt(this,"y1"),Dt(this,"x2"),Dt(this,"y2"),Dt(this,"xloc"),Dt(this,"extend"),Dt(this,"color"),Dt(this,"style"),Dt(this,"width"),Dt(this,"force_overlay"),Dt(this,"_deleted"),Dt(this,"_helper"),Dt(this,"_createdAtBar",-1),this.id=AT++,this.x1=e,this.y1=n,this.x2=r,this.y2=i,this.xloc=s,this.extend=a,this.color=o,this.style=l,this.width=c,this.force_overlay=u,this._deleted=!1,this._helper=null}set_x1(e){this._helper?this._helper.set_x1(this,e):this._deleted||(this.x1=e)}set_y1(e){this._helper?this._helper.set_y1(this,e):this._deleted||(this.y1=e)}set_x2(e){this._helper?this._helper.set_x2(this,e):this._deleted||(this.x2=e)}set_y2(e){this._helper?this._helper.set_y2(this,e):this._deleted||(this.y2=e)}set_xy1(e,n){this._helper?this._helper.set_xy1(this,e,n):this._deleted||(this.x1=e,this.y1=n)}set_xy2(e,n){this._helper?this._helper.set_xy2(this,e,n):this._deleted||(this.x2=e,this.y2=n)}set_color(e){this._helper?this._helper.set_color(this,e):this._deleted||(this.color=e)}set_width(e){this._helper?this._helper.set_width(this,e):this._deleted||(this.width=e)}set_style(e){this._helper?this._helper.set_style(this,e):this._deleted||(this.style=e)}set_extend(e){this._helper?this._helper.set_extend(this,e):this._deleted||(this.extend=e)}set_xloc(e,n,r){this._helper?this._helper.set_xloc(this,e,n,r):this._deleted||(this.x1=e,this.x2=n,this.xloc=r)}set_first_point(e){this._helper&&this._helper.set_first_point(this,e)}set_second_point(e){this._helper&&this._helper.set_second_point(this,e)}get_x1(){return this._deleted?NaN:this.x1}get_y1(){return this._deleted?NaN:this.y1}get_x2(){return this._deleted?NaN:this.x2}get_y2(){return this._deleted?NaN:this.y2}get_price(e){return this._helper?this._helper.get_price(this,e):NaN}delete(){this._helper?this._helper.delete(this):this._deleted=!0}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new t(this.x1,this.y1,this.x2,this.y2,this.xloc,this.extend,this.color,this.style,this.width,this.force_overlay)}toPlotData(){return{id:this.id,x1:this.x1,y1:this.y1,x2:this.x2,y2:this.y2,xloc:this.xloc,extend:this.extend,color:this.color,style:this.style,width:this.width,force_overlay:this.force_overlay,_deleted:this._deleted}}},Yf=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,NT=(t,e,n)=>e in t?Yf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mt=(t,e,n,r)=>{for(var i=r>1?void 0:r?TT(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Yf(e,n,i),i},Hp=(t,e,n)=>NT(t,typeof e!="symbol"?e+"":e,n),CT=[["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"],["first_point","second_point","xloc","extend","color","style","width","force_overlay"]],IT={x1:"number",y1:"number",x2:"number",y2:"number",xloc:"string",extend:"string",color:"color",style:"string",width:"number",force_overlay:"boolean",first_point:"point",second_point:"point"},nt=class{constructor(e){this.context=e,Hp(this,"_lines",[]),Hp(this,"linefills",null)}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__lines__||(this.context.plots.__lines__={title:"__lines__",data:[],options:{style:"drawing_line",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._lines=this._lines.filter(s=>!s._deleted);let n=this._lines.map(s=>s.toPlotData()),r=n.filter(s=>!s.force_overlay),i=n.filter(s=>s.force_overlay);this.context.plots.__lines__.data=[{time:e,value:r,options:{style:"drawing_line"}}],i.length>0?this.context.plots.__lines_overlay__={title:"__lines_overlay__",data:[{time:e,value:i,options:{style:"drawing_line"}}],options:{style:"drawing_line",overlay:!0}}:delete this.context.plots.__lines_overlay__}_resolvePoint(e,n){return Wa(e,n)}_resolve(e){return e==null?e:e instanceof $t?NaN:typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"?e.get(0):typeof e=="function"?e():e}_resolveColor(e){let n=this._resolve(e);return n==null?n:typeof n=="number"&&isNaN(n)?NaN:n}_createLine(e,n,r,i,s="bi",a="none",o="",l="style_solid",c=1,u=!1){let h=new Qn(e,n,r,i,s,this._resolve(a),this._resolveColor(o),this._resolve(l),this._resolve(c)||1,u);return h._helper=this,h._createdAtBar=this.context.idx,this._lines.push(h),this._enforceMaxCount(),h}_enforceMaxCount(){let e=this.context.indicator?.max_lines_count??50,n=this._lines.filter(r=>!r._deleted);if(n.length>e){let r=n.length-e,i=0;for(let s of this._lines){if(i>=r)break;s._deleted||(s._deleted=!0,i++)}}}new(...e){let n=Te(e,CT,IT),r,i,s,a,o=n.xloc;if(n.first_point instanceof vt){let l=n.first_point,c=n.second_point,u=this._resolvePoint(l,o);r=u.x,i=l.price,o=o||u.xloc,c instanceof vt?(s=this._resolvePoint(c,o).x,a=c.price):(s=0,a=NaN)}else r=this._resolve(n.x1),i=this._resolve(n.y1),s=this._resolve(n.x2),a=this._resolve(n.y2);return this._createLine(r,i,s,a,o,n.extend,n.color,n.style,n.width,n.force_overlay)}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof $t||typeof n=="number"&&isNaN(n))return null;if(n instanceof Qn)return n;if(n instanceof _){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Qn)return r}return null}return this.new(...e)}set_x1(e,n){e&&!e._deleted&&(e.x1=this._resolve(n))}set_y1(e,n){e&&!e._deleted&&(e.y1=this._resolve(n))}set_x2(e,n){e&&!e._deleted&&(e.x2=this._resolve(n))}set_y2(e,n){e&&!e._deleted&&(e.y2=this._resolve(n))}set_xy1(e,n,r){e&&!e._deleted&&(e.x1=this._resolve(n),e.y1=this._resolve(r))}set_xy2(e,n,r){e&&!e._deleted&&(e.x2=this._resolve(n),e.y2=this._resolve(r))}set_color(e,n){e&&!e._deleted&&(e.color=this._resolveColor(n))}set_width(e,n){e&&!e._deleted&&(e.width=this._resolve(n)||1)}set_style(e,n){e&&!e._deleted&&(e.style=this._resolve(n))}set_extend(e,n){e&&!e._deleted&&(e.extend=this._resolve(n))}set_xloc(e,n,r,i){e&&!e._deleted&&(e.x1=n,e.x2=r,e.xloc=i)}set_first_point(e,n){e&&!e._deleted&&n&&(e.x1=this._resolvePoint(n,e.xloc).x,e.y1=n.price)}set_second_point(e,n){e&&!e._deleted&&n&&(e.x2=this._resolvePoint(n,e.xloc).x,e.y2=n.price)}get_x1(e){return e&&!e._deleted?e.x1:NaN}get_y1(e){return e&&!e._deleted?e.y1:NaN}get_x2(e){return e&&!e._deleted?e.x2:NaN}get_y2(e){return e&&!e._deleted?e.y2:NaN}get_price(e,n){if(!e||e._deleted)return NaN;if(e.xloc!=="bi")return NaN;let r=e.x2-e.x1;return r===0?e.y1:e.y1+(n-e.x1)/r*(e.y2-e.y1)}copy(e){if(!e)return;let n=e._clone();return n._helper=this,n._createdAtBar=this.context.idx,this._lines.push(n),this._enforceMaxCount(),n}delete(e){e&&(e._deleted=!0,e instanceof Qn&&this.linefills?.deleteForLine(e))}get all(){return this._lines.filter(e=>!e._deleted)}rollbackFromBar(e){this._lines=this._lines.filter(n=>n._createdAtBar<e),this.syncToPlot()}get style_solid(){return"style_solid"}get style_dotted(){return"style_dotted"}get style_dashed(){return"style_dashed"}get style_arrow_left(){return"style_arrow_left"}get style_arrow_right(){return"style_arrow_right"}get style_arrow_both(){return"style_arrow_both"}};mt([R],nt.prototype,"new",1),mt([R],nt.prototype,"set_x1",1),mt([R],nt.prototype,"set_y1",1),mt([R],nt.prototype,"set_x2",1),mt([R],nt.prototype,"set_y2",1),mt([R],nt.prototype,"set_xy1",1),mt([R],nt.prototype,"set_xy2",1),mt([R],nt.prototype,"set_color",1),mt([R],nt.prototype,"set_width",1),mt([R],nt.prototype,"set_style",1),mt([R],nt.prototype,"set_extend",1),mt([R],nt.prototype,"set_xloc",1),mt([R],nt.prototype,"set_first_point",1),mt([R],nt.prototype,"set_second_point",1),mt([R],nt.prototype,"copy",1),mt([R],nt.prototype,"delete",1);var MT=Object.defineProperty,PT=(t,e,n)=>e in t?MT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qe=(t,e,n)=>PT(t,typeof e!="symbol"?e+"":e,n),DT=0,ki=class t{constructor(e,n,r,i,s="bi",a="none",o="#2962ff",l="style_solid",c=1,u="#2962ff",h="",p="#000000",d="auto",f="center",m="center",y="wrap_none",g="default",w="format_none",k=!1){qe(this,"id"),qe(this,"left"),qe(this,"top"),qe(this,"right"),qe(this,"bottom"),qe(this,"xloc"),qe(this,"extend"),qe(this,"border_color"),qe(this,"border_style"),qe(this,"border_width"),qe(this,"bgcolor"),qe(this,"text"),qe(this,"text_color"),qe(this,"text_size"),qe(this,"text_halign"),qe(this,"text_valign"),qe(this,"text_wrap"),qe(this,"text_font_family"),qe(this,"text_formatting"),qe(this,"force_overlay"),qe(this,"_deleted"),qe(this,"_helper"),qe(this,"_createdAtBar",-1),this.id=DT++,this.left=e,this.top=n,this.right=r,this.bottom=i,this.xloc=s,this.extend=a,this.border_color=o,this.border_style=l,this.border_width=c,this.bgcolor=u,this.text=h,this.text_color=p,this.text_size=d,this.text_halign=f,this.text_valign=m,this.text_wrap=y,this.text_font_family=g,this.text_formatting=w,this.force_overlay=k,this._deleted=!1,this._helper=null}set_left(e){this._helper?this._helper.set_left(this,e):this._deleted||(this.left=e)}set_right(e){this._helper?this._helper.set_right(this,e):this._deleted||(this.right=e)}set_top(e){this._helper?this._helper.set_top(this,e):this._deleted||(this.top=e)}set_bottom(e){this._helper?this._helper.set_bottom(this,e):this._deleted||(this.bottom=e)}set_lefttop(e,n){this._helper?this._helper.set_lefttop(this,e,n):this._deleted||(this.left=e,this.top=n)}set_rightbottom(e,n){this._helper?this._helper.set_rightbottom(this,e,n):this._deleted||(this.right=e,this.bottom=n)}set_top_left_point(e){this._helper&&this._helper.set_top_left_point(this,e)}set_bottom_right_point(e){this._helper&&this._helper.set_bottom_right_point(this,e)}set_xloc(e,n,r){this._helper?this._helper.set_xloc(this,e,n,r):this._deleted||(this.left=e,this.right=n,this.xloc=r)}set_bgcolor(e){this._helper?this._helper.set_bgcolor(this,e):this._deleted||(this.bgcolor=e)}set_border_color(e){this._helper?this._helper.set_border_color(this,e):this._deleted||(this.border_color=e)}set_border_width(e){this._helper?this._helper.set_border_width(this,e):this._deleted||(this.border_width=e)}set_border_style(e){this._helper?this._helper.set_border_style(this,e):this._deleted||(this.border_style=e)}set_extend(e){this._helper?this._helper.set_extend(this,e):this._deleted||(this.extend=e)}set_text(e){this._helper?this._helper.set_text(this,e):this._deleted||(this.text=e)}set_text_color(e){this._helper?this._helper.set_text_color(this,e):this._deleted||(this.text_color=e)}set_text_size(e){this._helper?this._helper.set_text_size(this,e):this._deleted||(this.text_size=e)}set_text_halign(e){this._helper?this._helper.set_text_halign(this,e):this._deleted||(this.text_halign=e)}set_text_valign(e){this._helper?this._helper.set_text_valign(this,e):this._deleted||(this.text_valign=e)}set_text_wrap(e){this._helper?this._helper.set_text_wrap(this,e):this._deleted||(this.text_wrap=e)}set_text_font_family(e){this._helper?this._helper.set_text_font_family(this,e):this._deleted||(this.text_font_family=e)}set_text_formatting(e){this._helper?this._helper.set_text_formatting(this,e):this._deleted||(this.text_formatting=e)}get_left(){return this._deleted?NaN:this.left}get_right(){return this._deleted?NaN:this.right}get_top(){return this._deleted?NaN:this.top}get_bottom(){return this._deleted?NaN:this.bottom}delete(){this._deleted=!0}toPlotData(){return{id:this.id,left:this.left,top:this.top,right:this.right,bottom:this.bottom,xloc:this.xloc,extend:this.extend,border_color:this.border_color,border_style:this.border_style,border_width:this.border_width,bgcolor:this.bgcolor,text:this.text,text_color:this.text_color,text_size:this.text_size,text_halign:this.text_halign,text_valign:this.text_valign,text_wrap:this.text_wrap,text_font_family:this.text_font_family,text_formatting:this.text_formatting,force_overlay:this.force_overlay,_deleted:this._deleted}}copy(){return this._helper?this._helper.copy(this):this._clone()}_clone(){return new t(this.left,this.top,this.right,this.bottom,this.xloc,this.extend,this.border_color,this.border_style,this.border_width,this.bgcolor,this.text,this.text_color,this.text_size,this.text_halign,this.text_valign,this.text_wrap,this.text_font_family,this.text_formatting,this.force_overlay)}},Xf=Object.defineProperty,OT=Object.getOwnPropertyDescriptor,RT=(t,e,n)=>e in t?Xf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fe=(t,e,n,r)=>{for(var i=r>1?void 0:r?OT(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Xf(e,n,i),i},LT=(t,e,n)=>RT(t,typeof e!="symbol"?e+"":e,n),FT=[["left","top","right","bottom","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"],["top_left","bottom_right","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"]],BT={left:"number",top:"number",right:"number",bottom:"number",top_left:"point",bottom_right:"point",border_color:"color",border_width:"number",border_style:"string",extend:"string",xloc:"string",bgcolor:"color",text:"string",text_size:"size",text_color:"color",text_halign:"string",text_valign:"string",text_wrap:"string",text_font_family:"string",force_overlay:"boolean"},Me=class{constructor(e){this.context=e,LT(this,"_boxes",[])}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__boxes__||(this.context.plots.__boxes__={title:"__boxes__",data:[],options:{style:"drawing_box",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._boxes=this._boxes.filter(s=>!s._deleted);let n=this._boxes.map(s=>s.toPlotData()),r=n.filter(s=>!s.force_overlay),i=n.filter(s=>s.force_overlay);this.context.plots.__boxes__.data=[{time:e,value:r,options:{style:"drawing_box"}}],i.length>0?this.context.plots.__boxes_overlay__={title:"__boxes_overlay__",data:[{time:e,value:i,options:{style:"drawing_box"}}],options:{style:"drawing_box",overlay:!0}}:delete this.context.plots.__boxes_overlay__}_resolvePoint(e,n){return Wa(e,n)}_resolve(e){return e==null?e:e instanceof $t?NaN:typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"?e.get(0):typeof e=="function"?e():e}_resolveColor(e,n){let r=this._resolve(e);return r==null?r:typeof r=="number"&&isNaN(r)?NaN:r||n}_createBox(e,n,r,i,s="bi",a="none",o="#2962ff",l="style_solid",c=1,u="#2962ff",h="",p="#000000",d="auto",f="center",m="center",y="wrap_none",g="default",w="format_none",k=!1){let S=new ki(e,n,r,i,s,this._resolve(a),this._resolveColor(o,"#2962ff"),this._resolve(l)||"style_solid",this._resolve(c)??1,this._resolveColor(u,"#2962ff"),this._resolve(h)||"",this._resolveColor(p,"#000000"),this._resolve(d)||"auto",this._resolve(f)||"center",this._resolve(m)||"center",this._resolve(y)||"wrap_none",this._resolve(g)||"default",this._resolve(w)||"format_none",k);return S._helper=this,S._createdAtBar=this.context.idx,this._boxes.push(S),this._enforceMaxCount(),S}_enforceMaxCount(){let e=this.context.indicator?.max_boxes_count??50,n=this._boxes.filter(r=>!r._deleted);if(n.length>e){let r=n.length-e,i=0;for(let s of this._boxes){if(i>=r)break;s._deleted||(s._deleted=!0,i++)}}}new(...e){let n=Te(e,FT,BT),r,i,s,a,o=n.xloc;if(n.top_left instanceof vt){let l=n.top_left,c=n.bottom_right,u=this._resolvePoint(l,o);r=u.x,i=l.price,o=o||u.xloc,c instanceof vt?(s=this._resolvePoint(c,o).x,a=c.price):(s=0,a=NaN)}else r=this._resolve(n.left),i=this._resolve(n.top),s=this._resolve(n.right),a=this._resolve(n.bottom);return this._createBox(r,i,s,a,o,n.extend,n.border_color,n.border_style,n.border_width,n.bgcolor,n.text,n.text_color,n.text_size,n.text_halign,n.text_valign,n.text_wrap,n.text_font_family,void 0,n.force_overlay)}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof $t||typeof n=="number"&&isNaN(n))return null;if(n instanceof ki)return n;if(n instanceof _){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof ki)return r}return null}return this.new(...e)}set_left(e,n){e&&!e._deleted&&(e.left=this._resolve(n))}set_right(e,n){e&&!e._deleted&&(e.right=this._resolve(n))}set_top(e,n){e&&!e._deleted&&(e.top=this._resolve(n))}set_bottom(e,n){e&&!e._deleted&&(e.bottom=this._resolve(n))}set_lefttop(e,n,r){e&&!e._deleted&&(e.left=this._resolve(n),e.top=this._resolve(r))}set_rightbottom(e,n,r){e&&!e._deleted&&(e.right=this._resolve(n),e.bottom=this._resolve(r))}set_top_left_point(e,n){e&&!e._deleted&&n&&(e.left=this._resolvePoint(n,e.xloc).x,e.top=n.price)}set_bottom_right_point(e,n){e&&!e._deleted&&n&&(e.right=this._resolvePoint(n,e.xloc).x,e.bottom=n.price)}set_xloc(e,n,r,i){e&&!e._deleted&&(e.left=this._resolve(n),e.right=this._resolve(r),e.xloc=this._resolve(i))}set_bgcolor(e,n){e&&!e._deleted&&(e.bgcolor=this._resolve(n))}set_border_color(e,n){e&&!e._deleted&&(e.border_color=this._resolve(n))}set_border_width(e,n){e&&!e._deleted&&(e.border_width=this._resolve(n)??1)}set_border_style(e,n){e&&!e._deleted&&(e.border_style=this._resolve(n))}set_extend(e,n){e&&!e._deleted&&(e.extend=this._resolve(n))}set_text(e,n){e&&!e._deleted&&(e.text=this._resolve(n)||"")}set_text_color(e,n){e&&!e._deleted&&(e.text_color=this._resolve(n))}set_text_size(e,n){e&&!e._deleted&&(e.text_size=this._resolve(n))}set_text_halign(e,n){e&&!e._deleted&&(e.text_halign=this._resolve(n))}set_text_valign(e,n){e&&!e._deleted&&(e.text_valign=this._resolve(n))}set_text_wrap(e,n){e&&!e._deleted&&(e.text_wrap=this._resolve(n))}set_text_font_family(e,n){e&&!e._deleted&&(e.text_font_family=this._resolve(n))}set_text_formatting(e,n){e&&!e._deleted&&(e.text_formatting=this._resolve(n))}get_left(e){return e&&!e._deleted?e.left:NaN}get_right(e){return e&&!e._deleted?e.right:NaN}get_top(e){return e&&!e._deleted?e.top:NaN}get_bottom(e){return e&&!e._deleted?e.bottom:NaN}copy(e){if(!e)return;let n=e._clone();return n._helper=this,n._createdAtBar=this.context.idx,this._boxes.push(n),this._enforceMaxCount(),n}delete(e){e&&(e._deleted=!0)}get all(){return this._boxes.filter(e=>!e._deleted)}rollbackFromBar(e){this._boxes=this._boxes.filter(n=>n._createdAtBar<e),this.syncToPlot()}};Fe([R],Me.prototype,"new",1),Fe([R],Me.prototype,"set_left",1),Fe([R],Me.prototype,"set_right",1),Fe([R],Me.prototype,"set_top",1),Fe([R],Me.prototype,"set_bottom",1),Fe([R],Me.prototype,"set_lefttop",1),Fe([R],Me.prototype,"set_rightbottom",1),Fe([R],Me.prototype,"set_top_left_point",1),Fe([R],Me.prototype,"set_bottom_right_point",1),Fe([R],Me.prototype,"set_xloc",1),Fe([R],Me.prototype,"set_bgcolor",1),Fe([R],Me.prototype,"set_border_color",1),Fe([R],Me.prototype,"set_border_width",1),Fe([R],Me.prototype,"set_border_style",1),Fe([R],Me.prototype,"set_extend",1),Fe([R],Me.prototype,"set_text",1),Fe([R],Me.prototype,"set_text_color",1),Fe([R],Me.prototype,"set_text_size",1),Fe([R],Me.prototype,"set_text_halign",1),Fe([R],Me.prototype,"set_text_valign",1),Fe([R],Me.prototype,"set_text_wrap",1),Fe([R],Me.prototype,"set_text_font_family",1),Fe([R],Me.prototype,"set_text_formatting",1),Fe([R],Me.prototype,"copy",1),Fe([R],Me.prototype,"delete",1);var VT=Object.defineProperty,$T=(t,e,n)=>e in t?VT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fi=(t,e,n)=>$T(t,typeof e!="symbol"?e+"":e,n),zT=0,xs=class{constructor(e,n,r){fi(this,"id"),fi(this,"line1"),fi(this,"line2"),fi(this,"color"),fi(this,"_deleted"),fi(this,"_createdAtBar",-1),this.id=zT++,this.line1=e,this.line2=n,this.color=r,this._deleted=!1}get_line1(){return this.line1}get_line2(){return this.line2}set_color(...e){let[n]=M(e,["color"]);this._deleted||(typeof n=="function"&&(n=n()),n&&typeof n=="object"&&Array.isArray(n.data)&&typeof n.get=="function"&&(n=n.get(0)),this.color=n||"")}delete(){this._deleted=!0}toPlotData(){let e=r=>r?{id:r.id,x1:r.x1,y1:r.y1,x2:r.x2,y2:r.y2,xloc:r.xloc,extend:r.extend,color:r.color,style:r.style,width:r.width,_deleted:r._deleted}:null,n=!!(this.line1?.force_overlay||this.line2?.force_overlay);return{id:this.id,line1:e(this.line1),line2:e(this.line2),color:this.color,force_overlay:n,_deleted:this._deleted}}},Zf=Object.defineProperty,jT=Object.getOwnPropertyDescriptor,qT=(t,e,n)=>e in t?Zf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fl=(t,e,n,r)=>{for(var i=r>1?void 0:r?jT(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Zf(e,n,i),i},UT=(t,e,n)=>qT(t,typeof e!="symbol"?e+"":e,n),Ai=class{constructor(e){this.context=e,UT(this,"_linefills",[])}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__linefills__||(this.context.plots.__linefills__={title:"__linefills__",data:[],options:{style:"linefill",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._linefills=this._linefills.filter(s=>!s._deleted);let n=this._linefills.map(s=>s.toPlotData()),r=n.filter(s=>!s.force_overlay),i=n.filter(s=>s.force_overlay);this.context.plots.__linefills__.data=[{time:e,value:r,options:{style:"linefill"}}],i.length>0?this.context.plots.__linefills_overlay__={title:"__linefills_overlay__",data:[{time:e,value:i,options:{style:"linefill"}}],options:{style:"linefill",overlay:!0}}:delete this.context.plots.__linefills_overlay__}_resolve(e){return e==null?e:e instanceof $t?NaN:typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"?e.get(0):typeof e=="function"?e():e}_resolveColor(e){let n=this._resolve(e);return n==null?n:typeof n=="number"&&isNaN(n)?NaN:n}new(e,n,r){let i=this._resolve(e),s=this._resolve(n);if(!(i instanceof Qn)||!(s instanceof Qn))return null;let a=r&&typeof r=="object"&&!Array.isArray(r)&&"color"in r?r.color:r,o=this._resolveColor(a);if(i&&s){let c=i.id,u=s.id;for(let h of this._linefills){if(h._deleted)continue;let p=h.line1?.id,d=h.line2?.id;if(p===c&&d===u||p===u&&d===c)return h.color=o,h._createdAtBar=this.context.idx,h}}let l=new xs(i,s,o);return l._createdAtBar=this.context.idx,this._linefills.push(l),this._enforceMaxCount(),l}_enforceMaxCount(){let e=this.context.indicator?.max_lines_count??50,n=this._linefills.filter(r=>!r._deleted).length-e;for(let r of this._linefills){if(n<=0)break;r._deleted||(r._deleted=!0,n--)}}any(...e){if(e.length===1){let n=e[0];return n==null||n instanceof $t||typeof n=="number"&&isNaN(n)?null:n instanceof xs?n:null}return this.new(e[0],e[1],e[2])}set_color(e,n){e&&!e._deleted&&(e.color=this._resolveColor(n))}get_line1(e){return e?e.line1:void 0}get_line2(e){return e?e.line2:void 0}delete(e){e&&(e._deleted=!0)}deleteForLine(e){for(let n of this._linefills)!n._deleted&&(n.line1===e||n.line2===e)&&(n._deleted=!0)}get all(){return this._linefills.filter(e=>!e._deleted)}rollbackFromBar(e){this._linefills=this._linefills.filter(n=>n._createdAtBar<e),this.syncToPlot()}};fl([R],Ai.prototype,"new",1),fl([R],Ai.prototype,"set_color",1),fl([R],Ai.prototype,"delete",1);var WT=Object.defineProperty,HT=(t,e,n)=>e in t?WT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nn=(t,e,n)=>HT(t,typeof e!="symbol"?e+"":e,n),GT=0,Ti=class{constructor(e,n=!1,r=!1,i="bi",s="#2962ff",a="",o="style_solid",l=1,c=!1){nn(this,"id"),nn(this,"points"),nn(this,"curved"),nn(this,"closed"),nn(this,"xloc"),nn(this,"line_color"),nn(this,"fill_color"),nn(this,"line_style"),nn(this,"line_width"),nn(this,"force_overlay"),nn(this,"_deleted"),nn(this,"_createdAtBar",-1),this.id=GT++,this.points=e,this.curved=n,this.closed=r,this.xloc=i,this.line_color=s,this.fill_color=a,this.line_style=o,this.line_width=l,this.force_overlay=c,this._deleted=!1}delete(){this._deleted=!0}toPlotData(){return{id:this.id,points:this.points.map(e=>({time:e.time,index:e.index,price:e.price})),curved:this.curved,closed:this.closed,xloc:this.xloc,line_color:this.line_color,fill_color:this.fill_color,line_style:this.line_style,line_width:this.line_width,force_overlay:this.force_overlay,_deleted:this._deleted}}},Jf=Object.defineProperty,KT=Object.getOwnPropertyDescriptor,YT=(t,e,n)=>e in t?Jf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gp=(t,e,n,r)=>{for(var i=r>1?void 0:r?KT(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Jf(e,n,i),i},XT=(t,e,n)=>YT(t,typeof e!="symbol"?e+"":e,n),vs=class{constructor(e){this.context=e,XT(this,"_polylines",[])}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__polylines__||(this.context.plots.__polylines__={title:"__polylines__",data:[],options:{style:"drawing_polyline",overlay:this.context.indicator?.overlay||!1}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._polylines=this._polylines.filter(n=>!n._deleted),this.context.plots.__polylines__.data=[{time:e,value:this._polylines.map(n=>n.toPlotData()),options:{style:"drawing_polyline"}}]}_resolve(e){return e==null?e:e instanceof $t?NaN:typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"?e.get(0):typeof e=="function"?e():e}_resolveColor(e,n){let r=this._resolve(e);return r==null?r:typeof r=="number"&&isNaN(r)?NaN:r||n}_extractPoints(e){let n=this._resolve(e),r=n&&n.array?n.array:n;return Array.isArray(r)?r.filter(i=>i instanceof vt):[]}new(...e){let n,r=!1,i=!1,s="bi",a="#2962ff",o="",l="style_solid",c=1,u=!1,h=(g,w)=>Object.prototype.hasOwnProperty.call(g,w),p=g=>{h(g,"curved")&&(r=g.curved),h(g,"closed")&&(i=g.closed),h(g,"xloc")&&(s=g.xloc),h(g,"line_color")&&(a=g.line_color),h(g,"fill_color")&&(o=g.fill_color),h(g,"line_style")&&(l=g.line_style),h(g,"line_width")&&(c=g.line_width),h(g,"force_overlay")&&(u=g.force_overlay)},d=e.length>=1?e[e.length-1]:null,f=e.length>=2&&d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof _)&&!(d instanceof vt);if(e.length===1&&d&&typeof d=="object"&&!Array.isArray(d)&&"points"in d)n=d.points,p(d);else{let g=f?e.slice(0,-1):e;n=g[0],g.length>1&&(r=g[1]),g.length>2&&(i=g[2]),g.length>3&&(s=g[3]),g.length>4&&(a=g[4]),g.length>5&&(o=g[5]),g.length>6&&(l=g[6]),g.length>7&&(c=g[7]),g.length>8&&(u=g[8]),f&&p(d)}let m=this._extractPoints(n),y=new Ti(m,this._resolve(r)??!1,this._resolve(i)??!1,this._resolve(s)||"bi",this._resolveColor(a,"#2962ff"),this._resolveColor(o,""),this._resolve(l)||"style_solid",this._resolve(c)||1,this._resolve(u)??!1);return y._createdAtBar=this.context.idx,this._polylines.push(y),this._enforceMaxCount(),y}_enforceMaxCount(){let e=this.context.indicator?.max_polylines_count??50,n=this._polylines.filter(r=>!r._deleted);if(n.length>e){let r=n.length-e,i=0;for(let s of this._polylines){if(i>=r)break;s._deleted||(s._deleted=!0,i++)}}}any(...e){if(e.length===1){let n=e[0];if(n==null||n instanceof $t||typeof n=="number"&&isNaN(n))return null;if(n instanceof Ti)return n;if(n instanceof _){let r=n.get(0);if(r==null||typeof r=="number"&&isNaN(r))return null;if(r instanceof Ti)return r}return null}return this.new(...e)}delete(e){e&&(e._deleted=!0)}get all(){return this._polylines.filter(e=>!e._deleted)}rollbackFromBar(e){this._polylines=this._polylines.filter(n=>n._createdAtBar<e),this.syncToPlot()}};Gp([R],vs.prototype,"new",1),Gp([R],vs.prototype,"delete",1);var ZT=Object.defineProperty,JT=(t,e,n)=>e in t?ZT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ot=(t,e,n)=>JT(t,typeof e!="symbol"?e+"":e,n),QT=0;function _t(t){return Number.isFinite(t)?Math.trunc(t):NaN}var ws=class{constructor(e="top_right",n=1,r=1,i="",s="",a=0,o="",l=0,c=!1){Ot(this,"id"),Ot(this,"position"),Ot(this,"columns"),Ot(this,"rows"),Ot(this,"bgcolor"),Ot(this,"frame_color"),Ot(this,"frame_width"),Ot(this,"border_color"),Ot(this,"border_width"),Ot(this,"force_overlay"),Ot(this,"_deleted"),Ot(this,"cells"),Ot(this,"merges"),Ot(this,"_helper"),this.id=QT++,this.position=e,this.columns=_t(n),this.rows=_t(r),this.bgcolor=i,this.frame_color=s,this.frame_width=a,this.border_color=o,this.border_width=l,this.force_overlay=c,this._deleted=!1,this.merges=[],jt((this.rows>0?this.rows:0)*(this.columns>0?this.columns:0),"table.new"),this.cells=[];for(let u=0;u<this.rows;u++){this.cells[u]=[];for(let h=0;h<this.columns;h++)this.cells[u][h]=null}}delete(){this._deleted=!0}toPlotData(){let e=this.cells.map(n=>n.map(r=>r?{...r}:null));return{id:this.id,position:this.position,columns:this.columns,rows:this.rows,bgcolor:this.bgcolor,frame_color:this.frame_color,frame_width:this.frame_width,border_color:this.border_color,border_width:this.border_width,force_overlay:this.force_overlay,_deleted:this._deleted,cells:e,merges:this.merges.map(n=>({...n}))}}setCell(e,n,r){if(e=_t(e),n=_t(n),!(n>=0&&n<this.rows&&e>=0&&e<this.columns))return;let i=new Set;for(;;){let a=this.cells[n][e];if(!a?._merged||!a._merge_parent)break;i.add(n*this.columns+e);let[o,l]=a._merge_parent;if(!(l>=0&&l<this.rows&&o>=0&&o<this.columns)||i.has(l*this.columns+o)){a._merged=!1,a._merge_parent=null;break}e=o,n=l}let s=this.cells[n][e]||this._defaultCell();Object.assign(s,r),this.cells[n][e]=s}markMerged(e,n,r,i){if(!(n>=0&&n<this.rows&&e>=0&&e<this.columns))return;let s=this.cells[n][e]||this._defaultCell();s._merged=!0,s._merge_parent=[r,i],this.cells[n][e]=s}getCell(e,n){return e=_t(e),n=_t(n),n>=0&&n<this.rows&&e>=0&&e<this.columns?this.cells[n][e]:null}clearCell(e,n){e=_t(e),n=_t(n),n>=0&&n<this.rows&&e>=0&&e<this.columns&&(this.cells[n][e]=null)}_setHelper(e){this._helper=e}cell(...e){return this._helper.cell(this,...e)}clear(...e){return this._helper.clear(this,...e)}merge_cells(...e){return this._helper.merge_cells(this,...e)}cell_set_text(...e){return this._helper.cell_set_text(this,...e)}cell_set_bgcolor(...e){return this._helper.cell_set_bgcolor(this,...e)}cell_set_text_color(...e){return this._helper.cell_set_text_color(this,...e)}cell_set_text_size(...e){return this._helper.cell_set_text_size(this,...e)}cell_set_height(...e){return this._helper.cell_set_height(this,...e)}cell_set_width(...e){return this._helper.cell_set_width(this,...e)}cell_set_tooltip(...e){return this._helper.cell_set_tooltip(this,...e)}cell_set_text_halign(...e){return this._helper.cell_set_text_halign(this,...e)}cell_set_text_valign(...e){return this._helper.cell_set_text_valign(this,...e)}cell_set_text_font_family(...e){return this._helper.cell_set_text_font_family(this,...e)}cell_set_text_formatting(...e){return this._helper.cell_set_text_formatting(this,...e)}set_position(...e){return this._helper.set_position(this,...e)}set_bgcolor(...e){return this._helper.set_bgcolor(this,...e)}set_border_color(...e){return this._helper.set_border_color(this,...e)}set_border_width(...e){return this._helper.set_border_width(this,...e)}set_frame_color(...e){return this._helper.set_frame_color(this,...e)}set_frame_width(...e){return this._helper.set_frame_width(this,...e)}_defaultCell(){return{text:"",width:0,height:0,text_color:"#000000",text_halign:"center",text_valign:"center",text_size:"normal",bgcolor:"",tooltip:"",text_font_family:"default",text_formatting:"none",_merged:!1,_merge_parent:null}}},Qf=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(t,e,n)=>e in t?Qf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ge=(t,e,n,r)=>{for(var i=r>1?void 0:r?eN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&Qf(e,n,i),i},nN=(t,e,n)=>tN(t,typeof e!="symbol"?e+"":e,n),rN=["position","columns","rows","bgcolor","frame_color","frame_width","border_color","border_width","force_overlay"],iN=["table_id","column","row","text","width","height","text_color","text_halign","text_valign","text_size","bgcolor","tooltip","text_font_family","text_formatting"],Kp=["table_id","start_column","start_row","end_column","end_row"],Be=class{constructor(e){this.context=e,nN(this,"_tables",[])}param(e,n=0,r){return _.from(e).get(n)}_ensurePlotsEntry(){this.context.plots.__tables__||(this.context.plots.__tables__={title:"__tables__",data:[],options:{style:"table",overlay:!0}})}syncToPlot(){this._ensurePlotsEntry();let e=this.context.marketData[0]?.openTime||0;this._tables=this._tables.filter(n=>!n._deleted),this.context.plots.__tables__.data=[{time:e,value:this._tables.map(n=>n.toPlotData()),options:{style:"table"}}]}_resolve(e){return e==null?e:typeof e=="object"&&"__value"in e?e.__value:typeof e=="object"&&Array.isArray(e.data)&&typeof e.get=="function"?e.get(0):typeof e=="function"?e():e}new(...e){let n="top_right",r=1,i=1,s="",a="",o=0,l="",c=0,u=!1;e=M(e,rN),n=e[0]??n,r=e[1]??r,i=e[2]??i,s=e[3]??s,a=e[4]??a,o=e[5]??o,l=e[6]??l,c=e[7]??c,u=e[8]??u;let h=new ws(this._resolve(n)||"top_right",this._resolve(r)||1,this._resolve(i)||1,this._resolve(s)||"",this._resolve(a)||"",this._resolve(o)||0,this._resolve(l)||"",this._resolve(c)||0,this._resolve(u)??!1);return h._setHelper(this),this._takePosition(h),this._tables.push(h),h}_takePosition(e){for(let n of this._tables)n!==e&&!n._deleted&&n.position===e.position&&(n._deleted=!0)}any(...e){if(e.length===1){let n=e[0];return n==null||typeof n=="object"&&"__value"in n||typeof n=="number"&&isNaN(n)?null:n instanceof ws?n:null}return this.new(...e)}cell(...e){let n,r,i,s="",a=0,o=0,l="#000000",c="center",u="center",h="normal",p="",d="",f="default",m="none";e=M(e,iN),n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??s,a=e[4]??a,o=e[5]??o,l=e[6]??l,c=e[7]??c,u=e[8]??u,h=e[9]??h,p=e[10]??p,d=e[11]??d,f=e[12]??f,m=e[13]??m;let y=this._resolve(n);if(!y||y._deleted)return;let g=this._resolve(r)??0,w=this._resolve(i)??0;y.setCell(g,w,{text:this._resolveText(this._resolve(s)),width:this._resolve(a)||0,height:this._resolve(o)||0,text_color:this._resolve(l)||"#000000",text_halign:this._resolve(c)||"center",text_valign:this._resolve(u)||"center",text_size:this._resolve(h)||"normal",bgcolor:this._resolve(p)||"",tooltip:this._resolveText(this._resolve(d)),text_font_family:this._resolve(f)||"default",text_formatting:this._resolve(m)||"none"})}delete(e){e&&(e._deleted=!0)}clear(...e){let n,r,i,s,a;e=M(e,Kp),n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??r,a=e[4]??i;let o=this._resolve(n);if(!o||o._deleted)return;let l=_t(this._resolve(r)??0),c=_t(this._resolve(i)??0),u=_t(this._resolve(s)??l),h=_t(this._resolve(a)??c);for(let p=c;p<=h;p++)for(let d=l;d<=u;d++)o.clearCell(d,p)}merge_cells(...e){let n,r,i,s,a;e=M(e,Kp),n=e[0],r=e[1]??0,i=e[2]??0,s=e[3]??0,a=e[4]??0;let o=this._resolve(n);if(!o||o._deleted)return;let l=_t(this._resolve(r)??0),c=_t(this._resolve(i)??0),u=_t(this._resolve(s)??0),h=_t(this._resolve(a)??0);if(!(isNaN(l)||isNaN(c)||isNaN(u)||isNaN(h))){for(let p=c;p<=h;p++)for(let d=l;d<=u;d++)p===c&&d===l||o.markMerged(d,p,l,c);o.merges.push({startCol:l,startRow:c,endCol:u,endRow:h})}}cell_set_text(e,n,r,i){this._setCellProp(e,n,r,"text",i,!0)}cell_set_bgcolor(e,n,r,i){this._setCellProp(e,n,r,"bgcolor",i)}cell_set_text_color(e,n,r,i){this._setCellProp(e,n,r,"text_color",i)}cell_set_text_size(e,n,r,i){this._setCellProp(e,n,r,"text_size",i)}cell_set_height(e,n,r,i){this._setCellProp(e,n,r,"height",i)}cell_set_width(e,n,r,i){this._setCellProp(e,n,r,"width",i)}cell_set_tooltip(e,n,r,i){this._setCellProp(e,n,r,"tooltip",i,!0)}cell_set_text_halign(e,n,r,i){this._setCellProp(e,n,r,"text_halign",i)}cell_set_text_valign(e,n,r,i){this._setCellProp(e,n,r,"text_valign",i)}cell_set_text_font_family(e,n,r,i){this._setCellProp(e,n,r,"text_font_family",i)}cell_set_text_formatting(e,n,r,i){this._setCellProp(e,n,r,"text_formatting",i)}set_position(e,n){let r=this._resolve(e);!r||r._deleted||(r.position=this._resolve(n)||r.position,this._takePosition(r))}set_bgcolor(e,n){let r=this._resolve(e);!r||r._deleted||(r.bgcolor=this._resolve(n)||"")}set_border_color(e,n){let r=this._resolve(e);!r||r._deleted||(r.border_color=this._resolve(n)||"")}set_border_width(e,n){let r=this._resolve(e);!r||r._deleted||(r.border_width=this._resolve(n)||0)}set_frame_color(e,n){let r=this._resolve(e);!r||r._deleted||(r.frame_color=this._resolve(n)||"")}set_frame_width(e,n){let r=this._resolve(e);!r||r._deleted||(r.frame_width=this._resolve(n)||0)}get all(){return this._tables.filter(e=>!e._deleted)}rollbackFromBar(e){this.syncToPlot()}_setCellProp(e,n,r,i,s,a=!1){let o=this._resolve(e);if(!o||o._deleted)return;let l=this._resolve(n)??0,c=this._resolve(r)??0,u=this._resolve(s);o.setCell(l,c,{[i]:a?this._resolveText(u):u})}_resolveText(e){return e==null||e!==e?"":String(e)}};Ge([R],Be.prototype,"new",1),Ge([R],Be.prototype,"cell",1),Ge([R],Be.prototype,"delete",1),Ge([R],Be.prototype,"clear",1),Ge([R],Be.prototype,"merge_cells",1),Ge([R],Be.prototype,"cell_set_text",1),Ge([R],Be.prototype,"cell_set_bgcolor",1),Ge([R],Be.prototype,"cell_set_text_color",1),Ge([R],Be.prototype,"cell_set_text_size",1),Ge([R],Be.prototype,"cell_set_height",1),Ge([R],Be.prototype,"cell_set_width",1),Ge([R],Be.prototype,"cell_set_tooltip",1),Ge([R],Be.prototype,"cell_set_text_halign",1),Ge([R],Be.prototype,"cell_set_text_valign",1),Ge([R],Be.prototype,"cell_set_text_font_family",1),Ge([R],Be.prototype,"cell_set_text_formatting",1),Ge([R],Be.prototype,"set_position",1),Ge([R],Be.prototype,"set_bgcolor",1),Ge([R],Be.prototype,"set_border_color",1),Ge([R],Be.prototype,"set_border_width",1),Ge([R],Be.prototype,"set_frame_color",1),Ge([R],Be.prototype,"set_frame_width",1);function Xn(t,e){let n=Nu(t);if(n instanceof Ma)return n;throw new fe(`The \\`footprint\\` ID used in the \\`${e}()\\` call cannot be \\`na\\`.`,`footprint.${e}`)}var uc=class{constructor(e){this.context=e}param(e,n=0,r){return _.from(e).get(n)}any(){throw new fe("Could not find function or function reference \'footprint\'","footprint")}buy_volume(e){return Xn(e,"buy_volume").buy_volume()}sell_volume(e){return Xn(e,"sell_volume").sell_volume()}total_volume(e){return Xn(e,"total_volume").total_volume()}delta(e){return Xn(e,"delta").delta()}poc(e){return Xn(e,"poc").poc()}vah(e){return Xn(e,"vah").vah()}val(e){return Xn(e,"val").val()}rows(e){return Xn(e,"rows").rows()}get_row_by_price(e,n){return Xn(e,"get_row_by_price").get_row_by_price(n)}};function _r(t,e){let n=Nu(t);if(n instanceof Ia)return n;throw new fe(`The \\`volume_row\\` ID used in the \\`${e}()\\` call cannot be \\`na\\`.`,`volume_row.${e}`)}var hc=class{constructor(e){this.context=e}param(e,n=0,r){return _.from(e).get(n)}any(){throw new fe("Could not find function or function reference \'volume_row\'","volume_row")}up_price(e){return _r(e,"up_price").up_price()}down_price(e){return _r(e,"down_price").down_price()}buy_volume(e){return _r(e,"buy_volume").buy_volume()}sell_volume(e){return _r(e,"sell_volume").sell_volume()}total_volume(e){return _r(e,"total_volume").total_volume()}delta(e){return _r(e,"delta").delta()}has_buy_imbalance(e){return _r(e,"has_buy_imbalance").has_buy_imbalance()}has_sell_imbalance(e){return _r(e,"has_sell_imbalance").has_sell_imbalance()}},Yp=["session","adjustment","backadjustment","settlement_as_close"],sN=t=>t!==null&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype;function Xp(t,e){let n={};return t.forEach((r,i)=>{sN(r)?Object.assign(n,r):i<e.length&&r!==void 0&&(n[e[i]]=r)}),n}function Zp(t){let{modifier:e}=Yr(t);return e?{base:t.slice(0,t.lastIndexOf(";")),chartType:e}:{base:t,chartType:null}}var pc=class{constructor(e){this.context=e}param(e,n=0,r){return typeof e=="string"?e:_.from(e).get(n)}inherit(e,n){let{base:r,chartType:i}=Zp(this._coerce(e)),s=Tr(this._coerce(n)),a=sl(s,ss(r).modifiers);return i&&i!=="standard"?`${a};${i}`:a}new(e,n,...r){let i=Xp([e,n,...r],["prefix","ticker",...Yp]),s=this._coerce(i.prefix),a=this._coerce(i.ticker),o=s?a?`${s}:${a}`:s:a;return sl(o,this._applyModifiers({},i))}modify(e,...n){let r=Xp([e,...n],["tickerid",...Yp]),{base:i,chartType:s}=Zp(this._coerce(r.tickerid)),{symbol:a,modifiers:o}=ss(i),l=sl(a,this._applyModifiers(o,r));return s?`${l};${s}`:l}_applyModifiers(e,n){let r={...e},i=c=>{let u=c===void 0?"":this._coerce(c);return u===""?void 0:u},s=i(n.session);s==="regular"?delete r.session:s!==void 0&&(r.session=s);let a=i(n.adjustment);a!==void 0&&(r.adjustment=a);let o=i(n.backadjustment);o==="on"?r.backadjustment="default":o==="off"&&delete r.backadjustment;let l=i(n.settlement_as_close);return l==="on"?r["settlement-as-close"]=!0:l==="off"&&(r["settlement-as-close"]=!1),r}standard(e){return e==null?Tr(this.context?.pine?.syminfo?.tickerid||this.context?.tickerId||""):Tr(this._coerce(e))}heikinashi(e){return yf(this._coerce(e),"heikinashi")}renko(e,n,r,i,s){return this._coerce(e)}kagi(e,n){return this._coerce(e)}linebreak(e,n){return this._coerce(e)}pointfigure(e,n,r,i,s){return this._coerce(e)}_coerce(e){if(e==null)return"";if(e instanceof _){let n=e.get(0);return n==null?"":String(n)}return typeof e=="number"&&isNaN(e)?"":String(e)}};function aN(t){let e=t.trim();if(e.endsWith("[]"))return"array";let n=e.indexOf("<");n>=0&&(e=e.slice(0,n));let r=e.split(/\\s+/).filter(Boolean);return r.length?r[r.length-1]:""}function oN(t,e,n){if(e)return n instanceof Cn&&n._udt?.__name__===e;let r=t?.__pineReceiverType__;if(typeof r!="string")return!1;switch(aN(r)){case"line":return n instanceof Qn;case"box":return n instanceof ki;case"label":return n instanceof Ei;case"polyline":return n instanceof Ti;case"linefill":return n instanceof xs;case"table":return n instanceof ws;case"array":return n instanceof Q||Array.isArray(n);case"map":return n instanceof fs;case"matrix":return n instanceof be;case"chart.point":return n instanceof vt;case"string":return typeof n=="string";case"bool":return typeof n=="boolean";case"int":case"float":return typeof n=="number";default:return!1}}var sr=["ta","math","request","array","input","color","ticker","strategy"],It=["hline","plot","fill","label","line","box","linefill","polyline","table","footprint","volume_row","na","alert","time","time_close","dayofmonth","dayofweek","hour","minute","month","second","weekofyear","year"],lN=["request.security","request.security_lower_tf","request.footprint"],cN=["chart.left_visible_bar_time","chart.right_visible_bar_time"],Jp=["plot","hline","fill","strategy.exit"],uN=["plotchar","plotshape","plotarrow","plotbar","plotcandle","bgcolor","barcolor"],hN=["line.new","line.copy","label.new","label.copy","polyline.new","box.new","box.copy","table.new","linefill.new"],ua=new Set([...sr,"fill","plot","hline","label","line","size","extend","display","format","location","shape","text","xloc","yloc","linefill","polyline","box","table","map","matrix","chart","alert","barstate","syminfo","session","timeframe","strategy","log","str","footprint","volume_row","position","font","order","currency","dayofweek","adjustment","barmerge","scale","settlement_as_close"]),Qs=new Set(["arguments","await","case","catch","class","const","debugger","default","delete","do","enum","eval","extends","finally","function","implements","Infinity","instanceof","interface","let","NaN","new","package","private","protected","public","return","static","super","this","throw","try","typeof","undefined","void","with","yield"]),Ss=new Set(["abs","add_col","add_row","avg","binary_search","binary_search_leftmost","binary_search_rightmost","buy_volume","cell","cell_set_bgcolor","cell_set_height","cell_set_text","cell_set_text_color","cell_set_text_font_family","cell_set_text_formatting","cell_set_text_halign","cell_set_text_size","cell_set_text_valign","cell_set_tooltip","cell_set_width","clear","col","columns","concat","contains","copy","covariance","delete","delta","det","diff","down_price","eigenvalues","eigenvectors","elements_count","every","fill","first","get","get_bottom","get_left","get_line1","get_line2","get_price","get_right","get_row_by_price","get_text","get_top","get_x","get_x1","get_x2","get_y","get_y1","get_y2","has_buy_imbalance","has_sell_imbalance","includes","indexof","insert","inv","is_antidiagonal","is_antisymmetric","is_binary","is_diagonal","is_identity","is_square","is_stochastic","is_symmetric","is_triangular","is_zero","join","keys","kron","last","lastindexof","max","median","merge_cells","min","mode","mult","percentile_linear_interpolation","percentile_nearest_rank","percentrank","pinv","poc","pop","pow","push","put","put_all","range","rank","remove","remove_col","remove_row","reshape","reverse","row","rows","sell_volume","set","set_bgcolor","set_border_color","set_border_style","set_border_width","set_bottom","set_bottom_right_point","set_color","set_extend","set_first_point","set_frame_color","set_frame_width","set_left","set_lefttop","set_point","set_position","set_right","set_rightbottom","set_second_point","set_size","set_style","set_text","set_text_color","set_text_font_family","set_text_formatting","set_text_halign","set_text_size","set_text_valign","set_text_wrap","set_textalign","set_textcolor","set_tooltip","set_top","set_top_left_point","set_width","set_x","set_x1","set_x2","set_xloc","set_xy","set_xy1","set_xy2","set_y","set_y1","set_y2","set_yloc","shift","size","slice","some","sort","sort_indices","standardize","stdev","submatrix","sum","swap_columns","swap_rows","total_volume","trace","transpose","unshift","up_price","vah","val","values","variance"]),pN={footprint:new Set(["buy_volume","sell_volume","total_volume","delta","poc","vah","val","rows","get_row_by_price"]),volume_row:new Set(["up_price","down_price","buy_volume","sell_volume","total_volume","delta","has_buy_imbalance","has_sell_imbalance"])},em=new Set(["poc","vah","val","get_row_by_price"]),tm=["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","openTime","closeTime"],yo=[...sr,"plotchar","plotshape","plotarrow","plotbar","plotcandle","plot","bgcolor","barcolor","hline","fill","indicator","library","alertcondition","alert","error","max_bars_back","fixnan","na","nz","timestamp","str","box","line","label","table","chart","linefill","polyline","map","matrix","log","runtime","footprint","volume_row","Type","bool","int","float","string","timeframe","syminfo","barstate","session","bar_index","last_bar_index","last_bar_time","timenow","ask","bid","inputs","time","time_close","time_tradingday","dayofmonth","hour","minute","month","second","weekofyear","year","order","currency","display","shape","location","size","format","dayofweek","xloc","yloc","text","font","extend","position","scale","barmerge","adjustment","backadjustment","settlement_as_close","earnings","dividends","splits"],dN=["na","nz","plot","plotchar","color","hline","fill"],Je=["id"],ue=t=>["id",t],fN={set_x1:ue("x"),set_y1:ue("y"),set_x2:ue("x"),set_y2:ue("y"),set_xy1:["id","x","y"],set_xy2:["id","x","y"],set_color:ue("color"),set_width:ue("width"),set_style:ue("style"),set_extend:ue("extend"),set_xloc:["id","x1","x2","xloc"],set_first_point:ue("point"),set_second_point:ue("point"),get_x1:Je,get_y1:Je,get_x2:Je,get_y2:Je,get_price:ue("x"),copy:Je,delete:Je},mN={set_left:ue("left"),set_right:ue("right"),set_top:ue("top"),set_bottom:ue("bottom"),set_lefttop:["id","left","top"],set_rightbottom:["id","right","bottom"],set_top_left_point:ue("point"),set_bottom_right_point:ue("point"),set_xloc:["id","left","right","xloc"],set_bgcolor:ue("color"),set_border_color:ue("color"),set_border_width:ue("width"),set_border_style:ue("style"),set_extend:ue("extend"),set_text:ue("text"),set_text_color:ue("text_color"),set_text_size:ue("text_size"),set_text_halign:ue("text_halign"),set_text_valign:ue("text_valign"),set_text_wrap:ue("text_wrap"),set_text_font_family:ue("text_font_family"),set_text_formatting:ue("text_formatting"),get_left:Je,get_right:Je,get_top:Je,get_bottom:Je,copy:Je,delete:Je},yN={set_x:ue("x"),set_y:ue("y"),set_xy:["id","x","y"],set_text:ue("text"),set_color:ue("color"),set_textcolor:ue("textcolor"),set_size:ue("size"),set_style:ue("style"),set_textalign:ue("textalign"),set_tooltip:ue("tooltip"),set_text_font_family:ue("text_font_family"),set_text_formatting:ue("text_formatting"),set_xloc:["id","x","xloc"],set_yloc:ue("yloc"),set_point:ue("point"),get_x:Je,get_y:Je,get_text:Je,copy:Je,delete:Je},gN={set_color:ue("color"),get_line1:Je,get_line2:Je,delete:Je},_N={delete:Je},bn=t=>["table_id","column","row",t],mi=t=>["table_id",t],bN={delete:["table_id"],cell_set_text:bn("text"),cell_set_bgcolor:bn("bgcolor"),cell_set_text_color:bn("text_color"),cell_set_text_size:bn("text_size"),cell_set_height:bn("height"),cell_set_width:bn("width"),cell_set_tooltip:bn("tooltip"),cell_set_text_halign:bn("text_halign"),cell_set_text_valign:bn("text_valign"),cell_set_text_font_family:bn("text_font_family"),cell_set_text_formatting:bn("text_formatting"),set_position:mi("position"),set_bgcolor:mi("bgcolor"),set_border_color:mi("border_color"),set_border_width:mi("border_width"),set_frame_color:mi("frame_color"),set_frame_width:mi("frame_width")},xN={line:fN,box:mN,label:yN,linefill:gN,polyline:_N,table:bN},vN=Object.defineProperty,wN=(t,e,n)=>e in t?vN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e,n)=>wN(t,typeof e!="symbol"?e+"":e,n),SN=new Proxy({},{get:(t,e)=>e==="get_text"||e==="get_tooltip"?()=>"":()=>NaN}),dc=class ha{constructor({marketData:e,source:n,tickerId:r,timeframe:i,limit:s,sDate:a,eDate:o,fullContext:l,inputs:c}){se(this,"data",{open:new _([]),high:new _([]),low:new _([]),close:new _([]),volume:new _([]),hl2:new _([]),hlc3:new _([]),ohlc4:new _([]),hlcc4:new _([]),bar_index:new _([])}),se(this,"indicator"),se(this,"cache",{}),se(this,"taState",{}),se(this,"strategy"),se(this,"isSecondaryContext",!1),se(this,"chartTimezone",null),se(this,"chartStyle","standard"),se(this,"dataVersion",0),se(this,"__maxLoops",5e5),se(this,"NA",NaN),se(this,"warnings",[]),se(this,"alerts",[]),se(this,"_alertMode","realtime"),se(this,"_fillsOnTickGrid",!1),se(this,"importResolver",null),se(this,"_rawBar"),se(this,"_propOverrides",{}),se(this,"_execTick",0),se(this,"lang"),se(this,"length",0),se(this,"_drawingHelpers",[]),se(this,"pine"),se(this,"idx",0),se(this,"params",{}),se(this,"const",{}),se(this,"var",{}),se(this,"let",{}),se(this,"lctx",new Map),se(this,"result"),se(this,"plots",{}),se(this,"marketData"),se(this,"source"),se(this,"tickerId"),se(this,"timeframe",""),se(this,"pineVersion",null),se(this,"limit"),se(this,"sDate"),se(this,"eDate"),se(this,"fullContext"),se(this,"viewportLeft"),se(this,"viewportRight"),se(this,"pineTSCode"),se(this,"transpiledFn",null),se(this,"inputs",{}),se(this,"_callStack",[]),se(this,"_pathStack",[]),this.marketData=e,this.source=n,this.tickerId=r,this.timeframe=i,this.limit=s,this.sDate=a,this.eDate=o,this.fullContext=l||this,this.inputs=c||{};let u=new Sa(this),h={Type:u.Type.bind(u),na:new $t,nz:u.nz.bind(u),indicator:u.indicator.bind(u),library:u.library.bind(u),fixnan:u.fixnan.bind(u),alertcondition:u.alertcondition.bind(u),alert:new wa(this),error:u.error.bind(u),max_bars_back:u.max_bars_back.bind(u),timestamp:u.timestamp.bind(u),time:new va(this,"openTime"),time_close:new va(this,"closeTime"),dayofmonth:new Rn(this,mr.dayofmonth),dayofweek:new Rn(this,mr.dayofweek),hour:new Rn(this,mr.hour),minute:new Rn(this,mr.minute),month:new Rn(this,mr.month),second:new Rn(this,mr.second),weekofyear:new Rn(this,mr.weekofyear),year:new Rn(this,mr.year),bool:u.bool.bind(u),int:u.int.bind(u),float:u.float.bind(u),string:u.string.bind(u)},p=this;this.pine={input:new Bl(this),ta:new Ql(this),math:new ql(this),request:new Gl(this),array:new Il(this),map:new Ml(this),matrix:new Pl(this),ticker:new pc(this),strategy:new ic(this),syminfo:null,timeframe:new lc(this),barstate:new Dl(this),session:new Fl(this),get bar_index(){return p.data.bar_index},get last_bar_index(){let C=p.marketData;return Array.isArray(C)&&C.length>0?C.length-1:p.data.close.length-1},get last_bar_time(){let C=p.marketData;return Array.isArray(C)&&C.length>0?C[C.length-1].openTime:p.data.openTime.get(0)},get timenow(){return new Date().getTime()},get ask(){return NaN},get bid(){return NaN},get time_tradingday(){let C=_.from(p.data.closeTime).get(0);if(isNaN(C))return NaN;let ae=p.pine?.syminfo?.timezone||"UTC",te=Ir(C,ae);return Date.UTC(te.year,te.month-1,te.day,0,0,0)},get inputs(){return p.inputs},log:new sc(this),runtime:new ac(this),str:new oc(this),...h,...Ud};let d=h.dayofweek;Object.assign(d,{sunday:1,monday:2,tuesday:3,wednesday:4,thursday:5,friday:6,saturday:7}),this.pine.dayofweek=d;let f=new Sn(this),m=new qa(this),y=new Ua(this);this.bindContextObject(f,["plotchar","plotshape","plotarrow","plotbar","plotcandle","bgcolor","barcolor"]),this.bindContextObject(f,["any","param","linestyle_dashed","linestyle_dotted","linestyle_solid","style_area","style_areabr","style_circles","style_columns","style_cross","style_histogram","style_line","style_linebr","style_stepline","style_stepline_diamond","style_steplinebr"],"plot"),this.bindContextObject(m,["any","style_dashed","style_solid","style_dotted","param"],"hline"),this.bindContextObject(y,["any","param"],"fill");let g=new cc(this);this.pine.chart={param:g.param.bind(g),get bg_color(){return g.bg_color()},get fg_color(){return g.fg_color()},get is_standard(){return g.is_standard()},get is_heikinashi(){return g.is_heikinashi()},get is_kagi(){return g.is_kagi()},get is_linebreak(){return g.is_linebreak()},get is_pnf(){return g.is_pnf()},get is_range(){return g.is_range()},get is_renko(){return g.is_renko()},point:g.point,get left_visible_bar_time(){if(p.viewportLeft!==void 0)return p.viewportLeft;let C=p.marketData;return Array.isArray(C)&&C.length>0?C[0].openTime:NaN},get right_visible_bar_time(){if(p.viewportRight!==void 0)return p.viewportRight;let C=p.marketData;return Array.isArray(C)&&C.length>0?C[C.length-1].openTime:NaN}};let w=new Ze(this);this.bindContextObject(w,["any","new","param","set_x","set_y","set_xy","set_text","set_color","set_textcolor","set_size","set_style","set_textalign","set_tooltip","set_text_font_family","set_text_formatting","set_point","set_xloc","set_yloc","get_x","get_y","get_text","copy","delete","style_label_down","style_label_up","style_label_left","style_label_right","style_label_lower_left","style_label_lower_right","style_label_upper_left","style_label_upper_right","style_label_center","style_circle","style_square","style_diamond","style_flag","style_arrowup","style_arrowdown","style_cross","style_xcross","style_triangleup","style_triangledown","style_none","style_text_outline"],"label"),Object.defineProperty(this.pine.label,"all",{get:()=>new Q(w.all,Z.label,this)});let k=new nt(this);this.bindContextObject(k,["any","new","param","set_x1","set_y1","set_x2","set_y2","set_xy1","set_xy2","set_color","set_width","set_style","set_extend","set_xloc","set_first_point","set_second_point","get_x1","get_y1","get_x2","get_y2","get_price","copy","delete","style_solid","style_dotted","style_dashed","style_arrow_left","style_arrow_right","style_arrow_both"],"line"),Object.defineProperty(this.pine.line,"all",{get:()=>new Q(k.all,Z.line,this)});let S=new Me(this);this.bindContextObject(S,["any","new","param","copy","delete","set_left","set_right","set_top","set_bottom","set_lefttop","set_rightbottom","set_top_left_point","set_bottom_right_point","set_bgcolor","set_border_color","set_border_width","set_border_style","set_extend","set_xloc","set_text","set_text_color","set_text_size","set_text_halign","set_text_valign","set_text_wrap","set_text_font_family","set_text_formatting","get_left","get_right","get_top","get_bottom"],"box"),Object.defineProperty(this.pine.box,"all",{get:()=>new Q(S.all,Z.box,this)});let E=new Ai(this);k.linefills=E,this.bindContextObject(E,["any","new","param","set_color","get_line1","get_line2","delete"],"linefill"),Object.defineProperty(this.pine.linefill,"all",{get:()=>new Q(E.all,Z.linefill,this)});let T=new vs(this);this.bindContextObject(T,["any","new","param","delete"],"polyline"),Object.defineProperty(this.pine.polyline,"all",{get:()=>new Q(T.all,Z.any,this)});let N=new Be(this);this.bindContextObject(N,["any","new","param","cell","delete","clear","merge_cells","cell_set_text","cell_set_bgcolor","cell_set_text_color","cell_set_text_size","cell_set_height","cell_set_width","cell_set_tooltip","cell_set_text_halign","cell_set_text_valign","cell_set_text_font_family","cell_set_text_formatting","set_position","set_bgcolor","set_border_color","set_border_width","set_frame_color","set_frame_width"],"table"),Object.defineProperty(this.pine.table,"all",{get:()=>new Q(N.all,Z.table,this)}),this._drawingHelpers=[w,k,S,E,T,N];let $=new uc(this);this.bindContextObject($,["any","param","buy_volume","sell_volume","total_volume","delta","poc","vah","val","rows","get_row_by_price"],"footprint");let z=new hc(this);this.bindContextObject(z,["any","param","up_price","down_price","buy_volume","sell_volume","total_volume","delta","has_buy_imbalance","has_sell_imbalance"],"volume_row");let H=new Cl(this);this.bindContextObject(H,["any","param","new","rgb","from_gradient","r","g","b","t","aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow"],"color")}warn(e,n){this.warnings.push({message:e,method:n,bar:this.idx})}rollbackDrawings(e){for(let n of this._drawingHelpers)n.rollbackFromBar(e)}bindContextObject(e,n,r=""){r&&!this.pine[r]&&(this.pine[r]={});let i=r?this.pine[r]:this.pine,s=xN[r];for(let a of n)typeof e[a]=="function"?(s&&s[a]&&(e[a]=P(e[a].bind(e),s[a])),i[a]=e[a].bind(e)):i[a]=e[a]}toTuple(e,n){return Array.isArray(e)?Array.isArray(e[0])?e:[e]:[new Array(n).fill(NaN)]}init(e,n,r=0){let i;return n instanceof _?i=n.get(0):Array.isArray(n)?Array.isArray(n[0])?i=n[0]:i=n[n.length-1+r]:i=n,e?e instanceof _?(e.data[e.data.length-1]=i,typeof i=="boolean"&&this.pineVersion>=6&&(e.beforeStart=!1),e):Array.isArray(e)?(e[e.length-1]=i,this.typedSeries(e,i)):this.typedSeries([i],i):this.typedSeries([i],i)}typedSeries(e,n,r=0){let i=new _(e,r);return typeof n=="boolean"&&this.pineVersion>=6&&(i.beforeStart=!1),i}initVar(e,n,r=!1){if(e)return e;if(typeof n=="function"&&(n=n()),n instanceof Cn){let a=n.__def__;for(let o in a)typeof n[o]=="function"&&(n[o]=n[o]())}let i;n instanceof _?i=n.get(0):Array.isArray(n)?Array.isArray(n[0])?i=n[0]:i=this.precision(n[n.length-1]):i=this.precision(n);let s=this.typedSeries([i],i);return r&&(s.varip=!0),s}precision(e,n=10){if(typeof e!="number")return e;let r=n===10?ha.PRECISION_EPSILON:10**n;return Math.abs(e)*r<2**53?Math.round(e*r)/r:e}param(e,n,r){if(typeof e=="string")return e;if(e instanceof _){if(n){let i=new _(e.data,e.offset+n);return i.beforeStart=e.beforeStart,i}return e}return xa(e)&&(e=e.__value),!Array.isArray(e)&&typeof e=="object"?e:(this.params[r]||(this.params[r]=[]),Array.isArray(e)?new _(e,n||0):(this.params[r].length===0?this.params[r].push(e):this.params[r][this.params[r].length-1]=e,this.typedSeries(this.params[r],e,n||0)))}get(e,n){if((n==null||Number.isNaN(n))&&(n=0),typeof n=="number"&&!Number.isInteger(n)&&(n=Math.trunc(n)),e instanceof _)return e.get(n);if(Array.isArray(e)){let r=e.length-1-n;return r<0||r>=e.length?NaN:e[r]}return e}set(e,n){if(e instanceof _){e.set(0,typeof n=="number"?this.precision(n):n);return}if(Array.isArray(e)){e.length>0?e[e.length-1]=n:e.push(n);return}}iter(e){return e==null?[]:Array.isArray(e.array)?e.array:e.map instanceof Map?e.map:e instanceof be?this._matrixRows(e):e}_matrixRows(e){return e.matrix.map((n,r)=>e.row(r))}entries(e){return e==null?[].entries():Array.isArray(e.array)?e.array.entries():e.map instanceof Map?e.map.entries():e instanceof be?this._matrixRows(e).entries():Array.isArray(e)||typeof e.entries=="function"?e.entries():[].entries()}pushId(e){let n=this._pathStack.length>0?this._pathStack[this._pathStack.length-1]:"",r=n?n+"|"+e:e;this._callStack.push(e),this._pathStack.push(r)}popId(){this._callStack.pop(),this._pathStack.pop()}peekId(){return this._pathStack.length>0?this._pathStack[this._pathStack.length-1]:""}peekCtx(){let e=this.peekId();if(!e)return this;let n=this.lctx.get(e);return n||(n={id:e,let:{},const:{},var:{}},this.lctx.set(e,n)),n}loopError(e){throw new fe(e)}drawingOrNa(e){return e==null||typeof e=="number"&&isNaN(e)?SN:e}call(e,n,...r){this.pushId(n);try{let i=e(...r);return i===void 0?NaN:i}finally{this.popId()}}callMethod(e,n,r,i,...s){let a=c=>c instanceof _?c.get(0):c,o=a(i);if(o==null||typeof o=="number"&&Number.isNaN(o))return;for(let[c,u]of r)if(oN(c,u,o))return this.call(c,n,i,...s);if(!Ss.has(e))return;let l=o[e];return typeof l=="function"?l.apply(o,s.map(a)):void 0}get math(){return this._showDeprecationWarning("const math = context.math","const { math, ta, input } = context.pine"),this.pine.math}get ta(){return this._showDeprecationWarning("const ta = context.ta","const { ta, math, input } = context.pine"),this.pine.ta}get input(){return this._showDeprecationWarning("const input = context.input","const { input, math, ta } = context.pine"),this.pine.input}get request(){return this._showDeprecationWarning("const request = context.request","const { request, math, ta } = context.pine"),this.pine.request}get array(){return this._showDeprecationWarning("const array = context.array","const { array, math, ta } = context.pine"),this.pine.array}get core(){return this._showDeprecationWarning("context.core.*","context.pine (e.g., const { na, plotchar, color, plot, nz } = context.pine)"),{na:this.pine.na,fill:this.pine.fill,plotchar:this.pine.plotchar,plotshape:this.pine.plotshape,plotarrow:this.pine.plotarrow,color:this.pine.color,plot:this.pine.plot,nz:this.pine.nz}}_showDeprecationWarning(e,n){let r=`${e}->${n}`;ha._deprecationWarningsShown.has(r)||(ha._deprecationWarningsShown.add(r),typeof window<"u"?console.warn("%c[WARNING]%c %s syntax is deprecated. Use %s instead. This will be removed in a future version.","color: #FFA500; font-weight: bold;","color: #FFA500;",e,n):console.warn(`\\x1B[33m[WARNING] ${e} syntax is deprecated. Use ${n} instead. This will be removed in a future version.\\x1B[0m`))}};se(dc,"_deprecationWarningsShown",new Set),se(dc,"PRECISION_EPSILON",10**10);var Di=dc;function Qp(t){let e=_.from(t).get(0);if(e==null||typeof e=="number"&&isNaN(e))return["",""];let n=Tr(String(e)),r=n.indexOf(":");return r<0?["",""]:[n.slice(0,r),n.slice(r+1)]}function ed(t){return{...t,param:(e,n=0)=>_.from(e).get(n),__ticker:e=>Qp(e)[1],__prefix:e=>Qp(e)[0]}}var EN=[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,78,5,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,199,7,137,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,55,9,266,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,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],nm=[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,7,25,39,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,5,57,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,24,43,261,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,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,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,208,30,2,2,2,1,2,6,3,4,10,1,225,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,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],kN="\\u200C\\u200D\\xB7\\u0300-\\u036F\\u0387\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u0669\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u06F0-\\u06F9\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07C0-\\u07C9\\u07EB-\\u07F3\\u07FD\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u0897-\\u089F\\u08CA-\\u08E1\\u08E3-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0966-\\u096F\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u09E6-\\u09EF\\u09FE\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A66-\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0AE6-\\u0AEF\\u0AFA-\\u0AFF\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B55-\\u0B57\\u0B62\\u0B63\\u0B66-\\u0B6F\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C04\\u0C3C\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0CE6-\\u0CEF\\u0CF3\\u0D00-\\u0D03\\u0D3B\\u0D3C\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D66-\\u0D6F\\u0D81-\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0E50-\\u0E59\\u0EB1\\u0EB4-\\u0EBC\\u0EC8-\\u0ECE\\u0ED0-\\u0ED9\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1040-\\u1049\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F-\\u109D\\u135D-\\u135F\\u1369-\\u1371\\u1712-\\u1715\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u180F-\\u1819\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u194F\\u19D0-\\u19DA\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AB0-\\u1ABD\\u1ABF-\\u1ADD\\u1AE0-\\u1AEB\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BB0-\\u1BB9\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1C40-\\u1C49\\u1C50-\\u1C59\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF4\\u1CF7-\\u1CF9\\u1DC0-\\u1DFF\\u200C\\u200D\\u203F\\u2040\\u2054\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\u30FB\\uA620-\\uA629\\uA66F\\uA674-\\uA67D\\uA69E\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA82C\\uA880\\uA881\\uA8B4-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F1\\uA8FF-\\uA909\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uA9D0-\\uA9D9\\uA9E5\\uA9F0-\\uA9F9\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA50-\\uAA59\\uAA7B-\\uAA7D\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF10-\\uFF19\\uFF3F\\uFF65",rm="\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088F\\u08A0-\\u08C9\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C5C\\u0C5D\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDC-\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D04-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-\\u0EA3\\u0EA5\\u0EA7-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u1711\\u171F-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1878\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4C\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C8A\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CE9-\\u1CEC\\u1CEE-\\u1CF3\\u1CF5\\u1CF6\\u1CFA\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2118-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309B-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u31A0-\\u31BF\\u31F0-\\u31FF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7DC\\uA7F1-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA8FE\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC",ml={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"},yl="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",AN={5:yl,"5module":yl+" export import",6:yl+" const class extends export import super"},im=/^in(stanceof)?$/,TN=new RegExp("["+rm+"]"),NN=new RegExp("["+rm+kN+"]");function fc(t,e){for(var n=65536,r=0;r<e.length;r+=2){if(n+=e[r],n>t)return!1;if(n+=e[r+1],n>=t)return!0}return!1}function Hn(t,e){return t<65?t===36:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&TN.test(String.fromCharCode(t)):e===!1?!1:fc(t,nm)}function Pr(t,e){return t<48?t===36:t<58?!0:t<65?!1:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&NN.test(String.fromCharCode(t)):e===!1?!1:fc(t,nm)||fc(t,EN)}var we=function(t,e){e===void 0&&(e={}),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop||null,this.updateContext=null};function rn(t,e){return new we(t,{beforeExpr:!0,binop:e})}var sn={beforeExpr:!0},Rt={startsExpr:!0},ju={};function ye(t,e){return e===void 0&&(e={}),e.keyword=t,ju[t]=new we(t,e)}var x={num:new we("num",Rt),regexp:new we("regexp",Rt),string:new we("string",Rt),name:new we("name",Rt),privateId:new we("privateId",Rt),eof:new we("eof"),bracketL:new we("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new we("]"),braceL:new we("{",{beforeExpr:!0,startsExpr:!0}),braceR:new we("}"),parenL:new we("(",{beforeExpr:!0,startsExpr:!0}),parenR:new we(")"),comma:new we(",",sn),semi:new we(";",sn),colon:new we(":",sn),dot:new we("."),question:new we("?",sn),questionDot:new we("?."),arrow:new we("=>",sn),template:new we("template"),invalidTemplate:new we("invalidTemplate"),ellipsis:new we("...",sn),backQuote:new we("`",Rt),dollarBraceL:new we("${",{beforeExpr:!0,startsExpr:!0}),eq:new we("=",{beforeExpr:!0,isAssign:!0}),assign:new we("_=",{beforeExpr:!0,isAssign:!0}),incDec:new we("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new we("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:rn("||",1),logicalAND:rn("&&",2),bitwiseOR:rn("|",3),bitwiseXOR:rn("^",4),bitwiseAND:rn("&",5),equality:rn("==/!=/===/!==",6),relational:rn("</>/<=/>=",7),bitShift:rn("<</>>/>>>",8),plusMin:new we("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:rn("%",10),star:rn("*",10),slash:rn("/",10),starstar:new we("**",{beforeExpr:!0}),coalesce:rn("??",1),_break:ye("break"),_case:ye("case",sn),_catch:ye("catch"),_continue:ye("continue"),_debugger:ye("debugger"),_default:ye("default",sn),_do:ye("do",{isLoop:!0,beforeExpr:!0}),_else:ye("else",sn),_finally:ye("finally"),_for:ye("for",{isLoop:!0}),_function:ye("function",Rt),_if:ye("if"),_return:ye("return",sn),_switch:ye("switch"),_throw:ye("throw",sn),_try:ye("try"),_var:ye("var"),_const:ye("const"),_while:ye("while",{isLoop:!0}),_with:ye("with"),_new:ye("new",{beforeExpr:!0,startsExpr:!0}),_this:ye("this",Rt),_super:ye("super",Rt),_class:ye("class",Rt),_extends:ye("extends",sn),_export:ye("export"),_import:ye("import",Rt),_null:ye("null",Rt),_true:ye("true",Rt),_false:ye("false",Rt),_in:ye("in",{beforeExpr:!0,binop:7}),_instanceof:ye("instanceof",{beforeExpr:!0,binop:7}),_typeof:ye("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:ye("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:ye("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},zt=/\\r\\n?|\\n|\\u2028|\\u2029/,CN=new RegExp(zt.source,"g");function Vi(t){return t===10||t===13||t===8232||t===8233}function sm(t,e,n){n===void 0&&(n=t.length);for(var r=e;r<n;r++){var i=t.charCodeAt(r);if(Vi(i))return r<n-1&&i===13&&t.charCodeAt(r+1)===10?r+2:r+1}return-1}var am=/[\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff]/,bt=/(?:\\s|\\/\\/.*|\\/\\*[^]*?\\*\\/)*/g,om=Object.prototype,IN=om.hasOwnProperty,MN=om.toString,$i=Object.hasOwn||(function(t,e){return IN.call(t,e)}),td=Array.isArray||(function(t){return MN.call(t)==="[object Array]"}),nd=Object.create(null);function kr(t){return nd[t]||(nd[t]=new RegExp("^(?:"+t.replace(/ /g,"|")+")$"))}function nr(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}var PN=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Es=function(t,e){this.line=t,this.column=e};Es.prototype.offset=function(t){return new Es(this.line,this.column+t)};var go=function(t,e,n){this.start=e,this.end=n,t.sourceFile!==null&&(this.source=t.sourceFile)};function lm(t,e){for(var n=1,r=0;;){var i=sm(t,r,e);if(i<0)return new Es(n,e-r);++n,r=i}}var mc={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},rd=!1;function DN(t){var e={};for(var n in mc)e[n]=t&&$i(t,n)?t[n]:mc[n];if(e.ecmaVersion==="latest"?e.ecmaVersion=1e8:e.ecmaVersion==null?(!rd&&typeof console=="object"&&console.warn&&(rd=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=11):e.ecmaVersion>=2015&&(e.ecmaVersion-=2009),e.allowReserved==null&&(e.allowReserved=e.ecmaVersion<5),(!t||t.allowHashBang==null)&&(e.allowHashBang=e.ecmaVersion>=14),td(e.onToken)){var r=e.onToken;e.onToken=function(i){return r.push(i)}}if(td(e.onComment)&&(e.onComment=ON(e,e.onComment)),e.sourceType==="commonjs"&&e.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return e}function ON(t,e){return function(n,r,i,s,a,o){var l={type:n?"Block":"Line",value:r,start:i,end:s};t.locations&&(l.loc=new go(this,a,o)),t.ranges&&(l.range=[i,s]),e.push(l)}}var Xr=1,Qr=2,qu=4,cm=8,Uu=16,um=32,_o=64,hm=128,ei=256,Os=512,pm=1024,bo=Xr|Qr|ei;function Wu(t,e){return Qr|(t?qu:0)|(e?cm:0)}var Ha=0,Hu=1,ar=2,dm=3,fm=4,mm=5,it=function(t,e,n){this.options=t=DN(t),this.sourceFile=t.sourceFile,this.keywords=kr(AN[t.ecmaVersion>=6?6:t.sourceType==="module"?"5module":5]);var r="";t.allowReserved!==!0&&(r=ml[t.ecmaVersion>=6?6:t.ecmaVersion===5?5:3],t.sourceType==="module"&&(r+=" await")),this.reservedWords=kr(r);var i=(r?r+" ":"")+ml.strict;this.reservedWordsStrict=kr(i),this.reservedWordsStrictBind=kr(i+" "+ml.strictBind),this.input=String(e),this.containsEsc=!1,n?(this.pos=n,this.lineStart=this.input.lastIndexOf(`\n`,n-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(zt).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=x.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=t.sourceType==="module",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),this.pos===0&&t.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType==="commonjs"?Qr:Xr),this.regexpState=null,this.privateNameStack=[]},dn={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};it.prototype.parse=function(){var t=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(t)};dn.inFunction.get=function(){return(this.currentVarScope().flags&Qr)>0};dn.inGenerator.get=function(){return(this.currentVarScope().flags&cm)>0};dn.inAsync.get=function(){return(this.currentVarScope().flags&qu)>0};dn.canAwait.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(ei|Os))return!1;if(n&Qr)return(n&qu)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};dn.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&Xr)};dn.allowSuper.get=function(){var t=this.currentThisScope(),e=t.flags;return(e&_o)>0||this.options.allowSuperOutsideMethod};dn.allowDirectSuper.get=function(){return(this.currentThisScope().flags&hm)>0};dn.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};dn.allowNewDotTarget.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],n=e.flags;if(n&(ei|Os)||n&Qr&&!(n&Uu))return!0}return!1};dn.allowUsing.get=function(){var t=this.currentScope(),e=t.flags;return!(e&pm||!this.inModule&&e&Xr)};dn.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&ei)>0};it.extend=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];for(var n=this,r=0;r<t.length;r++)n=t[r](n);return n};it.parse=function(t,e){return new this(e,t).parse()};it.parseExpressionAt=function(t,e,n){var r=new this(n,t,e);return r.nextToken(),r.parseExpression()};it.tokenizer=function(t,e){return new this(e,t)};Object.defineProperties(it.prototype,dn);var Mt=it.prototype,RN=/^(?:\'((?:\\\\[^]|[^\'\\\\])*?)\'|"((?:\\\\[^]|[^"\\\\])*?)")/;Mt.strictDirective=function(t){if(this.options.ecmaVersion<5)return!1;for(;;){bt.lastIndex=t,t+=bt.exec(this.input)[0].length;var e=RN.exec(this.input.slice(t));if(!e)return!1;if((e[1]||e[2])==="use strict"){bt.lastIndex=t+e[0].length;var n=bt.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===";"||i==="}"||zt.test(n[0])&&!(/[(`.[+\\-/*%<>=,?^&]/.test(i)||i==="!"&&this.input.charAt(r+1)==="=")}t+=e[0].length,bt.lastIndex=t,t+=bt.exec(this.input)[0].length,this.input[t]===";"&&t++}};Mt.eat=function(t){return this.type===t?(this.next(),!0):!1};Mt.isContextual=function(t){return this.type===x.name&&this.value===t&&!this.containsEsc};Mt.eatContextual=function(t){return this.isContextual(t)?(this.next(),!0):!1};Mt.expectContextual=function(t){this.eatContextual(t)||this.unexpected()};Mt.canInsertSemicolon=function(){return this.type===x.eof||this.type===x.braceR||zt.test(this.input.slice(this.lastTokEnd,this.start))};Mt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};Mt.semicolon=function(){!this.eat(x.semi)&&!this.insertSemicolon()&&this.unexpected()};Mt.afterTrailingComma=function(t,e){if(this.type===t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0};Mt.expect=function(t){this.eat(t)||this.unexpected()};Mt.unexpected=function(t){this.raise(t??this.start,"Unexpected token")};var xo=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};Mt.checkPatternErrors=function(t,e){if(t){t.trailingComma>-1&&this.raiseRecoverable(t.trailingComma,"Comma is not permitted after the rest element");var n=e?t.parenthesizedAssign:t.parenthesizedBind;n>-1&&this.raiseRecoverable(n,e?"Assigning to rvalue":"Parenthesized pattern")}};Mt.checkExpressionErrors=function(t,e){if(!t)return!1;var n=t.shorthandAssign,r=t.doubleProto;if(!e)return n>=0||r>=0;n>=0&&this.raise(n,"Shorthand property assignments are valid only in destructuring patterns"),r>=0&&this.raiseRecoverable(r,"Redefinition of __proto__ property")};Mt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")};Mt.isSimpleAssignTarget=function(t){return t.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(t.expression):t.type==="Identifier"||t.type==="MemberExpression"};var X=it.prototype;X.parseTopLevel=function(t){var e=Object.create(null);for(t.body||(t.body=[]);this.type!==x.eof;){var n=this.parseStatement(null,!0,e);t.body.push(n)}if(this.inModule)for(var r=0,i=Object.keys(this.undefinedExports);r<i.length;r+=1){var s=i[r];this.raiseRecoverable(this.undefinedExports[s].start,"Export \'"+s+"\' is not defined")}return this.adaptDirectivePrologue(t.body),this.next(),t.sourceType=this.options.sourceType==="commonjs"?"script":this.options.sourceType,this.finishNode(t,"Program")};var Gu={kind:"loop"},LN={kind:"switch"};X.isLet=function(t){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;bt.lastIndex=this.pos;var e=bt.exec(this.input),n=this.pos+e[0].length,r=this.fullCharCodeAt(n);if(r===91||r===92)return!0;if(t)return!1;if(r===123)return!0;if(Hn(r)){var i=n;do n+=r<=65535?1:2;while(Pr(r=this.fullCharCodeAt(n)));if(r===92)return!0;var s=this.input.slice(i,n);if(!im.test(s))return!0}return!1};X.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;bt.lastIndex=this.pos;var t=bt.exec(this.input),e=this.pos+t[0].length,n;return!zt.test(this.input.slice(this.pos,e))&&this.input.slice(e,e+8)==="function"&&(e+8===this.input.length||!(Pr(n=this.fullCharCodeAt(e+8))||n===92))};X.isUsingKeyword=function(t,e){if(this.options.ecmaVersion<17||!this.isContextual(t?"await":"using"))return!1;bt.lastIndex=this.pos;var n=bt.exec(this.input),r=this.pos+n[0].length;if(zt.test(this.input.slice(this.pos,r)))return!1;if(t){var i=r+5,s;if(this.input.slice(r,i)!=="using"||i===this.input.length||Pr(s=this.fullCharCodeAt(i))||s===92)return!1;bt.lastIndex=i;var a=bt.exec(this.input);if(r=i+a[0].length,a&&zt.test(this.input.slice(i,r)))return!1}var o=this.fullCharCodeAt(r);if(!Hn(o)&&o!==92)return!1;var l=r;do r+=o<=65535?1:2;while(Pr(o=this.fullCharCodeAt(r)));if(o===92)return!0;var c=this.input.slice(l,r);return!(im.test(c)||e&&c==="of")};X.isAwaitUsing=function(t){return this.isUsingKeyword(!0,t)};X.isUsing=function(t){return this.isUsingKeyword(!1,t)};X.parseStatement=function(t,e,n){var r=this.type,i=this.startNode(),s;switch(this.isLet(t)&&(r=x._var,s="let"),r){case x._break:case x._continue:return this.parseBreakContinueStatement(i,r.keyword);case x._debugger:return this.parseDebuggerStatement(i);case x._do:return this.parseDoStatement(i);case x._for:return this.parseForStatement(i);case x._function:return t&&(this.strict||t!=="if"&&t!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!t);case x._class:return t&&this.unexpected(),this.parseClass(i,!0);case x._if:return this.parseIfStatement(i);case x._return:return this.parseReturnStatement(i);case x._switch:return this.parseSwitchStatement(i);case x._throw:return this.parseThrowStatement(i);case x._try:return this.parseTryStatement(i);case x._const:case x._var:return s=s||this.value,t&&s!=="var"&&this.unexpected(),this.parseVarStatement(i,s);case x._while:return this.parseWhileStatement(i);case x._with:return this.parseWithStatement(i);case x.braceL:return this.parseBlock(!0,i);case x.semi:return this.parseEmptyStatement(i);case x._export:case x._import:if(this.options.ecmaVersion>10&&r===x._import){bt.lastIndex=this.pos;var a=bt.exec(this.input),o=this.pos+a[0].length,l=this.input.charCodeAt(o);if(l===40||l===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(e||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\'")),r===x._import?this.parseImport(i):this.parseExport(i,n);default:if(this.isAsyncFunction())return t&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!t);var c=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(c)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),c==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(i,!1,c),this.semicolon(),this.finishNode(i,"VariableDeclaration");var u=this.value,h=this.parseExpression();return r===x.name&&h.type==="Identifier"&&this.eat(x.colon)?this.parseLabeledStatement(i,u,h,t):this.parseExpressionStatement(i,h)}};X.parseBreakContinueStatement=function(t,e){var n=e==="break";this.next(),this.eat(x.semi)||this.insertSemicolon()?t.label=null:this.type!==x.name?this.unexpected():(t.label=this.parseIdent(),this.semicolon());for(var r=0;r<this.labels.length;++r){var i=this.labels[r];if((t.label==null||i.name===t.label.name)&&(i.kind!=null&&(n||i.kind==="loop")||t.label&&n))break}return r===this.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,n?"BreakStatement":"ContinueStatement")};X.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")};X.parseDoStatement=function(t){return this.next(),this.labels.push(Gu),t.body=this.parseStatement("do"),this.labels.pop(),this.expect(x._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(x.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")};X.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(Gu),this.enterScope(0),this.expect(x.parenL),this.type===x.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var n=this.isLet();if(this.type===x._var||this.type===x._const||n){var r=this.startNode(),i=n?"let":this.value;return this.next(),this.parseVar(r,!0,i),this.finishNode(r,"VariableDeclaration"),this.parseForAfterInit(t,r,e)}var s=this.isContextual("let"),a=!1,o=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(o){var l=this.startNode();return this.next(),o==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(l,!0,o),this.finishNode(l,"VariableDeclaration"),this.parseForAfterInit(t,l,e)}var c=this.containsEsc,u=new xo,h=this.start,p=e>-1?this.parseExprSubscripts(u,"await"):this.parseExpression(!0,u);return this.type===x._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(e>-1?(this.type===x._in&&this.unexpected(e),t.await=!0):a&&this.options.ecmaVersion>=8&&(p.start===h&&!c&&p.type==="Identifier"&&p.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(t.await=!1)),s&&a&&this.raise(p.start,"The left-hand side of a for-of loop may not start with \'let\'."),this.toAssignable(p,!1,u),this.checkLValPattern(p),this.parseForIn(t,p)):(this.checkExpressionErrors(u,!0),e>-1&&this.unexpected(e),this.parseFor(t,p))};X.parseForAfterInit=function(t,e,n){return(this.type===x._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&e.declarations.length===1?(this.options.ecmaVersion>=9&&(this.type===x._in?n>-1&&this.unexpected(n):t.await=n>-1),this.parseForIn(t,e)):(n>-1&&this.unexpected(n),this.parseFor(t,e))};X.parseFunctionStatement=function(t,e,n){return this.next(),this.parseFunction(t,os|(n?0:yc),!1,e)};X.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(x._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")};X.parseReturnStatement=function(t){return this.allowReturn||this.raise(this.start,"\'return\' outside of function"),this.next(),this.eat(x.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")};X.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(x.braceL),this.labels.push(LN),this.enterScope(pm);for(var e,n=!1;this.type!==x.braceR;)if(this.type===x._case||this.type===x._default){var r=this.type===x._case;e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),r?e.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),n=!0,e.test=null),this.expect(x.colon)}else e||this.unexpected(),e.consequent.push(this.parseStatement(null));return this.exitScope(),e&&this.finishNode(e,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(t,"SwitchStatement")};X.parseThrowStatement=function(t){return this.next(),zt.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var FN=[];X.parseCatchClauseParam=function(){var t=this.parseBindingAtom(),e=t.type==="Identifier";return this.enterScope(e?um:0),this.checkLValPattern(t,e?fm:ar),this.expect(x.parenR),t};X.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===x._catch){var e=this.startNode();this.next(),this.eat(x.parenL)?e.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),e.param=null,this.enterScope(0)),e.body=this.parseBlock(!1),this.exitScope(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(x._finally)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")};X.parseVarStatement=function(t,e,n){return this.next(),this.parseVar(t,!1,e,n),this.semicolon(),this.finishNode(t,"VariableDeclaration")};X.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(Gu),t.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(t,"WhileStatement")};X.parseWithStatement=function(t){return this.strict&&this.raise(this.start,"\'with\' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement("with"),this.finishNode(t,"WithStatement")};X.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")};X.parseLabeledStatement=function(t,e,n,r){for(var i=0,s=this.labels;i<s.length;i+=1){var a=s[i];a.name===e&&this.raise(n.start,"Label \'"+e+"\' is already declared")}for(var o=this.type.isLoop?"loop":this.type===x._switch?"switch":null,l=this.labels.length-1;l>=0;l--){var c=this.labels[l];if(c.statementStart===t.start)c.statementStart=this.start,c.kind=o;else break}return this.labels.push({name:e,kind:o,statementStart:this.start}),t.body=this.parseStatement(r?r.indexOf("label")===-1?r+"label":r:"label"),this.labels.pop(),t.label=n,this.finishNode(t,"LabeledStatement")};X.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")};X.parseBlock=function(t,e,n){for(t===void 0&&(t=!0),e===void 0&&(e=this.startNode()),e.body=[],this.expect(x.braceL),t&&this.enterScope(0);this.type!==x.braceR;){var r=this.parseStatement(null);e.body.push(r)}return n&&(this.strict=!1),this.next(),t&&this.exitScope(),this.finishNode(e,"BlockStatement")};X.parseFor=function(t,e){return t.init=e,this.expect(x.semi),t.test=this.type===x.semi?null:this.parseExpression(),this.expect(x.semi),t.update=this.type===x.parenR?null:this.parseExpression(),this.expect(x.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,"ForStatement")};X.parseForIn=function(t,e){var n=this.type===x._in;return this.next(),e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(e.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer"),t.left=e,t.right=n?this.parseExpression():this.parseMaybeAssign(),this.expect(x.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,n?"ForInStatement":"ForOfStatement")};X.parseVar=function(t,e,n,r){for(t.declarations=[],t.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(x.eq)?i.init=this.parseMaybeAssign(e):!r&&n==="const"&&!(this.type===x._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!r&&(n==="using"||n==="await using")&&this.options.ecmaVersion>=17&&this.type!==x._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+n+" declaration"):!r&&i.id.type!=="Identifier"&&!(e&&(this.type===x._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):i.init=null,t.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(x.comma))break}return t};X.parseVarId=function(t,e){t.id=e==="using"||e==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(t.id,e==="var"?Hu:ar,!1)};var os=1,yc=2,ym=4;X.parseFunction=function(t,e,n,r,i){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===x.star&&e&yc&&this.unexpected(),t.generator=this.eat(x.star)),this.options.ecmaVersion>=8&&(t.async=!!r),e&os&&(t.id=e&ym&&this.type!==x.name?null:this.parseIdent(),t.id&&!(e&yc)&&this.checkLValSimple(t.id,this.strict||t.generator||t.async?this.treatFunctionsAsVar?Hu:ar:dm));var s=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Wu(t.async,t.generator)),e&os||(t.id=this.type===x.name?this.parseIdent():null),this.parseFunctionParams(t),this.parseFunctionBody(t,n,!1,i),this.yieldPos=s,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(t,e&os?"FunctionDeclaration":"FunctionExpression")};X.parseFunctionParams=function(t){this.expect(x.parenL),t.params=this.parseBindingList(x.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};X.parseClass=function(t,e){this.next();var n=this.strict;this.strict=!0,this.parseClassId(t,e),this.parseClassSuper(t);var r=this.enterClassBody(),i=this.startNode(),s=!1;for(i.body=[],this.expect(x.braceL);this.type!==x.braceR;){var a=this.parseClassElement(t.superClass!==null);a&&(i.body.push(a),a.type==="MethodDefinition"&&a.kind==="constructor"?(s&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),s=!0):a.key&&a.key.type==="PrivateIdentifier"&&BN(r,a)&&this.raiseRecoverable(a.key.start,"Identifier \'#"+a.key.name+"\' has already been declared"))}return this.strict=n,this.next(),t.body=this.finishNode(i,"ClassBody"),this.exitClassBody(),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")};X.parseClassElement=function(t){if(this.eat(x.semi))return null;var e=this.options.ecmaVersion,n=this.startNode(),r="",i=!1,s=!1,a="method",o=!1;if(this.eatContextual("static")){if(e>=13&&this.eat(x.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===x.star?o=!0:r="static"}if(n.static=o,!r&&e>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===x.star)&&!this.canInsertSemicolon()?s=!0:r="async"),!r&&(e>=9||!s)&&this.eat(x.star)&&(i=!0),!r&&!s&&!i){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=l:r=l)}if(r?(n.computed=!1,n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),n.key.name=r,this.finishNode(n.key,"Identifier")):this.parseClassElementName(n),e<13||this.type===x.parenL||a!=="method"||i||s){var c=!n.static&&Ga(n,"constructor"),u=c&&t;c&&a!=="method"&&this.raise(n.key.start,"Constructor can\'t have get/set modifier"),n.kind=c?"constructor":a,this.parseClassMethod(n,i,s,u)}else this.parseClassField(n);return n};X.isClassElementNameStart=function(){return this.type===x.name||this.type===x.privateId||this.type===x.num||this.type===x.string||this.type===x.bracketL||this.type.keyword};X.parseClassElementName=function(t){this.type===x.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can\'t have an element named \'#constructor\'"),t.computed=!1,t.key=this.parsePrivateIdent()):this.parsePropertyName(t)};X.parseClassMethod=function(t,e,n,r){var i=t.key;t.kind==="constructor"?(e&&this.raise(i.start,"Constructor can\'t be a generator"),n&&this.raise(i.start,"Constructor can\'t be an async method")):t.static&&Ga(t,"prototype")&&this.raise(i.start,"Classes may not have a static property named prototype");var s=t.value=this.parseMethod(e,n,r);return t.kind==="get"&&s.params.length!==0&&this.raiseRecoverable(s.start,"getter should have no params"),t.kind==="set"&&s.params.length!==1&&this.raiseRecoverable(s.start,"setter should have exactly one param"),t.kind==="set"&&s.params[0].type==="RestElement"&&this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params"),this.finishNode(t,"MethodDefinition")};X.parseClassField=function(t){return Ga(t,"constructor")?this.raise(t.key.start,"Classes can\'t have a field named \'constructor\'"):t.static&&Ga(t,"prototype")&&this.raise(t.key.start,"Classes can\'t have a static field named \'prototype\'"),this.eat(x.eq)?(this.enterScope(Os|_o),t.value=this.parseMaybeAssign(),this.exitScope()):t.value=null,this.semicolon(),this.finishNode(t,"PropertyDefinition")};X.parseClassStaticBlock=function(t){t.body=[];var e=this.labels;for(this.labels=[],this.enterScope(ei|_o);this.type!==x.braceR;){var n=this.parseStatement(null);t.body.push(n)}return this.next(),this.exitScope(),this.labels=e,this.finishNode(t,"StaticBlock")};X.parseClassId=function(t,e){this.type===x.name?(t.id=this.parseIdent(),e&&this.checkLValSimple(t.id,ar,!1)):(e===!0&&this.unexpected(),t.id=null)};X.parseClassSuper=function(t){t.superClass=this.eat(x._extends)?this.parseExprSubscripts(null,!1):null};X.enterClassBody=function(){var t={declared:Object.create(null),used:[]};return this.privateNameStack.push(t),t.declared};X.exitClassBody=function(){var t=this.privateNameStack.pop(),e=t.declared,n=t.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,i=r===0?null:this.privateNameStack[r-1],s=0;s<n.length;++s){var a=n[s];$i(e,a.name)||(i?i.used.push(a):this.raiseRecoverable(a.start,"Private field \'#"+a.name+"\' must be declared in an enclosing class"))}};function BN(t,e){var n=e.key.name,r=t[n],i="true";return e.type==="MethodDefinition"&&(e.kind==="get"||e.kind==="set")&&(i=(e.static?"s":"i")+e.kind),r==="iget"&&i==="iset"||r==="iset"&&i==="iget"||r==="sget"&&i==="sset"||r==="sset"&&i==="sget"?(t[n]="true",!1):r?!0:(t[n]=i,!1)}function Ga(t,e){var n=t.computed,r=t.key;return!n&&(r.type==="Identifier"&&r.name===e||r.type==="Literal"&&r.value===e)}X.parseExportAllDeclaration=function(t,e){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(t.exported=this.parseModuleExportName(),this.checkExport(e,t.exported,this.lastTokStart)):t.exported=null),this.expectContextual("from"),this.type!==x.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ExportAllDeclaration")};X.parseExport=function(t,e){if(this.next(),this.eat(x.star))return this.parseExportAllDeclaration(t,e);if(this.eat(x._default))return this.checkExport(e,"default",this.lastTokStart),t.declaration=this.parseExportDefaultDeclaration(),this.finishNode(t,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())t.declaration=this.parseExportDeclaration(t),t.declaration.type==="VariableDeclaration"?this.checkVariableExport(e,t.declaration.declarations):this.checkExport(e,t.declaration.id,t.declaration.id.start),t.specifiers=[],t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[]);else{if(t.declaration=null,t.specifiers=this.parseExportSpecifiers(e),this.eatContextual("from"))this.type!==x.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause());else{for(var n=0,r=t.specifiers;n<r.length;n+=1){var i=r[n];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type==="Literal"&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[])}this.semicolon()}return this.finishNode(t,"ExportNamedDeclaration")};X.parseExportDeclaration=function(t){return this.parseStatement(null)};X.parseExportDefaultDeclaration=function(){var t;if(this.type===x._function||(t=this.isAsyncFunction())){var e=this.startNode();return this.next(),t&&this.next(),this.parseFunction(e,os|ym,!1,t)}else if(this.type===x._class){var n=this.startNode();return this.parseClass(n,"nullableID")}else{var r=this.parseMaybeAssign();return this.semicolon(),r}};X.checkExport=function(t,e,n){t&&(typeof e!="string"&&(e=e.type==="Identifier"?e.name:e.value),$i(t,e)&&this.raiseRecoverable(n,"Duplicate export \'"+e+"\'"),t[e]=!0)};X.checkPatternExport=function(t,e){var n=e.type;if(n==="Identifier")this.checkExport(t,e,e.start);else if(n==="ObjectPattern")for(var r=0,i=e.properties;r<i.length;r+=1){var s=i[r];this.checkPatternExport(t,s)}else if(n==="ArrayPattern")for(var a=0,o=e.elements;a<o.length;a+=1){var l=o[a];l&&this.checkPatternExport(t,l)}else n==="Property"?this.checkPatternExport(t,e.value):n==="AssignmentPattern"?this.checkPatternExport(t,e.left):n==="RestElement"&&this.checkPatternExport(t,e.argument)};X.checkVariableExport=function(t,e){if(t)for(var n=0,r=e;n<r.length;n+=1){var i=r[n];this.checkPatternExport(t,i.id)}};X.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};X.parseExportSpecifier=function(t){var e=this.startNode();return e.local=this.parseModuleExportName(),e.exported=this.eatContextual("as")?this.parseModuleExportName():e.local,this.checkExport(t,e.exported,e.exported.start),this.finishNode(e,"ExportSpecifier")};X.parseExportSpecifiers=function(t){var e=[],n=!0;for(this.expect(x.braceL);!this.eat(x.braceR);){if(n)n=!1;else if(this.expect(x.comma),this.afterTrailingComma(x.braceR))break;e.push(this.parseExportSpecifier(t))}return e};X.parseImport=function(t){return this.next(),this.type===x.string?(t.specifiers=FN,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===x.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ImportDeclaration")};X.parseImportSpecifier=function(){var t=this.startNode();return t.imported=this.parseModuleExportName(),this.eatContextual("as")?t.local=this.parseIdent():(this.checkUnreserved(t.imported),t.local=t.imported),this.checkLValSimple(t.local,ar),this.finishNode(t,"ImportSpecifier")};X.parseImportDefaultSpecifier=function(){var t=this.startNode();return t.local=this.parseIdent(),this.checkLValSimple(t.local,ar),this.finishNode(t,"ImportDefaultSpecifier")};X.parseImportNamespaceSpecifier=function(){var t=this.startNode();return this.next(),this.expectContextual("as"),t.local=this.parseIdent(),this.checkLValSimple(t.local,ar),this.finishNode(t,"ImportNamespaceSpecifier")};X.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===x.name&&(t.push(this.parseImportDefaultSpecifier()),!this.eat(x.comma)))return t;if(this.type===x.star)return t.push(this.parseImportNamespaceSpecifier()),t;for(this.expect(x.braceL);!this.eat(x.braceR);){if(e)e=!1;else if(this.expect(x.comma),this.afterTrailingComma(x.braceR))break;t.push(this.parseImportSpecifier())}return t};X.parseWithClause=function(){var t=[];if(!this.eat(x._with))return t;this.expect(x.braceL);for(var e={},n=!0;!this.eat(x.braceR);){if(n)n=!1;else if(this.expect(x.comma),this.afterTrailingComma(x.braceR))break;var r=this.parseImportAttribute(),i=r.key.type==="Identifier"?r.key.name:r.key.value;$i(e,i)&&this.raiseRecoverable(r.key.start,"Duplicate attribute key \'"+i+"\'"),e[i]=!0,t.push(r)}return t};X.parseImportAttribute=function(){var t=this.startNode();return t.key=this.type===x.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(x.colon),this.type!==x.string&&this.unexpected(),t.value=this.parseExprAtom(),this.finishNode(t,"ImportAttribute")};X.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===x.string){var t=this.parseLiteral(this.value);return PN.test(t.value)&&this.raise(t.start,"An export name cannot include a lone surrogate."),t}return this.parseIdent(!0)};X.adaptDirectivePrologue=function(t){for(var e=0;e<t.length&&this.isDirectiveCandidate(t[e]);++e)t[e].directive=t[e].expression.raw.slice(1,-1)};X.isDirectiveCandidate=function(t){return this.options.ecmaVersion>=5&&t.type==="ExpressionStatement"&&t.expression.type==="Literal"&&typeof t.expression.value=="string"&&(this.input[t.start]===\'"\'||this.input[t.start]==="\'")};var fn=it.prototype;fn.toAssignable=function(t,e,n){if(this.options.ecmaVersion>=6&&t)switch(t.type){case"Identifier":this.inAsync&&t.name==="await"&&this.raise(t.start,"Cannot use \'await\' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern",n&&this.checkPatternErrors(n,!0);for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];this.toAssignable(s,e),s.type==="RestElement"&&(s.argument.type==="ArrayPattern"||s.argument.type==="ObjectPattern")&&this.raise(s.argument.start,"Unexpected token")}break;case"Property":t.kind!=="init"&&this.raise(t.key.start,"Object pattern can\'t contain getter or setter"),this.toAssignable(t.value,e);break;case"ArrayExpression":t.type="ArrayPattern",n&&this.checkPatternErrors(n,!0),this.toAssignableList(t.elements,e);break;case"SpreadElement":t.type="RestElement",this.toAssignable(t.argument,e),t.argument.type==="AssignmentPattern"&&this.raise(t.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":t.operator!=="="&&this.raise(t.left.end,"Only \'=\' operator can be used for specifying default value."),t.type="AssignmentPattern",delete t.operator,this.toAssignable(t.left,e);break;case"ParenthesizedExpression":this.toAssignable(t.expression,e,n);break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}else n&&this.checkPatternErrors(n,!0);return t};fn.toAssignableList=function(t,e){for(var n=t.length,r=0;r<n;r++){var i=t[r];i&&this.toAssignable(i,e)}if(n){var s=t[n-1];this.options.ecmaVersion===6&&e&&s&&s.type==="RestElement"&&s.argument.type!=="Identifier"&&this.unexpected(s.argument.start)}return t};fn.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")};fn.parseRestBinding=function(){var t=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==x.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")};fn.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case x.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(x.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case x.braceL:return this.parseObj(!0)}return this.parseIdent()};fn.parseBindingList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);)if(s?s=!1:this.expect(x.comma),e&&this.type===x.comma)i.push(null);else{if(n&&this.afterTrailingComma(t))break;if(this.type===x.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),i.push(a),this.type===x.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(t);break}else i.push(this.parseAssignableListItem(r))}return i};fn.parseAssignableListItem=function(t){var e=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(e),e};fn.parseBindingListItem=function(t){return t};fn.parseMaybeDefault=function(t,e,n){if(n=n||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(x.eq))return n;var r=this.startNodeAt(t,e);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,"AssignmentPattern")};fn.checkLValSimple=function(t,e,n){e===void 0&&(e=Ha);var r=e!==Ha;switch(t.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(t.name)&&this.raiseRecoverable(t.start,(r?"Binding ":"Assigning to ")+t.name+" in strict mode"),r&&(e===ar&&t.name==="let"&&this.raiseRecoverable(t.start,"let is disallowed as a lexically bound name"),n&&($i(n,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),n[t.name]=!0),e!==mm&&this.declareName(t.name,e,t.start));break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":r&&this.raiseRecoverable(t.start,"Binding member expression");break;case"ParenthesizedExpression":return r&&this.raiseRecoverable(t.start,"Binding parenthesized expression"),this.checkLValSimple(t.expression,e,n);default:this.raise(t.start,(r?"Binding":"Assigning to")+" rvalue")}};fn.checkLValPattern=function(t,e,n){switch(e===void 0&&(e=Ha),t.type){case"ObjectPattern":for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];this.checkLValInnerPattern(s,e,n)}break;case"ArrayPattern":for(var a=0,o=t.elements;a<o.length;a+=1){var l=o[a];l&&this.checkLValInnerPattern(l,e,n)}break;default:this.checkLValSimple(t,e,n)}};fn.checkLValInnerPattern=function(t,e,n){switch(e===void 0&&(e=Ha),t.type){case"Property":this.checkLValInnerPattern(t.value,e,n);break;case"AssignmentPattern":this.checkLValPattern(t.left,e,n);break;case"RestElement":this.checkLValPattern(t.argument,e,n);break;default:this.checkLValPattern(t,e,n)}};var xn=function(t,e,n,r,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!n,this.override=r,this.generator=!!i},je={b_stat:new xn("{",!1),b_expr:new xn("{",!0),b_tmpl:new xn("${",!1),p_stat:new xn("(",!1),p_expr:new xn("(",!0),q_tmpl:new xn("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new xn("function",!1),f_expr:new xn("function",!0),f_expr_gen:new xn("function",!0,!1,null,!0),f_gen:new xn("function",!1,!1,null,!0)},zi=it.prototype;zi.initialContext=function(){return[je.b_stat]};zi.curContext=function(){return this.context[this.context.length-1]};zi.braceIsBlock=function(t){var e=this.curContext();return e===je.f_expr||e===je.f_stat?!0:t===x.colon&&(e===je.b_stat||e===je.b_expr)?!e.isExpr:t===x._return||t===x.name&&this.exprAllowed?zt.test(this.input.slice(this.lastTokEnd,this.start)):t===x._else||t===x.semi||t===x.eof||t===x.parenR||t===x.arrow?!0:t===x.braceL?e===je.b_stat:t===x._var||t===x._const||t===x.name?!1:!this.exprAllowed};zi.inGeneratorContext=function(){for(var t=this.context.length-1;t>=1;t--){var e=this.context[t];if(e.token==="function")return e.generator}return!1};zi.updateContext=function(t){var e,n=this.type;n.keyword&&t===x.dot?this.exprAllowed=!1:(e=n.updateContext)?e.call(this,t):this.exprAllowed=n.beforeExpr};zi.overrideContext=function(t){this.curContext()!==t&&(this.context[this.context.length-1]=t)};x.parenR.updateContext=x.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var t=this.context.pop();t===je.b_stat&&this.curContext().token==="function"&&(t=this.context.pop()),this.exprAllowed=!t.isExpr};x.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?je.b_stat:je.b_expr),this.exprAllowed=!0};x.dollarBraceL.updateContext=function(){this.context.push(je.b_tmpl),this.exprAllowed=!0};x.parenL.updateContext=function(t){var e=t===x._if||t===x._for||t===x._with||t===x._while;this.context.push(e?je.p_stat:je.p_expr),this.exprAllowed=!0};x.incDec.updateContext=function(){};x._function.updateContext=x._class.updateContext=function(t){t.beforeExpr&&t!==x._else&&!(t===x.semi&&this.curContext()!==je.p_stat)&&!(t===x._return&&zt.test(this.input.slice(this.lastTokEnd,this.start)))&&!((t===x.colon||t===x.braceL)&&this.curContext()===je.b_stat)?this.context.push(je.f_expr):this.context.push(je.f_stat),this.exprAllowed=!1};x.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};x.backQuote.updateContext=function(){this.curContext()===je.q_tmpl?this.context.pop():this.context.push(je.q_tmpl),this.exprAllowed=!1};x.star.updateContext=function(t){if(t===x._function){var e=this.context.length-1;this.context[e]===je.f_expr?this.context[e]=je.f_expr_gen:this.context[e]=je.f_gen}this.exprAllowed=!0};x.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&t!==x.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var ce=it.prototype;ce.checkPropClash=function(t,e,n){if(!(this.options.ecmaVersion>=9&&t.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(t.computed||t.method||t.shorthand))){var r=t.key,i;switch(r.type){case"Identifier":i=r.name;break;case"Literal":i=String(r.value);break;default:return}var s=t.kind;if(this.options.ecmaVersion>=6){i==="__proto__"&&s==="init"&&(e.proto&&(n?n.doubleProto<0&&(n.doubleProto=r.start):this.raiseRecoverable(r.start,"Redefinition of __proto__ property")),e.proto=!0);return}i="$"+i;var a=e[i];if(a){var o;s==="init"?o=this.strict&&a.init||a.get||a.set:o=a.init||a[s],o&&this.raiseRecoverable(r.start,"Redefinition of property")}else a=e[i]={init:!1,get:!1,set:!1};a[s]=!0}};ce.parseExpression=function(t,e){var n=this.start,r=this.startLoc,i=this.parseMaybeAssign(t,e);if(this.type===x.comma){var s=this.startNodeAt(n,r);for(s.expressions=[i];this.eat(x.comma);)s.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(s,"SequenceExpression")}return i};ce.parseMaybeAssign=function(t,e,n){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(t);this.exprAllowed=!1}var r=!1,i=-1,s=-1,a=-1;e?(i=e.parenthesizedAssign,s=e.trailingComma,a=e.doubleProto,e.parenthesizedAssign=e.trailingComma=-1):(e=new xo,r=!0);var o=this.start,l=this.startLoc;(this.type===x.parenL||this.type===x.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=t==="await");var c=this.parseMaybeConditional(t,e);if(n&&(c=n.call(this,c,o,l)),this.type.isAssign){var u=this.startNodeAt(o,l);return u.operator=this.value,this.type===x.eq&&(c=this.toAssignable(c,!1,e)),r||(e.parenthesizedAssign=e.trailingComma=e.doubleProto=-1),e.shorthandAssign>=c.start&&(e.shorthandAssign=-1),this.type===x.eq?this.checkLValPattern(c):this.checkLValSimple(c),u.left=c,this.next(),u.right=this.parseMaybeAssign(t),a>-1&&(e.doubleProto=a),this.finishNode(u,"AssignmentExpression")}else r&&this.checkExpressionErrors(e,!0);return i>-1&&(e.parenthesizedAssign=i),s>-1&&(e.trailingComma=s),c};ce.parseMaybeConditional=function(t,e){var n=this.start,r=this.startLoc,i=this.parseExprOps(t,e);if(this.checkExpressionErrors(e))return i;if(this.eat(x.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(x.colon),s.alternate=this.parseMaybeAssign(t),this.finishNode(s,"ConditionalExpression")}return i};ce.parseExprOps=function(t,e){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(e,!1,!1,t);return this.checkExpressionErrors(e)||i.start===n&&i.type==="ArrowFunctionExpression"?i:this.parseExprOp(i,n,r,-1,t)};ce.parseExprOp=function(t,e,n,r,i){var s=this.type.binop;if(s!=null&&(!i||this.type!==x._in)&&s>r){var a=this.type===x.logicalOR||this.type===x.logicalAND,o=this.type===x.coalesce;o&&(s=x.logicalAND.binop);var l=this.value;this.next();var c=this.start,u=this.startLoc,h=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),c,u,s,i),p=this.buildBinary(e,n,t,h,l,a||o);return(a&&this.type===x.coalesce||o&&(this.type===x.logicalOR||this.type===x.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(p,e,n,r,i)}return t};ce.buildBinary=function(t,e,n,r,i,s){r.type==="PrivateIdentifier"&&this.raise(r.start,"Private identifier can only be left side of binary expression");var a=this.startNodeAt(t,e);return a.left=n,a.operator=i,a.right=r,this.finishNode(a,s?"LogicalExpression":"BinaryExpression")};ce.parseMaybeUnary=function(t,e,n,r){var i=this.start,s=this.startLoc,a;if(this.isContextual("await")&&this.canAwait)a=this.parseAwait(r),e=!0;else if(this.type.prefix){var o=this.startNode(),l=this.type===x.incDec;o.operator=this.value,o.prefix=!0,this.next(),o.argument=this.parseMaybeUnary(null,!0,l,r),this.checkExpressionErrors(t,!0),l?this.checkLValSimple(o.argument):this.strict&&o.operator==="delete"&&gm(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):o.operator==="delete"&&gc(o.argument)?this.raiseRecoverable(o.start,"Private fields can not be deleted"):e=!0,a=this.finishNode(o,l?"UpdateExpression":"UnaryExpression")}else if(!e&&this.type===x.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),a=this.parsePrivateIdent(),this.type!==x._in&&this.unexpected();else{if(a=this.parseExprSubscripts(t,r),this.checkExpressionErrors(t))return a;for(;this.type.postfix&&!this.canInsertSemicolon();){var c=this.startNodeAt(i,s);c.operator=this.value,c.prefix=!1,c.argument=a,this.checkLValSimple(a),this.next(),a=this.finishNode(c,"UpdateExpression")}}if(!n&&this.eat(x.starstar))if(e)this.unexpected(this.lastTokStart);else return this.buildBinary(i,s,a,this.parseMaybeUnary(null,!1,!1,r),"**",!1);else return a};function gm(t){return t.type==="Identifier"||t.type==="ParenthesizedExpression"&&gm(t.expression)}function gc(t){return t.type==="MemberExpression"&&t.property.type==="PrivateIdentifier"||t.type==="ChainExpression"&&gc(t.expression)||t.type==="ParenthesizedExpression"&&gc(t.expression)}ce.parseExprSubscripts=function(t,e){var n=this.start,r=this.startLoc,i=this.parseExprAtom(t,e);if(i.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return i;var s=this.parseSubscripts(i,n,r,!1,e);return t&&s.type==="MemberExpression"&&(t.parenthesizedAssign>=s.start&&(t.parenthesizedAssign=-1),t.parenthesizedBind>=s.start&&(t.parenthesizedBind=-1),t.trailingComma>=s.start&&(t.trailingComma=-1)),s};ce.parseSubscripts=function(t,e,n,r,i){for(var s=this.options.ecmaVersion>=8&&t.type==="Identifier"&&t.name==="async"&&this.lastTokEnd===t.end&&!this.canInsertSemicolon()&&t.end-t.start===5&&this.potentialArrowAt===t.start,a=!1;;){var o=this.parseSubscript(t,e,n,r,s,a,i);if(o.optional&&(a=!0),o===t||o.type==="ArrowFunctionExpression"){if(a){var l=this.startNodeAt(e,n);l.expression=o,o=this.finishNode(l,"ChainExpression")}return o}t=o}};ce.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(x.arrow)};ce.parseSubscriptAsyncArrow=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!0,r)};ce.parseSubscript=function(t,e,n,r,i,s,a){var o=this.options.ecmaVersion>=11,l=o&&this.eat(x.questionDot);r&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var c=this.eat(x.bracketL);if(c||l&&this.type!==x.parenL&&this.type!==x.backQuote||this.eat(x.dot)){var u=this.startNodeAt(e,n);u.object=t,c?(u.property=this.parseExpression(),this.expect(x.bracketR)):this.type===x.privateId&&t.type!=="Super"?u.property=this.parsePrivateIdent():u.property=this.parseIdent(this.options.allowReserved!=="never"),u.computed=!!c,o&&(u.optional=l),t=this.finishNode(u,"MemberExpression")}else if(!r&&this.eat(x.parenL)){var h=new xo,p=this.yieldPos,d=this.awaitPos,f=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var m=this.parseExprList(x.parenR,this.options.ecmaVersion>=8,!1,h);if(i&&!l&&this.shouldParseAsyncArrow())return this.checkPatternErrors(h,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use \'await\' as identifier inside an async function"),this.yieldPos=p,this.awaitPos=d,this.awaitIdentPos=f,this.parseSubscriptAsyncArrow(e,n,m,a);this.checkExpressionErrors(h,!0),this.yieldPos=p||this.yieldPos,this.awaitPos=d||this.awaitPos,this.awaitIdentPos=f||this.awaitIdentPos;var y=this.startNodeAt(e,n);y.callee=t,y.arguments=m,o&&(y.optional=l),t=this.finishNode(y,"CallExpression")}else if(this.type===x.backQuote){(l||s)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var g=this.startNodeAt(e,n);g.tag=t,g.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(g,"TaggedTemplateExpression")}return t};ce.parseExprAtom=function(t,e,n){this.type===x.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case x._super:return this.allowSuper||this.raise(this.start,"\'super\' keyword outside a method"),r=this.startNode(),this.next(),this.type===x.parenL&&!this.allowDirectSuper&&this.raise(r.start,"super() call outside constructor of a subclass"),this.type!==x.dot&&this.type!==x.bracketL&&this.type!==x.parenL&&this.unexpected(),this.finishNode(r,"Super");case x._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case x.name:var s=this.start,a=this.startLoc,o=this.containsEsc,l=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!o&&l.name==="async"&&!this.canInsertSemicolon()&&this.eat(x._function))return this.overrideContext(je.f_expr),this.parseFunction(this.startNodeAt(s,a),0,!1,!0,e);if(i&&!this.canInsertSemicolon()){if(this.eat(x.arrow))return this.parseArrowExpression(this.startNodeAt(s,a),[l],!1,e);if(this.options.ecmaVersion>=8&&l.name==="async"&&this.type===x.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return l=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(x.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,a),[l],!0,e)}return l;case x.regexp:var c=this.value;return r=this.parseLiteral(c.value),r.regex={pattern:c.pattern,flags:c.flags},r;case x.num:case x.string:return this.parseLiteral(this.value);case x._null:case x._true:case x._false:return r=this.startNode(),r.value=this.type===x._null?null:this.type===x._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,"Literal");case x.parenL:var u=this.start,h=this.parseParenAndDistinguishExpression(i,e);return t&&(t.parenthesizedAssign<0&&!this.isSimpleAssignTarget(h)&&(t.parenthesizedAssign=u),t.parenthesizedBind<0&&(t.parenthesizedBind=u)),h;case x.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(x.bracketR,!0,!0,t),this.finishNode(r,"ArrayExpression");case x.braceL:return this.overrideContext(je.b_expr),this.parseObj(!1,t);case x._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case x._class:return this.parseClass(this.startNode(),!1);case x._new:return this.parseNew();case x.backQuote:return this.parseTemplate();case x._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}};ce.parseExprAtomDefault=function(){this.unexpected()};ce.parseExprImport=function(t){var e=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===x.parenL&&!t)return this.parseDynamicImport(e);if(this.type===x.dot){var n=this.startNodeAt(e.start,e.loc&&e.loc.start);return n.name="import",e.meta=this.finishNode(n,"Identifier"),this.parseImportMeta(e)}else this.unexpected()};ce.parseDynamicImport=function(t){if(this.next(),t.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(x.parenR)?t.options=null:(this.expect(x.comma),this.afterTrailingComma(x.parenR)?t.options=null:(t.options=this.parseMaybeAssign(),this.eat(x.parenR)||(this.expect(x.comma),this.afterTrailingComma(x.parenR)||this.unexpected())));else if(!this.eat(x.parenR)){var e=this.start;this.eat(x.comma)&&this.eat(x.parenR)?this.raiseRecoverable(e,"Trailing comma is not allowed in import()"):this.unexpected(e)}return this.finishNode(t,"ImportExpression")};ce.parseImportMeta=function(t){this.next();var e=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="meta"&&this.raiseRecoverable(t.property.start,"The only valid meta property for import is \'import.meta\'"),e&&this.raiseRecoverable(t.start,"\'import.meta\' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(t.start,"Cannot use \'import.meta\' outside a module"),this.finishNode(t,"MetaProperty")};ce.parseLiteral=function(t){var e=this.startNode();return e.value=t,e.raw=this.input.slice(this.start,this.end),e.raw.charCodeAt(e.raw.length-1)===110&&(e.bigint=e.value!=null?e.value.toString():e.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(e,"Literal")};ce.parseParenExpression=function(){this.expect(x.parenL);var t=this.parseExpression();return this.expect(x.parenR),t};ce.shouldParseArrow=function(t){return!this.canInsertSemicolon()};ce.parseParenAndDistinguishExpression=function(t,e){var n=this.start,r=this.startLoc,i,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc,l=[],c=!0,u=!1,h=new xo,p=this.yieldPos,d=this.awaitPos,f;for(this.yieldPos=0,this.awaitPos=0;this.type!==x.parenR;)if(c?c=!1:this.expect(x.comma),s&&this.afterTrailingComma(x.parenR,!0)){u=!0;break}else if(this.type===x.ellipsis){f=this.start,l.push(this.parseParenItem(this.parseRestBinding())),this.type===x.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else l.push(this.parseMaybeAssign(!1,h,this.parseParenItem));var m=this.lastTokEnd,y=this.lastTokEndLoc;if(this.expect(x.parenR),t&&this.shouldParseArrow(l)&&this.eat(x.arrow))return this.checkPatternErrors(h,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=p,this.awaitPos=d,this.parseParenArrowList(n,r,l,e);(!l.length||u)&&this.unexpected(this.lastTokStart),f&&this.unexpected(f),this.checkExpressionErrors(h,!0),this.yieldPos=p||this.yieldPos,this.awaitPos=d||this.awaitPos,l.length>1?(i=this.startNodeAt(a,o),i.expressions=l,this.finishNodeAt(i,"SequenceExpression",m,y)):i=l[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var g=this.startNodeAt(n,r);return g.expression=i,this.finishNode(g,"ParenthesizedExpression")}else return i};ce.parseParenItem=function(t){return t};ce.parseParenArrowList=function(t,e,n,r){return this.parseArrowExpression(this.startNodeAt(t,e),n,!1,r)};var VN=[];ce.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var t=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===x.dot){var e=this.startNodeAt(t.start,t.loc&&t.loc.start);e.name="new",t.meta=this.finishNode(e,"Identifier"),this.next();var n=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="target"&&this.raiseRecoverable(t.property.start,"The only valid meta property for new is \'new.target\'"),n&&this.raiseRecoverable(t.start,"\'new.target\' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(t.start,"\'new.target\' can only be used in functions and class static block"),this.finishNode(t,"MetaProperty")}var r=this.start,i=this.startLoc;return t.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,i,!0,!1),this.eat(x.parenL)?t.arguments=this.parseExprList(x.parenR,this.options.ecmaVersion>=8,!1):t.arguments=VN,this.finishNode(t,"NewExpression")};ce.parseTemplateElement=function(t){var e=t.isTagged,n=this.startNode();return this.type===x.invalidTemplate?(e||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),n.value={raw:this.value.replace(/\\r\\n?/g,`\n`),cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\\r\\n?/g,`\n`),cooked:this.value},this.next(),n.tail=this.type===x.backQuote,this.finishNode(n,"TemplateElement")};ce.parseTemplate=function(t){t===void 0&&(t={});var e=t.isTagged;e===void 0&&(e=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:e});for(n.quasis=[r];!r.tail;)this.type===x.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(x.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(x.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:e}));return this.next(),this.finishNode(n,"TemplateLiteral")};ce.isAsyncProp=function(t){return!t.computed&&t.key.type==="Identifier"&&t.key.name==="async"&&(this.type===x.name||this.type===x.num||this.type===x.string||this.type===x.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===x.star)&&!zt.test(this.input.slice(this.lastTokEnd,this.start))};ce.parseObj=function(t,e){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(x.braceR);){if(r)r=!1;else if(this.expect(x.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(x.braceR))break;var s=this.parseProperty(t,e);t||this.checkPropClash(s,i,e),n.properties.push(s)}return this.finishNode(n,t?"ObjectPattern":"ObjectExpression")};ce.parseProperty=function(t,e){var n=this.startNode(),r,i,s,a;if(this.options.ecmaVersion>=9&&this.eat(x.ellipsis))return t?(n.argument=this.parseIdent(!1),this.type===x.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(n,"RestElement")):(n.argument=this.parseMaybeAssign(!1,e),this.type===x.comma&&e&&e.trailingComma<0&&(e.trailingComma=this.start),this.finishNode(n,"SpreadElement"));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(t||e)&&(s=this.start,a=this.startLoc),t||(r=this.eat(x.star)));var o=this.containsEsc;return this.parsePropertyName(n),!t&&!o&&this.options.ecmaVersion>=8&&!r&&this.isAsyncProp(n)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(x.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,t,r,i,s,a,e,o),this.finishNode(n,"Property")};ce.parseGetterSetter=function(t){var e=t.key.name;this.parsePropertyName(t),t.value=this.parseMethod(!1),t.kind=e;var n=t.kind==="get"?0:1;if(t.value.params.length!==n){var r=t.value.start;t.kind==="get"?this.raiseRecoverable(r,"getter should have no params"):this.raiseRecoverable(r,"setter should have exactly one param")}else t.kind==="set"&&t.value.params[0].type==="RestElement"&&this.raiseRecoverable(t.value.params[0].start,"Setter cannot use rest params")};ce.parsePropertyValue=function(t,e,n,r,i,s,a,o){(n||r)&&this.type===x.colon&&this.unexpected(),this.eat(x.colon)?(t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),t.kind="init"):this.options.ecmaVersion>=6&&this.type===x.parenL?(e&&this.unexpected(),t.method=!0,t.value=this.parseMethod(n,r),t.kind="init"):!e&&!o&&this.options.ecmaVersion>=5&&!t.computed&&t.key.type==="Identifier"&&(t.key.name==="get"||t.key.name==="set")&&this.type!==x.comma&&this.type!==x.braceR&&this.type!==x.eq?((n||r)&&this.unexpected(),this.parseGetterSetter(t)):this.options.ecmaVersion>=6&&!t.computed&&t.key.type==="Identifier"?((n||r)&&this.unexpected(),this.checkUnreserved(t.key),t.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=i),e?t.value=this.parseMaybeDefault(i,s,this.copyNode(t.key)):this.type===x.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),t.value=this.parseMaybeDefault(i,s,this.copyNode(t.key))):t.value=this.copyNode(t.key),t.kind="init",t.shorthand=!0):this.unexpected()};ce.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(x.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(x.bracketR),t.key;t.computed=!1}return t.key=this.type===x.num||this.type===x.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ce.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)};ce.parseMethod=function(t,e,n){var r=this.startNode(),i=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=t),this.options.ecmaVersion>=8&&(r.async=!!e),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Wu(e,r.generator)|_o|(n?hm:0)),this.expect(x.parenL),r.params=this.parseBindingList(x.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(r,"FunctionExpression")};ce.parseArrowExpression=function(t,e,n,r){var i=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(Wu(n,!1)|Uu),this.initFunction(t),this.options.ecmaVersion>=8&&(t.async=!!n),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0,!1,r),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(t,"ArrowFunctionExpression")};ce.parseFunctionBody=function(t,e,n,r){var i=e&&this.type!==x.braceL,s=this.strict,a=!1;if(i)t.body=this.parseMaybeAssign(r),t.expression=!0,this.checkParams(t,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(t.params);(!s||o)&&(a=this.strictDirective(this.end),a&&o&&this.raiseRecoverable(t.start,"Illegal \'use strict\' directive in function with non-simple parameter list"));var l=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(t,!s&&!a&&!e&&!n&&this.isSimpleParamList(t.params)),this.strict&&t.id&&this.checkLValSimple(t.id,mm),t.body=this.parseBlock(!1,void 0,a&&!s),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=l}this.exitScope()};ce.isSimpleParamList=function(t){for(var e=0,n=t;e<n.length;e+=1){var r=n[e];if(r.type!=="Identifier")return!1}return!0};ce.checkParams=function(t,e){for(var n=Object.create(null),r=0,i=t.params;r<i.length;r+=1){var s=i[r];this.checkLValInnerPattern(s,Hu,e?null:n)}};ce.parseExprList=function(t,e,n,r){for(var i=[],s=!0;!this.eat(t);){if(s)s=!1;else if(this.expect(x.comma),e&&this.afterTrailingComma(t))break;var a=void 0;n&&this.type===x.comma?a=null:this.type===x.ellipsis?(a=this.parseSpread(r),r&&this.type===x.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):a=this.parseMaybeAssign(!1,r),i.push(a)}return i};ce.checkUnreserved=function(t){var e=t.start,n=t.end,r=t.name;if(this.inGenerator&&r==="yield"&&this.raiseRecoverable(e,"Cannot use \'yield\' as identifier inside a generator"),this.inAsync&&r==="await"&&this.raiseRecoverable(e,"Cannot use \'await\' as identifier inside an async function"),!(this.currentThisScope().flags&bo)&&r==="arguments"&&this.raiseRecoverable(e,"Cannot use \'arguments\' in class field initializer"),this.inClassStaticBlock&&(r==="arguments"||r==="await")&&this.raise(e,"Cannot use "+r+" in class static initialization block"),this.keywords.test(r)&&this.raise(e,"Unexpected keyword \'"+r+"\'"),!(this.options.ecmaVersion<6&&this.input.slice(e,n).indexOf("\\\\")!==-1)){var i=this.strict?this.reservedWordsStrict:this.reservedWords;i.test(r)&&(!this.inAsync&&r==="await"&&this.raiseRecoverable(e,"Cannot use keyword \'await\' outside an async function"),this.raiseRecoverable(e,"The keyword \'"+r+"\' is reserved"))}};ce.parseIdent=function(t){var e=this.parseIdentNode();return this.next(!!t),this.finishNode(e,"Identifier"),t||(this.checkUnreserved(e),e.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=e.start)),e};ce.parseIdentNode=function(){var t=this.startNode();return this.type===x.name?t.name=this.value:this.type.keyword?(t.name=this.type.keyword,(t.name==="class"||t.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=x.name):this.unexpected(),t};ce.parsePrivateIdent=function(){var t=this.startNode();return this.type===x.privateId?t.name=this.value:this.unexpected(),this.next(),this.finishNode(t,"PrivateIdentifier"),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(t.start,"Private field \'#"+t.name+"\' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(t)),t};ce.parseYield=function(t){this.yieldPos||(this.yieldPos=this.start);var e=this.startNode();return this.next(),this.type===x.semi||this.canInsertSemicolon()||this.type!==x.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(x.star),e.argument=this.parseMaybeAssign(t)),this.finishNode(e,"YieldExpression")};ce.parseAwait=function(t){this.awaitPos||(this.awaitPos=this.start);var e=this.startNode();return this.next(),e.argument=this.parseMaybeUnary(null,!0,!1,t),this.finishNode(e,"AwaitExpression")};var Ka=it.prototype;Ka.raise=function(t,e){var n=lm(this.input,t);e+=" ("+n.line+":"+n.column+")",this.sourceFile&&(e+=" in "+this.sourceFile);var r=new SyntaxError(e);throw r.pos=t,r.loc=n,r.raisedAt=this.pos,r};Ka.raiseRecoverable=Ka.raise;Ka.curPosition=function(){if(this.options.locations)return new Es(this.curLine,this.pos-this.lineStart)};var Lr=it.prototype,$N=function(t){this.flags=t,this.var=[],this.lexical=[],this.functions=[]};Lr.enterScope=function(t){this.scopeStack.push(new $N(t))};Lr.exitScope=function(){this.scopeStack.pop()};Lr.treatFunctionsAsVarInScope=function(t){return t.flags&Qr||!this.inModule&&t.flags&Xr};Lr.declareName=function(t,e,n){var r=!1;if(e===ar){var i=this.currentScope();r=i.lexical.indexOf(t)>-1||i.functions.indexOf(t)>-1||i.var.indexOf(t)>-1,i.lexical.push(t),this.inModule&&i.flags&Xr&&delete this.undefinedExports[t]}else if(e===fm){var s=this.currentScope();s.lexical.push(t)}else if(e===dm){var a=this.currentScope();this.treatFunctionsAsVar?r=a.lexical.indexOf(t)>-1:r=a.lexical.indexOf(t)>-1||a.var.indexOf(t)>-1,a.functions.push(t)}else for(var o=this.scopeStack.length-1;o>=0;--o){var l=this.scopeStack[o];if(l.lexical.indexOf(t)>-1&&!(l.flags&um&&l.lexical[0]===t)||!this.treatFunctionsAsVarInScope(l)&&l.functions.indexOf(t)>-1){r=!0;break}if(l.var.push(t),this.inModule&&l.flags&Xr&&delete this.undefinedExports[t],l.flags&bo)break}r&&this.raiseRecoverable(n,"Identifier \'"+t+"\' has already been declared")};Lr.checkLocalExport=function(t){this.scopeStack[0].lexical.indexOf(t.name)===-1&&this.scopeStack[0].var.indexOf(t.name)===-1&&(this.undefinedExports[t.name]=t)};Lr.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};Lr.currentVarScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(bo|Os|ei))return e}};Lr.currentThisScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(bo|Os|ei)&&!(e.flags&Uu))return e}};var vo=function(t,e,n){this.type="",this.start=e,this.end=0,t.options.locations&&(this.loc=new go(t,n)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[e,0])},Rs=it.prototype;Rs.startNode=function(){return new vo(this,this.start,this.startLoc)};Rs.startNodeAt=function(t,e){return new vo(this,t,e)};function _m(t,e,n,r){return t.type=e,t.end=n,this.options.locations&&(t.loc.end=r),this.options.ranges&&(t.range[1]=n),t}Rs.finishNode=function(t,e){return _m.call(this,t,e,this.lastTokEnd,this.lastTokEndLoc)};Rs.finishNodeAt=function(t,e,n,r){return _m.call(this,t,e,n,r)};Rs.copyNode=function(t){var e=new vo(this,t.start,this.startLoc);for(var n in t)e[n]=t[n];return e};var zN="Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz",bm="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",xm=bm+" Extended_Pictographic",vm=xm,wm=vm+" EBase EComp EMod EPres ExtPict",Sm=wm,jN=Sm,qN={9:bm,10:xm,11:vm,12:wm,13:Sm,14:jN},UN="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",WN={9:"",10:"",11:"",12:"",13:"",14:UN},id="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",Em="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",km=Em+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Am=km+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Tm=Am+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Nm=Tm+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",HN=Nm+" "+zN,GN={9:Em,10:km,11:Am,12:Tm,13:Nm,14:HN},Cm={};function KN(t){var e=Cm[t]={binary:kr(qN[t]+" "+id),binaryOfStrings:kr(WN[t]),nonBinary:{General_Category:kr(id),Script:kr(GN[t])}};e.nonBinary.Script_Extensions=e.nonBinary.Script,e.nonBinary.gc=e.nonBinary.General_Category,e.nonBinary.sc=e.nonBinary.Script,e.nonBinary.scx=e.nonBinary.Script_Extensions}for(ea=0,gl=[9,10,11,12,13,14];ea<gl.length;ea+=1)sd=gl[ea],KN(sd);var sd,ea,gl,Y=it.prototype,Ya=function(t,e){this.parent=t,this.base=e||this};Ya.prototype.separatedFrom=function(t){for(var e=this;e;e=e.parent)for(var n=t;n;n=n.parent)if(e.base===n.base&&e!==n)return!0;return!1};Ya.prototype.sibling=function(){return new Ya(this.parent,this.base)};var Gn=function(t){this.parser=t,this.validFlags="gim"+(t.options.ecmaVersion>=6?"uy":"")+(t.options.ecmaVersion>=9?"s":"")+(t.options.ecmaVersion>=13?"d":"")+(t.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Cm[t.options.ecmaVersion>=14?14:t.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};Gn.prototype.reset=function(t,e,n){var r=n.indexOf("v")!==-1,i=n.indexOf("u")!==-1;this.start=t|0,this.source=e+"",this.flags=n,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=i&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=i&&this.parser.options.ecmaVersion>=9)};Gn.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)};Gn.prototype.at=function(t,e){e===void 0&&(e=!1);var n=this.source,r=n.length;if(t>=r)return-1;var i=n.charCodeAt(t);if(!(e||this.switchU)||i<=55295||i>=57344||t+1>=r)return i;var s=n.charCodeAt(t+1);return s>=56320&&s<=57343?(i<<10)+s-56613888:i};Gn.prototype.nextIndex=function(t,e){e===void 0&&(e=!1);var n=this.source,r=n.length;if(t>=r)return r;var i=n.charCodeAt(t),s;return!(e||this.switchU)||i<=55295||i>=57344||t+1>=r||(s=n.charCodeAt(t+1))<56320||s>57343?t+1:t+2};Gn.prototype.current=function(t){return t===void 0&&(t=!1),this.at(this.pos,t)};Gn.prototype.lookahead=function(t){return t===void 0&&(t=!1),this.at(this.nextIndex(this.pos,t),t)};Gn.prototype.advance=function(t){t===void 0&&(t=!1),this.pos=this.nextIndex(this.pos,t)};Gn.prototype.eat=function(t,e){return e===void 0&&(e=!1),this.current(e)===t?(this.advance(e),!0):!1};Gn.prototype.eatChars=function(t,e){e===void 0&&(e=!1);for(var n=this.pos,r=0,i=t;r<i.length;r+=1){var s=i[r],a=this.at(n,e);if(a===-1||a!==s)return!1;n=this.nextIndex(n,e)}return this.pos=n,!0};Y.validateRegExpFlags=function(t){for(var e=t.validFlags,n=t.flags,r=!1,i=!1,s=0;s<n.length;s++){var a=n.charAt(s);e.indexOf(a)===-1&&this.raise(t.start,"Invalid regular expression flag"),n.indexOf(a,s+1)>-1&&this.raise(t.start,"Duplicate regular expression flag"),a==="u"&&(r=!0),a==="v"&&(i=!0)}this.options.ecmaVersion>=15&&r&&i&&this.raise(t.start,"Invalid regular expression flag")};function YN(t){for(var e in t)return!0;return!1}Y.validateRegExpPattern=function(t){this.regexp_pattern(t),!t.switchN&&this.options.ecmaVersion>=9&&YN(t.groupNames)&&(t.switchN=!0,this.regexp_pattern(t))};Y.regexp_pattern=function(t){t.pos=0,t.lastIntValue=0,t.lastStringValue="",t.lastAssertionIsQuantifiable=!1,t.numCapturingParens=0,t.maxBackReference=0,t.groupNames=Object.create(null),t.backReferenceNames.length=0,t.branchID=null,this.regexp_disjunction(t),t.pos!==t.source.length&&(t.eat(41)&&t.raise("Unmatched \')\'"),(t.eat(93)||t.eat(125))&&t.raise("Lone quantifier brackets")),t.maxBackReference>t.numCapturingParens&&t.raise("Invalid escape");for(var e=0,n=t.backReferenceNames;e<n.length;e+=1){var r=n[e];t.groupNames[r]||t.raise("Invalid named capture referenced")}};Y.regexp_disjunction=function(t){var e=this.options.ecmaVersion>=16;for(e&&(t.branchID=new Ya(t.branchID,null)),this.regexp_alternative(t);t.eat(124);)e&&(t.branchID=t.branchID.sibling()),this.regexp_alternative(t);e&&(t.branchID=t.branchID.parent),this.regexp_eatQuantifier(t,!0)&&t.raise("Nothing to repeat"),t.eat(123)&&t.raise("Lone quantifier brackets")};Y.regexp_alternative=function(t){for(;t.pos<t.source.length&&this.regexp_eatTerm(t););};Y.regexp_eatTerm=function(t){return this.regexp_eatAssertion(t)?(t.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(t)&&t.switchU&&t.raise("Invalid quantifier"),!0):(t.switchU?this.regexp_eatAtom(t):this.regexp_eatExtendedAtom(t))?(this.regexp_eatQuantifier(t),!0):!1};Y.regexp_eatAssertion=function(t){var e=t.pos;if(t.lastAssertionIsQuantifiable=!1,t.eat(94)||t.eat(36))return!0;if(t.eat(92)){if(t.eat(66)||t.eat(98))return!0;t.pos=e}if(t.eat(40)&&t.eat(63)){var n=!1;if(this.options.ecmaVersion>=9&&(n=t.eat(60)),t.eat(61)||t.eat(33))return this.regexp_disjunction(t),t.eat(41)||t.raise("Unterminated group"),t.lastAssertionIsQuantifiable=!n,!0}return t.pos=e,!1};Y.regexp_eatQuantifier=function(t,e){return e===void 0&&(e=!1),this.regexp_eatQuantifierPrefix(t,e)?(t.eat(63),!0):!1};Y.regexp_eatQuantifierPrefix=function(t,e){return t.eat(42)||t.eat(43)||t.eat(63)||this.regexp_eatBracedQuantifier(t,e)};Y.regexp_eatBracedQuantifier=function(t,e){var n=t.pos;if(t.eat(123)){var r=0,i=-1;if(this.regexp_eatDecimalDigits(t)&&(r=t.lastIntValue,t.eat(44)&&this.regexp_eatDecimalDigits(t)&&(i=t.lastIntValue),t.eat(125)))return i!==-1&&i<r&&!e&&t.raise("numbers out of order in {} quantifier"),!0;t.switchU&&!e&&t.raise("Incomplete quantifier"),t.pos=n}return!1};Y.regexp_eatAtom=function(t){return this.regexp_eatPatternCharacters(t)||t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)};Y.regexp_eatReverseSolidusAtomEscape=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatAtomEscape(t))return!0;t.pos=e}return!1};Y.regexp_eatUncapturingGroup=function(t){var e=t.pos;if(t.eat(40)){if(t.eat(63)){if(this.options.ecmaVersion>=16){var n=this.regexp_eatModifiers(t),r=t.eat(45);if(n||r){for(var i=0;i<n.length;i++){var s=n.charAt(i);n.indexOf(s,i+1)>-1&&t.raise("Duplicate regular expression modifiers")}if(r){var a=this.regexp_eatModifiers(t);!n&&!a&&t.current()===58&&t.raise("Invalid regular expression modifiers");for(var o=0;o<a.length;o++){var l=a.charAt(o);(a.indexOf(l,o+1)>-1||n.indexOf(l)>-1)&&t.raise("Duplicate regular expression modifiers")}}}}if(t.eat(58)){if(this.regexp_disjunction(t),t.eat(41))return!0;t.raise("Unterminated group")}}t.pos=e}return!1};Y.regexp_eatCapturingGroup=function(t){if(t.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(t):t.current()===63&&t.raise("Invalid group"),this.regexp_disjunction(t),t.eat(41))return t.numCapturingParens+=1,!0;t.raise("Unterminated group")}return!1};Y.regexp_eatModifiers=function(t){for(var e="",n=0;(n=t.current())!==-1&&XN(n);)e+=nr(n),t.advance();return e};function XN(t){return t===105||t===109||t===115}Y.regexp_eatExtendedAtom=function(t){return t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)||this.regexp_eatInvalidBracedQuantifier(t)||this.regexp_eatExtendedPatternCharacter(t)};Y.regexp_eatInvalidBracedQuantifier=function(t){return this.regexp_eatBracedQuantifier(t,!0)&&t.raise("Nothing to repeat"),!1};Y.regexp_eatSyntaxCharacter=function(t){var e=t.current();return Im(e)?(t.lastIntValue=e,t.advance(),!0):!1};function Im(t){return t===36||t>=40&&t<=43||t===46||t===63||t>=91&&t<=94||t>=123&&t<=125}Y.regexp_eatPatternCharacters=function(t){for(var e=t.pos,n=0;(n=t.current())!==-1&&!Im(n);)t.advance();return t.pos!==e};Y.regexp_eatExtendedPatternCharacter=function(t){var e=t.current();return e!==-1&&e!==36&&!(e>=40&&e<=43)&&e!==46&&e!==63&&e!==91&&e!==94&&e!==124?(t.advance(),!0):!1};Y.regexp_groupSpecifier=function(t){if(t.eat(63)){this.regexp_eatGroupName(t)||t.raise("Invalid group");var e=this.options.ecmaVersion>=16,n=t.groupNames[t.lastStringValue];if(n)if(e)for(var r=0,i=n;r<i.length;r+=1){var s=i[r];s.separatedFrom(t.branchID)||t.raise("Duplicate capture group name")}else t.raise("Duplicate capture group name");e?(n||(t.groupNames[t.lastStringValue]=[])).push(t.branchID):t.groupNames[t.lastStringValue]=!0}};Y.regexp_eatGroupName=function(t){if(t.lastStringValue="",t.eat(60)){if(this.regexp_eatRegExpIdentifierName(t)&&t.eat(62))return!0;t.raise("Invalid capture group name")}return!1};Y.regexp_eatRegExpIdentifierName=function(t){if(t.lastStringValue="",this.regexp_eatRegExpIdentifierStart(t)){for(t.lastStringValue+=nr(t.lastIntValue);this.regexp_eatRegExpIdentifierPart(t);)t.lastStringValue+=nr(t.lastIntValue);return!0}return!1};Y.regexp_eatRegExpIdentifierStart=function(t){var e=t.pos,n=this.options.ecmaVersion>=11,r=t.current(n);return t.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(t,n)&&(r=t.lastIntValue),ZN(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function ZN(t){return Hn(t,!0)||t===36||t===95}Y.regexp_eatRegExpIdentifierPart=function(t){var e=t.pos,n=this.options.ecmaVersion>=11,r=t.current(n);return t.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(t,n)&&(r=t.lastIntValue),JN(r)?(t.lastIntValue=r,!0):(t.pos=e,!1)};function JN(t){return Pr(t,!0)||t===36||t===95||t===8204||t===8205}Y.regexp_eatAtomEscape=function(t){return this.regexp_eatBackReference(t)||this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)||t.switchN&&this.regexp_eatKGroupName(t)?!0:(t.switchU&&(t.current()===99&&t.raise("Invalid unicode escape"),t.raise("Invalid escape")),!1)};Y.regexp_eatBackReference=function(t){var e=t.pos;if(this.regexp_eatDecimalEscape(t)){var n=t.lastIntValue;if(t.switchU)return n>t.maxBackReference&&(t.maxBackReference=n),!0;if(n<=t.numCapturingParens)return!0;t.pos=e}return!1};Y.regexp_eatKGroupName=function(t){if(t.eat(107)){if(this.regexp_eatGroupName(t))return t.backReferenceNames.push(t.lastStringValue),!0;t.raise("Invalid named reference")}return!1};Y.regexp_eatCharacterEscape=function(t){return this.regexp_eatControlEscape(t)||this.regexp_eatCControlLetter(t)||this.regexp_eatZero(t)||this.regexp_eatHexEscapeSequence(t)||this.regexp_eatRegExpUnicodeEscapeSequence(t,!1)||!t.switchU&&this.regexp_eatLegacyOctalEscapeSequence(t)||this.regexp_eatIdentityEscape(t)};Y.regexp_eatCControlLetter=function(t){var e=t.pos;if(t.eat(99)){if(this.regexp_eatControlLetter(t))return!0;t.pos=e}return!1};Y.regexp_eatZero=function(t){return t.current()===48&&!wo(t.lookahead())?(t.lastIntValue=0,t.advance(),!0):!1};Y.regexp_eatControlEscape=function(t){var e=t.current();return e===116?(t.lastIntValue=9,t.advance(),!0):e===110?(t.lastIntValue=10,t.advance(),!0):e===118?(t.lastIntValue=11,t.advance(),!0):e===102?(t.lastIntValue=12,t.advance(),!0):e===114?(t.lastIntValue=13,t.advance(),!0):!1};Y.regexp_eatControlLetter=function(t){var e=t.current();return Mm(e)?(t.lastIntValue=e%32,t.advance(),!0):!1};function Mm(t){return t>=65&&t<=90||t>=97&&t<=122}Y.regexp_eatRegExpUnicodeEscapeSequence=function(t,e){e===void 0&&(e=!1);var n=t.pos,r=e||t.switchU;if(t.eat(117)){if(this.regexp_eatFixedHexDigits(t,4)){var i=t.lastIntValue;if(r&&i>=55296&&i<=56319){var s=t.pos;if(t.eat(92)&&t.eat(117)&&this.regexp_eatFixedHexDigits(t,4)){var a=t.lastIntValue;if(a>=56320&&a<=57343)return t.lastIntValue=(i-55296)*1024+(a-56320)+65536,!0}t.pos=s,t.lastIntValue=i}return!0}if(r&&t.eat(123)&&this.regexp_eatHexDigits(t)&&t.eat(125)&&QN(t.lastIntValue))return!0;r&&t.raise("Invalid unicode escape"),t.pos=n}return!1};function QN(t){return t>=0&&t<=1114111}Y.regexp_eatIdentityEscape=function(t){if(t.switchU)return this.regexp_eatSyntaxCharacter(t)?!0:t.eat(47)?(t.lastIntValue=47,!0):!1;var e=t.current();return e!==99&&(!t.switchN||e!==107)?(t.lastIntValue=e,t.advance(),!0):!1};Y.regexp_eatDecimalEscape=function(t){t.lastIntValue=0;var e=t.current();if(e>=49&&e<=57){do t.lastIntValue=10*t.lastIntValue+(e-48),t.advance();while((e=t.current())>=48&&e<=57);return!0}return!1};var Pm=0,rr=1,un=2;Y.regexp_eatCharacterClassEscape=function(t){var e=t.current();if(eC(e))return t.lastIntValue=-1,t.advance(),rr;var n=!1;if(t.switchU&&this.options.ecmaVersion>=9&&((n=e===80)||e===112)){t.lastIntValue=-1,t.advance();var r;if(t.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(t))&&t.eat(125))return n&&r===un&&t.raise("Invalid property name"),r;t.raise("Invalid property name")}return Pm};function eC(t){return t===100||t===68||t===115||t===83||t===119||t===87}Y.regexp_eatUnicodePropertyValueExpression=function(t){var e=t.pos;if(this.regexp_eatUnicodePropertyName(t)&&t.eat(61)){var n=t.lastStringValue;if(this.regexp_eatUnicodePropertyValue(t)){var r=t.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(t,n,r),rr}}if(t.pos=e,this.regexp_eatLoneUnicodePropertyNameOrValue(t)){var i=t.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(t,i)}return Pm};Y.regexp_validateUnicodePropertyNameAndValue=function(t,e,n){$i(t.unicodeProperties.nonBinary,e)||t.raise("Invalid property name"),t.unicodeProperties.nonBinary[e].test(n)||t.raise("Invalid property value")};Y.regexp_validateUnicodePropertyNameOrValue=function(t,e){if(t.unicodeProperties.binary.test(e))return rr;if(t.switchV&&t.unicodeProperties.binaryOfStrings.test(e))return un;t.raise("Invalid property name")};Y.regexp_eatUnicodePropertyName=function(t){var e=0;for(t.lastStringValue="";Dm(e=t.current());)t.lastStringValue+=nr(e),t.advance();return t.lastStringValue!==""};function Dm(t){return Mm(t)||t===95}Y.regexp_eatUnicodePropertyValue=function(t){var e=0;for(t.lastStringValue="";tC(e=t.current());)t.lastStringValue+=nr(e),t.advance();return t.lastStringValue!==""};function tC(t){return Dm(t)||wo(t)}Y.regexp_eatLoneUnicodePropertyNameOrValue=function(t){return this.regexp_eatUnicodePropertyValue(t)};Y.regexp_eatCharacterClass=function(t){if(t.eat(91)){var e=t.eat(94),n=this.regexp_classContents(t);return t.eat(93)||t.raise("Unterminated character class"),e&&n===un&&t.raise("Negated character class may contain strings"),!0}return!1};Y.regexp_classContents=function(t){return t.current()===93?rr:t.switchV?this.regexp_classSetExpression(t):(this.regexp_nonEmptyClassRanges(t),rr)};Y.regexp_nonEmptyClassRanges=function(t){for(;this.regexp_eatClassAtom(t);){var e=t.lastIntValue;if(t.eat(45)&&this.regexp_eatClassAtom(t)){var n=t.lastIntValue;t.switchU&&(e===-1||n===-1)&&t.raise("Invalid character class"),e!==-1&&n!==-1&&e>n&&t.raise("Range out of order in character class")}}};Y.regexp_eatClassAtom=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatClassEscape(t))return!0;if(t.switchU){var n=t.current();(n===99||Lm(n))&&t.raise("Invalid class escape"),t.raise("Invalid escape")}t.pos=e}var r=t.current();return r!==93?(t.lastIntValue=r,t.advance(),!0):!1};Y.regexp_eatClassEscape=function(t){var e=t.pos;if(t.eat(98))return t.lastIntValue=8,!0;if(t.switchU&&t.eat(45))return t.lastIntValue=45,!0;if(!t.switchU&&t.eat(99)){if(this.regexp_eatClassControlLetter(t))return!0;t.pos=e}return this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)};Y.regexp_classSetExpression=function(t){var e=rr,n;if(!this.regexp_eatClassSetRange(t))if(n=this.regexp_eatClassSetOperand(t)){n===un&&(e=un);for(var r=t.pos;t.eatChars([38,38]);){if(t.current()!==38&&(n=this.regexp_eatClassSetOperand(t))){n!==un&&(e=rr);continue}t.raise("Invalid character in character class")}if(r!==t.pos)return e;for(;t.eatChars([45,45]);)this.regexp_eatClassSetOperand(t)||t.raise("Invalid character in character class");if(r!==t.pos)return e}else t.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(t)){if(n=this.regexp_eatClassSetOperand(t),!n)return e;n===un&&(e=un)}};Y.regexp_eatClassSetRange=function(t){var e=t.pos;if(this.regexp_eatClassSetCharacter(t)){var n=t.lastIntValue;if(t.eat(45)&&this.regexp_eatClassSetCharacter(t)){var r=t.lastIntValue;return n!==-1&&r!==-1&&n>r&&t.raise("Range out of order in character class"),!0}t.pos=e}return!1};Y.regexp_eatClassSetOperand=function(t){return this.regexp_eatClassSetCharacter(t)?rr:this.regexp_eatClassStringDisjunction(t)||this.regexp_eatNestedClass(t)};Y.regexp_eatNestedClass=function(t){var e=t.pos;if(t.eat(91)){var n=t.eat(94),r=this.regexp_classContents(t);if(t.eat(93))return n&&r===un&&t.raise("Negated character class may contain strings"),r;t.pos=e}if(t.eat(92)){var i=this.regexp_eatCharacterClassEscape(t);if(i)return i;t.pos=e}return null};Y.regexp_eatClassStringDisjunction=function(t){var e=t.pos;if(t.eatChars([92,113])){if(t.eat(123)){var n=this.regexp_classStringDisjunctionContents(t);if(t.eat(125))return n}else t.raise("Invalid escape");t.pos=e}return null};Y.regexp_classStringDisjunctionContents=function(t){for(var e=this.regexp_classString(t);t.eat(124);)this.regexp_classString(t)===un&&(e=un);return e};Y.regexp_classString=function(t){for(var e=0;this.regexp_eatClassSetCharacter(t);)e++;return e===1?rr:un};Y.regexp_eatClassSetCharacter=function(t){var e=t.pos;if(t.eat(92))return this.regexp_eatCharacterEscape(t)||this.regexp_eatClassSetReservedPunctuator(t)?!0:t.eat(98)?(t.lastIntValue=8,!0):(t.pos=e,!1);var n=t.current();return n<0||n===t.lookahead()&&nC(n)||rC(n)?!1:(t.advance(),t.lastIntValue=n,!0)};function nC(t){return t===33||t>=35&&t<=38||t>=42&&t<=44||t===46||t>=58&&t<=64||t===94||t===96||t===126}function rC(t){return t===40||t===41||t===45||t===47||t>=91&&t<=93||t>=123&&t<=125}Y.regexp_eatClassSetReservedPunctuator=function(t){var e=t.current();return iC(e)?(t.lastIntValue=e,t.advance(),!0):!1};function iC(t){return t===33||t===35||t===37||t===38||t===44||t===45||t>=58&&t<=62||t===64||t===96||t===126}Y.regexp_eatClassControlLetter=function(t){var e=t.current();return wo(e)||e===95?(t.lastIntValue=e%32,t.advance(),!0):!1};Y.regexp_eatHexEscapeSequence=function(t){var e=t.pos;if(t.eat(120)){if(this.regexp_eatFixedHexDigits(t,2))return!0;t.switchU&&t.raise("Invalid escape"),t.pos=e}return!1};Y.regexp_eatDecimalDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;wo(n=t.current());)t.lastIntValue=10*t.lastIntValue+(n-48),t.advance();return t.pos!==e};function wo(t){return t>=48&&t<=57}Y.regexp_eatHexDigits=function(t){var e=t.pos,n=0;for(t.lastIntValue=0;Om(n=t.current());)t.lastIntValue=16*t.lastIntValue+Rm(n),t.advance();return t.pos!==e};function Om(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function Rm(t){return t>=65&&t<=70?10+(t-65):t>=97&&t<=102?10+(t-97):t-48}Y.regexp_eatLegacyOctalEscapeSequence=function(t){if(this.regexp_eatOctalDigit(t)){var e=t.lastIntValue;if(this.regexp_eatOctalDigit(t)){var n=t.lastIntValue;e<=3&&this.regexp_eatOctalDigit(t)?t.lastIntValue=e*64+n*8+t.lastIntValue:t.lastIntValue=e*8+n}else t.lastIntValue=e;return!0}return!1};Y.regexp_eatOctalDigit=function(t){var e=t.current();return Lm(e)?(t.lastIntValue=e-48,t.advance(),!0):(t.lastIntValue=0,!1)};function Lm(t){return t>=48&&t<=55}Y.regexp_eatFixedHexDigits=function(t,e){var n=t.pos;t.lastIntValue=0;for(var r=0;r<e;++r){var i=t.current();if(!Om(i))return t.pos=n,!1;t.lastIntValue=16*t.lastIntValue+Rm(i),t.advance()}return!0};var Ku=function(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,t.options.locations&&(this.loc=new go(t,t.startLoc,t.endLoc)),t.options.ranges&&(this.range=[t.start,t.end])},me=it.prototype;me.next=function(t){!t&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new Ku(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};me.getToken=function(){return this.next(),new Ku(this)};typeof Symbol<"u"&&(me[Symbol.iterator]=function(){var t=this;return{next:function(){var e=t.getToken();return{done:e.type===x.eof,value:e}}}});me.nextToken=function(){var t=this.curContext();if((!t||!t.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(x.eof);if(t.override)return t.override(this);this.readToken(this.fullCharCodeAtPos())};me.readToken=function(t){return Hn(t,this.options.ecmaVersion>=6)||t===92?this.readWord():this.getTokenFromCode(t)};me.fullCharCodeAt=function(t){var e=this.input.charCodeAt(t);if(e<=55295||e>=56320)return e;var n=this.input.charCodeAt(t+1);return n<=56319||n>=57344?e:(e<<10)+n-56613888};me.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};me.skipBlockComment=function(){var t=this.options.onComment&&this.curPosition(),e=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=n+2,this.options.locations)for(var r=void 0,i=e;(r=sm(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(e+2,n),e,this.pos,t,this.curPosition())};me.skipLineComment=function(t){for(var e=this.pos,n=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=t);this.pos<this.input.length&&!Vi(r);)r=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(e+t,this.pos),e,this.pos,n,this.curPosition())};me.skipSpace=function(){e:for(;this.pos<this.input.length;){var t=this.input.charCodeAt(this.pos);switch(t){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break e}break;default:if(t>8&&t<14||t>=5760&&am.test(String.fromCharCode(t)))++this.pos;else break e}}};me.finishToken=function(t,e){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=t,this.value=e,this.updateContext(n)};me.readToken_dot=function(){var t=this.input.charCodeAt(this.pos+1);if(t>=48&&t<=57)return this.readNumber(!0);var e=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&t===46&&e===46?(this.pos+=3,this.finishToken(x.ellipsis)):(++this.pos,this.finishToken(x.dot))};me.readToken_slash=function(){var t=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):t===61?this.finishOp(x.assign,2):this.finishOp(x.slash,1)};me.readToken_mult_modulo_exp=function(t){var e=this.input.charCodeAt(this.pos+1),n=1,r=t===42?x.star:x.modulo;return this.options.ecmaVersion>=7&&t===42&&e===42&&(++n,r=x.starstar,e=this.input.charCodeAt(this.pos+2)),e===61?this.finishOp(x.assign,n+1):this.finishOp(r,n)};me.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.pos+1);if(e===t){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61)return this.finishOp(x.assign,3)}return this.finishOp(t===124?x.logicalOR:x.logicalAND,2)}return e===61?this.finishOp(x.assign,2):this.finishOp(t===124?x.bitwiseOR:x.bitwiseAND,1)};me.readToken_caret=function(){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(x.assign,2):this.finishOp(x.bitwiseXOR,1)};me.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.pos+1);return e===t?e===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||zt.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(x.incDec,2):e===61?this.finishOp(x.assign,2):this.finishOp(x.plusMin,1)};me.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.pos+1),n=1;return e===t?(n=t===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+n)===61?this.finishOp(x.assign,n+1):this.finishOp(x.bitShift,n)):e===33&&t===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(e===61&&(n=2),this.finishOp(x.relational,n))};me.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(x.equality,this.input.charCodeAt(this.pos+2)===61?3:2):t===61&&e===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(x.arrow)):this.finishOp(t===61?x.eq:x.prefix,1)};me.readToken_question=function(){var t=this.options.ecmaVersion;if(t>=11){var e=this.input.charCodeAt(this.pos+1);if(e===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57)return this.finishOp(x.questionDot,2)}if(e===63){if(t>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61)return this.finishOp(x.assign,3)}return this.finishOp(x.coalesce,2)}}return this.finishOp(x.question,1)};me.readToken_numberSign=function(){var t=this.options.ecmaVersion,e=35;if(t>=13&&(++this.pos,e=this.fullCharCodeAtPos(),Hn(e,!0)||e===92))return this.finishToken(x.privateId,this.readWord1());this.raise(this.pos,"Unexpected character \'"+nr(e)+"\'")};me.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(x.parenL);case 41:return++this.pos,this.finishToken(x.parenR);case 59:return++this.pos,this.finishToken(x.semi);case 44:return++this.pos,this.finishToken(x.comma);case 91:return++this.pos,this.finishToken(x.bracketL);case 93:return++this.pos,this.finishToken(x.bracketR);case 123:return++this.pos,this.finishToken(x.braceL);case 125:return++this.pos,this.finishToken(x.braceR);case 58:return++this.pos,this.finishToken(x.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(x.backQuote);case 48:var e=this.input.charCodeAt(this.pos+1);if(e===120||e===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(e===111||e===79)return this.readRadixNumber(8);if(e===98||e===66)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(t);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(t);case 124:case 38:return this.readToken_pipe_amp(t);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(t);case 60:case 62:return this.readToken_lt_gt(t);case 61:case 33:return this.readToken_eq_excl(t);case 63:return this.readToken_question();case 126:return this.finishOp(x.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character \'"+nr(t)+"\'")};me.finishOp=function(t,e){var n=this.input.slice(this.pos,this.pos+e);return this.pos+=e,this.finishToken(t,n)};me.readRegexp=function(){for(var t,e,n=this.pos;;){this.pos>=this.input.length&&this.raise(n,"Unterminated regular expression");var r=this.input.charAt(this.pos);if(zt.test(r)&&this.raise(n,"Unterminated regular expression"),t)t=!1;else{if(r==="[")e=!0;else if(r==="]"&&e)e=!1;else if(r==="/"&&!e)break;t=r==="\\\\"}++this.pos}var i=this.input.slice(n,this.pos);++this.pos;var s=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(s);var o=this.regexpState||(this.regexpState=new Gn(this));o.reset(n,i,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var l=null;try{l=new RegExp(i,a)}catch{}return this.finishToken(x.regexp,{pattern:i,flags:a,value:l})};me.readInt=function(t,e,n){for(var r=this.options.ecmaVersion>=12&&e===void 0,i=n&&this.input.charCodeAt(this.pos)===48,s=this.pos,a=0,o=0,l=0,c=e??1/0;l<c;++l,++this.pos){var u=this.input.charCodeAt(this.pos),h=void 0;if(r&&u===95){i&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),o===95&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),l===0&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),o=u;continue}if(u>=97?h=u-97+10:u>=65?h=u-65+10:u>=48&&u<=57?h=u-48:h=1/0,h>=t)break;o=u,a=a*t+h}return r&&o===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===s||e!=null&&this.pos-s!==e?null:a};function sC(t,e){return e?parseInt(t,8):parseFloat(t.replace(/_/g,""))}function Fm(t){return typeof BigInt!="function"?null:BigInt(t.replace(/_/g,""))}me.readRadixNumber=function(t){var e=this.pos;this.pos+=2;var n=this.readInt(t);return n==null&&this.raise(this.start+2,"Expected number in radix "+t),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(n=Fm(this.input.slice(e,this.pos)),++this.pos):Hn(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(x.num,n)};me.readNumber=function(t){var e=this.pos;!t&&this.readInt(10,void 0,!0)===null&&this.raise(e,"Invalid number");var n=this.pos-e>=2&&this.input.charCodeAt(e)===48;n&&this.strict&&this.raise(e,"Invalid number");var r=this.input.charCodeAt(this.pos);if(!n&&!t&&this.options.ecmaVersion>=11&&r===110){var i=Fm(this.input.slice(e,this.pos));return++this.pos,Hn(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(x.num,i)}n&&/[89]/.test(this.input.slice(e,this.pos))&&(n=!1),r===46&&!n&&(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),(r===69||r===101)&&!n&&(r=this.input.charCodeAt(++this.pos),(r===43||r===45)&&++this.pos,this.readInt(10)===null&&this.raise(e,"Invalid number")),Hn(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s=sC(this.input.slice(e,this.pos),n);return this.finishToken(x.num,s)};me.readCodePoint=function(){var t=this.input.charCodeAt(this.pos),e;if(t===123){this.options.ecmaVersion<6&&this.unexpected();var n=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(n,"Code point out of bounds")}else e=this.readHexChar(4);return e};me.readString=function(t){for(var e="",n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===t)break;r===92?(e+=this.input.slice(n,this.pos),e+=this.readEscapedChar(!1),n=this.pos):r===8232||r===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Vi(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return e+=this.input.slice(n,this.pos++),this.finishToken(x.string,e)};var Bm={};me.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(t){if(t===Bm)this.readInvalidTemplateToken();else throw t}this.inTemplateElement=!1};me.invalidStringToken=function(t,e){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw Bm;this.raise(t,e)};me.readTmplToken=function(){for(var t="",e=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===x.template||this.type===x.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(x.dollarBraceL)):(++this.pos,this.finishToken(x.backQuote)):(t+=this.input.slice(e,this.pos),this.finishToken(x.template,t));if(n===92)t+=this.input.slice(e,this.pos),t+=this.readEscapedChar(!0),e=this.pos;else if(Vi(n)){switch(t+=this.input.slice(e,this.pos),++this.pos,n){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:t+=`\n`;break;default:t+=String.fromCharCode(n);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),e=this.pos}else++this.pos}};me.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\\\":++this.pos;break;case"$":if(this.input[this.pos+1]!=="{")break;case"`":return this.finishToken(x.invalidTemplate,this.input.slice(this.start,this.pos));case"\\r":this.input[this.pos+1]===`\n`&&++this.pos;case`\n`:case"\\u2028":case"\\u2029":++this.curLine,this.lineStart=this.pos+1;break}this.raise(this.start,"Unterminated template")};me.readEscapedChar=function(t){var e=this.input.charCodeAt(++this.pos);switch(++this.pos,e){case 110:return`\n`;case 114:return"\\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return nr(this.readCodePoint());case 116:return" ";case 98:return"\\b";case 118:return"\\v";case 102:return"\\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),t){var n=this.pos-1;this.invalidStringToken(n,"Invalid escape sequence in template string")}default:if(e>=48&&e<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,e=this.input.charCodeAt(this.pos),(r!=="0"||e===56||e===57)&&(this.strict||t)&&this.invalidStringToken(this.pos-1-r.length,t?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(i)}return Vi(e)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(e)}};me.readHexChar=function(t){var e=this.pos,n=this.readInt(16,t);return n===null&&this.invalidStringToken(e,"Bad character escape sequence"),n};me.readWord1=function(){this.containsEsc=!1;for(var t="",e=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(Pr(i,r))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,t+=this.input.slice(n,this.pos);var s=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\\\uXXXX"),++this.pos;var a=this.readCodePoint();(e?Hn:Pr)(a,r)||this.invalidStringToken(s,"Invalid Unicode escape"),t+=nr(a),n=this.pos}else break;e=!1}return t+this.input.slice(n,this.pos)};me.readWord=function(){var t=this.readWord1(),e=x.name;return this.keywords.test(t)&&(e=ju[t]),this.finishToken(e,t)};var aC="8.16.0";it.acorn={Parser:it,version:aC,defaultOptions:mc,Position:Es,SourceLocation:go,getLineInfo:lm,Node:vo,TokenType:we,tokTypes:x,keywordTypes:ju,TokContext:xn,tokContexts:je,isIdentifierChar:Pr,isIdentifierStart:Hn,Token:Ku,isNewLine:Vi,lineBreak:zt,lineBreakG:CN,nonASCIIwhitespace:am};function Xa(t,e){return it.parse(t,e)}var{stringify:oC}=JSON;if(!String.prototype.repeat)throw new Error("String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation");if(!String.prototype.endsWith)throw new Error("String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation");var ta={"||":2,"??":3,"&&":4,"|":5,"^":6,"&":7,"==":8,"!=":8,"===":8,"!==":8,"<":9,">":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},Tn=17,lC={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:Tn,ClassExpression:Tn,FunctionExpression:Tn,ObjectExpression:Tn,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function yi(t,e){let{generator:n}=t;if(t.write("("),e!=null&&e.length>0){n[e[0].type](e[0],t);let{length:r}=e;for(let i=1;i<r;i++){let s=e[i];t.write(", "),n[s.type](s,t)}}t.write(")")}function Vm(t,e,n,r){let i=t.expressionsPrecedence[e.type];if(i===Tn)return!0;let s=t.expressionsPrecedence[n.type];return i!==s?!r&&i===15&&s===14&&n.operator==="**"||i<s:i!==13&&i!==14?!1:e.operator==="**"&&n.operator==="**"?!r:i===13&&s===13&&(e.operator==="??"||n.operator==="??")?!0:r?ta[e.operator]<=ta[n.operator]:ta[e.operator]<ta[n.operator]}function na(t,e,n,r){let{generator:i}=t;Vm(t,e,n,r)?(t.write("("),i[e.type](e,t),t.write(")")):i[e.type](e,t)}function cC(t,e,n,r){let i=e.split(`\n`),s=i.length-1;if(t.write(i[0].trim()),s>0){t.write(r);for(let a=1;a<s;a++)t.write(n+i[a].trim()+r);t.write(n+i[s].trim())}}function kt(t,e,n,r){let{length:i}=e;for(let s=0;s<i;s++){let a=e[s];t.write(n),a.type[0]==="L"?t.write("// "+a.value.trim()+`\n`,a):(t.write("/*"),cC(t,a.value,n,r),t.write("*/"+r))}}function uC(t){let e=t;for(;e!=null;){let{type:n}=e;if(n[0]==="C"&&n[1]==="a")return!0;if(n[0]==="M"&&n[1]==="e"&&n[2]==="m")e=e.object;else return!1}}function _l(t,e){let{generator:n}=t,{declarations:r}=e;t.write(e.kind+" ");let{length:i}=r;if(i>0){n.VariableDeclarator(r[0],t);for(let s=1;s<i;s++)t.write(", "),n.VariableDeclarator(r[s],t)}}var ad,od,ld,cd,ud,hd,Yu={Program(t,e){let n=e.indent.repeat(e.indentLevel),{lineEnd:r,writeComments:i}=e;i&&t.comments!=null&&kt(e,t.comments,n,r);let s=t.body,{length:a}=s;for(let o=0;o<a;o++){let l=s[o];i&&l.comments!=null&&kt(e,l.comments,n,r),e.write(n),this[l.type](l,e),e.write(r)}i&&t.trailingComments!=null&&kt(e,t.trailingComments,n,r)},BlockStatement:hd=function(t,e){let n=e.indent.repeat(e.indentLevel++),{lineEnd:r,writeComments:i}=e,s=n+e.indent;e.write("{");let a=t.body;if(a!=null&&a.length>0){e.write(r),i&&t.comments!=null&&kt(e,t.comments,s,r);let{length:o}=a;for(let l=0;l<o;l++){let c=a[l];i&&c.comments!=null&&kt(e,c.comments,s,r),e.write(s),this[c.type](c,e),e.write(r)}e.write(n)}else i&&t.comments!=null&&(e.write(r),kt(e,t.comments,s,r),e.write(n));i&&t.trailingComments!=null&&kt(e,t.trailingComments,s,r),e.write("}"),e.indentLevel--},ClassBody:hd,StaticBlock(t,e){e.write("static "),this.BlockStatement(t,e)},EmptyStatement(t,e){e.write(";")},ExpressionStatement(t,e){let n=e.expressionsPrecedence[t.expression.type];n===Tn||n===3&&t.expression.left.type[0]==="O"?(e.write("("),this[t.expression.type](t.expression,e),e.write(")")):this[t.expression.type](t.expression,e),e.write(";")},IfStatement(t,e){e.write("if ("),this[t.test.type](t.test,e),e.write(") "),this[t.consequent.type](t.consequent,e),t.alternate!=null&&(e.write(" else "),this[t.alternate.type](t.alternate,e))},LabeledStatement(t,e){this[t.label.type](t.label,e),e.write(": "),this[t.body.type](t.body,e)},BreakStatement(t,e){e.write("break"),t.label!=null&&(e.write(" "),this[t.label.type](t.label,e)),e.write(";")},ContinueStatement(t,e){e.write("continue"),t.label!=null&&(e.write(" "),this[t.label.type](t.label,e)),e.write(";")},WithStatement(t,e){e.write("with ("),this[t.object.type](t.object,e),e.write(") "),this[t.body.type](t.body,e)},SwitchStatement(t,e){let n=e.indent.repeat(e.indentLevel++),{lineEnd:r,writeComments:i}=e;e.indentLevel++;let s=n+e.indent,a=s+e.indent;e.write("switch ("),this[t.discriminant.type](t.discriminant,e),e.write(") {"+r);let{cases:o}=t,{length:l}=o;for(let c=0;c<l;c++){let u=o[c];i&&u.comments!=null&&kt(e,u.comments,s,r),u.test?(e.write(s+"case "),this[u.test.type](u.test,e),e.write(":"+r)):e.write(s+"default:"+r);let{consequent:h}=u,{length:p}=h;for(let d=0;d<p;d++){let f=h[d];i&&f.comments!=null&&kt(e,f.comments,a,r),e.write(a),this[f.type](f,e),e.write(r)}}e.indentLevel-=2,e.write(n+"}")},ReturnStatement(t,e){e.write("return"),t.argument&&(e.write(" "),this[t.argument.type](t.argument,e)),e.write(";")},ThrowStatement(t,e){e.write("throw "),this[t.argument.type](t.argument,e),e.write(";")},TryStatement(t,e){if(e.write("try "),this[t.block.type](t.block,e),t.handler){let{handler:n}=t;n.param==null?e.write(" catch "):(e.write(" catch ("),this[n.param.type](n.param,e),e.write(") ")),this[n.body.type](n.body,e)}t.finalizer&&(e.write(" finally "),this[t.finalizer.type](t.finalizer,e))},WhileStatement(t,e){e.write("while ("),this[t.test.type](t.test,e),e.write(") "),this[t.body.type](t.body,e)},DoWhileStatement(t,e){e.write("do "),this[t.body.type](t.body,e),e.write(" while ("),this[t.test.type](t.test,e),e.write(");")},ForStatement(t,e){if(e.write("for ("),t.init!=null){let{init:n}=t;n.type[0]==="V"?_l(e,n):this[n.type](n,e)}e.write("; "),t.test&&this[t.test.type](t.test,e),e.write("; "),t.update&&this[t.update.type](t.update,e),e.write(") "),this[t.body.type](t.body,e)},ForInStatement:ad=function(t,e){e.write(`for ${t.await?"await ":""}(`);let{left:n}=t;n.type[0]==="V"?_l(e,n):this[n.type](n,e),e.write(t.type[3]==="I"?" in ":" of "),this[t.right.type](t.right,e),e.write(") "),this[t.body.type](t.body,e)},ForOfStatement:ad,DebuggerStatement(t,e){e.write("debugger;",t)},FunctionDeclaration:od=function(t,e){e.write((t.async?"async ":"")+(t.generator?"function* ":"function ")+(t.id?t.id.name:""),t),yi(e,t.params),e.write(" "),this[t.body.type](t.body,e)},FunctionExpression:od,VariableDeclaration(t,e){_l(e,t),e.write(";")},VariableDeclarator(t,e){this[t.id.type](t.id,e),t.init!=null&&(e.write(" = "),this[t.init.type](t.init,e))},ClassDeclaration(t,e){if(e.write("class "+(t.id?`${t.id.name} `:""),t),t.superClass){e.write("extends ");let{superClass:n}=t,{type:r}=n,i=e.expressionsPrecedence[r];(r[0]!=="C"||r[1]!=="l"||r[5]!=="E")&&(i===Tn||i<e.expressionsPrecedence.ClassExpression)?(e.write("("),this[t.superClass.type](n,e),e.write(")")):this[n.type](n,e),e.write(" ")}this.ClassBody(t.body,e)},ImportDeclaration(t,e){e.write("import ");let{specifiers:n,attributes:r}=t,{length:i}=n,s=0;if(i>0){for(;s<i;){s>0&&e.write(", ");let a=n[s],o=a.type[6];if(o==="D")e.write(a.local.name,a),s++;else if(o==="N")e.write("* as "+a.local.name,a),s++;else break}if(s<i){for(e.write("{");;){let a=n[s],{name:o}=a.imported;if(e.write(o,a),o!==a.local.name&&e.write(" as "+a.local.name),++s<i)e.write(", ");else break}e.write("}")}e.write(" from ")}if(this.Literal(t.source,e),r&&r.length>0){e.write(" with { ");for(let a=0;a<r.length;a++)this.ImportAttribute(r[a],e),a<r.length-1&&e.write(", ");e.write(" }")}e.write(";")},ImportAttribute(t,e){this.Identifier(t.key,e),e.write(": "),this.Literal(t.value,e)},ImportExpression(t,e){e.write("import("),this[t.source.type](t.source,e),e.write(")")},ExportDefaultDeclaration(t,e){e.write("export default "),this[t.declaration.type](t.declaration,e),e.expressionsPrecedence[t.declaration.type]!=null&&t.declaration.type[0]!=="F"&&e.write(";")},ExportNamedDeclaration(t,e){if(e.write("export "),t.declaration)this[t.declaration.type](t.declaration,e);else{e.write("{");let{specifiers:n}=t,{length:r}=n;if(r>0)for(let i=0;;){let s=n[i],{name:a}=s.local;if(e.write(a,s),a!==s.exported.name&&e.write(" as "+s.exported.name),++i<r)e.write(", ");else break}if(e.write("}"),t.source&&(e.write(" from "),this.Literal(t.source,e)),t.attributes&&t.attributes.length>0){e.write(" with { ");for(let i=0;i<t.attributes.length;i++)this.ImportAttribute(t.attributes[i],e),i<t.attributes.length-1&&e.write(", ");e.write(" }")}e.write(";")}},ExportAllDeclaration(t,e){if(t.exported!=null?e.write("export * as "+t.exported.name+" from "):e.write("export * from "),this.Literal(t.source,e),t.attributes&&t.attributes.length>0){e.write(" with { ");for(let n=0;n<t.attributes.length;n++)this.ImportAttribute(t.attributes[n],e),n<t.attributes.length-1&&e.write(", ");e.write(" }")}e.write(";")},MethodDefinition(t,e){t.static&&e.write("static ");let n=t.kind[0];(n==="g"||n==="s")&&e.write(t.kind+" "),t.value.async&&e.write("async "),t.value.generator&&e.write("*"),t.computed?(e.write("["),this[t.key.type](t.key,e),e.write("]")):this[t.key.type](t.key,e),yi(e,t.value.params),e.write(" "),this[t.value.body.type](t.value.body,e)},ClassExpression(t,e){this.ClassDeclaration(t,e)},ArrowFunctionExpression(t,e){e.write(t.async?"async ":"",t);let{params:n}=t;n!=null&&(n.length===1&&n[0].type[0]==="I"?e.write(n[0].name,n[0]):yi(e,t.params)),e.write(" => "),t.body.type[0]==="O"?(e.write("("),this.ObjectExpression(t.body,e),e.write(")")):this[t.body.type](t.body,e)},ThisExpression(t,e){e.write("this",t)},Super(t,e){e.write("super",t)},RestElement:ld=function(t,e){e.write("..."),this[t.argument.type](t.argument,e)},SpreadElement:ld,YieldExpression(t,e){e.write(t.delegate?"yield*":"yield"),t.argument&&(e.write(" "),this[t.argument.type](t.argument,e))},AwaitExpression(t,e){e.write("await ",t),na(e,t.argument,t)},TemplateLiteral(t,e){let{quasis:n,expressions:r}=t;e.write("`");let{length:i}=r;for(let a=0;a<i;a++){let o=r[a],l=n[a];e.write(l.value.raw,l),e.write("${"),this[o.type](o,e),e.write("}")}let s=n[n.length-1];e.write(s.value.raw,s),e.write("`")},TemplateElement(t,e){e.write(t.value.raw,t)},TaggedTemplateExpression(t,e){na(e,t.tag,t),this[t.quasi.type](t.quasi,e)},ArrayExpression:ud=function(t,e){if(e.write("["),t.elements.length>0){let{elements:n}=t,{length:r}=n;for(let i=0;;){let s=n[i];if(s!=null&&this[s.type](s,e),++i<r)e.write(", ");else{s==null&&e.write(", ");break}}}e.write("]")},ArrayPattern:ud,ObjectExpression(t,e){let n=e.indent.repeat(e.indentLevel++),{lineEnd:r,writeComments:i}=e,s=n+e.indent;if(e.write("{"),t.properties.length>0){e.write(r),i&&t.comments!=null&&kt(e,t.comments,s,r);let a=","+r,{properties:o}=t,{length:l}=o;for(let c=0;;){let u=o[c];if(i&&u.comments!=null&&kt(e,u.comments,s,r),e.write(s),this[u.type](u,e),++c<l)e.write(a);else break}e.write(r),i&&t.trailingComments!=null&&kt(e,t.trailingComments,s,r),e.write(n+"}")}else i?t.comments!=null?(e.write(r),kt(e,t.comments,s,r),t.trailingComments!=null&&kt(e,t.trailingComments,s,r),e.write(n+"}")):t.trailingComments!=null?(e.write(r),kt(e,t.trailingComments,s,r),e.write(n+"}")):e.write("}"):e.write("}");e.indentLevel--},Property(t,e){t.method||t.kind[0]!=="i"?this.MethodDefinition(t,e):(t.shorthand||(t.computed?(e.write("["),this[t.key.type](t.key,e),e.write("]")):this[t.key.type](t.key,e),e.write(": ")),this[t.value.type](t.value,e))},PropertyDefinition(t,e){if(t.static&&e.write("static "),t.computed&&e.write("["),this[t.key.type](t.key,e),t.computed&&e.write("]"),t.value==null){t.key.type[0]!=="F"&&e.write(";");return}e.write(" = "),this[t.value.type](t.value,e),e.write(";")},ObjectPattern(t,e){if(e.write("{"),t.properties.length>0){let{properties:n}=t,{length:r}=n;for(let i=0;this[n[i].type](n[i],e),++i<r;)e.write(", ")}e.write("}")},SequenceExpression(t,e){yi(e,t.expressions)},UnaryExpression(t,e){if(t.prefix){let{operator:n,argument:r,argument:{type:i}}=t;e.write(n);let s=Vm(e,r,t);!s&&(n.length>1||i[0]==="U"&&(i[1]==="n"||i[1]==="p")&&r.prefix&&r.operator[0]===n&&(n==="+"||n==="-"))&&e.write(" "),s?(e.write(n.length>1?" (":"("),this[i](r,e),e.write(")")):this[i](r,e)}else this[t.argument.type](t.argument,e),e.write(t.operator)},UpdateExpression(t,e){t.prefix?(e.write(t.operator),this[t.argument.type](t.argument,e)):(this[t.argument.type](t.argument,e),e.write(t.operator))},AssignmentExpression(t,e){this[t.left.type](t.left,e),e.write(" "+t.operator+" "),this[t.right.type](t.right,e)},AssignmentPattern(t,e){this[t.left.type](t.left,e),e.write(" = "),this[t.right.type](t.right,e)},BinaryExpression:cd=function(t,e){let n=t.operator==="in";n&&e.write("("),na(e,t.left,t,!1),e.write(" "+t.operator+" "),na(e,t.right,t,!0),n&&e.write(")")},LogicalExpression:cd,ConditionalExpression(t,e){let{test:n}=t,r=e.expressionsPrecedence[n.type];r===Tn||r<=e.expressionsPrecedence.ConditionalExpression?(e.write("("),this[n.type](n,e),e.write(")")):this[n.type](n,e),e.write(" ? "),this[t.consequent.type](t.consequent,e),e.write(" : "),this[t.alternate.type](t.alternate,e)},NewExpression(t,e){e.write("new ");let n=e.expressionsPrecedence[t.callee.type];n===Tn||n<e.expressionsPrecedence.CallExpression||uC(t.callee)?(e.write("("),this[t.callee.type](t.callee,e),e.write(")")):this[t.callee.type](t.callee,e),yi(e,t.arguments)},CallExpression(t,e){let n=e.expressionsPrecedence[t.callee.type];n===Tn||n<e.expressionsPrecedence.CallExpression?(e.write("("),this[t.callee.type](t.callee,e),e.write(")")):this[t.callee.type](t.callee,e),t.optional&&e.write("?."),yi(e,t.arguments)},ChainExpression(t,e){this[t.expression.type](t.expression,e)},MemberExpression(t,e){let n=e.expressionsPrecedence[t.object.type];n===Tn||n<e.expressionsPrecedence.MemberExpression?(e.write("("),this[t.object.type](t.object,e),e.write(")")):this[t.object.type](t.object,e),t.computed?(t.optional&&e.write("?."),e.write("["),this[t.property.type](t.property,e),e.write("]")):(t.optional?e.write("?."):e.write("."),this[t.property.type](t.property,e))},MetaProperty(t,e){e.write(t.meta.name+"."+t.property.name,t)},Identifier(t,e){e.write(t.name,t)},PrivateIdentifier(t,e){e.write(`#${t.name}`,t)},Literal(t,e){t.raw!=null?e.write(t.raw,t):t.regex!=null?this.RegExpLiteral(t,e):t.bigint!=null?e.write(t.bigint+"n",t):e.write(oC(t.value),t)},RegExpLiteral(t,e){let{regex:n}=t;e.write(`/${n.pattern}/${n.flags}`,t)}},hC={},pC=Yu,_c=class{constructor(e){let n=e??hC;this.output="",n.output!=null?(this.output=n.output,this.write=this.writeToStream):this.output="",this.generator=n.generator!=null?n.generator:Yu,this.expressionsPrecedence=n.expressionsPrecedence!=null?n.expressionsPrecedence:lC,this.indent=n.indent!=null?n.indent:" ",this.lineEnd=n.lineEnd!=null?n.lineEnd:`\n`,this.indentLevel=n.startingIndentLevel!=null?n.startingIndentLevel:0,this.writeComments=n.comments?n.comments:!1,n.sourceMap!=null&&(this.write=n.output==null?this.writeAndMap:this.writeToStreamAndMap,this.sourceMap=n.sourceMap,this.line=1,this.column=0,this.lineEndSize=this.lineEnd.split(`\n`).length-1,this.mapping={original:null,generated:this,name:void 0,source:n.sourceMap.file||n.sourceMap._file})}write(e){this.output+=e}writeToStream(e){this.output.write(e)}writeAndMap(e,n){this.output+=e,this.map(e,n)}writeToStreamAndMap(e,n){this.output.write(e),this.map(e,n)}map(e,n){if(n!=null){let{type:s}=n;if(s[0]==="L"&&s[2]==="n"){this.column=0,this.line++;return}if(n.loc!=null){let{mapping:a}=this;a.original=n.loc.start,a.name=n.name,this.sourceMap.addMapping(a)}if(s[0]==="T"&&s[8]==="E"||s[0]==="L"&&s[1]==="i"&&typeof n.value=="string"){let{length:a}=e,{column:o,line:l}=this;for(let c=0;c<a;c++)e[c]===`\n`?(o=0,l++):o++;this.column=o,this.line=l;return}}let{length:r}=e,{lineEnd:i}=this;r>0&&(this.lineEndSize>0&&(i.length===1?e[r-1]===i:e.endsWith(i))?(this.line+=this.lineEndSize,this.column=0):this.column+=r)}toString(){return this.output}};function Xu(t,e){let n=new _c(e);return n.generator[t.type](t,n),n.output}var dC=Object.defineProperty,fC=(t,e,n)=>e in t?dC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,de=(t,e,n)=>fC(t,typeof e!="symbol"?e+"":e,n),mC=new Set(["Infinity","NaN","undefined","null","true","false"]),yC=new Set(["Math","Array","Object","String","Number","Boolean","Date","RegExp","Error","JSON","Promise","Set","Map","WeakSet","WeakMap","Symbol","BigInt","Proxy","Reflect","console","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]);function bc(t){if(!t||typeof t!="string")return;let e=t.trim();if(e.endsWith("[]"))return"array";let n=e.indexOf("<");n>=0&&(e=e.slice(0,n));let r=e.split(/\\s+/).filter(Boolean);return r.length>0?r[r.length-1]:void 0}var xc=class{constructor(){de(this,"scopes",[]),de(this,"scopeTypes",[]),de(this,"scopeCounts",new Map),de(this,"contextBoundVars",new Set),de(this,"arrayPatternElements",new Set),de(this,"rootParams",new Set),de(this,"localSeriesVars",new Set),de(this,"functionParams",new Set),de(this,"varKinds",new Map),de(this,"loopVars",new Set),de(this,"loopVarNames",new Map),de(this,"paramIdCounter",0),de(this,"cacheIdCounter",0),de(this,"tempVarCounter",0),de(this,"taCallIdCounter",0),de(this,"userCallIdCounter",0),de(this,"plotCallIdCounter",0),de(this,"bareCallIdCounters",new Map),de(this,"alertCallIdCounter",0),de(this,"loopGuardCounter",0),de(this,"hoistingStack",[]),de(this,"hoistingRoots",[]),de(this,"suppressHoisting",!1),de(this,"inLoopTest",!1),de(this,"chainHoist",null),de(this,"historyRecordDepth",0),de(this,"reservedNames",new Set),de(this,"userFunctions",new Set),de(this,"userMethods",new Set),de(this,"regularUserFunctions",new Set),de(this,"udtTypeNames",new Map),de(this,"udtInstances",new Map),de(this,"functionReturnTypes",new Map),de(this,"functionReturnTupleTypes",new Map),de(this,"functionParamUdtTypes",new Map),de(this,"varStaticTypes",new Map),de(this,"methodReceiverTypes",new Map),de(this,"functionParamStaticTypes",new Map),de(this,"methodCandidates",new Map),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`\'p${this.paramIdCounter++}\'`}}get nextCacheIdArg(){return{type:"Identifier",name:`\'cache_${this.cacheIdCounter++}\'`}}getNextTACallId(){return{type:"Literal",value:`_ta${this.taCallIdCounter++}`}}getNextUserCallId(){return{type:"Literal",value:`_fn${this.userCallIdCounter++}`}}getNextPlotCallId(){return{type:"Literal",value:`#${this.plotCallIdCounter++}`}}getNextBareCallsiteId(e){let n=this.bareCallIdCounters.get(e)??0;return this.bareCallIdCounters.set(e,n+1),{type:"Literal",value:`${e}#${n}`}}getNextAlertCallId(){return{type:"Literal",value:`alert_${this.alertCallIdCounter++}`}}getNextLoopGuardName(){return`__lg${this.loopGuardCounter++}`}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]}isInsideFunctionScope(){for(let e=this.scopeTypes.length-1;e>=0;e--)if(this.scopeTypes[e]==="fn")return!0;return!1}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addLocalSeriesVar(e){this.localSeriesVars.add(e)}removeLocalSeriesVar(e){this.localSeriesVars.delete(e)}isLocalSeriesVar(e){return this.localSeriesVars.has(e)}addFunctionParam(e){this.functionParams.add(e),this.localSeriesVars.add(e)}removeFunctionParam(e){this.functionParams.delete(e),this.localSeriesVars.delete(e)}isFunctionParam(e){return this.functionParams.has(e)}addUdtTypeName(e,n={}){this.udtTypeNames.set(e,n)}isUdtTypeName(e){return this.udtTypeNames.has(e)}getUdtTypeFields(e){return this.udtTypeNames.get(e)}markVariableAsUdtInstance(e,n){this.udtInstances.set(e,n)}getVariableUdtType(e){return this.udtInstances.get(e)}isUdtInstance(e){return this.udtInstances.has(e)}setFunctionReturnType(e,n){let r=this.functionReturnTypes.get(e);if(r&&r!==n){this.functionReturnTypes.delete(e);return}this.functionReturnTypes.set(e,n)}getFunctionReturnType(e){return this.functionReturnTypes.get(e)}setFunctionReturnTupleType(e,n){let r=this.functionReturnTupleTypes.get(e);if(r&&(r.length!==n.length||r.some((i,s)=>i!==n[s]))){this.functionReturnTupleTypes.delete(e);return}this.functionReturnTupleTypes.set(e,n)}getFunctionReturnTupleType(e){return this.functionReturnTupleTypes.get(e)}setFunctionParamUdtTypes(e,n){this.functionParamUdtTypes.set(e,n)}getFunctionParamUdtTypes(e){return this.functionParamUdtTypes.get(e)}unmarkVariableAsUdtInstance(e){this.udtInstances.delete(e)}setVarStaticType(e,n){let r=bc(n);r&&this.varStaticTypes.set(e,r)}getVarStaticType(e){return this.varStaticTypes.get(e)}unsetVarStaticType(e){this.varStaticTypes.delete(e)}addMethodCandidate(e,n){let r=this.methodCandidates.get(e)??[];r.includes(n)||r.push(n),this.methodCandidates.set(e,r)}getMethodCandidates(e){return this.methodCandidates.get(e)??[]}setMethodReceiverType(e,n){let r=bc(n);r&&this.methodReceiverTypes.set(e,r)}isMethodReceiverTypeName(e){for(let n of this.methodReceiverTypes.values())if(n===e)return!0;return!1}getMethodReceiverType(e){return this.methodReceiverTypes.get(e)}setFunctionParamStaticTypes(e,n){this.functionParamStaticTypes.set(e,n)}getFunctionParamStaticTypes(e){return this.functionParamStaticTypes.get(e)}addContextBoundVar(e,n=!1){this.contextBoundVars.add(e),n&&this.rootParams.add(e)}removeContextBoundVar(e){this.contextBoundVars.has(e)&&(this.contextBoundVars.delete(e),this.rootParams.has(e)&&this.rootParams.delete(e))}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return mC.has(e)||yC.has(e)?!1:this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,n){this.loopVars.add(e),this.loopVarNames.set(e,n)}removeLoopVariable(e){this.loopVars.delete(e),this.loopVarNames.delete(e)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addReservedName(e){this.reservedNames.add(e)}addUserFunction(e){this.userFunctions.add(e)}isUserFunction(e){return this.userFunctions.has(e)}addUserMethod(e){this.userMethods.add(e)}isUserMethod(e){return this.userMethods.has(e)}addRegularUserFunction(e){this.regularUserFunctions.add(e)}isRegularUserFunction(e){return this.regularUserFunctions.has(e)}addVariable(e,n){if(this.isContextBound(e))return e;let r=this.scopes[this.scopes.length-1],i=this.scopeTypes[this.scopeTypes.length-1],s=this.scopeCounts.get(i)||1,a=`${i}${s}_${e}`;return r.set(e,a),this.varKinds.set(a,n),a}hideCurrentScopeVariable(e){let n=this.scopes[this.scopes.length-1],r=n?.get(e);return r===void 0?()=>{}:(n.delete(e),()=>n.set(e,r))}getVariable(e){if(this.loopVars.has(e)){let n=this.loopVarNames.get(e);if(n)return[n,"let"]}if(this.isContextBound(e))return[e,"let"];for(let n=this.scopes.length-1;n>=0;n--){let r=this.scopes[n];if(r.has(e)){let i=r.get(e),s=this.varKinds.get(i)||"let";return[i,s]}}return[e,"let"]}isVariableInFunctionScope(e){for(let n=this.scopes.length-1;n>=0;n--)if(this.scopes[n].has(e)){for(let r=0;r<=n;r++)if(this.scopeTypes[r]==="fn")return!0;return!1}return!1}generateTempVar(){return`temp_${++this.tempVarCounter}`}enterHoistingScope(){this.hoistingStack.push([])}exitHoistingScope(){return this.hoistingStack.pop()||[]}addHoistedStatement(e){this.hoistingStack.length>0&&!this.suppressHoisting&&((this.historyRecordDepth>0?this.activeChainFrame():null)??this.hoistingStack[this.hoistingStack.length-1]).push(e)}setChainHoistFrame(e){let n=this.chainHoist;return this.chainHoist=e?{frame:e,depth:this.hoistingStack.length}:null,n}restoreChainHoistFrame(e){this.chainHoist=e}enterHistoryRecord(){this.historyRecordDepth++}exitHistoryRecord(){this.historyRecordDepth--}activeChainFrame(){return this.chainHoist&&this.chainHoist.depth===this.hoistingStack.length?this.chainHoist.frame:null}addOuterHoistedStatement(e){if(this.hoistingStack.length>0){let n=Math.min(1,this.hoistingStack.length-1);this.hoistingStack[n].push(e)}}enterFunctionHoistingRoot(){this.hoistingRoots.push(this.hoistingStack.length)}exitFunctionHoistingRoot(){this.hoistingRoots.pop()}addScopeRootHoistedStatement(e){if(this.hoistingStack.length===0)return!1;let n=this.hoistingRoots.length>0?this.hoistingRoots[this.hoistingRoots.length-1]:1;return this.hoistingStack[Math.min(n,this.hoistingStack.length-1)].push(e),!0}getCurrentHoistingScope(){return this.hoistingStack.length===0?null:this.hoistingStack[this.hoistingStack.length-1]}setSuppressHoisting(e){this.suppressHoisting=e}setInLoopTest(e){this.inLoopTest=e}addEagerHoistedStatement(e){return this.hoistingStack.length===0||this.inLoopTest?!1:((this.activeChainFrame()??this.hoistingStack[this.hoistingStack.length-1]).push(e),!0)}shouldSuppressHoisting(){return this.suppressHoisting}hasVariableInScope(e){if(this.reservedNames.has(e))return!0;for(let n=this.scopes.length-1;n>=0;n--)if(this.scopes[n].has(e))return!0;return!!(this.contextBoundVars.has(e)||this.loopVars.has(e)||this.localSeriesVars.has(e))}generateParamId(){let e=`p${this.paramIdCounter++}`;for(;this.hasVariableInScope(e);)e=`p${this.paramIdCounter++}`;let n=this.scopes[this.scopes.length-1];return n&&n.set(e,e),e}};function xt(t,e,n,r,i){n||(n=j),(function s(a,o,l){var c=l||a.type;$m(n,c,a,o,s),e[c]&&e[c](a,o)})(t,r,i)}function Zu(t,e,n,r,i){var s=[];n||(n=j),(function a(o,l,c){var u=c||o.type,h=o!==s[s.length-1];h&&s.push(o),$m(n,u,o,l,a),e[u]&&e[u](o,l||s,s),h&&s.pop()})(t,r,i)}function ct(t,e,n,r,i){var s=n?gC(n,r||void 0):r;(function a(o,l,c){s[c||o.type](o,l,a)})(t,e,i)}function gC(t,e){var n=Object.create(e||j);for(var r in t)n[r]=t[r];return n}function Ju(t,e,n){n(t,e)}function ti(t,e,n){}function $m(t,e,n,r,i){if(t[e]==null)throw new Error("No walker function defined for node type "+e);t[e](n,r,i)}var j={};j.Program=j.BlockStatement=j.StaticBlock=function(t,e,n){for(var r=0,i=t.body;r<i.length;r+=1){var s=i[r];n(s,e,"Statement")}};j.Statement=Ju;j.EmptyStatement=ti;j.ExpressionStatement=j.ParenthesizedExpression=j.ChainExpression=function(t,e,n){return n(t.expression,e,"Expression")};j.IfStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Statement"),t.alternate&&n(t.alternate,e,"Statement")};j.LabeledStatement=function(t,e,n){return n(t.body,e,"Statement")};j.BreakStatement=j.ContinueStatement=ti;j.WithStatement=function(t,e,n){n(t.object,e,"Expression"),n(t.body,e,"Statement")};j.SwitchStatement=function(t,e,n){n(t.discriminant,e,"Expression");for(var r=0,i=t.cases;r<i.length;r+=1){var s=i[r];n(s,e)}};j.SwitchCase=function(t,e,n){t.test&&n(t.test,e,"Expression");for(var r=0,i=t.consequent;r<i.length;r+=1){var s=i[r];n(s,e,"Statement")}};j.ReturnStatement=j.YieldExpression=j.AwaitExpression=function(t,e,n){t.argument&&n(t.argument,e,"Expression")};j.ThrowStatement=j.SpreadElement=function(t,e,n){return n(t.argument,e,"Expression")};j.TryStatement=function(t,e,n){n(t.block,e,"Statement"),t.handler&&n(t.handler,e),t.finalizer&&n(t.finalizer,e,"Statement")};j.CatchClause=function(t,e,n){t.param&&n(t.param,e,"Pattern"),n(t.body,e,"Statement")};j.WhileStatement=j.DoWhileStatement=function(t,e,n){n(t.test,e,"Expression"),n(t.body,e,"Statement")};j.ForStatement=function(t,e,n){t.init&&n(t.init,e,"ForInit"),t.test&&n(t.test,e,"Expression"),t.update&&n(t.update,e,"Expression"),n(t.body,e,"Statement")};j.ForInStatement=j.ForOfStatement=function(t,e,n){n(t.left,e,"ForInit"),n(t.right,e,"Expression"),n(t.body,e,"Statement")};j.ForInit=function(t,e,n){t.type==="VariableDeclaration"?n(t,e):n(t,e,"Expression")};j.DebuggerStatement=ti;j.FunctionDeclaration=function(t,e,n){return n(t,e,"Function")};j.VariableDeclaration=function(t,e,n){for(var r=0,i=t.declarations;r<i.length;r+=1){var s=i[r];n(s,e)}};j.VariableDeclarator=function(t,e,n){n(t.id,e,"Pattern"),t.init&&n(t.init,e,"Expression")};j.Function=function(t,e,n){t.id&&n(t.id,e,"Pattern");for(var r=0,i=t.params;r<i.length;r+=1){var s=i[r];n(s,e,"Pattern")}n(t.body,e,t.expression?"Expression":"Statement")};j.Pattern=function(t,e,n){t.type==="Identifier"?n(t,e,"VariablePattern"):t.type==="MemberExpression"?n(t,e,"MemberPattern"):n(t,e)};j.VariablePattern=ti;j.MemberPattern=Ju;j.RestElement=function(t,e,n){return n(t.argument,e,"Pattern")};j.ArrayPattern=function(t,e,n){for(var r=0,i=t.elements;r<i.length;r+=1){var s=i[r];s&&n(s,e,"Pattern")}};j.ObjectPattern=function(t,e,n){for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];s.type==="Property"?(s.computed&&n(s.key,e,"Expression"),n(s.value,e,"Pattern")):s.type==="RestElement"&&n(s.argument,e,"Pattern")}};j.Expression=Ju;j.ThisExpression=j.Super=j.MetaProperty=ti;j.ArrayExpression=function(t,e,n){for(var r=0,i=t.elements;r<i.length;r+=1){var s=i[r];s&&n(s,e,"Expression")}};j.ObjectExpression=function(t,e,n){for(var r=0,i=t.properties;r<i.length;r+=1){var s=i[r];n(s,e)}};j.FunctionExpression=j.ArrowFunctionExpression=j.FunctionDeclaration;j.SequenceExpression=function(t,e,n){for(var r=0,i=t.expressions;r<i.length;r+=1){var s=i[r];n(s,e,"Expression")}};j.TemplateLiteral=function(t,e,n){for(var r=0,i=t.quasis;r<i.length;r+=1){var s=i[r];n(s,e)}for(var a=0,o=t.expressions;a<o.length;a+=1){var l=o[a];n(l,e,"Expression")}};j.TemplateElement=ti;j.UnaryExpression=j.UpdateExpression=function(t,e,n){n(t.argument,e,"Expression")};j.BinaryExpression=j.LogicalExpression=function(t,e,n){n(t.left,e,"Expression"),n(t.right,e,"Expression")};j.AssignmentExpression=j.AssignmentPattern=function(t,e,n){n(t.left,e,"Pattern"),n(t.right,e,"Expression")};j.ConditionalExpression=function(t,e,n){n(t.test,e,"Expression"),n(t.consequent,e,"Expression"),n(t.alternate,e,"Expression")};j.NewExpression=j.CallExpression=function(t,e,n){if(n(t.callee,e,"Expression"),t.arguments)for(var r=0,i=t.arguments;r<i.length;r+=1){var s=i[r];n(s,e,"Expression")}};j.MemberExpression=function(t,e,n){n(t.object,e,"Expression"),t.computed&&n(t.property,e,"Expression")};j.ExportNamedDeclaration=j.ExportDefaultDeclaration=function(t,e,n){if(t.declaration&&n(t.declaration,e,t.type==="ExportNamedDeclaration"||t.declaration.id?"Statement":"Expression"),t.source&&n(t.source,e,"Expression"),t.attributes)for(var r=0,i=t.attributes;r<i.length;r+=1){var s=i[r];n(s,e)}};j.ExportAllDeclaration=function(t,e,n){if(t.exported&&n(t.exported,e),n(t.source,e,"Expression"),t.attributes)for(var r=0,i=t.attributes;r<i.length;r+=1){var s=i[r];n(s,e)}};j.ImportAttribute=function(t,e,n){n(t.value,e,"Expression")};j.ImportDeclaration=function(t,e,n){for(var r=0,i=t.specifiers;r<i.length;r+=1){var s=i[r];n(s,e)}if(n(t.source,e,"Expression"),t.attributes)for(var a=0,o=t.attributes;a<o.length;a+=1){var l=o[a];n(l,e)}};j.ImportExpression=function(t,e,n){n(t.source,e,"Expression"),t.options&&n(t.options,e,"Expression")};j.ImportSpecifier=j.ImportDefaultSpecifier=j.ImportNamespaceSpecifier=j.Identifier=j.PrivateIdentifier=j.Literal=ti;j.TaggedTemplateExpression=function(t,e,n){n(t.tag,e,"Expression"),n(t.quasi,e,"Expression")};j.ClassDeclaration=j.ClassExpression=function(t,e,n){return n(t,e,"Class")};j.Class=function(t,e,n){t.id&&n(t.id,e,"Pattern"),t.superClass&&n(t.superClass,e,"Expression"),n(t.body,e)};j.ClassBody=function(t,e,n){for(var r=0,i=t.body;r<i.length;r+=1){var s=i[r];n(s,e)}};j.MethodDefinition=j.PropertyDefinition=j.Property=function(t,e,n){t.computed&&n(t.key,e,"Expression"),t.value&&n(t.value,e,"Expression")};var Oe="$",A={createIdentifier(t){return{type:"Identifier",name:t}},createLiteral(t){return{type:"Literal",value:t}},createMemberExpression(t,e,n=!1){return{type:"MemberExpression",object:t,property:e,computed:n}},createContextIdentifier(){return this.createIdentifier("$")},createLocalContextIdentifier(){return this.createIdentifier("$$")},createContextVariableReference(t,e){let n=this.createContextIdentifier(),r=this.createIdentifier(t),i=this.createIdentifier(e);return this.createMemberExpression(this.createMemberExpression(n,r,!1),i,!1)},createLocalContextVariableReference(t,e){let n=this.createLocalContextIdentifier(),r=this.createIdentifier(t),i=this.createIdentifier(e);return this.createMemberExpression(this.createMemberExpression(n,r,!1),i,!1)},createDynamicContextVariableReference(t,e){let n=this.createContextIdentifier(),r=this.createIdentifier(t);return this.createMemberExpression(this.createMemberExpression(n,r,!1),e,!0)},createContextVariableAccess0(t,e){let n=this.createContextVariableReference(t,e);return this.createGetCall(n,0)},createDynamicContextVariableAccess0(t,e){let n=this.createDynamicContextVariableReference(t,e);return this.createGetCall(n,0)},createArrayAccess(t,e){let n=typeof e=="number"?this.createLiteral(e):e;return this.createMemberExpression(t,n,!0)},createCallExpression(t,e){return{type:"CallExpression",callee:t,arguments:e}},createAssignmentExpression(t,e,n="="){return{type:"AssignmentExpression",operator:n,left:t,right:e}},createExpressionStatement(t){return{type:"ExpressionStatement",expression:t}},createInitCall(t,e,n){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("init"),!1),i=[t,e];return n&&i.push(n),this.createCallExpression(r,i)},createInitVarCall(t,e,n=!1){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("initVar"),!1),i=[t,e];return n&&i.push(this.createLiteral(!0)),this.createCallExpression(r,i)},createGetCall(t,e){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("get"),!1),r=typeof e=="number"?this.createLiteral(e):e;return this.createCallExpression(n,[t,r])},createSetCall(t,e){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("set"),!1);return this.createCallExpression(n,[t,e])},createMathEqCall(t,e){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(n,this.createIdentifier("math"),!1),i=this.createMemberExpression(r,this.createIdentifier("__eq"),!1);return this.createCallExpression(i,[t,e])},createMathNeqCall(t,e){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(n,this.createIdentifier("math"),!1),i=this.createMemberExpression(r,this.createIdentifier("__neq"),!1);return this.createCallExpression(i,[t,e])},createMathCompareCall(t,e,n){let r=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),i=this.createMemberExpression(r,this.createIdentifier("math"),!1),s=this.createMemberExpression(i,this.createIdentifier(t),!1);return this.createCallExpression(s,[e,n])},createMathIntDivCall(t,e){let n=this.createMemberExpression(this.createContextIdentifier(),this.createIdentifier("pine"),!1),r=this.createMemberExpression(n,this.createIdentifier("math"),!1),i=this.createMemberExpression(r,this.createIdentifier("__idiv"),!1);return this.createCallExpression(i,[t,e])},createWrapperFunction(t){return{type:"FunctionDeclaration",id:null,params:[this.createIdentifier("context")],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t}]}}},createVariableDeclaration(t,e){return{type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:this.createIdentifier(t),init:e}]}},createAwaitExpression(t){return{type:"AwaitExpression",argument:t}}};function _C(t){let e=null,n=Oe;if(t.type==="Program"&&t.body.length>0){let d=t.body[0];if(d.type==="ExpressionStatement"&&(d.expression.type==="ArrowFunctionExpression"||d.expression.type==="FunctionExpression")){let f=d.expression;f.body.type==="BlockStatement"&&(e=f.body.body,f.params.length>0&&f.params[0].type==="Identifier"&&(n=f.params[0].name))}}if(!e)return;let r=new Set,i=new Set,s=d=>{d.type==="Identifier"?r.add(d.name):d.type==="ObjectPattern"?d.properties.forEach(f=>s(f.value)):d.type==="ArrayPattern"&&d.elements.forEach(f=>{f&&s(f)})};ct(t,{},{VariableDeclarator(d,f,m){s(d.id),d.init&&m(d.init,f)},FunctionDeclaration(d,f,m){s(d.id);for(let y of d.params)y&&y.type==="AssignmentPattern"&&y.right&&m(y.right,f);m(d.body,f)},Identifier(d,f,m){i.add(d.name)},MemberExpression(d,f,m){m(d.object,f),d.computed&&m(d.property,f)},Property(d,f,m){d.computed&&m(d.key,f),m(d.value,f)}}),e.forEach(d=>{d.type==="VariableDeclaration"?d.declarations.forEach(f=>s(f.id)):d.type==="FunctionDeclaration"&&s(d.id)});let a=tm,o=yo,l=a.filter(d=>!r.has(d)),c=o.filter(d=>!r.has(d)),u=l.filter(d=>i.has(d)),h=c.filter(d=>i.has(d)),p=[];u.length>0&&p.push({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"ObjectPattern",properties:u.map(d=>({type:"Property",key:{type:"Identifier",name:d},value:{type:"Identifier",name:d},kind:"init",shorthand:!0}))},init:{type:"MemberExpression",object:{type:"Identifier",name:n},property:{type:"Identifier",name:"data"},computed:!1}}]}),h.length>0&&p.push({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"ObjectPattern",properties:h.map(d=>({type:"Property",key:{type:"Identifier",name:d},value:{type:"Identifier",name:d},kind:"init",shorthand:!0}))},init:{type:"MemberExpression",object:{type:"Identifier",name:n},property:{type:"Identifier",name:"pine"},computed:!1}}]}),p.length>0&&e.unshift(...p)}function bC(t){let e=null,n=Oe;if(t.type==="Program"&&t.body.length>0){let o=t.body[0];if(o.type==="ExpressionStatement"&&(o.expression.type==="ArrowFunctionExpression"||o.expression.type==="FunctionExpression")){let l=o.expression;l.body.type==="BlockStatement"&&(e=l.body.body,l.params.length>0&&l.params[0].type==="Identifier"&&(n=l.params[0].name))}}if(!e)return;let r=new Set(tm),i=new Set(yo),s=new Set(dN),a=new Map;e.forEach(o=>{o.type==="VariableDeclaration"&&o.declarations.forEach(l=>{if(l.init&&l.init.type==="MemberExpression"&&l.init.object.type==="Identifier"&&l.init.object.name===n&&l.init.property.type==="Identifier"){let c=l.init.property.name,u=null;if(c==="data"?u=r:c==="pine"?u=i:c==="core"&&(u=s),u&&l.id.type==="ObjectPattern")l.id.properties.forEach(h=>{if(h.type==="Property"&&h.key.type==="Identifier"&&h.value.type==="Identifier"){let p=h.key.name,d=h.value.name;u.has(p)&&p!==d&&(a.set(d,p),h.value.name=p,h.shorthand=!0)}});else if(l.id.type==="Identifier"&&sr.includes(c)){let h=c,p=l.id.name;h!==p&&(a.set(p,h),l.id.name=h)}}})}),a.size>0&&ct(t,{},{Identifier(o){a.has(o.name)&&(o.name=a.get(o.name))},MemberExpression(o,l,c){c(o.object,l),o.computed&&c(o.property,l)},Property(o,l,c){o.computed&&c(o.key,l),c(o.value,l)}})}function xC(t){try{let e=Xa(t,{ecmaVersion:"latest",sourceType:"module"});if(e.type==="Program"&&e.body.length===1){let n=e.body[0];if(n.type==="ExpressionStatement"){let r=n.expression;if(r.type==="ArrowFunctionExpression"||r.type==="FunctionExpression")return{isWrapped:!0,isAsync:r.async||!1,functionNode:r}}if(n.type==="FunctionDeclaration")return{isWrapped:!0,isAsync:n.async||!1,functionNode:n}}return{isWrapped:!1,isAsync:!1}}catch{return{isWrapped:!1,isAsync:!1}}}function vC(t){return t.async=!0,Xu(t)}function wC(t){t=t.trim();let{isWrapped:e,isAsync:n,functionNode:r}=xC(t);return e&&r?n?t:vC(r):`async (context) => {\n${t}\n}`}function SC(t){ct(t,null,{VariableDeclaration(e,n,r){e.declarations&&e.declarations.length>0&&e.declarations.forEach(i=>{if(i.init&&i.init.type==="ArrowFunctionExpression"&&i.init.start!==0){let s={type:"FunctionDeclaration",id:i.id,params:i.init.params,body:i.init.body.type==="BlockStatement"?i.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:i.init.body}]},async:i.init.async,generator:!1};Object.assign(e,s)}}),e.body&&e.body.body&&e.body.body.forEach(i=>r(i,n))}})}function EC(t){let e=new Set;if(xt(t,{FunctionDeclaration(i){i.id?.name&&e.add(i.id.name)}}),e.size===0)return;let n=i=>i.type==="AssignmentPattern"?i.left:i,r=new Map;xt(t,{FunctionDeclaration(i){let s=new Map;for(let a of i.params){let o=n(a);o?.type==="Identifier"&&e.has(o.name)&&(s.set(o.name,`${o.name}_$arg`),o.name=`${o.name}_$arg`)}s.size!==0&&(r.set(i.id.name,s),Zu(i.body,{Identifier(a,o,l){let c=s.get(a.name);if(!c)return;let u=l[l.length-2];u?.type==="CallExpression"&&u.callee===a||u?.type==="MemberExpression"&&u.property===a&&!u.computed||u?.type==="Property"&&u.key===a&&!u.computed||u?.type==="FunctionDeclaration"&&u.id===a||(a.name=c)}}))}}),xt(t,{AssignmentExpression(i){let s=i.left;if(s?.type!=="MemberExpression"||s.property?.name!=="__pineParamTypes__")return;let a=r.get(s.object?.name);if(!(!a||i.right?.type!=="ObjectExpression"))for(let o of i.right.properties){let l=o.key?.type==="Identifier"?o.key.name:o.key?.value,c=a.get(l);c&&(o.key={type:"Literal",value:c})}}})}function kC(t,e){xt(t,{VariableDeclaration(i){for(let s of i.declarations)if(!(s.id?.type!=="Identifier"||!s.init)&&s.init.type==="CallExpression"&&s.init.callee?.type==="Identifier"&&s.init.callee.name==="Type"&&s.init.arguments?.length===1&&s.init.arguments[0]?.type==="ObjectExpression"){let a={};for(let o of s.init.arguments[0].properties)o.type!=="Property"||o.key?.type!=="Identifier"||(o.value?.type==="ArrayExpression"&&o.value.elements?.[0]?.type==="Literal"?a[o.key.name]=String(o.value.elements[0].value):o.value?.type==="Literal"&&(a[o.key.name]=String(o.value.value)));e.addUdtTypeName(s.id.name,a),s.init._udtName=s.id.name}}});let n=!0;for(;n;)n=!1,xt(t,{FunctionDeclaration(i){if(!i.id?.name)return;let s=i.id.name;if(e.getFunctionReturnType(s)||e.getFunctionReturnTupleType(s))return;let a=NC(i.body);if(a.length===0)return;if(a.every(c=>c.type==="ArrayExpression")){let c=a[0].elements.length;if(c>0&&a.every(u=>u.elements.length===c)){let u=[],h=!0;for(let p=0;p<c;p++){let d=a.map(m=>ls(m.elements[p],e)),f=d[0];if(!d.every(m=>m===f)){h=!1;break}u.push(f)}if(h&&u.some(p=>!!p)){e.setFunctionReturnTupleType(s,u),n=!0;return}}}let o=a.map(c=>ls(c,e)),l=o[0];!l||!o.every(c=>c===l)||(e.setFunctionReturnType(s,l),n=!0)}});xt(t,{VariableDeclaration(i){for(let s of i.declarations)if(s.init){if(s.id?.type==="Identifier"){let a=ls(s.init,e);if(a){e.markVariableAsUdtInstance(s.id.name,a);continue}let o=vc(s.init);o&&e.setVarStaticType(s.id.name,o);continue}if(s.id?.type==="ArrayPattern"&&s.init.type==="CallExpression"&&s.init.callee?.type==="Identifier"){let a=e.getFunctionReturnTupleType(s.init.callee.name);if(!a)continue;s.id.elements?.forEach((o,l)=>{if(!o||o.type!=="Identifier")return;let c=a[l];c&&e.markVariableAsUdtInstance(o.name,c)})}}},ExpressionStatement(i){let s=i.expression;if(s?.type==="Literal"&&typeof s.value=="string"&&s.value.startsWith("__pineUdtVar:")){let a=s.value.match(/^__pineUdtVar:([A-Za-z_$][\\w$]*)=([A-Za-z_$][\\w$]*)$/);if(a){let[,o,l]=a;e.isUdtTypeName(l)&&e.markVariableAsUdtInstance(o,l)}}else if(s?.type==="Literal"&&typeof s.value=="string"&&s.value.startsWith("__pineTypedVar:")){let a=s.value.slice(15),o=a.indexOf("=");if(o>0){let l=a.slice(0,o),c=a.slice(o+1);/^[A-Za-z_$][\\w$]*$/.test(l)&&c&&e.setVarStaticType(l,c)}}}});let r=i=>{for(let s=0;s<i.length-1;s++){let a=i[s]?.type==="ExpressionStatement"?i[s].expression:null;if(a?.type!=="Literal"||typeof a.value!="string"||!a.value.startsWith("__pineVarip:"))continue;let o=a.value.slice(12),l=i[s+1];if(!(l?.type!=="VariableDeclaration"||l.kind!=="var"))for(let c of l.declarations)c.id?.type==="Identifier"&&c.id.name===o&&(c._varip=!0)}};xt(t,{Program(i){r(i.body)},BlockStatement(i){r(i.body)},SwitchCase(i){r(i.consequent)}}),xt(t,{ExpressionStatement(i){let s=i.expression;if(!s||s.type!=="AssignmentExpression"||s.operator!=="=")return;let a=s.left;if(a?.type!=="MemberExpression"||a.computed||a.property?.type!=="Identifier"||a.object?.type!=="Identifier")return;let o=a.object.name,l=o.startsWith("$M_")?o.slice(3):o;if(a.property.name==="__pineReceiverType__"){s.right?.type==="Literal"&&typeof s.right.value=="string"&&e.setMethodReceiverType(l,s.right.value);return}if(a.property.name!=="__pineParamTypes__"||s.right?.type!=="ObjectExpression")return;let c={},u={};for(let h of s.right.properties){if(h.type!=="Property")continue;let p;if(h.key?.type==="Identifier"?p=h.key.name:h.key?.type==="Literal"&&typeof h.key.value=="string"&&(p=h.key.value),!p||h.value?.type!=="Literal"||typeof h.value.value!="string")continue;u[p]=h.value.value;let d=h.value.value.split(/\\s+/).pop();e.isUdtTypeName(d)&&(c[p]=d)}Object.keys(c).length>0&&e.setFunctionParamUdtTypes(l,c),Object.keys(u).length>0&&e.setFunctionParamStaticTypes(l,u)}})}var AC=new Set(["table","line","label","box","linefill","polyline","array","matrix","map"]),TC={"request.footprint":"footprint","footprint.poc":"volume_row","footprint.vah":"volume_row","footprint.val":"volume_row","footprint.get_row_by_price":"volume_row"};function vc(t){if(t){if(t.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&!t.callee.computed&&t.callee.object?.type==="Identifier"&&t.callee.property?.type==="Identifier"){let e=t.callee.object.name,n=t.callee.property.name;if(AC.has(e)&&(n==="new"||n==="copy"||n==="from"||n.startsWith("new_")))return e;let r=TC[`${e}.${n}`];if(r)return r}if(t.type==="ConditionalExpression"){let e=vc(t.consequent),n=vc(t.alternate);if(e&&e===n)return e}}}function NC(t){let e=[];if(!t)return e;function n(r){if(!(!r||typeof r!="object")&&!(r.type==="FunctionDeclaration"||r.type==="FunctionExpression"||r.type==="ArrowFunctionExpression")){if(r.type==="ReturnStatement"&&r.argument){e.push(r.argument);return}for(let i of Object.keys(r)){if(i==="type")continue;let s=r[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&s.type&&n(s)}}}return n(t),e}function ls(t,e){if(t){if(t.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&!t.callee.computed&&t.callee.object?.type==="Identifier"&&t.callee.property?.type==="Identifier"&&(t.callee.property.name==="new"||t.callee.property.name==="copy")&&e.isUdtTypeName(t.callee.object.name))return t.callee.object.name;if(t.type==="CallExpression"&&t.callee?.type==="Identifier"){let n=e.getFunctionReturnType(t.callee.name);if(n)return n}if(t.type==="ConditionalExpression"){let n=ls(t.consequent,e),r=ls(t.alternate,e);if(n&&n===r)return n}}}function CC(t,e){xt(t,{VariableDeclaration(n){n.declarations.forEach(r=>{let i=r.init&&r.init.type==="MemberExpression"&&r.init.object&&(r.init.object.name==="context"||r.init.object.name===Oe||r.init.object.name==="context2"),s=r.init&&r.init.type==="MemberExpression"&&r.init.object?.object&&(r.init.object.object.name==="context"||r.init.object.object.name===Oe||r.init.object.object.name==="context2");(i||s)&&(r.id.name&&e.addContextBoundVar(r.id.name),r.id.properties&&r.id.properties.forEach(a=>{a.key.name&&e.addContextBoundVar(a.key.name)}))})}})}function IC(t,e,n=!1){t.params.forEach(r=>{r.type==="Identifier"&&n&&e.addContextBoundVar(r.name,n)})}function MC(t,e){let n;return Zu(t,{FunctionDeclaration(r){r.id&&r.id.name&&(e.addReservedName(r.id.name),e.addUserFunction(r.id.name),r.id.name.startsWith("$M_")||e.addRegularUserFunction(r.id.name))},ExpressionStatement(r){let i=r.expression;if(i&&i.type==="AssignmentExpression"&&i.operator==="="&&i.left?.type==="MemberExpression"&&i.left.property?.name==="__pineMethod__"&&i.left.object?.type==="Identifier"&&i.right?.value===!0){let s=i.left.object.name,a=s.startsWith("$M_")?s.slice(3):s;e.addMethodCandidate(a.replace(/\\$\\d+$/,""),s),e.addUserMethod(a),e.addUserFunction(a)}},ArrowFunctionExpression(r){let i=r.start===0;i&&r.params&&r.params.length>0&&(n=r.params[0].name,r.params[0].name=Oe),IC(r,e,i)},VariableDeclaration(r,i){let s=i.length>1?i[i.length-2]:null,a=s&&(s.type==="ForOfStatement"||s.type==="ForInStatement")&&s.left===r;r.declarations.forEach(o=>{if(o.id.type==="Identifier")e.addReservedName(o.id.name);else if(o.id.type==="ObjectPattern")o.id.properties.forEach(l=>{l.key&&l.key.type==="Identifier"&&e.addReservedName(l.key.name)});else if(o.id.type==="ArrayPattern"){if(o.id.elements?.forEach(p=>{p&&p.type==="Identifier"&&e.addReservedName(p.name)}),a)return;let l=[...i].reverse().find(p=>p!==r&&(p.type==="FunctionDeclaration"||p.type==="FunctionExpression"||p.type==="ArrowFunctionExpression"));if(l&&l.type!=="FunctionDeclaration"&&!(l.type==="ArrowFunctionExpression"&&l.start===0)){o.init={type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Oe},property:{type:"Identifier",name:"toTuple"},computed:!1},arguments:[o.init,{type:"Literal",value:o.id.elements.length}],_transformed:!0},property:{type:"Literal",value:0},computed:!0};return}let c=e.generateTempVar(),u={type:"VariableDeclaration",kind:r.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:c},init:o.init,_tupleArity:o.id.elements.length}]};o.id.elements?.forEach(p=>{p.type==="Identifier"&&e.addArrayPatternElement(p.name)});let h=o.id.elements.map((p,d)=>({type:"VariableDeclaration",kind:r.kind,declarations:[{type:"VariableDeclarator",id:p,init:{type:"MemberExpression",object:{type:"Identifier",name:c},property:{type:"Literal",value:d},computed:!0}}]}));Object.assign(r,{type:"BlockStatement",body:[u,...h]})}})},ForStatement(r){}}),n}var PC=Object.defineProperty,DC=(t,e,n)=>e in t?PC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OC=(t,e,n)=>DC(t,typeof e!="symbol"?e+"":e,n),RC=new Set(["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]),LC=new Set(["input.int","math.floor","math.ceil","array.size","matrix.rows","matrix.columns","str.length","timestamp","ta.barssince","ta.highestbars","ta.lowestbars"]);function FC(t){return t&&t.type==="Literal"&&typeof t.value=="number"&&Number.isInteger(t.value)&&!(typeof t.raw=="string"&&/[.eE]/.test(t.raw))}function BC(t){return t?t.type==="Identifier"?t.name:t.type==="MemberExpression"&&!t.computed&&t.object?.type==="Identifier"&&t.property?.type==="Identifier"?`${t.object.name}.${t.property.name}`:null:null}function VC(t){let e=new Set;return(function n(r){if(!(!r||typeof r!="object")){r.type==="AssignmentExpression"&&r.left?.type==="Identifier"?e.add(r.left.name):r.type==="UpdateExpression"&&r.argument?.type==="Identifier"&&e.add(r.argument.name);for(let i in r){if(i==="type"||i==="start"||i==="end"||i==="loc"||i==="raw")continue;let s=r[i];if(Array.isArray(s))for(let a of s)a&&typeof a=="object"&&n(a);else s&&typeof s=="object"&&n(s)}}})(t),e}function wc(t,e){return t!=="notint"&&e!=="notint"?"int":"notint"}var Sc=class{constructor(){OC(this,"stack",[new Map])}push(){this.stack.push(new Map)}pop(){this.stack.length>1&&this.stack.pop()}set(e,n){this.stack[this.stack.length-1].set(e,n)}get(e){for(let n=this.stack.length-1;n>=0;n--){let r=this.stack[n].get(e);if(r!==void 0)return r}}assign(e,n){for(let r=this.stack.length-1;r>=0;r--)if(this.stack[r].has(e)){this.stack[r].set(e,wc(this.stack[r].get(e),n));return}this.stack[this.stack.length-1].set(e,wc(n,n))}};function $C(t,e,n={intDivision:!0}){let r=new Sc,i=VC(t);function s(o){if(!o||typeof o!="object")return"notint";switch(o.type){case"Literal":return typeof o.value=="number"&&FC(o)?"constint":"notint";case"Identifier":return RC.has(o.name)?"int":r.get(o.name)??"notint";case"UnaryExpression":return o.operator==="-"||o.operator==="+"?s(o.argument):(s(o.argument),"notint");case"BinaryExpression":{let l=s(o.left),c=s(o.right);if(o.operator==="/"){if(n.intDivision&&l==="constint"&&c==="constint"){let u=A.createMathIntDivCall(o.left,o.right);return Object.assign(o,u),"constint"}return"notint"}return o.operator==="+"||o.operator==="-"||o.operator==="*"||o.operator==="%"?l==="constint"&&c==="constint"?"constint":l!=="notint"&&c!=="notint"?"int":"notint":"notint"}case"ConditionalExpression":{s(o.test);let l=s(o.consequent),c=s(o.alternate);return wc(l,c)}case"LogicalExpression":return s(o.left),s(o.right),"notint";case"CallExpression":{o.callee?.type==="MemberExpression"&&s(o.callee.object);let l=(o.arguments||[]).map(u=>s(u)),c=BC(o.callee);return c==="array.from"&&l.length>0&&l.every(u=>u!=="notint")&&(o.callee.property.name="__from_int"),c&&LC.has(c)?"int":"notint"}case"MemberExpression":return s(o.object),o.computed&&s(o.property),"notint";case"VariableDeclaration":{for(let l of o.declarations||[]){let c=l.init?s(l.init):"notint";l.id?.type==="Identifier"&&(c==="constint"&&(o.kind==="var"||i.has(l.id.name))&&(c="int"),r.set(l.id.name,c))}return"notint"}case"AssignmentExpression":{let l=s(o.right);return o.left?.type==="Identifier"?r.assign(o.left.name,l):s(o.left),l}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":{r.push();for(let l of o.params||[]){let c=l.type==="AssignmentPattern"?l.left:l;c?.type==="Identifier"&&r.set(c.name,"notint")}return s(o.body),r.pop(),"notint"}default:return a(o),"notint"}}function a(o){for(let l in o){if(l==="type"||l==="start"||l==="end"||l==="loc"||l==="raw")continue;let c=o[l];if(Array.isArray(c))for(let u of c)u&&typeof u.type=="string"&&s(u);else c&&typeof c.type=="string"&&s(c)}}s(t)}var zC=new Set(["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"]),jC=new Set(["&&","||","??"]);function pd(t){return t!==null&&typeof t=="object"&&typeof t.type=="string"}function qC(t){return t.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&t.callee.object?.type==="Identifier"&&t.callee.object.name==="request"}function vn(t,e,n){if(pd(t)){if(e&&(t._lazyOperand=!0),zC.has(t.type)){Array.isArray(t.params)&&t.params.forEach(r=>vn(r,e,n)),vn(t.body,!1,n);return}if(qC(t)){t._lazyOperand=!1,t.arguments.forEach(r=>vn(r,!1,n));return}if(t.type==="ConditionalExpression"){vn(t.test,e,n),vn(t.consequent,!0,n),vn(t.alternate,!0,n);return}if(t.type==="LogicalExpression"&&jC.has(t.operator)){if(n.lazyLogical){vn(t.left,e,n),vn(t.right,!0,n);return}e&&t.operator!=="??"&&(t._strictLogical=!0)}for(let r of Object.keys(t)){if(r==="parent"||r.startsWith("_"))continue;let i=t[r];Array.isArray(i)?i.forEach(s=>vn(s,e,n)):pd(i)&&vn(i,e,n)}}}function UC(t,e){vn(t,!1,e)}var bl={open:"float",high:"float",low:"float",close:"float",volume:"float",hl2:"float",hlc3:"float",ohlc4:"float",hlcc4:"float",bar_index:"int",last_bar_index:"int",time:"int",time_close:"int"};function WC(t,e){return!t||!e?!1:t===e||t==="int"&&e==="float"}var Ar=()=>({type:"Identifier",name:"undefined"});function Ur(t,e){let n={type:"Identifier",name:`\'${e}\'`};if(!t.isInsideFunctionScope())return n;let[r]=t.getVariable("$$");return r?{type:"BinaryExpression",operator:"+",left:A.createMemberExpression(A.createLocalContextIdentifier(),A.createIdentifier("id")),right:n}:n}function rt(t,e){let[n,r]=e.getVariable(t);if((n.match(/^fn\\d+_/)||e.isVariableInFunctionScope(t))&&t!=="$$"){let[i]=e.getVariable("$$");if(i)return A.createLocalContextVariableReference(r,n)}return A.createContextVariableReference(r,n)}function Qu(t,e){let n=rt(t,e);return A.createGetCall(n,0)}var HC=["BinaryExpression","UnaryExpression","LogicalExpression","ConditionalExpression"];function or(t,e){if(t.computed&&t.property.type==="Identifier"){if(e.isLoopVariable(t.property.name)){if(t.object.type==="Identifier"&&!e.isLoopVariable(t.object.name)){if(e.isLocalSeriesVar(t.object.name)){let n=A.createIdentifier(t.object.name);n._skipTransformation=!0;let r=A.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0;return}if(!e.isContextBound(t.object.name)){let n=rt(t.object.name,e),r=A.createGetCall(n,t.property);Object.assign(t,r),t._indexTransformed=!0}}return}if(!e.isContextBound(t.property.name))if(e.isLocalSeriesVar(t.property.name)){let n=A.createIdentifier(t.property.name);n._skipTransformation=!0,t.property=A.createGetCall(n,0)}else t.property=rt(t.property.name,e),t.property=A.createGetCall(t.property,0)}if(t.computed&&t.object.type==="Identifier"){if(e.isLoopVariable(t.object.name))return;if(e.isLocalSeriesVar(t.object.name)){let n=A.createIdentifier(t.object.name);n._skipTransformation=!0;let r=HC.includes(t.property.type)?th(t.property,e):t.property,i=A.createGetCall(n,r);Object.assign(t,i),t._indexTransformed=!0;return}if(e.isContextBound(t.object.name)||(t.object=rt(t.object.name,e)),t.property.type==="MemberExpression"){let n=t.property;n._indexTransformed||(or(n,e),n._indexTransformed=!0)}}t.computed&&t.property.type!=="Identifier"&&t.property.type!=="MemberExpression"&&!t._indexTransformed&&(t.property.type==="BinaryExpression"||t.property.type==="UnaryExpression"||t.property.type==="LogicalExpression"||t.property.type==="ConditionalExpression")&&(t.property=Ft(t.property,e))}function zm(t,e,n){return t.type==="Identifier"&&!e.isContextBound(t.name)&&!e.isLoopVariable(t.name)?A.createGetCall(Gr(t,e),0):t.type==="BinaryExpression"||t.type==="UnaryExpression"||t.type==="LogicalExpression"||t.type==="ConditionalExpression"?Ft(t,e,n):t}function jm(t,e,n,r,i){let s=t;for(;s.object&&s.object.type==="MemberExpression";)s=s.object;let a=i.isLocalSeriesVar(e),[o,l]=i.getVariable(e);if(!a&&l!=="var"&&l!=="varip")return s.object=A.createGetCall(n,r),t;s.object=A.createGetCall(n,0);let c=i.generateParamId(),u={type:"CallExpression",callee:A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("param")),arguments:[t,Ar(),Ur(i,c)],_transformed:!0,_isParamCall:!0},h=A.createVariableDeclaration(c,u),p=a||/^(glb|fn)\\d+_/.test(o),d=u;return(p?i.addScopeRootHoistedStatement(h):i.addEagerHoistedStatement(h))&&(d=A.createIdentifier(c),d._skipTransformation=!0,d._arrayAccessed=!0),A.createGetCall(d,r)}function Bt(t,e){let n=A.createGetCall(A.createIdentifier(t.name),0);t.start!==void 0&&(n.start=t.start),t.end!==void 0&&(n.end=t.end),n._indexTransformed=!0,Object.assign(t,n)}function tt(t,e){if(!t._skipTransformation&&t.name!==Oe){if(It.includes(t.name)&&e.isContextBound(t.name)){let p=t.parent&&t.parent.type==="CallExpression"&&t.parent.callee===t,d=t.parent&&t.parent.type==="MemberExpression"&&t.parent.object===t&&!t.parent.computed;if(!p&&!d){let f={type:"MemberExpression",object:{type:"Identifier",name:t.name},property:{type:"Identifier",name:"__value"},computed:!1},m=A.createGetCall(f,0);Object.assign(t,m),delete t.name;return}}if(t.name==="Math"||t.name==="NaN"||t.name==="undefined"||t.name==="Infinity"||t.name==="null"||t.name.startsWith("\'")&&t.name.endsWith("\'")||t.name.startsWith(\'"\')&&t.name.endsWith(\'"\')||t.name.startsWith("`")&&t.name.endsWith("`")||e.isLoopVariable(t.name))return;let n=!1;if(t.parent&&t.parent.type==="CallExpression"&&t.parent.arguments.includes(t)){let p=t.parent.callee;if(p.type==="MemberExpression"&&p.object&&p.object.name===Oe&&["get","set","init","param","call"].includes(p.property.name)){let d=t.parent.arguments.indexOf(t);p.property.name==="call"?d>=2&&(n=!0):d===0&&(n=!0)}else{let d=p.type==="MemberExpression"&&p.object&&p.object.type==="Identifier"&&sr.includes(p.object.name);p.type==="MemberExpression"&&!d?n=!1:n=!0}}let r=t.parent&&t.parent.type==="MemberExpression"&&t.parent.object===t&&e.isContextBound(t.name),i=t.parent&&t.parent.type==="CallExpression"&&t.parent.callee&&t.parent.callee.type==="MemberExpression"&&t.parent.callee.property.name==="param";t.parent&&t.parent.type==="AssignmentExpression"&&t.parent.left;let s=t.parent&&t.parent.type==="CallExpression"&&t.parent.callee===t,a=t.parent&&t.parent.type==="MemberExpression"&&t.parent.computed&&t.parent.object===t,o=t.parent&&t.parent.type==="MemberExpression"&&t.parent.computed&&t.parent.property===t&&t.parent.parent&&t.parent.parent.type==="CallExpression"&&t.parent.parent.callee&&t.parent.parent.callee.type==="MemberExpression"&&e.isContextBound(t.parent.parent.callee.object.name);if(r||i||n||o||s){if(s||t.parent&&t.parent.type==="CallExpression"&&t.parent.callee&&t.parent.callee.type==="MemberExpression"&&t.parent.callee.object&&t.parent.callee.object.name===Oe&&t.parent.callee.property.name==="call"&&t.parent.arguments[0]===t||e.isLocalSeriesVar(t.name)||e.isContextBound(t.name)&&!e.isRootParam(t.name))return;let p=rt(t.name,e);Object.assign(t,p);return}let l=e.isContextBound(t.name)&&!e.isRootParam(t.name);if(l){let p=t.parent&&t.parent.type==="CallExpression"&&t.parent.arguments.includes(t),d=t.parent&&t.parent.type==="SwitchStatement"&&t.parent.discriminant===t,f=t.parent&&t.parent.type==="SwitchCase"&&t.parent.test===t;if(!p&&!d&&!f)return}if(e.isLocalSeriesVar(t.name)){if(!a){let p=A.createIdentifier(t.name),d=A.createGetCall(p,0);Object.assign(t,d)}return}let[c,u]=e.getVariable(t.name),h;if(l)h=A.createIdentifier(t.name);else{if(c===t.name&&!e.isContextBound(t.name))return;h=rt(t.name,e)}if(a)Object.assign(t,h);else{let p=A.createGetCall(h,0);Object.assign(t,p)}}}var eh=["CallExpression","BinaryExpression","LogicalExpression","ConditionalExpression","UnaryExpression"];function So(t,e){return t?.type==="MemberExpression"&&!t.computed&&t.object?.type==="Identifier"&&sr.includes(t.object.name)&&e.isContextBound(t.object.name)}function qm(t,e){return t.type==="CallExpression"?(t._transformed||Ye(t,e),t):Ft(t,e)}function th(t,e){if(t.type==="Literal"||t.type==="CallExpression"&&t.callee?.object?.name===Oe)return t;if(t.type==="MemberExpression"&&t.computed){or(t,e);let n=r=>{r.type==="MemberExpression"&&(r.computed&&n(r.property),Le(r,"",e))};return n(t),t}return t.type==="CallExpression"?(t._transformed||Ye(t,e),t):Ft(t,e)}function Ec(t,e){if(t.type!=="Identifier")return th(t,e);if(e.isLoopVariable(t.name))return t;if(e.isLocalSeriesVar(t.name)){let n=A.createIdentifier(t.name);return n._skipTransformation=!0,A.createGetCall(n,0)}return A.createGetCall(Gr(t,e),0)}function GC(t,e,n){let r=t.object.name,i={type:"CallExpression",callee:A.createMemberExpression(A.createIdentifier(r),A.createIdentifier(t.property.name)),arguments:r==="ta"?[n.getNextTACallId()]:[],_transformed:!0},s=n.generateParamId(),a={type:"CallExpression",callee:A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("param")),arguments:[i,Ar(),{type:"Identifier",name:`\'${s}\'`}],_transformed:!0,_isParamCall:!0};n.addOuterHoistedStatement(A.createVariableDeclaration(s,a));let o=A.createIdentifier(s);o._skipTransformation=!0,o._arrayAccessed=!0;let l=A.createGetCall(o,e);return l._transformed=!0,l._historyTransformed=!0,l}function Le(t,e,n){if(t.object&&t.object.type==="Identifier"&&t.object.name==="Math")return;if(t.computed&&So(t.object,n)){let l=GC(t.object,Ec(t.property,n),n);Object.assign(t,l),delete t.object,delete t.property,delete t.computed;return}if(t.computed&&t.object&&eh.includes(t.object.type)&&!t._historyTransformed){n.enterHistoryRecord();try{t.object=qm(t.object,n)}finally{n.exitHistoryRecord()}t.property=Ec(t.property,n);let l=n.generateParamId(),c={type:"CallExpression",callee:A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("param")),arguments:[t.object,Ar(),Ur(n,l)],_transformed:!0,_isParamCall:!0},u=c;n.addEagerHoistedStatement(A.createVariableDeclaration(l,c))&&(u=A.createIdentifier(l),u._skipTransformation=!0,u._arrayAccessed=!0);let h=A.createGetCall(u,t.property);h._transformed=!0,h._historyTransformed=!0,Object.assign(t,h),delete t.object,delete t.property,delete t.computed;return}if(t.object&&t.object.type==="Identifier"&&sr.includes(t.object.name)&&n.isContextBound(t.object.name)&&!t.computed){let l=t.parent&&t.parent.type==="CallExpression"&&t.parent.callee===t,c=t.parent&&(t.parent.type==="VariableDeclarator"&&(t.parent.id.type==="ArrayPattern"||t.parent.id.type==="ObjectPattern")||t.parent.type==="AssignmentExpression"&&(t.parent.left.type==="ArrayPattern"||t.parent.left.type==="ObjectPattern")||t.parent.type==="Property");if(!l&&!c){let u={type:"CallExpression",callee:{type:"MemberExpression",object:t.object,property:t.property,computed:!1},arguments:[],_transformed:!1};t.start!==void 0&&(u.start=t.start),t.end!==void 0&&(u.end=t.end),Object.assign(t,u);return}}if(!t.computed&&t.object&&t.object.type==="Identifier"&&n.isLocalSeriesVar(t.object.name)){let l=A.createIdentifier(t.object.name);l._skipTransformation=!0,t.object=A.createGetCall(l,0);return}let r=n.getCurrentScopeType()=="if",i=n.getCurrentScopeType()=="els",s=n.getCurrentScopeType()=="for";if(!r&&!i&&!s&&t.object&&t.object.type==="Identifier"&&n.isContextBound(t.object.name)&&!n.isRootParam(t.object.name)&&!t.computed)return;t._indexTransformed||(or(t,n),t._indexTransformed=!0);let a=t.object&&t.object.type==="MemberExpression"&&t.object.object&&t.object.object.type==="MemberExpression"&&t.object.object.object&&(t.object.object.object.name===Oe||t.object.object.object.name==="$$"),o=t.object&&t.object.type==="Identifier"&&n.isContextBound(t.object.name);if(t.computed&&(a||o)){if(t.parent&&t.parent.type==="AssignmentExpression"&&t.parent.left===t)return;t.object.type==="Identifier"&&It.includes(t.object.name)&&n.isContextBound(t.object.name)&&(t.object={type:"MemberExpression",object:{type:"Identifier",name:t.object.name},property:{type:"Identifier",name:"__value"},computed:!1});let l=A.createGetCall(t.object,t.property);t.start&&(l.start=t.start),t.end&&(l.end=t.end),Object.assign(t,l),delete t.object,delete t.property,delete t.computed;return}if(t.computed&&t.object&&t.object.type==="MemberExpression"){let l=t.object;for(;l.object&&l.object.type==="MemberExpression";)l=l.object;if(l.object&&l.object.type==="Identifier"&&n.isUdtInstance(l.object.name)){let c=l.object.name,u=n.isLocalSeriesVar(c)?(()=>{let p=A.createIdentifier(c);return p._skipTransformation=!0,p})():rt(c,n),h=t._indexTransformed?t.property:zm(t.property,n);Object.assign(t,jm(t.object,c,u,h,n)),delete t.computed;return}}}function Gr(t,e){if(t.type==="Identifier"){if(It.includes(t.name)&&e.isContextBound(t.name)){let a=t.name;return Object.assign(t,{type:"MemberExpression",object:{type:"Identifier",name:a},property:{type:"Identifier",name:"__value"},computed:!1}),delete t.name,t}if(e.isLoopVariable(t.name))return t;if(e.isRootParam(t.name)){let[a,o]=e.getVariable(t.name);return A.createContextVariableReference(o,a)}if(e.isContextBound(t.name))return t;let[n,r]=e.getVariable(t.name),i=n!==t.name,s=e.isFunctionParam(t.name)&&!e.isVariableInFunctionScope(t.name);return e.isLocalSeriesVar(t.name)&&(!i||s)?t:i?rt(t.name,e):n===t.name&&!e.isContextBound(t.name)?t:rt(t.name,e)}return t}function Ft(t,e,n=""){switch(t.type){case"BinaryExpression":return kc(t,e,n);case"LogicalExpression":return Ac(t,e,n);case"MemberExpression":{let r=!t.computed&&t.object.type==="Identifier"&&It.includes(t.object.name)&&e.isContextBound(t.object.name);if(t.computed&&t.object.type==="Identifier"&&It.includes(t.object.name)&&e.isContextBound(t.object.name)){let a={type:"MemberExpression",object:{type:"Identifier",name:t.object.name},property:{type:"Identifier",name:"__value"},computed:!1};return A.createGetCall(a,Ec(t.property,e))}if(t.computed&&So(t.object,e))return Le(t,"",e),t;!t.computed&&t.object.type==="CallExpression"&&!t.object._transformed?Ye(t.object,e):!t.computed&&t.object.type==="MemberExpression"&&!t.object.computed&&(t.object=Ft(t.object,e,n),t.object.parent=t,Le(t.object,"",e));let i=t.object.type==="Identifier"&&!r?Gr(t.object,e):t.object,s=i;if(!t.computed&&t.object.type==="Identifier"&&!r){let[a]=e.getVariable(t.object.name);a!==t.object.name&&!e.isLoopVariable(t.object.name)&&(s=A.createGetCall(i,0))}return{type:"MemberExpression",object:s,property:t.property,computed:t.computed}}case"Identifier":{if(e.isLoopVariable(t.name)||t.parent&&t.parent.type==="MemberExpression"&&t.parent.property===t)return t;let r=Gr(t,e);return r.type==="Identifier"&&(r.name==="NaN"||r.name==="undefined"||r.name==="Infinity"||r.name==="null"||r.name==="Math")?r:A.createGetCall(r,0)}case"UnaryExpression":return Tc(t,e,n);case"ConditionalExpression":{let r=Ft(t.test,e,n),i=Ft(t.consequent,e,n),s=Ft(t.alternate,e,n);return{type:"ConditionalExpression",test:r,consequent:i,alternate:s,start:t.start,end:t.end}}}return t}function kc(t,e,n){let r=Ft(t.left,e,n),i=Ft(t.right,e,n),s={type:"BinaryExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return ct(s,e,{CallExpression(a,o){a._transformed||Ye(a,o)},MemberExpression(a){Le(a,"",e)}}),s}function Ac(t,e,n){let r=Ft(t.left,e,n),i=Ft(t.right,e,n),s={type:"LogicalExpression",operator:t.operator,left:r,right:i,start:t.start,end:t.end};return ct(s,e,{CallExpression(a,o){a._transformed||Ye(a,o)}}),s}function KC(t,e,n){Um(t,e);let r=A.createMemberExpression(A.createIdentifier(n),A.createIdentifier("param")),i=e.generateParamId(),s={type:"CallExpression",callee:r,arguments:[t,Ar(),Ur(e,i)],_transformed:!0,_isParamCall:!0};if(!e.shouldSuppressHoisting()){let a=i;e.addLocalSeriesVar(a);let o=A.createVariableDeclaration(a,s);return e.addHoistedStatement(o),A.createIdentifier(a)}return s}function Um(t,e){ct(t,{parent:t,inNamespaceCall:!1},{Identifier(n,r,i){if(n.name=="NaN")return;if(It.includes(n.name)&&e.isContextBound(n.name)){if(r.parent&&r.parent.type==="MemberExpression"&&r.parent.object===n&&!r.parent.computed)return;let a={type:"MemberExpression",object:{type:"Identifier",name:n.name},property:{type:"Identifier",name:"__value"},computed:!1},o=A.createGetCall(a,0);Object.assign(n,o),delete n.name;return}n.parent=r.parent,tt(n,e);let s=n.parent&&n.parent.type==="BinaryExpression";(n.parent&&n.parent.type==="ConditionalExpression"||s)&&(n.type==="MemberExpression"?or(n,e):n.type==="Identifier"&&(n.parent&&n.parent.type==="CallExpression"&&n.parent.callee&&n.parent.callee.object&&n.parent.callee.object.name===Oe&&n.parent.callee.property.name==="get"||Bt(n)))},MemberExpression(n,r,i){Le(n,"",e),n.object&&i(n.object,{parent:n,inNamespaceCall:r.inNamespaceCall})},ConditionalExpression(n,r,i){let s={...r,parent:n};n.test&&i(n.test,s),n.consequent&&i(n.consequent,s),n.alternate&&i(n.alternate,s)},BinaryExpression(n,r,i){let s={...r,parent:n};i(n.left,s),i(n.right,s)},LogicalExpression(n,r,i){let s={...r,parent:n};i(n.left,s),i(n.right,s)},UnaryExpression(n,r,i){let s={...r,parent:n};i(n.argument,s)},CallExpression(n,r,i){let s=n.callee&&n.callee.type==="MemberExpression"&&n.callee.object&&n.callee.object.type==="Identifier"&&e.isContextBound(n.callee.object.name);Ye(n,e),!(n.type!=="CallExpression"||nh(n))&&n.arguments.forEach(a=>i(a,{parent:n,inNamespaceCall:s||r.inNamespaceCall}))}})}function Tc(t,e,n){let r=Ft(t.argument,e,n),i={type:"UnaryExpression",operator:t.operator,prefix:t.prefix,argument:r,start:t.start,end:t.end};return ct(i,e,{CallExpression(s,a){s._transformed||Ye(s,a)},MemberExpression(s){Le(s,"",e)}}),i}function dd(t,e){let n=t;for(;n&&n.type==="MemberExpression"&&n.object;){if(n.object.type==="Identifier"){let r=n.object,[i]=e.getVariable(r.name);i!==r.name&&!e.isContextBound(r.name)&&!e.isRootParam(r.name)&&!e.isLoopVariable(r.name)&&!e.isLocalSeriesVar(r.name)&&!It.includes(r.name)&&!sr.includes(r.name)&&(n.object=Qu(r.name,e));break}n=n.object}}var xl=t=>t?.type==="Identifier"&&t.name==="undefined";function vi(t,e,n){switch(t?.type){case"BinaryExpression":t=kc(t,n,e);break;case"LogicalExpression":t=Ac(t,n,e);break;case"ConditionalExpression":return KC(t,n,e);case"UnaryExpression":t=Tc(t,n,e);break;case"ArrayExpression":t.elements=t.elements.map(c=>{if(c.type==="Identifier"){if(n.isContextBound(c.name)&&!n.isRootParam(c.name))return It.includes(c.name)&&c.name!=="na"?A.createMemberExpression(A.createIdentifier(c.name),A.createIdentifier("__value")):c;if(n.isLocalSeriesVar(c.name)){let u=A.createIdentifier(c.name);return A.createGetCall(u,0)}return Qu(c.name,n)}return c.type==="CallExpression"?(Ye(c,n),c):c.type==="BinaryExpression"?kc(c,n,e):c.type==="LogicalExpression"?Ac(c,n,e):c.type==="ConditionalExpression"?(Um(c,n),c):c.type==="UnaryExpression"?Tc(c,n,e):(c.type==="MemberExpression"&&(Le(c,e,n),c.computed||dd(c,n)),c)});break}t?.type==="MemberExpression"&&t.computed&&So(t.object,n)&&Le(t,"",n);let r=t.type==="MemberExpression"&&t.computed&&t.property,i=t.type==="MemberExpression"&&!t.computed;if(r){if(t.object&&t.object.type==="MemberExpression"){let g=t.object;for(;g.object&&g.object.type==="MemberExpression";)g=g.object;if(g.object?.type==="Identifier"&&n.isUdtInstance(g.object.name)){let w=g.object.name,k=n.isLocalSeriesVar(w)?(()=>{let S=A.createIdentifier(w);return S._skipTransformation=!0,S})():rt(w,n);return t._udtIndexTransformed||(t.property=zm(t.property,n,e),t._udtIndexTransformed=!0),jm(t.object,w,k,t.property,n)}}let c=eh.includes(t.object.type);if(c){n.enterHistoryRecord();try{t.object=qm(t.object,n)}finally{n.exitHistoryRecord()}}else t.object.type==="MemberExpression"&&(Le(t.object,"",n),dd(t.object,n),c=t.object.type==="CallExpression");let u=t.object.type==="Identifier"&&n.isContextBound(t.object.name)&&!n.isRootParam(t.object.name)?It.includes(t.object.name)?A.createMemberExpression(A.createIdentifier(t.object.name),A.createIdentifier("__value")):t.object:Gr(t.object,n),h;if(t.property.type==="Identifier"&&!n.isContextBound(t.property.name)&&!n.isLoopVariable(t.property.name))h=A.createGetCall(Gr(t.property,n),0);else if(t.property.type==="Identifier"&&n.isContextBound(t.property.name)&&!n.isLoopVariable(t.property.name)){let g=t.property.name,w=It.includes(g)?A.createMemberExpression(A.createIdentifier(g),A.createIdentifier("__value")):A.createIdentifier(g);h=A.createGetCall(w,0)}else if(t.property.type==="BinaryExpression"||t.property.type==="UnaryExpression"||t.property.type==="LogicalExpression"||t.property.type==="ConditionalExpression")h=Ft(t.property,n,e);else if(t.property.type==="MemberExpression"){or(t.property,n);let g=w=>{w.type==="MemberExpression"&&(w.computed&&g(w.property),Le(w,"",n))};g(t.property),h=t.property}else t.property.type==="CallExpression"&&(t.property._transformed||Ye(t.property,n)),h=t.property;let p=u,d=h;if(c){let g=n.generateParamId(),w={type:"CallExpression",callee:A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("param")),arguments:[t.object,Ar(),Ur(n,g)],_transformed:!0,_isParamCall:!0},k=w;n.addEagerHoistedStatement(A.createVariableDeclaration(g,w))&&(k=A.createIdentifier(g),k._skipTransformation=!0,k._arrayAccessed=!0),p=A.createGetCall(k,h),p._transformed=!0,p._historyTransformed=!0,d=Ar()}let f=A.createMemberExpression(A.createIdentifier(e),A.createIdentifier("param")),m=n.generateParamId(),y={type:"CallExpression",callee:f,arguments:[p,d,Ur(n,m)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let g=m;n.addLocalSeriesVar(g);let w=A.createVariableDeclaration(g,y);return n.addHoistedStatement(w),A.createIdentifier(g)}return y}if(i){if(t.object.type==="Identifier"&&sr.includes(t.object.name)&&n.isContextBound(t.object.name)&&!t.computed){let c=t.object.name,u={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:c},property:{type:"Identifier",name:t.property.name},computed:!1},arguments:[],_transformed:!0};c==="ta"&&u.arguments.push(n.getNextTACallId());let h=n.generateTempVar();n.addLocalSeriesVar(h);let p=A.createVariableDeclaration(h,u);return n.addOuterHoistedStatement(p),Object.assign(t,A.createIdentifier(h)),t}if(t.object.type==="Identifier"){let c=t.object.name,[u,h]=n.getVariable(c);if(u!==c&&!n.isLoopVariable(c)){let p=rt(c,n),d=A.createGetCall(p,0);t.object=d}else if(n.isLocalSeriesVar(c)){let p=A.createIdentifier(c);p._skipTransformation=!0,t.object=A.createGetCall(p,0)}}else t.object.type==="MemberExpression"?vi(t.object,e,n):t.object.type==="CallExpression"&&(t.object._transformed||Ye(t.object,n))}if(t.type==="ObjectExpression"&&(t.properties=t.properties.map(c=>{if(c.value.name){if(It.includes(c.value.name)&&c.value.name!=="na"&&n.isContextBound(c.value.name)){let u=A.createMemberExpression(A.createIdentifier(c.value.name),A.createIdentifier("__value"));return{...c,shorthand:!1,value:A.createGetCall(u,0)}}return n.isContextBound(c.value.name)||n.isLocalSeriesVar(c.value.name)||n.isLoopVariable(c.value.name)?{type:"Property",key:{type:"Identifier",name:c.key.name},value:A.createIdentifier(c.value.name),kind:"init",method:!1,shorthand:!1,computed:!1}:{type:"Property",key:{type:"Identifier",name:c.key.name},value:rt(c.value.name,n),kind:"init",method:!1,shorthand:!1,computed:!1}}else c.value.type!=="Literal"&&(c.value=vi(c.value,e,n));return c})),t.type==="Identifier"){if(It.includes(t.name)&&n.isContextBound(t.name)){let c=t.name;Object.assign(t,{type:"MemberExpression",object:{type:"Identifier",name:c},property:{type:"Identifier",name:"__value"},computed:!1}),delete t.name}else if(n.isContextBound(t.name)&&!n.isRootParam(t.name)){let c=A.createMemberExpression(A.createIdentifier(e),A.createIdentifier("param")),u=n.generateParamId(),h={type:"CallExpression",callee:c,arguments:[t,Ar(),Ur(n,u)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let p=u;n.addLocalSeriesVar(p);let d=A.createVariableDeclaration(p,h);return n.addHoistedStatement(d),A.createIdentifier(p)}return h}}t?.type==="CallExpression"&&Ye(t,n,e);let s=A.createMemberExpression(A.createIdentifier(e),A.createIdentifier("param")),a=t.type==="Identifier"?Gr(t,n):t,o=n.generateParamId(),l={type:"CallExpression",callee:s,arguments:[a,Ar(),Ur(n,o)],_transformed:!0,_isParamCall:!0};if(!n.shouldSuppressHoisting()){let c=o;n.addLocalSeriesVar(c);let u=A.createVariableDeclaration(c,l);return n.addHoistedStatement(u),A.createIdentifier(c)}return l}function ns(t){if(!t)return!1;if(Wm(t))return!0;if(t.type==="MemberExpression")return ns(t.object);if(t.type==="ChainExpression")return ns(t.expression);if(t.type==="CallExpression"){let e=t.callee;if(e?.type==="MemberExpression")return ns(e.object);if(e?.type==="ChainExpression")return ns(e.expression)}return!1}function YC(t,e){if(t?._orderflowType)return t._orderflowType;if(t?.type!=="CallExpression"||t.callee?.type!=="MemberExpression"||t.callee.computed||!em.has(t.callee.property?.name))return;let n=t.callee.object;return n?.name&&!e.getVariableUdtType(n.name)&&e.getVarStaticType(n.name)==="footprint"?"volume_row":void 0}function Wm(t){return t?.type==="CallExpression"&&t.callee?.type==="MemberExpression"&&t.callee.object?.name==="$"&&t.callee.property?.name==="get"}function Nc(t,e,n){t&&(t.type==="Identifier"?(t.parent=e,tt(t,n)):t.type==="MemberExpression"?(Nc(t.object,t,n),t.parent=e,Le(t,"",n),t.type==="CallExpression"&&!t._transformed&&Ye(t,n)):t.type==="CallExpression"&&(t.callee&&t.callee.type==="MemberExpression"&&Nc(t.callee.object,t.callee,n),t._transformed||Ye(t,n)))}function nh(t){return!!t&&t.type==="CallExpression"&&t._transformed===!0&&t._lazyOperand===!0}function Ye(t,e,n){if(!t._transformed){if(t._lazyOperand===!0&&!e.shouldSuppressHoisting()){e.setSuppressHoisting(!0);try{fd(t,e,n)}finally{e.setSuppressHoisting(!1)}return}fd(t,e)}}function fd(t,e,n){t.callee&&t.callee.name,t.callee&&t.callee.type==="Identifier"&&(sr.includes(t.callee.name)||It.includes(t.callee.name))&&e.isContextBound(t.callee.name)&&(t.callee=A.createMemberExpression(t.callee,A.createIdentifier("any")));let r=t.callee?.type==="MemberExpression"&&!t.callee.computed&&t.callee.object?.type==="Identifier"&&t.callee.object.name in bl&&t.callee.property?.type==="Identifier"&&e.isUserMethod(t.callee.property.name),i=t.callee&&t.callee.type==="MemberExpression"&&t.callee.object&&t.callee.object.type==="Identifier"&&!r&&(e.isContextBound(t.callee.object.name)||t.callee.object.name==="math"||t.callee.object.name==="ta"),s=!i&&t.callee?.type==="MemberExpression";if(i){if(t.callee.object.name===Oe&&["get","init","param"].includes(t.callee.property.name))return;let o=t.callee.object.name;o==="syminfo"&&!t.callee.computed&&["ticker","prefix"].includes(t.callee.property?.name)&&(t.callee.property=A.createIdentifier(`__${t.callee.property.name}`));let l=[];t.arguments.forEach(m=>{if(m._isParamCall||xl(m)){l.push(m);return}l.push(vi(m,o,e))}),t.arguments=l;let c=t.callee.property.name,u=`${o}.${c}`;if(Jp.includes(o)||Jp.includes(u)){let m=e.getNextPlotCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:m,kind:"init",computed:!1,shorthand:!1}]})}if(o==="input"&&t._varId!==void 0&&t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__varId"},value:{type:"Literal",value:t._varId},kind:"init",computed:!1,shorthand:!1}]}),o==="alert"){let m=e.getNextAlertCallId();t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:m,kind:"init",computed:!1,shorthand:!1}]})}if(o==="ta"||u==="math.random"||u==="math.sum")if(e.isInsideFunctionScope()){let m=e.getNextTACallId(),[y]=e.getVariable("$$"),g;y?g=A.createMemberExpression(A.createLocalContextIdentifier(),A.createIdentifier("id")):g=A.createLiteral("");let w={type:"BinaryExpression",operator:"+",left:g,right:m};t.arguments.push(w)}else t.arguments.push(e.getNextTACallId());let h=t.callee.property.name,p=`${o}.${h}`,d=lN.includes(p),f=t._insideAwait===!0;if(d&&!f){let m=Object.assign({},t),y=A.createAwaitExpression(m);Object.assign(t,y)}if(!e.shouldSuppressHoisting()){let m=e.generateTempVar();e.addLocalSeriesVar(m);let y=t._insideAwait===!0,g=Object.assign({},t);y&&(g=A.createAwaitExpression(g));let w=A.createVariableDeclaration(m,g);e.addHoistedStatement(w);let k=A.createIdentifier(m);Object.assign(t,k),t._wasHoisted=!0,t._wasInsideAwait=y;return}t._transformed=!0}else if(t.callee&&t.callee.type==="Identifier"){if(t.arguments=t.arguments.map(o=>o._isParamCall||xl(o)?o:vi(o,Oe,e)),t.callee.name==="Type"&&t._udtName&&e.isMethodReceiverTypeName(t._udtName)&&t.arguments.push({type:"Literal",value:t._udtName,raw:JSON.stringify(t._udtName)}),uN.includes(t.callee.name)&&e.isContextBound(t.callee.name)&&t.arguments.push({type:"ObjectExpression",properties:[{type:"Property",key:{type:"Identifier",name:"__callsiteId"},value:e.getNextBareCallsiteId(t.callee.name),kind:"init",computed:!1,shorthand:!1}]}),!e.isContextBound(t.callee.name)){let o=e.getNextUserCallId(),l=A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("call")),c=t.callee.name,u=t.callee;e.isUserMethod(c)&&!e.isRegularUserFunction(c)&&(u=A.createIdentifier(`$M_${c}`),u._skipTransformation=!0);let h=[u,o,...t.arguments];t.callee=l,t.arguments=h}t._transformed=!0}let a;if(!i&&t.callee&&t.callee.type==="MemberExpression"){let o=t.callee.property.name,l=e.isUserFunction(o),c=t.callee.object,u=e.isUserMethod(o),h;if(c.name)h=e.getVariableUdtType(c.name)??e.getVarStaticType(c.name);else if(c.type==="MemberExpression"&&!c.computed&&c.property?.type==="Identifier"&&c.object?.name){let T=e.getVariableUdtType(c.object.name);if(T){let N=e.getUdtTypeFields(T)?.[c.property.name];h=bc(N)}}let p=c.type==="Literal"?typeof c.value=="string"?"string":typeof c.value=="boolean"?"bool":void 0:c.type==="Identifier"&&c.name in bl&&e.isContextBound(c.name)?bl[c.name]:void 0,d=h??p,f=e.getMethodCandidates(o),m=T=>e.getMethodReceiverType(T.slice(3)),y=f.find(T=>WC(d,m(T))),g=y!==void 0,w=h??YC(c,e);w&&pN[w]?.has(o)&&(a=w);let k=!!c.name&&e.isUdtInstance(c.name),S=h===void 0&&!Ss.has(o),E=d===void 0&&!k&&(Ss.has(o)||f.length>1);if(l&&u&&(!e.isContextBound(o)||g)&&(g||k||S||E)){let T=t.callee.object;t.callee.property;let N=t.arguments.map(te=>te._isParamCall||xl(te)?te:vi(te,Oe,e));T.type==="CallExpression"&&Ye(T,e);let $=vi(T,Oe,e),z=A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("call")),H=e.getNextUserCallId();if(E){let te=(f.length?f:[`$M_${o}`]).map(I=>{let V=A.createIdentifier(I);V._skipTransformation=!0;let ee=m(I),oe=ee&&e.isUdtTypeName(ee)?{type:"Literal",value:ee,raw:JSON.stringify(ee)}:{type:"Literal",value:null,raw:"null"};return{type:"ArrayExpression",elements:[V,oe]}});t.callee=A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("callMethod")),t.arguments=[{type:"Literal",value:o,raw:JSON.stringify(o)},H,{type:"ArrayExpression",elements:te},$,...N],t._transformed=!0;return}let C=A.createIdentifier(y??f[0]??`$M_${o}`);C._skipTransformation=!0;let ae=[C,H,$,...N];t.callee=z,t.arguments=ae,t._transformed=!0;return}t.callee.object.type==="Identifier"?tt(t.callee.object,e):Nc(t.callee.object,t.callee,e)}if(t.arguments.forEach(o=>{ct(o,{parent:t},{Identifier(l,c,u){l.parent=c.parent,tt(l,e);let h=l.parent&&l.parent.type==="BinaryExpression",p=l.parent&&l.parent.type==="ConditionalExpression",d=s&&l.parent?.type==="Property"&&l.parent.value===l;(p||h||d)&&(l.type==="MemberExpression"?or(l,e):l.type==="Identifier"&&(l.parent&&l.parent.type==="CallExpression"&&l.parent.callee&&l.parent.callee.object&&l.parent.callee.object.name===Oe&&l.parent.callee.property.name==="get"||Bt(l)))},BinaryExpression(l,c,u){let h={...c,parent:l};u(l.left,h),u(l.right,h)},LogicalExpression(l,c,u){let h={...c,parent:l};u(l.left,h),u(l.right,h)},UnaryExpression(l,c,u){let h={...c,parent:l};u(l.argument,h)},ConditionalExpression(l,c,u){let h=s?{...c,parent:l}:c;u(l.test,h),u(l.consequent,h),u(l.alternate,h)},ObjectExpression(l,c,u){for(let h of l.properties)u(h.value,s?{...c,parent:h}:c)},CallExpression(l,c,u){l.callee&&l.callee.type==="MemberExpression"&&l.callee.object&&(l.callee.object.parent=l.callee,u(l.callee.object,{parent:l.callee})),l._transformed||Ye(l,e)},MemberExpression(l,c,u){Le(l,"",e),l.object&&u(l.object,{parent:l})}})}),a&&!t._transformed){let o=t.callee.property.name,l=A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("pine")),c=A.createMemberExpression(l,A.createIdentifier(a));t.arguments=[t.callee.object,...t.arguments],t.callee=A.createMemberExpression(c,A.createIdentifier(o)),a==="footprint"&&em.has(o)&&(t._orderflowType="volume_row"),t._transformed=!0;return}if(t.callee&&t.callee.type==="MemberExpression"){let o=t.callee.object,l=Wm(o),c=o?.type==="MemberExpression"&&ns(o),u=o?.type==="CallExpression"&&o.callee?.type==="MemberExpression"&&o.callee.object?.name===Oe&&["call","callMethod"].includes(o.callee.property?.name),h=o?.type==="MemberExpression"&&!o.computed&&o.property?.type==="Identifier"||u,p=!t.callee.computed&&t.callee.property?.name==="delete"&&h;if(!t.callee.computed&&/^(get|set)_\\w+$/.test(t.callee.property?.name??"")&&(l||c||h)&&(t.callee.object={type:"CallExpression",callee:A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("drawingOrNa")),arguments:[o],_transformed:!0}),l||c||p){let d=Object.assign({},t.callee,{optional:!0});t.callee={type:"ChainExpression",expression:d},t.optional=!0}}}function cs(t){let e={type:"VariableDeclaration",kind:"let",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:t},init:{type:"Literal",value:0}}]},n={type:"IfStatement",test:{type:"BinaryExpression",operator:">",_skipCompare:!0,left:{type:"UpdateExpression",operator:"++",prefix:!0,argument:{type:"Identifier",name:t}},right:{type:"Identifier",name:"__maxLoops"}},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"$"},property:{type:"Identifier",name:"loopError"},computed:!1},arguments:[{type:"Literal",value:`Loop exceeded maximum iterations (${t})`}]}},alternate:null};return{counterDecl:e,guardCheck:n}}function Eo(t,e){let n=null;if(t.left.type==="Identifier")n=rt(t.left.name,e);else if(t.left.type==="MemberExpression"&&t.left.computed){if(t.left.object.type==="Identifier"){let i=t.left.object.name,[s,a]=e.getVariable(i),o=s!==i,l=e.isContextBound(i);(o||l)&&!e.isLoopVariable(i)&&t.left.property.type==="Literal"&&t.left.property.value===0&&(n=rt(i,e))}}else if(t.left.type==="MemberExpression"&&!t.left.computed){let i=null,s=t.left;for(;s.type==="MemberExpression"&&!s.computed;){if(s.object.type==="Identifier"){i=s;break}s=s.object}if(i){let a=i.object.name,[o,l]=e.getVariable(a);if(o!==a&&!e.isLoopVariable(a)){let c=rt(a,e),u=A.createGetCall(c,0);i.object=u}else if(e.isLocalSeriesVar(a)){let c=A.createIdentifier(a);c._skipTransformation=!0,i.object=A.createGetCall(c,0)}}}let r=i=>{if(i){if(i.type==="CallExpression"&&(i.callee?.type==="ArrowFunctionExpression"||i.callee?.type==="FunctionExpression")){(i.callee.body?.type==="BlockStatement"?i.callee.body.body:[]).some(s=>/^(For|ForOf|ForIn|While|DoWhile)Statement$/.test(s.type))||(Hm(i,e),i._iifeTransformed=!0);return}i.type==="BinaryExpression"||i.type==="LogicalExpression"?(r(i.left),r(i.right)):i.type==="ConditionalExpression"?(r(i.test),r(i.consequent),r(i.alternate)):i.type==="UnaryExpression"&&r(i.argument)}};if(r(t.right),ct(t.right,{parent:t.right,inNamespaceCall:!1},{Identifier(i,s,a){let o=s.parent&&s.parent.type==="MemberExpression"&&!s.parent.computed&&s.parent.object===i;if(It.includes(i.name)&&e.isContextBound(i.name)&&!o){let y={type:"MemberExpression",object:{type:"Identifier",name:i.name},property:{type:"Identifier",name:"__value"},computed:!1},g=A.createGetCall(y,0);Object.assign(i,g),delete i.name;return}i.parent=s.parent,tt(i,e);let l=i.parent&&i.parent.type==="BinaryExpression",c=i.parent&&i.parent.type==="ConditionalExpression",u=e.isContextBound(i.name)&&!e.isRootParam(i.name),h=i.parent&&i.parent.type==="MemberExpression"&&i.parent.computed&&i.parent.object===i,p=i.parent&&i.parent._isParamCall,d=i.parent&&i.parent.type==="MemberExpression",f=i.name==="NaN",m=i.parent&&i.parent.type==="CallExpression"&&i.parent.callee&&i.parent.callee.object&&i.parent.callee.object.name===Oe&&i.parent.callee.property.name==="get";(u||c||l)&&(i.type==="MemberExpression"?or(i,e):i.type==="Identifier"&&!d&&!h&&!p&&!f&&!m&&Bt(i))},MemberExpression(i,s,a){Le(i,"",e),i.type==="CallExpression"?i.arguments.forEach(o=>a(o,{parent:i,inNamespaceCall:s.inNamespaceCall})):i.object&&a(i.object,{parent:i,inNamespaceCall:s.inNamespaceCall})},CallExpression(i,s,a){if(i._iifeTransformed)return;let o=i.callee&&i.callee.type==="MemberExpression"&&i.callee.object&&i.callee.object.type==="Identifier"&&e.isContextBound(i.callee.object.name);Ye(i,e),!(i.type!=="CallExpression"||nh(i))&&(i.callee.type==="MemberExpression"&&a(i.callee,{parent:i,inNamespaceCall:o||s.inNamespaceCall}),i.arguments.forEach(l=>a(l,{parent:i,inNamespaceCall:o||s.inNamespaceCall})))}}),n){let i=t.right;if(t.operator!=="="){let a=t.operator.replace("=",""),o=A.createGetCall(n,0);i={type:"BinaryExpression",operator:a,left:o,right:t.right,start:t.start,end:t.end}}let s=A.createSetCall(n,i);t.start&&(s.start=t.start),t.end&&(s.end=t.end),Object.assign(t,s)}}function Hm(t,e){ct(t,{parent:t},{Identifier(n,r){n.parent=r.parent,tt(n,e);let i=n.parent&&n.parent.type==="BinaryExpression",s=n.parent&&n.parent.type==="UnaryExpression",a=n.parent&&n.parent.type==="ConditionalExpression",o=n.parent&&n.parent.type==="CallExpression"&&n.parent.callee&&n.parent.callee.object&&n.parent.callee.object.name===Oe&&n.parent.callee.property.name==="get";n.type==="Identifier"&&(i||s||a)&&!o&&Bt(n)},CallExpression(n,r,i){n.callee.type==="Identifier"&&(n.callee.parent=n),n.arguments.forEach(s=>{s.type==="Identifier"&&(s.parent=n)}),(n.callee.type==="ArrowFunctionExpression"||n.callee.type==="FunctionExpression")&&i(n.callee,{parent:n}),Ye(n,e),!(n.type!=="CallExpression"||nh(n))&&(n.callee.type==="MemberExpression"&&i(n.callee,{parent:n}),n.arguments.forEach(s=>i(s,{parent:n})))},BinaryExpression(n,r,i){n.left.type==="Identifier"&&(n.left.parent=n),n.right.type==="Identifier"&&(n.right.parent=n),i(n.left,{parent:n}),i(n.right,{parent:n})},LogicalExpression(n,r,i){n.left.type==="Identifier"&&(n.left.parent=n),n.right.type==="Identifier"&&(n.right.parent=n),i(n.left,{parent:n}),i(n.right,{parent:n})},UnaryExpression(n,r,i){n.argument.type==="Identifier"&&(n.argument.parent=n),i(n.argument,{parent:n})},MemberExpression(n,r,i){n.object&&n.object.type==="Identifier"&&(n.object.parent=n),n.property&&n.property.type==="Identifier"&&(n.property.parent=n),Le(n,"",e),n.type==="CallExpression"?n.arguments.forEach(s=>i(s,{parent:n})):n.object&&i(n.object,{parent:n})},AwaitExpression(n,r,i){n.argument&&(n.argument._insideAwait=!0,i(n.argument,{parent:n}),n.argument.type==="Identifier"&&n.argument._wasInsideAwait&&Object.assign(n,n.argument))},ArrowFunctionExpression(n,r,i){if(n.body)if(n.body.type==="BlockStatement"){let s=[];n.body.body.forEach(a=>{e.enterHoistingScope(),i(a,{parent:n.body,insideIIFE:!0});let o=e.exitHoistingScope();s.push(...o),s.push(a)}),n.body.body=s}else i(n.body,{parent:n,insideIIFE:!0})},FunctionExpression(n,r,i){if(n.body&&n.body.type==="BlockStatement"){let s=[];n.body.body.forEach(a=>{e.enterHoistingScope(),i(a,{parent:n.body,insideIIFE:!0});let o=e.exitHoistingScope();s.push(...o),s.push(a)}),n.body.body=s}},BlockStatement(n,r,i){let s=[];n.body.forEach(a=>{e.enterHoistingScope(),i(a,{...r,parent:n});let o=e.exitHoistingScope();s.push(...o),s.push(a)}),n.body=s},SwitchStatement(n,r,i){n.discriminant&&(n.discriminant.parent=n,i(n.discriminant,{parent:n})),n.cases&&n.cases.forEach(s=>{s.parent=n,i(s,{parent:n,insideIIFE:r.insideIIFE})})},SwitchCase(n,r,i){if(n.test&&(n.test.parent=n,i(n.test,{parent:n,insideIIFE:r.insideIIFE})),n.consequent){let s=[];n.consequent.forEach(a=>{e.enterHoistingScope(),a.parent=n,i(a,{parent:n,insideIIFE:r.insideIIFE});let o=e.exitHoistingScope();s.push(...o),s.push(a)}),n.consequent=s}},AssignmentExpression(n,r,i){if(r.insideIIFE){if(n.left.type==="Identifier"){let[s]=e.getVariable(n.left.name);if(s===n.left.name&&!e.isContextBound(n.left.name)){i(n.right,{parent:n});return}}Eo(n,e)}}})}function Gm(t,e){t._skipTransformation||t.declarations.forEach(n=>{if(n.init?.type==="CallExpression"&&n.id?.type==="Identifier"){let d=n.init.callee;(d?.type==="MemberExpression"&&d.object?.type==="Identifier"&&d.object.name==="input"||d?.type==="Identifier"&&d.name==="input")&&(n.init._varId=n.id.name)}if(n.init&&n.init.type==="Identifier"&&It.includes(n.init.name)&&e.isContextBound(n.init.name)){let d=n.init.name;Object.assign(n.init,{type:"MemberExpression",object:{type:"Identifier",name:d},property:{type:"Identifier",name:"__value"},computed:!1}),delete n.init.name}let r=n.init&&n.init.type==="MemberExpression"&&n.init.object&&(n.init.object.name==="context"||n.init.object.name===Oe||n.init.object.name==="context2"),i=n.init&&n.init.type==="MemberExpression"&&n.init.object?.object&&(n.init.object.object.name==="context"||n.init.object.object.name===Oe||n.init.object.object.name==="context2"),s=n.init&&n.init.type==="ArrowFunctionExpression";if(r){n.id.name&&e.addContextBoundVar(n.id.name),n.id.properties&&n.id.properties.forEach(d=>{d.key.name&&e.addContextBoundVar(d.key.name)}),n.init.object.name=Oe;return}if(i){n.id.name&&e.addContextBoundVar(n.id.name),n.id.properties&&n.id.properties.forEach(d=>{d.key.name&&e.addContextBoundVar(d.key.name)}),n.init.object.object.name=Oe;return}e.addVariable(n.id.name,t.kind);let a=t.kind,o=e.hideCurrentScopeVariable(n.id.name),l=e.isArrayPatternElement(n.id.name)&&n.init&&n.init.type==="MemberExpression"&&n.init.computed;n.init&&!s&&!l&&(n.init.type==="CallExpression"&&n.init.callee.type==="MemberExpression"&&n.init.callee.object&&n.init.callee.object.type==="Identifier"&&e.isContextBound(n.init.callee.object.name)?Ye(n.init,e):Hm(n.init,e)),o();let c=rt(n.id.name,e),u=!l&&n.init&&n.init.type==="MemberExpression"&&n.init.computed&&n.init.property&&(n.init.property.type==="Literal"||n.init.property.type==="MemberExpression");if(n.init?.property?.type==="MemberExpression"&&(n.init.property._indexTransformed||(or(n.init.property,e),n.init.property._indexTransformed=!0)),a==="var"){let d=e.getCurrentHoistingScope();if(d){for(let f of d)if(f.type==="VariableDeclaration")for(let m of f.declarations){if(!m.init||m.init.type!=="CallExpression")continue;let y=m.init.callee;if(y?.type!=="MemberExpression")continue;let g,w=y.property?.name;if(y.object?.type==="Identifier"?g=y.object.name:y.object?.type==="MemberExpression"&&y.object.property?.name&&(g=y.object.property.name),g&&w){let k=`${g}.${w}`;hN.includes(k)&&(m.init={type:"ArrowFunctionExpression",params:[],body:m.init,expression:!0,async:!1})}}}}let h;if(n.init)if(s||l)h=n.init;else if(a==="var")h=A.createInitVarCall(c,n.init,n._varip===!0);else if(n._tupleArity!==void 0){let d=A.createCallExpression(A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("toTuple")),[n.init,A.createLiteral(n._tupleArity)]);h=A.createInitCall(c,d)}else h=A.createInitCall(c,u?n.init.object:n.init,u?n.init.property:void 0);else a!=="var"?h=A.createInitCall(c,A.createIdentifier("NaN")):h=A.createIdentifier("undefined");let p=A.createExpressionStatement(A.createAssignmentExpression(c,h));if(l){let d=n.init.object.name,f=rt(d,e),m=n.init.property.value,y={type:"MemberExpression",object:A.createGetCall(f,0),property:{type:"Literal",value:m},computed:!0};p.expression.right=A.createCallExpression(A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("init")),[c,y])}s&&(e.pushScope("fn"),ct(n.init.body,e,{IfStatement(d,f,m){f.pushScope("if"),d.test&&rh(d.test,f),m(d.consequent,f),d.alternate&&(f.pushScope("els"),m(d.alternate,f),f.popScope()),f.popScope()},VariableDeclaration(d,f){Gm(d,f)},Identifier(d,f){tt(d,f)},AssignmentExpression(d,f){Eo(d,f)},SwitchStatement(d,f,m){d.discriminant.parent=d,m(d.discriminant,f),d.cases.forEach(y=>{y.parent=d,m(y,f)})},SwitchCase(d,f,m){d.test&&(d.test.parent=d,m(d.test,f));let y=[];d.consequent.forEach(g=>{f.enterHoistingScope(),m(g,f);let w=f.exitHoistingScope();y.push(...w),y.push(g)}),d.consequent=y},BlockStatement(d,f,m){let y=[];d.body.forEach(g=>{f.enterHoistingScope(),m(g,f);let w=f.exitHoistingScope();y.push(...w),y.push(g)}),d.body=y}}),e.popScope()),Object.assign(t,p)})}function Km(t,e,n){if(e.setSuppressHoisting(!0),e.setInLoopTest(!0),t.init&&t.init.type==="VariableDeclaration"){let s=t.init.declarations.map(a=>(e.addLoopVariable(a.id.name,a.id.name),{type:"VariableDeclarator",id:{type:"Identifier",name:a.id.name},init:a.init}));t.init={type:"VariableDeclaration",kind:t.init.kind,declarations:s};for(let a of s)a.init&&ct(a.init,e,{Identifier(o,l){!e.isLoopVariable(o.name)&&!o.computed&&(e.pushScope("for"),tt(o,l),o.type==="Identifier"&&(e.isContextBound(o.name)&&o.parent&&o.parent.type==="MemberExpression"&&o.parent.object===o||(o.computed=!0,Bt(o))),e.popScope())},MemberExpression(o,l,c){e.pushScope("for"),Le(o,"",e),e.popScope(),o.type==="MemberExpression"&&o.object&&(o.object.type!=="Identifier"||!e.isContextBound(o.object.name))&&c(o.object,l)},CallExpression(o,l,c){o.callee.parent=o,c(o.callee,l);for(let u of o.arguments)c(u,l)}})}t.test&&ct(t.test,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),tt(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Bt(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),Le(s,"",e),e.popScope(),s.type==="MemberExpression"&&s.object&&(s.object.type!=="Identifier"||!e.isContextBound(s.object.name))&&o(s.object,a)},CallExpression(s,a,o){s.callee.parent=s,o(s.callee,a);for(let l of s.arguments)o(l,a)}}),t.update&&ct(t.update,e,{Identifier(s,a){!e.isLoopVariable(s.name)&&!s.computed&&(e.pushScope("for"),tt(s,a),s.type==="Identifier"&&(e.isContextBound(s.name)&&s.parent&&s.parent.type==="MemberExpression"&&s.parent.object===s||(s.computed=!0,Bt(s))),e.popScope())},MemberExpression(s,a,o){e.pushScope("for"),Le(s,"",e),e.popScope(),s.type==="MemberExpression"&&s.object&&(s.object.type!=="Identifier"||!e.isContextBound(s.object.name))&&o(s.object,a)},CallExpression(s,a,o){s.callee.parent=s,o(s.callee,a);for(let l of s.arguments)o(l,a)}}),e.setSuppressHoisting(!1),e.setInLoopTest(!1);let r=e.getNextLoopGuardName(),i=cs(r);if(e.addHoistedStatement(i.counterDecl),e.pushScope("for"),n(t.body,e),e.popScope(),t.body.type!=="BlockStatement"&&(t.body={type:"BlockStatement",body:[t.body]}),t.body.body.unshift(i.guardCheck),t.init&&t.init.type==="VariableDeclaration")for(let s of t.init.declarations)e.removeLoopVariable(s.id.name)}function Ym(t,e,n){e.setSuppressHoisting(!0),e.setInLoopTest(!0),t.test&&rh(t.test,e),e.setSuppressHoisting(!1),e.setInLoopTest(!1);let r=e.getNextLoopGuardName(),i=cs(r);e.addHoistedStatement(i.counterDecl),e.pushScope("whl"),n(t.body,e),e.popScope(),t.body.type!=="BlockStatement"&&(t.body={type:"BlockStatement",body:[t.body]}),t.body.body.unshift(i.guardCheck)}function rh(t,e){ct(t,e,{MemberExpression(n,r,i){(n.object&&n.object.type==="Identifier"&&!e.isContextBound(n.object.name)&&!n.computed||n.object&&!n.computed&&(n.object.type==="CallExpression"||n.object.type==="MemberExpression"))&&(n.object.parent=n,i(n.object,r)),Le(n,"",e)},CallExpression(n,r){Ye(n,r)},BinaryExpression(n,r,i){n.left.type==="Identifier"&&(n.left.parent=n),n.right.type==="Identifier"&&(n.right.parent=n),i(n.left,r),i(n.right,r)},LogicalExpression(n,r,i){n.left.type==="Identifier"&&(n.left.parent=n),n.right.type==="Identifier"&&(n.right.parent=n),i(n.left,r),i(n.right,r)},UnaryExpression(n,r,i){n.argument.type==="Identifier"&&(n.argument.parent=n),i(n.argument,r)},Identifier(n,r){let i=n.parent,s=i&&i.type==="UnaryExpression",a=i&&i.type==="BinaryExpression",o=i&&i.type==="LogicalExpression",l=i&&i.type==="ConditionalExpression";tt(n,r),n.type==="Identifier"&&(s||a||o||l)&&(i&&i.type==="CallExpression"&&i.callee&&i.callee.object&&i.callee.object.name===Oe&&i.callee.property?.name==="get"||Bt(n));let c=e.getCurrentScopeType()==="if";e.isContextBound(n.name)&&!e.isRootParam(n.name)&&c&&Bt(n)}})}function XC(t,e,n){let r=t._chainHoistFrame??e.getCurrentHoistingScope();if(t.test){e.pushScope("if");let i=t._chainHoistFrame?e.setChainHoistFrame(t._chainHoistFrame):void 0;try{rh(t.test,e)}finally{t._chainHoistFrame&&e.restoreChainHoistFrame(i??null)}e.popScope()}if(e.pushScope("if"),n(t.consequent,e),e.popScope(),t.alternate){if(e.pushScope("els"),t.alternate.type==="IfStatement"){r&&(t.alternate._chainHoistFrame=r);let i={type:"BlockStatement",body:[t.alternate]};n(i,e),t.alternate=i.body.length===1&&i.body[0].type==="IfStatement"?i.body[0]:i}else n(t.alternate,e);e.popScope()}}function md(t,e,n){let r=t.object;if(!(!r||t.computed))if(r.type==="Identifier"){if(e.isContextBound(r.name))return;r.parent=t,tt(r,e)}else(r.type==="MemberExpression"||r.type==="CallExpression"&&!ZC(r))&&(r.parent=t,n(r,e))}function ZC(t){return t.callee?.type==="MemberExpression"&&t.callee.object?.type==="Identifier"&&t.callee.object.name===Oe}function JC(t){let e=t.object;return e?.type==="MemberExpression"&&e.object?.type==="Identifier"&&e.object.name===Oe&&["const","let","var","params"].includes(e.property?.name)}function QC(t,e){let n=e.getCurrentScopeType();if(t.argument){if(t.argument.type==="ArrayExpression")t.argument.elements=t.argument.elements.map(r=>{if(r.type==="Identifier"){if(e.isContextBound(r.name)&&!e.isRootParam(r.name))return A.createGetCall(r,0);if(e.isLocalSeriesVar(r.name)){let i=A.createIdentifier(r.name);return i._skipTransformation=!0,A.createGetCall(i,0)}return Qu(r.name,e)}else{if(r.type==="MemberExpression"&&JC(r))return A.createGetCall(r,0);if(r.type==="MemberExpression"&&r.computed)return Le(r,"",e),r;if(r.type==="MemberExpression"||r.type==="BinaryExpression"||r.type==="LogicalExpression"||r.type==="ConditionalExpression"||r.type==="CallExpression"||r.type==="UnaryExpression")return ct(r,e,{Identifier(i,s){tt(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Bt(i),i._arrayAccessed=!0)},MemberExpression(i,s,a){md(i,s,a),Le(i,"",e)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),Ye(i,s),i.type==="CallExpression"&&i.arguments.forEach(o=>a(o,s))},BinaryExpression(i,s,a){a(i.left,s),a(i.right,s)}}),r}return r}),t.argument={type:"ArrayExpression",elements:[t.argument]};else if(t.argument.type==="ObjectExpression")t.argument.properties=t.argument.properties.map(r=>r.shorthand?e.isContextBound(r.value.name)?r:(e.getVariable(r.value.name),{type:"Property",key:A.createIdentifier(r.key.name),value:rt(r.value.name,e),kind:"init",method:!1,shorthand:!1,computed:!1}):(r.value&&r.value.type==="Identifier"&&(e.isContextBound(r.value.name)&&!e.isRootParam(r.value.name)||e.isContextBound(r.value.name)||(r.value=rt(r.value.name,e))),r));else if(t.argument.type==="Identifier")tt(t.argument,e),t.argument.type==="Identifier"&&Bt(t.argument);else if(t.argument.type==="MemberExpression"){if(t.argument.object.type==="Identifier"&&!e.isContextBound(t.argument.object.name)&&!e.isLoopVariable(t.argument.object.name)&&!(t.argument.computed&&e.isLocalSeriesVar(t.argument.object.name)))tt(t.argument.object,e);else if(!t.argument.computed&&t.argument.object.type==="MemberExpression"){let r=t.argument.object;for(;r.type==="MemberExpression"&&!r.computed;)r=r.object;r.type==="Identifier"&&!e.isContextBound(r.name)&&!e.isLoopVariable(r.name)&&tt(r,e)}else if(t.argument.computed&&t.argument.object.type==="MemberExpression"){let r=t.argument.object;for(;r.object&&r.object.type==="MemberExpression";)r=r.object;r.object?.type==="Identifier"&&e.isUdtInstance(r.object.name)&&Le(t.argument,"",e)}}if(n==="fn"){t.argument.type==="Identifier"&&e.isContextBound(t.argument.name)&&!e.isRootParam(t.argument.name)?t.argument=A.createArrayAccess(t.argument,0):t.argument.type==="MemberExpression"?t.argument.computed&&(eh.includes(t.argument.object.type)||So(t.argument.object,e))?(Le(t.argument,"",e),t.argument._historyTransformed&&(t.argument.arguments[1]=th(t.argument.arguments[1],e))):t.argument.object.type==="Identifier"&&e.isContextBound(t.argument.object.name)&&!e.isRootParam(t.argument.object.name)?t.argument.computed?Le(t.argument,"",e):t.argument._indexTransformed||(or(t.argument,e),t.argument._indexTransformed=!0):t.argument.computed&&t.argument.object.type==="Identifier"&&e.isLocalSeriesVar(t.argument.object.name)&&Le(t.argument,"",e):(t.argument.type==="BinaryExpression"||t.argument.type==="LogicalExpression"||t.argument.type==="ConditionalExpression"||t.argument.type==="CallExpression"||t.argument.type==="UnaryExpression"||t.argument.type==="AssignmentExpression")&&ct(t.argument,e,{Identifier(i,s){tt(i,s),i.type==="Identifier"&&!i._arrayAccessed&&(Bt(i),i._arrayAccessed=!0)},MemberExpression(i,s,a){md(i,s,a),Le(i,"",e)},AssignmentExpression(i,s,a){if(i.left.type==="Identifier"){let[o]=s.getVariable(i.left.name);if(o===i.left.name&&!s.isContextBound(i.left.name)){a(i.right,s);return}}Eo(i,s)},CallExpression(i,s,a){(i.callee.type==="ArrowFunctionExpression"||i.callee.type==="FunctionExpression")&&a(i.callee,s),Ye(i,s),i.type==="CallExpression"&&i.arguments.forEach(o=>a(o,s))},BinaryExpression(i,s,a){a(i.left,s),a(i.right,s)},ForStatement(i,s,a){Km(i,s,a)},WhileStatement(i,s,a){Ym(i,s,a)},ArrowFunctionExpression(i,s,a){if(i.body)if(i.body.type==="BlockStatement"){let o=[];i.body.body.forEach(l=>{e.enterHoistingScope(),a(l,s);let c=e.exitHoistingScope();o.push(...c),o.push(l)}),i.body.body=o}else a(i.body,s)},FunctionExpression(i,s,a){if(i.body&&i.body.type==="BlockStatement"){let o=[];i.body.body.forEach(l=>{e.enterHoistingScope(),a(l,s);let c=e.exitHoistingScope();o.push(...c),o.push(l)}),i.body.body=o}},SwitchStatement(i,s,a){i.discriminant.parent=i,a(i.discriminant,s),i.cases.forEach(o=>{o.parent=i,a(o,s)})},SwitchCase(i,s,a){i.test&&(i.test.parent=i,a(i.test,s));let o=[];i.consequent.forEach(l=>{e.enterHoistingScope(),a(l,s);let c=e.exitHoistingScope();o.push(...c),o.push(l)}),i.consequent=o},BlockStatement(i,s,a){let o=[];i.body.forEach(l=>{s.enterHoistingScope(),a(l,s);let c=s.exitHoistingScope();o.push(...c),o.push(l)}),i.body=o}});let r=A.createCallExpression(A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("precision")),[t.argument]);t.argument=r}}}function eI(t,e,n){let r=A.createVariableDeclaration("$$",A.createCallExpression(A.createMemberExpression(A.createContextIdentifier(),A.createIdentifier("peekCtx")),[]));if(r._skipTransformation=!0,e.addLoopVariable("$$","$$"),t.body&&t.body.type==="BlockStatement"){t.body.body.unshift(r),e.pushScope("fn"),t.params.forEach(u=>{u.type==="Identifier"?e.addFunctionParam(u.name):u.type==="AssignmentPattern"&&u.left?.type==="Identifier"&&e.addFunctionParam(u.left.name)});let i=t.id?.name,s=i?.startsWith("$M_")?i.slice(3):i,a=s?e.getFunctionParamUdtTypes(s):void 0,o={};if(a)for(let[u,h]of Object.entries(a))o[u]=e.getVariableUdtType(u),e.markVariableAsUdtInstance(u,h);let l=s?e.getFunctionParamStaticTypes(s):void 0,c={};if(l)for(let[u,h]of Object.entries(l))c[u]=e.getVarStaticType(u),e.setVarStaticType(u,h);if(e.enterFunctionHoistingRoot(),n(t.body,e),e.exitFunctionHoistingRoot(),t.params.forEach(u=>{u.type==="Identifier"?e.removeFunctionParam(u.name):u.type==="AssignmentPattern"&&u.left?.type==="Identifier"&&e.removeFunctionParam(u.left.name)}),a)for(let u of Object.keys(a)){e.unmarkVariableAsUdtInstance(u);let h=o[u];h!==void 0&&e.markVariableAsUdtInstance(u,h)}if(l)for(let u of Object.keys(l)){e.unsetVarStaticType(u);let h=c[u];h!==void 0&&e.setVarStaticType(u,h)}e.popScope()}}function tI(t){let e={...j,LineComment:()=>{}};function n(o){return o?o.type==="Identifier"?o.name:o.type==="CallExpression"&&o.callee?.type==="MemberExpression"&&o.callee.object?.name==="$"&&o.callee.property?.name==="get"&&o.arguments?.[0]?.type==="Identifier"?o.arguments[0].name:null:null}let r=new Map;xt(t,{FunctionDeclaration(o){o.id?.name&&r.set(o.id.name,o)}},e);function i(o){let l=!1,c={...e,FunctionDeclaration:()=>{},FunctionExpression:()=>{},ArrowFunctionExpression:()=>{}};return xt(o,{AwaitExpression(){l=!0}},c),l}let s=!0,a=0;for(;s&&a<20;){s=!1,a++,xt(t,{ArrowFunctionExpression(c){!c.async&&i(c.body)&&(c.async=!0,s=!0)},FunctionExpression(c){!c.async&&i(c.body)&&(c.async=!0,s=!0)}},e);let o=[];xt(t,{CallExpression(c){!c._asyncWrapped&&(c.callee?.type==="ArrowFunctionExpression"||c.callee?.type==="FunctionExpression")&&c.callee.async===!0&&o.push(c)}},e);for(let c of o){let u={};for(let h of Object.keys(c))u[h]=c[h];u._asyncWrapped=!0;for(let h of Object.keys(c))delete c[h];c.type="AwaitExpression",c.argument=u,s=!0}let l=new Set;for(let[c,u]of r)i(u.body)&&(u.async||(u.async=!0,s=!0),l.add(c));if(l.size>0){let c=[];xt(t,{CallExpression(u){if(!u._asyncWrapped&&u.callee?.type==="MemberExpression"&&u.callee.object?.name==="$"&&u.callee.property?.name==="call"&&u.arguments?.length>0){let h=n(u.arguments[0]);h&&l.has(h)&&c.push(u)}}},e);for(let u of c){let h={};for(let p of Object.keys(u))h[p]=u[p];h._asyncWrapped=!0;for(let p of Object.keys(u))delete u[p];u.type="AwaitExpression",u.argument=h,s=!0}}}}var nI={"==":"__eq","===":"__eq","!=":"__neq","!==":"__neq","<":"__lt","<=":"__le",">":"__gt",">=":"__ge"},rI=new Set(["<","<=",">",">="]);function iI(t,e){if(t._skipCompare)return!0;for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1];if(r.type==="ForStatement"&&(i===r.test||i===r.update)||r.type==="ForStatement"&&i===r.init&&e.slice(n+1).some(s=>s.type==="VariableDeclarator"&&/^__for_up\\d+$/.test(s.id?.name))||(r.type==="WhileStatement"||r.type==="DoWhileStatement")&&i===r.test)return!0}return!1}function sI(t){let e={...j,LineComment:()=>{}};Zu(t,{BinaryExpression(n,r,i){let s=nI[n.operator];if(!s||rI.has(n.operator)&&iI(n,i))return;let a=A.createMathCompareCall(s,n.left,n.right);a._transformed=!0,Object.assign(n,a)}},e)}var aI={"&&":"__and","||":"__or"};function oI(t){let e={...j,LineComment:()=>{}};xt(t,{LogicalExpression(n){if(!n._strictLogical)return;let r=aI[n.operator];if(!r)return;let i=A.createMathCompareCall(r,n.left,n.right);i._transformed=!0,Object.assign(n,i),delete n.operator,delete n.left,delete n.right}},e)}var lI={"+":"__union","-":"__minus"};function yd(t){return t?.type==="MemberExpression"&&!t.computed&&t.object?.type==="Identifier"&&t.object.name==="display"?!0:t?.type==="CallExpression"&&t._displaySetOp===!0}function cI(t){let e={...j,LineComment:()=>{}};xt(t,{BinaryExpression(n){let r=lI[n.operator];if(!r||!yd(n.left)&&!yd(n.right))return;let i=A.createMemberExpression(A.createIdentifier("display"),A.createIdentifier(r),!1),s=A.createCallExpression(i,[n.left,n.right]);s._displaySetOp=!0,Object.assign(n,s)}},e)}function uI(t,e,n,r={debug:!1,ln:!1},i=[]){let s=a=>{if(!r.debug||!a.loc||!i.length)return null;let o=a.loc.start.line-1;if(o>=0&&o<i.length){let l=i[o].trim();if(l)return{type:"LineComment",value:`${r.ln?` [Line ${a.loc.start.line}]`:""} ${l}`}}return null};ct(t,e,{Program(a,o,l){let c=[];a.body.forEach(u=>{o.enterHoistingScope(),l(u,o);let h=o.exitHoistingScope(),p=s(u);p&&c.push(p),c.push(...h),c.push(u)}),a.body=c},BlockStatement(a,o,l){let c=[];a.body.forEach(u=>{o.enterHoistingScope(),l(u,o);let h=o.exitHoistingScope(),p=s(u);p&&c.push(p),c.push(...h),c.push(u)}),a.body=c},ReturnStatement(a,o,l){a.argument&&a.argument.type!=="ArrayExpression"&&a.argument.type!=="ObjectExpression"&&a.argument.type!=="Identifier"&&a.argument.type!=="MemberExpression"&&o.getCurrentScopeType()!=="fn"&&l(a.argument,o),QC(a,o)},VariableDeclaration(a,o){Gm(a,o)},Identifier(a,o){tt(a,o)},CallExpression(a,o,l){a.callee&&(a.callee.type==="ArrowFunctionExpression"||a.callee.type==="FunctionExpression")?l(a.callee,o):a.callee&&a.callee.type==="MemberExpression"&&a.callee.object&&(a.callee.object.parent=a.callee,l(a.callee.object,o)),Ye(a,o)},ArrowFunctionExpression(a,o,l){a.body&&l(a.body,o)},FunctionExpression(a,o,l){a.body&&l(a.body,o)},ForOfStatement(a,o,l){if(a.left&&a.left.type==="VariableDeclaration"){a.left._skipTransformation=!0;let h=a.left.declarations[0];h.id.type==="Identifier"?o.addLoopVariable(h.id.name,h.id.name):h.id.type==="ArrayPattern"&&h.id.elements.forEach(p=>{p.type==="Identifier"&&o.addLoopVariable(p.name,p.name)})}if(a.right){a.right.type==="Identifier"?(tt(a.right,o),a.right.type==="Identifier"&&Bt(a.right)):l(a.right,o);let h=a.left&&a.left.type==="VariableDeclaration"&&a.left.declarations[0].id.type==="ArrayPattern"?"entries":"iter",p={...a.right},d=A.createCallExpression(A.createMemberExpression(A.createIdentifier("$"),A.createIdentifier(h),!1),[p]);Object.assign(a.right,d)}let c=o.getNextLoopGuardName(),u=cs(c);if(o.addHoistedStatement(u.counterDecl),a.body&&l(a.body,o),a.body&&(a.body.type!=="BlockStatement"&&(a.body={type:"BlockStatement",body:[a.body]}),a.body.body.unshift(u.guardCheck)),a.left&&a.left.type==="VariableDeclaration"){let h=a.left.declarations[0];h.id.type==="Identifier"?o.removeLoopVariable(h.id.name):h.id.type==="ArrayPattern"&&h.id.elements.forEach(p=>{p.type==="Identifier"&&o.removeLoopVariable(p.name)})}},ForInStatement(a,o,l){a.left&&a.left.type==="VariableDeclaration"&&(a.left._skipTransformation=!0),a.right&&a.right.type==="Identifier"?(tt(a.right,o),a.right.type==="Identifier"&&Bt(a.right)):a.right&&l(a.right,o);let c=cs(o.getNextLoopGuardName());o.addHoistedStatement(c.counterDecl),a.body&&(l(a.body,o),a.body.type!=="BlockStatement"&&(a.body={type:"BlockStatement",body:[a.body]}),a.body.body.unshift(c.guardCheck))},DoWhileStatement(a,o,l){let c=cs(o.getNextLoopGuardName());o.addHoistedStatement(c.counterDecl),a.test&&l(a.test,o),a.body&&(l(a.body,o),a.body.type!=="BlockStatement"&&(a.body={type:"BlockStatement",body:[a.body]}),a.body.body.unshift(c.guardCheck))},MemberExpression(a,o,l){a.object&&(a.object.type==="CallExpression"||a.object.type==="MemberExpression")&&(a.object.parent=a,l(a.object,o)),a.object&&a.object.type==="Identifier"&&!o.isContextBound(a.object.name)&&(a.object.parent=a,l(a.object,o)),Le(a,n,o)},AssignmentExpression(a,o,l){Eo(a,o);let c=u=>{u&&(u.type==="CallExpression"&&u.callee&&!u._iifeTransformed&&(u.callee.type==="ArrowFunctionExpression"||u.callee.type==="FunctionExpression")&&l(u.callee,o),(u.type==="BinaryExpression"||u.type==="LogicalExpression"||u.type==="ConditionalExpression")&&(c(u.left),c(u.right),c(u.consequent),c(u.alternate)))};a.type==="AssignmentExpression"?c(a.right):a.type==="CallExpression"&&a.arguments&&a.arguments.forEach(u=>c(u))},FunctionDeclaration(a,o,l){eI(a,o,l)},ForStatement(a,o,l){Km(a,o,l)},WhileStatement(a,o,l){Ym(a,o,l)},IfStatement(a,o,l){XC(a,o,l)},SwitchStatement(a,o,l){a.discriminant.parent=a,l(a.discriminant,o),a.cases.forEach(c=>{c.parent=a,l(c,o)})},SwitchCase(a,o,l){a.test&&(a.test.parent=a,l(a.test,o));let c=[];a.consequent.forEach(u=>{o.enterHoistingScope(),l(u,o);let h=o.exitHoistingScope();c.push(...h),c.push(u)}),a.consequent=c},AwaitExpression(a,o,l){a.argument&&(a.argument._insideAwait=!0,l(a.argument,o),a.argument.type==="Identifier"&&a.argument._wasInsideAwait===!0&&(a.type="Identifier",a.name=a.argument.name,a.argument._wasHoisted&&(a._wasHoisted=a.argument._wasHoisted),delete a.argument))}})}var hI=Object.defineProperty,pI=(t,e,n)=>e in t?hI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vl=(t,e,n)=>pI(t,typeof e!="symbol"?e+"":e,n),b={NUMBER:"NUMBER",STRING:"STRING",BOOLEAN:"BOOLEAN",IDENTIFIER:"IDENTIFIER",KEYWORD:"KEYWORD",OPERATOR:"OPERATOR",LPAREN:"LPAREN",RPAREN:"RPAREN",LBRACKET:"LBRACKET",RBRACKET:"RBRACKET",LBRACE:"LBRACE",RBRACE:"RBRACE",COMMA:"COMMA",DOT:"DOT",COLON:"COLON",SEMICOLON:"SEMICOLON",INDENT:"INDENT",DEDENT:"DEDENT",NEWLINE:"NEWLINE",COMMENT:"COMMENT",EOF:"EOF"},dI=new Set(["if","else","for","while","switch","break","continue","var","varip","type","and","or","not","to","by","in","as","import","export","method","enum"]),fI=new Set(["type","method","enum"]),gd=new Set(["catch","class","do","ellipse","is","polygon","range","return","struct","text","throw","try"]),mI=["==","!=","<=",">=",":=","+=","-=","*=","/=","%=","=>","//","and","or","not"],Cc=class{constructor(e,n,r,i,s=0,a=null){this.type=e,this.value=n,this.line=r,this.column=i,this.indent=s,this.raw=a,vl(this,"wrapped",null),vl(this,"grouped",!1),vl(this,"startColumn")}},yI=Object.defineProperty,gI=(t,e,n)=>e in t?yI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,an=(t,e,n)=>gI(t,typeof e!="symbol"?e+"":e,n),Xm=class rs{constructor(e){an(this,"source"),an(this,"pos"),an(this,"line"),an(this,"column"),an(this,"tokens"),an(this,"indentStack"),an(this,"atLineStart"),an(this,"parenDepth"),an(this,"bracketDepth"),an(this,"braceDepth"),an(this,"pendingWrap",null),this.source=e,this.pos=0,this.line=1,this.column=1,this.tokens=[],this.indentStack=[0],this.atLineStart=!0,this.parenDepth=0,this.bracketDepth=0,this.braceDepth=0}tokenize(){for(;this.pos<this.source.length;){let e=this.peek();if(e==="\\r"){this.advance();continue}if(e===`\n`){this.handleNewline();continue}if(this.atLineStart&&e!==`\n`){this.handleIndentation(),this.atLineStart=!1;continue}if(e===" "||e===" "){this.advance();continue}if(this.pos>=this.source.length)break;if(e==="/"&&this.peek(1)==="/"){this.readComment();continue}if(e===\'"\'||e==="\'"){this.readString();continue}if(e==="#"){this.readColorLiteral();continue}if(this.isDigit(e)){this.readNumber();continue}if(this.isIdentifierStart(e)){this.readIdentifier();continue}if(!this.readOperatorOrPunctuation())throw new Error(`Unexpected character \'${e}\' at ${this.line}:${this.column}`)}for(;this.indentStack.length>1;)this.indentStack.pop(),this.addToken(b.DEDENT,"",this.getCurrentIndent());return this.addToken(b.EOF,""),this.resolveContextualKeywords(),this.tokens}resolveContextualKeywords(){let e=r=>r.type===b.NEWLINE||r.type===b.INDENT||r.type===b.DEDENT||r.type===b.COMMENT,n=r=>!!r&&(r.type===b.IDENTIFIER||r.type===b.KEYWORD);for(let r=0;r<this.tokens.length;r++){let i=this.tokens[r];if(i.type!==b.KEYWORD||!fI.has(i.value))continue;let s=r-1;for(;s>=0&&this.tokens[s].type===b.COMMENT;)s--;let a=s>=0?this.tokens[s]:null;!i.wrapped&&(a===null||e(a)||a.type===b.KEYWORD&&a.value==="export")&&n(this.tokens[r+1])||(i.type=b.IDENTIFIER)}}handleNewline(){this.parenDepth===0&&this.bracketDepth===0&&this.braceDepth===0&&(this.addToken(b.NEWLINE,`\n`),this.atLineStart=!0),this.advance(),this.line++,this.column=1}handleIndentation(){let e=0;for(;this.pos<this.source.length;){let i=this.peek();if(i===" ")e+=1,this.advance();else if(i===" ")e+=rs.TAB_WIDTH,this.advance();else break}if(this.peek()===`\n`||this.peek()==="\\r"||this.peek()==="\\0"||this.peek()==="/"&&this.peek(1)==="/")return;if(e%rs.TAB_WIDTH!==0||this.isContinuationFromPrevToken()){this.joinWithPreviousLine(e);return}let n=e/rs.TAB_WIDTH,r=this.indentStack[this.indentStack.length-1];if(n>r){if(n>r+1){let i=(r+1)*rs.TAB_WIDTH;throw new Error(`Indentation error at ${this.line}:${this.column} - line is indented by ${e} columns, but a local block must be indented by exactly one level (${i} columns: four spaces or one tab) deeper than the enclosing block`)}this.indentStack.push(n),this.addToken(b.INDENT,"",n)}else if(n<r){for(;this.indentStack.length>1&&this.indentStack[this.indentStack.length-1]>n;)this.indentStack.pop(),this.addToken(b.DEDENT,"",this.indentStack[this.indentStack.length-1]);if(this.indentStack[this.indentStack.length-1]!==n)throw new Error(`Indentation error at ${this.line}:${this.column} - misaligned dedent`)}}joinWithPreviousLine(e){let n=null;for(;this.tokens.length>0;){let r=this.tokens[this.tokens.length-1];if(r.type!==b.NEWLINE&&r.type!==b.COMMENT)break;this.tokens.pop()}this.tokens.length!==0&&(n=this.tokens[this.tokens.length-1].line,this.pendingWrap={width:e,fromLine:n,column:this.column})}isContinuationFromPrevToken(){for(let e=this.tokens.length-1;e>=0;e--){let n=this.tokens[e];if(!(n.type===b.NEWLINE||n.type===b.COMMENT))return n.type===b.OPERATOR?n.value!=="=>":n.type===b.COMMA||n.type===b.COLON||n.type===b.KEYWORD&&(n.value==="and"||n.value==="or")}return!1}readComment(){this.column;let e="";for(this.advance(),this.advance();this.pos<this.source.length&&this.peek()!==`\n`;)e+=this.advance();this.parenDepth>0||this.bracketDepth>0||this.braceDepth>0||this.addToken(b.COMMENT,e.trim())}readString(){if(this.peek(1)===this.peek()&&this.peek(2)===this.peek()){this.readMultilineString();return}let e=this.advance(),n=this.column-1,r="";for(;this.pos<this.source.length&&this.peek()!==e;)this.peek()==="\\\\"?r+=this.readEscape(e):r+=this.advance();if(this.peek()!==e)throw new Error(`Unterminated string at ${this.line}:${n}`);this.advance(),this.addToken(b.STRING,r),this.tokens[this.tokens.length-1].startColumn=n}readEscape(e){this.advance();let n=this.advance();switch(n){case"n":return`\n`;case"t":return" ";case"r":return"\\r";case"\\\\":return"\\\\";case e:return e;default:return n}}readMultilineString(){let e=this.peek(),n=this.line,r=this.column;this.advance(),this.advance(),this.advance();let i="";for(;this.pos<this.source.length;){let s=this.peek();if(s===e&&this.peek(1)===e&&this.peek(2)===e){this.advance(),this.advance(),this.advance(),this.addToken(b.STRING,i);return}if(s==="\\r"){this.advance();continue}if(s===`\n`){this.advance(),this.line++,this.column=1,i+=`\n`;continue}if(s==="\\\\"){i+=this.readEscape(e);continue}i+=this.advance()}throw new Error(`Unterminated multiline string at ${n}:${r}`)}readColorLiteral(){let e=this.column,n="#";for(this.advance();this.pos<this.source.length&&n.length<9;){let r=this.peek();if(r>="0"&&r<="9"||r>="A"&&r<="F"||r>="a"&&r<="f")n+=this.advance();else break}if(n.length!==7&&n.length!==9)throw new Error(`Invalid color literal \'${n}\' at ${this.line}:${e}`);this.addToken(b.STRING,n)}readNumber(){this.column;let e="",n=!1;for(this.peek()==="."&&this.isDigit(this.peek(1))&&(n=!0,e+=this.advance());this.pos<this.source.length;){let r=this.peek();if(this.isDigit(r))e+=this.advance();else if(r==="."&&!n){let i=this.peek(1);if(this.isDigit(i)||!this.isIdentifierStart(i)){if(n=!0,e+=this.advance(),!this.isDigit(this.peek()))break}else break}else break}if(this.pos<this.source.length){let r=this.peek();if(r==="e"||r==="E"){let i=this.peek(1);if(this.isDigit(i))for(e+=this.advance();this.pos<this.source.length&&this.isDigit(this.peek());)e+=this.advance();else if(i==="+"||i==="-"){let s=this.peek(2);if(this.isDigit(s))for(e+=this.advance(),e+=this.advance();this.pos<this.source.length&&this.isDigit(this.peek());)e+=this.advance()}}}this.addToken(b.NUMBER,parseFloat(e),null,e)}readIdentifier(){this.column;let e="";for(;this.pos<this.source.length&&this.isIdentifierChar(this.peek());)e+=this.advance();dI.has(e)?this.addToken(b.KEYWORD,e):e==="true"||e==="false"?this.addToken(b.BOOLEAN,e==="true"):this.addToken(b.IDENTIFIER,e)}readOperatorOrPunctuation(){let e=this.peek(),n=this.peek(1),r=e+n;if(mI.includes(r))return this.advance(),this.advance(),this.addToken(b.OPERATOR,r),!0;if("+-*/%<>=!?".includes(e))return this.advance(),this.addToken(b.OPERATOR,e),!0;switch(e){case"(":return this.parenDepth++,this.advance(),this.addToken(b.LPAREN,e),!0;case")":return this.parenDepth--,this.advance(),this.addToken(b.RPAREN,e),!0;case"[":{let i=this.parenDepth>0||this.bracketDepth>0||this.braceDepth>0;return this.bracketDepth++,this.advance(),this.addToken(b.LBRACKET,e),this.tokens[this.tokens.length-1].grouped=i,!0}case"]":return this.bracketDepth--,this.advance(),this.addToken(b.RBRACKET,e),!0;case"{":return this.braceDepth++,this.advance(),this.addToken(b.LBRACE,e),!0;case"}":return this.braceDepth--,this.advance(),this.addToken(b.RBRACE,e),!0;case",":return this.advance(),this.addToken(b.COMMA,e),!0;case".":return this.isDigit(this.peek(1))?(this.readNumber(),!0):(this.advance(),this.addToken(b.DOT,e),!0);case":":return this.advance(),this.addToken(b.COLON,e),!0;case";":return this.advance(),this.addToken(b.SEMICOLON,e),!0}return!1}peek(e=0){let n=this.pos+e;return n<this.source.length?this.source[n]:"\\0"}advance(){let e=this.source[this.pos++];return this.column++,e}skipWhitespaceInline(){if(!this.atLineStart)for(;this.pos<this.source.length&&(this.peek()===" "||this.peek()===" ");)this.advance()}isDigit(e){return e>="0"&&e<="9"}isIdentifierStart(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isIdentifierChar(e){return this.isIdentifierStart(e)||this.isDigit(e)}getCurrentIndent(){return this.indentStack[this.indentStack.length-1]}addToken(e,n,r=null,i=null){let s=new Cc(e,n,this.line,this.column,r!==null?r:this.getCurrentIndent(),i);this.pendingWrap&&(s.wrapped=this.pendingWrap,this.pendingWrap=null),this.tokens.push(s)}};an(Xm,"TAB_WIDTH",4);var ih=Xm,_I=Object.defineProperty,bI=(t,e,n)=>e in t?_I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xt=(t,e,n)=>bI(t,typeof e!="symbol"?e+"":e,n),Ne=class{constructor(e){this.type=e}},Ic=class extends Ne{constructor(e){super("Program"),this.body=e}},gt=class extends Ne{constructor(e){super("ExpressionStatement"),this.expression=e}},On=(t=>(t.VAR="var",t.LET="let",t.CONST="const",t))(On||{}),on=class extends Ne{constructor(e,n="let"){super("VariableDeclaration"),this.declarations=e,this.kind=n}},Lt=class extends Ne{constructor(e,n,r=null){super("VariableDeclarator"),this.id=e,this.init=n,this.varType=r}},Za=class extends Ne{constructor(e,n,r,i=null){super("FunctionDeclaration"),this.id=e,this.params=n,this.body=r,this.returnType=i}},Mc=class extends Ne{constructor(e,n){super("TypeDefinition"),this.name=e,this.fields=n}},Pc=class extends Ne{constructor(e,n,r,i,s){super("ImportDeclaration"),this.path=e,this.user=n,this.name=r,this.version=i,this.alias=s}},us=class extends Ne{constructor(e,n,r=null){super("IfStatement"),this.test=e,this.consequent=n,this.alternate=r,Xt(this,"_line")}},Ja=class extends Ne{constructor(e,n,r,i){super("ForStatement"),this.init=e,this.test=n,this.update=r,this.body=i,Xt(this,"isForIn")}},Dc=class extends Ne{constructor(e,n){super("WhileStatement"),this.test=e,this.body=n}},ln=class extends Ne{constructor(e){super("BlockStatement"),this.body=e}},Oc=class extends Ne{constructor(e){super("ReturnStatement"),this.argument=e}},ge=class extends Ne{constructor(e){super("Identifier"),this.name=e,Xt(this,"varType"),Xt(this,"returnType"),Xt(this,"isMethod")}},Tt=class extends Ne{constructor(e,n=null){super("Literal"),this.value=e,this.raw=n}},wn=class extends Ne{constructor(e,n,r){super("BinaryExpression"),this.operator=e,this.left=n,this.right=r}},hs=class extends Ne{constructor(e,n,r=!0){super("UnaryExpression"),this.operator=e,this.argument=n,this.prefix=r}},xr=class extends Ne{constructor(e,n,r){super("AssignmentExpression"),this.operator=e,this.left=n,this.right=r}},Qa=class extends Ne{constructor(e,n,r=!1){super("UpdateExpression"),this.operator=e,this.argument=n,this.prefix=r}},Rc=class extends Ne{constructor(e,n){super("CallExpression"),this.callee=e,this.args=n,Xt(this,"arguments"),this.callee=e,this.arguments=n}},ks=class extends Ne{constructor(e,n,r=!1){super("MemberExpression"),this.object=e,this.property=n,this.computed=r}},Fn=class extends Ne{constructor(e,n,r){super("ConditionalExpression"),this.test=e,this.consequent=n,this.alternate=r,Xt(this,"needsIIFE"),Xt(this,"consequentStmts"),Xt(this,"alternateStmts")}},Lc=class extends Ne{constructor(e){super("ArrayExpression"),this.elements=e}},As=class extends Ne{constructor(e){super("ObjectExpression"),this.properties=e}},Oi=class extends Ne{constructor(e,n){super("Property"),this.key=e,this.value=n,Xt(this,"kind"),Xt(this,"method"),Xt(this,"shorthand"),Xt(this,"computed"),this.kind="init",this.method=!1,this.shorthand=!1,this.computed=!1}},eo=class extends Ne{constructor(e){super("ArrayPattern"),this.elements=e}},to=class extends Ne{constructor(e,n){super("AssignmentPattern"),this.left=e,this.right=n}},Fc=class extends Ne{constructor(e,n){super("SwitchExpression"),this.discriminant=e,this.cases=n}},Bc=class extends Ne{constructor(e,n,r){super("SwitchCase"),this.test=e,this.consequent=n,this.statements=r,this.statements=r}};function xI(t){let e=t.split("/"),n=Number(e[2]);if(e.length!==3||!e[0]||!e[1]||!/^\\d+$/.test(e[2]??"")||!Number.isSafeInteger(n))throw new Error(`Invalid import path "${t}". Expected <user>/<library>/<version>, e.g. "TradingView/ta/7"`);return{user:e[0],name:e[1],version:n}}var _d=new Set([b.NEWLINE,b.COMMENT,b.EOF,b.INDENT,b.DEDENT]);function Zm(t,e){let n=t[e],r=`${n.line}:${n.column-6}`,i=e+1,s="";for(;i<t.length&&!_d.has(t[i].type)&&!(t[i].type===b.KEYWORD&&t[i].value==="as");){let l=t[i++];s+=l.raw??String(l.value)}if(!s)throw new Error(`Missing library path after "import" at ${r}`);let a;try{a=xI(s)}catch(l){throw new Error(`${l.message} at ${r}`)}let o=a.name;if(t[i]?.type===b.KEYWORD&&t[i].value==="as"){let l=t[i+1];if(l?.type!==b.IDENTIFIER)throw new Error(`Expected an alias after "as" at ${r}`);o=l.value,i+=2}if(i<t.length&&!_d.has(t[i].type))throw new Error(`Unexpected token \'${t[i].value}\' in import statement at ${r}`);return{spec:{path:s,...a,alias:o},next:i}}function bd(t){let e=new ih(t).tokenize(),n=[],r=0;for(let i=0;i<e.length;i++){let s=e[i];if(s.type===b.INDENT?r++:s.type===b.DEDENT&&r--,r!==0||s.type!==b.KEYWORD||s.value!=="import")continue;let a=e[i-1];if(a&&a.type!==b.NEWLINE&&a.type!==b.DEDENT&&a.type!==b.COMMENT)continue;let o=e[i+1]?.type;o!==b.IDENTIFIER&&o!==b.NUMBER||n.push(Zm(e,i).spec)}return n}var vI=Object.defineProperty,wI=(t,e,n)=>e in t?vI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yt=(t,e,n)=>wI(t,typeof e!="symbol"?e+"":e,n),wl=["const","simple","series"],Jm=class Qm{constructor(e){Yt(this,"tokens"),Yt(this,"pos"),Yt(this,"functionNames",new Set),Yt(this,"typeNames",new Set),Yt(this,"typeVariableNames",new Set),Yt(this,"paramScopes",[]),Yt(this,"loopValueCounter",0),Yt(this,"onceCounter",0),Yt(this,"functionTupleArity",new Map),Yt(this,"functionParamNames",new Map),Yt(this,"tupleLiteralStart",new WeakMap),Yt(this,"forLoopCount",0),this.tokens=e,this.pos=0}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}isCurrentFunctionParam(e){for(let n of this.paramScopes)if(n.has(e))return!0;return!1}advance(){return this.tokens[this.pos++]}match(e,n=null){let r=this.peek();return!(r.type!==e||n!==null&&r.value!==n)}expect(e,n=null){let r=this.peek();if(r.type!==e)throw new Error(`Expected ${e} but got ${r.type} at ${r.line}:${r.column}${this.layoutHint(r)}`);if(n!==null&&r.value!==n)throw new Error(`Expected \'${n}\' but got \'${r.value}\' at ${r.line}:${r.column}${this.layoutHint(r)}`);return this.advance()}unexpected(e){if(e.type===b.INDENT){let i=this.tokens[this.tokens.indexOf(e)+1]??e;return new Error(`Unexpected indentation at ${e.line}:${e.column} - \'${i.value}\' is indented as a local block, but the previous statement does not open one. A line indented by a multiple of four columns starts a new statement; to wrap a long line, indent the continuation by a number of columns that is not a multiple of four`)}let n=e.type===b.NEWLINE?"end of line":e.value,r=e.wrapped?e.wrapped.column:e.column;return new Error(`Unexpected token ${e.type} \'${n}\' at ${e.line}:${r}${this.layoutHint(e)}`)}layoutHint(e){let n=e.wrapped;if(!n)return"";let r=n.width%4!==0?`is indented by ${n.width} columns, which is not a multiple of four, so it continues line ${n.fromLine} (Pine line wrapping)`:`continues line ${n.fromLine}, which ends with an operator`;return` - line ${e.line} ${r}. A statement inside a local block must be indented by four spaces or one tab per level`}rejectDanglingWrappedLine(){let e=this.peek();if(e.wrapped&&e.type!==b.COMMA)throw this.unexpected(e)}startsNewLine(){let e=this.peek();if(e.wrapped||e.grouped)return!1;let n=this.pos-1;for(;n>=0&&this.tokens[n].type===b.DEDENT;)n--;if(n<0)return!0;let r=this.tokens[n];return r.type===b.NEWLINE||r.line!==e.line}reservedNameError(e){let n=e.column-String(e.value).length;return new Error(`"${e.value}" cannot be used as a variable or function name. at ${e.line}:${n}`)}isReservedName(e){return e.type===b.KEYWORD||e.type===b.IDENTIFIER&&gd.has(e.value)}expectName(){let e=this.peek();if(this.isReservedName(e))throw this.reservedNameError(e);if(e.type!==b.IDENTIFIER)throw new Error(`Expected ${b.IDENTIFIER} but got ${e.type} at ${e.line}:${e.column}`);return this.advance()}assertDeclarableName(e,n){if(e?.type==="Identifier"&&gd.has(e.name))throw this.reservedNameError(n)}assertParamDefault(e,n){if(e?.type==="CallExpression")throw new Error(`The default value cannot be a function, variable or calculation. at ${this.startOf(n)}`);if(e?.type==="BinaryExpression"||e?.type==="LogicalExpression"||e?.type==="ConditionalExpression")throw new Error(`The default value assigned to a parameter must be either a literal value (e.g., "5") or a built-in variable (e.g., "close"). at ${this.startOf(n)}`)}startOf(e){return`${e.line}:${e.column-String(e.value).length}`}dottedName(e){if(e?.type==="Identifier")return e.name;if(e?.type==="MemberExpression"&&!e.computed&&e.property?.type==="Identifier"){let n=this.dottedName(e.object);return n===null?null:`${n}.${e.property.name}`}return null}tupleArityOf(e){if(!(e?.type!=="CallExpression"||e.callee?.type!=="Identifier"))return this.functionTupleArity.get(e.callee.name)??void 0}assertNotTupleLiteral(e){if(e?.type==="ArrayExpression"){let n=this.tupleLiteralStart.get(e);throw new Error(`Syntax error at input "["${n?` at ${this.startOf(n)}`:""}`)}}assertNotTupleAssignment(e,n,r){if(this.assertNotTupleLiteral(n),e?.type==="Identifier"&&this.tupleArityOf(n)!==void 0)throw new Error(`Invalid assignment. Cannot assign a tuple to a variable "${e.name}". at ${this.startOf(r)}`)}rejectReservedAssignmentTarget(){let e=this.peek(),n=this.peek(1);if(this.isReservedName(e)&&n.type===b.OPERATOR&&n.value==="=")throw this.reservedNameError(e)}isNameSlot(e){return e.type===b.IDENTIFIER?!0:e.type===b.KEYWORD&&!Qm.STATEMENT_KEYWORDS.has(e.value)}peekOperatorEx(e){let n=this.peek();return n.type!==b.OPERATOR||!e.includes(n.value)?null:n.value}isLayoutToken(){return this.match(b.NEWLINE)||this.match(b.COMMENT)}skipNewlines(e=!1){for(;this.isLayoutToken();)this.advance();e&&this.match(b.INDENT)&&this.advance()}parse(){let e=[];for(this.collectTopLevelFunctionNames();!this.match(b.EOF);){if(this.skipNewlines(),this.match(b.DEDENT)){this.advance();continue}if(this.match(b.EOF))break;let n=this.parseTopLevelStatement();n&&e.push(n),this.skipNewlines()}return new Ic(e)}parseTopLevelStatement(){if(this.isImportStatement()){let e=this.peek().line,{spec:n,next:r}=Zm(this.tokens,this.pos);this.pos=r;let i=new Pc(n.path,n.user,n.name,n.version,n.alias);return i._line=e,i}if(this.isExportStatement()){let e=this.advance(),n=this.parseStatement(!1);if(n?.type!=="FunctionDeclaration"&&n?.type!=="TypeDefinition"&&!n?._enum)throw new Error(`Only functions, methods, types and enums can be exported at ${this.startOf(e)}`);return n.exported=!0,n}return this.parseStatement()}isImportStatement(){let e=this.peek(1).type;return this.match(b.KEYWORD,"import")&&(e===b.IDENTIFIER||e===b.NUMBER)}isExportStatement(){let e=this.peek(1).type;return this.match(b.KEYWORD,"export")&&(e===b.IDENTIFIER||e===b.KEYWORD)}collectTopLevelFunctionNames(){let e=0;for(let r=0;r<this.tokens.length;r++){let i=this.tokens[r];i.type===b.INDENT?e++:i.type===b.DEDENT&&e--;let s=r===0||this.tokens[r-1].type===b.NEWLINE||this.tokens[r-1].type===b.DEDENT,a=this.tokens[r-1],o=a?.type===b.KEYWORD&&a.value==="export";if(e===0&&i.type===b.KEYWORD&&i.value==="type"&&r+1<this.tokens.length&&(s||o)&&this.typeNames.add(this.tokens[r+1].value),e!==0||!(s||o)||i.type!==b.IDENTIFIER||(this.pos=r,!this.isFunctionDeclaration()))continue;let l=this.peek(1).type!==b.LPAREN;this.functionNames.add(this.peek(l?1:0).value)}this.pos=0;let n=0;for(let r=0;r<this.tokens.length-1;r++){let i=this.tokens[r];i.type===b.LPAREN||i.type===b.LBRACKET?n++:(i.type===b.RPAREN||i.type===b.RBRACKET)&&n--;let s=this.tokens[r+1];n===0&&i.type===b.IDENTIFIER&&this.typeNames.has(i.value)&&s.type===b.OPERATOR&&s.value==="="&&this.typeVariableNames.add(i.value)}}variableName(e){return this.functionNames.has(e)||this.typeVariableNames.has(e)?e+"_var":e}isTypeMemberAccess(){return this.peek().type===b.DOT&&this.peek(1).type===b.IDENTIFIER&&(this.peek(1).value==="new"||this.peek(1).value==="copy")&&this.peek(2).type===b.LPAREN}isOnceStatement(){if(this.peek().type!==b.IDENTIFIER||this.peek().value!=="once")return!1;let e=this.peek(1);if(e.type===b.COMMA||e.type===b.DOT||e.type===b.OPERATOR&&["=",":=","+=","-=","*=","/=","%="].includes(e.value))return!1;let n=1,r=0;for(;;n++){let i=this.peek(n);if(i.type===b.EOF)return!1;if(i.type===b.LPAREN||i.type===b.LBRACKET)r++;else if(i.type===b.RPAREN||i.type===b.RBRACKET)r--;else{if(r<=0&&(i.type===b.NEWLINE||i.type===b.INDENT))break;if(i.type===b.OPERATOR&&i.value==="=>")return!1}}for(;this.peek(n).type===b.NEWLINE||this.peek(n).type===b.COMMENT;)n++;return this.peek(n).type===b.INDENT}parseOnceStatement(){this.advance();let e=this.match(b.NEWLINE)||this.match(b.INDENT)?null:this.parseExpression();this.skipNewlines();let n=this.parseBlock(),r=`__once_${this.onceCounter++}`,i=new ge(r);i.varType="bool";let s=new on([new Lt(i,new Tt(!1),"bool")],On.VAR);n.body.unshift(new gt(new xr("=",new ge(r),new Tt(!0))));let a=e?new ln([new us(e,n)]):n,o=new us(new hs("!",new ge(r)),a),l=new ln([s,o]);return l._sequence=!0,l}parseStatement(e=!0){this.skipNewlines();let n=this.peek().line;if(this.match(b.COMMENT))return this.advance(),null;let r;if(this.match(b.KEYWORD,"enum"))r=this.parseEnumDefinition();else if(this.match(b.KEYWORD,"type"))r=this.parseTypeDefinition();else if(this.match(b.KEYWORD,"var")||this.match(b.KEYWORD,"varip"))r=this.parseVarDeclaration();else if(this.match(b.KEYWORD,"method"))r=this.parseMethodDeclaration();else if(this.isOnceStatement())r=this.parseOnceStatement();else if(this.isFunctionDeclaration())r=this.parseFunctionDeclaration();else if(this.match(b.KEYWORD,"if"))r=this.parseIfStatement();else if(this.match(b.KEYWORD,"for"))r=this.parseForStatement();else if(this.match(b.KEYWORD,"while"))r=this.parseWhileStatement();else if(this.isImportStatement()||this.isExportStatement()){let i=this.peek();throw new Error(`"${i.value}" is only allowed in the global scope at ${this.startOf(i)}`)}else if(this.match(b.KEYWORD,"break")||this.match(b.KEYWORD,"continue")){let i=this.advance().value;r=new gt(new ge(i))}else this.isTupleDestructuring()?r=this.parseTupleDestructuring():this.peek().type===b.IDENTIFIER&&this.isTypedVarDeclaration()&&(r=this.parseTypedVarDeclaration());if(!r){this.rejectReservedAssignmentTarget();let i=this.peek(),s=this.parseExpression();if(this.match(b.OPERATOR)){let a=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(a)){this.advance(),this.skipNewlines(!0);let o=this.parseExpression();a==="="&&s.type==="Identifier"?(this.assertDeclarableName(s,i),this.assertNotTupleAssignment(s,o,i),r=new on([new Lt(s,o)],On.LET)):r=new gt(new xr(a===":="?"=":a,s,o))}else r=new gt(s)}else r=new gt(s)}if(r&&(r._line=n,e&&this.match(b.COMMA))){let i=[r];for(;this.match(b.COMMA);){this.advance(),this.skipNewlines(!0);let a=this.parseStatement(!1);a&&i.push(a)}this.rejectDanglingWrappedLine();let s=new ln(i);return s._sequence=!0,s}return this.rejectDanglingWrappedLine(),r}isFunctionDeclaration(){let e=this.pos;try{let n=0;if(this.peek(n).type===b.IDENTIFIER&&this.isNameSlot(this.peek(n+1))&&n++,!this.isNameSlot(this.peek(n))||(n++,this.peek(n).type!==b.LPAREN))return!1;n++;let r=1;for(;r>0&&this.peek(n).type!==b.EOF;)this.peek(n).type===b.LPAREN&&r++,this.peek(n).type===b.RPAREN&&r--,n++;return this.peek(n).type===b.OPERATOR&&this.peek(n).value==="=>"}finally{this.pos=e}}parseTypeExpression(){let e=this.expect(b.IDENTIFIER).value;for(;this.match(b.DOT)&&this.peek(1).type===b.IDENTIFIER;)this.advance(),e+="."+this.advance().value;if(this.match(b.OPERATOR,"<")){this.advance();let n=[];for(n.push(this.parseTypeExpression());this.match(b.COMMA);)this.advance(),this.skipNewlines(),n.push(this.parseTypeExpression());return this.expect(b.OPERATOR,">"),e+"<"+n.join(", ")+">"}return this.match(b.LBRACKET)&&this.peek(1).type===b.RBRACKET?(this.advance(),this.advance(),"array<"+e+">"):e}parseEnumDefinition(){this.expect(b.KEYWORD,"enum");let e=this.expectName().value;this.skipNewlines(),this.expect(b.INDENT);let n=[];for(;!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){if(this.match(b.COMMENT)){this.advance();continue}let a=this.expectName().value,o=null;this.match(b.OPERATOR,"=")&&(this.advance(),o=this.expect(b.STRING).value),n.push({name:a,title:o}),this.skipNewlines()}this.match(b.DEDENT)&&this.advance();let r=n.map(a=>new Oi(new ge(a.name),new Tt(a.title!==null?a.title:a.name))),i=new As(r),s=new on([new Lt(new ge(e),i)],On.CONST);return s._enum=!0,s}parseTypeDefinition(){this.expect(b.KEYWORD,"type");let e=this.expectName().value;this.match(b.OPERATOR,"=>")&&this.advance(),this.skipNewlines(),this.expect(b.INDENT);let n=[];for(;!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){if(this.match(b.KEYWORD,"varip")&&this.advance(),this.isNameSlot(this.peek())&&this.peek(1).type===b.OPERATOR&&this.peek(1).value==="="){let a=this.expectName().value;this.advance(),this.skipNewlines();let o=this.parseExpression();n.push({type:this.inferFieldType(o),name:a,defaultValue:o}),this.skipNewlines();continue}let r=this.parseTypeExpression(),i=this.expectName().value,s=null;this.match(b.OPERATOR,"=")&&(this.advance(),this.skipNewlines(),s=this.parseExpression()),n.push({type:r,name:i,defaultValue:s}),this.skipNewlines()}return this.match(b.DEDENT)&&this.advance(),new Mc(e,n)}inferFieldType(e){if(e?.type==="UnaryExpression"&&(e.operator==="-"||e.operator==="+"))return this.inferFieldType(e.argument);if(e?.type==="Literal"){if(typeof e.value=="boolean")return"bool";if(typeof e.value=="string")return"string";if(typeof e.value=="number")return typeof e.raw=="string"&&/^\\d+$/.test(e.raw)?"int":"float"}return e?.type==="MemberExpression"&&e.object?.type==="Identifier"&&e.object.name==="color"?"color":"float"}parseVarDeclaration(){let e=this.advance(),n=e.value,r=null,i=null;if(this.peek().type===b.IDENTIFIER&&wl.includes(this.peek().value)&&this.peek(1).type===b.IDENTIFIER&&this.advance(),this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.LBRACKET&&this.peek(2).type===b.RBRACKET)r=this.advance().value,this.advance(),r+="[]",this.advance(),i=this.expectName().value;else if(this.peek().type===b.IDENTIFIER&&(this.peek(1).type===b.DOT||this.isNameSlot(this.peek(1))||this.peek(1).type===b.OPERATOR&&this.peek(1).value==="<")){for(r=this.advance().value;this.match(b.DOT)&&this.peek(1).type===b.IDENTIFIER;)this.advance(),r+="."+this.advance().value;if(this.match(b.LBRACKET)&&this.peek(1).type===b.RBRACKET)this.advance(),this.advance(),r+="[]",i=this.expectName().value;else if(this.match(b.OPERATOR,"<")){for(this.advance(),r+="<";!this.match(b.OPERATOR,">");)if(this.match(b.IDENTIFIER))for(r+=this.advance().value;this.match(b.DOT)&&this.peek(1).type===b.IDENTIFIER;)r+=".",this.advance(),r+=this.advance().value;else if(this.match(b.COMMA))r+=this.advance().value,this.skipNewlines();else break;this.match(b.OPERATOR,">")&&(r+=">",this.advance()),i=this.expectName().value}else i=this.expectName().value}else if(this.isNameSlot(this.peek()))i=this.expectName().value;else throw this.match(b.OPERATOR,"=")||this.match(b.LPAREN)?this.reservedNameError(e):new Error(`Expected identifier after ${n} at ${this.peek().line}:${this.peek().column}`);i=this.variableName(i),this.expect(b.OPERATOR,"="),this.skipNewlines(!0);let s=this.parseExpression(),a=new ge(i);r&&(a.varType=r);let o=[new Lt(a,s,r)];for(;this.match(b.COMMA)&&this.peek(1).type===b.KEYWORD&&(this.peek(1).value==="var"||this.peek(1).value==="varip");){this.advance();let l=this.parseVarDeclaration();o.push(...l.declarations)}return new on(o,n)}isTypedVarDeclaration(){let e=0;if(this.peek(e).type!==b.IDENTIFIER)return!1;for(wl.includes(this.peek(e).value)&&this.peek(e+1).type===b.IDENTIFIER&&e++,e++;this.peek(e).type===b.DOT&&this.peek(e+1).type===b.IDENTIFIER;)e+=2;if(this.peek(e).type===b.LBRACKET&&this.peek(e+1).type===b.RBRACKET)return e+=2,this.isNameSlot(this.peek(e))?(e++,this.peek(e).type===b.OPERATOR&&this.peek(e).value==="="):!1;if(this.peek(e).type===b.OPERATOR&&this.peek(e).value==="<"){e++;let n=1;for(;n>0&&this.peek(e).type!==b.EOF;)this.peek(e).type===b.OPERATOR&&this.peek(e).value==="<"?n++:this.peek(e).type===b.OPERATOR&&this.peek(e).value===">"&&n--,e++;return this.isNameSlot(this.peek(e))?(e++,this.peek(e).type===b.OPERATOR&&this.peek(e).value==="="):!1}if(!this.isNameSlot(this.peek(e)))return!1;for(e++;this.isNameSlot(this.peek(e));)e++;return this.peek(e).type===b.OPERATOR&&this.peek(e).value==="="}parseTypedVarDeclaration(){let e="";wl.includes(this.peek().value)&&this.peek(1).type===b.IDENTIFIER&&(e=this.advance().value+" ");let n=this.advance().value;for(;this.match(b.DOT)&&this.peek(1).type===b.IDENTIFIER;)this.advance(),n+="."+this.advance().value;if(this.match(b.LBRACKET)&&this.peek(1).type===b.RBRACKET)this.advance(),this.advance(),n+="[]";else if(this.match(b.OPERATOR,"<")){for(this.advance(),n+="<";!this.match(b.OPERATOR,">");)if(this.match(b.IDENTIFIER))for(n+=this.advance().value;this.match(b.DOT)&&this.peek(1).type===b.IDENTIFIER;)n+=".",this.advance(),n+=this.advance().value;else if(this.match(b.COMMA))n+=this.advance().value,this.skipNewlines();else break;this.match(b.OPERATOR,">")&&(n+=">",this.advance())}else for(;this.peek().type===b.IDENTIFIER&&this.isNameSlot(this.peek(1));)n+=" "+this.advance().value;n=e+n;let r=this.variableName(this.expectName().value);this.expect(b.OPERATOR,"="),this.skipNewlines(!0);let i=this.parseExpression(),s=new ge(r);s.varType=n;let a=[new Lt(s,i,n)];for(;this.match(b.COMMA)&&this.peek(1).type===b.IDENTIFIER&&this.peek(2).type===b.OPERATOR&&this.peek(2).value==="=";){this.advance(),this.skipNewlines(!0);let o=this.variableName(this.expectName().value);this.expect(b.OPERATOR,"="),this.skipNewlines(!0);let l=this.parseExpression(),c=new ge(o);c.varType=n,a.push(new Lt(c,l,n))}return new on(a,On.LET)}parseFunctionDeclaration(){let e=null;this.peek().type===b.IDENTIFIER&&this.isNameSlot(this.peek(1))&&(e=this.advance().value);let n=this.expectName().value;this.functionNames.add(n),this.expect(b.LPAREN);let r=[];for(;!this.match(b.RPAREN)&&(this.skipNewlines(),!this.match(b.RPAREN));){let u=this.peek(),h=null;for(;this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.IDENTIFIER&&this.peek(2).type!==b.LPAREN;)h&&(h+=" "),h=(h||"")+this.advance().value;if(this.isDottedParamType()){let f=this.parseTypeExpression();h=h?h+" "+f:f}if(this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.OPERATOR&&this.peek(1).value==="<"){let f=this.parseTypeExpression();h=h?h+" "+f:f}if(this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.LBRACKET&&this.peek(2).type===b.RBRACKET){let f=this.parseTypeExpression();h=h?h+" "+f:f}let p=this.expectName().value,d=new ge(p);if(h&&(d.varType=h),this.match(b.OPERATOR,"=")){this.advance(),this.skipNewlines();let f=this.parseExpression();this.assertParamDefault(f,u),r.push(new to(d,f))}else r.push(d);this.match(b.COMMA)&&this.advance()}this.expect(b.RPAREN),this.skipNewlines(),this.expect(b.OPERATOR,"=>"),this.skipNewlines();let i=new Set;for(let u of r){let h=u.type==="AssignmentPattern"?u.left:u;h&&h.name&&i.add(h.name)}this.paramScopes.push(i);let s;try{s=this.parseFunctionBody()}finally{this.paramScopes.pop()}let a=new ge(n);e&&(a.returnType=e);let o=s.body[s.body.length-1],l=o?.type==="ReturnStatement"?o.argument:null,c=l?.type==="ArrayExpression"?l.elements.length:this.tupleArityOf(l)??null;return this.functionTupleArity.set(n,this.functionTupleArity.has(n)&&this.functionTupleArity.get(n)!==c?null:c),this.functionParamNames.set(n,this.functionParamNames.has(n)?null:[...i]),new Za(a,r,s,e)}isDottedParamType(){if(this.peek().type!==b.IDENTIFIER||this.peek(1).type!==b.DOT||this.peek(2).type!==b.IDENTIFIER)return!1;let e=3;for(;this.peek(e).type===b.DOT&&this.peek(e+1).type===b.IDENTIFIER;)e+=2;let n=this.peek(e);return n.type===b.LBRACKET?this.peek(e+1).type===b.RBRACKET:n.type===b.OPERATOR&&n.value==="<"?!0:this.isNameSlot(n)}parseMethodDeclaration(){this.expect(b.KEYWORD,"method");let e=null;this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.IDENTIFIER&&this.peek(2).type===b.LPAREN&&(e=this.advance().value);let n=this.expectName().value;this.expect(b.LPAREN);let r=[];for(;!this.match(b.RPAREN)&&(this.skipNewlines(),!this.match(b.RPAREN));){let o=this.peek(),l=null;for(;this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.IDENTIFIER&&this.peek(2).type!==b.LPAREN;)l&&(l+=" "),l=(l||"")+this.advance().value;if(this.isDottedParamType()){let h=this.parseTypeExpression();l=l?l+" "+h:h}if(this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.OPERATOR&&this.peek(1).value==="<"){let h=this.parseTypeExpression();l=l?l+" "+h:h}if(this.peek().type===b.IDENTIFIER&&this.peek(1).type===b.LBRACKET&&this.peek(2).type===b.RBRACKET){let h=this.parseTypeExpression();l=l?l+" "+h:h}let c=this.expectName().value,u=new ge(c);if(l&&(u.varType=l),this.match(b.OPERATOR,"=")){this.advance(),this.skipNewlines();let h=this.parseExpression();this.assertParamDefault(h,o),r.push(new to(u,h))}else r.push(u);this.match(b.COMMA)&&this.advance()}this.expect(b.RPAREN),this.skipNewlines(),this.expect(b.OPERATOR,"=>"),this.skipNewlines();let i=new Set;for(let o of r){let l=o.type==="AssignmentPattern"?o.left:o;l&&l.name&&i.add(l.name)}this.paramScopes.push(i);let s;try{s=this.parseFunctionBody()}finally{this.paramScopes.pop()}let a=new ge(n);return e&&(a.returnType=e),a.isMethod=!0,new Za(a,r,s,e)}parseFunctionBody(){let e=[];if(!this.match(b.INDENT)){let n=this.parseStatementOrSequence(),r=Array.isArray(n)?n:n?[n]:[];return r.length>0&&this._addImplicitReturn(r),new ln(r)}for(this.advance();!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){let n=this.parseStatementOrSequence();Array.isArray(n)?e.push(...n):n&&e.push(n)}return this.match(b.DEDENT)&&this.advance(),e.length>0&&this._addImplicitReturn(e),new ln(e)}_addImplicitReturn(e){this._emitLastValue(e,n=>new Oc(n))}_captureLoopValue(e){let n=e[e.length-1];if(n.body?.type!=="BlockStatement"||n.body.body.length===0)return null;let r=`__loopValue_${this.loopValueCounter++}`,i=()=>new ge("na"),s=a=>new gt(new xr("=",new ge(r),a));return this._emitLastValue(n.body.body,s)?(n.body.body.unshift(s(i())),e.splice(e.length-1,0,new on([new Lt(new ge(r),i())],On.LET)),r):null}_valueOfTrailingLoop(e){let n=e[e.length-1];(n?.type==="ForStatement"||n?.type==="WhileStatement")&&this._emitLastValue(e,r=>new gt(r))}_emitLastValue(e,n){let r=e[e.length-1];if(r.type==="ForStatement"||r.type==="WhileStatement"){let i=this._captureLoopValue(e);return i?(e.push(n(new ge(i))),!0):!1}if(r.type==="ExpressionStatement"){let i=r.expression;return i?.type==="Identifier"&&(i.name==="break"||i.name==="continue")?!1:(i?.type==="AssignmentExpression"&&i.left?.type==="Identifier"?e.push(n(new ge(i.left.name))):e[e.length-1]=n(i),!0)}if(r.type==="VariableDeclaration"){let i=r.declarations[r.declarations.length-1];return i?.id?.type!=="Identifier"?!1:(e.push(n(new ge(i.id.name))),!0)}if(r.type==="IfStatement"){let i=!1;for(let s=r;s;s=s.alternate?.type==="IfStatement"?s.alternate:null){let a=[s.consequent,s.alternate?.type==="BlockStatement"?s.alternate:null];for(let o of a)o?.body?.length>0&&(i=this._emitLastValue(o.body,n)||i)}return i}return!1}continueSequence(e){if(!this.match(b.COMMA))return e;let n=[e];for(;this.match(b.COMMA);){this.advance(),this.skipNewlines(!0);let r=this.parseStatementOrSequence();Array.isArray(r)?n.push(...r):r&&n.push(r)}return n}parseStatementOrSequence(){this.pos;let e=this.peek().line;if(this.match(b.KEYWORD,"if")){let r=this.parseIfStatement();return r&&(r._line=e),r}if(this.match(b.KEYWORD,"for"))return this.parseForStatement();if(this.match(b.KEYWORD,"while"))return this.parseWhileStatement();if(this.isOnceStatement())return this.parseOnceStatement();if(this.match(b.KEYWORD,"break")||this.match(b.KEYWORD,"continue")){let r=this.advance().value;return new gt(new ge(r))}if(this.match(b.KEYWORD,"var")||this.match(b.KEYWORD,"varip"))return this.continueSequence(this.parseVarDeclaration());if(this.isTupleDestructuring())return this.continueSequence(this.parseTupleDestructuring());if(this.peek().type===b.IDENTIFIER&&this.isTypedVarDeclaration())return this.continueSequence(this.parseTypedVarDeclaration());let n=[];for(;;){if(n.length>0&&(this.match(b.KEYWORD,"var")||this.match(b.KEYWORD,"varip")||this.isTupleDestructuring()||this.peek().type===b.IDENTIFIER&&this.isTypedVarDeclaration())){let s=this.parseStatementOrSequence();Array.isArray(s)?n.push(...s):s&&n.push(s);break}this.rejectReservedAssignmentTarget();let r=this.peek(),i=this.parseExpression();if(this.match(b.OPERATOR)){let s=this.peek().value;if(["=",":=","+=","-=","*=","/=","%="].includes(s)){this.advance(),this.skipNewlines(!0);let a=this.parseExpression();if(s==="="&&i.type==="Identifier"?(this.assertDeclarableName(i,r),this.assertNotTupleAssignment(i,a,r),n.push(new on([new Lt(i,a)],On.LET))):n.push(new gt(new xr(s===":="?"=":s,i,a))),this.match(b.COMMA)){this.advance(),this.skipNewlines();continue}break}else{if(n.length>0)n.push(new gt(i));else return new gt(i);break}}else if(this.match(b.COMMA)){n.push(new gt(i)),this.advance(),this.skipNewlines();continue}else{if(n.length>0)n.push(new gt(i));else return new gt(i);break}}return n.length>1?n:n.length===1?n[0]:null}parseIfStatement(){this.expect(b.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock(),r=null;return this.skipNewlines(),this.match(b.KEYWORD,"else")&&(this.advance(),this.skipNewlines(),this.match(b.KEYWORD,"if")?r=this.parseIfStatement():r=this.parseBlock()),new us(e,n,r)}parseForStatement(){this.expect(b.KEYWORD,"for");let e=null,n=!1;if(this.match(b.LBRACKET)){this.advance();let r=[];for(;!this.match(b.RBRACKET);)this.skipNewlines(),r.push(new ge(this.expect(b.IDENTIFIER).value)),this.match(b.COMMA)&&this.advance();this.expect(b.RBRACKET),e=new eo(r),n=!0}else{let r=this.expectName().value;e=new ge(r)}if(this.match(b.KEYWORD,"in")){this.advance();let r=this.parseExpression();this.skipNewlines();let i=this.parseBlock(),s=new on([new Lt(e,r)],On.CONST),a=new Ja(s,null,null,i);return a.isForIn=!0,a}else{if(n)throw new Error(`Range-based for loops don\'t support destructuring at ${this.peek().line}:${this.peek().column}`);this.expect(b.OPERATOR,"=");let r=this.parseExpression();this.expect(b.KEYWORD,"to");let i=this.parseExpression(),s=null;this.match(b.KEYWORD,"by")&&(this.advance(),s=this.parseExpression()),this.skipNewlines();let a=this.parseBlock(),o=new ge(`__for_up${this.forLoopCount++}`),l=new on([new Lt(e,r),new Lt(o,new wn("<=",e,i))],On.LET),c=new Fn(o,new wn("<=",e,i),new wn(">=",e,i)),u;return s?u=new Fn(o,new xr("+=",e,s),new xr("-=",e,s)):u=new Fn(o,new Qa("++",e),new Qa("--",e)),new Ja(l,c,u,a)}}parseWhileStatement(){this.expect(b.KEYWORD,"while");let e=this.parseExpression();this.skipNewlines();let n=this.parseBlock();return new Dc(e,n)}parseBlock(){if(!this.match(b.INDENT)){this.rejectDanglingWrappedLine();let r=this.parseStatement();return new ln(r?[r]:[])}let e=this.peek().indent;this.advance();let n=[];for(;!this.match(b.EOF);){if(this.skipNewlines(),this.match(b.DEDENT)){if(this.peek().indent<e)break;this.advance();continue}if(this.match(b.EOF))break;let r=this.parseStatement();r&&n.push(r)}return this.match(b.DEDENT)&&this.peek().indent<e&&this.advance(),new ln(n)}isTupleDestructuring(){if(!this.match(b.LBRACKET))return!1;let e=1;for(;;){for(;this.peek(e).type===b.NEWLINE;)e++;if(this.peek(e).type!==b.IDENTIFIER)return!1;for(e++,this.peek(e).type===b.IDENTIFIER&&e++;this.peek(e).type===b.NEWLINE;)e++;if(this.peek(e).type===b.RBRACKET){e++;break}else if(this.peek(e).type===b.COMMA){e++;continue}else return!1}for(;this.peek(e).type===b.NEWLINE;)e++;return this.peek(e).type===b.OPERATOR&&(this.peek(e).value==="="||this.peek(e).value===":=")}parseTupleDestructuring(){let e=this.expect(b.LBRACKET),n=[],r=new Set;for(;!this.match(b.RBRACKET);){this.skipNewlines();let a=this.expect(b.IDENTIFIER);if(this.match(b.IDENTIFIER))throw new Error(`Mismatched input "${this.peek().value}" expecting set "]" at ${this.startOf(this.peek())}`);let o=a.value;if(o!=="_"){if(r.has(o))throw new Error(`"${o}" is already defined at ${this.startOf(e)}`);r.add(o)}o=this.variableName(o),n.push(new ge(o)),this.match(b.COMMA)&&this.advance()}if(this.expect(b.RBRACKET),this.skipNewlines(),this.match(b.OPERATOR,":="))throw new Error(`Mismatched input ":=" expecting set "=" at ${this.startOf(this.peek())}`);this.expect(b.OPERATOR,"="),this.skipNewlines(!0);let i=this.parseExpression();this.assertNotTupleLiteral(i);let s=this.tupleArityOf(i);if(s!==void 0&&s!==n.length)throw new Error(`Syntax error: The quantities of tuple elements on each side of the assignment operator do not match. The right side has ${s} but the left side has ${n.length}. at ${this.startOf(e)}`);return new on([new Lt(new eo(n),i)],On.CONST)}parseExpression(){return this.parseTernary()}parseTernary(){let e=this.parseLogicalOr();if(this.match(b.OPERATOR,"?")){let n=this.advance();this.skipNewlines(!0);let r=this.parseExpression();this.expect(b.COLON),this.skipNewlines(!0);let i=this.parseExpression(),s=[r,i].find(a=>a.type==="ArrayExpression");if(s)throw new Error(`Ternary operations cannot return tuples. Convert the expression into an \\`if\\` or \\`switch\\` conditional structure to return a tuple. at ${this.startOf(this.tupleLiteralStart.get(s)??n)}`);return new Fn(e,r,i)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match(b.KEYWORD,"or")||this.peekOperatorEx(["||"]);){this.advance(),this.skipNewlines(!0);let n=this.parseLogicalAnd();e=new wn("||",e,n)}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match(b.KEYWORD,"and")||this.peekOperatorEx(["&&"]);){this.advance(),this.skipNewlines(!0);let n=this.parseEquality();e=new wn("&&",e,n)}return e}parseEquality(){let e=this.parseComparison();for(;this.peekOperatorEx(["==","!="]);){let n=this.advance().value;this.skipNewlines(!0);let r=this.parseComparison();e=new wn(n,e,r)}return e}parseComparison(){let e=this.parseAdditive();for(;this.peekOperatorEx(["<",">","<=",">="]);){let n=this.advance().value;this.skipNewlines(!0);let r=this.parseAdditive();e=new wn(n,e,r)}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.peekOperatorEx(["+","-"]);){let n=this.advance().value;this.skipNewlines(!0);let r=this.parseMultiplicative();e=new wn(n,e,r)}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.peekOperatorEx(["*","/","%"]);){let n=this.advance().value;this.skipNewlines(!0);let r=this.parseUnary();e=new wn(n,e,r)}return e}parseUnary(){if(this.match(b.OPERATOR)){let e=this.peek().value;if(["+","-","!"].includes(e)){let n=this.advance();this.skipNewlines();let r=new hs(e,this.parseUnary());return r._pos=this.startOf(n),r}}return this.match(b.KEYWORD,"not")?(this.advance(),this.skipNewlines(),new hs("!",this.parseUnary())):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;)if(this.match(b.OPERATOR,"<")){let n=this.pos;this.advance();let r=1,i=!0,s="",a="",o=new Set(["float","int","string","bool","color","line","label","box","linefill","table"]);for(;r>0&&!this.match(b.EOF);)if(this.match(b.OPERATOR,"<"))r++,this.advance();else if(this.match(b.OPERATOR,">"))r--,this.advance();else if(this.match(b.IDENTIFIER)||this.match(b.COMMA)||this.match(b.DOT))r===1&&this.match(b.IDENTIFIER)&&s===""&&(s=this.peek().value),r===1&&(a+=this.peek().value),this.advance();else{i=!1,this.pos=n;break}if(i&&e.type==="MemberExpression"&&e.property.name==="new"&&(e.object.name==="array"||e.object.name==="matrix")&&o.has(s)&&(e.property=new ge("new_"+s)),i&&this.match(b.LPAREN)){let l=e.type==="MemberExpression"&&e.property.name==="new"&&e.object.name==="map";e=this.parseCallExpression(e),l&&a.split(",")[1]==="string"&&e.arguments.length===0&&e.arguments.push(new Tt("string"));continue}else{if(i)continue;break}}else if(this.match(b.LPAREN)){if(this.startsNewLine())break;e=this.parseCallExpression(e)}else if(this.match(b.DOT)){this.advance(),this.skipNewlines();let n=this.peek();if(n.type!==b.IDENTIFIER&&n.type!==b.KEYWORD)throw new Error(`Expected property name but got ${n.type} at ${n.line}:${n.column}`);this.advance(),e=new ks(e,new ge(n.value),!1)}else if(this.match(b.LBRACKET)){if(this.startsNewLine())break;this.advance(),this.skipNewlines();let n=this.parseExpression();this.expect(b.RBRACKET),e=new ks(e,n,!0)}else break;return e}parseCallExpression(e){let n=this.tokens[this.pos-1];this.expect(b.LPAREN);let r=[],i=[],s=this.dottedName(e),a=s!==null&&(s==="input"||/^(request|input)\\./.test(s)),o=(c,u,h)=>{if(!(c.type!=="ArrayExpression"||a))throw h!==void 0?new Error(`The "${h}" parameter of the "${s}()" function cannot accept a tuple as an argument. Pass a single argument to this parameter. at ${this.startOf(n)}`):new Error(`Cannot call "${s??"function"}" with a tuple argument. Only the expression parameter of request.*() functions and the options parameter of input.*() functions accept tuples. at ${this.startOf(u)}`)},l=s!==null?this.functionParamNames.get(s):void 0;for(;!this.match(b.RPAREN)&&(this.skipNewlines(),!this.match(b.RPAREN));){let c=this.peek();if((this.peek().type===b.IDENTIFIER||this.peek().type===b.KEYWORD)&&this.peek(1).type===b.OPERATOR&&this.peek(1).value==="="){let u=this.advance(),h=u.value;this.advance(),this.skipNewlines();let p=this.peek(),d=this.parseExpression();o(d,p,l?h:void 0);let f=new ge(h);f._pos=this.startOf(u),i.push(new Oi(f,d))}else{let u=this.parseExpression();o(u,c,l?.[r.length]),r.push(u)}this.match(b.COMMA)&&this.advance(),this.skipNewlines()}return this.expect(b.RPAREN),i.length>0&&r.push(new As(i)),new Rc(e,r)}parsePrimary(){let e=this.peek();if(this.match(b.NUMBER)){let n=this.advance(),r=new Tt(n.value,n.raw);return typeof n.raw=="string"&&(r._pos=`${n.line}:${n.column-n.raw.length}`),r}if(this.match(b.STRING)){let n=this.advance(),r=new Tt(n.value);return n.startColumn!==void 0&&(r._pos=`${n.line}:${n.startColumn}`),r}if(this.match(b.BOOLEAN)){let n=this.advance(),r=new Tt(n.value);return r._pos=this.startOf(n),r}if(this.match(b.IDENTIFIER)){let n=this.advance(),r=n.value;(this.functionNames.has(r)&&this.peek().type!==b.LPAREN&&!this.isCurrentFunctionParam(r)&&!(this.peek().type===b.DOT&&ua.has(r))&&!(this.peek().type===b.DOT&&this.typeNames.has(r))||this.typeVariableNames.has(r)&&!this.isCurrentFunctionParam(r)&&!this.isTypeMemberAccess())&&(r=r+"_var");let i=new ge(r);return i._pos=this.startOf(n),i}if(this.match(b.LBRACKET))return this.parseArrayLiteral();if(this.match(b.LPAREN)){this.advance(),this.skipNewlines();let n=this.parseExpression();return this.skipNewlines(),this.expect(b.RPAREN),n}if(this.match(b.KEYWORD,"if"))return this.parseIfExpression();if(this.match(b.KEYWORD,"switch"))return this.parseSwitchExpression();if(this.match(b.KEYWORD,"for"))return this.parseForExpression();if(this.match(b.KEYWORD,"while"))return this.parseWhileExpression();throw this.unexpected(e)}parseArrayLiteral(){let e=this.expect(b.LBRACKET),n=[];for(;!this.match(b.RBRACKET)&&(this.skipNewlines(),!this.match(b.RBRACKET));)n.push(this.parseExpression()),this.match(b.COMMA)&&this.advance(),this.skipNewlines();this.expect(b.RBRACKET);let r=new Lc(n);return this.tupleLiteralStart.set(r,e),r._pos=this.startOf(e),r}parseIfExpression(){this.expect(b.KEYWORD,"if");let e=this.parseExpression();this.skipNewlines(),this.expect(b.INDENT);let n=[];for(;!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){let a=this.parseStatement();a&&n.push(a)}this.advance(),this._valueOfTrailingLoop(n);let r=[];if(this.match(b.KEYWORD,"else"))if(this.advance(),this.skipNewlines(),this.match(b.KEYWORD,"if")){let a=this.parseIfExpression();if(this.needsIIFE(n,r)){let o=new Fn(e,new ln(n),a);return o.needsIIFE=!0,o.consequentStmts=n,o.alternateExpr=a,o}else return new Fn(e,this.getBlockValue(n),a)}else{for(this.expect(b.INDENT);!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){let a=this.parseStatement();a&&r.push(a)}this.advance(),this._valueOfTrailingLoop(r)}if(this.needsIIFE(n,r)){let a=new Fn(e,new ln(n),new ln(r));return a.needsIIFE=!0,a.consequentStmts=n,a.alternateStmts=r,a}let i=this.getBlockValue(n),s=r.length>0?this.getBlockValue(r):new Tt(null);return new Fn(e,i,s)}needsIIFE(e,n){if(e.length>1||n.length>1)return!0;let r=i=>i.some(s=>s.type==="IfStatement"||s.type==="ForStatement"||s.type==="WhileStatement"||s.type==="BlockStatement");return r(e)||r(n)}parseSwitchExpression(){this.expect(b.KEYWORD,"switch");let e=null;!this.match(b.NEWLINE)&&!this.match(b.INDENT)&&(e=this.parseExpression()),this.skipNewlines(),this.expect(b.INDENT);let n=[];for(;!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){let r=null;this.match(b.OPERATOR,"=>")||(r=this.parseExpression()),this.expect(b.OPERATOR,"=>"),this.skipNewlines();let i=[];if(this.match(b.INDENT)){for(this.advance();!this.match(b.DEDENT)&&!this.match(b.EOF)&&(this.skipNewlines(),!this.match(b.DEDENT));){let a=this.parseStatement();a&&i.push(a)}this.advance()}else{let a=this.parseStatement();a&&i.push(a)}this._valueOfTrailingLoop(i);let s=this.getBlockValue(i);n.push(new Bc(r,s,i)),this.skipNewlines()}return this.advance(),new Fc(e,n)}parseForExpression(){let e=this.parseForStatement();return e.isExpression=!0,e}parseWhileExpression(){let e=this.parseWhileStatement();return e.isExpression=!0,e}getBlockValue(e){if(e.length===0)return new Tt(null);let n=e[e.length-1];return n.type==="ExpressionStatement"?n.expression:n.type==="VariableDeclaration"&&n.declarations.length>0?n.declarations[0].id:new Tt(null)}};Yt(Jm,"STATEMENT_KEYWORDS",new Set(["if","else","for","while","switch"]));var ey=Jm,xd={"array.new_bool":[["size","initial_value"]],"array.new_box":[["size","initial_value"]],"array.new_color":[["size","initial_value"]],"array.new_float":[["size","initial_value"]],"array.new_int":[["size","initial_value"]],"array.new_label":[["size","initial_value"]],"array.new_line":[["size","initial_value"]],"array.new_linefill":[["size","initial_value"]],"array.new_string":[["size","initial_value"]],"array.new_table":[["size","initial_value"]],"array.new<type>":[["size","initial_value"]],bool:[["x"]],box:[["x"]],"chart.point.copy":[["id"]],"chart.point.from_index":[["index","price"]],"chart.point.from_time":[["time","price"]],"chart.point.new":[["time","index","price"]],"chart.point.now":[["price"]],color:[["x"]],"color.b":[["color"]],"color.from_gradient":[["value","bottom_value","top_value","bottom_color","top_color"]],"color.g":[["color"]],"color.new":[["color","transp"]],"color.r":[["color"]],"color.rgb":[["red","green","blue","transp"]],"color.t":[["color"]],fixnan:[["source"]],float:[["x"]],"footprint.buy_volume":[["id"]],"footprint.delta":[["id"]],"footprint.get_row_by_price":[["id","price"]],"footprint.poc":[["id"]],"footprint.rows":[["id"]],"footprint.sell_volume":[["id"]],"footprint.total_volume":[["id"]],"footprint.vah":[["id"]],"footprint.val":[["id"]],int:[["x"]],label:[["x"]],line:[["x"]],linefill:[["x"]],"linefill.new":[["line1","line2","color"]],"math.abs":[["number"]],"math.acos":[["angle"]],"math.asin":[["angle"]],"math.atan":[["angle"]],"math.ceil":[["number"]],"math.cos":[["angle"]],"math.exp":[["number"]],"math.floor":[["number"]],"math.log":[["number"]],"math.log10":[["number"]],"math.pow":[["base","exponent"]],"math.random":[["min","max","seed"]],"math.round":[["number"],["number","precision"]],"math.round_to_mintick":[["number"]],"math.sign":[["number"]],"math.sin":[["angle"]],"math.sqrt":[["number"]],"math.sum":[["source","length"]],"math.tan":[["angle"]],"math.todegrees":[["radians"]],"math.toradians":[["degrees"]],"matrix.new<type>":[["rows","columns","initial_value"]],max_bars_back:[["var","num"]],na:[["x"]],nz:[["source","replacement"]],"polyline.new":[["points","curved","closed","xloc","line_color","fill_color","line_style","line_width","force_overlay"]],"request.currency_rate":[["from","to","ignore_invalid_currency"]],"request.dividends":[["ticker","field","gaps","lookahead","ignore_invalid_symbol","currency"]],"request.earnings":[["ticker","field","gaps","lookahead","ignore_invalid_symbol","currency"]],"request.economic":[["country_code","field","gaps","ignore_invalid_symbol"]],"request.financial":[["symbol","financial_id","period","gaps","ignore_invalid_symbol","currency"]],"request.quandl":[["ticker","gaps","index","ignore_invalid_symbol"]],"request.security":[["symbol","timeframe","expression","gaps","lookahead","ignore_invalid_symbol","currency","calc_bars_count"]],"request.security_lower_tf":[["symbol","timeframe","expression","ignore_invalid_symbol","currency","ignore_invalid_timeframe","calc_bars_count"]],"request.seed":[["source","symbol","expression","ignore_invalid_symbol","calc_bars_count"]],"request.splits":[["ticker","field","gaps","lookahead","ignore_invalid_symbol"]],"runtime.error":[["message"]],"str.contains":[["source","str"]],"str.endswith":[["source","str"]],"str.format_time":[["time","format","timezone"]],"str.length":[["string"]],"str.lower":[["source"]],"str.match":[["source","regex"]],"str.pos":[["source","str"]],"str.repeat":[["source","repeat","separator"]],"str.replace":[["source","target","replacement","occurrence"]],"str.replace_all":[["source","target","replacement"]],"str.split":[["string","separator"]],"str.startswith":[["source","str"]],"str.substring":[["source","begin_pos","end_pos"]],"str.tonumber":[["string"]],"str.tostring":[["value"],["value","format"]],"str.trim":[["source"]],"str.upper":[["source"]],"strategy.closedtrades.commission":[["trade_num"]],"strategy.closedtrades.entry_bar_index":[["trade_num"]],"strategy.closedtrades.entry_comment":[["trade_num"]],"strategy.closedtrades.entry_id":[["trade_num"]],"strategy.closedtrades.entry_price":[["trade_num"]],"strategy.closedtrades.entry_time":[["trade_num"]],"strategy.closedtrades.exit_bar_index":[["trade_num"]],"strategy.closedtrades.exit_comment":[["trade_num"]],"strategy.closedtrades.exit_id":[["trade_num"]],"strategy.closedtrades.exit_price":[["trade_num"]],"strategy.closedtrades.exit_time":[["trade_num"]],"strategy.closedtrades.max_drawdown":[["trade_num"]],"strategy.closedtrades.max_drawdown_percent":[["trade_num"]],"strategy.closedtrades.max_runup":[["trade_num"]],"strategy.closedtrades.max_runup_percent":[["trade_num"]],"strategy.closedtrades.profit":[["trade_num"]],"strategy.closedtrades.profit_percent":[["trade_num"]],"strategy.closedtrades.size":[["trade_num"]],"strategy.convert_to_account":[["value"]],"strategy.convert_to_symbol":[["value"]],"strategy.default_entry_qty":[["fill_price"]],"strategy.opentrades.commission":[["trade_num"]],"strategy.opentrades.entry_bar_index":[["trade_num"]],"strategy.opentrades.entry_comment":[["trade_num"]],"strategy.opentrades.entry_id":[["trade_num"]],"strategy.opentrades.entry_price":[["trade_num"]],"strategy.opentrades.entry_time":[["trade_num"]],"strategy.opentrades.max_drawdown":[["trade_num"]],"strategy.opentrades.max_drawdown_percent":[["trade_num"]],"strategy.opentrades.max_runup":[["trade_num"]],"strategy.opentrades.max_runup_percent":[["trade_num"]],"strategy.opentrades.profit":[["trade_num"]],"strategy.opentrades.profit_percent":[["trade_num"]],"strategy.opentrades.size":[["trade_num"]],"strategy.risk.allow_entry_in":[["value"]],"strategy.risk.max_cons_loss_days":[["count","alert_message"]],"strategy.risk.max_drawdown":[["value","type","alert_message"]],"strategy.risk.max_intraday_filled_orders":[["count","alert_message"]],"strategy.risk.max_intraday_loss":[["value","type","alert_message"]],"strategy.risk.max_position_size":[["contracts"]],string:[["x"]],"syminfo.prefix":[["symbol"]],"syminfo.ticker":[["symbol"]],"ta.alma":[["series","length","offset","sigma","floor"]],"ta.atr":[["length"]],"ta.barssince":[["condition"]],"ta.bb":[["series","length","mult"]],"ta.bbw":[["series","length","mult"]],"ta.cci":[["source","length"]],"ta.change":[["source","length"]],"ta.cmo":[["series","length"]],"ta.cog":[["source","length"]],"ta.correlation":[["source1","source2","length"]],"ta.cross":[["source1","source2"]],"ta.crossover":[["source1","source2"]],"ta.crossunder":[["source1","source2"]],"ta.cum":[["source"]],"ta.dev":[["source","length"]],"ta.dmi":[["diLength","adxSmoothing"]],"ta.ema":[["source","length"]],"ta.falling":[["source","length"]],"ta.highest":[["source","length"]],"ta.highestbars":[["source","length"]],"ta.hma":[["source","length"]],"ta.kc":[["series","length","mult","useTrueRange"]],"ta.kcw":[["series","length","mult","useTrueRange"]],"ta.linreg":[["source","length","offset"]],"ta.lowest":[["source","length"]],"ta.lowestbars":[["source","length"]],"ta.macd":[["source","fastlen","slowlen","siglen"]],"ta.max":[["source"]],"ta.median":[["source","length"]],"ta.mfi":[["series","length"]],"ta.min":[["source"]],"ta.mode":[["source","length"]],"ta.mom":[["source","length"]],"ta.percentile_linear_interpolation":[["source","length","percentage"]],"ta.percentile_nearest_rank":[["source","length","percentage"]],"ta.percentrank":[["source","length"]],"ta.pivot_point_levels":[["type","anchor","developing"]],"ta.pivothigh":[["leftbars","rightbars"],["source","leftbars","rightbars"]],"ta.pivotlow":[["leftbars","rightbars"],["source","leftbars","rightbars"]],"ta.range":[["source","length"]],"ta.rci":[["source","length"]],"ta.rising":[["source","length"]],"ta.rma":[["source","length"]],"ta.roc":[["source","length"]],"ta.rsi":[["source","length"]],"ta.sar":[["start","inc","max"]],"ta.sma":[["source","length"]],"ta.stdev":[["source","length","biased"]],"ta.stoch":[["source","high","low","length"]],"ta.supertrend":[["factor","atrPeriod"]],"ta.swma":[["source"]],"ta.tr":[["handle_na"]],"ta.tsi":[["source","short_length","long_length"]],"ta.valuewhen":[["condition","source","occurrence"]],"ta.variance":[["source","length","biased"]],"ta.vwap":[["source","anchor"],["source","anchor","stdev_mult"]],"ta.vwma":[["source","length"]],"ta.wma":[["source","length"]],"ta.wpr":[["length"]],table:[["x"]],"ticker.heikinashi":[["symbol"]],"ticker.inherit":[["from_tickerid","symbol"]],"ticker.kagi":[["symbol","reversal"],["symbol","param","style"]],"ticker.linebreak":[["symbol","number_of_lines"]],"ticker.modify":[["tickerid","session","adjustment","backadjustment","settlement_as_close"]],"ticker.new":[["prefix","ticker","session","adjustment","backadjustment","settlement_as_close"]],"ticker.pointfigure":[["symbol","source","style","param","reversal"]],"ticker.renko":[["symbol","style","param","request_wicks","source"]],"ticker.standard":[["symbol"]],"timeframe.change":[["timeframe"]],"timeframe.from_seconds":[["seconds"]],"timeframe.in_seconds":[["timeframe"]],"volume_row.buy_volume":[["id"]],"volume_row.delta":[["id"]],"volume_row.down_price":[["id"]],"volume_row.has_buy_imbalance":[["id"]],"volume_row.has_sell_imbalance":[["id"]],"volume_row.sell_volume":[["id"]],"volume_row.total_volume":[["id"]],"volume_row.up_price":[["id"]]},SI=Object.defineProperty,EI=(t,e,n)=>e in t?SI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,At=(t,e,n)=>EI(t,typeof e!="symbol"?e+"":e,n),vd=new Set(yo),ra=t=>typeof t=="string"&&/(^|\\s)string$/.test(t),ia=t=>t?.type==="Identifier"&&t.name==="na",Vc=class{constructor(e={}){At(this,"indent"),At(this,"indentStr"),At(this,"output"),At(this,"sourceCode"),At(this,"sourceLines"),At(this,"lastCommentedLine"),At(this,"includeSourceComments"),At(this,"paramRenameCounter"),At(this,"functionParams"),At(this,"methodParams"),At(this,"userFunctionCollisions"),At(this,"userFunctionRenames"),At(this,"renamedTypeNames"),At(this,"methodNameCounts",new Map),At(this,"stringVarScopes",[new Map]),this.indent=0,this.indentStr=e.indentStr||" ",this.output=[],this.sourceCode=e.sourceCode||null,this.sourceLines=this.sourceCode?this.sourceCode.split(`\n`):[],this.lastCommentedLine=-1,this.includeSourceComments=e.includeSourceComments||!1,this.paramRenameCounter=0,this.functionParams=new Map,this.methodParams=new Map,this.userFunctionCollisions=new Set,this.userFunctionRenames=new Map,this.renamedTypeNames=new Set}renameDiscardTargets(e){let n=new Set;for(let r of e)!r||r.type!=="Identifier"||(r.name==="_"?r.name=this.freshDiscardName():n.has(r.name)&&(r.name=`${r.name}${this.paramRenameCounter++}`),n.add(r.name))}freshDiscardName(){return`_$${this.paramRenameCounter++}`}generate(e){if(this.output=[],this.indent=0,this.lastCommentedLine=-1,this.functionParams=new Map,this.methodParams=new Map,this.userFunctionCollisions=new Set,this.userFunctionRenames=new Map,e.type==="Program")this.preProcessAST(e),this.generateProgram(e);else throw new Error(`Expected Program node, got ${e.type}`);return this.output.join("")}preProcessAST(e){this.renameConflictingVariables(e),this.renameFunctionsSharingTypeNames(e),this.collectFunctionParams(e)}renameFunctionsSharingTypeNames(e){let n=new Set;for(let s of e.body)s.type==="TypeDefinition"&&typeof s.name=="string"&&n.add(s.name);if(n.size===0)return;let r=new Map;for(let s of e.body){let a=s.type==="FunctionDeclaration"&&!s.id?.isMethod?s.id?.name:void 0;a&&n.has(a)&&!r.has(a)&&r.set(a,`${a}_$${this.paramRenameCounter++}`)}if(r.size===0)return;let i=s=>{if(!(!s||typeof s!="object")){s.type==="FunctionDeclaration"&&!s.id?.isMethod&&r.has(s.id?.name)&&(s.id.name=r.get(s.id.name)),s.type==="CallExpression"&&s.callee?.type==="Identifier"&&r.has(s.callee.name)&&(s.callee.name=r.get(s.callee.name));for(let a of Object.keys(s)){if(a==="type")continue;let o=s[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&o.type&&i(o)}}};i(e)}renameConflictingVariables(e){let n=new Map;this.renamedTypeNames=new Set,this.collectConflictingVarNames(e,n),n.size>0&&this.renameVariableRefsInAST(e,n)}renameTypeString(e,n){return typeof e!="string"||this.renamedTypeNames.size===0?e:e.replace(/[A-Za-z_]\\w*/g,r=>this.renamedTypeNames.has(r)&&n.has(r)?n.get(r):r)}isReservedName(e){return!!e&&(ua.has(e)||Qs.has(e))}collectConflictingVarNames(e,n){if(!(!e||typeof e!="object")){if(e.type==="VariableDeclaration"){for(let r of e.declarations)if(r.id?.type==="Identifier"&&this.isReservedName(r.id.name)&&!n.has(r.id.name)&&n.set(r.id.name,`${r.id.name}_$${this.paramRenameCounter++}`),r.id?.type==="ArrayPattern")for(let i of r.id.elements)i?.type==="Identifier"&&this.isReservedName(i.name)&&!n.has(i.name)&&n.set(i.name,`${i.name}_$${this.paramRenameCounter++}`)}(e.type==="AssignmentExpression"||e.type==="ReassignmentExpression")&&e.left?.type==="Identifier"&&this.isReservedName(e.left.name)&&!n.has(e.left.name)&&n.set(e.left.name,`${e.left.name}_$${this.paramRenameCounter++}`),e.type==="FunctionDeclaration"&&e.id?.type==="Identifier"&&!e.id.isMethod&&this.isReservedName(e.id.name)&&(n.has(e.id.name)||n.set(e.id.name,`${e.id.name}_$${this.paramRenameCounter++}`),this.userFunctionRenames.set(e.id.name,n.get(e.id.name)),ua.has(e.id.name)&&this.userFunctionCollisions.add(e.id.name)),e.type==="TypeDefinition"&&typeof e.name=="string"&&Qs.has(e.name)&&(n.has(e.name)||n.set(e.name,`${e.name}_$${this.paramRenameCounter++}`),this.renamedTypeNames.add(e.name));for(let r of Object.keys(e)){if(r==="type")continue;let i=e[r];if(Array.isArray(i))for(let s of i)s&&typeof s=="object"&&this.collectConflictingVarNames(s,n);else i&&typeof i=="object"&&i.type&&this.collectConflictingVarNames(i,n)}}}renameVariableRefsInAST(e,n){if(!(!e||typeof e!="object")){if(e.type==="FunctionDeclaration"){e.id?.type==="Identifier"&&n.has(e.id.name)&&(e.id.name=n.get(e.id.name)),e.id&&(e.id.returnType=this.renameTypeString(e.id.returnType,n)),e.returnType=this.renameTypeString(e.returnType,n);let r=n;for(let i of e.params??[]){let s=i.type==="AssignmentPattern"?i.left:i;s&&(s.varType=this.renameTypeString(s.varType,n),s.type==="Identifier"&&r.has(s.name)&&(r===n&&(r=new Map(n)),r.delete(s.name)))}for(let i of e.params??[])i.type==="AssignmentPattern"&&i.right&&this.renameVariableRefsInAST(i.right,r);r.size>0&&this.renameVariableRefsInAST(e.body,r);return}if(e.type==="TypeDefinition"){typeof e.name=="string"&&n.has(e.name)&&(e.name=n.get(e.name));for(let r of e.fields??[])r.type=this.renameTypeString(r.type,n),r.defaultValue&&this.renameVariableRefsInAST(r.defaultValue,n);return}if(e.type==="VariableDeclarator"&&(e.varType=this.renameTypeString(e.varType,n)),e.type==="Identifier"&&(e.varType=this.renameTypeString(e.varType,n)),e.type==="CallExpression"){if(e.callee?.type==="Identifier"&&n.has(e.callee.name)?(Qs.has(e.callee.name)||this.userFunctionCollisions.has(e.callee.name))&&(e.callee.name=n.get(e.callee.name)):e.callee?.type==="Identifier"&&this.userFunctionRenames.has(e.callee.name)?e.callee.name=this.userFunctionRenames.get(e.callee.name):this.renameVariableRefsInAST(e.callee,n),e.arguments)for(let r of e.arguments)this.renameVariableRefsInAST(r,n);return}if(e.type==="MemberExpression"){if(!e.computed&&e.object?.type==="Identifier"&&n.has(e.object.name)&&ua.has(e.object.name))return;if(!e.computed&&e.property?.type==="Identifier"&&n.has(e.property.name)){this.renameVariableRefsInAST(e.object,n);return}this.renameVariableRefsInAST(e.object,n),e.computed&&this.renameVariableRefsInAST(e.property,n);return}if(e.type==="Property"){this.renameVariableRefsInAST(e.value,n);return}if(e.type==="Identifier"&&n.has(e.name)){e.name=n.get(e.name);return}for(let r of Object.keys(e)){if(r==="type")continue;let i=e[r];if(Array.isArray(i))for(let s of i)s&&typeof s=="object"&&this.renameVariableRefsInAST(s,n);else i&&typeof i=="object"&&i.type&&this.renameVariableRefsInAST(i,n)}}}collectFunctionParams(e){if(!(!e||typeof e!="object")){if(e.type==="FunctionDeclaration"&&e.id?.name){let n={names:[],defaults:[]};for(let r of e.params)if(r.type==="Identifier")n.names.push(r.name),n.defaults.push(null);else if(r.type==="AssignmentPattern"&&r.left?.name){n.names.push(r.left.name);let i=ra(r.left.varType)&&ia(r.right);n.defaults.push(i?{type:"Literal",value:"",raw:\'""\'}:r.right)}if(this.functionParams.set(e.id.name,n),e.id.isMethod){let r=this.methodParams.get(e.id.name)??[];r.push({names:n.names.slice(1),defaults:n.defaults.slice(1)}),this.methodParams.set(e.id.name,r)}}if(Array.isArray(e.body))for(let n of e.body)this.collectFunctionParams(n);else e.body&&typeof e.body=="object"&&this.collectFunctionParams(e.body)}}writeSourceComment(e,n=null){if(!this.sourceLines.length)return;let r=n||e,i=[];for(let s=e-1;s<r&&s<this.sourceLines.length;s++)if(s>this.lastCommentedLine){let a=this.sourceLines[s].trim();a&&!a.startsWith("//@")&&!a.startsWith("//")&&i.push(this.sourceLines[s])}if(i.length>0){for(let s of i)this.write(this.indentStr.repeat(this.indent)),this.write("/// "),this.write(s.trimEnd()),this.write(`\n`);this.lastCommentedLine=Math.max(this.lastCommentedLine,r-1)}}write(e){this.output.push(e)}writeLine(e=""){e?this.output.push(this.indentStr.repeat(this.indent)+e+`\n`):this.output.push(`\n`)}increaseIndent(){this.indent++}decreaseIndent(){this.indent--}generateProgram(e){for(let n=0;n<e.body.length;n++)if(this.generateStatement(e.body[n]),n<e.body.length-1){let r=e.body[n],i=e.body[n+1];(r.type==="FunctionDeclaration"||r.type==="TypeDefinition")&&(i.type==="FunctionDeclaration"||i.type==="TypeDefinition")&&this.writeLine()}}generateStatement(e){switch(this.includeSourceComments&&e._line&&this.sourceLines.length>0&&this.writeSourceComment(e._line),e.type){case"FunctionDeclaration":return this.generateFunctionDeclaration(e);case"VariableDeclaration":return this.generateVariableDeclaration(e);case"ExpressionStatement":return this.generateExpressionStatement(e);case"IfStatement":return this.generateIfStatement(e);case"ForStatement":return this.generateForStatement(e);case"WhileStatement":return this.generateWhileStatement(e);case"ReturnStatement":return this.generateReturnStatement(e);case"BlockStatement":if(e._sequence){for(let n of e.body)this.generateStatement(n);return}return this.generateBlockStatement(e);case"TypeDefinition":return this.generateTypeDefinition(e);case"ImportDeclaration":return;default:throw new Error(`Unknown statement type: ${e.type}`)}}generateTypeDefinition(e){if(this.write(this.indentStr.repeat(this.indent)),this.write(`const ${e.name} = Type({`),e.fields.length>0){this.write(" ");for(let n=0;n<e.fields.length;n++){let r=e.fields[n];r.defaultValue?(this.write(`${r.name}: [\'${r.type}\', `),this.generateExpression(r.defaultValue),this.write("]")):this.write(`${r.name}: \'${r.type}\'`),n<e.fields.length-1&&this.write(", ")}this.write(" ")}this.write(`});\n`)}renameIdentifiersInAST(e,n){if(!(!e||typeof e!="object")){if(e.type==="Identifier"&&n.has(e.name)){e.name=n.get(e.name);return}if(e.type!=="FunctionDeclaration")for(let r of Object.keys(e)){if(r==="type")continue;let i=e[r];if(Array.isArray(i))for(let s of i)s&&typeof s=="object"&&this.renameIdentifiersInAST(s,n);else i&&typeof i=="object"&&i.type&&this.renameIdentifiersInAST(i,n)}}}renameParamRefsInBody(e,n){if(!(!e||typeof e!="object")&&e.type!=="FunctionDeclaration"){if(e.type==="CallExpression"){if(e.callee?.type==="Identifier"&&n.has(e.callee.name)||this.renameParamRefsInBody(e.callee,n),e.arguments)for(let r of e.arguments)this.renameParamRefsInBody(r,n);return}if(e.type==="MemberExpression"){if(!e.computed&&e.object?.type==="Identifier"&&n.has(e.object.name))return;this.renameParamRefsInBody(e.object,n),e.computed&&this.renameParamRefsInBody(e.property,n);return}if(e.type==="Property"){this.renameParamRefsInBody(e.value,n);return}if(e.type==="Identifier"&&n.has(e.name)){e.name=n.get(e.name);return}for(let r of Object.keys(e)){if(r==="type")continue;let i=e[r];if(Array.isArray(i))for(let s of i)s&&typeof s=="object"&&this.renameParamRefsInBody(s,n);else i&&typeof i=="object"&&i.type&&this.renameParamRefsInBody(i,n)}}}generateFunctionDeclaration(e){this.write(this.indentStr.repeat(this.indent));let n=e.id.isMethod,r=new Map;for(let h of e.params){let p=h.type==="AssignmentPattern"?h.left.name:h.name;if(p&&vd.has(p)){let d=`${p}_$${this.paramRenameCounter++}`;r.set(p,d)}}let i=h=>h.type==="Identifier"&&h.name==="this"||h.type==="AssignmentPattern"&&h.left?.name==="this",s=new Map;n&&e.params.length>0&&i(e.params[0])&&s.set("this","self");let a=new Map;if(e.params.forEach((h,p)=>{let d=(h.type==="AssignmentPattern"?h.left:h)?.name;!d||!Qs.has(d)||r.has(d)||n&&p===0&&d==="this"||a.set(d,`${d}_$${this.paramRenameCounter++}`)}),r.size>0||s.size>0||a.size>0){for(let h of e.params){let p=h.type==="AssignmentPattern"?h.left:h;if(p?.type==="Identifier"){let d=r.get(p.name)??s.get(p.name)??a.get(p.name);d&&(p.name=d)}h.type==="AssignmentPattern"&&h.right&&(r.size>0&&this.renameParamRefsInBody(h.right,r),s.size>0&&this.renameIdentifiersInAST(h.right,s),a.size>0&&this.renameVariableRefsInAST(h.right,a))}r.size>0&&this.renameParamRefsInBody(e.body,r),s.size>0&&this.renameIdentifiersInAST(e.body,s),a.size>0&&this.renameVariableRefsInAST(e.body,a)}let o=e.id.name;if(n){let h=(this.methodNameCounts.get(e.id.name)??0)+1;this.methodNameCounts.set(e.id.name,h),o=h===1?`$M_${e.id.name}`:`$M_${e.id.name}$${h}`}this.write("function "),this.write(o),this.write("(");let l=e.params,c=new Map;for(let h=0;h<l.length;h++){let p=l[h];if(p.type==="Identifier")this.write(p.name),c.set(p.name,ra(p.varType));else if(p.type==="AssignmentPattern"){let d=ra(p.left.varType);c.set(p.left.name,d),this.write(p.left.name),this.write(" = "),d&&ia(p.right)?this.write(\'""\'):this.generateExpression(p.right)}h<l.length-1&&this.write(", ")}this.write(") "),this.stringVarScopes.push(c);try{this.generateBlockStatement(e.body,!1)}finally{this.stringVarScopes.pop()}if(this.write(`\n`),n){this.write(this.indentStr.repeat(this.indent)),this.write(`${o}.__pineMethod__ = true;\n`);let h=e.params[0],p=h?.type==="AssignmentPattern"?h.left?.varType:h?.varType;typeof p=="string"&&p.length>0&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${o}.__pineReceiverType__ = ${JSON.stringify(p)};\n`))}let u=[];for(let h=0;h<e.params.length;h++){let p=e.params[h],d=p.type==="AssignmentPattern"?p.left?.name:p.name;if(n&&h===0&&d==="self")continue;let f=p.type==="AssignmentPattern"?p.left?.varType:p.varType;d&&f&&u.push([d,f])}if(u.length>0){this.write(this.indentStr.repeat(this.indent));let h=u.map(([p,d])=>`${JSON.stringify(p)}: ${JSON.stringify(d)}`).join(", ");this.write(`${o}.__pineParamTypes__ = {${h}};\n`)}}generateVariableDeclaration(e){let n=e.kind==="var"||e.kind==="varip"?"var":"let";for(let r=0;r<e.declarations.length;r++){let i=e.declarations[r];if(i.id?.type==="Identifier"&&i.id.name==="_"?i.id.name=this.freshDiscardName():i.id?.type==="ArrayPattern"&&this.renameDiscardTargets(i.id.elements),e.kind==="varip"&&i.id?.type==="Identifier"&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${JSON.stringify(`__pineVarip:${i.id.name}`)};\n`)),i.init&&i.init.type==="ConditionalExpression"&&i.init.needsIIFE){let l=i.id.type==="Identifier"?i.id.name:null;if(l){this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),this.write(l),this.write(`;\n`),this.generateIfStatementWithAssignment(i.init,l);continue}}this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" "),i.id.type==="Identifier"?this.write(i.id.name):i.id.type==="ArrayPattern"&&(this.write("["),this.write(i.id.elements.map(l=>l.name).join(", ")),this.write("]"));let s=i.id.type==="Identifier"&&(i.id.varType?ra(i.id.varType):i.init?.type==="Literal"&&typeof i.init.value=="string");i.id.type==="Identifier"&&this.stringVarScopes[this.stringVarScopes.length-1].set(i.id.name,s),i.init&&(this.write(" = "),s&&ia(i.init)?this.write(\'""\'):this.generateExpression(i.init)),this.write(`;\n`);let a=i.id?.varType,o=i.id?.type==="Identifier"?i.id.name:null;o&&typeof a=="string"&&/^[A-Za-z_$][\\w$]*$/.test(a)&&a[0]===a[0].toUpperCase()?(this.write(this.indentStr.repeat(this.indent)),this.write(`"__pineUdtVar:${o}=${a}";\n`)):o&&typeof a=="string"&&a.length>0&&(this.write(this.indentStr.repeat(this.indent)),this.write(`${JSON.stringify(`__pineTypedVar:${o}=${a}`)};\n`))}}generateExpressionStatement(e){if(e.expression.type==="SwitchExpression"&&e.expression.discriminant===null){this.write(this.indentStr.repeat(this.indent)),this.generateSwitchAsIfElse(e.expression),this.write(`\n`);return}this.write(this.indentStr.repeat(this.indent)),this.generateExpression(e.expression),this.write(`;\n`)}generateIfStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(") "),this.generateBlockStatement(e.consequent,!1),e.alternate?(this.write(" else "),e.alternate.type==="IfStatement"?this.generateIfStatement(e.alternate):this.generateBlockStatement(e.alternate,!1)):this.write(`\n`)}generateIfStatementWithAssignment(e,n){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequentStmts)for(let r=0;r<e.consequentStmts.length;r++){let i=e.consequentStmts[r];r===e.consequentStmts.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternateExpr)this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(e.alternateExpr),this.write(`;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");else if(e.alternateStmts&&e.alternateStmts.length>0){this.write(` else {\n`),this.indent++;for(let r=0;r<e.alternateStmts.length;r++){let i=e.alternateStmts[r];r===e.alternateStmts.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(` = false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");this.write(`\n`)}generateNestedIfWithAssignments(e,n){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequent.type==="BlockStatement"&&e.consequent.body.length>0)for(let r=0;r<e.consequent.body.length;r++){let i=e.consequent.body[r];r===e.consequent.body.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternate)if(e.alternate.type==="IfStatement"){if(this.write(" else "),this.write("if ("),this.generateExpression(e.alternate.test),this.write(`) {\n`),this.indent++,e.alternate.consequent.type==="BlockStatement"&&e.alternate.consequent.body.length>0)for(let r=0;r<e.alternate.consequent.body.length;r++){let i=e.alternate.consequent.body[r];r===e.alternate.consequent.body.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternatesWithAssignments(e.alternate.alternate,n)}else if(e.alternate.type==="BlockStatement"&&e.alternate.body.length>0){this.write(` else {\n`),this.indent++;for(let r=0;r<e.alternate.body.length;r++){let i=e.alternate.body[r];r===e.alternate.body.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(` = false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`);else this.write(`\n`)}generateNestedIfAlternatesWithAssignments(e,n){if(e)if(e.type==="IfStatement"){if(this.write(" else "),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequent.type==="BlockStatement"&&e.consequent.body.length>0)for(let r=0;r<e.consequent.body.length;r++){let i=e.consequent.body[r];r===e.consequent.body.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternatesWithAssignments(e.alternate,n)}else if(e.type==="BlockStatement"&&e.body.length>0){this.write(` else {\n`),this.indent++;for(let r=0;r<e.body.length;r++){let i=e.body[r];r===e.body.length-1?i.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(" = "),this.generateExpression(i.expression),this.write(`;\n`)):i.type==="IfStatement"?this.generateNestedIfWithAssignments(i,n):this.generateStatement(i):this.generateStatement(i)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(n),this.write(` = false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}generateForStatement(e){if(this.write(this.indentStr.repeat(this.indent)),e.isForIn){if(this.write("for ("),e.init&&e.init.type==="VariableDeclaration"){let n=e.init.declarations[0];this.write(`${e.init.kind} `),n.id.type==="Identifier"?this.write(n.id.name):n.id.type==="ArrayPattern"&&(this.renameDiscardTargets(n.id.elements),this.write("["),this.write(n.id.elements.map(r=>r.name).join(", ")),this.write("]")),this.write(" of "),this.generateExpression(n.init)}this.write(") "),this.generateBlockStatement(e.body,!1);return}this.write("for ("),e.init&&(e.init.type==="VariableDeclaration"?(this.write(`${e.init.kind} `),e.init.declarations.forEach((n,r)=>{r&&this.write(", "),this.write(n.id.name),n.init&&(this.write(" = "),this.generateExpression(n.init))})):this.generateExpression(e.init)),this.write("; "),e.test&&this.generateExpression(e.test),this.write("; "),e.update&&(e.update.type==="AssignmentExpression"?(this.generateExpression(e.update.left),this.write(` ${e.update.operator} `),this.generateExpression(e.update.right)):this.generateExpression(e.update)),this.write(") "),this.generateBlockStatement(e.body,!1)}generateWhileStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("while ("),this.generateExpression(e.test),this.write(") "),this.generateBlockStatement(e.body,!1)}generateReturnStatement(e){this.write(this.indentStr.repeat(this.indent)),this.write("return"),e.argument&&(this.write(" "),this.generateExpression(e.argument)),this.write(`;\n`)}generateBlockStatement(e,n=!0){this.write(`{\n`),n?this.increaseIndent():this.indent++;for(let r of e.body)this.generateStatement(r);n?this.decreaseIndent():this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),n&&this.write(`\n`)}generateExpression(e){switch(e.type){case"Identifier":return this.write(e.name);case"Literal":return this.generateLiteral(e);case"BinaryExpression":case"LogicalExpression":return this.generateBinaryExpression(e);case"UnaryExpression":return this.generateUnaryExpression(e);case"AssignmentExpression":return this.generateAssignmentExpression(e);case"UpdateExpression":return this.generateUpdateExpression(e);case"CallExpression":return this.generateCallExpression(e);case"MemberExpression":return this.generateMemberExpression(e);case"ConditionalExpression":return this.generateConditionalExpression(e);case"ArrayExpression":return this.generateArrayExpression(e);case"ObjectExpression":return this.generateObjectExpression(e);case"SwitchExpression":return this.generateSwitchExpression(e);case"SequenceExpression":return this.generateSequenceExpression(e);case"ForStatement":return this.generateLoopAsExpression(e,"for");case"WhileStatement":return this.generateLoopAsExpression(e,"while");default:throw new Error(`Unknown expression type: ${e.type}`)}}generateLiteral(e){if(typeof e.value=="string"){let n=e.value.replace(/\\\\/g,"\\\\\\\\").replace(/\'/g,"\\\\\'").replace(/\\n/g,"\\\\n").replace(/\\r/g,"\\\\r").replace(/\\t/g,"\\\\t");this.write(`\'${n}\'`)}else if(e.value===null)this.write("null");else{let n=String(e.value);typeof e.raw=="string"&&/[.eE]/.test(e.raw)&&!/[.eE]/.test(n)?this.write(n+".0"):this.write(n)}}generateBinaryExpression(e){let n=this.getPrecedence(e);this.getPrecedence(e.left)<n?(this.write("("),this.generateExpression(e.left),this.write(")")):this.generateExpression(e.left),this.write(" ");let r=e.operator;r==="and"?r="&&":r==="or"&&(r="||"),this.write(r),this.write(" ");let i=this.getPrecedence(e.right),s=i<n;i===n&&(r==="-"||r==="/"||r==="%")&&(s=!0),s?(this.write("("),this.generateExpression(e.right),this.write(")")):this.generateExpression(e.right)}generateUnaryExpression(e){let n=e.operator;n==="not"&&(n="!"),this.write(n),this.getPrecedence(e.argument)<15||e.argument.type==="UnaryExpression"&&(n==="-"||n==="+")&&(e.argument.operator==="-"||e.argument.operator==="+")?(this.write("("),this.generateExpression(e.argument),this.write(")")):this.generateExpression(e.argument)}generateAssignmentExpression(e){this.generateExpression(e.left),this.write(" ");let n=e.operator;n===":="&&(n="="),this.write(n),this.write(" "),n==="="&&e.left.type==="Identifier"&&ia(e.right)&&this.isStringVariable(e.left.name)?this.write(\'""\'):this.generateExpression(e.right)}isStringVariable(e){for(let n=this.stringVarScopes.length-1;n>=0;n--){let r=this.stringVarScopes[n].get(e);if(r!==void 0)return r}return!1}generateUpdateExpression(e){e.prefix?(this.write(e.operator),this.generateExpression(e.argument)):(this.generateExpression(e.argument),this.write(e.operator))}userMethodParams(e){if(e?.type!=="MemberExpression"||e.computed||e.property?.type!=="Identifier")return null;let n=e.property.name;return Ss.has(n)||e.object?.type==="Identifier"&&vd.has(e.object.name)?null:this.methodParams.get(n)??null}generateCallExpression(e){this.getPrecedence(e.callee)<19?(this.write("("),this.generateExpression(e.callee),this.write(")")):this.generateExpression(e.callee),this.write("(");let n=e.callee?.type==="Identifier"?e.callee.name:null,r=e.arguments.length>0?e.arguments[e.arguments.length-1]:null,i=r?.type==="ObjectExpression",s=n?this.functionParams.get(n):null,a=i?s||this.namedParamsFor(e.callee,e.arguments.length-1,r):null;if(i&&a){let o=e.arguments.slice(0,-1),l=new Map;for(let p of r.properties){let d=p.key?.name||p.key?.value;d&&l.set(d,p.value)}let c=[],u=-1;for(let p=0;p<a.names.length;p++)p<o.length?(c.push(o[p]),u=p):l.has(a.names[p])?(c.push(l.get(a.names[p])),u=p):c.push(a.defaults[p]);let h=c.slice(0,u+1);for(let p=0;p<h.length;p++)h[p]===null?this.write("undefined"):this.generateExpression(h[p]),p<h.length-1&&this.write(", ")}else for(let o=0;o<e.arguments.length;o++){let l=e.arguments[o];l.type==="AssignmentExpression"&&l.operator==="="?this.generateExpression(l.right):this.generateExpression(l),o<e.arguments.length-1&&this.write(", ")}this.write(")")}calleePath(e){if(e?.type==="Identifier")return e.name;if(e?.type==="MemberExpression"&&!e.computed&&e.property?.type==="Identifier"){let n=this.calleePath(e.object);return n?`${n}.${e.property.name}`:null}return null}namedParamsFor(e,n,r){let i=this.calleePath(e),s=i&&/^(array|matrix)\\.new(_\\w+)?$/.test(i)?xd[`${i.split(".")[0]}.new<type>`]:void 0,a=i?xd[i]??s:void 0;if(a){let l=a.map(c=>({names:c,defaults:c.map(()=>null)}));return this.pickOverload(l,n,r)}let o=this.userMethodParams(e);return o?this.pickOverload(o,n,r):null}pickOverload(e,n,r){let i=r.properties.map(o=>o.key?.name??o.key?.value),s=null,a=1/0;for(let o of e){let l=o.names;if(n>l.length||!i.every(u=>l.indexOf(u)>=n))continue;let c=Math.max(n-1,...i.map(u=>l.indexOf(u)))+1-n-i.length;c<a&&(s=o,a=c)}return s}generateMemberExpression(e){this.getPrecedence(e.object)<19?(this.write("("),this.generateExpression(e.object),this.write(")")):this.generateExpression(e.object),e.computed?(this.write("["),this.generateExpression(e.property),this.write("]")):(this.write("."),this.generateExpression(e.property))}generateConditionalExpression(e){if(e.needsIIFE){this.generateIIFEConditional(e);return}this.write("("),this.generateExpression(e.test),this.write(" ? "),this.generateExpression(e.consequent),this.write(" : "),this.generateExpression(e.alternate),this.write(")")}generateIIFEConditional(e){this.write(`(() => {\n`),this.indent++,this.generateIIFEIfBlock(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateIIFEIfBlock(e){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequentStmts)for(let n=0;n<e.consequentStmts.length;n++){let r=e.consequentStmts[n];n===e.consequentStmts.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternateExpr)this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(e.alternateExpr),this.write(`;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");else if(e.alternateStmts&&e.alternateStmts.length>0){this.write(` else {\n`),this.indent++;for(let n=0;n<e.alternateStmts.length;n++){let r=e.alternateStmts[n];n===e.alternateStmts.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}");this.write(`\n`)}generateNestedIfWithReturns(e){if(this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequent.type==="BlockStatement"&&e.consequent.body.length>0)for(let n=0;n<e.consequent.body.length;n++){let r=e.consequent.body[n];n===e.consequent.body.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}if(this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),e.alternate)if(e.alternate.type==="IfStatement"){if(this.write(" else "),this.write("if ("),this.generateExpression(e.alternate.test),this.write(`) {\n`),this.indent++,e.alternate.consequent.type==="BlockStatement"&&e.alternate.consequent.body.length>0)for(let n=0;n<e.alternate.consequent.body.length;n++){let r=e.alternate.consequent.body[n];n===e.alternate.consequent.body.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternates(e.alternate.alternate)}else if(e.alternate.type==="BlockStatement"&&e.alternate.body.length>0){this.write(` else {\n`),this.indent++;for(let n=0;n<e.alternate.body.length;n++){let r=e.alternate.body[n];n===e.alternate.body.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`);else this.write(`\n`)}generateNestedIfAlternates(e){if(e)if(e.type==="IfStatement"){if(this.write(" else "),this.write("if ("),this.generateExpression(e.test),this.write(`) {\n`),this.indent++,e.consequent.type==="BlockStatement"&&e.consequent.body.length>0)for(let n=0;n<e.consequent.body.length;n++){let r=e.consequent.body[n];n===e.consequent.body.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),this.generateNestedIfAlternates(e.alternate)}else if(e.type==="BlockStatement"&&e.body.length>0){this.write(` else {\n`),this.indent++;for(let n=0;n<e.body.length;n++){let r=e.body[n];n===e.body.length-1?r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):r.type==="IfStatement"?this.generateNestedIfWithReturns(r):this.generateStatement(r):this.generateStatement(r)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}else this.write(` else {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`return false;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}generateIfWithReturns(e){this.write(this.indentStr.repeat(this.indent)),this.write("if ("),this.generateExpression(e.test),this.write(") "),this.generateBlockWithReturn(e.consequent),e.alternate&&(this.write(" else "),e.alternate.type==="IfStatement"?(this.write(`{\n`),this.indent++,this.generateIfWithReturns(e.alternate),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")):this.generateBlockWithReturn(e.alternate)),this.write(`\n`)}generateBlockWithReturn(e){let n=e.type==="BlockStatement"?e.body:[e];this.write(`{\n`),this.indent++,n.forEach((r,i)=>{let s=i===n.length-1;s&&r.type==="ExpressionStatement"?(this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.expression),this.write(`;\n`)):s&&r.type==="IfStatement"?this.generateIfWithReturns(r):(this.write(this.indentStr.repeat(this.indent)),this.generateStatement(r))}),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}")}generateNestedIfAsExpression(e){if(e.type==="IfStatement"){if(this.write("("),this.generateExpression(e.test),this.write(" ? "),e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let n=e.consequent.body[e.consequent.body.length-1];n.type==="ExpressionStatement"?this.generateExpression(n.expression):n.type==="IfStatement"&&this.generateNestedIfAsExpression(n)}if(this.write(" : "),e.alternate)if(e.alternate.type==="IfStatement")this.generateNestedIfAsExpression(e.alternate);else if(e.alternate.type==="BlockStatement"&&e.alternate.body.length>0){let n=e.alternate.body[e.alternate.body.length-1];n.type==="ExpressionStatement"&&this.generateExpression(n.expression)}else this.write("false");else this.write("false");this.write(")")}}generateArrayExpression(e){this.write("[");for(let n=0;n<e.elements.length;n++)this.generateExpression(e.elements[n]),n<e.elements.length-1&&this.write(", ");this.write("]")}generateObjectExpression(e){this.write("{");for(let n=0;n<e.properties.length;n++){let r=e.properties[n];r.key.type==="Identifier"?this.write(r.key.name):this.generateExpression(r.key),this.write(": "),this.generateExpression(r.value),n<e.properties.length-1&&this.write(", ")}this.write("}")}generateSwitchExpression(e){if(e.discriminant===null){this.generateSwitchAsIfElseIIFE(e);return}this.write(`(() => {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write("switch ("),this.generateExpression(e.discriminant),this.write(`) {\n`),this.indent++;for(let n of e.cases){if(this.write(this.indentStr.repeat(this.indent)),n.test?(this.write("case "),this.generateExpression(n.test),this.write(`: {\n`)):this.write(`default: {\n`),this.indent++,n.statements&&n.statements.length>0){let r=n.statements[n.statements.length-1];if(r.type==="ExpressionStatement"||r.type==="VariableDeclaration"){for(let i=0;i<n.statements.length-1;i++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(n.statements[i]);this.write(this.indentStr.repeat(this.indent)),this.write("return "),r.type==="ExpressionStatement"?this.generateExpression(r.expression):this.generateExpression(n.consequent),this.write(`;\n`)}else if(r.type==="IfStatement"){for(let i=0;i<n.statements.length-1;i++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(n.statements[i]);this.generateIfWithReturns(r),this.write(this.indentStr.repeat(this.indent)),this.write(`return null;\n`)}else{for(let i=0;i<n.statements.length;i++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(n.statements[i]);this.write(this.indentStr.repeat(this.indent)),this.write(`return null;\n`)}}else this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(n.consequent),this.write(`;\n`);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`)}this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write(`}\n`),this.writeNaForMissingDefault(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateSwitchAsIfElseIIFE(e){this.write(`(() => {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent));for(let n=0;n<e.cases.length;n++){let r=e.cases[n];if(r.test?(n===0?this.write("if ("):this.write(" else if ("),this.generateExpression(r.test),this.write(`) {\n`)):n>0?this.write(` else {\n`):this.write(`{\n`),this.indent++,r.statements&&r.statements.length>0){let i=r.statements[r.statements.length-1];if(i.type==="ExpressionStatement"||i.type==="VariableDeclaration"){for(let s=0;s<r.statements.length-1;s++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(r.statements[s]);this.write(this.indentStr.repeat(this.indent)),this.write("return "),i.type==="ExpressionStatement"?this.generateExpression(i.expression):this.generateExpression(r.consequent),this.write(`;\n`)}else if(i.type==="IfStatement"){for(let s=0;s<r.statements.length-1;s++)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(r.statements[s]);this.generateIfWithReturns(i),this.write(this.indentStr.repeat(this.indent)),this.write(`return null;\n`)}else{for(let s of r.statements)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(s);this.write(this.indentStr.repeat(this.indent)),this.write(`return null;\n`)}}else this.write(this.indentStr.repeat(this.indent)),this.write("return "),this.generateExpression(r.consequent),this.write(`;\n`);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),n>=e.cases.length-1&&this.write(`\n`)}this.writeNaForMissingDefault(e),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}writeNaForMissingDefault(e){if(e.cases.some(i=>!i.test))return;let n=i=>{let s=i.statements?.length?i.statements[i.statements.length-1]:null;return s?s.type==="ExpressionStatement"?s.expression:null:i.consequent},r=e.cases.length>0&&e.cases.every(i=>{let s=n(i);return s?.type==="Literal"&&typeof s.value=="string"});this.write(this.indentStr.repeat(this.indent)),this.write(r?`return "";\n`:`return na;\n`)}generateSwitchAsIfElse(e){for(let n=0;n<e.cases.length;n++){let r=e.cases[n];if(r.test?(n===0?this.write("if ("):this.write(" else if ("),this.generateExpression(r.test),this.write(`) {\n`)):n>0?this.write(` else {\n`):this.write(`{\n`),this.indent++,r.statements&&r.statements.length>0)for(let i of r.statements)this.write(this.indentStr.repeat(this.indent)),this.generateStatement(i);else this.write(this.indentStr.repeat(this.indent)),this.generateExpression(r.consequent),this.write(`;\n`);this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("}"),n<e.cases.length-1||this.write(`\n`)}}generateLoopAsExpression(e,n){this.write(`(() => {\n`),this.indent++,this.write(this.indentStr.repeat(this.indent)),this.write(`let __result;\n`);let r=e.body;if(r&&r.body&&r.body.length>0){let i=r.body.length-1,s=r.body[i];s.type==="ExpressionStatement"&&(r.body[i]={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"__result"},right:s.expression},_line:s._line})}n==="for"?this.generateForStatement(e):this.generateWhileStatement(e),this.write(this.indentStr.repeat(this.indent)),this.write(`return __result;\n`),this.indent--,this.write(this.indentStr.repeat(this.indent)),this.write("})()")}generateSequenceExpression(e){this.write("(");for(let n=0;n<e.expressions.length;n++)this.generateExpression(e.expressions[n]),n<e.expressions.length-1&&this.write(", ");this.write(")")}getPrecedence(e){switch(e.type){case"Literal":case"Identifier":case"ArrayExpression":case"ObjectExpression":return 20;case"CallExpression":case"MemberExpression":return 19;case"UnaryExpression":case"UpdateExpression":return 15;case"BinaryExpression":case"LogicalExpression":switch(e.operator){case"*":case"/":case"%":return 13;case"+":case"-":return 12;case"<":case"<=":case">":case">=":return 10;case"==":case"!=":return 9;case"and":case"&&":return 5;case"or":case"||":return 4;default:return 0}case"ConditionalExpression":return 3;case"AssignmentExpression":case"AssignmentPattern":return 2;case"SequenceExpression":return 1;default:return 0}}},wd={pi:Math.PI,e:Math.E,phi:1.618033988749895,rphi:.618033988749895},ty=/^#[0-9a-f]{6}([0-9a-f]{2})?$/i,Ct=(t,e,n=!0)=>Number.isFinite(t)?{value:t,type:e,exact:n}:void 0,$n=t=>!!t&&(t.type==="int"||t.type==="float")&&typeof t.value=="number",_i=(...t)=>t.every(e=>e.type==="int")?"int":"float",ps=(...t)=>t.every(e=>e.exact);function no(t){return t.type==="int"&&typeof t.value=="number"?Math.trunc(t.value):t.value}function ir(t){if(t?.type==="Identifier")return t.name;if(t?.type==="MemberExpression"&&!t.computed&&t.property?.type==="Identifier"){let e=ir(t.object);return e===null?null:`${e}.${t.property.name}`}return null}function Nn(t,e){if(t!=null)switch(t.type){case"Literal":return kI(t);case"Identifier":return t.name==="na"?void 0:co.has(t.name)?{value:t.name,type:"source",exact:!1}:e.lookup(t.name);case"MemberExpression":return AI(t,e);case"UnaryExpression":return TI(t,e);case"BinaryExpression":case"LogicalExpression":return NI(t,e);case"ConditionalExpression":{let n=Nn(t.test,e);return n?.type!=="bool"?void 0:Nn(n.value?t.consequent:t.alternate,e)}case"CallExpression":return II(t,e);default:return}}function kI(t){let e=t.value;if(typeof e=="boolean")return{value:e,type:"bool",exact:!0};if(typeof e=="string")return ty.test(e)?{value:e,type:"color",exact:!1}:{value:e,type:"string",exact:!0};if(typeof e=="number"){let n=typeof t.raw=="string"?/[.eE]/.test(t.raw):!Number.isInteger(e);return Ct(e,n?"float":"int")}}function AI(t,e){let n=ir(t);if(n===null)return;if(e.enums.has(n))return{value:e.enums.get(n),type:"enum",exact:!1};let[r,i]=n.split(".");if(r==="math"&&i in wd)return Ct(wd[i],"float");if(r==="color"&&Li(n))return{value:n,type:"color",exact:!1};let s=o_[r];if(r!=="display"&&s&&typeof s=="object"&&i in s){let a=s[i];if(typeof a=="string")return{value:a,type:"string",exact:!1};if(typeof a=="number")return{value:a,type:Number.isInteger(a)?"int":"float",exact:!1}}return{value:n,type:"other",exact:!1}}function TI(t,e){let n=Nn(t.argument,e);if(n){if(t.operator==="!"||t.operator==="not")return n.type==="bool"?{value:!n.value,type:"bool",exact:n.exact}:void 0;if($n(n)){if(t.operator==="-")return Ct(-n.value,n.type,n.exact);if(t.operator==="+")return n}}}function NI(t,e){let n=t.operator;if(n==="&&"||n==="||"||n==="and"||n==="or"){let l=Nn(t.left,e);if(l?.type!=="bool")return;if(n==="&&"||n==="and"?!l.value:l.value)return l;let c=Nn(t.right,e);return c?.type==="bool"?{value:c.value,type:"bool",exact:l.exact&&c.exact}:void 0}let r=Nn(t.left,e),i=Nn(t.right,e);if(!r||!i)return;if(n==="+"&&r.type==="string"&&i.type==="string")return{value:String(r.value)+String(i.value),type:"string",exact:ps(r,i)};if(n==="=="||n==="==="||n==="!="||n==="!=="){if(!($n(r)&&$n(i)||r.type===i.type&&["string","bool"].includes(r.type)))return;let l=$n(r)?Math.abs(r.value-i.value)<1e-10:r.value===i.value;return{value:n.startsWith("=")?l:!l,type:"bool",exact:ps(r,i)}}if(!$n(r)||!$n(i))return;let s=r.value,a=i.value,o=ps(r,i);switch(n){case"+":return Ct(s+a,_i(r,i),o);case"-":return Ct(s-a,_i(r,i),o);case"*":return Ct(s*a,_i(r,i),o);case"/":{if(a===0)return;let l=_i(r,i),c=s/a;return Ct(l==="int"&&e.truncatingIntDivision?Math.trunc(c):c,l,o)}case"%":return a===0?void 0:Ct(s%a,_i(r,i),o);case">":return{value:s>a,type:"bool",exact:o};case"<":return{value:s<a,type:"bool",exact:o};case">=":return{value:s>=a,type:"bool",exact:o};case"<=":return{value:s<=a,type:"bool",exact:o};default:return}}var CI={abs:{arity:[1,1],type:"same",fn:Math.abs},max:{arity:[2,1/0],type:"same",fn:Math.max},min:{arity:[2,1/0],type:"same",fn:Math.min},avg:{arity:[2,1/0],type:"float",fn:(...t)=>t.reduce((e,n)=>e+n,0)/t.length},floor:{arity:[1,1],type:"int",fn:Math.floor},ceil:{arity:[1,1],type:"int",fn:Math.ceil},sqrt:{arity:[1,1],type:"float",fn:Math.sqrt},pow:{arity:[2,2],type:"float",fn:Math.pow},exp:{arity:[1,1],type:"float",fn:Math.exp},log:{arity:[1,1],type:"float",fn:Math.log},log10:{arity:[1,1],type:"float",fn:Math.log10},sign:{arity:[1,1],type:"float",fn:Math.sign},sin:{arity:[1,1],type:"float",fn:Math.sin},cos:{arity:[1,1],type:"float",fn:Math.cos},tan:{arity:[1,1],type:"float",fn:Math.tan},asin:{arity:[1,1],type:"float",fn:Math.asin},acos:{arity:[1,1],type:"float",fn:Math.acos},atan:{arity:[1,1],type:"float",fn:Math.atan},todegrees:{arity:[1,1],type:"float",fn:t=>t*180/Math.PI},toradians:{arity:[1,1],type:"float",fn:t=>t*Math.PI/180}};function II(t,e){let n=ir(t.callee);if(n===null)return;let r=t.arguments??[];if(r.some(a=>a?.type==="ObjectExpression"))return;let i=r.map(a=>Nn(a,e));if(i.some(a=>!a))return;let s=i;if(n==="int"&&s.length===1&&$n(s[0]))return Ct(Math.trunc(s[0].value),"int",s[0].exact);if(n==="float"&&s.length===1&&$n(s[0]))return Ct(no(s[0]),"float",s[0].exact);if(n.startsWith("math.")){let a=n.slice(5);if(a==="round"){if(!s.every($n)||s.length<1||s.length>2)return;let c=s[0].value;if(s.length===1)return Ct(Math.round(c),"int",s[0].exact);let u=Math.pow(10,s[1].value);return Ct(Math.round(c*u)/u,"float",ps(...s))}let o=CI[a];if(!o||s.length<o.arity[0]||s.length>o.arity[1]||!s.every($n))return;let l=o.type==="same"?_i(...s):o.type;return Ct(o.fn(...s.map(c=>c.value)),l,ps(...s))}if(n==="str.upper"||n==="str.lower"||n==="str.length"){if(s.length!==1||s[0].type!=="string")return;let a=String(s[0].value);return n==="str.length"?Ct(a.length,"int",s[0].exact):{value:n==="str.upper"?a.toUpperCase():a.toLowerCase(),type:"string",exact:s[0].exact}}if(n==="color.new"||n==="color.rgb")return MI(n,s);if(n==="timestamp"&&s.length===1&&s[0].type==="string")return PI(String(s[0].value))}function MI(t,e){let n=s=>Math.max(0,Math.min(1,s));if(t==="color.rgb"){let[s,a,o,l]=e.map(u=>u.value);if(typeof s!="number"||typeof a!="number"||typeof o!="number")return;let c=n((100-(typeof l=="number"?l:0))/100);return{value:fa(s,a,o,c),type:"color",exact:!1}}let r=Li(e[0]?.value),i=e[1]?.value;if(!(!r||typeof i!="number"))return{value:fa(r[0],r[1],r[2],n((100-i)/100)),type:"color",exact:!1}}function PI(t){let e=t.trim(),n=/[Zz]$/.test(e)||/[+-]\\d{2}:?\\d{2}$/.test(e),r=n?new Date(e).getTime():new Date(e.includes("T")?e+"Z":e.replace(/\\s+/,"T")+"Z").getTime();return!n&&Number.isNaN(r)&&(r=new Date(`${e} UTC`).getTime()),Ct(r,"int",n)}var Sd={const:0,input:1,simple:2,series:3},ds=(...t)=>t.reduce((e,n)=>Sd[n]>Sd[e]?n:e,"const"),$c={},ni=(t,e,n)=>n.forEach(r=>$c[r]={qual:t,type:e});ni("series","float",["open","high","low","close","volume","hl2","hlc3","ohlc4","hlcc4","ask","bid"]);ni("series","int",["bar_index","last_bar_index","time","time_close","timenow","year","month","weekofyear","dayofmonth","dayofweek","hour","minute","second"]);ni("series","bool",["barstate.isfirst","barstate.islast","barstate.ishistory","barstate.isrealtime","barstate.isnew","barstate.isconfirmed","barstate.islastconfirmedhistory"]);ni("simple","int",["timeframe.multiplier"]);ni("simple","float",["syminfo.mintick","syminfo.pointvalue"]);ni("simple","string",["timeframe.period","syminfo.ticker","syminfo.tickerid","syminfo.timezone","syminfo.currency","syminfo.type","syminfo.prefix","syminfo.root","syminfo.description"]);ni("simple","bool",["timeframe.isintraday","timeframe.isdaily","timeframe.isweekly","timeframe.ismonthly","timeframe.isdwm","timeframe.isminutes","timeframe.isseconds"]);var DI=new Set(["cross","crossover","crossunder","rising","falling"]),OI=new Set(["barssince","highestbars","lowestbars"]),RI=new Set(["floor","ceil"]),LI=new Set(["abs","max","min"]),ny=(...t)=>t.every(e=>e==="int")?"int":"float",wr=t=>t==="int"||t==="float";function Vn(t,e){if(t)switch(t.type){case"Literal":return typeof t.value=="boolean"?{qual:"const",type:"bool"}:typeof t.value=="string"?{qual:"const",type:ty.test(t.value)?"color":"string"}:typeof t.value=="number"?{qual:"const",type:typeof t.raw=="string"&&/[.eE]/.test(t.raw)?"float":"int"}:void 0;case"Identifier":{let n=e.lookup(t.name);return n===null?void 0:n??$c[t.name]}case"MemberExpression":{let n=ir(t);return n?.startsWith("color.")&&Li(n)?{qual:"const",type:"color"}:n?$c[n]:void 0}case"UnaryExpression":{let n=Vn(t.argument,e);return n?t.operator==="!"?n.type==="bool"?n:void 0:wr(n.type)?n:void 0:void 0}case"BinaryExpression":case"LogicalExpression":{let n=Vn(t.left,e),r=Vn(t.right,e);if(!n||!r)return;let i=ds(n.qual,r.qual),s=t.operator;return["&&","||",">","<",">=","<=","==","!=","===","!=="].includes(s)?{qual:i,type:"bool"}:s==="+"&&n.type==="string"&&r.type==="string"?{qual:i,type:"string"}:["+","-","*","/","%"].includes(s)&&wr(n.type)&&wr(r.type)?{qual:i,type:ny(n.type,r.type)}:void 0}case"ConditionalExpression":{let n=Vn(t.test,e),r=Vn(t.consequent,e),i=Vn(t.alternate,e);if(!n||!r||!i)return;let s=ds(n.qual,r.qual,i.qual);return r.type===i.type?{qual:s,type:r.type}:wr(r.type)&&wr(i.type)?{qual:s,type:"float"}:void 0}case"CallExpression":return FI(t,e);default:return}}function FI(t,e){let n=ir(t.callee);if(!n)return;let r=(t.arguments??[]).filter(o=>o?.type!=="ObjectExpression");if(n.startsWith("ta.")){let o=n.slice(3);return{qual:"series",type:DI.has(o)?"bool":OI.has(o)?"int":"float"}}let i=r.map(o=>Vn(o,e));if(i.some(o=>!o))return;let s=i,a=ds(...s.map(o=>o.qual));if(n==="timestamp")return s.length===1&&s[0].type==="string"?{qual:a,type:"int"}:s.length>=3?{qual:ds("simple",a),type:"int"}:void 0;if(n==="color.new"||n==="color.rgb")return{qual:a,type:"color"};if(n==="int"&&s.length===1&&wr(s[0].type))return{qual:a,type:"int"};if(n==="float"&&s.length===1&&wr(s[0].type))return{qual:a,type:"float"};if(n==="str.tostring"||n==="str.format")return{qual:ds("simple",a),type:"string"};if(n.startsWith("math.")&&s.length&&s.every(o=>wr(o.type))){let o=n.slice(5);return o==="round"?{qual:a,type:s.length===1?"int":"float"}:RI.has(o)?{qual:a,type:"int"}:LI.has(o)?{qual:a,type:ny(...s.map(l=>l.type))}:{qual:a,type:"float"}}}var BI={"&&":"and","||":"or","!":"not","===":"==","!==":"!="};function Ed(t,e){let n=`(${e.qual} ${e.type})`;switch(t?.type){case"Identifier":case"MemberExpression":return ir(t)??"";case"CallExpression":return`call "${ir(t.callee)}" ${n}`;case"ConditionalExpression":return`call "operator ?:" ${n}`;case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":return`call "operator ${BI[t.operator]??t.operator}" ${n}`;default:return""}}function kn(t){switch(t?.type){case"Identifier":case"Literal":case"UnaryExpression":case"ArrayExpression":return t._pos;case"MemberExpression":return kn(t.object);case"CallExpression":return kn(t.callee);case"BinaryExpression":case"LogicalExpression":return kn(t.left);case"ConditionalExpression":return kn(t.test);default:return}}var VI=Object.defineProperty,$I=(t,e,n)=>e in t?VI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,br=(t,e,n)=>$I(t,typeof e!="symbol"?e+"":e,n),zI="untitled",jI=new Set(["bool","color","enum","float","int","price","session","source","string","symbol","text_area","time","timeframe"]),kd={"":["defval","title","tooltip","inline","group","display","active"],bool:["defval","title","tooltip","inline","group","confirm","display","active"],color:["defval","title","tooltip","inline","group","confirm","display","active"],enum:["defval","title","options","tooltip","inline","group","confirm","display","active"],price:["defval","title","tooltip","inline","group","confirm","display","active"],session:["defval","title","options","tooltip","inline","group","confirm","display","active"],source:["defval","title","tooltip","inline","group","display","active","confirm"],string:["defval","title","options","tooltip","inline","group","confirm","display","active"],symbol:["defval","title","tooltip","inline","group","confirm","display","active"],text_area:["defval","title","tooltip","group","confirm","display","active"],time:["defval","title","tooltip","inline","group","confirm","display","active"],timeframe:["defval","title","options","tooltip","inline","group","confirm","display","active"]},qI=["defval","title","inline","group","tooltip","display","active"],Ad=["defval","title","options","tooltip","inline","group","confirm","display","active"],Td=["defval","title","minval","maxval","step","tooltip","inline","group","confirm","display","active"],UI={"":"bool",int:"int",float:"float",bool:"bool",string:"string",text_area:"string",session:"string",symbol:"string",timeframe:"string",time:"int",price:"float",color:"color"};function WI(t,e){if(e==="defval")return UI[t];if(e==="title"||e==="tooltip"||e==="group"||e==="inline")return"string";if(e==="minval"||e==="maxval"||e==="step")return t==="int"?"int":"float";if(e==="confirm")return"bool"}var vr=class{constructor(e){this.parent=e,br(this,"vars",new Map)}resolve(e){for(let n=this;n;n=n.parent){let r=n.vars.get(e);if(r)return r}}};function HI(t,e={}){return new zc(t,e).run()}function ry(t){if(t?.type!=="CallExpression")return null;let e=ir(t.callee);return e==="input"?"":e?.startsWith("input.")&&jI.has(e.slice(6))?e.slice(6):null}var zc=class{constructor(e,n){this.ast=e,br(this,"sites",[]),br(this,"enums",new Map),br(this,"reassigned",new Set),br(this,"visited",new WeakSet),br(this,"inputDefaults",new WeakMap),br(this,"functionNames",new Set),br(this,"truncatingIntDivision"),this.truncatingIntDivision=n.version!=null&&n.version<6}run(){this.collectEnumsAndReassignments(this.ast);let e=new vr(null);return this.visitStatements(this.ast.body??[],{scope:e,target:null,fnName:null}),this.sites}collectEnumsAndReassignments(e){pa(e,n=>{if(n.type==="FunctionDeclaration"&&n.id?.name&&this.functionNames.add(n.id.name),n.type==="AssignmentExpression"&&n.left?.type==="Identifier"&&this.reassigned.add(n.left.name),n.type==="VariableDeclaration")for(let r of n.declarations??[]){let i=r?.init;if(!(r?.id?.type!=="Identifier"||i?.type!=="ObjectExpression"||!i.properties?.length||!i.properties.every(s=>s.value?.type==="Literal"&&typeof s.value.value=="string")))for(let s of i.properties)this.enums.set(`${r.id.name}.${s.key.name}`,s.value.value)}})}pineName(e){return e.endsWith("_var")&&this.functionNames.has(e.slice(0,-4))?e.slice(0,-4):e}env(e,n=!1){return{enums:this.enums,truncatingIntDivision:this.truncatingIntDivision,lookup:r=>{let i=e.resolve(r);if(n&&i?.kind==="value"&&!i.nonConst&&i.inputDefault)return i.inputDefault;if(!(!i||i.kind!=="value"||i.nonConst||i.busy))return i.cache===void 0&&(i.busy=!0,i.cache=Nn(i.init,this.env(i.scope))??null,i.busy=!1),i.cache??void 0}}}fold(e,n){return Nn(e,this.env(n))}foldCondition(e,n){let r=this.fold(e,n);return r?.type==="bool"?r.value:void 0}declareValue(e,n,r,i){let s=this.reassigned.has(n)||/\\b(series|simple)\\b/.test(i??"");e.vars.set(n,{kind:"value",name:n,init:r,scope:e,nonConst:s,inputDerived:Id(r)})}declarePattern(e,n,r){if(n?.type==="Identifier")e.vars.set(n.name,{kind:r,name:n.name});else if(n?.type==="ArrayPattern")for(let i of n.elements??[])this.declarePattern(e,i,r);else n?.type==="AssignmentPattern"&&this.declarePattern(e,n.left,r)}visitStatements(e,n){for(let r of e)this.visit(r,n)}visit(e,n){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let r of e)this.visit(r,n);return}if(!(typeof e.type!="string"||this.visited.has(e)))switch(this.visited.add(e),e.type){case"VariableDeclaration":for(let r of e.declarations??[]){let i=r.id?.type==="Identifier"?r.id.name:null;if(this.visit(r.init,{...n,target:i?this.pineName(i):n.target}),i){this.declareValue(n.scope,i,r.init,r.varType??r.id?.varType??null);let s=n.scope.vars.get(i),a=this.inputDefaults.get(r.init);s?.kind==="value"&&a&&(s.inputDefault=a)}}return;case"AssignmentExpression":{let r=e.left?.type==="Identifier"?e.left.name:null;if(this.visit(e.right,{...n,target:r?this.pineName(r):n.target}),r&&Id(e.right)){let i=n.scope.resolve(r);i?.kind==="value"&&(i.inputDerived=!0)}return}case"BlockStatement":this.visitStatements(e.body??[],e._sequence?n:{...n,scope:new vr(n.scope)});return;case"IfStatement":{this.visit(e.test,n);let r=this.foldCondition(e.test,n.scope);r!==!1&&this.visitBranch(e.consequent,n),r!==!0&&e.alternate&&this.visitBranch(e.alternate,n);return}case"ConditionalExpression":{this.visit(e.test,n);let r=this.foldCondition(e.test,n.scope);r!==!1&&this.visit(e.consequent,n),r!==!0&&this.visit(e.alternate,n);return}case"BinaryExpression":case"LogicalExpression":{this.visit(e.left,n);let r=e.operator;if((r==="&&"||r==="||")&&this.foldCondition(e.left,n.scope)===(r==="||"))return;this.visit(e.right,n);return}case"SwitchExpression":this.visitSwitch(e,n);return;case"ForStatement":{let r=new vr(n.scope),i=e.init;if(i?.type==="VariableDeclaration")for(let a of i.declarations??[])this.visit(a.init,n),this.declarePattern(r,a.id,"loop");else this.visit(i,n);let s={...n,scope:r};this.visit(e.test,s),this.visit(e.update,s),this.visitBranch(e.body,s);return}case"FunctionDeclaration":{let r=new vr(n.scope);for(let s of e.params??[])this.declarePattern(r,s,"param");let i={scope:r,target:null,fnName:e.id?.name??null};this.visit(e.params,i),this.visitBranch(e.body,i);return}case"CallExpression":{let r=ry(e);if(r!==null){this.recordInput(e,r,n);return}this.visit(e.callee,n),this.visit(e.arguments,n);return}default:this.visitChildren(e,n)}}}visitBranch(e,n){e?.type==="BlockStatement"?this.visit(e,n):this.visit(e,{...n,scope:new vr(n.scope)})}visitSwitch(e,n){this.visit(e.discriminant,n);let r=e.discriminant?this.fold(e.discriminant,n.scope):void 0,i=!1;for(let s of e.cases??[]){let a=!i;if(a&&s.test)if(this.visit(s.test,n),e.discriminant){let l=r?this.fold(s.test,n.scope):void 0;r&&l&&l.type===r.type&&(l.value===r.value?i=!0:a=!1)}else{let l=this.foldCondition(s.test,n.scope);l===!0?i=!0:l===!1&&(a=!1)}else a&&!s.test&&(i=!0);if(!a)continue;let o={...n,scope:new vr(n.scope)};s.statements?.length?this.visitStatements(s.statements,o):this.visit(s.consequent,o)}}visitChildren(e,n){for(let r of Object.keys(e)){if(r==="args"||r==="type"||r.startsWith("_"))continue;let i=e[r];i&&typeof i=="object"&&this.visit(i,n)}}recordInput(e,n,r){let i=e.arguments??[],s=i[i.length-1],a=s?.type==="ObjectExpression",o=a?s.properties??[]:[],l=a?i.slice(0,-1):i.slice(),c=n===""?"input":`input.${n}`,u={},h=l[0]??o.find(E=>E.key?.name==="defval")?.value,p=n==="int"||n==="float"?o.some(E=>E.key?.name==="options")||l[2]?.type==="ArrayExpression"?Ad:Td:n===""&&Sl(h,r.scope)?qI:kd[n];l.forEach((E,T)=>{T<p.length&&(u[p[T]]={node:E,holder:i,key:String(T)})});let d=n==="int"||n==="float"?new Set([...Ad,...Td]):new Set(kd[n]);for(let E of o)if(!(E.type!=="Property"||!E.key?.name)){if(!d.has(E.key.name))throw new Error(`The "${c}" function does not have an argument with the name "${E.key.name}"${E.key._pos?` at ${E.key._pos}`:""}`);u[E.key.name]={node:E.value,holder:E,key:"value"}}this.validateArguments(e,r.scope,u.active?.node),this.checkArgumentTypes(e,n,u,r.scope);let f={},m;for(let[E,{node:T}]of Object.entries(u)){let N=T?.type==="ArrayExpression"?void 0:E==="active"?Nn(T,this.env(r.scope,!0)):this.fold(T,r.scope);E==="defval"&&(m=N?.type,N&&this.inputDefaults.set(e,N)),f[E]=N?no(N):GI(T,$=>this.fold($,r.scope))}if(this.checkDefvalConstraints(e,n,u,f,r.scope),n==="enum"&&f.options===void 0){let E=this.enumField(u.defval?.node,r.scope),T=E?.slice(0,E.lastIndexOf(".")+1);T&&(f.options=[...this.enums].filter(([N])=>N.startsWith(T)&&!N.slice(T.length).includes(".")).map(([,N])=>N))}this.inlineDefval(u.defval,r.scope);let y=`in_${this.sites.length}`,g=typeof f.title=="string"?f.title:void 0,w=r.target??void 0,k={id:y,fn:n,name:g??r.target??r.fnName??zI,args:f};w!==void 0&&(k.varId=w),m!==void 0&&(k.defvalType=m),this.sites.push(k);let S=[new Oi(new ge("__inputId"),new Tt(y))];w!==void 0&&S.push(new Oi(new ge("__varId"),new Tt(w))),i.push(new As(S))}inlineDefval(e,n){if(!e||!e.node||e.node.type==="Literal")return;let r=this.fold(e.node,n);if(!r||!r.exact||!["int","float","bool","string"].includes(r.type))return;let i=no(r),s=r.type==="float"&&typeof i=="number"&&Number.isInteger(i)?`${i}.0`:typeof i=="number"?String(i):null;e.holder[e.key]=new Tt(i,s)}qualifierEnv(e,n=new Set){return{lookup:r=>{let i=e.resolve(r);if(!i)return;if(i.kind!=="value"||i.nonConst||i.inputDerived||n.has(i))return null;let s=this.fold({type:"Identifier",name:r},e);if(s&&["int","float","bool","string"].includes(s.type))return{qual:"const",type:s.type};n.add(i);let a=Vn(i.init,this.qualifierEnv(i.scope,n));return n.delete(i),a??null}}}checkArgumentTypes(e,n,r,i){let s=this.qualifierEnv(i),a=n===""?"input":`input.${n}`,o=El(e.callee),l=c=>c?` at ${c}`:"";for(let[c,{node:u}]of Object.entries(r)){if(!u)continue;if(n==="source"&&c==="defval"){if(Sl(u,i))continue;throw new Error(`Invalid value for the "defval" parameter of the "input.source" function. Possible values: [open, high, low, close, hl2, hlc3, ohlc4, hlcc4].${l(o)}`)}if(n==="enum")continue;if(c==="defval"&&u.type==="Identifier"&&u.name==="na"&&!i.resolve("na"))throw n===""?new Error(`Arguments of input function must be of constant type, or "source" builtin variables.${l(o)}`):n==="bool"?new Error(`Cannot call "input.bool" with argument "defval"="na". An argument of "simple na" type was used but a "const bool" is expected.${l(kn(u))}`):new Error(`The "defval" parameter of the "${a}()" function cannot accept a "na" argument.${l(kn(u))}`);if(c==="options"&&u.type==="ArrayExpression"){this.checkOptionTypes(a,n,u,s);continue}let h=WI(n,c);if(!h)continue;let p=Vn(u,s);if(!p)continue;let d=p.qual==="simple"||p.qual==="series";if(n===""&&c==="defval"){if(!d)continue;if(p.type!=="bool"&&p.type!=="string"){if(Sl(u,i)||u.type==="ConditionalExpression")continue;throw new Error(`Arguments of input function must be of constant type, or "source" builtin variables.${l(o)}`)}}else if(!d&&Nd(p.type,h))continue;let f=u.type==="Literal",m=f?Cd(u):Ed(u,p);throw new Error(`Cannot call "${a}" with argument "${c}"="${m}". An argument of "${f?"literal":p.qual} ${p.type}" type was used but a "const ${h}" is expected.${l(kn(u))}`)}}checkOptionTypes(e,n,r,i){let s=n==="int"?"int":n==="float"?"float":["string","session","timeframe"].includes(n)?"string":void 0;if(!s)return;let a=r.elements??[],o=a.map(h=>Vn(h,i));if(o.some(h=>!h)||o.every(h=>h.qual!=="simple"&&h.qual!=="series"&&Nd(h.type,s)))return;let l=a.map((h,p)=>h.type==="Literal"?Cd(h):Ed(h,o[p])).join(","),c=a.map((h,p)=>`${h.type==="Literal"?"literal":o[p].qual} ${o[p].type}`).join(", "),u=kn(r);throw new Error(`Cannot call "${e}" with argument "options"="${l}". An argument of "[${c}]" type was used but a "[const ${s}...]" is expected.${u?` at ${u}`:""}`)}enumField(e,n){if(e?.type==="ConditionalExpression"){let r=this.foldCondition(e.test,n);return r===void 0?null:this.enumField(r?e.consequent:e.alternate,n)}return ir(e)}checkDefvalConstraints(e,n,r,i,s){let a=r.defval?.node,o=u=>u?` at ${u}`:"";if(n==="enum"){let u=[a,...r.options?.node?.type==="ArrayExpression"?r.options.node.elements:[]].map(h=>this.enumField(h,s));if(u.some(h=>!h||!this.enums.has(h)))return;if(new Set(u.map(h=>h.slice(0,h.lastIndexOf(".")))).size>1)throw new Error(`All values passed to "input.enum()" as its "defval" or "options" must be fields of the same enum.${o(El(e.callee))}`);if(r.options){let[h,...p]=u;if(!p.includes(h))throw new Error(`input\'s defval should be in options, but \'${h}\' is not in [${p.join(", ")}]${o(kn(a))}`)}return}let l=i.defval;if(typeof l=="number"&&(n==="int"||n==="float")){let{minval:u,maxval:h}=i;if(typeof u=="number"&&l<u||typeof h=="number"&&l>h)throw new Error(`Input\'s "defval" value must be between "minval" and "maxval"${o(kn(a))}`)}let c=i.options;if(Array.isArray(c)&&r.options?.node?.type==="ArrayExpression"&&(typeof l=="number"||typeof l=="string")&&!c.some(u=>typeof u=="number"&&typeof l=="number"?Math.abs(u-l)<1e-10:u===l)&&c.every(u=>typeof u==typeof l)){let u=typeof l=="string"?`\'${l}\'`:String(l);throw new Error(`input\'s defval should be in options, but ${u} is not in [${c.map(String).join(", ")}]${o(kn(a))}`)}}validateArguments(e,n,r){let i=new Set;r&&pa(r,s=>i.add(s)),pa({type:"Args",list:e.arguments??[]},(s,a,o)=>{if(s.type!=="Identifier"||a?.type==="Property"&&o==="key"||a?.type==="MemberExpression"&&o==="property"&&!a.computed)return;let l=n.resolve(s.name);if(l){if(l.kind==="loop"||l.kind==="param")throw new Error(`Undeclared identifier "${s.name}"${s._pos?` at ${s._pos}`:""}`);if(l.kind==="value"&&l.inputDerived&&!i.has(s)){let c=El(e.callee);throw new Error(`Arguments of input function must be of constant type, or "source" builtin variables.${c?` at ${c}`:""}`)}}})}};function Sl(t,e){return t?.type==="Identifier"&&co.has(t.name)&&!e.resolve(t.name)}function Nd(t,e){return t===e||e==="float"&&t==="int"}function Cd(t){return String(t.value)}function GI(t,e){if(t?.type==="ArrayExpression")return(t.elements??[]).map(n=>{let r=e(n);return r?no(r):void 0})}function Id(t){let e=!1;return pa(t,n=>{!e&&ry(n)!==null&&(e=!0)}),e}function El(t){let e=t;for(;e?.type==="MemberExpression";)e=e.object;return e?._pos}function pa(t,e){let n=new WeakSet,r=(i,s,a)=>{if(!(!i||typeof i!="object")){if(Array.isArray(i)){for(let o of i)r(o,s,a);return}if(!n.has(i)){n.add(i),typeof i.type=="string"&&e(i,s,a);for(let o of Object.keys(i)){if(o==="args"||o.startsWith("_"))continue;let l=i[o];l&&typeof l=="object"&&r(l,i,o)}}}};r(t,null,"")}function ko(t){let e=/^\\s*\\/\\/\\s*@version\\s*=\\s*(\\d+)\\s*$/im,n=t.match(e);return n&&n[1]?parseInt(n[1],10):null}var KI=Object.defineProperty,YI=(t,e,n)=>e in t?KI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nt=(t,e,n)=>YI(t,typeof e!="symbol"?e+"":e,n),Md=new Set(yo),XI=/[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)?/g,jc=class{constructor(e,n){this.spec=e,this.prefix=n,Nt(this,"decls",[]),Nt(this,"byKey",new Map),Nt(this,"exported",new Set),Nt(this,"functions",new Map),Nt(this,"types",new Map),Nt(this,"enums",new Map),Nt(this,"globals",new Map),Nt(this,"methodRenames",new Map),Nt(this,"methods",new Set),Nt(this,"imports",new Map)}addDecl(e,n){let r={node:e,keys:n,edges:[]};this.decls.push(r);for(let i of n){let s=this.byKey.get(i)??[];s.push(r),this.byKey.set(i,s),e.exported&&this.exported.add(i)}}},ro=class{constructor(e,n,r){this.mod=e,this.imports=n,this.refs=r,Nt(this,"shadow",new Set),Nt(this,"seen",new WeakSet)}};function ZI(t,e){let n=t.body.filter(r=>r.type==="ImportDeclaration").map(r=>({path:r.path,user:r.user,name:r.name,version:r.version,alias:r.alias}));return n.length===0?{imports:n,unresolved:[]}:e?new qc(e).link(t,n):{imports:n,unresolved:n}}var Ji=t=>!!t&&"missing"in t,qc=class{constructor(e){this.libraries=e,Nt(this,"modules",new Map),Nt(this,"loading",[]),Nt(this,"prefixes",new Set)}link(e,n){let r=this.loadImports(n,null),i=e.body.findIndex(o=>o.type==="ImportDeclaration");e.body=e.body.filter(o=>o.type!=="ImportDeclaration");let s=[],a=new ro(null,r,s);for(let o of e.body)this.visit(o,a);return e.body.splice(i,0,...this.emit(r,this.reach(s))),{imports:n,unresolved:n.filter(o=>Ji(r.get(o.alias)))}}loadImports(e,n){let r=new Map;for(let i of e){if(r.has(i.alias))throw new Error(`Duplicate import alias "${i.alias}"${n?` in library "${n.spec.path}"`:""}`);r.set(i.alias,this.load(i)??{missing:i})}return r}load(e){let n=this.modules.get(e.path);if(n)return n;let r=this.libraries[e.path];if(typeof r!="string")return null;if(this.loading.includes(e.path))throw new Error(`Circular library import: ${[...this.loading,e.path].join(" -> ")}`);this.loading.push(e.path);try{let i=this.parseLibrary(e,r);return this.modules.set(e.path,i),i}finally{this.loading.pop()}}parseLibrary(e,n){let r=ko(n);if(r===null||r<5)throw new Error(`Library "${e.path}": ${r===null?"missing //@version annotation":`Pine Script version ${r} is not supported`}`);let i;try{i=new ey(new ih(n).tokenize()).parse()}catch(o){throw new Error(`Failed to parse library "${e.path}": ${o.message}`)}let s=iy(i.body);if(!s.some(JI))throw new Error(`"${e.path}" is not a library: its source has no library() declaration`);let a=new jc(e,this.prefixFor(e));a.imports=this.loadImports(s.filter(o=>o.type==="ImportDeclaration"),a);for(let o of s)if(o.type==="FunctionDeclaration"){let l=o.id.name;o.id.isMethod?a.methods.add(l):a.functions.set(l,a.prefix+l),a.addDecl(o,[(o.id.isMethod?"m:":"f:")+l])}else if(o.type==="TypeDefinition")a.types.set(o.name,a.prefix+o.name),a.addDecl(o,["t:"+o.name]);else if(o.type==="VariableDeclaration"&&o._enum){let l=o.declarations[0].id.name;a.enums.set(l,a.prefix+l),a.addDecl(o,["e:"+l])}else if(o.type==="VariableDeclaration"){let l=o.declarations.flatMap(c=>da(c.id).map(u=>u.name));for(let c of l)a.globals.set(c,a.prefix+c);a.addDecl(o,l.map(c=>"g:"+c))}for(let o of a.methods)!a.exported.has("m:"+o)&&!Ss.has(o)&&a.methodRenames.set(o,a.prefix+o);for(let o of a.decls)this.rewriteDeclaration(a,o);return a}prefixFor(e){let n=s=>s.replace(/[^A-Za-z0-9_]/g,"_"),r=`${n(e.user)}$${n(e.name)}$${e.version}$`;/^\\d/.test(r)&&(r="_"+r);let i=r;for(let s=2;this.prefixes.has(i);s++)i=`${r}${s}$`;return this.prefixes.add(i),i}rewriteDeclaration(e,n){let r=new ro(e,e.imports,n.edges),i=n.node;if(delete i._line,i.type==="FunctionDeclaration"){let s=i.id.name;i.id.name=i.id.isMethod?e.methodRenames.get(s)??s:e.functions.get(s),r.shadow=QI(i),this.renameTypes(i,r),this.renameTypes(i.id,r);for(let a of i.params)this.renameTypes(a.type==="AssignmentPattern"?a.left:a,r),a.type==="AssignmentPattern"&&this.visit(a.right,r);this.visit(i.body,r)}else if(i.type==="TypeDefinition")i.name=e.types.get(i.name),this.visit(i,r);else if(i._enum){let s=i.declarations[0].id;s.name=e.enums.get(s.name)}else{for(let s of i.declarations)for(let a of da(s.id))a.name=e.globals.get(a.name)??a.name;this.visit(i.declarations,r)}}visit(e,n){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let r of e)this.visit(r,n);return}if(!(typeof e.type!="string"||n.seen.has(e))){switch(n.seen.add(e),n.mod&&delete e._line,this.renameTypes(e,n),e.type){case"CallExpression":return this.visitCall(e,n);case"MemberExpression":return this.visitMember(e,n);case"Identifier":return this.visitReference(e,n);case"Property":return this.visit(e.value,n);case"VariableDeclarator":for(let r of da(e.id))this.renameTypes(r,n);return this.visit(e.init,n);case"TypeDefinition":for(let r of e.fields)r.type=this.renameTypeString(r.type,n),this.visit(r.defaultValue,n);return}for(let r of Object.keys(e))r!=="type"&&this.visit(e[r],n)}}}visitReference(e,n){if(!n.mod||n.shadow.has(e.name))return;let r=n.mod.globals.get(e.name);r&&(n.refs.push({mod:n.mod,key:"g:"+e.name}),e.name=r)}visitMember(e,n){let r=e.object;if(!e.computed&&r?.type==="MemberExpression"&&!r.computed&&r.object?.type==="Identifier"){let i=this.aliasType(r.object.name,r.property?.name,n);i&&e2(r,i)}else if(!e.computed&&r?.type==="Identifier"&&n.mod&&!n.shadow.has(r.name)){let i=n.mod.types.get(r.name),s=n.mod.enums.get(r.name);i&&n.refs.push({mod:n.mod,key:"t:"+r.name}),s&&n.refs.push({mod:n.mod,key:"e:"+r.name}),(i||s)&&(r.name=i||s)}this.visit(r,n),e.computed&&this.visit(e.property,n)}visitCall(e,n){let r=e.callee;if(r?.type==="Identifier")n.mod&&this.linkCallee(r,n);else if(r?.type==="MemberExpression"&&!r.computed&&r.property?.type==="Identifier"){let i=r.object;i?.type==="Identifier"&&n.imports.has(i.name)&&this.linkAliasCall(e,i.name,r.property.name,n)?e.callee.type==="MemberExpression"&&this.visit(e.callee.object,n):(this.linkMethodCall(r,n),this.visit(r,n))}else this.visit(r,n);this.visit(e.arguments,n)}linkCallee(e,n){let r=n.mod,i=e.name,s=r.functions.get(i);if(s){n.refs.push({mod:r,key:"f:"+i}),e.name=s;return}if(r.methods.has(i)){n.refs.push({mod:r,key:"m:"+i}),e.name=r.methodRenames.get(i)??i;return}let a=!n.shadow.has(i)&&r.types.get(i);a&&(n.refs.push({mod:r,key:"t:"+i}),e.name=a)}linkAliasCall(e,n,r,i){let s=i.imports.get(n);if(Ji(s))return this.missingRef(s,`${n}.${r}()`,i),!1;if(s.exported.has("f:"+r))return i.refs.push({mod:s,key:"f:"+r}),e.callee=new ge(s.functions.get(r)),!0;if(s.exported.has("m:"+r)){i.refs.push({mod:s,key:"m:"+r});let[a,...o]=e.arguments;return a&&a.type!=="ObjectExpression"?(e.callee=new ks(a,new ge(r),!1),e.arguments=o):e.callee=new ge(r),!0}if(Md.has(n))return!1;throw new Error(`Could not find function or function reference "${n}.${r}": library "${s.spec.path}" does not export it`)}linkMethodCall(e,n){let r=e.object;if(r?.type==="Identifier"&&!n.shadow.has(r.name)&&(Md.has(r.name)||n.imports.has(r.name)))return;let i=e.property.name;if(n.mod?.methods.has(i)){n.refs.push({mod:n.mod,key:"m:"+i});let s=n.mod.methodRenames.get(i);s&&(e.property.name=s)}for(let s of n.imports.values())!Ji(s)&&s.exported.has("m:"+i)&&n.refs.push({mod:s,key:"m:"+i})}aliasType(e,n,r){let i=r.imports.get(e);if(!(!i||!n)){if(Ji(i)){this.missingRef(i,`${e}.${n}`,r);return}if(i.exported.has("t:"+n))return r.refs.push({mod:i,key:"t:"+n}),i.types.get(n);if(i.exported.has("e:"+n))return r.refs.push({mod:i,key:"e:"+n}),i.enums.get(n)}}missingRef(e,n,r){r.mod&&r.refs.push({missing:e.missing,via:n,from:r.mod.spec.path})}renameTypes(e,n){typeof e.varType=="string"&&(e.varType=this.renameTypeString(e.varType,n)),typeof e.returnType=="string"&&(e.returnType=this.renameTypeString(e.returnType,n))}renameTypeString(e,n){return typeof e!="string"?e:e.replace(XI,r=>{let i=r.indexOf(".");if(i>0)return this.aliasType(r.slice(0,i),r.slice(i+1),n)??r;let s=n.mod;if(!s)return r;let a=s.types.get(r);if(a)return n.refs.push({mod:s,key:"t:"+r}),a;let o=s.enums.get(r);return o?(n.refs.push({mod:s,key:"e:"+r}),o):r})}reach(e){let n=new Set,r=[...e];for(;r.length>0;){let i=r.pop();if("missing"in i)throw new Error(`Library "${i.from}" uses ${i.via} from "${i.missing.path}", which could not be resolved`);for(let s of i.mod.byKey.get(i.key)??[])n.has(s)||(n.add(s),r.push(...s.edges))}return n}emit(e,n){let r=[],i=new Set,s=a=>{if(!(Ji(a)||i.has(a))){i.add(a);for(let o of a.imports.values())s(o);r.push(a)}};for(let a of e.values())s(a);return r.flatMap(a=>a.decls.filter(o=>n.has(o)).map(o=>o.node))}};function iy(t){return t.flatMap(e=>e?.type==="BlockStatement"&&e._sequence?iy(e.body):[e])}function JI(t){let e=t?.type==="ExpressionStatement"?t.expression:null;return e?.type==="CallExpression"&&e.callee?.type==="Identifier"&&e.callee.name==="library"}function da(t){return t?.type==="Identifier"?[t]:t?.type==="ArrayPattern"?t.elements.filter(e=>e?.type==="Identifier"):[]}function QI(t){let e=new Set;for(let i of t.params){let s=i.type==="AssignmentPattern"?i.left:i;s?.name&&e.add(s.name)}let n=new WeakSet,r=i=>{if(!(!i||typeof i!="object"||n.has(i))){if(n.add(i),Array.isArray(i))return i.forEach(r);if(i.type==="VariableDeclarator")for(let s of da(i.id))e.add(s.name);for(let s of Object.keys(i))s!=="type"&&r(i[s])}};return r(t.body),e}function e2(t,e){for(let n of Object.keys(t))delete t[n];t.type="Identifier",t.name=e}function sh(t,e={}){let n=ko(t);if(n===null)return{success:!1,version:null,error:"Pine Script version not found. Please add //@version=X comment to your script."};if(n<5)return{success:!1,version:n,error:`Pine Script version ${n} is not supported. Only version 5 and above are supported.`};try{let r=new ih(t).tokenize(),i=new ey(r).parse(),{libraries:s,...a}=e,o=ZI(i,s),l=HI(i,{version:n}),c={...a,sourceCode:t},u=new Vc(c).generate(i);return{success:!0,version:n,code:u,ast:i,tokens:r,inputs:l,imports:o.imports,unresolvedImports:o.unresolved}}catch(r){return{success:!1,version:n,error:r.message,stack:r.stack}}}var t2=new Set(["security_lower_tf","security"]),sy=new Set(["type","loc","start","end","range","parent","leadingComments","trailingComments"]);function n2(t){if(!t||t.type!=="CallExpression")return!1;let e=t.callee;return!e||e.type!=="MemberExpression"||e.computed||e.object?.type!=="Identifier"||e.object.name!=="request"||e.property?.type!=="Identifier"?!1:t2.has(e.property.name)}function r2(t){let e=t?.arguments?.[2];return e?.type==="Identifier"&&typeof e.name=="string"?e.name:null}function i2(t){let e=[],n=new WeakSet;function r(i,s){if(!i||typeof i!="object"||n.has(i))return;n.add(i);let a=s.concat([i]);n2(i)&&e.push({call:i,path:a});for(let o of Object.keys(i)){if(sy.has(o))continue;let l=i[o];if(Array.isArray(l))for(let c of l)r(c,a);else l&&typeof l=="object"&&r(l,a)}}return r(t,[]),e}function Uc(t){return t?t.type==="FunctionExpression"||t.type==="ArrowFunctionExpression"||t.type==="FunctionDeclaration":!1}function Bn(t,e,n){if(n>=e.length-1)return t;let r=e[n+1];switch(t.type){case"BlockStatement":{let i=t.body.indexOf(r);if(i<0)return t;let s=t.body.slice(0,i);return s.push(Bn(r,e,n+1)),{...t,body:s}}case"IfStatement":return r===t.test?{...t,test:Bn(r,e,n+1),consequent:{type:"BlockStatement",body:[]},alternate:null}:r===t.consequent?{...t,consequent:Bn(r,e,n+1),alternate:null}:r===t.alternate?{...t,alternate:Bn(r,e,n+1)}:t;case"ForStatement":case"WhileStatement":case"DoWhileStatement":case"ForInStatement":case"ForOfStatement":return r===t.body?{...t,body:Bn(r,e,n+1)}:t;case"SwitchStatement":{let i=t.cases.indexOf(r);if(i>=0){let s=t.cases.slice(0,i);return s.push(Bn(r,e,n+1)),{...t,cases:s}}return t}case"SwitchCase":{let i=t.consequent.indexOf(r);if(i>=0){let s=t.consequent.slice(0,i);return s.push(Bn(r,e,n+1)),{...t,consequent:s}}return t}case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return r===t.body?{...t,body:Bn(r,e,n+1)}:t;default:return t}}function s2(t){if(!t||t.type!=="CallExpression")return null;let e=t.callee;if(!e||e.type!=="MemberExpression"||e.computed||e.object?.type!=="Identifier"||e.object.name!=="$"||e.property?.type!=="Identifier"||e.property.name!=="call")return null;let n=t.arguments?.[0];return n?.type==="Identifier"&&typeof n.name=="string"?n.name:null}function a2(t,e,n){let r=t.body||[];for(let i=r.length-1;i>=0;i--){let s=r[i];if(s!==n&&o2(s,e))return i}return-1}function o2(t,e){let n=!1,r=new WeakSet;function i(s){if(!(n||!s||typeof s!="object")&&!r.has(s)){if(r.add(s),s2(s)===e){n=!0;return}for(let a of Object.keys(s)){if(sy.has(a))continue;let o=s[a];if(Array.isArray(o))for(let l of o)i(l);else o&&typeof o=="object"&&i(o)}}}return i(t),n}function l2(t,e){let n=-1;for(let p=1;p<e.length;p++)if(Uc(e[p])){n=p;break}if(n<0)return null;let r=e[n];for(let p=n+1;p<e.length;p++)if(Uc(e[p]))return null;if(r.type!=="FunctionDeclaration"||!r.id?.name)return null;let i=r.id.name,s=e.slice(n),a=Bn(r,s,0),o=a2(t,i,r);if(o<0)return null;let l=t.body||[],c=l.indexOf(r);if(c<0)return null;let u=[],h=Math.max(o,c);for(let p=0;p<=h;p++){let d=l[p];u.push(d===r?a:d)}return u}function c2(t,e){let n={type:"Program",sourceType:"module",body:[{type:"ExpressionStatement",expression:{type:"ArrowFunctionExpression",async:!!t.async,params:t.params,body:{type:"BlockStatement",body:e}}}]},r=`var _r = ${Xu(n)}\n; return _r;`;return new Function("",r)()}function u2(t){let e={};if(!t||t.type!=="Program"||!Array.isArray(t.body)||t.body.length===0)return e;let n=t.body[0],r=null;if(n.type==="ExpressionStatement"){let s=n.expression;s&&(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")&&(r=s)}else n.type==="FunctionDeclaration"&&(r=n);if(!r||r.body?.type!=="BlockStatement")return e;let i=i2(r.body);for(let{call:s,path:a}of i){let o=r2(s);if(!o||o in e)continue;let l=a.some(h=>Uc(h)),c=null;if(l)c=l2(r.body,a);else{let h=Bn(r.body,a,0);c=h&&h.body?h.body:[]}if(!c||c.length===0)continue;let u=c2(r,c);e[o]=u}return e}var h2=new Set(["undefined","NaN","Infinity"]),p2=new Set(["constructor","prototype","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","context","pineTS","marketData","provider","_context"]),ay=new Set(["type","parent","loc","start","end","range","leadingComments","trailingComments"]),En=class extends Error{constructor(e){super(e),this.name="ClosedWorldViolation"}};function Sr(t,e){if(!(!t||typeof t!="object"))switch(t.type){case"Identifier":e.add(t.name);return;case"ObjectPattern":for(let n of t.properties||[])n.type==="RestElement"?Sr(n.argument,e):Sr(n.value,e);return;case"ArrayPattern":for(let n of t.elements||[])Sr(n,e);return;case"AssignmentPattern":Sr(t.left,e);return;case"RestElement":Sr(t.argument,e);return;default:return}}function Wc(t,e,n){if(!(!t||typeof t!="object"||n.has(t))){switch(n.add(t),t.type){case"VariableDeclarator":Sr(t.id,e);break;case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":t.id?.name&&e.add(t.id.name);for(let r of t.params||[])Sr(r,e);break;case"ClassDeclaration":case"ClassExpression":t.id?.name&&e.add(t.id.name);break;case"CatchClause":t.param&&Sr(t.param,e);break}for(let r of Object.keys(t)){if(ay.has(r))continue;let i=t[r];if(Array.isArray(i))for(let s of i)Wc(s,e,n);else i&&typeof i=="object"&&typeof i.type=="string"&&Wc(i,e,n)}}}function d2(t){return t.length>=2&&(t.startsWith("\'")&&t.endsWith("\'")||t.startsWith(\'"\')&&t.endsWith(\'"\'))}function Pd(t){if(typeof t=="string"&&p2.has(t))throw new En(`Access to reserved property "${t}" is not allowed`)}function Hc(t,e,n,r,i){if(!(!t||typeof t!="object"||typeof t.type!="string"||i.has(t))){switch(i.add(t),t.type){case"ThisExpression":throw new En(\'"this" is not available in Pine scripts\');case"Super":throw new En(\'"super" is not available in Pine scripts\');case"MetaProperty":throw new En(\'"import.meta" is not available in Pine scripts\');case"ImportExpression":throw new En("dynamic import() is not available in Pine scripts");case"WithStatement":throw new En(\'"with" is not available in Pine scripts\');case"NewExpression":if(!(t.callee?.type==="Identifier"&&t.callee.name==="Error"))throw new En("object construction is not available in Pine scripts");break;case"Identifier":{let s=e?.type==="MemberExpression"&&n==="property"&&!e.computed,a=e?.type==="Property"&&n==="key"&&!e.computed;if(s||a){Pd(t.name);return}if(d2(t.name)||t.name==="Error"&&e?.type==="NewExpression"&&n==="callee")return;if(!r.has(t.name)&&!h2.has(t.name))throw new En(`Undeclared identifier "${t.name}"`);return}case"MemberExpression":if(t.computed)if(t.property?.type==="Literal")Pd(t.property.value);else throw new En("dynamic computed member access is not allowed");break}for(let s of Object.keys(t)){if(ay.has(s))continue;let a=t[s];if(Array.isArray(a))for(let o of a)Hc(o,t,s,r,i);else a&&typeof a=="object"&&typeof a.type=="string"&&Hc(a,t,s,r,i)}}}function f2(t){let e=new Set;Wc(t,e,new WeakSet),Hc(t,null,null,e,new WeakSet)}function m2(t,e={}){if(typeof t=="function")return{code:t.toString(),version:null};{let n=ko(t);if(n===null){if(e.pineOnly)throw new Error("Pine Script version marker required: markerless source is treated as raw JavaScript and is rejected when pineOnly is set.");return{code:t,version:null}}if(n>=5){let r=sh(t,{libraries:e.libraries});if(r.success){let i=r.unresolvedImports??[];if(i.length>0)throw new Error(`Unresolved Pine Script import${i.length>1?"s":""}: ${i.map(s=>`"${s.path}"`).join(", ")}. Provide the library source with an import resolver (pineTS.setImportResolver) or the "libraries" transpile option.`);return{code:r.code,version:n}}else throw new Error(`Failed to transpile Pine Script version ${n}: ${r.error}`)}else throw new Error(`Unsupported Pine Script version ${n}. Only version 5 and above are supported.`)}}function y2(t,e={debug:!1,ln:!1}){typeof e=="boolean"&&(e={debug:e,ln:!0});let{debug:n}=e,{code:r,version:i}=m2(t,{pineOnly:e.pineOnly,libraries:e.libraries}),s=r;s=wC(s);let a=n?s.split(`\n`):[],o=Xa(s,{ecmaVersion:"latest",sourceType:"module",locations:n});SC(o),EC(o),bC(o),_C(o);let l=new xc;CC(o,l),kC(o,l);let c=MC(o,l)||"";if(i!==null&&$C(o,l,{intDivision:i<6}),UC(o,{lazyLogical:i===null||i>=6}),uI(o,l,c,e,a),sI(o),oI(o),cI(o),tI(o),o.type==="Program"&&o.body.length>0){let m=o.body[0],y=m?.expression||m;y.body?.type==="BlockStatement"&&y.body.body.unshift({type:"VariableDeclaration",kind:"const",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"__maxLoops"},init:{type:"LogicalExpression",operator:"||",left:{type:"MemberExpression",object:{type:"Identifier",name:"$"},property:{type:"Identifier",name:"__maxLoops"},computed:!1},right:{type:"Literal",value:5e5}}}]})}let u=pC||Yu||void 0,h=Object.assign({},u,{LineComment(m,y){y.write("//"+m.value)}}),p=Xu(o,{generator:h,comments:n});if(e.verify!==!1&&i!==null){let m=Xa(p,{ecmaVersion:"latest"});f2(m)}let d=typeof process<"u"&&process?.env?.PINETS_DISABLE_LTF_SLICING==="1"?{}:u2(o),f=new Function("",`var _r = ${p}\n; return _r;`)(this);if(f._pineVersion=i,d&&Object.keys(d).length>0){for(let m of Object.values(d))m._pineVersion=i;f._ltfSlices=d}return f}var g2={bool:"bool",color:"color",enum:"enum",float:"float",int:"int",price:"price",session:"session",source:"source",string:"string",symbol:"symbol",text_area:"text_area",time:"time",timeframe:"timeframe"},_2=new Set(["bool","color","time","text_area"]),b2=["open","high","low","close","hl2","hlc3","hlcc4","ohlc4"];function x2(t,e){if(typeof t!="string")return[];let n=sh(t,{libraries:e});if(!n.success||!n.inputs)return[];let r=[];for(let i of n.inputs){let s=v2(i);s&&r.push(s)}return r}function v2(t){let e=t.args,n=t.fn===""?w2(e.defval,t.defvalType):g2[t.fn];if(!n)return null;let r={id:t.id,name:t.name,type:n,defval:e.defval};t.varId!==void 0&&(r.varId=t.varId),e.title!==void 0&&(r.title=String(e.title)),e.tooltip!==void 0&&e.tooltip!==""&&(r.tooltip=String(e.tooltip)),e.group!==void 0&&(r.group=String(e.group)),e.inline!==void 0&&(r.inline=String(e.inline)),e.confirm!==void 0&&(r.confirm=!!e.confirm),e.active!==void 0&&(r.active=!!e.active);let i="display"in e?S2(e.display):_2.has(n)?"none":"all";return i!==void 0&&(r.display=i),Array.isArray(e.options)?r.options=e.options:n==="source"&&(r.options=[...b2]),typeof e.minval=="number"&&(r.minval=e.minval),typeof e.maxval=="number"&&(r.maxval=e.maxval),typeof e.step=="number"&&(r.step=e.step),r}function w2(t,e){switch(e){case"int":case"float":case"bool":case"string":case"color":case"source":return e}return typeof t=="boolean"?"bool":typeof t=="number"?Number.isInteger(t)?"int":"float":typeof t=="string"?co.has(t)?"source":t.startsWith("#")?"color":"string":null}function S2(t){if(typeof t!="string")return;let e=t.startsWith("display.")?t.slice(8):t;if(e==="none"||e==="data_window"||e==="status_line"||e==="all")return e}function oy(t,e,n,r,i="key"){let s={},a=new Map;for(let o of t)a.set(o.key,o),s[o.key]=r&&o.key in r?r[o.key]:o.defval;for(let o of t)for(let l of o.aliases??[])!l||a.has(l)||a.set(l,o);return{proxy:new Proxy(s,{get(o,l){if(typeof l=="symbol")return o[l];let c=a.get(l);return c?o[c.key]:o[l]},set(o,l,c){if(typeof l!="string")return!1;let u=a.get(l);if(!u)throw new Error(`[${e}] unknown ${i} "${l}". Known: ${[...a.keys()].join(", ")||"(none)"}`);return E2(u,c,e),o[u.key]=c,n?.(u.key),!0},deleteProperty(o,l){throw new Error(`[${e}] cannot delete "${String(l)}" \\u2014 keys are fixed by the script\'s source.`)},defineProperty(){throw new Error(`[${e}] cannot define new properties \\u2014 keys are fixed by the script\'s source.`)},ownKeys(o){return Reflect.ownKeys(o)},getOwnPropertyDescriptor(o,l){return Reflect.getOwnPropertyDescriptor(o,l)},has(o,l){return typeof l=="string"&&a.has(l)}}),values:s,entryByKey:a}}function E2(t,e,n){let r=t.key;switch(t.type){case"int":if(typeof e!="number"||!Number.isInteger(e))throw new TypeError(`[${n}] "${r}" expects an int; got ${gi(e)}`);break;case"float":case"price":case"time":if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`[${n}] "${r}" expects a number; got ${gi(e)}`);break;case"bool":if(typeof e!="boolean")throw new TypeError(`[${n}] "${r}" expects a boolean; got ${gi(e)}`);break;case"string":case"session":case"symbol":case"timeframe":case"text_area":case"color":case"enum":case"source":if(typeof e!="string")throw new TypeError(`[${n}] "${r}" expects a string; got ${gi(e)}`);break}if(t.options&&!t.options.some(i=>k2(i,e)))throw new RangeError(`[${n}] "${r}" value ${gi(e)} is not one of: ${t.options.map(gi).join(", ")}`);if(typeof e=="number"){if(typeof t.minval=="number"&&e<t.minval)throw new RangeError(`[${n}] "${r}" value ${e} is below minval ${t.minval}`);if(typeof t.maxval=="number"&&e>t.maxval)throw new RangeError(`[${n}] "${r}" value ${e} is above maxval ${t.maxval}`)}}function k2(t,e){return t===e?!0:typeof t=="number"&&typeof e=="number"?Math.abs(t-e)<1e-12:!1}function gi(t){return t===null?"null":typeof t=="string"?JSON.stringify(t):String(t)}function A2(t,e){let n=new Map,r=[],i=new Set(t.map(o=>o.id));for(let o of t){let l=[o.varId,o.title].find(u=>u&&!n.has(u)&&!i.has(u))??o.id,c=[o.title,o.id].filter(u=>!!u&&u!==l);n.set(l,o),r.push({key:l,type:o.type,defval:o.defval,options:o.type==="source"?void 0:o.options,minval:o.minval,maxval:o.maxval,aliases:c.length?c:void 0})}let{proxy:s,values:a}=oy(r,"Indicator.input",e,void 0,"input key");return{proxy:s,values:a,metaByKey:n}}var ly=[{name:"title",type:"string",defval:"",mutable:!1,appliesTo:"both"},{name:"shorttitle",type:"string",defval:"",mutable:!1,appliesTo:"both"},{name:"overlay",type:"bool",defval:!1,mutable:!0,appliesTo:"both"},{name:"format",type:"enum",defval:"inherit",options:["inherit","price","volume","percent","mintick"],mutable:!0,appliesTo:"both"},{name:"precision",type:"int",defval:10,minval:0,maxval:16,mutable:!0,appliesTo:"both"},{name:"scale",type:"enum",defval:"right",options:["right","left","none"],mutable:!0,appliesTo:"both"},{name:"max_bars_back",type:"int",defval:0,minval:0,maxval:5e3,mutable:!0,appliesTo:"both"},{name:"explicit_plot_zorder",type:"bool",defval:!1,mutable:!0,appliesTo:"both"},{name:"max_lines_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"max_labels_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"max_boxes_count",type:"int",defval:50,minval:1,maxval:500,mutable:!0,appliesTo:"both"},{name:"calc_bars_count",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"both"},{name:"max_polylines_count",type:"int",defval:50,minval:1,maxval:100,mutable:!0,appliesTo:"both"},{name:"dynamic_requests",type:"bool",defval:!0,mutable:!0,appliesTo:"both",version:6},{name:"behind_chart",type:"bool",defval:!0,mutable:!0,appliesTo:"both",version:6}],cy=[...ly.filter(t=>t.appliesTo==="both").map(t=>({...t,appliesTo:"indicator"})),{name:"timeframe",type:"string",defval:"",mutable:!0,appliesTo:"indicator"},{name:"timeframe_gaps",type:"bool",defval:!0,mutable:!0,appliesTo:"indicator"}],uy=[...ly.filter(t=>t.appliesTo==="both").map(t=>({...t,appliesTo:"strategy"})),{name:"pyramiding",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"calc_on_order_fills",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"calc_on_every_tick",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"backtest_fill_limits_assumption",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"default_qty_type",type:"enum",defval:"fixed",options:["fixed","cash","percent_of_equity"],mutable:!0,appliesTo:"strategy"},{name:"default_qty_value",type:"float",defval:1,minval:0,mutable:!0,appliesTo:"strategy"},{name:"initial_capital",type:"float",defval:1e6,minval:0,mutable:!0,appliesTo:"strategy"},{name:"currency",type:"enum",defval:"USD",options:["AED","ARS","AUD","BDT","BHD","BRL","BTC","CAD","CHF","CLP","CNY","COP","CZK","DKK","EGP","ETH","EUR","GBP","HKD","HUF","IDR","ILS","INR","ISK","JPY","KES","KRW","KWD","LKR","MAD","MXN","MYR","NGN","NOK","NONE","NZD","PEN","PHP","PKR","PLN","QAR","RON","RSD","RUB","SAR","SEK","SGD","THB","TND","TRY","TWD","USD","USDT","VES","VND","ZAR"],mutable:!0,appliesTo:"strategy"},{name:"slippage",type:"int",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"commission_type",type:"enum",defval:"percent",options:["percent","cash_per_contract","cash_per_order"],mutable:!0,appliesTo:"strategy"},{name:"commission_value",type:"float",defval:0,minval:0,mutable:!0,appliesTo:"strategy"},{name:"process_orders_on_close",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"close_entries_rule",type:"enum",defval:"FIFO",options:["FIFO","ANY"],mutable:!0,appliesTo:"strategy"},{name:"margin_long",type:"float",defval:100,minval:0,maxval:100,mutable:!0,appliesTo:"strategy"},{name:"margin_short",type:"float",defval:100,minval:0,maxval:100,mutable:!0,appliesTo:"strategy"},{name:"risk_free_rate",type:"float",defval:2,mutable:!0,appliesTo:"strategy"},{name:"use_bar_magnifier",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"},{name:"fill_orders_on_standard_ohlc",type:"bool",defval:!1,mutable:!0,appliesTo:"strategy"}];function T2(t){return t==="strategy"?uy:cy}function N2(t){return typeof t=="string"?C2(t):typeof t=="function"?I2(t):{type:null,args:{}}}function C2(t){let e=sh(t);if(!e.success||!e.ast)return{type:null,args:{}};let n=null;return io(e.ast,r=>{if(n||r.type!=="ExpressionStatement"&&r.type!=="VariableDeclaration")return;let i=r.type==="ExpressionStatement"?r.expression:r.declarations?.[0]?.init;if(!i||i.type!=="CallExpression")return;let s=i.callee;s?.type==="Identifier"&&(s.name!=="indicator"&&s.name!=="strategy"||(n={type:s.name,args:py(i.arguments??[],hy(s.name))}))}),n??{type:null,args:{}}}function I2(t){let e;try{e=Xa(`(${t.toString()})`,{ecmaVersion:"latest"})}catch{return{type:null,args:{}}}let n=null;return io(e,r=>{if(n||r.type!=="CallExpression")return;let i=r.callee;i?.type==="Identifier"&&(i.name!=="indicator"&&i.name!=="strategy"||(n={type:i.name,args:py(r.arguments??[],hy(i.name))}))}),n??{type:null,args:{}}}function hy(t){return t==="strategy"?uy:cy}function py(t,e){let n={},r=t[t.length-1],i=r?.type==="ObjectExpression",s=i?t.slice(0,-1):t.slice();for(let a=0;a<s.length&&a<e.length;a++){let o=e[a].name;n[o]=Gc(s[a])}if(i)for(let a of r.properties??[])a.type!=="Property"||!a.key?.name||(n[a.key.name]=Gc(a.value));return n}function Gc(t){if(t!=null)switch(t.type){case"Literal":return t.value;case"Identifier":return t.name;case"MemberExpression":{let e=t;for(;e?.type==="MemberExpression";)e=e.property;return e?.type==="Identifier"?e.name:void 0}case"UnaryExpression":return t.operator==="-"&&t.argument?.type==="Literal"&&typeof t.argument.value=="number"?-t.argument.value:void 0;case"ArrayExpression":return(t.elements??[]).map(Gc);default:return}}function io(t,e){if(!(!t||typeof t!="object")){e(t);for(let n of Object.keys(t)){let r=t[n];if(!(n==="loc"||n==="range"||n==="start"||n==="end"))if(Array.isArray(r))for(let i of r)io(i,e);else r&&typeof r=="object"&&typeof r.type=="string"&&io(r,e)}}}function M2(t,e,n){let r=new Map,i=[];for(let o of t)r.set(o.name,o),o.mutable&&i.push({key:o.name,type:o.type,defval:o.defval,options:o.options,minval:o.minval,maxval:o.maxval});let{proxy:s,values:a}=oy(i,"Indicator.prop",n,e);return{proxy:s,values:a,propByName:r}}var P2=Object.defineProperty,D2=(t,e,n)=>e in t?P2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Qi=(t,e,n)=>D2(t,typeof e!="symbol"?e+"":e,n),Ri=class{constructor(e){Qi(this,"_configured"),Qi(this,"_resolverName"),Qi(this,"_cached"),Qi(this,"_cacheDuration",1/0),Qi(this,"_cache",new Map),this._resolverName=e.resolverName,this._configured=!e.requiresConfig,this._cached=e.cached??!0}ensureConfigured(){if(!this._configured)throw new Error(`The ${this._resolverName} import resolver requires configuration before use. Call ImportResolver.${this._resolverName}.configure({ ... }) or instantiate directly: new ${this._resolverName}ImportResolver({ ... })`)}configure(e){this._configured=!0,e?.cacheDuration!==void 0&&(this._cacheDuration=e.cacheDuration),this.clearCache()}get isConfigured(){return this._configured}resolve(e,n){if(!this._cached)return this._resolveUncached(n);let r=this._cache.get(e);if(r&&Date.now()-r.time<this._cacheDuration)return r.source;let i={source:this._resolveUncached(n),time:Date.now()};return this._cache.set(e,i),i.source.catch(()=>{this._cache.get(e)===i&&this._cache.delete(e)}),i.source}clearCache(){this._cache.clear()}async firstFound(e,n,r){for(let i of n){let s=await r(e+i);if(s!==null)return s}return null}_resolveUncached(e){return Promise.resolve().then(()=>(this.ensureConfigured(),this._resolveNative(e))).then(n=>typeof n=="string"?n:null)}},Kc=class extends Ri{constructor(e){super({requiresConfig:!1,resolverName:"Function"}),this._fn=e}_resolveNative(e){return this._fn(e.path,e)}};function dy(t){return typeof t=="function"?new Kc(t):t}async function ah(t,e){let n={};if(!/^import\\s/m.test(t)||ko(t)===null)return n;let r=bd(t);if(r.length===0)return n;if(!e)throw new Error(`The script imports ${r.map(o=>`"${o.path}"`).join(", ")} but no import resolver is configured. Call pineTS.setImportResolver(...) with a resolver that returns the library sources.`);let i=dy(e),s=new Set,a=async(o,l)=>{if(s.has(o.path))return;s.add(o.path);let{path:c,user:u,name:h,version:p}=o,d=await i.resolve(c,{path:c,user:u,name:h,version:p,importer:l});if(typeof d!="string"){if(l===void 0)throw new Error(`Import "${c}" could not be resolved: the import resolver returned no source`);return}n[c]=d;let f;try{f=bd(d)}catch(m){throw new Error(`Library "${c}": ${m.message}`)}await Promise.all(f.map(m=>a(m,c)))};return await Promise.all(r.map(o=>a(o))),n}var O2=Object.defineProperty,R2=(t,e,n)=>e in t?O2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,yt=(t,e,n)=>R2(t,typeof e!="symbol"?e+"":e,n),Dr=class t{constructor(e,n={}){yt(this,"source"),yt(this,"inputs"),yt(this,"_prepared",null),yt(this,"_libraries",null),yt(this,"_librariesResolver",null),yt(this,"_inputMeta",null),yt(this,"_inputValues",{}),yt(this,"_explicitOverrides",new Set),yt(this,"_inputProxy",null),yt(this,"_inputMetaByKey",new Map),yt(this,"_propMeta",null),yt(this,"_propValues",{}),yt(this,"_propProxy",null),yt(this,"_declarationType",null),yt(this,"_sourcePropArgs",{}),yt(this,"_explicitPropOverrides",new Set),this.source=e,this.inputs=n,Object.defineProperty(this,"input",{get:()=>this._getInputProxy(),set:()=>{throw new Error(\'[Indicator] .input cannot be replaced \\u2014 mutate individual keys (e.g. ind.input["My Title"] = 20).\')},enumerable:!0,configurable:!1}),Object.defineProperty(this,"prop",{get:()=>this._getPropProxy(),set:()=>{throw new Error(\'[Indicator] .prop cannot be replaced \\u2014 mutate individual keys (e.g. ind.prop["initial_capital"] = 50000).\')},enumerable:!0,configurable:!1})}static from(e){return e instanceof t?e:new t(e)}prepare(e={}){if(this._prepared)return this._prepared;let n=y2(this.source,{debug:!!e.debug,ln:e.ln,libraries:this._libraries??void 0}),r=F2(n),i=n._ltfSlices,s=this;return this._prepared={fn:n,get inputs(){return s.getRuntimeInputs()},usesVisibleRange:r,ltfSlices:i},this._prepared}async resolveImports(e){if(typeof this.source!="string"||this._libraries&&this._librariesResolver===e)return;let n=await ah(this.source,e);this._libraries&&!L2(this._libraries,n)&&(this._prepared=null),this._libraries=n,this._librariesResolver=e}usesVisibleRange(){return this.prepare().usesVisibleRange}getRuntimeInputs(){let e={...this.inputs??{}};if(this._inputMeta)for(let n of this._explicitOverrides){let r=this._inputValues[n],i=this._inputMetaByKey.get(n);i&&(e[i.id]=r),this._inputMeta.some(s=>s!==i&&(s.varId===n||s.title===n))||(e[n]=r)}return e}getInputsMeta(){return this._ensureInputsScanned(),this._inputMeta}getPropsMeta(){return this._ensurePropsScanned(),this._propMeta}getRuntimePropOverrides(){let e={};if(this._propMeta)for(let n of this._explicitPropOverrides)e[n]=this._propValues[n];return e}getDeclarationType(){return this._ensurePropsScanned(),this._declarationType}_ensureInputsScanned(){if(this._inputMeta)return;this._inputMeta=x2(this.source,this._libraries??void 0);for(let n of this._inputMeta)n.type==="color"&&n.defval!==void 0&&(n.defval=s_(n.defval));let e=A2(this._inputMeta,n=>this._explicitOverrides.add(n));this._inputValues=e.values,this._inputProxy=e.proxy,this._inputMetaByKey=e.metaByKey}_getInputProxy(){return this._ensureInputsScanned(),this._inputProxy}_ensurePropsScanned(){if(this._propMeta)return;let e=N2(this.source);this._declarationType=e.type,this._sourcePropArgs=e.args,this._propMeta=T2(e.type);let n=M2(this._propMeta,this._sourcePropArgs,r=>this._explicitPropOverrides.add(r));this._propValues=n.values,this._propProxy=n.proxy}_getPropProxy(){return this._ensurePropsScanned(),this._propProxy}};function L2(t,e){let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(r=>t[r]===e[r])}function F2(t){let e=t.toString();return cN.some(n=>{let r=n.replace(/\\./g,"\\\\.");return new RegExp(`\\\\b${r}\\\\b`).test(e)})}var B2=Object.defineProperty,V2=(t,e,n)=>e in t?B2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>V2(t,typeof e!="symbol"?e+"":e,n);function Dd(t){let e=pt(t);return e?Vt(e)*1e3:864e5}var Or=class{constructor(e,n,r,i,s,a){this.source=e,this.tickerId=n,this.timeframe=r,this.limit=i,this.sDate=s,this.eDate=a,Ae(this,"data",[]),Ae(this,"open",[]),Ae(this,"high",[]),Ae(this,"low",[]),Ae(this,"close",[]),Ae(this,"volume",[]),Ae(this,"hl2",[]),Ae(this,"hlc3",[]),Ae(this,"ohlc4",[]),Ae(this,"hlcc4",[]),Ae(this,"openTime",[]),Ae(this,"closeTime",[]),Ae(this,"_readyPromise",null),Ae(this,"_ready",!1),Ae(this,"_debugSettings",{ln:!1,debug:!1}),Ae(this,"_transpiledCode",null),Ae(this,"_currentIndicator",null),Ae(this,"_isSecondaryContext",!1),Ae(this,"_syminfo"),Ae(this,"_chartTimezone",null),Ae(this,"_maxLoops",5e5),Ae(this,"_fillsOnTickGrid",!0),Ae(this,"_alertMode","realtime"),Ae(this,"_importResolver",null),Ae(this,"_viewportLeft"),Ae(this,"_viewportRight"),Ae(this,"_usesVisibleRange",!1),Ae(this,"_lastRunViewport",{}),Ae(this,"_lastResult",null),Ae(this,"_lastPineTSCode",null),this._readyPromise=this._loadData(e,n,r,i,s,a),this._readyPromise.catch(()=>{})}get transpiledCode(){return this._transpiledCode}markAsSecondary(e){this._isSecondaryContext=!0,e&&(this._importResolver=e.importResolver)}setTimezone(e){this._chartTimezone=e}setMaxLoops(e){this._maxLoops=e}setFillsOnTickGrid(e){this._fillsOnTickGrid=e}setAlertMode(e){this._alertMode=e}setImportResolver(e){this._importResolver=e==null?null:dy(e)}setVisibleRange(e,n){this._viewportLeft=e,this._viewportRight=n}usesVisibleRange(){return this._usesVisibleRange}get visibleRangeLeft(){return this._viewportLeft}get visibleRangeRight(){return this._viewportRight}async update(e){let n=e??this._lastPineTSCode;if(!n)throw new Error("pine.update(): pineTSCode is required on the first call.");let r=this._lastResult===null,i=this._viewportLeft!==this._lastRunViewport.left||this._viewportRight!==this._lastRunViewport.right;return r||this._usesVisibleRange&&i?(this._lastPineTSCode=n,this._lastRunViewport={left:this._viewportLeft,right:this._viewportRight},this._lastResult=await this.run(n),this._lastResult):this._lastResult}async _loadData(e,n,r,i,s,a){let o=await this.loadMarketData(e,n,r,i,s,a);this.data=o;let l=o.map(S=>S.open),c=o.map(S=>S.close),u=o.map(S=>S.high),h=o.map(S=>S.low),p=o.map(S=>S.volume),d=o.map(S=>(S.high+S.low+S.close)/3),f=o.map(S=>(S.high+S.low)/2),m=o.map(S=>(S.high+S.low+S.open+S.close)/4),y=o.map(S=>(S.high+S.low+S.close+S.close)/4),g=o.map(S=>S.openTime),w=Dd(this.timeframe),k=o.map(S=>S.closeTime!=null?S.closeTime:S.openTime+w);if(this.open=l,this.close=c,this.high=u,this.low=h,this.volume=p,this.hl2=f,this.hlc3=d,this.ohlc4=m,this.hlcc4=y,this.openTime=g,this.closeTime=k,e&&e.getSymbolInfo)try{this._syminfo=await e.getSymbolInfo(n)}catch(S){console.warn("Failed to get symbol info, using default values:",S)}return this._ready=!0,!0}setDebugSettings({ln:e,debug:n}){this._debugSettings.ln=e,this._debugSettings.debug=n}async loadMarketData(e,n,r,i,s,a){return Array.isArray(e)?e:e.getMarketData(n,r,i,s,a)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw new Error("PineTS is not ready");return this._readyPromise}run(e,n,r){let i=Dr.from(e);if(this._currentIndicator=i,r&&r>0){let s=typeof this.eDate>"u"&&!Array.isArray(this.source);return this._runPaginated(i,n,r,s)}else return this._runComplete(i,n)}stream(e,n={}){let{live:r=!0,interval:i=1e3}=n,s=n.pageSize||this.data.length,a=Dr.from(e);this._currentIndicator=a;let o={data:[],error:[],warning:[],alert:[]},l=!1,c=(p,...d)=>{o[p]&&o[p].forEach(f=>f(...d))},u=(p,d)=>{o[p]||(o[p]=[]),o[p].push(d)},h=()=>{l=!0};return(async()=>{try{r&&typeof this.eDate<"u"&&(this.eDate=Math.max(this.eDate,Date.now()));let p=!Array.isArray(this.source)&&r,d=this._runPaginated(a,void 0,s,p);for await(let f of d){if(l)break;if(f===null){await new Promise(m=>setTimeout(m,i));continue}if(c("data",f),f.warnings&&f.warnings.length>0){for(let m of f.warnings)c("warning",m);f.warnings.length=0}if(f.alerts&&f.alerts.length>0){for(let m of f.alerts)c("alert",m);f.alerts.length=0}if(p&&!l){let m=f.marketData[f.idx],y=m&&m.closeTime<Date.now(),g=f.idx>=f.marketData.length-1;(!y||g)&&await new Promise(w=>setTimeout(w,i))}}}catch(p){c("error",p)}})(),{on:u,stop:h}}async runPretranspiled(e,n={},r){await this.ready(),r||(r=this.data.length);let i=this._initializeContext(null,n,this._isSecondaryContext);i.pineVersion=e._pineVersion??null,this._transpiledCode=e,i.transpiledFn=e;let s=e._ltfSlices;s&&(i._ltfTruncatedBodies=s);let a=this.data.length-r,o=this.data.length;return o-a>1?(await this._executeIterations(i,e,a,o-1),i._varSnapshot=this._snapshotVarState(i),await this._executeIterations(i,e,o-1,o)):await this._executeIterations(i,e,a,o),i}async _runComplete(e,n){await this.ready(),n||(n=this.data.length),await e.resolveImports(this._importResolver);let r=e.prepare(this._debugSettings);this._usesVisibleRange=r.usesVisibleRange;let i=this._initializeContext(e.source??null,r.inputs,this._isSecondaryContext);i.pineVersion=r.fn._pineVersion??null,this._transpiledCode=r.fn,i.transpiledFn=r.fn,r.ltfSlices&&(i._ltfTruncatedBodies=r.ltfSlices);let s=this.data.length-n,a=this.data.length;return a-s>1?(await this._executeIterations(i,r.fn,s,a-1),i._varSnapshot=this._snapshotVarState(i),await this._executeIterations(i,r.fn,a-1,a)):await this._executeIterations(i,r.fn,s,a),i}async*_runPaginated(e,n,r,i=!1){await this.ready(),n||(n=this.data.length),await e.resolveImports(this._importResolver);let s=e.prepare(this._debugSettings);this._usesVisibleRange=s.usesVisibleRange;let a=this._initializeContext(e.source??null,s.inputs,this._isSecondaryContext);a.pineVersion=s.fn._pineVersion??null,this._transpiledCode=s.fn,a.transpiledFn=s.fn,s.ltfSlices&&(a._ltfTruncatedBodies=s.ltfSlices);let o=this.data.length-n,l=null;for(;;){let c=this.data.length,u=c-o;if(u>0){let m=Math.min(u,r),y=this._getResultLength(a.result),g=o+m;i&&g>=c&&m>1?(await this._executeIterations(a,this._transpiledCode,o,g-1),l=this._snapshotVarState(a),await this._executeIterations(a,this._transpiledCode,g-1,g)):i&&g>=c&&m===1?await this._executeIterations(a,this._transpiledCode,o,g):await this._executeIterations(a,this._transpiledCode,o,g),o+=m,yield this._createPageContext(a,y);continue}if(!i||Array.isArray(this.source))break;let h=Date.now(),{newCandles:p,updatedLastCandle:d}=await this._updateMarketData(),f=Date.now()-h;if(p===0&&!d){yield null;continue}if(p===0&&d&&f<1e3&&await new Promise(m=>setTimeout(m,1e3-f)),a.dataVersion++,a.length=this.data.length,this._restoreVarState(a,l),Array.isArray(a.result))a.result.pop();else if(typeof a.result=="object"&&a.result!==null)for(let m in a.result)Array.isArray(a.result[m])&&a.result[m].pop();a.data.close.data.pop(),a.data.open.data.pop(),a.data.high.data.pop(),a.data.low.data.pop(),a.data.volume.data.pop(),a.data.hl2.data.pop(),a.data.hlc3.data.pop(),a.data.ohlc4.data.pop(),a.data.hlcc4.data.pop(),a.data.openTime.data.pop(),a.data.closeTime&&a.data.closeTime.data.pop(),a.data.bar_index.data.pop(),o=this.data.length-(p+1),a.rollbackDrawings(o),p>0&&(l=null),a.pine.barstate.setLive()}}_getResultLength(e){if(Array.isArray(e))return e.length;if(typeof e=="object"&&e!==null){let n=Object.keys(e);if(n.length>0&&Array.isArray(e[n[0]]))return e[n[0]].length}return 0}_createPageContext(e,n){let r=new Di({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,fullContext:e,inputs:e.inputs});if(r.pineTSCode=e.pineTSCode,r.idx=e.idx,Array.isArray(e.result))r.result=e.result.slice(n);else if(typeof e.result=="object"&&e.result!==null){r.result={};for(let i in e.result)Array.isArray(e.result[i])?r.result[i]=e.result[i].slice(n):r.result[i]=e.result[i]}else r.result=e.result;return r.plots={...e.plots},r.warnings=e.warnings,r.alerts=e.alerts,r}async _updateMarketData(e){if(Array.isArray(this.source))return{newCandles:0,updatedLastCandle:!1};let n=this.source,r=this.data.length-1,i=this.data[r].openTime;try{let s=await n.getMarketData(this.tickerId,this.timeframe,void 0,i,e);if(!s||s.length===0)return{newCandles:0,updatedLastCandle:!1};let a=!1,o=0;for(let l=0;l<s.length;l++){let c=s[l];c.openTime===i?(this._replaceCandle(r,c),a=!0):c.openTime>i&&(this._appendCandle(c),o++)}return{newCandles:o,updatedLastCandle:a}}catch(s){return console.error("Error updating market data:",s),{newCandles:0,updatedLastCandle:!1}}}_replaceCandle(e,n){this.data[e]=n,this.open[e]=n.open,this.close[e]=n.close,this.high[e]=n.high,this.low[e]=n.low,this.volume[e]=n.volume,this.hl2[e]=(n.high+n.low)/2,this.hlc3[e]=(n.high+n.low+n.close)/3,this.ohlc4[e]=(n.high+n.low+n.open+n.close)/4,this.hlcc4[e]=(n.high+n.low+n.close+n.close)/4,this.openTime[e]=n.openTime,this.closeTime[e]=this._closeTimeOf(n)}_closeTimeOf(e){return e.closeTime!=null?e.closeTime:e.openTime+Dd(this.timeframe)}_appendCandle(e){this.data.push(e),this.open.push(e.open),this.close.push(e.close),this.high.push(e.high),this.low.push(e.low),this.volume.push(e.volume),this.hl2.push((e.high+e.low)/2),this.hlc3.push((e.high+e.low+e.close)/3),this.ohlc4.push((e.high+e.low+e.open+e.close)/4),this.hlcc4.push((e.high+e.low+e.close+e.close)/4),this.openTime.push(e.openTime),this.closeTime.push(this._closeTimeOf(e))}async updateTail(e){if(this.data.length===0||Array.isArray(this.source))return!1;let{newCandles:n,updatedLastCandle:r}=await this._updateMarketData();if(n===0&&!r)return!1;let i=e._varSnapshot;i?(this._restoreVarState(e,i),this._popLastBar(e)):this._removeLastResult(e),e.dataVersion=(e.dataVersion||0)+1,e.length=this.data.length;let s=this.data.length-(n+1);e.rollbackDrawings(s);let a=this.data.length;return s<a-1?(await this._executeIterations(e,this._transpiledCode,s,a-1),e._varSnapshot=this._snapshotVarState(e),await this._executeIterations(e,this._transpiledCode,a-1,a)):await this._executeIterations(e,this._transpiledCode,s,a),!0}_popLastBar(e){if(Array.isArray(e.result))e.result.pop();else if(typeof e.result=="object"&&e.result!==null)for(let n in e.result)Array.isArray(e.result[n])&&e.result[n].pop();e.data.close.data.pop(),e.data.open.data.pop(),e.data.high.data.pop(),e.data.low.data.pop(),e.data.volume.data.pop(),e.data.hl2.data.pop(),e.data.hlc3.data.pop(),e.data.ohlc4.data.pop(),e.data.hlcc4.data.pop(),e.data.openTime.data.pop(),e.data.closeTime&&e.data.closeTime.data.pop(),e.data.bar_index.data.pop()}_removeLastResult(e){this._popLastBar(e);let n=["const","var","let","params"],r=i=>{for(let s of n)if(i[s])for(let a in i[s]){let o=i[s][a];o instanceof _?o.data.pop():Array.isArray(o)&&o.pop()}};r(e),e.lctx&&e.lctx.forEach(i=>r(i))}_snapshotVarState(e){let n=["const","var","let","params"],r={main:{},lctx:[]},i=s=>{let a={};for(let o of n)if(s[o]){a[o]={};for(let l in s[o]){let c=s[o][l];if(c instanceof _){let u=c.data.length,h=u>0?c.data[u-1]:void 0;a[o][l]={len:u,lastVal:h}}}}return a};if(r.main=i(e),e.lctx){let s=[];e.lctx.forEach(a=>s.push(i(a))),r.lctx=s}return r.strategy=YE(e.strategy),r.resultLength=this._getResultLength(e.result),r.dataLength=e.data.close?.data?.length??0,r}_restoreVarState(e,n){if(!n)return;let r=["const","var","let","params"],i=(s,a)=>{for(let o of r)if(!(!a[o]||!s[o]))for(let l in a[o]){let c=s[o][l],u=a[o][l];c instanceof _&&u&&typeof u.len=="number"&&(c.data.length>u.len&&(c.data.length=u.len),u.len>0&&u.lastVal!==void 0&&!c.varip&&(c.data[u.len-1]=u.lastVal))}};if(i(e,n.main),e.lctx&&n.lctx){let s=0;e.lctx.forEach(a=>{n.lctx[s]&&i(a,n.lctx[s]),s++})}XE(e.strategy,n.strategy)}_initializeContext(e,n={},r=!1){let i=new Di({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,inputs:n});i.pine.syminfo=ed(this._syminfo);let s=Yr(String(this.tickerId??"")).modifier;return i.chartStyle=s==="heikinashi"?"heikinashi":"standard",this._syminfo&&s==="heikinashi"&&(i.pine.syminfo=ed({...this._syminfo,tickerid:yf(String(this._syminfo.tickerid??this.tickerId),"heikinashi")})),this._chartTimezone&&(i.chartTimezone=this._chartTimezone),i.viewportLeft=this._viewportLeft,i.viewportRight=this._viewportRight,i.__maxLoops=this._maxLoops,i._alertMode=this._alertMode,i._fillsOnTickGrid=this._fillsOnTickGrid,i.importResolver=this._importResolver,i._propOverrides=this._currentIndicator?.getRuntimePropOverrides()??{},i.pineTSCode=e,i.isSecondaryContext=r,i.data.close=new _([]),i.data.open=new _([]),i.data.high=new _([]),i.data.low=new _([]),i.data.volume=new _([]),i.data.hl2=new _([]),i.data.hlc3=new _([]),i.data.ohlc4=new _([]),i.data.hlcc4=new _([]),i.data.openTime=new _([]),i.data.closeTime=new _([]),i.length=this.data.length,i}async _processBarWithOrderFills(e,n,r){let i=e.strategy,s=e.data,a=s.close.data.length-1,o={open:s.open.data[a],high:s.high.data[a],low:s.low.data[a],close:s.close.data[a]},l=r??o,c=(p,d,f,m)=>{s.open.data[a]=p,s.high.data[a]=d,s.low.data[a]=f,s.close.data[a]=m},u=jn(o.open,o.high,o.low,o.close),h=null;for(let p=0;p<u.length;p++){let d=p===0?u[0]:u[p-1],f=u[p];c(d,Math.max(d,f),Math.min(d,f),f);let m=i._fillCount??0;e._excSeg=p===0?{offset:0,scale:0}:{offset:p-1,scale:1/3},Pp(e),e._excSeg=void 0;for(let w of i.opentrades)w._intrabarEntry?.bar===e.idx&&(w._intrabarEntry=void 0);if(p===u.length-1||(i._fillCount??0)===m)continue;c(l.open,l.high,l.low,l.close),h||(h=this._snapshotVarState(e),h.strategy=null);let y=new Map(Object.entries(e.plots??{}).map(([w,k])=>[w,k?.data?.length??0])),g=new Set(i.pending_orders);e._execTick=(e._execTick||0)+1,e._fillPointPrice=f,await n(e),e._fillPointPrice=void 0;for(let w of i.pending_orders)!g.has(w)&&w.bar===e.idx&&(w.bar=e.idx-1);for(let w of Object.keys(e.plots??{})){let k=y.get(w);k===void 0?delete e.plots[w]:e.plots[w]?.data?.length>k&&(e.plots[w].data.length=k)}e.rollbackDrawings(e.idx),this._restoreVarState(e,h)}c(o.open,o.high,o.low,o.close),h&&(e._execTick=(e._execTick||0)+1)}_snapBarForBroker(e){if(!this._fillsOnTickGrid||!e.strategy)return null;let n=e.pine?.syminfo?.mintick;if(!n||n<=0)return null;let r=e.data,i=r.close.data.length-1,s={open:r.open.data[i],high:r.high.data[i],low:r.low.data[i],close:r.close.data[i]},a={open:Er(s.open,n),high:Er(s.high,n),low:Er(s.low,n),close:Er(s.close,n)};return a.open===s.open&&a.high===s.high&&a.low===s.low&&a.close===s.close?null:(this._setBar(e,a),e._rawBar=s,s)}_restoreRawBar(e,n){this._setBar(e,n),e._rawBar=void 0}_setBar(e,n){let r=e.data,i=r.close.data.length-1;r.open.data[i]=n.open,r.high.data[i]=n.high,r.low.data[i]=n.low,r.close.data[i]=n.close}async _executeIterations(e,n,r,i){let s=["const","var","let","params"];for(let a=r;a<i;a++){if(e.idx=a,e._execTick=(e._execTick||0)+1,e.data.close.data.push(this.close[a]),e.data.open.data.push(this.open[a]),e.data.high.data.push(this.high[a]),e.data.low.data.push(this.low[a]),e.data.volume.data.push(this.volume[a]),e.data.hl2.data.push(this.hl2[a]),e.data.hlc3.data.push(this.hlc3[a]),e.data.ohlc4.data.push(this.ohlc4[a]),e.data.hlcc4.data.push(this.hlcc4[a]),e.data.openTime.data.push(this.openTime[a]),e.data.closeTime.data.push(this.closeTime[a]),e.data.bar_index.data.push(a),e.strategy){let c=this._snapBarForBroker(e);Df(e),ME(e),zE(e),e.strategy.config?.calc_on_order_fills?await this._processBarWithOrderFills(e,n,c):Pp(e),qE(e),c&&this._restoreRawBar(e,c)}let o=await n(e);if(e.strategy){let c=this._snapBarForBroker(e);Cp(e),e.strategy._pending_close_mc||ts(e,"close"),Cp(e),kE(e),c&&this._restoreRawBar(e,c)}if(typeof o=="object"){typeof e.result!="object"&&(e.result={});for(let c in o){e.result[c]===void 0&&(e.result[c]=[]);let u;o[c]instanceof _?u=o[c].get(0):Array.isArray(o[c])?u=o[c][o[c].length-1]:u=o[c],e.result[c].push(u)}}else Array.isArray(e.result)||(e.result=[]),e.result.push(o);for(let c of e._drawingHelpers)c.syncToPlot&&c.syncToPlot();let l=c=>{for(let u of s)if(c[u])for(let h in c[u]){let p=c[u][h];if(p instanceof _){let d=p.get(0);p.data.push(d)}else if(Array.isArray(p)){let d=p[p.length-1];p.push(d)}}};l(e),e.lctx&&e.lctx.forEach(c=>l(c))}e.strategy&&UE(e)}},fy=t=>t.unit==="D"||t.unit==="W"||t.unit==="M",oh=t=>fy(t)&&!(t.unit==="D"&&t.multiplier===1);function $2(t,e){let n=pt(t);if(!n)return null;if(oh(n))return e.has("D")?"D":null;let r=Vt(n),i=null,s=0;for(let a of e){let o=pt(a);if(!o||fy(o))continue;let l=Vt(o);l<r&&r%l===0&&l>s&&(i=a,s=l)}return i}function my(t,e){let n=pt(t),r=pt(e);return!n||!r||oh(n)?1/0:Vt(n)/Vt(r)}function z2(t,e){let n=pt(t),r=pt(e);return!n||!r?1:Vt(n)/Vt(r)}function j2(t,e,n,r={}){if(t.length===0)return[];let i=pt(e);if(!i)return[];if(r.calendarGrid||oh(i))return q2(t,i,!!r.calendarGrid);let s=my(e,n);return U2(t,s)}function q2(t,e,n){let r=[],i=[],s=NaN,a=()=>{let o=Yc(i);n&&(o.openTime=s,o.closeTime=Zx(s,e)),r.push(o)};for(let o of t){let l=ms(o.openTime,e);i.length>0&&l!==s&&(a(),i=[]),s=l,i.push(o)}return i.length>0&&a(),r}function U2(t,e){if(t.length===0)return[];let n=[],r=[t[0]],i=W2(t),s=i>0?i*1.5:0;for(let a=1;a<t.length;a++){let o=t[a].openTime-t[a-1].openTime;(s>0&&o>s||r.length>=e)&&(n.push(Yc(r)),r=[]),r.push(t[a])}return r.length>0&&n.push(Yc(r)),n}function Yc(t){let e=t[0],n=t[t.length-1],r=e.high,i=e.low,s=0,a=0,o=0,l=0,c=0;for(let u=0;u<t.length;u++){let h=t[u];h.high>r&&(r=h.high),h.low<i&&(i=h.low),s+=h.volume,a+=h.quoteAssetVolume,o+=h.numberOfTrades,l+=h.takerBuyBaseAssetVolume,c+=h.takerBuyQuoteAssetVolume}return{openTime:e.openTime,open:e.open,high:r,low:i,close:n.close,volume:s,closeTime:n.closeTime,quoteAssetVolume:a,numberOfTrades:o,takerBuyBaseAssetVolume:l,takerBuyQuoteAssetVolume:c,ignore:0}}function W2(t){if(t.length<2)return 0;let e=Math.min(t.length-1,20),n=1/0;for(let r=0;r<e;r++){let i=t[r+1].openTime-t[r].openTime;i>0&&i<n&&(n=i)}return n===1/0?0:n}var H2=Object.defineProperty,G2=(t,e,n)=>e in t?H2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sa=(t,e,n)=>G2(t,typeof e!="symbol"?e+"":e,n);function K2(t){return Rl(t)??t}var Ts=class{constructor(e){sa(this,"_configured"),sa(this,"_requiresApiKey"),sa(this,"_providerName"),sa(this,"_aggregationSubTimeframe",null),this._requiresApiKey=e.requiresApiKey,this._providerName=e.providerName,this._configured=!e.requiresApiKey}ensureConfigured(){if(!this._configured)throw new Error(`${this._providerName} requires configuration before use. Call Provider.${this._providerName}.configure({ apiKey: \'...\' }) or instantiate directly: new ${this._providerName}Provider({ apiKey: \'...\' })`)}configure(e){this._configured=!0}get isConfigured(){return this._configured}normalizeCloseTime(e){Qx(e)}setAggregationSubTimeframe(e){this._aggregationSubTimeframe=e}getSupportedTimeframes(){return new Set(["1S","5S","10S","15S","30S","1","3","5","15","30","45","60","120","180","240","D","W","M"])}aggregatesOnCalendarGrid(){return!1}async getMarketData(e,n,r,i,s){e=Tr(e);let a=K2(n),o=this.getSupportedTimeframes();if(o.has(a))return this._getMarketDataNative(e,a,r,i,s);let l=this._aggregationSubTimeframe,c=l&&o.has(l)?l:$2(a,o);if(!c)return console.error(`${this._providerName}: Timeframe \'${n}\' is not supported and no valid sub-timeframe found for aggregation.`),[];let u=this._computeSubLimit(a,c,r),h=this.aggregatesOnCalendarGrid(),p=pt(a),d=h&&i!==void 0&&p?ms(i,p):i,f=await this._getMarketDataNative(e,c,u,d,s);if(f.length===0)return[];let m=j2(f,a,c,{calendarGrid:h});return r&&r>0&&m.length>r?m.slice(m.length-r):m}_computeSubLimit(e,n,r){if(!r)return;let i=my(e,n);if(i===1/0){let s=z2(e,n);return Math.ceil(r*s)+2*Math.ceil(s)}return Math.ceil(r*i)+Math.ceil(i)}},Y2=Object.defineProperty,X2=(t,e,n)=>e in t?Y2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,so=(t,e,n)=>X2(t,typeof e!="symbol"?e+"":e,n),kl="https://api.binance.com/api/v3",Od="https://api.binance.us/api/v3",Al={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"},Xc=class{constructor(e=300*1e3){so(this,"cache"),so(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter(([n,r])=>r!==void 0).map(([n,r])=>`${n}:${r}`).join("|")}get(e){let n=this.generateKey(e),r=this.cache.get(n);return r?Date.now()-r.timestamp>this.cacheDuration?(this.cache.delete(n),null):r.data:null}set(e,n){let r=this.generateKey(e);this.cache.set(r,{data:n,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){let e=Date.now();for(let[n,r]of this.cache.entries())e-r.timestamp>this.cacheDuration&&this.cache.delete(n)}},Zc=class extends Ts{constructor(){super({requiresApiKey:!1,providerName:"Binance"}),so(this,"cacheManager"),so(this,"activeApiUrl",null),this.cacheManager=new Xc(300*1e3)}async getBaseUrl(){if(this.activeApiUrl)return this.activeApiUrl;try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${kl}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=kl,this.activeApiUrl}catch{}try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${Od}/ping`,{signal:e.signal});if(clearTimeout(n),r.ok)return this.activeApiUrl=Od,this.activeApiUrl}catch{}return kl}async _fetchRawChunk(e,n,r,i,s){let a=Al[n.toUpperCase()];if(!a)return console.error(`Unsupported timeframe: ${n}`),[];let o=`${await this.getBaseUrl()}/klines?symbol=${e}&interval=${a}`;r&&(o+=`&limit=${Math.min(r,1e3)}`),i&&(o+=`&startTime=${i}`),s&&(o+=`&endTime=${s}`);let l=await fetch(o);if(!l.ok)throw new Error(`HTTP error! status: ${l.status}`);return(await l.json()).map(c=>({openTime:parseInt(c[0]),open:parseFloat(c[1]),high:parseFloat(c[2]),low:parseFloat(c[3]),close:parseFloat(c[4]),volume:parseFloat(c[5]),closeTime:parseInt(c[6]),quoteAssetVolume:parseFloat(c[7]),numberOfTrades:parseInt(c[8]),takerBuyBaseAssetVolume:parseFloat(c[9]),takerBuyQuoteAssetVolume:parseFloat(c[10]),ignore:c[11]}))}async getMarketDataInterval(e,n,r,i){try{let s=Al[n.toUpperCase()];if(!s)return console.error(`Unsupported timeframe: ${n}`),[];let a=[],o=r,l=i,c=Jx[s];if(!c)return console.error(`Duration not defined for interval: ${s}`),[];for(;o<l;){let u=Math.min(o+1e3*c,l),h=await this._fetchRawChunk(e,n,1e3,o,u);if(h.length===0){let[p]=await this._fetchRawChunk(e,n,1,o);if(!p||p.openTime>=l||p.openTime<=o)break;o=p.openTime;continue}a=a.concat(h),o=h[h.length-1].closeTime+1}return this.normalizeCloseTime(a),a}catch(s){return console.error("Error in getMarketDataInterval:",s),[]}}async getMarketDataBackwards(e,n,r,i){let s=r,a=[],o=i,l=0,c=Math.ceil(r/1e3)+5;for(;s>0&&l<c;){l++;let u=Math.min(s,1e3),h=await this._fetchRawChunk(e,n,u,void 0,o);if(h.length===0||(a=h.concat(a),s-=h.length,o=h[0].openTime-1,h.length<u))break}return this.normalizeCloseTime(a),a}getSupportedTimeframes(){return new Set(["1","3","5","15","30","60","120","240","D","W","M"])}aggregatesOnCalendarGrid(){return!0}async _getMarketDataNative(e,n,r,i,s){try{let a=s!==void 0,o={tickerId:e,timeframe:n,limit:r,sDate:i,eDate:s};if(a){let c=this.cacheManager.get(o);if(c)return c}if(!Al[n.toUpperCase()])return console.error(`Unsupported timeframe: ${n}`),[];if(this.shouldPaginate(r,i,s)){if(i&&s){let c=await this.getMarketDataInterval(e,n,i,s),u=r?c.slice(0,r):c;return this.cacheManager.set(o,u),u}else if(r&&r>1e3){let c=await this.getMarketDataBackwards(e,n,r,s);return this.cacheManager.set(o,c),c}}let l=await this._fetchRawChunk(e,n,r,i,s);return this.normalizeCloseTime(l),a&&this.cacheManager.set(o,l),l}catch(a){return console.error("Error in binance.klines:",a),[]}}shouldPaginate(e,n,r){return e&&e>1e3?!0:!!(n&&r)}async getSymbolInfo(e){e=Tr(e);try{let n="crypto",r=await this.getBaseUrl(),i=e,s="";e.endsWith(".P")?(n="futures",i=e.replace(".P",""),r="https://fapi.binance.com/fapi/v1",s="Perpetual"):e.includes("_")&&(n="futures",i=e,r="https://dapi.binance.com/dapi/v1",s="Delivery");let a=n==="crypto"?`${r}/exchangeInfo?symbol=${i}`:`${r}/exchangeInfo`,o=await fetch(a);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);let l=(await o.json()).symbols;if(!l||l.length===0)return console.error(`Symbol ${e} not found`),null;let c=n==="futures"?l.find(k=>k.symbol===i):l[0];if(!c)return console.error(`Symbol ${i} not found in exchange info`),null;let u=c.filters?.find(k=>k.filterType==="PRICE_FILTER"),h=c.filters?.find(k=>k.filterType==="LOT_SIZE"),p=u?parseFloat(u.tickSize):.01,d=h?parseFloat(h.minQty):0,f=Math.round(1/p),m=c.baseAsset,y=c.quoteAsset,g=s?` ${s}`:"",w=`${m} / ${y}${g}`;return{ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",root:e,description:w,type:n,main_tickerid:`BINANCE:${e}`,current_contract:s,isin:"",basecurrency:m,currency:y,timezone:"Etc/UTC",country:"",mintick:p,pricescale:f,minmove:1,pointvalue:c.contractSize||1,mincontract:d,session:"regular",volumetype:"base",expiration_date:c.deliveryDate||NaN,employees:NaN,industry:"",sector:"",shareholders:NaN,shares_outstanding_float:NaN,shares_outstanding_total:NaN,recommendations_buy:NaN,recommendations_buy_strong:NaN,recommendations_date:NaN,recommendations_hold:NaN,recommendations_sell:NaN,recommendations_sell_strong:NaN,recommendations_total:NaN,target_price_average:NaN,target_price_date:NaN,target_price_estimates:NaN,target_price_high:NaN,target_price_low:NaN,target_price_median:NaN}}catch(n){return console.error("Error in binance.exchangeInfo:",n),null}}},Z2=Object.defineProperty,J2=(t,e,n)=>e in t?Z2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,es=(t,e,n)=>J2(t,typeof e!="symbol"?e+"":e,n),Q2="https://financialmodelingprep.com",Rd=new Set(["USD","EUR","GBP","JPY","CHF","AUD","CAD","NZD","SEK","NOK","DKK","SGD","HKD","KRW","MXN","ZAR","TRY","BRL","INR","CNY","PLN","CZK","HUF","ILS","THB","TWD","PHP","IDR","MYR","RUB","CLP","COP"]),Ld={"1D":{endpoint:"/stable/historical-price-eod/full",type:"daily"},D:{endpoint:"/stable/historical-price-eod/full",type:"daily"},1:{endpoint:"/stable/historical-chart/1min",interval:"1min",type:"intraday"},5:{endpoint:"/stable/historical-chart/5min",interval:"5min",type:"intraday"},15:{endpoint:"/stable/historical-chart/15min",interval:"15min",type:"intraday"},30:{endpoint:"/stable/historical-chart/30min",interval:"30min",type:"intraday"},60:{endpoint:"/stable/historical-chart/1hour",interval:"1hour",type:"intraday"},240:{endpoint:"/stable/historical-chart/4hour",interval:"4hour",type:"intraday"},"4H":{endpoint:"/stable/historical-chart/4hour",interval:"4hour",type:"intraday"}},Fd={NASDAQ:"America/New_York",NYSE:"America/New_York",AMEX:"America/New_York",NYSEArca:"America/New_York",BATS:"America/New_York",OTC:"America/New_York",PNK:"America/New_York",TSX:"America/Toronto",TSXV:"America/Toronto",LSE:"Europe/London",EURONEXT:"Europe/Paris",XETRA:"Europe/Berlin",JPX:"Asia/Tokyo",HKSE:"Asia/Hong_Kong",SSE:"Asia/Shanghai",SHZ:"Asia/Shanghai",ASX:"Australia/Sydney",NSE:"Asia/Kolkata",BSE:"Asia/Kolkata",KRX:"Asia/Seoul",CRYPTO:"Etc/UTC"},Bd={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",NYSEArca:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",PNK:"0930-1600",TSX:"0930-1600",TSXV:"0930-1600",LSE:"0800-1630",EURONEXT:"0900-1730",XETRA:"0900-1730",JPX:"0900-1530",HKSE:"0930-1600",SSE:"0930-1500",SHZ:"0930-1500",ASX:"1000-1600",NSE:"0915-1530",BSE:"0915-1530",KRX:"0900-1530",CRYPTO:"24x7"},eM={daily:{periodType:"day",multiplier:1},"1min":{periodType:"minute",multiplier:1},"5min":{periodType:"minute",multiplier:5},"15min":{periodType:"minute",multiplier:15},"30min":{periodType:"minute",multiplier:30},"1hour":{periodType:"hour",multiplier:1},"4hour":{periodType:"hour",multiplier:4}},Jc=class extends Ts{constructor(e){super({requiresApiKey:!0,providerName:"FMP"}),es(this,"_apiKey",null),es(this,"_baseUrl",Q2),es(this,"_profileCache",new Map),es(this,"_symbolInfoCache",new Map),es(this,"_mintickCache",new Map),e?.apiKey&&this.configure(e)}configure(e){super.configure(e),this._apiKey=e.apiKey,e.baseUrl&&(this._baseUrl=e.baseUrl)}getSupportedTimeframes(){return new Set(["1","5","15","30","60","240","D"])}async _getMarketDataNative(e,n,r,i,s){this.ensureConfigured();try{let a=n.toUpperCase(),o=Ld[a]||Ld[n];if(!o)return console.error(`FMP: Unsupported timeframe: ${n}`),[];let l;if(o.type==="intraday"?l=await this._fetchIntradayData(e,o.endpoint,o.interval,i,s,r):l=await this._fetchDailyData(e,i,s,r),l.length>0&&!this._mintickCache.has(e)){let c=this._estimateMintick(l);c!==void 0&&this._mintickCache.set(e,c)}return l}catch(a){return console.error("Error in FMPProvider.getMarketData:",a),[]}}async _fetchDailyData(e,n,r,i){let s=`${this._baseUrl}/stable/historical-price-eod/full?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`;n&&(s+=`&from=${this._msToDateStr(n)}`),r&&(s+=`&to=${this._msToDateStr(r)}`);let a=await fetch(s);if(!a.ok){let h=await a.text();throw new Error(`FMP HTTP ${a.status}: ${h}`)}let o=await a.json();if(!Array.isArray(o)||o.length===0)return[];o.reverse();let l=i&&i>0&&i<o.length?o.slice(o.length-i):o,{session:c,timezone:u}=await this._resolveSessionInfo(e);return l.map(h=>{let p=this._dateStrToMs(h.date),d=np(p,c,u,"day");return{openTime:p,open:h.open,high:h.high,low:h.low,close:h.close,volume:h.volume,closeTime:d,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async _fetchIntradayData(e,n,r,i,s,a){let o=`${this._baseUrl}${n}?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`;i&&(o+=`&from=${this._msToDateStr(i)}`),s&&(o+=`&to=${this._msToDateStr(s)}`);let l=await fetch(o);if(!l.ok){let m=await l.text();if(l.status===403||m.includes("Restricted Endpoint"))return console.error(`FMP: Intraday data (${r}) requires a paid plan. Use daily timeframe (\'D\') with a free API key, or upgrade at https://financialmodelingprep.com/`),[];throw new Error(`FMP HTTP ${l.status}: ${m}`)}let c=await l.json();if(!Array.isArray(c)||c.length===0)return[];c.reverse();let u=a&&a>0&&a<c.length?c.slice(c.length-a):c,{periodType:h,multiplier:p}=eM[r]||{periodType:"minute",multiplier:1},{session:d,timezone:f}=await this._resolveSessionInfo(e);return u.map(m=>{let y=this._dateTimeStrToMs(m.date),g=np(y,d,f,h,p);return{openTime:y,open:m.open,high:m.high,low:m.low,close:m.close,volume:m.volume,closeTime:g,quoteAssetVolume:0,numberOfTrades:0,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}})}async getSymbolInfo(e){if(this.ensureConfigured(),e=Tr(e),this._symbolInfoCache.has(e))return this._symbolInfoCache.get(e);try{let n=await this._fetchProfile(e),r="stock";n?.isEtf?r="etf":n?.isFund?r="fund":this._isForex(e)?r="forex":this._isCrypto(e)&&(r="crypto");let i=n?.exchange||(r==="crypto"?"CRYPTO":r==="forex"?"FX":""),s=r==="crypto"||r==="forex"?"Etc/UTC":Fd[i]||"America/New_York",a=r==="crypto"?"24x7":r==="forex"?"0000-0000":Bd[i]||"0930-1600",o=n?.currency||(this._isForex(e)?e.slice(3,6):"USD"),l=this._isForex(e)?e.slice(0,3):n?.currency||"USD",c=this._mintickCache.get(e)??.01,u=Math.round(1/c),h=Math.round(c*u),p={ticker:n?.symbol||e,tickerid:`${i}:${n?.symbol||e}`,prefix:i,root:n?.symbol||e,description:n?.companyName||e,type:r,main_tickerid:`${i}:${n?.symbol||e}`,current_contract:"",isin:n?.isin||"",basecurrency:l,currency:o,timezone:s,country:n?.country||"",mintick:c,pricescale:u,minmove:h,pointvalue:1,mincontract:0,session:a,volumetype:"base",expiration_date:0,employees:n&&parseInt(n.fullTimeEmployees)||0,industry:n?.industry||"",sector:n?.sector||"",shareholders:0,shares_outstanding_float:0,shares_outstanding_total:0,recommendations_buy:0,recommendations_buy_strong:0,recommendations_date:0,recommendations_hold:0,recommendations_sell:0,recommendations_sell_strong:0,recommendations_total:0,target_price_average:0,target_price_date:0,target_price_estimates:0,target_price_high:0,target_price_low:0,target_price_median:0};return this._mintickCache.has(e)&&this._symbolInfoCache.set(e,p),p}catch(n){return console.error("Error in FMPProvider.getSymbolInfo:",n),null}}_estimateMintick(e){let n=[];for(let o=0;o<e.length;o++){let l=e[o],c=Math.abs(l.close-l.open),u=Math.abs(l.high-l.low);if(c>0&&n.push(c),u>0&&n.push(u),o>0){let h=Math.abs(l.close-e[o-1].close);h>0&&n.push(h)}}if(n.length===0)return;let r=Math.min(...n),i=Math.floor(Math.log10(r)),s=r/10**i,a=(Math.floor(s+1e-12)<5?1:10)*10**i;return a>=1?.01:a}async _fetchProfile(e){if(this._profileCache.has(e))return this._profileCache.get(e);let n=`${this._baseUrl}/stable/profile?symbol=${encodeURIComponent(e)}&apikey=${this._apiKey}`,r=await fetch(n);if(!r.ok)return null;let i=await r.json();if(!Array.isArray(i)||i.length===0)return null;let s=i[0];return this._profileCache.set(e,s),s}async _resolveSessionInfo(e){try{let n=await this._fetchProfile(e);if(n){let r=n.exchange||"",i=this._isCrypto(e),s=i?"Etc/UTC":Fd[r]||"America/New_York";return{session:i?"24x7":Bd[r]||"0930-1600",timezone:s}}}catch{}return{session:"0930-1600",timezone:"America/New_York"}}_msToDateStr(e){return new Date(e).toISOString().split("T")[0]}_dateStrToMs(e){return new Date(e+"T00:00:00Z").getTime()}_dateTimeStrToMs(e){return new Date(e.replace(" ","T")+"Z").getTime()}_isForex(e){return/^[A-Z]{6}$/.test(e)&&Rd.has(e.slice(0,3))&&Rd.has(e.slice(3,6))}_isCrypto(e){return this._isForex(e)?!1:/^[A-Z]+(USD|USDT|BTC|ETH)$/.test(e)&&e.length<=15}},tM=Object.defineProperty,nM=(t,e,n)=>e in t?tM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qr=(t,e,n)=>nM(t,typeof e!="symbol"?e+"":e,n),rM="https://data.alpaca.markets",iM="https://paper-api.alpaca.markets/v2",sM="https://api.alpaca.markets/v2",Tl=1e4,Vd={1:"1Min",3:"3Min",5:"5Min",15:"15Min",30:"30Min",60:"1Hour",120:"2Hour",240:"4Hour","4H":"4Hour","1D":"1Day",D:"1Day","1W":"1Week",W:"1Week","1M":"1Month",M:"1Month"},aM={NASDAQ:"America/New_York",NYSE:"America/New_York",AMEX:"America/New_York",ARCA:"America/New_York",BATS:"America/New_York",OTC:"America/New_York",CRYPTO:"Etc/UTC"},oM={NASDAQ:"0930-1600",NYSE:"0930-1600",AMEX:"0930-1600",ARCA:"0930-1600",BATS:"0930-1600",OTC:"0930-1600",CRYPTO:"24x7"},lM={Min:"minute",Hour:"hour",Day:"day",Week:"week",Month:"month"},Qc=class extends Ts{constructor(e){super({requiresApiKey:!0,providerName:"Alpaca"}),qr(this,"_apiKey",null),qr(this,"_apiSecret",null),qr(this,"_dataUrl",rM),qr(this,"_tradingUrl",iM),qr(this,"_feed",null),qr(this,"_assetCache",new Map),qr(this,"_calendarCache",new Map),e?.apiKey&&e?.apiSecret&&this.configure(e)}configure(e){super.configure(e),this._apiKey=e.apiKey,this._apiSecret=e.apiSecret,e.feed&&(this._feed=e.feed),e.dataUrl&&(this._dataUrl=e.dataUrl),e.tradingUrl?this._tradingUrl=e.tradingUrl:e.paper===!1&&(this._tradingUrl=sM)}_headers(){return{"APCA-API-KEY-ID":this._apiKey,"APCA-API-SECRET-KEY":this._apiSecret}}getSupportedTimeframes(){return new Set(["1","3","5","15","30","45","60","120","180","240","D","W","M"])}async _getMarketDataNative(e,n,r,i,s){this.ensureConfigured();try{let a=this._resolveTimeframe(n);if(!a)return console.error(`Alpaca: Unsupported timeframe: ${n}`),[];let o=this._isCrypto(e),l=await this._fetchAllBars(e,a,o,i,s,r);if(l.length===0)return[];let{periodType:c,multiplier:u}=this._parseAlpacaTimeframe(a);if(o)return this._convertBarsCrypto(l,c,u);let h=l[0].t.slice(0,10),p=l[l.length-1].t.slice(0,10),d=this._addDaysToDate(p,40);return await this._ensureCalendar(h,d),this._convertBarsStock(l,c,u)}catch(a){return console.error("Error in AlpacaProvider.getMarketData:",a),[]}}async _fetchAllBars(e,n,r,i,s,a){let o=[],l=null,c=a||1/0,u=Math.min(a||Tl,Tl);do{let h=this._buildBarsUrl(e,n,r,i,s,u,l),p=await fetch(h,{headers:this._headers()});if(!p.ok){let m=await p.text();throw new Error(`Alpaca HTTP ${p.status}: ${m}`)}let d=await p.json(),f=Object.keys(d.bars||{})[0];if(!f||!d.bars[f]||(o.push(...d.bars[f]),l=d.next_page_token,o.length>=c))break}while(l);return a&&a>0&&o.length>a?o.slice(0,a):o}_buildBarsUrl(e,n,r,i,s,a,o){let l=r?`${this._dataUrl}/v1beta3/crypto/us/bars`:`${this._dataUrl}/v2/stocks/bars`,c=new URLSearchParams;return c.set("symbols",e),c.set("timeframe",n),c.set("sort","asc"),i&&c.set("start",new Date(i).toISOString()),s&&c.set("end",new Date(s).toISOString()),a&&c.set("limit",String(Math.min(a,Tl))),o&&c.set("page_token",o),!r&&this._feed&&c.set("feed",this._feed),`${l}?${c.toString()}`}async getSymbolInfo(e){this.ensureConfigured(),e=Tr(e);try{let n=await this._fetchAsset(e);if(!n)return console.error(`Alpaca: Symbol ${e} not found`),null;let r=n.exchange||"",i=n.class==="crypto",s=i?"Etc/UTC":aM[r]||"America/New_York",a=i?"24x7":oM[r]||"0930-1600",o="stock";i&&(o="crypto");let l=i&&e.split("/")[1]||"USD",c=i?e.split("/")[0]||e:l,u=n.price_increment?parseFloat(n.price_increment):.01,h=Math.round(1/u);return{ticker:n.symbol,tickerid:`${r}:${n.symbol}`,prefix:r,root:i?e.split("/")[0]:n.symbol,description:n.name||n.symbol,type:o,main_tickerid:`${r}:${n.symbol}`,current_contract:"",isin:"",basecurrency:c,currency:l,timezone:s,country:i?"":"US",mintick:u,pricescale:h,minmove:1,pointvalue:1,mincontract:n.min_order_size?parseFloat(n.min_order_size):0,session:a,volumetype:"base",expiration_date:0,employees:0,industry:"",sector:"",shareholders:0,shares_outstanding_float:0,shares_outstanding_total:0,recommendations_buy:0,recommendations_buy_strong:0,recommendations_date:0,recommendations_hold:0,recommendations_sell:0,recommendations_sell_strong:0,recommendations_total:0,target_price_average:0,target_price_date:0,target_price_estimates:0,target_price_high:0,target_price_low:0,target_price_median:0}}catch(n){return console.error("Error in AlpacaProvider.getSymbolInfo:",n),null}}_convertBarsCrypto(e,n,r){return e.map((i,s,a)=>{let o=new Date(i.t).getTime(),l=s<a.length-1?new Date(a[s+1].t).getTime():is(o,n,r);return this._toKline(i,o,l)})}_convertBarsStock(e,n,r){let i="America/New_York";return e.map(s=>{let a=new Date(s.t).getTime(),o=s.t.slice(0,10),l;if(n==="day"){let c=this._calendarCache.get(o),u=c?c.close:"16:00";l=An(o,u,i)}else if(n==="minute"||n==="hour"){let c=a+r*{minute:6e4,hour:36e5}[n],u=this._calendarCache.get(o),h=u?u.close:"16:00",p=An(o,h,i);l=Math.min(c,p)}else n==="week"?l=this._weeklyCloseFromCalendar(o,i):n==="month"?l=this._monthlyCloseFromCalendar(o,i):l=is(a,n,r);return this._toKline(s,a,l)})}_toKline(e,n,r){return{openTime:n,open:e.o,high:e.h,low:e.l,close:e.c,volume:e.v,closeTime:r,quoteAssetVolume:0,numberOfTrades:e.n,takerBuyBaseAssetVolume:0,takerBuyQuoteAssetVolume:0,ignore:0}}_weeklyCloseFromCalendar(e,n){let r=new Date(e+"T00:00:00Z"),i=r.getUTCDay(),s=i<=5?5-i:5-i+7;for(let l=s;l>=0;l--){let c=r.getTime()+l*864e5,u=new Date(c).toISOString().split("T")[0],h=this._calendarCache.get(u);if(h)return An(u,h.close,n)}let a=r.getTime()+s*864e5,o=new Date(a).toISOString().split("T")[0];return An(o,"16:00",n)}_monthlyCloseFromCalendar(e,n){let[r,i]=e.split("-").map(Number),s=new Date(Date.UTC(r,i,0)).getUTCDate();for(let o=s;o>=1;o--){let l=`${r}-${String(i).padStart(2,"0")}-${String(o).padStart(2,"0")}`,c=this._calendarCache.get(l);if(c)return An(l,c.close,n)}let a=new Date(Date.UTC(r,i,0));for(;a.getUTCDay()===0||a.getUTCDay()===6;)a.setUTCDate(a.getUTCDate()-1);return An(a.toISOString().split("T")[0],"16:00",n)}async _ensureCalendar(e,n){if(this._calendarCache.has(e)&&this._calendarCache.has(n))return;let r=`${this._tradingUrl}/calendar?start=${e}&end=${n}`,i=await fetch(r,{headers:this._headers()});if(!i.ok){console.warn(`Alpaca calendar API returned ${i.status}, falling back to defaults`);return}let s=await i.json();for(let a of s)this._calendarCache.set(a.date,a)}async _fetchAsset(e){if(this._assetCache.has(e))return this._assetCache.get(e);let n=encodeURIComponent(e),r=`${this._tradingUrl}/assets/${n}`,i=await fetch(r,{headers:this._headers()});if(!i.ok)return null;let s=await i.json();return this._assetCache.set(e,s),s}_parseAlpacaTimeframe(e){let n=e.match(/^(\\d+)(Min|Hour|Day|Week|Month)$/);if(n){let r=parseInt(n[1],10),i=lM[n[2]];if(i)return{periodType:i,multiplier:r}}return{periodType:"day",multiplier:1}}_resolveTimeframe(e){return Vd[e.toUpperCase()]||Vd[e]||null}_isCrypto(e){return e.includes("/")}_addDaysToDate(e,n){let r=new Date(e+"T00:00:00Z");return r.setUTCDate(r.getUTCDate()+n),r.toISOString().split("T")[0]}},eu=class{async getMarketData(){return[]}},cM=typeof process<"u"&&process.versions&&process.versions.node,ao=null;if(cM)try{ao=new eu}catch{ao=null}var f5={Binance:new Zc,FMP:new Jc,Alpaca:new Qc,...ao?{Mock:ao}:{}},uM=Object.defineProperty,hM=(t,e,n)=>e in t?uM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pM=(t,e,n)=>hM(t,typeof e!="symbol"?e+"":e,n),Ns=class extends Ri{constructor(e){super({requiresConfig:!1,resolverName:"Map",cached:!1}),pM(this,"_libraries",{}),e&&this.configure(e)}configure(e){super.configure(e),e.libraries&&(this._libraries=e.libraries)}_resolveNative(e){return this._get(e.path)??this._get(`${e.user}/${e.name}`)??this._get(e.name)??null}_get(e){let n=this._libraries;return n instanceof Map?n.get(e):Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}};function yy(t,e){return t.replace(/\\{(path|user|name|version)\\}/g,(n,r)=>String(e[r]))}async function tu(t,e,n){let r=t??globalThis.fetch;if(typeof r!="function")throw new Error("No fetch implementation available: pass one in the resolver config");let i=await r(e,n?{headers:n}:void 0);if(i.status===404)return null;if(!i.ok)throw new Error(`Failed to fetch ${e}: ${i.status} ${i.statusText??""}`.trim());return i.text()}var dM=Object.defineProperty,fM=(t,e,n)=>e in t?dM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nl=(t,e,n)=>fM(t,typeof e!="symbol"?e+"":e,n),nu=class extends Ri{constructor(e){super({requiresConfig:!0,resolverName:"Url"}),Nl(this,"_url",null),Nl(this,"_headers"),Nl(this,"_fetch"),e?.url&&this.configure(e)}configure(e){super.configure(e),e.url!==void 0&&(this._url=e.url),e.headers!==void 0&&(this._headers=e.headers),e.fetch!==void 0&&(this._fetch=e.fetch)}_resolveNative(e){let n=this._url;if(!n)throw new Error(\'The Url import resolver has no "url" configured\');return tu(this._fetch,typeof n=="function"?n(e):yy(n,e),this._headers)}},mM=Object.defineProperty,yM=(t,e,n)=>e in t?mM(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,aa=(t,e,n)=>yM(t,typeof e!="symbol"?e+"":e,n),ru=class extends Ri{constructor(e){super({requiresConfig:!0,resolverName:"GitHub"}),aa(this,"_location",null),aa(this,"_token"),aa(this,"_extensions",["",".pine"]),aa(this,"_fetch"),(e?.url||e?.owner)&&this.configure(e)}configure(e){super.configure(e),e.url!==void 0&&(this._location=gM(e.url)),(e.owner!==void 0||e.repo!==void 0)&&(this._location={...this._location??{owner:"",repo:""},file:void 0},e.owner!==void 0&&(this._location.owner=e.owner),e.repo!==void 0&&(this._location.repo=e.repo)),this._location&&(e.ref!==void 0&&(this._location.ref=e.ref),e.path!==void 0&&(this._location.path=e.path)),e.token!==void 0&&(this._token=e.token),e.extensions&&(this._extensions=e.extensions),e.fetch!==void 0&&(this._fetch=e.fetch)}_resolveNative(e){let n=this._location;if(!n?.owner||!n.repo)throw new Error("The GitHub import resolver has no repository configured (url, or owner and repo)");if(n.file){let i=n.file.split("/").pop()?.replace(/\\.[^.]*$/,"");return e.name===i?this._get(n,n.file):Promise.resolve(null)}let r=n.path?n.path.includes("{")?n.path:`${n.path.replace(/\\/+$/,"")}/{name}`:"{name}";return this.firstFound(yy(r,e),this._extensions,i=>this._get(n,i))}_get(e,n){let r=n.split("/").map(encodeURIComponent).join("/");if(this._token){let i=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${r}${e.ref?`?ref=${encodeURIComponent(e.ref)}`:""}`;return tu(this._fetch,i,{Accept:"application/vnd.github.raw",Authorization:`Bearer ${this._token}`,"X-GitHub-Api-Version":"2022-11-28"})}return tu(this._fetch,`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref??"HEAD"}/${r}`)}};function gM(t){let e=t.trim().match(/^(?:https?:\\/\\/)?(?:www\\.)?(github\\.com|raw\\.githubusercontent\\.com)\\/([^/]+)\\/([^/#?]+)(?:\\/(.*?))?\\/?(?:[?#].*)?$/i);if(!e)throw new Error(`Not a GitHub repository URL: "${t}"`);let[,n,r,i,s=""]=e,a=i.replace(/\\.git$/,""),o=s.split("/").filter(Boolean).map(decodeURIComponent);if(n.toLowerCase()==="raw.githubusercontent.com"){if(o.length<2)throw new Error(`A raw.githubusercontent.com URL must point to a file: "${t}"`);return{owner:r,repo:a,ref:o[0],file:o.slice(1).join("/")}}if(o.length===0)return{owner:r,repo:a};if((o[0]==="tree"||o[0]==="blob")&&o.length>=2){let l={owner:r,repo:a,ref:o[1]},c=o.slice(2).join("/");return o[0]==="blob"?l.file=c:c&&(l.path=c),l}throw new Error(`Unsupported GitHub URL: "${t}". Use a repository, folder (/tree/...) or file (/blob/...) URL`)}var iu=class{configure(){}async resolve(){throw new Error("FileImportResolver is only available in Node.js")}};var _M=typeof process<"u"&&process.versions&&process.versions.node,oo=null;if(_M)try{oo=new iu}catch{oo=null}var m5={Map:new Ns,Url:new nu,GitHub:new ru,...oo?{File:oo}:{}};var Ao="Study";function J(t){return typeof t=="string"?t:void 0}function Ce(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function gy(t){if(typeof t=="boolean")return t;if(typeof t=="object"&&t!==null&&Array.isArray(t.data)){let e=t;return gy(e.data[e.offset??0])}}function bM(t){let e=new Map,n=!1;for(let i=0;i<t.length;i+=1){let s=t[i].time;e.has(s)&&(n=!0),e.set(s,i)}if(!n)return t;let r=new Set(e.values());return t.filter((i,s)=>r.has(s))}function lh(t){let e=t??{},n=e.fullContext??e;return Object.keys({...n.indicator,...n.strategy?.config}).length>0}function To(t){let e=t??{},n=e.fullContext??e,r={...n.indicator,...n.strategy?.config},i=J(r.title),s={title:i===void 0?"Indicator":i.trim()?i:Ao,overlay:gy(r.overlay)??!1,precision:Ce(r.precision),shorttitle:J(r.shorttitle),format:J(r.format)},a=n.plots??{},o=Object.entries(a).map(([c,u])=>{let h=u??{},p=h.options??{};return{key:c,title:J(h.title),style:J(p.style),options:p,data:Array.isArray(h.data)?bM(h.data):[],plot1:J(h.plot1)??J(p.plot1),plot2:J(h.plot2)??J(p.plot2)}}),l=n.strategy?xM(n.strategy):void 0;return{meta:s,plots:o,...l?{trades:l}:{}}}function xM(t){let e=[],n=Array.isArray(t.closedtrades)?t.closedtrades:[],r=Array.isArray(t.opentrades)?t.opentrades:[];for(let i of[...n,...r]){let s=i??{},a=Ce(s.entry_price),o=Ce(s.entry_time),l=Ce(s.size);a===void 0||o===void 0||l===void 0||l===0||e.push({id:J(s.id)??`trade_${e.length}`,entry_id:J(s.entry_id)??"",entry_price:a,entry_time:o,entry_comment:J(s.entry_comment),exit_id:J(s.exit_id),exit_price:Ce(s.exit_price),exit_time:Ce(s.exit_time),exit_comment:J(s.exit_comment),size:l,status:s.status==="closed"?"closed":"open"})}return e}var vM={line:"line",style_line:"line",style_linebr:"line",style_area:"area",style_areabr:"area",style_stepline:"step",style_steplinebr:"step",style_stepline_diamond:"step",style_histogram:"histogram",style_columns:"columns",style_circles:"circles",style_cross:"cross",shape:"markers",char:"markers",bar:"bar",candle:"candle",background:"background",barcolor:"barcolor",hline:"hline",fill:"fill",drawing_line:"drawing_line",drawing_box:"drawing_box",label:"label",drawing_polyline:"drawing_polyline",linefill:"linefill",table:"table"};function _y(t){return t==null||t===""?"line":vM[t]??"line"}function No(t){if(typeof t!="string")return!1;let e=t.trim();if(!e)return!1;let n=e.toLowerCase();if(n==="na"||n==="nan")return!1;let r=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})$/.exec(e);return!(r&&parseInt(r[1]??"ff",16)===0||/^rgba\\([^)]*,\\s*0(?:\\.0+)?\\s*\\)$/i.test(e))}function Se(t,e){return No(t)?t.trim():e}var by="#00000000";var xy=Symbol.for("@luxalgo/vela-ui");function Co(t,e){let n=globalThis,r=n[xy]??(n[xy]=Object.create(null));return t in r||(r[t]=e()),r[t]}var wM=Co("icons@1",()=>new Map);function B(t,e){wM.set(t,e)}function vy(t,e=""){return`<svg viewBox="0 0 16 16" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`}function D(t,e=""){return`<svg viewBox="0 0 24 24" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`}var K=vy;B("style-candles",K(\'<path d="M4.5 2v2M4.5 12v2M11.5 2v1.5M11.5 11v3"/><rect x="2.8" y="4" width="3.4" height="8" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="3.5" width="3.4" height="7.5" rx="0.6" fill="currentColor"/>\'));B("style-bars",K(\'<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>\'));B("style-line",K(\'<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>\'));B("style-linemarkers",K(\'<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/><g fill="currentColor" stroke="none"><circle cx="1.5" cy="11.5" r="1.4"/><circle cx="5.5" cy="7" r="1.4"/><circle cx="8.5" cy="9.5" r="1.4"/><circle cx="13.5" cy="3.5" r="1.4"/></g>\'));B("style-stepline",K(\'<path d="M1.5 11.5H5V7.5h3.5V10H12V4h2.5"/>\'));B("style-area",K(\'<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/><path d="M1.5 11.5 5.5 7l3 2.5 5-6V13.5h-12z" fill="currentColor" fill-opacity="0.25" stroke="none"/>\'));B("style-baseline",K(\'<path d="M1.5 8h13" stroke-dasharray="2 2"/><path d="M2.5 8 5.25 4.5 8 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M2.5 8 5.25 4.5 8 8"/><path d="M8 8l2.75 3.5L13.5 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M8 8l2.75 3.5L13.5 8"/>\'));B("style-columns",K(\'<rect x="2" y="8" width="3" height="5.5" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="6.5" y="4" width="3" height="9.5" rx="0.6" fill="currentColor"/><rect x="11" y="6.5" width="3" height="7" rx="0.6" fill="currentColor" fill-opacity="0.25"/>\'));B("style-heikinashi",K(\'<path d="M4.5 12v2M11.5 2v2"/><rect x="2.8" y="5" width="3.4" height="7" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="4" width="3.4" height="7" rx="0.6" fill="currentColor"/>\'));B("indicators",K(\'<path d="M1.5 12.5 5 7l2.5 3.5L11 4l3.5 5"/><circle cx="11" cy="4" r="1.4" fill="currentColor" stroke="none"/>\'));B("undo",K(\'<path d="M6.2 9.5 2.7 6l3.5-3.5"/><path d="M2.7 6h6.8a3.65 3.65 0 0 1 0 7.3H7.5"/>\'));B("redo",K(\'<path d="M9.8 9.5 13.3 6 9.8 2.5"/><path d="M13.3 6H6.5a3.65 3.65 0 0 0 0 7.3h2"/>\'));B("objects",K(\'<path d="M8 1.8 14 5 8 8.2 2 5z"/><path d="M2 8l6 3.2L14 8" opacity="0.7"/><path d="M2 11l6 3.2 6-3.2" opacity="0.4"/>\'));B("clock",K(\'<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>\'));B("calendar",K(\'<rect x="2.2" y="3.2" width="11.6" height="10.6" rx="1.4"/><path d="M5.2 1.8v2.8M10.8 1.8v2.8M2.2 6.8h11.6"/>\'));B("datawindow",K(\'<rect x="1.8" y="2.5" width="12.4" height="11" rx="1.5"/><path d="M4.5 5.5h4M4.5 8h7M4.5 10.5h5.5"/>\'));B("camera",K(\'<path d="M5.5 4 6.5 2.5h3L10.5 4h3A1 1 0 0 1 14.5 5v7.5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><circle cx="8" cy="8.5" r="2.6"/>\'));B("gear",K(\'<path d="M6.55 1.4h2.9l.32 1.72c.48.14.92.38 1.3.7l1.66-.55 1.45 2.5-1.35 1.1c.08.34.12.7.12 1.07s-.04.73-.12 1.07l1.35 1.1-1.45 2.5-1.66-.55a4.3 4.3 0 0 1-1.3.7L9.45 14.6h-2.9l-.32-1.72a4.3 4.3 0 0 1-1.3-.7l-1.66.55-1.45-2.5 1.35-1.1A4.4 4.4 0 0 1 3.05 7.94c0-.37.04-.73.12-1.07l-1.35-1.1 1.45-2.5 1.66.55c.38-.32.82-.56 1.3-.7L6.55 1.4z"/><circle cx="8" cy="8" r="2.2"/>\'));B("search",K(\'<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>\'));B("bell",K(\'<path d="M8 2a4 4 0 0 0-4 4v2.5L2.5 11v1h11v-1L12 8.5V6a4 4 0 0 0-4-4z"/><path d="M6.5 13.5a1.5 1.5 0 0 0 3 0"/>\'));B("market-open",D(\'<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>\'));B("market-pre",D(\'<path d="M12 2v8"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m8 6 4-4 4 4"/><path d="M16 18a4 4 0 0 0-8 0"/>\'));B("market-post",D(\'<path d="M12 10V2"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 14-4 4-4-4"/><path d="M16 6a4 4 0 0 0-8 0"/>\'));B("market-extended",D(\'<path d="M22 22H2"/><path d="M12 3a5 5 0 0 0 7.5 7.5A7.5 7.5 0 1 1 12 3Z"/>\'));B("market-closed",D(\'<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>\'));B("market-holiday",D(\'<path d="m10 20-1.25-2.5L6 16"/><path d="M10 4 8.75 6.5 6 8"/><path d="m14 20 1.25-2.5L18 16"/><path d="m14 4 1.25 2.5L18 8"/><path d="m17 10-5 5-5-5"/><path d="M4 12h16"/>\'));B("chevron-right",K(\'<path d="m6 3.5 4.5 4.5L6 12.5"/>\'));B("chevron-left",K(\'<path d="M10 3.5 5.5 8l4.5 4.5"/>\'));B("chevron-down",K(\'<path d="M3.5 6 8 10.5 12.5 6"/>\'));B("chevron-up",K(\'<path d="M3.5 10 8 5.5 12.5 10"/>\'));B("chevrons-right",K(\'<path d="m4 3.5 4.5 4.5L4 12.5"/><path d="m8.5 3.5 4.5 4.5-4.5 4.5"/>\'));B("chevrons-left",K(\'<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>\'));B("replay",K(\'<path d="M14 4.2v7.6L8.6 8z"/><path d="M7.4 4.2v7.6L2 8z"/>\'));B("check",K(\'<path d="m2.8 8.4 3.4 3.4 7-7.6"/>\'));B("close",K(\'<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>\'));B("pin",K(\'<path d="M5.6 2.5h4.8M6.4 2.5v3.6L4.4 8.4v.9h7.2v-.9L9.6 6.1V2.5M8 9.3v4.2"/>\'));B("pin-filled",K(\'<path d="M5.6 2.5h4.8M6.4 2.5v3.6L4.4 8.4v.9h7.2v-.9L9.6 6.1V2.5M8 9.3v4.2"/><path d="M6.4 2.5h3.2v3.6l2 2.3v.9H4.4v-.9l2-2.3z" fill="currentColor" stroke="none"/>\'));B("eye",K(\'<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>\'));B("eye-off",K(\'<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z" opacity="0.45"/><path d="m3 13 10-10"/>\'));B("lock",K(\'<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.8 0V7"/>\'));B("unlock",K(\'<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.7-.7"/>\'));B("trash",K(\'<path d="M2.5 4.3h11M6.2 4.3V3.1a1 1 0 0 1 1-1h1.6a1 1 0 0 1 1 1v1.2M4.2 4.3l.5 9.1a1.15 1.15 0 0 0 1.15 1.1h4.3a1.15 1.15 0 0 0 1.15-1.1l.5-9.1M6.5 7v4.5M9.5 7v4.5"/>\'));B("group",K(\'<path d="M1.8 4.5V2.4a.6.6 0 0 1 .6-.6h2.1M11.5 1.8h2.1a.6.6 0 0 1 .6.6v2.1M14.2 11.5v2.1a.6.6 0 0 1-.6.6h-2.1M4.5 14.2H2.4a.6.6 0 0 1-.6-.6v-2.1"/><rect x="4" y="4" width="4.2" height="4.2" rx="0.7"/><rect x="7.8" y="7.8" width="4.2" height="4.2" rx="0.7"/>\'));B("ungroup",K(\'<rect x="1.6" y="1.6" width="6.2" height="6.2" rx="0.9"/><rect x="8.2" y="8.2" width="6.2" height="6.2" rx="0.9" stroke-dasharray="2 1.5"/>\'));B("clone",K(\'<rect x="5.5" y="5.5" width="9" height="9" rx="1.2"/><path d="M11 5.5v-3a1 1 0 0 0-1-1H2.5a1 1 0 0 0-1 1V10a1 1 0 0 0 1 1h3"/>\'));B("arrow-up",K(\'<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>\'));B("arrow-down",K(\'<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>\'));B("move-vertical",K(\'<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>\'));B("move",K(\'<path d="M8 1.8v12.4M1.8 8h12.4M5.6 4.2 8 1.8l2.4 2.4M5.6 11.8 8 14.2l2.4-2.4M4.2 5.6 1.8 8l2.4 2.4M11.8 5.6 14.2 8l-2.4 2.4"/>\'));B("pen",K(\'<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>\'));B("wave",K(\'<path d="M1.5 10.4c1.6 0 1.9-4.8 3.4-4.8s1.8 4.8 3.4 4.8 1.8-4.8 3.4-4.8 1.6 4.8 2.8 4.8"/>\'));B("folder-plus",K(\'<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M8 7.6v3.6M6.2 9.4h3.6"/>\'));B("folder-minus",K(\'<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M6.2 9.4h3.6"/>\'));B("collapse",K(\'<path d="M3 8h10"/>\'));B("expand",K(\'<rect x="2.2" y="2.2" width="11.6" height="11.6" rx="1.4"/><path d="M8 5.4v5.2M5.4 8h5.2"/>\'));B("plus",K(\'<path d="M8 2.8v10.4M2.8 8h10.4"/>\'));B("minus",K(\'<path d="M2.8 8h10.4"/>\'));B("maximize",K(\'<path d="M2.5 6V3a.5.5 0 0 1 .5-.5h3M10 2.5h3a.5.5 0 0 1 .5.5v3M13.5 10v3a.5.5 0 0 1-.5.5h-3M6 13.5H3a.5.5 0 0 1-.5-.5v-3"/>\'));B("restore",K(\'<path d="M6 2.5v3a.5.5 0 0 1-.5.5h-3M13.5 6h-3a.5.5 0 0 1-.5-.5v-3M10 13.5v-3a.5.5 0 0 1 .5-.5h3M2.5 10h3a.5.5 0 0 1 .5.5v3"/>\'));B("restore",K(\'<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>\'));B("star",K(\'<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>\'));B("star-filled",K(\'<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>\',\'fill="currentColor"\'));B("grip",K(\'<circle cx="6" cy="3.5" r="1"/><circle cx="10" cy="3.5" r="1"/><circle cx="6" cy="8" r="1"/><circle cx="10" cy="8" r="1"/><circle cx="6" cy="12.5" r="1"/><circle cx="10" cy="12.5" r="1"/>\',\'fill="currentColor" stroke="none"\'));B("kebab",K(\'<circle cx="8" cy="3.2" r="1.2"/><circle cx="8" cy="8" r="1.2"/><circle cx="8" cy="12.8" r="1.2"/>\',\'fill="currentColor" stroke="none"\'));B("burger",K(\'<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>\'));B("info",K(\'<path d="M8 7.4v4.4"/><circle cx="8" cy="4.6" r="0.9" fill="currentColor" stroke="none"/>\'));B("reset",K(\'<path d="M2 8a6 6 0 1 0 6-6 6.5 6.5 0 0 0-4.5 1.83L2 5.33"/><path d="M2 2v3.33h3.33"/>\'));B("circle-check",K(\'<circle cx="8" cy="8" r="6.2"/><path d="m5.4 8.2 1.8 1.8 3.4-3.7"/>\'));B("circle-info",K(\'<circle cx="8" cy="8" r="6.2"/><path d="M8 7.4v3.6"/><circle cx="8" cy="5.1" r="0.8" fill="currentColor" stroke="none"/>\'));B("triangle-alert",K(\'<path d="M7.1 2.6a1 1 0 0 1 1.8 0l5.3 9.6a1 1 0 0 1-.9 1.5H2.7a1 1 0 0 1-.9-1.5z"/><path d="M8 6.3v3.2"/><circle cx="8" cy="11.4" r="0.8" fill="currentColor" stroke="none"/>\'));B("circle-x",K(\'<circle cx="8" cy="8" r="6.2"/><path d="m5.9 5.9 4.2 4.2M10.1 5.9l-4.2 4.2"/>\'));B("loader",K(\'<path d="M8 1.8a6.2 6.2 0 1 0 6.2 6.2"/>\'));B("pane-collapse",K(\'<path d="M2.6 9.4h4v4M13.4 6.6h-4v-4"/><path d="m9.4 6.6 4.2-4.2M2.4 13.6l4.2-4.2"/>\'));B("pane-expand",K(\'<path d="M9.8 2.4h3.8v3.8M6.2 13.6H2.4V9.8"/><path d="m13.6 2.4-4.4 4.4M2.4 13.6l4.4-4.4"/>\'));B("cursor",D(\'<path d="M5 3l6 16 2-6 6-2z"/>\',\'fill="currentColor" stroke="none"\'));B("ruler",D(\'<path d="M21.3 15.3 8.7 2.7a1 1 0 0 0-1.4 0L2.7 7.3a1 1 0 0 0 0 1.4l12.6 12.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4Z"/><path d="m7.5 10.5 2 2"/><path d="m10.5 7.5 2 2"/><path d="m13.5 4.5 2 2"/><path d="m4.5 13.5 2 2"/>\'));B("magnet",D(\'<path d="m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15"/><path d="m5 8 4 4"/><path d="m12 15 4 4"/>\'));B("eraser",D(\'<path d="m7 21-4.3-4.3a1 1 0 0 1 0-1.4L13 5a2 2 0 0 1 2.8 0l4.2 4.2a2 2 0 0 1 0 2.8L12 20"/><path d="M22 21H7"/><path d="m5 11 9 9"/>\'));B("pen-lock",D(\'<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="13" y="14.5" width="8" height="6" rx="1.2"/><path d="M15 14.5v-1.6a2 2 0 0 1 4 0v1.6"/>\'));B("pen-sync",D(\'<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="12.5" y="13.5" width="6" height="4.8" rx="1"/><path d="M15.5 18.3v1a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-2.8a1 1 0 0 0-1-1h-1"/>\'));B("brush",D(\'<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>\'));B("bucket",D(\'<path d="m18.5 11.5-7-7L4 12a1.8 1.8 0 0 0 0 2.5l5 5a1.8 1.8 0 0 0 2.5 0Z"/><path d="m5 5 4 4"/><path d="M3.5 13.5h13"/><path d="M21 17.5c0 1.1-.9 2-2 2s-2-.9-2-2c0-1 1.2-1.7 2-3 .8 1.3 2 2 2 3Z"/>\'));B("type",D(\'<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>\'));B("bold",D(\'<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7Z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7Z"/>\',\'stroke-width="2.4"\'));B("italic",D(\'<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>\',\'stroke-width="2.2"\'));B("price-delta",D(\'<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>\'));B("date-delta",D(\'<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>\'));B("bring-front",D(\'<rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/>\'));B("send-back",D(\'<rect x="8.5" y="8.5" width="7" height="7" rx="1.5" fill="currentColor" stroke="none" opacity="0.35"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/><rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/>\'));B("r-squared",\'<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none"><text x="2.5" y="17.5" font-size="14" font-family="serif">R\\xB2</text></svg>\');B("bands",D(\'<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>\'));B("dedekind",D(\'<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0"/><path d="M8 20a4 4 0 0 1 8 0"/><path d="M12 4v16"/>\'));B("sonic",D(\'<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>\'));B("supersonic",D(\'<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>\'));function EM(t){let e=typeof t=="string"?t.trim():"";if(!e)return"en";try{return Intl.getCanonicalLocales(e)[0]??e}catch{return e}}function Mo(t){try{return new Intl.Locale(t)}catch{return null}}function fh(t){return(Mo(t)?.language??t.split(/[-_]/)[0]??t).toLowerCase()}function kM(t){let e=[],n=i=>{i&&!e.includes(i)&&e.push(i)};n(t);let r=Mo(t);if(r){let i=r.baseName;n(i);let s=i.split("-"),a;if(!r.script)try{a=r.maximize().script}catch{a=void 0}for(let o=s.length-1;o>=1;o-=1)o===1&&a&&r.region&&n(`${r.language}-${a}`),n(s.slice(0,o).join("-"));a&&!r.region&&n(`${r.language}-${a}`);try{let o=new Intl.Locale(r.language).maximize();o.region&&o.script===(r.script??a)&&n(`${r.language}-${o.region}`)}catch{}}return n("en"),e}var AM=new Set(["Arab","Hebr","Thaa","Syrc","Nkoo","Adlm","Rohg","Mand","Samr","Yezi"]),TM=new Set(["ar","he","iw","fa","ur","ps","sd","ug","yi","dv","ckb","ks"]);function NM(t){let e=Mo(t);if(e){try{let n=e,r=typeof n.getTextInfo=="function"?n.getTextInfo():n.textInfo;if(r?.direction==="rtl"||r?.direction==="ltr")return r.direction}catch{}try{let n=e.script??e.maximize().script;if(n)return AM.has(n)?"rtl":"ltr"}catch{}}return TM.has(fh(t))?"rtl":"ltr"}var wy=new Map;function CM(t,e){let n=`${t}|${e??""}`,r=wy.get(n);if(r)return r;let i="latn";try{e==="locale"?i=new Intl.NumberFormat(t).resolvedOptions().numberingSystem:e?i=new Intl.NumberFormat(t,{numberingSystem:e}).resolvedOptions().numberingSystem:Mo(t)?.numberingSystem&&(i=new Intl.NumberFormat(t).resolvedOptions().numberingSystem)}catch{i="latn"}return wy.set(n,i),i}var IM=[],Sy=0,Ey=new Map;function MM(t){let e=t.join("|"),n=Ey.get(e);if(n&&n.version===Sy)return n.map;let r=new Map;for(let i=t.length-1;i>=0;i-=1){let s=t[i];for(let a of IM)if(a.tag===s)for(let[o,l]of Object.entries(a.messages))typeof l=="string"&&r.set(o,l)}return Ey.set(e,{version:Sy,map:r}),r}var PM=/[]/g;function Ut(t){return t.replace(PM,"")}var ky=new Map;function lr(t,e){let n=`${t.locale}|${t.numberingSystem}|${JSON.stringify(e)}`,r=ky.get(n);if(!r){try{r=new Intl.NumberFormat(t.locale,{...e,numberingSystem:t.numberingSystem})}catch{r=new Intl.NumberFormat("en",e)}ky.set(n,r)}return r}var Ay=new Map;function Ry(t){let e=`${t.locale}|${t.numberingSystem}`,n=Ay.get(e);if(n)return n;let r=lr(t,{useGrouping:!1,minimumFractionDigits:1,maximumFractionDigits:1}).formatToParts(-1.5),i=Ut(r.find(c=>c.type==="decimal")?.value??".")||".",s=Ut(r.find(c=>c.type==="minusSign")?.value??"-")||"-",a=lr(t,{useGrouping:!1,maximumFractionDigits:0}),o=Array.from({length:10},(c,u)=>Ut(a.format(u)));return n={ascii:i==="."&&s==="-"&&o.every((c,u)=>c===String(u)),decimal:i,minus:s,digits:o},Ay.set(e,n),n}function Fr(t,e){let n=Ry(e);if(n.ascii)return t;let r="";for(let i of t){let s=i.charCodeAt(0);s>=48&&s<=57?r+=n.digits[s-48]:i==="."?r+=n.decimal:i==="-"?r+=n.minus:r+=i}return r}function Ty(t,e){let n=Ry(e);return n.digits.every((r,i)=>r===String(i))?t:t.replace(/[0-9]/g,r=>n.digits[Number(r)])}var Po=t=>Number.isFinite(t)?Math.max(0,Math.min(20,Math.trunc(t))):2;function DM(t,e,n){return Fr(t.toFixed(Po(e)),n)}function OM(t,e,n){let r=Po(e);return Ut(lr(n,{minimumFractionDigits:r,maximumFractionDigits:r}).format(t))}function Ly(t,e,n){return Ut(n==="integer"?lr(e,{maximumFractionDigits:0}).format(t):n==="percent"?lr(e,{style:"percent"}).format(t):lr(e,{}).format(t))}function Fy(t,e,n){let r=Po(e?.decimals??2),i=e?.signed??!0;if(n.english){let a=i?`${t>=0?"+":"-"}${Math.abs(t).toFixed(r)}%`:`${t.toFixed(r)}%`;return Fr(a,n)}let s=lr(n,{style:"percent",minimumFractionDigits:r,maximumFractionDigits:r,signDisplay:i?"always":"auto"});return Ut(s.format(t/100))}function RM(t,e,n){let r=e.mode??"price";return r==="percent"?Fy(t,{decimals:e.decimals,signed:!0},n):r==="indexed"||!e.grouping?DM(t,e.decimals,n):OM(t,e.decimals,n)}var LM=[[1e9,"B"],[1e6,"M"],[1e3,"K"]];function FM(t,e,n){let r=Po(e?.decimals??2),i=e?.trimZeros??!0;if(n.english){let a=Math.abs(t),o=1,l="";for(let[h,p]of LM)if(a>=h){o=h,l=p;break}let c=t/o,u=i?Number(c.toFixed(r)).toString():c.toFixed(r);return Fr(u,n)+l}let s=lr(n,{notation:"compact",compactDisplay:"short",maximumFractionDigits:r,minimumFractionDigits:i?0:r});return Ut(s.format(t))}var By=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],BM=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hh=t=>t<10?`0${t}`:String(t),ch=864e5,Ny=new Map;function VM(t,e){if(!e||e==="UTC")return 0;let n=Ny.get(e);if(n===void 0){try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{n=null}Ny.set(e,n)}if(!n)return 0;try{let r=n.formatToParts(new Date(t)),i=a=>Number(r.find(o=>o.type===a)?.value);return Date.UTC(i("year"),i("month")-1,i("day"),i("hour")%24,i("minute"),i("second"))-t}catch{return 0}}var Cy=new Map;function mh(t,e){let n=`${t.locale}|${t.numberingSystem}|${JSON.stringify(e)}`,r=Cy.get(n);if(!r){let i={...e,timeZone:"UTC",calendar:"gregory",numberingSystem:t.numberingSystem};try{r=new Intl.DateTimeFormat(t.locale,i)}catch{r=new Intl.DateTimeFormat("en",{...e,timeZone:"UTC",calendar:"gregory"})}Cy.set(n,r)}return r}function yh(t){return t.hourCycle==="h23"?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:t.hourCycle==="h12"?{hour:"numeric",minute:"2-digit",hourCycle:"h12"}:{hour:"numeric",minute:"2-digit"}}function Vy(t,e){return e.hourCycle==="h23"?Fr(`${hh(t.getUTCHours())}:${hh(t.getUTCMinutes())}`,e):Ut(mh(e,yh(e)).format(t))}var $M={year:{year:"numeric"},month:{month:"short"},day:{month:"short",day:"numeric"}},Iy=t=>t==="hour"||t==="minute"||t==="second";function zM(t,e,n){let r=new Date(t+(e.offsetMs??0)),i=e.unit;if(n.english){if(Iy(i))return Vy(r,n);let a=By[r.getUTCMonth()];return i==="year"?Fr(String(r.getUTCFullYear()),n):i==="month"?a:Fr(`${a} ${r.getUTCDate()}`,n)}let s=Iy(i)?yh(n):$M[i];return Ut(mh(n,s).format(r))}function jM(t,e,n){let r=new Date(t+VM(t,e?.timeZone??"UTC")),i=e?.withTime??!0;if(n.english){let a=Fr(`${BM[r.getUTCDay()]} ${r.getUTCDate()} ${By[r.getUTCMonth()]} \'${hh(r.getUTCFullYear()%100)}`,n);return i?`${a} ${Vy(r,n)}`:a}let s={weekday:"short",day:"numeric",month:"short",year:"2-digit",...i?yh(n):{}};return Ut(mh(n,s).format(r))}function qM(t){let e=Math.max(0,Math.ceil(t/1e3)),n=e%60,r=Math.floor(e/60)%60,i=Math.floor(e/3600),s=a=>String(a).padStart(2,"0");return i>0?`${i}:${s(r)}:${s(n)}`:`${s(r)}:${s(n)}`}function UM(t){let e=Math.abs(t),n=36e5,r=6e4;if(e>=ch){let i=Math.floor(e/ch),s=Math.round(e%ch/n);return s?[[i,"day"],[s,"hour"]]:[[i,"day"]]}if(e>=n){let i=Math.floor(e/n),s=Math.round(e%n/r);return s?[[i,"hour"],[s,"minute"]]:[[i,"hour"]]}return e>=r?[[Math.round(e/r),"minute"]]:[[Math.round(e/1e3),"second"]]}var WM={day:"d",hour:"h",minute:"m",second:"s"};function HM(t,e,n){if((e?.style??"countdown")==="countdown")return Ty(qM(t),n);let r=UM(t);return n.english?Ty(r.map(([i,s])=>`${i}${WM[s]}`).join(" "),n):r.map(([i,s])=>Ut(lr(n,{style:"unit",unit:s,unitDisplay:"narrow"}).format(i))).join(" ")}var My=new Map;function GM(t,e,n){let r=e?.timeZone??"UTC",i=e?.seconds??!0,s=n.english&&n.hourCycle==="h23",a=`${s?"en-GB":n.locale}|${n.numberingSystem}|${n.hourCycle}|${r}|${i}`,o=My.get(a);if(o===void 0){let l={hour:"2-digit",minute:"2-digit",...i?{second:"2-digit"}:{},timeZone:r};try{o=s?new Intl.DateTimeFormat("en-GB",{...l,hour12:!1}):new Intl.DateTimeFormat(n.locale,{...l,calendar:"gregory",numberingSystem:n.numberingSystem,...n.hourCycle==="locale"?{}:{hourCycle:n.hourCycle}})}catch{o=null}My.set(a,o)}if(!o)return"";try{return Ut(o.format(new Date(t)))}catch{return""}}var KM=new Set(["AG","AS","BD","BR","BS","BT","BW","BZ","CA","CN","CO","DM","DO","ET","GT","GU","HK","HN","ID","IL","IN","JM","JP","KE","KH","KR","LA","MH","MM","MO","MT","MX","MZ","NI","NP","PA","PE","PH","PK","PR","PT","PY","SA","SG","SV","TH","TT","TW","UM","US","VE","VI","WS","YE","ZA","ZW"]),YM=new Set(["AE","AF","BH","DJ","DZ","EG","IQ","IR","JO","KW","LY","OM","QA","SD","SY"]);function XM(t){let e;try{e=new Intl.Locale(t)}catch{return 1}try{let r=e,s=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(typeof s=="number")return s===7?0:s===6?6:1}catch{}let n=e.region;if(!n)try{n=e.maximize().region}catch{n=void 0}return n&&KM.has(n)?0:n&&YM.has(n)?6:1}function $y(t){return{price:(e,n)=>RM(e,n,t),percent:(e,n)=>Fy(e,n,t),compact:(e,n)=>FM(e,n,t),timeTick:(e,n)=>zM(e,n,t),timeStamp:(e,n)=>jM(e,n,t),duration:(e,n)=>HM(e,n,t),clock:(e,n)=>GM(e,n,t)}}var zy=Object.freeze({locale:"en",numberingSystem:"latn",hourCycle:"h23",english:!0}),M5=$y(zy),Py=!1;function ri(t,e,n,r){try{let i=t(e,n);if(typeof i=="string")return i}catch(i){Py||(Py=!0,console.warn("[vela] a host formatter threw; the built-in formatting is used instead.",i))}return r()}function ZM(t,e){let n=$y(t);if(!e)return n;let r=(s,a,o,l)=>({locale:t.locale,timeZone:o??"UTC",surface:s??a,fallback:l}),i=e;return{price(s,a){let o=()=>n.price(s,a);return typeof i.price!="function"?o():ri(i.price,s,{...r(a.surface,"priceAxis",void 0,o),decimals:a.decimals,mintick:a.mintick,mode:a.mode??"price",paneId:a.paneId,grouping:a.grouping??!1},o)},percent(s,a){let o=()=>n.percent(s,a);return typeof i.percent!="function"?o():ri(i.percent,s,{...r(a?.surface,"statusLine",void 0,o),decimals:a?.decimals??2,signed:a?.signed??!0},o)},compact(s,a){let o=()=>n.compact(s,a);return typeof i.compact!="function"?o():ri(i.compact,s,{...r(a?.surface,"priceAxis",void 0,o),decimals:a?.decimals??2,trimZeros:a?.trimZeros??!0},o)},timeTick(s,a){let o=()=>n.timeTick(s,a);return typeof i.timeTick!="function"?o():ri(i.timeTick,s,{...r(a.surface,"timeAxis",a.timeZone,o),unit:a.unit,major:a.major,offsetMs:a.offsetMs??0},o)},timeStamp(s,a){let o=()=>n.timeStamp(s,a);return typeof i.timeStamp!="function"?o():ri(i.timeStamp,s,{...r(a?.surface,"crosshair",a?.timeZone,o),withTime:a?.withTime??!0},o)},duration(s,a){let o=()=>n.duration(s,a);return typeof i.duration!="function"?o():ri(i.duration,s,{...r(a?.surface,"lastPrice",void 0,o),style:a?.style??"countdown"},o)},clock(s,a){let o=()=>n.clock(s,a);return typeof i.clock!="function"?o():ri(i.clock,s,{...r(a?.surface,"clock",a?.timeZone,o),seconds:a?.seconds??!0},o)}}}var JM=class{constructor(t){this.src=t,this.i=0}parse(){let t=this.message(!1,0);if(this.i<this.src.length)throw this.error("unmatched }");return t}error(t){return new SyntaxError(`[vela] message syntax: ${t} at ${this.i} in "${this.src}"`)}message(t,e){if(e>8)throw this.error("nesting too deep");let n=this.src,r=[],i="",s=()=>{i&&r.push(i),i=""};for(;this.i<n.length;){let a=n[this.i];if(a==="\'"){let o=n[this.i+1];if(o==="\'")i+="\'",this.i+=2;else if(o==="{"||o==="}"||t&&o==="#")for(this.i+=1;this.i<n.length;){let l=n[this.i];if(l==="\'"){if(n[this.i+1]==="\'"){i+="\'",this.i+=2;continue}this.i+=1;break}i+=l,this.i+=1}else i+="\'",this.i+=1}else if(a==="{")s(),this.i+=1,r.push(this.argument(e));else{if(a==="}")break;a==="#"&&t?(s(),r.push({kind:"pound"}),this.i+=1):(i+=a,this.i+=1)}}return s(),r}skipSpace(){for(;this.i<this.src.length&&/\\s/.test(this.src[this.i]);)this.i+=1}word(){this.skipSpace();let t=this.i;for(;this.i<this.src.length&&!/[\\s,{}]/.test(this.src[this.i]);)this.i+=1;return this.src.slice(t,this.i)}expect(t){if(this.skipSpace(),this.src[this.i]!==t)throw this.error(`expected "${t}"`);this.i+=1}argument(t){let e=this.word();if(!e)throw this.error("empty argument name");if(this.skipSpace(),this.src[this.i]==="}")return this.i+=1,{kind:"arg",name:e};this.expect(",");let n=this.word();if(this.skipSpace(),n==="number"){let r;return this.src[this.i]===","&&(this.i+=1,r=this.word()||void 0),this.expect("}"),{kind:"arg",name:e,format:"number",style:r}}if(n==="plural"||n==="selectordinal"||n==="select"){this.expect(",");let r=0;if(this.skipSpace(),n!=="select"&&this.src.startsWith("offset:",this.i)&&(this.i+=7,r=Number(this.word()),!Number.isFinite(r)))throw this.error("bad offset");let i={};for(;;){if(this.skipSpace(),this.src[this.i]==="}"){this.i+=1;break}let s=this.word();if(!s)throw this.error("expected a selector");this.expect("{"),i[s]=this.message(n!=="select",t+1),this.expect("}")}if(!i.other)throw this.error(`"${e}" has no "other" option`);return n==="select"?{kind:"select",name:e,options:i}:{kind:"plural",name:e,ordinal:n==="selectordinal",offset:r,options:i}}throw this.error(`unknown argument type "${n}"`)}},Io=new Map,QM=2e3;function eP(t){let e=Io.get(t);return e||(e=new JM(t).parse(),Io.size>=QM&&Io.clear(),Io.set(t,e)),e}var Dy=new Map;function tP(t,e){let n=`${t}|${e?"o":"c"}`,r=Dy.get(n);if(!r){try{r=new Intl.PluralRules(t,{type:e?"ordinal":"cardinal"})}catch{r=new Intl.PluralRules("en",{type:e?"ordinal":"cardinal"})}Dy.set(n,r)}return r}function ph(t,e,n,r){let i="";for(let s of t){if(typeof s=="string"){i+=s;continue}if(s.kind==="pound"){i+=r==null?"#":n.formatNumber(r);continue}let a=e?.[s.name];if(s.kind==="arg"){a===void 0?i+=`{${s.name}}`:typeof a=="number"?i+=n.formatNumber(a,s.format==="number"?s.style:void 0):s.format==="number"&&a.trim()!==""&&Number.isFinite(Number(a))?i+=n.formatNumber(Number(a),s.style):i+=a;continue}if(s.kind==="select"){let c=s.options[String(a)]??s.options.other;i+=ph(c,e,n,r);continue}let o=typeof a=="number"?a:Number(a),l;Number.isFinite(o)&&(l=s.options[`=${o}`]??s.options[tP(n.locale,s.ordinal).select(o-s.offset)]),i+=ph(l??s.options.other,e,n,Number.isFinite(o)?o-s.offset:null)}return i}function dh(t,e,n){return t.indexOf("{")<0&&t.indexOf("\'")<0?t:ph(eP(t),e,n,null)}function jy(t){return typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.defaultMessage=="string"}var Oy=!1;function qy(t,e){if(!t)return;let n=null;for(let r of Object.keys(t)){let i=t[r];typeof i=="object"&&i!==null&&(n??(n={...t}),n[r]=e(i))}return n??t}var Uy=class{constructor(t={}){this.runtime={locale:"en",formatNumber:(e,n)=>Ly(e,this.settings,n)},this.opts={...t},this.resolve()}get options(){return this.opts}get localeExplicit(){return this.opts.locale!==void 0}get directionExplicit(){return this.opts.direction!==void 0}update(t){let e=typeof t=="string"?{locale:t}:t;this.opts={...this.opts,...e};for(let n of Object.keys(this.opts))this.opts[n]===void 0&&delete this.opts[n];this.resolve()}resolve(){let t=this.opts,e=EM(t.locale),n=CM(e,t.numberingSystem),r=t.hourCycle==="h12"||t.hourCycle==="locale"?t.hourCycle:"h23";this.settings={locale:e,numberingSystem:n,hourCycle:r,english:fh(e)==="en"},this.chain=kM(e),this.resolvedDirection=t.direction==="rtl"||t.direction==="ltr"?t.direction:t.direction==="auto"?NM(e):"ltr",this.resolvedWeekStart=t.weekStart===0||t.weekStart===1||t.weekStart===6?t.weekStart:XM(e),this.runtime.locale=e,this.formatters=ZM(this.settings,t.formatters)}get locale(){return this.settings.locale}get direction(){return this.resolvedDirection}get numberingSystem(){return this.settings.numberingSystem}get hourCycle(){return this.settings.hourCycle}get weekStart(){return this.resolvedWeekStart}get format(){return this.formatters}get formatSettings(){return this.settings}t(t,e){if(typeof t=="string")return t;if(!jy(t))return t==null?"":String(t);let{id:n,defaultMessage:r}=t,i=t.values,s=qy(i?e?{...i,...e}:i:e,l=>this.t(l)),a=this.opts.messages?.[n],o=typeof a=="string"?a:MM(this.chain).get(n)??r;try{return dh(o,s,this.runtime)}catch(l){if(Oy||(Oy=!0,console.warn(`[vela] message "${n}" could not be formatted; the English text is used instead.`,l)),o===r)return r;try{return dh(r,s,this.runtime)}catch{return r}}}};var uh=null;function Do(){return uh??(uh=new Uy),uh}function nP(t){return t instanceof Uy?t.formatSettings:t?{locale:t.locale,numberingSystem:t.numberingSystem,hourCycle:t.hourCycle,english:fh(t.locale)==="en"}:Do().formatSettings}function v(t,e){return Object.freeze({id:t,defaultMessage:e})}var rP={locale:"en",formatNumber:(t,e)=>Ly(t,zy,e)};function Br(t,e){if(t==null)return"";if(typeof t=="string")return t;if(!jy(t))return String(t);let n=t.values,r=qy(n?e?{...n,...e}:n:e,i=>Br(i));try{return dh(t.defaultMessage,r,rP)}catch{return t.defaultMessage}}function cr(t,e,n){return(t??Do()).t(e,n)}function In(t,e){return Fr(t,nP(e))}var ur="#2962ff",Ls="#38c0fd",dt="#089981",Wt="#f23645",hr="#787b86";var ji="#ff9800",pr="#5b9cf6",Fs="#ff5d00",Bs="#0ecb81",Vs="#f6465d";var iP=Co("written-css@1",()=>new Set);function gh(t,...e){let n=t[0]??"";for(let r=0;r<e.length;r+=1)n+=String(e[r])+(t[r+1]??"");return iP.add(n),n}function Zt(t){let e=`--vela-${t}`,n=`var(${e})`;return{name:e,var:n,toString:()=>n}}function Pt(t,e){let n=t?Zt(t):{};for(let[r,i]of Object.entries(e))n[r]=Zt(i);return n}var Xe={space:Pt(null,{1:"space-1",2:"space-2",3:"space-3",4:"space-4"}),radius:Pt(null,{sm:"radius-sm",md:"radius-md",lg:"radius-lg"}),z:Pt(null,{tooltip:"z-tooltip",menu:"z-menu",dialog:"z-dialog",popover:"z-popover"}),ease:Zt("ease"),dur:Pt(null,{fast:"dur-fast",med:"dur-med"}),fontSize:Pt(null,{sm:"font-size-sm",md:"font-size-md",lg:"font-size-lg"}),font:Zt("font"),bg:Zt("bg"),fg:Pt("fg",{muted:"fg-muted",faint:"fg-faint",bright:"fg-bright",onFill:"fg-on-fill"}),surface:Pt("surface",{elev:"surface-elev",overlay:"surface-overlay",sunken:"surface-sunken"}),border:Pt("border",{strong:"border-strong",soft:"border-soft",faint:"border-faint"}),hover:Pt("hover",{strong:"hover-strong"}),active:Zt("active"),focus:Pt("focus",{soft:"focus-soft"}),separatorHover:Pt(null,{band:"separator-hover-band",line:"separator-hover-line"}),scroll:Pt("scroll",{size:"scroll-size"}),accent:Pt("accent",{bright:"accent-bright"}),highlight:Zt("highlight"),selected:Pt(null,{bg:"selected-bg",fg:"selected-fg"}),up:Zt("up"),down:Zt("down"),profit:Zt("profit"),loss:Zt("loss"),danger:Zt("danger"),shadow:Pt("shadow",{dialog:"shadow-dialog"}),backdrop:Zt("backdrop")};var U=Ls;function sP(){return{lineColor:U,lineWidth:2,lineStyle:"solid"}}function zo(t=""){return{value:t,size:"normal",hAlign:"left",vAlign:"top"}}var Ro=6e4,xh=60*Ro,_h=24*xh,Ng=[{key:"s",label:v("drawing.showOn.seconds","Sec"),fromMs:0},{key:"1",label:v("drawing.showOn.minute1","1m"),fromMs:Ro},{key:"5",label:v("drawing.showOn.minute5","5m"),fromMs:5*Ro},{key:"15",label:v("drawing.showOn.minute15","15m"),fromMs:15*Ro},{key:"60",label:v("drawing.showOn.hour1","1H"),fromMs:xh},{key:"240",label:v("drawing.showOn.hour4","4H"),fromMs:4*xh},{key:"D",label:v("drawing.showOn.day","D"),fromMs:_h},{key:"W",label:v("drawing.showOn.week","W"),fromMs:7*_h},{key:"M",label:v("drawing.showOn.month","M"),fromMs:28*_h}],aP=new Set(Ng.map(t=>t.key));function oP(t){if(!Array.isArray(t))return;let e=new Set(t.filter(n=>typeof n=="string"&&aP.has(n)));return Ng.map(n=>n.key).filter(n=>e.has(n))}var Cg=class Ig{constructor(e){this.locked=!1,this.visible=!0,this.zIndex=0,this.id=e.id??`dw-${Ig.seq+=1}`,this.paneId=e.paneId,this.anchors=(e.anchors??[]).map(n=>({time:n.time,price:n.price})),this.style=e.style?{...e.style}:sP(),this.text=e.text?{...e.text}:void 0,this.locked=e.locked??!1,this.visible=e.visible??!0,this.zIndex=e.zIndex??0,this.showOn=oP(e.showOn),this.createdAt=e.createdAt??Date.now(),e.props&&this.readProps(e.props)}isComplete(){return this.anchors.length>=this.anchorSchema().min}placementMode(){return"click"}onPlaced(e){}dragHandle(e,n){let r=this.anchors[e];if(!r)return;let i=this.anchorSchema().slots[e]?.free??"both";(i==="both"||i==="x")&&(r.time=n.time),(i==="both"||i==="y")&&(r.price=n.price)}constrainHandleDrag(e){}translateBody(e,n,r){return r.map(i=>({time:i.time+e,price:i.price+n}))}timeExtent(){if(this.anchors.length===0)return null;let e=1/0,n=-1/0;for(let r of this.anchors)r.time<e&&(e=r.time),r.time>n&&(n=r.time);return{min:e,max:n}}placeholderText(){return null}editableLevels(){return null}applySettings(e){for(let[n,r]of Object.entries(e))n.startsWith("text.")&&!this.text&&(this.text=zo()),lP(this,n,r)}applyProps(e){this.readProps(e)}serialize(){return{id:this.id,type:this.type,paneId:this.paneId,anchors:this.anchors.map(e=>({time:e.time,price:e.price})),style:{...this.style},text:this.text?{...this.text}:void 0,locked:this.locked,visible:this.visible,zIndex:this.zIndex,createdAt:this.createdAt,props:this.writeProps(),showOn:this.showOn?[...this.showOn]:void 0}}writeProps(){}readProps(e){}};Cg.seq=0;var Pe=Cg;function lP(t,e,n){let r=e.split("."),i=t;for(let s=0;s<r.length-1;s+=1){let a=r[s],o=i[a];(o==null||typeof o!="object")&&(o={},i[a]=o),i=o}i[r[r.length-1]]=n}var ii=[{value:"solid",label:v("drawing.option.solid","Solid")},{value:"dashed",label:v("drawing.option.dashed","Dashed")},{value:"dotted",label:v("drawing.option.dotted","Dotted")}],xe=[{path:"style.lineColor",label:v("drawing.field.lineColor","Line color"),kind:"color",group:"line"},{path:"style.lineWidth",label:v("drawing.field.lineWidth","Line width"),kind:"number",min:1,max:10,step:1,group:"line"},{path:"style.lineStyle",label:v("drawing.field.lineStyle","Line style"),kind:"lineStyle",options:ii,group:"line"}],jo=[{path:"style.lineColor",label:v("drawing.field.borderColor","Border color"),kind:"color",group:"line"},{path:"style.lineWidth",label:v("drawing.field.borderWidth","Border width"),kind:"number",min:1,max:10,step:1,group:"line"},{path:"style.lineStyle",label:v("drawing.field.borderStyle","Border style"),kind:"lineStyle",options:ii,group:"line"}],Ht=[{path:"style.fillColor",label:v("drawing.field.fillColor","Fill color"),kind:"color",group:"fill"}],Sh=[{value:"small",label:v("drawing.option.small","Small")},{value:"normal",label:v("drawing.option.normal","Normal")},{value:"large",label:v("drawing.option.large","Large")},{value:"huge",label:v("drawing.option.huge","Huge")}],_e=[{path:"text.value",label:v("drawing.field.text","Text"),kind:"text",group:"text"},{path:"text.color",label:v("drawing.field.textColor","Text color"),kind:"color",group:"text"},{path:"text.size",label:v("drawing.field.textSize","Text size"),kind:"select",options:Sh,group:"text"},{path:"text.bold",label:v("drawing.field.bold","Bold"),kind:"boolean",group:"text"},{path:"text.italic",label:v("drawing.field.italic","Italic"),kind:"boolean",group:"text"}];function ut(t,e,n,r,i,s){let a=i-n,o=s-r,l=a*a+o*o;if(l<=1e-9)return Math.hypot(t-n,e-r);let c=((t-n)*a+(e-r)*o)/l;return c=c<0?0:c>1?1:c,Math.hypot(t-(n+c*a),e-(r+c*o))}function Eh(t,e,n){let r=1/0;for(let i=1;i<n.length;i+=1){let s=n[i-1],a=n[i],o=ut(t,e,s[0],s[1],a[0],a[1]);o<r&&(r=o)}return r}function fr(t,e,n,r,i,s,a=0){let o=Math.min(n,i)-a,l=Math.max(n,i)+a,c=Math.min(r,s)-a,u=Math.max(r,s)+a;return t>=o&&t<=l&&e>=c&&e<=u}function js(t,e,n){let r=!1;for(let i=0,s=n.length-1;i<n.length;s=i,i+=1){let a=n[i],o=n[s];a[1]>e!=o[1]>e&&t<(o[0]-a[0])*(e-a[1])/(o[1]-a[1])+a[0]&&(r=!r)}return r}function De(t,e,n,r=6){for(let i=0;i<n.length;i+=1){let s=n[i];if(Math.hypot(t-s[0],e-s[1])<=r)return i}return-1}function wt(t,e,n,r,i,s,a){if(i==="none")return[t,e,n,r];let o=n-t,l=i==="left"||i==="both",c=i==="right"||i==="both";if(Math.abs(o)<1e-6){if(l&&c)return[t,0,n,a];let f=r>=e;return c?f?[t,e,n,a]:[t,e,n,0]:f?[t,0,n,r]:[t,a,n,r]}let u=(r-e)/o,h=f=>e+u*(f-t),p=l?-2:Math.min(t,n),d=c?s+2:Math.max(t,n);return[p,h(p),d,h(d)]}var cP=class extends Pe{constructor(){super(...arguments),this.type="trendline"}anchorSchema(){return{min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:[t.xOf(e.time),r,t.xOf(n.time),i]}extension(){let{extendLeft:t,extendRight:e}=this.style;return t&&e?"both":t?"left":e?"right":"none"}hitTest(t,e,n,r){let i=this.pixels(n);if(!i)return!1;let[s,a,o,l]=wt(i[0],i[1],i[2],i[3],this.extension(),n.width,n.height);return ut(t,e,s,a,o,l)<=r}handlePoints(t){let e=this.pixels(t);return e?[[e[0],e[1]],[e[2],e[3]]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pixels(t);if(!e)return null;let n=Math.min(e[0],e[2]),r=Math.min(e[1],e[3]);return{x:n,y:r,w:Math.abs(e[2]-e[0]),h:Math.abs(e[3]-e[1])}}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,{path:"style.arrowRight",label:v("drawing.trendline.arrowRight","Arrow"),kind:"boolean",group:"line"},{path:"style.extendLeft",label:v("drawing.trendline.extendLeft","Extend left"),kind:"boolean",group:"line"},{path:"style.extendRight",label:v("drawing.trendline.extendRight","Extend right"),kind:"boolean",group:"line"},..._e]}}},uP=class extends Pe{constructor(){super(...arguments),this.type="hline"}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"y"}]}}y(t){let e=this.anchors[0];return e?t.yOf(e.price,this.paneId):null}hitTest(t,e,n,r){let i=this.y(n);return i!=null&&Math.abs(e-i)<=r}handlePoints(t){let e=this.anchors[0],n=this.y(t);return!e||n==null?[]:[[t.xOf(e.time),n]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.y(t);return e==null?null:{x:0,y:e-1,w:t.width,h:2}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return{fields:[...xe,..._e]}}},hP=class extends Pe{constructor(){super(...arguments),this.type="ray"}anchorSchema(){return{min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:[t.xOf(e.time),r,t.xOf(n.time),i]}hitTest(t,e,n,r){let i=this.pixels(n);if(!i)return!1;let[s,a,o,l]=wt(i[0],i[1],i[2],i[3],"right",n.width,n.height);return ut(t,e,s,a,o,l)<=r}handlePoints(t){let e=this.pixels(t);return e?[[e[0],e[1]],[e[2],e[3]]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pixels(t);return e?{x:Math.min(e[0],e[2]),y:Math.min(e[1],e[3]),w:Math.abs(e[2]-e[0]),h:Math.abs(e[3]-e[1])}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,..._e]}}},kh=class extends Pe{anchorSchema(){return{min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:[t.xOf(e.time),r,t.xOf(n.time),i]}hitTest(t,e,n,r){let i=this.pixels(n);return i!=null&&ut(t,e,i[0],i[1],i[2],i[3])<=r}handlePoints(t){let e=this.pixels(t);return e?[[e[0],e[1]],[e[2],e[3]]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pixels(t);return e?{x:Math.min(e[0],e[2]),y:Math.min(e[1],e[3]),w:Math.abs(e[2]-e[0]),h:Math.abs(e[3]-e[1])}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,..._e]}}},pP=class extends kh{constructor(){super(...arguments),this.type="extendedline"}hitTest(t,e,n,r){let i=this.pixels(n);if(!i)return!1;let[s,a,o,l]=wt(i[0],i[1],i[2],i[3],"both",n.width,n.height);return ut(t,e,s,a,o,l)<=r}timeExtent(){return null}},dP=class extends Pe{constructor(){super(...arguments),this.type="vline"}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"x"}]}}x(t){let e=this.anchors[0];return e?t.xOf(e.time):null}hitTest(t,e,n,r){let i=this.x(n);return i!=null&&Math.abs(t-i)<=r}handlePoints(t){let e=this.anchors[0],n=this.x(t);if(!e||n==null)return[];let r=t.yOf(e.price,this.paneId);return r==null?[]:[[n,r]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.x(t);return e==null?null:{x:e-1,y:0,w:2,h:t.height}}priceRange(){return null}schema(){return{fields:[...xe,..._e]}}},fP=class extends Pe{constructor(){super(...arguments),this.type="hray"}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let e=this.anchors[0];if(!e)return null;let n=t.yOf(e.price,this.paneId);return n==null?null:[t.xOf(e.time),n]}hitTest(t,e,n,r){let i=this.pt(n);return i!=null&&ut(t,e,i[0],i[1],n.width,i[1])<=r}handlePoints(t){let e=this.pt(t);return e?[e]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pt(t);return e?{x:e[0],y:e[1]-1,w:Math.max(0,t.width-e[0]),h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){let t=this.anchors[0];return t?{min:t.time,max:Number.POSITIVE_INFINITY}:null}schema(){return{fields:[...xe,..._e]}}},mP=class extends Pe{constructor(){super(...arguments),this.type="crossline"}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let e=this.anchors[0];if(!e)return null;let n=t.yOf(e.price,this.paneId);return n==null?null:[t.xOf(e.time),n]}hitTest(t,e,n,r){let i=this.pt(n);return i!=null&&(Math.abs(e-i[1])<=r||Math.abs(t-i[0])<=r)}handlePoints(t){let e=this.pt(t);return e?[e]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pt(t);return e?{x:e[0]-1,y:e[1]-1,w:2,h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return{fields:[...xe,..._e]}}},yP=class extends kh{constructor(){super(...arguments),this.type="infoline"}},gP=class extends kh{constructor(){super(...arguments),this.type="trendangle"}},_P=class extends Pe{constructor(){super(...arguments),this.type="box"}anchorSchema(){return{min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}rect(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:{x1:t.xOf(e.time),y1:r,x2:t.xOf(n.time),y2:i}}hitTest(t,e,n,r){let i=this.rect(n);return i?this.style.fillColor&&fr(t,e,i.x1,i.y1,i.x2,i.y2)?!0:[[i.x1,i.y1,i.x2,i.y1],[i.x2,i.y1,i.x2,i.y2],[i.x2,i.y2,i.x1,i.y2],[i.x1,i.y2,i.x1,i.y1]].some(a=>ut(t,e,a[0],a[1],a[2],a[3])<=r):!1}handlePoints(t){let e=this.rect(t);if(!e)return[];let n=(e.x1+e.x2)/2,r=(e.y1+e.y2)/2;return[[e.x1,e.y1],[e.x2,e.y2],[e.x2,e.y1],[e.x1,e.y2],[n,e.y1],[e.x2,r],[n,e.y2],[e.x1,r]]}dragHandle(t,e){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return;let i=[[n,n],[r,r],[r,n],[n,r],[null,n],[r,null],[null,r],[n,null]],[s,a]=i[t]??[null,null];s&&(s.time=e.time),a&&(a.price=e.price)}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.rect(t);return e?{x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),w:Math.abs(e.x2-e.x1),h:Math.abs(e.y2-e.y1)}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...jo,{path:"style.fillColor",label:v("drawing.box.fillColor","Fill color"),kind:"color",group:"fill"},..._e]}}},bP={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},Ah=class extends Pe{defaultLabel(){return v("drawing.text.placeholder","Text")}placeholderText(){return this.defaultLabel()}labelText(){return this.text?.value??Br(this.defaultLabel())}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"both"}]}}box(t){let e=this.anchors[0];if(!e)return null;let n=t.yOf(e.price,this.paneId);if(n==null)return null;let r=bP[this.text?.size??"normal"]??14,i=this.labelText().split(`\n`),s=Math.max(1,...i.map(a=>a.length));return{x:t.xOf(e.time),y:n,w:Math.max(12,s*r*.6)+8,h:i.length*r*1.4+4}}hitTest(t,e,n,r){let i=this.box(n);return i!=null&&fr(t,e,i.x,i.y,i.x+i.w,i.y+i.h)}handlePoints(t){let e=this.anchors[0],n=e?t.yOf(e.price,this.paneId):null;return e&&n!=null?[[t.xOf(e.time),n]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){return this.box(t)}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}},xP=class extends Ah{constructor(t){super(t),this.type="text",this.text||(this.text={...zo(),size:"large"})}schema(){return{fields:[..._e],textIsContent:!0}}},vP=class extends Ah{constructor(t){super(t),this.type="note",this.text||(this.text=zo(Br(this.defaultLabel())))}defaultLabel(){return v("drawing.note.placeholder","Note")}schema(){return{fields:[...xe,...Ht,..._e],textIsContent:!0}}},wP=class extends Ah{constructor(){super(...arguments),this.type="pricelabel"}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return{fields:[...xe,...Ht,..._e.filter(t=>t.path!=="text.value")]}}},SP={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},qo=class extends Pe{constructor(t){super(t),this.text||(this.text=zo(Br(this.defaultLabel())))}defaultLabel(){return v("drawing.callout.placeholder","Callout")}placeholderText(){let t=this.defaultLabel();return Br(t)===""?null:t}labelText(){return this.text?.value??Br(this.defaultLabel())}anchorSchema(){return{min:2,max:2,slots:[{role:"target",free:"both"},{role:"box",free:"both"}]}}box(t){let e=this.anchors[1];if(!e)return null;let n=t.yOf(e.price,this.paneId);if(n==null)return null;let r=SP[this.text?.size??"normal"]??14,i=this.labelText().split(`\n`),s=Math.max(1,...i.map(l=>l.length)),a=Math.max(20,s*r*.6)+16,o=i.length*r*1.4+12;return{x:t.xOf(e.time)-a/2,y:n-o/2,w:a,h:o}}points(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:[[t.xOf(e.time),r],[t.xOf(n.time),i]]}hitTest(t,e,n,r){let i=this.box(n);if(i&&fr(t,e,i.x,i.y,i.x+i.w,i.y+i.h,r))return!0;let s=this.points(n);return s!=null&&ut(t,e,s[0][0],s[0][1],s[1][0],s[1][1])<=r}handlePoints(t){let e=this.points(t);return e?[e[0]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}translateBody(t,e,n){let r=n[0],i=n[1];return!r||!i?n.map(s=>({time:s.time+t,price:s.price+e})):[{time:r.time,price:r.price},{time:i.time+t,price:i.price+e}]}bounds(t){return this.box(t)}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,...Ht,..._e],textIsContent:!0}}},EP=class extends qo{constructor(){super(...arguments),this.type="callout"}},kP=class extends qo{constructor(){super(...arguments),this.type="pricenote"}defaultLabel(){return""}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return{fields:[...xe,...Ht,..._e.filter(t=>t.path!=="text.value")]}}},AP=class extends qo{constructor(){super(...arguments),this.type="comment"}defaultLabel(){return v("drawing.comment.placeholder","Comment")}},TP=class extends qo{constructor(){super(...arguments),this.type="signpost"}defaultLabel(){return v("drawing.signpost.placeholder","Signpost")}},Mn=class extends Pe{hitTest(t,e,n,r){let i=this.geometry(n);return i?this.style.fillColor&&i.fill&&js(t,e,i.fill)?!0:i.segments.some(s=>ut(t,e,s[0],s[1],s[2],s[3])<=r):!1}handlePoints(t){let e=[];for(let n of this.anchors){let r=t.yOf(n.price,this.paneId);if(r==null)return[];e.push([t.xOf(n.time),r])}return e}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.handlePoints(t);if(e.length===0)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}},NP=class extends Mn{constructor(){super(...arguments),this.type="parallelchannel"}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"y"}]}}offset(){let t=this.anchors[0],e=this.anchors[1],n=this.anchors[2];return!t||!e||!n?0:n.price-(t.price+e.price)/2}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return[];let s=[[t.xOf(e.time),r],[t.xOf(n.time),i]],a=this.anchors[2];if(a){let o=t.yOf(a.price,this.paneId);o!=null&&s.push([t.xOf((e.time+n.time)/2),o])}return s}timeExtent(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.time,e.time),max:Math.max(t.time,e.time)}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=this.offset(),i=t.xOf(e.time),s=t.xOf(n.time),a=t.yOf(e.price,this.paneId),o=t.yOf(n.price,this.paneId),l=t.yOf(e.price+r,this.paneId),c=t.yOf(n.price+r,this.paneId);return a==null||o==null||l==null||c==null?null:{segments:[[i,a,s,o],[i,l,s,c]],fill:[[i,a],[s,o],[s,c],[i,l]]}}priceRange(){let t=this.anchors[0],e=this.anchors[1];if(!t||!e)return null;let n=this.offset(),r=[t.price,e.price,t.price+n,e.price+n],i=this.anchors[2];return i&&r.push(i.price),{min:Math.min(...r),max:Math.max(...r)}}schema(){return{fields:[...xe,...Ht,..._e]}}},CP=class extends Mn{constructor(){super(...arguments),this.type="disjointchannel"}anchorSchema(){return{min:4,max:4,slots:[{role:"top1",free:"both"},{role:"top2",free:"both"},{role:"bot1",free:"both"},{role:"bot2",free:"both"}]}}seg(t,e,n){let r=this.anchors[t],i=this.anchors[e];if(!r||!i)return null;let s=n.yOf(r.price,this.paneId),a=n.yOf(i.price,this.paneId);return s==null||a==null?null:[n.xOf(r.time),s,n.xOf(i.time),a]}geometry(t){let e=this.seg(0,1,t),n=this.seg(2,3,t),r=[e,n].filter(s=>s!=null);if(r.length===0)return null;let i=e&&n?[[e[0],e[1]],[e[2],e[3]],[n[2],n[3]],[n[0],n[1]]]:null;return{segments:r,fill:i}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,...Ht,..._e]}}},IP=class extends Mn{constructor(){super(...arguments),this.type="flattopbottom"}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"flat",free:"y"}]}}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return[];let s=[[t.xOf(e.time),r],[t.xOf(n.time),i]],a=this.anchors[2];if(a){let o=t.yOf(a.price,this.paneId);o!=null&&s.push([t.xOf((e.time+n.time)/2),o])}return s}timeExtent(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.time,e.time),max:Math.max(t.time,e.time)}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.xOf(e.time),i=t.xOf(n.time),s=t.yOf(e.price,this.paneId),a=t.yOf(n.price,this.paneId);if(s==null||a==null)return null;let o=this.anchors[2];if(!o)return{segments:[[r,s,i,a]],fill:null};let l=t.yOf(o.price,this.paneId);return l==null?null:{segments:[[r,s,i,a],[r,l,i,l]],fill:[[r,s],[i,a],[i,l],[r,l]]}}priceRange(){let t=this.anchors[0],e=this.anchors[1];if(!t||!e)return null;let n=[t.price,e.price],r=this.anchors[2];return r&&n.push(r.price),{min:Math.min(...n),max:Math.max(...n)}}schema(){return{fields:[...xe,...Ht,..._e]}}},MP=2;function sg(){return{midColor:hr,midStyle:"solid",upperColor:dt,upperStyle:"solid",lowerColor:Wt,lowerStyle:"solid",upperFill:`${dt}26`,lowerFill:`${Wt}26`,showR2:!0}}function PP(t){let e=t.length;if(e<2)return null;let n=0,r=0,i=0,s=0,a=0;for(let f=0;f<e;f+=1){let m=t[f].close;n+=f,r+=m,i+=f*m,s+=f*f,a+=m*m}let o=e*s-n*n,l=o===0?0:(e*i-n*r)/o,c=(r-l*n)/e,u=0;for(let f=0;f<e;f+=1){let m=t[f].close-(c+l*f);u+=m*m}let h=Math.sqrt(u/e),p=Math.sqrt(o*(e*a-r*r)),d=p===0?0:(e*i-n*r)/p;return{t0:t[0].time,t1:t[e-1].time,mid0:c,mid1:c+l*(e-1),dev:MP*h,r2:Math.max(0,Math.min(1,d*d)),n:e}}var DP=class extends Pe{constructor(t){super(t),this.type="regressionchannel",this.cachedRange=null,this.reg||(this.reg=sg())}anchorSchema(){return{min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}fit(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=Math.min(e.time,n.time),i=Math.max(e.time,n.time),s=t.barsInRange?.(r,i)??null,a=s?PP(s):null;return a&&(this.cachedRange={min:Math.min(a.mid0,a.mid1)-a.dev,max:Math.max(a.mid0,a.mid1)+a.dev}),a}layout(t){let e=this.fit(t);if(!e)return null;let n=t.yOf(e.mid0,this.paneId),r=t.yOf(e.mid1,this.paneId),i=t.yOf(e.mid0+e.dev,this.paneId),s=t.yOf(e.mid1+e.dev,this.paneId),a=t.yOf(e.mid0-e.dev,this.paneId),o=t.yOf(e.mid1-e.dev,this.paneId);return n==null||r==null||i==null||s==null||a==null||o==null?null:{x0:t.xOf(e.t0),x1:t.xOf(e.t1),midY0:n,midY1:r,upperY0:i,upperY1:s,lowerY0:a,lowerY1:o,r2:e.r2,showR2:this.reg.showR2}}band(t){let e=this.layout(t);return e?[[e.x0,e.upperY0],[e.x1,e.upperY1],[e.x1,e.lowerY1],[e.x0,e.lowerY0]]:null}hitTest(t,e,n,r){let i=this.layout(n);if(!i)return!1;let s=[[i.x0,i.upperY0],[i.x1,i.upperY1],[i.x1,i.lowerY1],[i.x0,i.lowerY0]];return js(t,e,s)?!0:[[i.x0,i.midY0,i.x1,i.midY1],[i.x0,i.upperY0,i.x1,i.upperY1],[i.x0,i.lowerY0,i.x1,i.lowerY1]].some(o=>ut(t,e,o[0],o[1],o[2],o[3])<=r)}handlePoints(t){let e=this.layout(t);if(e)return[[e.x0,e.midY0],[e.x1,e.midY1]];let n=[];for(let r of this.anchors){let i=t.yOf(r.price,this.paneId);if(i==null)return[];n.push([t.xOf(r.time),i])}return n}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.band(t);if(!e)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[{path:"reg.midColor",label:v("drawing.regressionchannel.regMidColor","Midline color"),kind:"color",group:"line"},{path:"reg.midStyle",label:v("drawing.regressionchannel.regMidStyle","Midline style"),kind:"lineStyle",group:"line"},{path:"reg.upperColor",label:v("drawing.regressionchannel.regUpperColor","Upper line color"),kind:"color",group:"line"},{path:"reg.upperStyle",label:v("drawing.regressionchannel.regUpperStyle","Upper line style"),kind:"lineStyle",group:"line"},{path:"reg.lowerColor",label:v("drawing.regressionchannel.regLowerColor","Lower line color"),kind:"color",group:"line"},{path:"reg.lowerStyle",label:v("drawing.regressionchannel.regLowerStyle","Lower line style"),kind:"lineStyle",group:"line"},{path:"reg.upperFill",label:v("drawing.regressionchannel.regUpperFill","Upper fill"),kind:"color",group:"fill"},{path:"reg.lowerFill",label:v("drawing.regressionchannel.regLowerFill","Lower fill"),kind:"color",group:"fill"},{path:"reg.showR2",label:v("drawing.regressionchannel.regShowR2","Show R\\xB2"),kind:"boolean",group:"behavior"}]}}writeProps(){return{...this.reg}}readProps(t){this.reg={...sg(),...t}}},ag=`${pr}00`;function og(){return{midColor:pr,midStyle:"solid",multiplier:1,upperColor:ag,upperStyle:"solid",lowerColor:ag,lowerStyle:"solid",bandFill:`${pr}33`}}function OP(t,e){let n=t.length;if(n<1)return null;let r=0;for(let c of t)r+=c.volume>0?c.volume:0;let i=r>0,s=0,a=0,o=0,l=[];for(let c=0;c<n;c+=1){let u=t[c],h=(u.high+u.low+u.close)/3,p=i?Math.max(0,u.volume):1;s+=p,a+=h*p,o+=h*h*p;let d=s>0?a/s:h,f=s>0?Math.max(0,o/s-d*d):0,m=Math.sqrt(f)*e;l.push({time:u.time,mid:d,upper:d+m,lower:d-m})}return l}var RP=class extends Pe{constructor(t){super(t),this.type="anchoredvwap",this.cachedRange=null,this.cachedExtent=null,this.vwap||(this.vwap=og())}anchorSchema(){return{min:1,max:1,slots:[{role:"anchor",free:"x"}]}}series(t){let e=this.anchors[0];if(!e)return null;let n=t.barsInRange?.(e.time,Number.POSITIVE_INFINITY)??null;if(!n||n.length<1)return null;let r=OP(n.map(i=>({time:i.time,high:i.high,low:i.low,close:i.close,volume:i.volume??0})),this.vwap.multiplier);if(r&&r.length>0){let i=1/0,s=-1/0;for(let a of r)a.lower<i&&(i=a.lower),a.upper>s&&(s=a.upper);this.cachedRange={min:i,max:s},this.cachedExtent={min:r[0].time,max:r[r.length-1].time}}return r}layout(t){let e=this.series(t);if(!e)return null;let n=[],r=[],i=[];for(let s of e){let a=t.xOf(s.time),o=t.yOf(s.mid,this.paneId),l=t.yOf(s.upper,this.paneId),c=t.yOf(s.lower,this.paneId);o==null||l==null||c==null||(n.push([a,o]),r.push([a,l]),i.push([a,c]))}return n.length>0?{mid:n,upper:r,lower:i}:null}bandPolygon(t){return[...t.upper,...[...t.lower].reverse()]}hitTest(t,e,n,r){let i=this.layout(n);return i?js(t,e,this.bandPolygon(i))?!0:bh(t,e,i.mid,r)||bh(t,e,i.upper,r)||bh(t,e,i.lower,r):!1}handlePoints(t){let e=this.layout(t);if(e&&e.mid.length>0)return[e.mid[0]];let n=this.anchors[0];if(!n)return[];let r=t.yOf(n.price,this.paneId);return r==null?[]:[[t.xOf(n.time),r]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.layout(t);if(!e)return null;let n=[...e.upper,...e.lower],r=n.map(o=>o[0]),i=n.map(o=>o[1]),s=Math.min(...r),a=Math.min(...i);return{x:s,y:a,w:Math.max(...r)-s,h:Math.max(...i)-a}}priceRange(){return this.cachedRange}timeExtent(){return this.cachedExtent}schema(){return{fields:[{path:"vwap.midColor",label:v("drawing.anchoredvwap.vwapMidColor","VWAP color"),kind:"color",group:"line"},{path:"vwap.midStyle",label:v("drawing.anchoredvwap.vwapMidStyle","VWAP style"),kind:"lineStyle",group:"line"},{path:"vwap.multiplier",label:v("drawing.anchoredvwap.vwapMultiplier","Band multiplier"),kind:"number",min:.5,max:5,step:.5,group:"behavior"},{path:"vwap.upperColor",label:v("drawing.anchoredvwap.vwapUpperColor","Upper band color"),kind:"color",group:"line"},{path:"vwap.lowerColor",label:v("drawing.anchoredvwap.vwapLowerColor","Lower band color"),kind:"color",group:"line"},{path:"vwap.bandFill",label:v("drawing.anchoredvwap.vwapBandFill","Band fill"),kind:"color",group:"fill"}]}}writeProps(){return{...this.vwap}}readProps(t){this.vwap={...og(),...t}}};function bh(t,e,n,r){for(let i=1;i<n.length;i+=1)if(ut(t,e,n[i-1][0],n[i-1][1],n[i][0],n[i][1])<=r)return!0;return!1}var LP=`${dt}66`,FP=`${Wt}66`,BP=`${dt}BF`,VP=`${Wt}BF`;function lg(){return{rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:LP,downColor:FP,vaUpColor:BP,vaDownColor:VP,showVah:!0,vahColor:hr,vahStyle:"solid",showVal:!0,valColor:hr,valStyle:"solid",showPoc:!0,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:!1,developingPocColor:ur,developingPocStyle:"dotted",showDevelopingVa:!1,developingVaColor:ur,developingVaStyle:"dotted"}}function $P(t,e){return t<0?0:t>=e?e-1:t}function Mg(t,e,n){let r=t.length,i=0,s=0;for(let u=0;u<r;u+=1){let h=t[u].up+t[u].down;i+=h,h>s&&(s=h)}let a=i*Math.min(1,Math.max(0,n)),o=e,l=e,c=s;for(;c<a&&(o>0||l<r-1);){let u=o>0?t[o-1].up+t[o-1].down:-1,h=l<r-1?t[l+1].up+t[l+1].down:-1;h>u?(l+=1,c+=h):(o-=1,c+=u)}return{vaFrom:o,vaTo:l}}function Pg(t,e,n,r){let i=r.volume;if(!(i>0))return;let s=t.length,a=r.close>=r.open?"up":"down",o=new Set;for(let l of[r.open,r.high,r.low,r.close])o.add($P(Math.floor((l-e)/n),s));for(let l of o)t[l][a]+=i}function Dg(t){let e=0,n=0;for(let r=0;r<t.length;r+=1){let i=t[r].up+t[r].down;i>e&&(e=i,n=r)}return e>0?{poc:n,maxTotal:e}:null}function zP(t,e,n){let r=1/0,i=-1/0;for(let d of t)d.volume>0&&(d.low<r&&(r=d.low),d.high>i&&(i=d.high));if(!Number.isFinite(r))return null;let s=i>r?Math.max(1,Math.round(e)):1,a=i>r?(i-r)/s:1,o=Array.from({length:s},(d,f)=>({price:r+f*a,up:0,down:0}));for(let d of t)Pg(o,r,a,d);let l=Dg(o);if(!l)return null;let{poc:c,maxTotal:u}=l,{vaFrom:h,vaTo:p}=Mg(o,c,n);return{rows:o,rowH:a,min:r,maxTotal:u,poc:c,vaFrom:h,vaTo:p}}function jP(t,e,n,r){let i=zP(t,e,n);if(!i)return null;if(!r||t.length<1)return{profile:i,developingPoc:[],developingVaHigh:[],developingVaLow:[]};let{min:s,rowH:a}=i,o=i.rows.length,l=Array.from({length:o},(p,d)=>({price:s+d*a,up:0,down:0})),c=[],u=[],h=[];for(let p of t){Pg(l,s,a,p);let d=Dg(l);if(!d)continue;let{poc:f}=d,{vaFrom:m,vaTo:y}=Mg(l,f,n);c.push({time:p.time,price:l[f].price+a/2}),u.push({time:p.time,price:l[y].price+a}),h.push({time:p.time,price:l[m].price})}return{profile:i,developingPoc:c,developingVaHigh:u,developingVaLow:h}}var qP=class extends Pe{constructor(t){super(t),this.type="fixedrangevp",this.cachedRange=null,this.frvp||(this.frvp=lg())}anchorSchema(){return{min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}barsInSpan(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=Math.min(e.time,n.time),i=Math.max(e.time,n.time),s=t.barsInRange?.(r,i)??null;return!s||s.length<1?null:s.map(a=>({time:a.time,open:a.open,high:a.high,low:a.low,close:a.close,volume:a.volume??0}))}compute(t){let e=this.barsInSpan(t);if(!e)return null;let n=this.frvp,r=n.showDevelopingPoc||n.showDevelopingVa,i=jP(e,n.rows,n.valueAreaPct/100,r);if(i){let{profile:s}=i;this.cachedRange={min:s.min,max:s.min+s.rowH*s.rows.length}}return i}layout(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=this.compute(t);if(!r)return null;let{profile:i}=r,s=Math.min(e.time,n.time),a=Math.max(e.time,n.time),o=t.xOf(s),l=t.xOf(a),c=Math.abs(l-o),u=Math.max(1,Math.min(100,Math.max(0,this.frvp.widthPct))/100*c),h=this.frvp.anchor==="left",p=h?Math.min(o,l):Math.max(o,l),d=h?1:-1,f=[];for(let S=0;S<=i.rows.length;S+=1){let E=t.yOf(i.min+S*i.rowH,this.paneId);if(E==null)return null;f.push(E)}let m=S=>t.yOf(S,this.paneId),y=i.rows[i.vaTo].price+i.rowH,g=i.rows[i.vaFrom].price,w=i.rows[i.poc].price+i.rowH/2,k=S=>{let E=[];for(let T of S){let N=m(T.price);N!=null&&E.push([t.xOf(T.time),N])}return E};return{x0:Math.min(o,l),x1:Math.max(o,l),anchorX:p,maxW:u,grow:d,profile:i,yEdges:f,vahY:m(y),valY:m(g),pocY:m(w),developingPoc:k(r.developingPoc),developingVaHigh:k(r.developingVaHigh),developingVaLow:k(r.developingVaLow)}}hitTest(t,e,n,r){let i=this.layout(n);if(!i)return!1;let s=i.grow===1?i.anchorX:i.anchorX-i.maxW,a=i.grow===1?i.anchorX+i.maxW:i.anchorX,o=Math.min(i.yEdges[0],i.yEdges[i.yEdges.length-1]),l=Math.max(i.yEdges[0],i.yEdges[i.yEdges.length-1]);if(js(t,e,[[s,o],[a,o],[a,l],[s,l]]))return!0;let c=[[i.x0,i.vahY],[i.x0,i.valY],[i.x0,i.pocY]];for(let[,u]of c)if(u!=null&&ut(t,e,i.x0,u,i.x1,u)<=r)return!0;for(let u of[i.developingPoc,i.developingVaHigh,i.developingVaLow])for(let h=1;h<u.length;h+=1)if(ut(t,e,u[h-1][0],u[h-1][1],u[h][0],u[h][1])<=r)return!0;return!1}handlePoints(t){let e=this.layout(t);if(e&&e.pocY!=null)return[[e.x0,e.pocY],[e.x1,e.pocY]];let n=[];for(let r of this.anchors){let i=t.yOf(r.price,this.paneId);if(i==null)return[];n.push([t.xOf(r.time),i])}return n}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.layout(t);if(!e)return null;let n=Math.min(e.x0,e.grow===1?e.anchorX:e.anchorX-e.maxW),r=Math.max(e.x1,e.grow===1?e.anchorX+e.maxW:e.anchorX),i=Math.min(e.yEdges[0],e.yEdges[e.yEdges.length-1]),s=Math.max(e.yEdges[0],e.yEdges[e.yEdges.length-1]);return{x:n,y:i,w:r-n,h:s-i}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[{path:"frvp.rows",label:v("drawing.fixedrangevp.frvpRows","Rows"),kind:"number",min:1,max:500,step:1,group:"behavior"},{path:"frvp.valueAreaPct",label:v("drawing.fixedrangevp.frvpValueAreaPct","Value Area"),kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.widthPct",label:v("drawing.fixedrangevp.frvpWidthPct","Width %"),kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.anchor",label:v("drawing.fixedrangevp.frvpAnchor","Anchor"),kind:"select",options:[{value:"right",label:v("drawing.fixedrangevp.option.right","Right")},{value:"left",label:v("drawing.fixedrangevp.option.left","Left")}],group:"behavior"},{path:"frvp.upColor",label:v("drawing.fixedrangevp.frvpUpColor","Up Volume"),kind:"color",group:"fill"},{path:"frvp.downColor",label:v("drawing.fixedrangevp.frvpDownColor","Down Volume"),kind:"color",group:"fill"},{path:"frvp.vaUpColor",label:v("drawing.fixedrangevp.frvpVaUpColor","Value Area Up"),kind:"color",group:"fill"},{path:"frvp.vaDownColor",label:v("drawing.fixedrangevp.frvpVaDownColor","Value Area Down"),kind:"color",group:"fill"},{path:"frvp.showVah",label:v("drawing.fixedrangevp.frvpShowVah","VAH"),kind:"boolean",group:"line"},{path:"frvp.vahColor",label:v("drawing.fixedrangevp.frvpVahColor","VAH color"),kind:"color",group:"line"},{path:"frvp.vahStyle",label:v("drawing.fixedrangevp.frvpVahStyle","VAH style"),kind:"lineStyle",options:ii,group:"line"},{path:"frvp.showVal",label:v("drawing.fixedrangevp.frvpShowVal","VAL"),kind:"boolean",group:"line"},{path:"frvp.valColor",label:v("drawing.fixedrangevp.frvpValColor","VAL color"),kind:"color",group:"line"},{path:"frvp.valStyle",label:v("drawing.fixedrangevp.frvpValStyle","VAL style"),kind:"lineStyle",options:ii,group:"line"},{path:"frvp.showPoc",label:v("drawing.fixedrangevp.frvpShowPoc","POC"),kind:"boolean",group:"line"},{path:"frvp.pocColor",label:v("drawing.fixedrangevp.frvpPocColor","POC color"),kind:"color",group:"line"},{path:"frvp.pocStyle",label:v("drawing.fixedrangevp.frvpPocStyle","POC style"),kind:"lineStyle",options:ii,group:"line"},{path:"frvp.showDevelopingPoc",label:v("drawing.fixedrangevp.frvpShowDevelopingPoc","Developing POC"),kind:"boolean",group:"line"},{path:"frvp.developingPocColor",label:v("drawing.fixedrangevp.frvpDevelopingPocColor","Developing POC color"),kind:"color",group:"line"},{path:"frvp.developingPocStyle",label:v("drawing.fixedrangevp.frvpDevelopingPocStyle","Developing POC style"),kind:"lineStyle",options:ii,group:"line"},{path:"frvp.showDevelopingVa",label:v("drawing.fixedrangevp.frvpShowDevelopingVa","Developing VA"),kind:"boolean",group:"line"},{path:"frvp.developingVaColor",label:v("drawing.fixedrangevp.frvpDevelopingVaColor","Developing VA color"),kind:"color",group:"line"},{path:"frvp.developingVaStyle",label:v("drawing.fixedrangevp.frvpDevelopingVaStyle","Developing VA style"),kind:"lineStyle",options:ii,group:"line"}]}}writeProps(){return{...this.frvp}}readProps(t){this.frvp={...lg(),...t}}},UP=class extends Mn{constructor(){super(...arguments),this.type="pitchfork"}anchorSchema(){return{min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=f=>{let m=t.yOf(f.price,this.paneId);return m==null?null:[t.xOf(f.time),m]},i=r(e),s=r(n);if(!i||!s)return null;let a=this.anchors[2];if(!a)return{segments:[[i[0],i[1],s[0],s[1]]],fill:null};let o=r(a);if(!o)return null;let l=(s[0]+o[0])/2,c=(s[1]+o[1])/2,u=l-i[0],h=c-i[1],p=t.width,d=t.height;return{segments:[wt(i[0],i[1],l,c,"right",p,d),wt(s[0],s[1],s[0]+u,s[1]+h,"right",p,d),wt(o[0],o[1],o[0]+u,o[1]+h,"right",p,d),[s[0],s[1],o[0],o[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,..._e]}}},Og=class extends Mn{anchorSchema(){return{min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=m=>{let y=t.yOf(m.price,this.paneId);return y==null?null:[t.xOf(m.time),y]},i=r(e),s=r(n);if(!i||!s)return null;let a=this.anchors[2];if(!a)return{segments:[[i[0],i[1],s[0],s[1]]],fill:null};let o=r(this.medianStart(e,n,a)),l=r(a);if(!o||!l)return null;let c=(s[0]+l[0])/2,u=(s[1]+l[1])/2,h=c-o[0],p=u-o[1],d=t.width,f=t.height;return{segments:[wt(o[0],o[1],c,u,"right",d,f),wt(s[0],s[1],s[0]+h,s[1]+p,"right",d,f),wt(l[0],l[1],l[0]+h,l[1]+p,"right",d,f),[s[0],s[1],l[0],l[1]],[i[0],i[1],s[0],s[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,..._e]}}},WP=class extends Og{constructor(){super(...arguments),this.type="schiffpitchfork"}medianStart(t,e){return{time:t.time,price:(t.price+e.price)/2}}},HP=class extends Og{constructor(){super(...arguments),this.type="modifiedschiffpitchfork"}medianStart(t,e){return{time:(t.time+e.time)/2,price:(t.price+e.price)/2}}},GP=class extends Mn{constructor(){super(...arguments),this.type="insidepitchfork"}anchorSchema(){return{min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=m=>{let y=t.yOf(m.price,this.paneId);return y==null?null:[t.xOf(m.time),y]},i=r(e),s=r(n);if(!i||!s)return null;let a=this.anchors[2];if(!a)return{segments:[[i[0],i[1],s[0],s[1]]],fill:null};let o=r({time:(e.time+n.time)/2,price:(e.price+n.price)/2}),l=r(a);if(!o||!l)return null;let c=(s[0]+l[0])/2,u=(s[1]+l[1])/2,h=l[0]-o[0],p=l[1]-o[1],d=t.width,f=t.height;return{segments:[wt(c,u,c+h,u+p,"right",d,f),wt(s[0],s[1],s[0]+h,s[1]+p,"right",d,f),wt(l[0],l[1],l[0]+h,l[1]+p,"right",d,f),[s[0],s[1],l[0],l[1]],[o[0],o[1],l[0],l[1]],[i[0],i[1],s[0],s[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,..._e]}}},KP=class extends Pe{constructor(){super(...arguments),this.type="arrow"}anchorSchema(){return{min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:[t.xOf(e.time),r,t.xOf(n.time),i]}hitTest(t,e,n,r){let i=this.pixels(n);return i!=null&&ut(t,e,i[0],i[1],i[2],i[3])<=r}handlePoints(t){let e=this.pixels(t);return e?[[e[0],e[1]],[e[2],e[3]]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.pixels(t);return e?{x:Math.min(e[0],e[2]),y:Math.min(e[1],e[3]),w:Math.abs(e[2]-e[0]),h:Math.abs(e[3]-e[1])}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,{path:"style.arrowRight",label:v("drawing.arrow.arrowRight","Head (end)"),kind:"boolean",group:"line"},{path:"style.arrowLeft",label:v("drawing.arrow.arrowLeft","Head (start)"),kind:"boolean",group:"line"},..._e]}}},cg=48,YP=class extends Pe{constructor(){super(...arguments),this.type="ellipse"}anchorSchema(){return{min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}oval(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time);return{cx:(s+a)/2,cy:(r+i)/2,rx:Math.abs(a-s)/2,ry:Math.abs(i-r)/2}}perimeter(t){let e=[];for(let n=0;n<=cg;n+=1){let r=n/cg*Math.PI*2;e.push([t.cx+t.rx*Math.cos(r),t.cy+t.ry*Math.sin(r)])}return e}hitTest(t,e,n,r){let i=this.oval(n);if(!i||i.rx<1||i.ry<1)return!1;let s=((t-i.cx)/i.rx)**2+((e-i.cy)/i.ry)**2;return this.style.fillColor&&s<=1?!0:Eh(t,e,this.perimeter(i))<=r}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?[]:[[t.xOf(e.time),r],[t.xOf(n.time),i]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.oval(t);return e?{x:e.cx-e.rx,y:e.cy-e.ry,w:e.rx*2,h:e.ry*2}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,...Ht,..._e]}}},XP=class extends Mn{constructor(){super(...arguments),this.type="triangle"}anchorSchema(){return{min:3,max:3,slots:[{role:"v1",free:"both"},{role:"v2",free:"both"},{role:"v3",free:"both"}]}}geometry(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=l=>{let c=t.yOf(l.price,this.paneId);return c==null?null:[t.xOf(l.time),c]},i=r(e),s=r(n);if(!i||!s)return null;let a=this.anchors[2];if(!a)return{segments:[[i[0],i[1],s[0],s[1]]],fill:null};let o=r(a);return o?{segments:[[i[0],i[1],s[0],s[1]],[s[0],s[1],o[0],o[1]],[o[0],o[1],i[0],i[1]]],fill:[i,s,o]}:null}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,...Ht,..._e]}}},ZP=512,Th=class extends Mn{anchorSchema(){return{min:2,max:ZP,slots:[]}}geometry(t){let e=[];for(let r of this.anchors){let i=t.yOf(r.price,this.paneId);if(i==null)return null;e.push([t.xOf(r.time),i])}if(e.length<2)return null;let n=[];for(let r=1;r<e.length;r+=1)n.push([e[r-1][0],e[r-1][1],e[r][0],e[r][1]]);return{segments:n,fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,..._e]}}},JP=class extends Th{constructor(){super(...arguments),this.type="polyline"}},Rg=class extends Th{placementMode(){return"freehand"}handlePoints(t){return[]}bounds(t){let e=[],n=[];for(let s of this.anchors){let a=t.yOf(s.price,this.paneId);a!=null&&(e.push(t.xOf(s.time)),n.push(a))}if(e.length===0)return null;let r=Math.min(...e),i=Math.min(...n);return{x:r,y:i,w:Math.max(...e)-r,h:Math.max(...n)-i}}},QP=class extends Rg{constructor(){super(...arguments),this.type="freehand"}},eD=[{path:"style.lineColor",label:v("drawing.highlighter.lineColor","Color"),kind:"color",group:"line"},{path:"style.lineWidth",label:v("drawing.highlighter.lineWidth","Width"),kind:"number",min:4,max:60,step:1,group:"line"}],tD=class extends Rg{constructor(){super(...arguments),this.type="highlighter"}schema(){return{fields:eD}}},nD=class extends Pe{constructor(){super(...arguments),this.type="circle"}anchorSchema(){return{min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}geom(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time);return{cx:s,cy:r,r:Math.hypot(a-s,i-r)}}hitTest(t,e,n,r){let i=this.geom(n);if(!i||i.r<1)return!1;let s=Math.hypot(t-i.cx,e-i.cy);return this.style.fillColor&&s<=i.r?!0:Math.abs(s-i.r)<=r}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?[]:[[t.xOf(e.time),r],[t.xOf(n.time),i]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.geom(t);return e?{x:e.cx-e.r,y:e.cy-e.r,w:e.r*2,h:e.r*2}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,...Ht,..._e]}}},rD=class extends Mn{constructor(){super(...arguments),this.type="rotatedrect"}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"w",free:"both"}]}}px(t,e){let n=this.anchors[e];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}geometry(t){let e=this.px(t,0),n=this.px(t,1);if(!e||!n)return null;let r=this.px(t,2);if(!r||this.anchors.length<3)return{segments:[[e[0],e[1],n[0],n[1]]],fill:null};let i=n[0]-e[0],s=n[1]-e[1],a=Math.hypot(i,s);if(a<1e-6)return{segments:[[e[0],e[1],n[0],n[1]]],fill:null};let o=-s/a,l=i/a,c=(r[0]-e[0])*o+(r[1]-e[1])*l,u=o*c,h=l*c,p=e,d=n,f=[n[0]+u,n[1]+h],m=[e[0]+u,e[1]+h];return{segments:[[p[0],p[1],d[0],d[1]],[d[0],d[1],f[0],f[1]],[f[0],f[1],m[0],m[1]],[m[0],m[1],p[0],p[1]]],fill:[p,d,f,m]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...jo,...Ht,..._e]}}},iD=class extends Th{constructor(){super(...arguments),this.type="path"}},ug=40,sD=class extends Mn{constructor(){super(...arguments),this.type="arc"}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"apex",free:"both"}]}}pinApex(){let t=this.anchors[0],e=this.anchors[1],n=this.anchors[2];t&&e&&n&&(n.time=(t.time+e.time)/2)}onPlaced(){this.pinApex()}constrainHandleDrag(){this.pinApex()}px(t,e){let n=this.anchors[e];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}geometry(t){let e=this.px(t,0),n=this.px(t,1);if(!e||!n)return null;let r=this.anchors[2];if(!r||this.anchors.length<3)return{segments:[[e[0],e[1],n[0],n[1]]],fill:null};let i=t.yOf(r.price,this.paneId);if(i==null)return null;let s=(e[0]+n[0])/2,a=(e[1]+n[1])/2,o=(n[0]-e[0])/2,l=(n[1]-e[1])/2,c=Math.hypot(o,l);if(c<1e-6)return{segments:[[e[0],e[1],n[0],n[1]]],fill:null};let u=-l/c,h=o/c,p=(i-a)*h;p<0&&(u=-u,h=-h);let d=Math.abs(p),f=[];for(let y=0;y<=ug;y+=1){let g=y/ug*Math.PI,w=Math.cos(g),k=Math.sin(g);f.push([s+w*o+k*d*u,a+w*l+k*d*h])}let m=[];for(let y=1;y<f.length;y+=1)m.push([f[y-1][0],f[y-1][1],f[y][0],f[y][1]]);return m.push([f[f.length-1][0],f[f.length-1][1],f[0][0],f[0][1]]),{segments:m,fill:f}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...jo,...Ht,..._e]}}},hg=40,aD=class extends Mn{constructor(){super(...arguments),this.type="curve"}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"control",free:"both"}]}}px(t,e){let n=this.anchors[e];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}geometry(t){let e=this.px(t,0),n=this.px(t,1);if(!e||!n)return null;let r=this.px(t,2);if(!r||this.anchors.length<3)return{segments:[[e[0],e[1],n[0],n[1]]],fill:null};let i=[];for(let a=0;a<=hg;a+=1){let o=a/hg,l=1-o;i.push([l*l*e[0]+2*l*o*r[0]+o*o*n[0],l*l*e[1]+2*l*o*r[1]+o*o*n[1]])}let s=[];for(let a=1;a<i.length;a+=1)s.push([i[a-1][0],i[a-1][1],i[a][0],i[a][1]]);return{segments:s,fill:i}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}schema(){return{fields:[...xe,...Ht,..._e]}}},oD={head:11,headW:9,stemW:3.5,len:22},Lg=class extends Pe{anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"both"}]}}glyphPoints(t){let e=this.anchors[0];if(!e)return null;let n=t.yOf(e.price,this.paneId);if(n==null)return null;let r=t.xOf(e.time),{head:i,headW:s,stemW:a,len:o}=oD,l=[[0,0],[-s,i],[-a,i],[-a,o],[a,o],[a,i],[s,i]],c=this.dir(),u=([h,p])=>{switch(c){case"up":return[h,p];case"down":return[h,-p];case"left":return[p,h];default:return[-p,h]}};return l.map(h=>{let[p,d]=u(h);return[r+p,n+d]})}hitTest(t,e,n,r){let i=this.glyphPoints(n);return i!=null&&js(t,e,i)}handlePoints(t){let e=this.anchors[0];if(!e)return[];let n=t.yOf(e.price,this.paneId);return n==null?[]:[[t.xOf(e.time),n]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.glyphPoints(t);if(!e)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}schema(){return{fields:[{path:"style.lineColor",label:v("drawing.arrowmarkup.lineColor","Color"),kind:"color",group:"line"},..._e]}}},lD=class extends Lg{constructor(){super(...arguments),this.type="arrowmarkup"}dir(){return"up"}},cD=class extends Lg{constructor(){super(...arguments),this.type="arrowmarkdown"}dir(){return"down"}},uD=["\\u2605","\\u2606","\\u25CF","\\u25C6","\\u25B2","\\u25BC","\\u27A4","\\u2691","\\u271A","\\u2715","\\u2764","\\u2666"],hD=["small","normal","large","huge"],pg={small:16,normal:22,large:32,huge:44},Fg=class extends Pe{constructor(t){super(t),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal")}sizePx(){return pg[this.size]??pg.normal}anchorSchema(){return{min:1,max:1,slots:[{role:"p",free:"both"}]}}center(t){let e=this.anchors[0];if(!e)return null;let n=t.yOf(e.price,this.paneId);return n==null?null:[t.xOf(e.time),n]}hitTest(t,e,n,r){let i=this.center(n);if(!i)return!1;let s=this.sizePx()/2+r;return Math.abs(t-i[0])<=s&&Math.abs(e-i[1])<=s}handlePoints(t){let e=this.center(t);return e?[e]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.center(t);if(!e)return null;let n=this.sizePx();return{x:e[0]-n/2,y:e[1]-n/2,w:n,h:n}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}schema(){return{fields:[{path:"glyph",label:v("drawing.flagmark.glyph","Icon"),kind:"select",options:uD.map(t=>({value:t,label:t})),group:"line"},{path:"size",label:v("drawing.flagmark.size","Size"),kind:"select",options:hD.map(t=>({value:t,label:t})),group:"line"},{path:"style.lineColor",label:v("drawing.flagmark.lineColor","Color"),kind:"color",group:"line"},..._e]}}writeProps(){return{glyph:this.glyph,size:this.size}}readProps(t){typeof t.glyph=="string"&&(this.glyph=t.glyph),typeof t.size=="string"&&(this.size=t.size)}},pD=class extends Fg{constructor(){super(...arguments),this.type="flagmark"}defaultGlyph(){return"\\u2691"}},dD=class extends Fg{constructor(){super(...arguments),this.type="iconstamp"}defaultGlyph(){return"\\u2605"}},dg=t=>t==="small"||t==="normal"||t==="large"||t==="huge";function fD(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==!1,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Pn=class extends Pe{constructor(t){super(t),this.levels||(this.levels=this.defaultLevels().map(e=>({...e}))),this.numbersSize||(this.numbersSize="small"),this.labelsSize||(this.labelsSize="normal")}fillBands(t){return[]}editableLevels(){return this.levels}anchorSchema(){return{min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}hitTest(t,e,n,r){let i=this.entryLines(n);return i!=null&&i.some(s=>ut(t,e,s.x1,s.y1,s.x2,s.y2)<=r)}handlePoints(t){let e=[];for(let n of this.anchors){let r=t.yOf(n.price,this.paneId);if(r==null)return[];e.push([t.xOf(n.time),r])}return e}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.handlePoints(t);if(e.length===0)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}schema(){return{fields:xe.filter(t=>t.path!=="style.lineColor")}}writeProps(){return{levels:this.levels.map(t=>({...t})),numbersSize:this.numbersSize,labelsSize:this.labelsSize}}readProps(t){if(Array.isArray(t.levels)){let e=t.levels.map(fD).filter(n=>n!=null);e.length&&(this.levels=e)}dg(t.numbersSize)&&(this.numbersSize=t.numbersSize),dg(t.labelsSize)&&(this.labelsSize=t.labelsSize)}},Bg=class extends Pn{constructor(t){super(t),this.showRatios===void 0&&(this.showRatios=!0),this.showPrices===void 0&&(this.showPrices=!0),this.labelSide===void 0&&(this.labelSide="left"),this.background===void 0&&(this.background=!0)}levelPrice(t,e,n){return e+t*(n-e)}levelLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.xOf(e.time),i=t.xOf(n.time),s=this.style.extendLeft?0:Math.min(r,i),a=this.style.extendRight?t.width:Math.max(r,i),o=[];for(let l of this.levels){if(!l.enabled)continue;let c=this.levelPrice(l.ratio,e.price,n.price),u=t.yOf(c,this.paneId);u!=null&&o.push({ratio:l.ratio,color:l.color,label:l.label,price:c,x1:s,x2:a,y:u})}return o}entryLines(t){let e=this.levelLines(t);if(!e)return null;let n=this.labelSide==="right";return e.map(r=>({color:r.color,label:r.label,x1:r.x1,y1:r.y,x2:r.x2,y2:r.y,numberText:this.levelText(r.ratio,r.price),numberX:n?r.x2-4:r.x1+4,numberY:r.y-7,numberAlign:n?"right":"left",labelX:(r.x1+r.x2)/2,labelY:r.y-7}))}levelText(t,e){let n=e.toFixed(2);return this.showRatios&&this.showPrices?`${t} (${n})`:this.showRatios?String(t):this.showPrices?n:""}fillBands(t){if(!this.background)return[];let e=this.levelLines(t)?.sort((r,i)=>r.ratio-i.ratio);if(!e)return[];let n=[];for(let r=1;r<e.length;r+=1){let i=e[r-1],s=e[r];n.push({color:s.color,x:i.x1,y:Math.min(i.y,s.y),w:i.x2-i.x1,h:Math.abs(s.y-i.y)})}return n}priceRange(){let t=this.anchors[0],e=this.anchors[1];if(!t||!e)return null;let n=this.levels.filter(r=>r.enabled).map(r=>this.levelPrice(r.ratio,t.price,e.price));return n.length===0?null:{min:Math.min(...n),max:Math.max(...n)}}schema(){return{fields:[...super.schema().fields,{path:"style.extendLeft",label:v("drawing.field.extendLeft","Extend left"),kind:"boolean",group:"line"},{path:"style.extendRight",label:v("drawing.field.extendRight","Extend right"),kind:"boolean",group:"line"}]}}writeProps(){return{...super.writeProps(),showRatios:this.showRatios,showPrices:this.showPrices,labelSide:this.labelSide,background:this.background}}readProps(t){super.readProps(t),typeof t.showRatios=="boolean"&&(this.showRatios=t.showRatios),typeof t.showPrices=="boolean"&&(this.showPrices=t.showPrices),(t.labelSide==="left"||t.labelSide==="right")&&(this.labelSide=t.labelSide),typeof t.background=="boolean"&&(this.background=t.background)}},Ui=hr,si=Wt,ai=ji,Bo="#4caf50",zs=dt,dr=pr,oi="#9c27b0",Lo="#e91e63",Vo="#26a69a",vh="#ab47bc",Vg="#ef5350",$o="#ffb74d",wh="#38c0fd",$g="#b2b5be",$s=[wh,dr,zs,Bo,ai,si,Lo,oi,Ui,Vo,vh,Vg];function zg(t){return $s[(t%$s.length+$s.length)%$s.length]}var mD=[[0,Ui],[.125,si],[.236,si],[.25,si],[.382,ai],[.5,Bo],[.618,zs],[.75,dr],[.786,dr],[1,Ui],[.705,$o],[.886,oi],[1.272,dr],[1.382,ai],[1.414,Vo],[1.618,si],[2,Ui],[2.272,vh],[2.382,ai],[2.414,Lo],[2.618,ai],[3,Ui],[3.272,Vg],[3.618,oi],[4.236,Bo],[4.618,Lo],[-.27,wh],[-.272,wh],[-.62,dr],[-.618,dr],[-1,Vo],[-1.5,vh],[-2,oi],[-2.5,Lo],[6.854,zs],[11.09,dr]];function yD(t,e=0){return mD.find(([n])=>n===t)?.[1]??zg(e)}function Jt(t){return t.map((e,n)=>{let r=typeof e=="number"?{ratio:e}:e;return{ratio:r.ratio,color:r.color??yD(r.ratio,n),enabled:r.enabled!==!1,...r.label?{label:r.label}:{}}})}function gD(t,e=t){return Array.from({length:t},(n,r)=>({ratio:r+1,color:zg(r),enabled:r<e,label:String(r+1)}))}var fg=[0,.236,.382,.5,.618,.705,.786,.886,1,1.272,1.414,1.618,2,2.272,2.414,2.618,3,3.272,3.618,4.236,4.618,-.272,-.618,-1],_D=[0,.236,.382,.5,.62,.705,.79,.886,1,1.272,1.414,1.618,2,2.618,3,3.618,4.236,4.618,-.27,-.62,-1,-1.5,-2,-2.5];function Fo(t,e,n={}){return Jt(t.map(r=>({ratio:r,enabled:e.includes(r),color:n[String(r)]})))}var bD=[{key:"classic",label:v("drawing.fibPreset.classic","Classic"),reverse:!1,levels:Fo(fg,[0,.236,.382,.5,.618,.786,1])},{key:"extension",label:v("drawing.fibPreset.extension","Extension"),reverse:!0,levels:Fo(fg,[0,1,1.272,1.414,1.618,2,2.618,3.618,4.236])},{key:"ote",label:v("drawing.fibPreset.ote","OTE"),reverse:!1,levels:Fo(_D,[0,.5,.62,.705,.79,1,-.27,-.62],{"0.62":$o,"0.79":$o})}];var xD=bD[0].levels,vD=class extends Bg{constructor(t){super(t),this.type="fibretracement",this.reverse===void 0&&(this.reverse=!1)}defaultLevels(){return xD}levelPrice(t,e,n){return this.reverse?e+t*(n-e):n+t*(e-n)}writeProps(){return{...super.writeProps(),reverse:this.reverse}}readProps(t){super.readProps(t),this.reverse=typeof t.reverse=="boolean"?t.reverse:!0}},wD=Fo([0,.236,.382,.5,.618,.786,1,1.272,1.414,1.618,2,2.272,2.414,2.618,3,3.272,3.618,4.236,4.618],[0,.382,.618,1,1.272,1.618,2.618],{"2.618":oi}),SD=class extends Bg{constructor(){super(...arguments),this.type="fibextension"}defaultLevels(){return wD}},ED=Jt([0,.382,.5,.618,1,1.618,{ratio:2.618,color:oi}]),kD=class extends Pn{constructor(){super(...arguments),this.type="fibextensiontrend"}anchorSchema(){return{min:3,max:3,slots:[{role:"a",free:"both"},{role:"b",free:"both"},{role:"c",free:"both"}]}}defaultLevels(){return ED}entryLines(t){let e=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!e||!n||!r)return null;let i=n.price-e.price,s=[t.xOf(e.time),t.xOf(n.time),t.xOf(r.time)],a=Math.min(...s),o=Math.max(...s),l=[];for(let c of this.levels){if(!c.enabled)continue;let u=r.price+c.ratio*i,h=t.yOf(u,this.paneId);h!=null&&l.push({color:c.color,label:c.label,x1:a,y1:h,x2:o,y2:h,numberText:`${c.ratio} (${u.toFixed(2)})`,numberX:a+4,numberY:h-7,numberAlign:"left",labelX:(a+o)/2,labelY:h-7})}return l}priceRange(){let t=this.anchors[0],e=this.anchors[1],n=this.anchors[2];if(!t||!e||!n)return null;let r=e.price-t.price,i=this.levels.filter(s=>s.enabled).map(s=>n.price+s.ratio*r);return i.push(t.price,e.price,n.price),{min:Math.min(...i),max:Math.max(...i)}}},AD=Jt([.236,.382,.5,.618,.786,1]),TD=class extends Pn{constructor(){super(...arguments),this.type="fibfan"}defaultLevels(){return AD}fanLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.xOf(e.time),i=t.yOf(e.price,this.paneId);if(i==null)return null;let s=t.xOf(n.time),a=n.price-e.price,o=[];for(let l of this.levels){if(!l.enabled)continue;let c=t.yOf(e.price+l.ratio*a,this.paneId);if(c==null)continue;let[u,h,p,d]=wt(r,i,s,c,"right",t.width,t.height);o.push({ratio:l.ratio,color:l.color,label:l.label,x1:u,y1:h,x2:p,y2:d,labelX:s+5,labelY:c})}return o}entryLines(t){let e=this.fanLines(t);return e?e.map(n=>({color:n.color,label:n.label,x1:n.x1,y1:n.y1,x2:n.x2,y2:n.y2,numberText:String(n.ratio),numberX:n.labelX,numberY:n.labelY,numberAlign:"left",labelX:n.labelX,labelY:n.labelY+13})):null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}},ND=[0,1,2,3,5,8,13,21,34].map(t=>({ratio:t,color:U,enabled:!0})),CD=class extends Pn{constructor(){super(...arguments),this.type="fibtimezones"}defaultLevels(){return ND}zoneLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=n.time-e.time;if(Math.abs(r)<1e-9)return null;let i=[];for(let s of this.levels)s.enabled&&i.push({n:s.ratio,color:s.color,label:s.label,x:t.xOf(e.time+s.ratio*r)});return i}entryLines(t){let e=this.zoneLines(t);if(!e)return null;let n=t.height;return e.map(r=>({color:r.color,label:r.label,x1:r.x,y1:0,x2:r.x,y2:n,numberText:String(r.n),numberX:r.x,numberY:9,numberAlign:"center",labelX:r.x,labelY:24}))}priceRange(){return null}timeExtent(){return null}},ID=Jt([0,.236,.382,.5,.618,.786,1,1.618,2.618]),MD=class extends Pn{constructor(){super(...arguments),this.type="fibchannel"}defaultLevels(){return ID}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"both"}]}}entryLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time),o=0,l=0,c=this.anchors[2];if(c){let h=t.yOf(c.price,this.paneId);if(h==null)return null;o=t.xOf(c.time)-s,l=h-r}let u=[];for(let h of this.levels){if(!h.enabled)continue;let p=h.ratio*o,d=h.ratio*l,f=a+p,m=i+d;u.push({color:h.color,label:h.label,x1:s+p,y1:r+d,x2:f,y2:m,numberText:String(h.ratio),numberX:f+5,numberY:m,numberAlign:"left",labelX:f+5,labelY:m+13})}return u}priceRange(){let t=this.anchors[0],e=this.anchors[1],n=this.anchors[2];if(!t||!e)return null;let r=n?n.price-t.price:0,i=1/0,s=-1/0;for(let a of this.levels)if(a.enabled)for(let o of[t.price,e.price]){let l=o+a.ratio*r;l<i&&(i=l),l>s&&(s=l)}return i<=s?{min:i,max:s}:null}},PD=Jt([0,.236,.382,.5,.618,.786,1]),DD=class extends Pn{constructor(){super(...arguments),this.type="fibspeedfan"}defaultLevels(){return PD}entryLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),o=t.xOf(n.time)-s,l=i-r,c=o>=0?"right":"left",u=t.width,h=t.height,p=[];for(let d of this.levels){if(!d.enabled)continue;let f=s+o,m=r+l*d.ratio,y=wt(s,r,f,m,c,u,h);if(p.push({color:d.color,label:d.label,x1:y[0],y1:y[1],x2:y[2],y2:y[3],numberText:String(d.ratio),numberX:c==="right"?f+5:f-5,numberY:m,numberAlign:c==="right"?"left":"right",labelX:f,labelY:m}),d.ratio===1)continue;let g=s+o*d.ratio,w=r+l,k=wt(s,r,g,w,c,u,h);p.push({color:d.color,label:d.label,x1:k[0],y1:k[1],x2:k[2],y2:k[3],numberText:String(d.ratio),numberX:g,numberY:w+(l>=0?12:-12),numberAlign:"center",labelX:g,labelY:w+12})}return p}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}},OD=Jt([0,.382,{ratio:.5,enabled:!1},.618,1,1.382,1.618,2,2.382,2.618,3]),RD=class extends Pn{constructor(){super(...arguments),this.type="trendfibtime"}defaultLevels(){return OD}anchorSchema(){return{min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"p3",free:"both"}]}}entryLines(t){let e=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!e||!n||!r)return null;let i=n.time-e.time;if(Math.abs(i)<1e-9)return null;let s=t.height,a=[];for(let o of this.levels){if(!o.enabled)continue;let l=t.xOf(r.time+o.ratio*i);a.push({color:o.color,label:o.label,x1:l,y1:0,x2:l,y2:s,numberText:String(o.ratio),numberX:l,numberY:9,numberAlign:"center",labelX:l,labelY:24})}return a}priceRange(){return null}timeExtent(){return null}};function LD(t,e,n){if(n-e>=Math.PI*2-.001)return!0;let r=t-e,i=Math.PI*2;for(;r<0;)r+=i;for(;r>=i;)r-=i;return r<=n-e+1e-6}var Nh=class extends Pn{boundingLines(t){return[]}entryLines(t){return[]}hitTest(t,e,n,r){let i=this.radial(n);if(i){let s=Math.hypot(t-i.cx,e-i.cy),a=Math.atan2(e-i.cy,t-i.cx);if(LD(a,i.a0,i.a1)){for(let o of this.levels)if(o.enabled&&Math.abs(s-i.R0*o.ratio)<=r)return!0}}return this.boundingLines(n).some(s=>ut(t,e,s[0],s[1],s[2],s[3])<=r)}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}},FD=Jt([.236,.382,.5,.618,.786,1,1.618,2.618]),BD=class extends Nh{constructor(){super(...arguments),this.type="fibcircles"}defaultLevels(){return FD}radial(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time);return{cx:s,cy:r,R0:Math.hypot(a-s,i-r),a0:0,a1:Math.PI*2}}},VD=Jt([.236,.382,.5,.618,.786,1,1.618,2.618]),$D=class extends Nh{constructor(){super(...arguments),this.type="fibarcs"}defaultLevels(){return VD}pts(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:{cx:t.xOf(e.time),cy:r,ex:t.xOf(n.time),ey:i}}radial(t){let e=this.pts(t);if(!e)return null;let n=Math.hypot(e.ex-e.cx,e.ey-e.cy),r=Math.atan2(e.ey-e.cy,e.ex-e.cx);return{cx:e.cx,cy:e.cy,R0:n,a0:r-Math.PI/2,a1:r+Math.PI/2}}boundingLines(t){let e=this.pts(t);return e?[[e.cx,e.cy,e.ex,e.ey]]:[]}},zD=Jt([.236,.382,.5,.618,.786,1]),jD=class extends Nh{constructor(){super(...arguments),this.type="fibwedge"}defaultLevels(){return zD}anchorSchema(){return{min:3,max:3,slots:[{role:"apex",free:"both"},{role:"radius",free:"both"},{role:"angle",free:"both"}]}}px(t,e){let n=this.anchors[e];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}radial(t){let e=this.px(t,0),n=this.px(t,1),r=this.px(t,2);if(!e||!n||!r)return null;let i=Math.hypot(n[0]-e[0],n[1]-e[1]);if(i<1)return null;let s=Math.atan2(n[1]-e[1],n[0]-e[0]),a=Math.atan2(r[1]-e[1],r[0]-e[0]),o=Math.min(s,a),l=Math.max(s,a);return l-o>Math.PI&&([o,l]=[l,o+Math.PI*2]),{cx:e[0],cy:e[1],R0:i,a0:o,a1:l}}boundingLines(t){let e=this.px(t,0),n=this.px(t,1);if(!e||!n)return[];let r=[[e[0],e[1],n[0],n[1]]],i=this.px(t,2);if(i){let s=Math.hypot(n[0]-e[0],n[1]-e[1]),a=Math.hypot(i[0]-e[0],i[1]-e[1]);a>1e-6&&r.push([e[0],e[1],e[0]+(i[0]-e[0])/a*s,e[1]+(i[1]-e[1])/a*s])}return r}},qD=1.6180339887,mg=Math.log(qD)/(Math.PI/2),UD=Math.PI/64,WD=Math.PI,HD=.5,GD=class extends Pe{constructor(){super(...arguments),this.type="fibspiral"}anchorSchema(){return{min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}spiralPoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time),o=Math.hypot(a-s,i-r);if(o<1)return null;let l=Math.atan2(i-r,a-s),c=Math.max(Math.log(HD/o)/mg,-8*Math.PI*2),u=[];for(let h=c;h<=WD;h+=UD){let p=o*Math.exp(mg*h),d=l+h;u.push([s+p*Math.cos(d),r+p*Math.sin(d)])}return u}hitTest(t,e,n,r){let i=this.spiralPoints(n);return i!=null&&i.length>=2&&Eh(t,e,i)<=r}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?[]:[[t.xOf(e.time),r],[t.xOf(n.time),i]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.handlePoints(t);if(e.length<2)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,..._e]}}},KD=Jt([{ratio:.125,color:si,label:"1/8"},{ratio:.25,color:ai,label:"1/4"},{ratio:.333,color:$o,label:"1/3"},{ratio:.5,color:Bo,label:"1/2"},{ratio:1,color:$g,label:"1/1"},{ratio:2,color:zs,label:"2/1"},{ratio:3,color:dr,label:"3/1"},{ratio:4,color:Vo,label:"4/1"},{ratio:8,color:oi,label:"8/1"}]),YD=class extends Pn{constructor(){super(...arguments),this.type="gannfan"}defaultLevels(){return KD}entryLines(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.xOf(e.time),i=t.yOf(e.price,this.paneId);if(i==null)return null;let s=t.xOf(n.time),a=n.price-e.price,o=[];for(let l of this.levels){if(!l.enabled)continue;let c=t.yOf(e.price+a*l.ratio,this.paneId);if(c==null)continue;let[u,h,p,d]=wt(r,i,s,c,"right",t.width,t.height);o.push({color:l.color,x1:u,y1:h,x2:p,y2:d,numberText:l.label??String(l.ratio),numberX:s+5,numberY:c,numberAlign:"left",labelX:s+5,labelY:c})}return o}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}},XD=Jt([0,.25,.382,.5,.618,.75,1].map(t=>({ratio:t,label:String(t)}))),ZD=class extends Pn{constructor(){super(...arguments),this.type="gannbox"}defaultLevels(){return XD}corners(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.xOf(e.time),i=t.xOf(n.time),s=t.yOf(e.price,this.paneId),a=t.yOf(n.price,this.paneId);return s==null||a==null?null:{c1:e,c2:n,left:Math.min(r,i),right:Math.max(r,i),top:Math.min(s,a),bot:Math.max(s,a)}}entryLines(t){let e=this.corners(t);if(!e)return null;let{c1:n,c2:r,left:i,right:s,top:a,bot:o}=e,l=[];for(let u of this.levels){if(!u.enabled)continue;let h=t.yOf(n.price+u.ratio*(r.price-n.price),this.paneId);h!=null&&l.push({color:u.color,x1:i,y1:h,x2:s,y2:h,numberText:u.label??String(u.ratio),numberX:i-5,numberY:h,numberAlign:"right",labelX:i,labelY:h});let p=t.xOf(n.time+u.ratio*(r.time-n.time));l.push({color:u.color,x1:p,y1:a,x2:p,y2:o,numberText:"",numberX:p,numberY:a,numberAlign:"center",labelX:p,labelY:a})}let c=this.levels.find(u=>u.ratio===1)?.color??Ui;return l.push({color:c,x1:i,y1:a,x2:s,y2:o,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),l.push({color:c,x1:i,y1:o,x2:s,y2:a,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),l}hitTest(t,e,n,r){let i=this.corners(n);return i!=null&&fr(t,e,i.left,i.top,i.right,i.bot,r)}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}},JD=Jt([0,.25,.382,.5,.618,.75,1].map(t=>({ratio:t,label:String(t)}))),QD=[{label:"3x1",x:3,y:1,color:si},{label:"2x1",x:2,y:1,color:ai},{label:"1x1",x:1,y:1,color:$g},{label:"1x2",x:1,y:2,color:zs},{label:"1x3",x:1,y:3,color:dr}];var eO=class extends Pn{constructor(){super(...arguments),this.type="gannsquare"}defaultLevels(){return JD}box(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time);return{ox:s,oy:r,bx:a-s,py:i-r,left:Math.min(s,a),top:Math.min(r,i),right:Math.max(s,a),bot:Math.max(r,i)}}arcGeom(t){let e=this.box(t);return e?{ox:e.ox,oy:e.oy,bx:e.bx,py:e.py}:null}entryLines(t){let e=this.box(t);if(!e)return null;let n=this.anchors[0],r=this.anchors[1],i=[];for(let s of this.levels){if(!s.enabled)continue;let a=t.yOf(n.price+s.ratio*(r.price-n.price),this.paneId);a!=null&&i.push({color:s.color,x1:e.left,y1:a,x2:e.right,y2:a,numberText:s.label??String(s.ratio),numberX:e.left-5,numberY:a,numberAlign:"right",labelX:e.left,labelY:a});let o=t.xOf(n.time+s.ratio*(r.time-n.time));i.push({color:s.color,x1:o,y1:e.top,x2:o,y2:e.bot,numberText:"",numberX:o,numberY:e.top,numberAlign:"center",labelX:o,labelY:e.top})}for(let s of QD){let a,o;s.x>s.y?(a=e.ox+e.bx,o=e.oy+s.y/s.x*e.py):(o=e.oy+e.py,a=e.ox+s.x/s.y*e.bx),i.push({color:s.color,x1:e.ox,y1:e.oy,x2:a,y2:o,numberText:s.label,numberX:a+4,numberY:o,numberAlign:"left",labelX:a+4,labelY:o})}return i}hitTest(t,e,n,r){let i=this.box(n);return i!=null&&fr(t,e,i.left,i.top,i.right,i.bot,r)}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}};var tO=24,nO=.75;function rO(t,e){if(!Number.isInteger(t)||!Number.isInteger(e)||e<=0)return!1;let n=t*t-1;return e%2===1?n%e===0:e%8===0?n%e!==0?!1:n/e%2!==0:!1}function iO(t){let e=[];for(let n=0;n<t;n+=1)rO(n,t)&&e.push(n);return e}var sO=class extends Pe{constructor(t){super(t),this.type="dedekind",this.maxCurvature===void 0&&(this.maxCurvature=tO)}anchorSchema(){return{min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}box(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=Math.min(t.xOf(e.time),t.xOf(n.time)),a=Math.max(t.xOf(e.time),t.xOf(n.time)),o=Math.min(r,i),l=Math.max(r,i),c=a-s,u=l-o;if(c<1||u<1)return null;let h=u,p=c/h;return{left:s,right:a,top:o,bot:l,unitPx:h,x0:0,realSpan:p}}geodesics(t){let e=this.box(t);if(!e)return null;let{left:n,top:r,bot:i,unitPx:s,x0:a,realSpan:o}=e,l=Math.max(1,Math.min(64,Math.round(this.maxCurvature))),c=a-1/l,u=a+o+1/l,h=n+o*s,p=[],d=Math.floor(c*2),f=Math.ceil(u*2);for(let m=d;m<=f;m+=1){if(m%2===0)continue;let y=n+(m/2-a)*s;y<n-.5||y>h+.5||p.push({kind:"vline",x:y,y0:i,y1:r})}for(let m=1;m<=l;m+=1){let y=1/m,g=y*s;if(g<nO)continue;let w=iO(m);if(w.length===0)continue;let k=Math.floor(c)-1,S=Math.ceil(u)+1;for(let E=k;E<=S;E+=1)for(let T of w){let N=T/m+E;if(N+y<c||N-y>u)continue;let $=n+(N-a)*s;$+g<n-1||$-g>h+1||p.push({kind:"arc",cx:$,cy:i,r:g})}}return p}hitTest(t,e,n,r){let i=this.box(n);return i!=null&&fr(t,e,i.left,i.top,i.right,i.bot,r)}handlePoints(t){let e=this.box(t);return e?[[e.left,e.top],[e.right,e.bot]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.box(t);return e?{x:e.left,y:e.top,w:e.right-e.left,h:e.bot-e.top}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[...xe,{path:"maxCurvature",label:v("drawing.dedekind.maxCurvature","Max curvature"),kind:"number",min:4,max:64,step:4,group:"behavior"},..._e]}}writeProps(){return{maxCurvature:this.maxCurvature}}readProps(t){typeof t.maxCurvature=="number"&&Number.isFinite(t.maxCurvature)&&(this.maxCurvature=Math.max(1,Math.min(64,Math.round(t.maxCurvature))))}};var Uo=6,aO=2;function jg(t=Uo){return[...gD($s.length,t)]}function oO(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==!1,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Wo={path:"showRatios",label:v("drawing.sonic.showRatios","Show ratios"),kind:"boolean",group:"behavior"},Ho=class extends Pe{constructor(t){super(t),this.waveCount===void 0&&(this.waveCount=Uo),this.showRatios===void 0&&(this.showRatios=!0);let e=Array.isArray(t.props?.levels);this.levels||(this.levels=this.defaultLevels().map(n=>({...n}))),!e&&this.shouldSyncWaveCount()&&this.syncLevelsToWaveCount()}shouldSyncWaveCount(){return!0}syncLevelsToWaveCount(){let t=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=t;for(let e=0;e<this.levels.length;e+=1)this.levels[e].enabled=e<t}editableLevels(){return this.levels}anchorSchema(){return{min:2,max:2,slots:[{role:"d1",free:"both"},{role:"d2",free:"both"}]}}geom(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);if(r==null||i==null)return null;let s=t.xOf(e.time),a=t.xOf(n.time),o=(s+a)/2,l=(r+i)/2,c=Math.hypot(a-s,i-r)/2;if(c<1)return null;let u=a-s,h=i-r,p=Math.hypot(u,h);p<1e-9?(u=1,h=0):(u/=p,h/=p);let d=this.levels.filter(E=>E.enabled&&E.ratio>0).slice().sort((E,T)=>E.ratio-T.ratio);if(d.length===0)return null;let f=Math.max(1,this.machNumber()),m=[];for(let E of d){let T=E.ratio*c;m.push({cx:o+f*(T-c)*u,cy:l+f*(T-c)*h,r:T,color:E.color,ratio:E.ratio})}let y=o-f*c*u,g=l-f*c*h,w=m[m.length-1].r,k=f*w+2*c,S=[];if(f<=1+1e-9){let E=-h,T=u;S.push([y-E*k,g-T*k,y+E*k,g+T*k])}else{let E=Math.asin(1/f),T=Math.cos(E),N=Math.sin(E),$=(te,I,V)=>[te*T-I*V*N,te*V*N+I*T],[z,H]=$(u,h,1),[C,ae]=$(u,h,-1);S.push([y,g,y+z*k,g+H*k]),S.push([y,g,y+C*k,g+ae*k])}return{c0x:o,c0y:l,R:c,fx:u,fy:h,noseX:y,noseY:g,circles:m,rays:S}}hitTest(t,e,n,r){let i=this.geom(n);if(!i)return!1;for(let s of i.circles)if(Math.abs(Math.hypot(t-s.cx,e-s.cy)-s.r)<=r)return!0;return i.rays.some(s=>ut(t,e,s[0],s[1],s[2],s[3])<=r)}handlePoints(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return[];let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?[]:[[t.xOf(e.time),r],[t.xOf(n.time),i]]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.geom(t);if(!e)return null;let n=e.noseX,r=e.noseX,i=e.noseY,s=e.noseY;for(let a of e.circles)n=Math.min(n,a.cx-a.r),r=Math.max(r,a.cx+a.r),i=Math.min(i,a.cy-a.r),s=Math.max(s,a.cy+a.r);for(let a of e.rays)n=Math.min(n,a[0],a[2]),r=Math.max(r,a[0],a[2]),i=Math.min(i,a[1],a[3]),s=Math.max(s,a[1],a[3]);return{x:n,y:i,w:r-n,h:s-i}}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}applySettings(t){if(super.applySettings(t),Object.prototype.hasOwnProperty.call(t,"waveCount")&&typeof this.waveCount=="number"){let e=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=e;for(let n=0;n<this.levels.length;n+=1)this.levels[n].enabled=n<e}}schema(){return{fields:[...xe,{path:"waveCount",label:v("drawing.sonic.waveCount","Waves"),kind:"number",min:3,max:12,step:1,group:"behavior"},Wo,..._e]}}writeProps(){return{waveCount:this.waveCount,showRatios:this.showRatios,levels:this.levels.map(t=>({...t}))}}readProps(t){if(typeof t.waveCount=="number"&&Number.isFinite(t.waveCount)&&(this.waveCount=Math.max(2,Math.min(12,Math.round(t.waveCount)))),typeof t.showRatios=="boolean"&&(this.showRatios=t.showRatios),Array.isArray(t.levels)){let e=t.levels.map(oO).filter(n=>n!=null);e.length&&(this.levels=e)}}},lO=class extends Ho{constructor(){super(...arguments),this.type="sonic"}defaultLevels(){return jg(Uo)}machNumber(){return 1}},cO=class extends Ho{constructor(t){super(t),this.type="supersonic",this.mach===void 0&&(this.mach=aO)}defaultLevels(){return jg(Uo)}machNumber(){return Math.max(1.01,this.mach)}schema(){return{fields:[...xe,{path:"mach",label:v("drawing.supersonic.mach","Mach number"),kind:"number",min:1.5,max:5,step:.5,group:"behavior"},{path:"waveCount",label:v("drawing.supersonic.waveCount","Waves"),kind:"number",min:3,max:12,step:1,group:"behavior"},Wo,..._e]}}writeProps(){return{...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)))}},qg=Jt([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),uO=2,hO=class extends Ho{constructor(){super(...arguments),this.type="goldensonic"}shouldSyncWaveCount(){return!1}defaultLevels(){return qg}machNumber(){return 1}schema(){return{fields:[...xe,Wo,..._e]}}},pO=class extends Ho{constructor(t){super(t),this.type="goldensupersonic",this.mach===void 0&&(this.mach=uO)}shouldSyncWaveCount(){return!1}defaultLevels(){return qg}machNumber(){return Math.max(1.01,this.mach)}schema(){return{fields:[...xe,{path:"mach",label:v("drawing.goldensupersonic.mach","Mach number"),kind:"number",min:1.5,max:5,step:.5,group:"behavior"},Wo,..._e]}}writeProps(){return{...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)))}},Wi=class extends Pe{legRatios(){return!1}fillTriangles(){return[]}necklineIndices(){return null}anchorSchema(){let t=this.vertexLabels().length,e=[];for(let n=0;n<t;n+=1)e.push({role:`p${n}`,free:"both"});return{min:t,max:t,slots:e}}handlePoints(t){let e=[];for(let n of this.anchors){let r=t.yOf(n.price,this.paneId);if(r==null)return[];e.push([t.xOf(n.time),r])}return e}hitTest(t,e,n,r){let i=this.handlePoints(n);return i.length>=2&&Eh(t,e,i)<=r}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.handlePoints(t);if(e.length===0)return null;let n=e.map(a=>a[0]),r=e.map(a=>a[1]),i=Math.min(...n),s=Math.min(...r);return{x:i,y:s,w:Math.max(...n)-i,h:Math.max(...r)-s}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(e=>e.price);return{min:Math.min(...t),max:Math.max(...t)}}patternName(){return null}ratioOk(t){return null}valid(){return null}ratioAt(t){let e=this.anchors[t-2],n=this.anchors[t-1],r=this.anchors[t];if(!e||!n||!r)return null;let i=Math.abs(n.price-e.price);return i<1e-9?null:Math.abs(r.price-n.price)/i}schema(){return{fields:[...xe,...this.fillTriangles().length?Ht:[]]}}},dO=class extends Wi{constructor(){super(...arguments),this.type="xabcd"}vertexLabels(){return["X","A","B","C","D"]}legRatios(){return!0}fillTriangles(){return[[0,1,2],[2,3,4]]}},fO=class extends Wi{constructor(){super(...arguments),this.type="abcd"}vertexLabels(){return["A","B","C","D"]}legRatios(){return!0}},mO=class extends Wi{constructor(){super(...arguments),this.type="elliottimpulse"}vertexLabels(){return["1","2","3","4","5"]}},yO=class extends Wi{constructor(){super(...arguments),this.type="elliottcorrection"}vertexLabels(){return["A","B","C"]}},gO=v("drawing.headshoulders.leftShoulder","LS"),_O=v("drawing.headshoulders.head","H"),bO=v("drawing.headshoulders.rightShoulder","RS"),xO=class extends Wi{constructor(){super(...arguments),this.type="headshoulders"}vertexLabels(){return["",gO,"",_O,"",bO,""]}necklineIndices(){return[2,4]}},Hi=class extends Wi{vertexLabels(){return["X","A","B","C","D"]}legRatios(){return!0}fillTriangles(){return[[0,1,2],[2,3,4]]}legValue(t){let[e,n,r,i,s]=this.anchors;if(!e||!n||!r||!i||!s)return null;let a=(u,h)=>Math.abs(h.price-u.price),o=a(e,n),l=a(n,r),c=a(r,i);switch(t){case"ab":return o<1e-9?null:l/o;case"bc":return l<1e-9?null:c/l;case"cd":return c<1e-9?null:a(i,s)/c;default:return o<1e-9?null:a(n,s)/o}}inBand(t,e){return t!=null&&t>=e.min&&t<=e.max}ratioOk(t){let e=this.ranges();return t===2?this.inBand(this.legValue("ab"),e.ab):t===3?this.inBand(this.legValue("bc"),e.bc):t===4?this.inBand(this.legValue("cd"),e.cd):null}valid(){if(this.anchors.length<5)return null;let t=this.ranges();return this.inBand(this.legValue("ab"),t.ab)&&this.inBand(this.legValue("bc"),t.bc)&&this.inBand(this.legValue("cd"),t.cd)&&this.inBand(this.legValue("ad"),t.ad)}},vO=class extends Hi{constructor(){super(...arguments),this.type="gartley"}patternName(){return v("drawing.gartley.patternName","Gartley")}ranges(){return{ab:{min:.55,max:.68},bc:{min:.382,max:.886},cd:{min:1.13,max:1.618},ad:{min:.74,max:.83}}}},wO=class extends Hi{constructor(){super(...arguments),this.type="bat"}patternName(){return v("drawing.bat.patternName","Bat")}ranges(){return{ab:{min:.382,max:.5},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:.84,max:.92}}}},SO=class extends Hi{constructor(){super(...arguments),this.type="butterfly"}patternName(){return v("drawing.butterfly.patternName","Butterfly")}ranges(){return{ab:{min:.74,max:.83},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:1.272,max:1.618}}}},EO=class extends Hi{constructor(){super(...arguments),this.type="crab"}patternName(){return v("drawing.crab.patternName","Crab")}ranges(){return{ab:{min:.382,max:.618},bc:{min:.382,max:.886},cd:{min:2.618,max:3.618},ad:{min:1.55,max:1.69}}}},kO=class extends Hi{constructor(){super(...arguments),this.type="shark"}patternName(){return v("drawing.shark.patternName","Shark")}ranges(){return{ab:{min:.382,max:.618},bc:{min:1.13,max:1.618},cd:{min:1.618,max:2.24},ad:{min:.886,max:1.13}}}},AO={min:1.272,max:1.414},TO={min:.74,max:.83},NO=class extends Hi{constructor(){super(...arguments),this.type="cypher"}patternName(){return v("drawing.cypher.patternName","Cypher")}ranges(){return{ab:{min:.382,max:.618},bc:{min:0,max:1/0},cd:{min:0,max:1/0},ad:{min:0,max:1/0}}}xcOverXa(){let t=this.anchors[0],e=this.anchors[1],n=this.anchors[3];if(!t||!e||!n)return null;let r=Math.abs(e.price-t.price);return r<1e-9?null:Math.abs(n.price-t.price)/r}cdOverXc(){let t=this.anchors[0],e=this.anchors[3],n=this.anchors[4];if(!t||!e||!n)return null;let r=Math.abs(e.price-t.price);return r<1e-9?null:Math.abs(n.price-e.price)/r}ratioOk(t){return t===2?this.inBand(this.legValue("ab"),this.ranges().ab):null}valid(){return this.anchors.length<5?null:this.inBand(this.legValue("ab"),this.ranges().ab)&&this.inBand(this.xcOverXa(),AO)&&this.inBand(this.cdOverXc(),TO)}},yg={priceChange:v("drawing.measure.priceChange","{change} ({percent}%)"),barsAndDuration:v("drawing.measure.barsAndDuration","{count, plural, one {{bars} bar} other {{bars} bars}}, {duration}")};function gg(t){return`${t>=0?"+":""}${t.toFixed(2)}`}var CO=class extends Pe{constructor(t){super(t),this.showPrice===void 0&&(this.showPrice=!0),this.showDate===void 0&&(this.showDate=!0)}anchorSchema(){return{min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}measureLabel(t,e){let n=[];return this.showPrice&&n.push(this.priceLabel(e)),this.showDate&&n.push(this.timeLabel(t,e)),n}isUp(){let t=this.anchors[0],e=this.anchors[1];return t!=null&&e!=null&&e.price>=t.price}priceLabel(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return"";let r=n.price-e.price,i=e.price!==0?r/e.price*100:0;return cr(t,yg.priceChange,{change:In(gg(r),t),percent:In(gg(i),t)})}timeLabel(t,e){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return"";let i=(e??Do()).format.duration(r.time-n.time,{style:"span",surface:"drawing"}),s=t.barsBetween?Math.round(t.barsBetween(n.time,r.time)):null;return s!=null?cr(e,yg.barsAndDuration,{count:s,bars:In(String(s),e),duration:i}):i}rect(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:{x1:t.xOf(e.time),y1:r,x2:t.xOf(n.time),y2:i}}hitTest(t,e,n,r){let i=this.rect(n);return i!=null&&fr(t,e,i.x1,i.y1,i.x2,i.y2,r)}handlePoints(t){let e=this.rect(t);return e?[[e.x1,e.y1],[e.x2,e.y2]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.rect(t);return e?{x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),w:Math.abs(e.x2-e.x1),h:Math.abs(e.y2-e.y1)}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[{path:"showPrice",label:v("drawing.measure.showPrice","Show price"),kind:"boolean",group:"behavior"},{path:"showDate",label:v("drawing.measure.showDate","Show date"),kind:"boolean",group:"behavior"},...xe.filter(t=>t.path!=="style.lineColor"),{path:"text.color",label:v("drawing.field.textColor","Text color"),kind:"color",group:"text"},{path:"text.size",label:v("drawing.field.textSize","Text size"),kind:"select",options:Sh,group:"text"}]}}writeProps(){return{showPrice:this.showPrice,showDate:this.showDate}}readProps(t){typeof t.showPrice=="boolean"&&(this.showPrice=t.showPrice),typeof t.showDate=="boolean"&&(this.showDate=t.showDate)}},IO=class extends CO{constructor(){super(...arguments),this.type="datepricerange"}},qi={header:v("drawing.position.header","{direction, select, long {LONG} other {SHORT}} \\xB7 R:R {ratio}"),lossSize:v("drawing.position.lossSize","Loss {loss} \\xB7 Size {size}"),target:v("drawing.position.targetLabel","Target +{percent}%"),targetAt:v("drawing.position.targetLabelAt","Target +{percent}% @ {price}"),stop:v("drawing.position.stopLabel","Stop \\u2212{percent}%"),stopAt:v("drawing.position.stopLabelAt","Stop \\u2212{percent}% @ {price}")},MO=[{value:"long",label:v("drawing.position.option.long","Long")},{value:"short",label:v("drawing.position.option.short","Short")}],Kn=class mn extends Pe{constructor(e){super(e),this.type="position",this.riskPercent===void 0&&(this.riskPercent=mn.DEFAULT_RISK_PERCENT),this.accountBalance===void 0&&(this.accountBalance=mn.DEFAULT_ACCOUNT_BALANCE),this.showText===void 0&&(this.showText=!0),this.showHeader===void 0&&(this.showHeader=!0),this.showPrices===void 0&&(this.showPrices=!1),this.showLossSize===void 0&&(this.showLossSize=!0),this.showTargetLabel===void 0&&(this.showTargetLabel=!0),this.showStopLabel===void 0&&(this.showStopLabel=!0),this.profitColor===void 0&&(this.profitColor=mn.DEFAULT_PROFIT_COLOR),this.lossColor===void 0&&(this.lossColor=mn.DEFAULT_LOSS_COLOR)}directionLabel(){let e=this.prices();return e&&e.target>=e.entry?"LONG":"SHORT"}get direction(){return this.directionLabel()==="LONG"?"long":"short"}set direction(e){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];!n||!r||!i||(e==="long"||e==="short")&&e!==this.direction&&(r.price=2*n.price-r.price,i.price=2*n.price-i.price)}get quantity(){return this.positionSize()}set quantity(e){let n=this.prices();if(!n||!Number.isFinite(e)||e<0)return;let r=Math.abs(n.entry-n.stop);r<1e-9||this.accountBalance<=0||(this.riskPercent=e*r/this.accountBalance*100)}get entryPrice(){return this.anchors[0]?.price??0}set entryPrice(e){let n=this.anchors[0];n&&Number.isFinite(e)&&(n.price=e,this.constrainHandleDrag(0))}get stopPrice(){return this.anchors[1]?.price??0}set stopPrice(e){let n=this.anchors[1];n&&Number.isFinite(e)&&(n.price=e,this.constrainHandleDrag(1))}get targetPrice(){return this.anchors[2]?.price??0}set targetPrice(e){let n=this.anchors[2];n&&Number.isFinite(e)&&(n.price=e,this.constrainHandleDrag(2))}anchorSchema(){return{min:2,max:2,slots:[{role:"entry",free:"both"},{role:"stop",free:"both"},{role:"target",free:"both"}]}}onPlaced(e){let n=this.anchors[0];if(!n)return;let r=e.xOf(n.time),i=e.yOf(n.price,this.paneId);if(i==null)return;let s=this.anchors[1],a=s?e.yOf(s.price,this.paneId):null,o,l;s&&a!=null&&Math.abs(a-i)>=mn.MIN_DRAG_PX?(o=a,l=r+Math.max(Math.abs(e.xOf(s.time)-r),mn.MIN_WIDTH_PX)):(o=i-mn.DEFAULT_RISK_PX*mn.DEFAULT_RR,l=r+mn.DEFAULT_WIDTH_PX);let c=i-(o-i)/mn.DEFAULT_RR,u=e.pxToPoint(l,i,this.paneId).time;this.anchors=[{time:n.time,price:n.price},{time:u,price:e.pxToPoint(r,c,this.paneId).price},{time:u,price:e.pxToPoint(r,o,this.paneId).price}]}constrainHandleDrag(e){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return;let s=Math.sign(r.price-n.price),a=Math.sign(i.price-n.price);s===0||a===0||s!==a||(e===2?r.price=2*n.price-r.price:i.price=2*n.price-i.price)}resolved(){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;if(this.anchors[2])return[e,n,this.anchors[2]];let r={time:n.time,price:e.price-(n.price-e.price)/mn.DEFAULT_RR};return[e,r,n]}prices(){let e=this.resolved();return e?{entry:e[0].price,stop:e[1].price,target:e[2].price}:null}rr(){let e=this.prices();if(!e)return 0;let n=Math.abs(e.entry-e.stop);return n<1e-9?0:Math.abs(e.target-e.entry)/n}rewardPct(){let e=this.prices();return e&&e.entry!==0?Math.abs(e.target-e.entry)/e.entry*100:0}riskPct(){let e=this.prices();return e&&e.entry!==0?Math.abs(e.entry-e.stop)/e.entry*100:0}dollarLoss(){return Math.max(0,this.accountBalance)*(Math.max(0,this.riskPercent)/100)}positionSize(){let e=this.prices();if(!e)return 0;let n=Math.abs(e.entry-e.stop);return n<1e-9?0:this.dollarLoss()/n}headerLabel(e){return cr(e,qi.header,{direction:this.directionLabel()==="LONG"?"long":"short",ratio:In(this.rr().toFixed(2),e)})}lossSizeLabel(e){return cr(e,qi.lossSize,{loss:In(DO(this.dollarLoss()),e),size:In(OO(this.positionSize()),e)})}targetLabel(e){let n=this.prices(),r=In(this.rewardPct().toFixed(2),e);return this.showPrices&&n?cr(e,qi.targetAt,{percent:r,price:In(_g(n.target),e)}):cr(e,qi.target,{percent:r})}stopLabel(e){let n=this.prices(),r=In(this.riskPct().toFixed(2),e);return this.showPrices&&n?cr(e,qi.stopAt,{percent:r,price:In(_g(n.stop),e)}):cr(e,qi.stop,{percent:r})}levelDisplayValue(e,n){let r=this.prices();if(!r)return 0;let i=e==="stop"?r.stop:r.target;return bg(n==="price"?i:Math.abs(i-r.entry))}levelPriceFromDisplay(e,n,r){let i=this.prices();if(!i||n==="price")return r;let s=e==="stop"?i.stop:i.target,a=Math.sign(s-i.entry);return a===0&&(a=(e==="target"?1:-1)*(this.direction==="long"?1:-1)),i.entry+a*Math.abs(r)}box(e){let n=this.handlePoints(e);if(n.length<3)return null;let r=n.map(i=>i[0]);return{x1:Math.min(...r),x2:Math.max(...r),ey:n[0][1],sy:n[1][1],ty:n[2][1]}}layout(e){return this.box(e)}hitTest(e,n,r,i){let s=this.box(r);if(!s)return!1;let a=Math.min(s.ey,s.sy,s.ty),o=Math.max(s.ey,s.sy,s.ty);return fr(e,n,s.x1,a,s.x2,o,i)}handlePoints(e){let n=this.resolved();if(!n)return[];let r=[];for(let i of n){let s=e.yOf(i.price,this.paneId);if(s==null)return[];r.push([e.xOf(i.time),s])}return r}hitHandle(e,n,r,i){return De(e,n,this.handlePoints(r),i+3)}bounds(e){let n=this.box(e);if(!n)return null;let r=Math.min(n.ey,n.sy,n.ty);return{x:n.x1,y:r,w:n.x2-n.x1,h:Math.max(n.ey,n.sy,n.ty)-r}}priceRange(){let e=this.resolved();if(!e)return null;let n=e.map(r=>r.price);return{min:Math.min(...n),max:Math.max(...n)}}schema(){return{fields:[{path:"riskPercent",label:v("drawing.position.riskPercent","Risk %"),kind:"number",min:0,max:100,step:.1,group:"behavior"},{path:"accountBalance",label:v("drawing.position.accountBalance","Account balance"),kind:"number",min:0,max:1e12,step:1,group:"behavior"},{path:"quantity",label:v("drawing.position.quantity","Position size"),kind:"number",group:"behavior"},{path:"direction",label:v("drawing.position.direction","Direction"),kind:"select",options:MO,group:"behavior"},{path:"entryPrice",label:v("drawing.position.entryPrice","Entry price"),kind:"number",group:"behavior"},{path:"stopPrice",label:v("drawing.position.stopPrice","Stop price"),kind:"number",group:"behavior"},{path:"targetPrice",label:v("drawing.position.targetPrice","Target price"),kind:"number",group:"behavior"},{path:"showText",label:v("drawing.position.showText","Show text"),kind:"boolean",group:"behavior"},{path:"showHeader",label:v("drawing.position.showHeader","Show direction & ratio"),kind:"boolean",group:"behavior"},{path:"showLossSize",label:v("drawing.position.showLossSize","Show loss & size"),kind:"boolean",group:"behavior"},{path:"showTargetLabel",label:v("drawing.position.showTargetLabel","Show target label"),kind:"boolean",group:"behavior"},{path:"showStopLabel",label:v("drawing.position.showStopLabel","Show stop label"),kind:"boolean",group:"behavior"},{path:"showPrices",label:v("drawing.position.showPrices","Show level prices"),kind:"boolean",group:"behavior"},{path:"profitColor",label:v("drawing.position.profitColor","Profit zone"),kind:"color",group:"fill"},{path:"lossColor",label:v("drawing.position.lossColor","Loss zone"),kind:"color",group:"fill"},...xe.filter(e=>e.path!=="style.lineColor"),{path:"text.color",label:v("drawing.position.textColor","Text color"),kind:"color",group:"text"},{path:"text.size",label:v("drawing.position.textSize","Text size"),kind:"select",options:Sh,group:"text"}]}}writeProps(){return{riskPercent:this.riskPercent,accountBalance:this.accountBalance,showText:this.showText,showHeader:this.showHeader,showPrices:this.showPrices,showLossSize:this.showLossSize,showTargetLabel:this.showTargetLabel,showStopLabel:this.showStopLabel,profitColor:this.profitColor,lossColor:this.lossColor}}readProps(e){typeof e.riskPercent=="number"&&Number.isFinite(e.riskPercent)&&(this.riskPercent=e.riskPercent),typeof e.accountBalance=="number"&&Number.isFinite(e.accountBalance)&&(this.accountBalance=e.accountBalance),typeof e.showText=="boolean"&&(this.showText=e.showText),typeof e.showHeader=="boolean"&&(this.showHeader=e.showHeader),typeof e.showPrices=="boolean"&&(this.showPrices=e.showPrices),typeof e.showLossSize=="boolean"&&(this.showLossSize=e.showLossSize),typeof e.showTargetLabel=="boolean"&&(this.showTargetLabel=e.showTargetLabel),typeof e.showStopLabel=="boolean"&&(this.showStopLabel=e.showStopLabel),typeof e.profitColor=="string"&&(this.profitColor=e.profitColor),typeof e.lossColor=="string"&&(this.lossColor=e.lossColor)}};Kn.DEFAULT_RR=2;Kn.MIN_DRAG_PX=6;Kn.DEFAULT_RISK_PX=64;Kn.DEFAULT_WIDTH_PX=150;Kn.MIN_WIDTH_PX=48;Kn.DEFAULT_RISK_PERCENT=1;Kn.DEFAULT_ACCOUNT_BALANCE=1e4;Kn.DEFAULT_PROFIT_COLOR=Bs;Kn.DEFAULT_LOSS_COLOR=Vs;var PO=Kn;function DO(t){if(!Number.isFinite(t))return"0";let e=Math.round(t*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function OO(t){return!Number.isFinite(t)||t===0?"0":t>=100?t.toFixed(2):t>=1?t.toFixed(4).replace(/\\.?0+$/,""):t.toPrecision(4).replace(/\\.?0+$/,"")}function _g(t){return Number.isFinite(t)?Math.abs(t)>=1?t.toFixed(2):t.toPrecision(4).replace(/\\.?0+$/,""):"0"}function bg(t){return Math.round(t*1e8)/1e8}var RO=[{value:"auto",label:v("drawing.magnifier.option.auto","Auto"),ms:0},{value:"1",label:v("drawing.magnifier.option.n1","1m"),ms:6e4},{value:"5",label:v("drawing.magnifier.option.n5","5m"),ms:3e5},{value:"15",label:v("drawing.magnifier.option.n15","15m"),ms:9e5},{value:"30",label:v("drawing.magnifier.option.n30","30m"),ms:18e5},{value:"60",label:v("drawing.magnifier.option.n60","1h"),ms:36e5},{value:"240",label:v("drawing.magnifier.option.n240","4h"),ms:144e5},{value:"D",label:v("drawing.magnifier.option.d","1D"),ms:864e5}];function xg(){return{timeframe:"auto",upColor:"",downColor:""}}var LO=class extends Pe{constructor(t){super(t),this.type="magnifier",this.chipRect=null,this.magnifier||(this.magnifier=xg())}anchorSchema(){return{min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}placementMode(){return"drag"}rect(t){let e=this.anchors[0],n=this.anchors[1];if(!e||!n)return null;let r=t.yOf(e.price,this.paneId),i=t.yOf(n.price,this.paneId);return r==null||i==null?null:{x1:t.xOf(e.time),y1:r,x2:t.xOf(n.time),y2:i}}hitTest(t,e,n,r){let i=this.rect(n);return i?fr(t,e,i.x1,i.y1,i.x2,i.y2)?!0:[[i.x1,i.y1,i.x2,i.y1],[i.x2,i.y1,i.x2,i.y2],[i.x2,i.y2,i.x1,i.y2],[i.x1,i.y2,i.x1,i.y1]].some(a=>ut(t,e,a[0],a[1],a[2],a[3])<=r):!1}handlePoints(t){let e=this.rect(t);return e?[[e.x1,e.y1],[e.x2,e.y2]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}bounds(t){let e=this.rect(t);return e?{x:Math.min(e.x1,e.x2),y:Math.min(e.y1,e.y2),w:Math.abs(e.x2-e.x1),h:Math.abs(e.y2-e.y1)}:null}priceRange(){let t=this.anchors[0],e=this.anchors[1];return!t||!e?null:{min:Math.min(t.price,e.price),max:Math.max(t.price,e.price)}}schema(){return{fields:[{path:"magnifier.timeframe",label:v("drawing.magnifier.magnifierTimeframe","Timeframe"),kind:"select",options:RO,group:"behavior"},...jo,{path:"magnifier.upColor",label:v("drawing.magnifier.magnifierUpColor","Up candles"),kind:"color",group:"fill"},{path:"magnifier.downColor",label:v("drawing.magnifier.magnifierDownColor","Down candles"),kind:"color",group:"fill"}]}}writeProps(){return{...this.magnifier}}readProps(t){this.magnifier={...xg(),...t}}},FO=3;function BO(t,e){if(t.length===0)return-1;let n=0,r=t.length-1;for(;n<r;){let i=n+r>>1;t[i].time<e?n=i+1:r=i}return n>0&&Math.abs(t[n-1].time-e)<=Math.abs(t[n].time-e)?n-1:n}function VO(t,e){let n=t[e-1],r=t[e+1];return!n||!r||!t[e]?null:r.low>n.high?{bull:!0,top:r.low,bottom:n.high}:r.high<n.low?{bull:!1,top:n.low,bottom:r.high}:null}function $O(t,e){for(let n=0;n<=FO;n+=1)for(let r of n===0?[e]:[e-n,e+n]){let i=VO(t,r);if(i)return{index:r,...i}}return null}function zO(t,e){let n=$O(t,e);if(!n)return null;let{index:r,bull:i,top:s,bottom:a}=n,o=(s+a)/2,l=null,c=null,u=null,h=null;for(let p=r+2;p<t.length&&h===null;p+=1){let d=t[p],f=i?d.low:d.high,m=y=>i?f<=y:f>=y;l===null&&m(i?s:a)&&(l=p),c===null&&m(o)&&(c=p),u===null&&m(i?a:s)&&(u=p),u!==null&&(i?d.close<a:d.close>s)&&(h=p)}return{index:r,bull:i,top:s,bottom:a,mid:o,tested:l,half:c,filled:u,inverted:h}}function jO(t,e,n){let r=t[e];if(!r)return null;let i=r.close<r.open,s=n==="body"?Math.max(r.open,r.close):r.high,a=n==="body"?Math.min(r.open,r.close):r.low,o=(s+a)/2,l=!1,c=null,u=null,h=null,p=!1,d=null;for(let f=e+1;f<t.length&&d===null;f+=1){let m=t[f];h===null?(l?(c===null&&(i?m.low<=s:m.high>=a)&&(c=f),u===null&&(i?m.low<=o:m.high>=o)&&(u=f)):l=i?m.low>s:m.high<a,(i?m.close<a:m.close>s)&&(h=f)):p?(i?m.high>=a:m.low<=s)&&(d=f):p=i?m.high<a:m.low>s}return{index:e,bull:i,top:s,bottom:a,mid:o,tested:c,half:u,broken:h,retest:d}}function qO(t,e,n){let r=t[e];if(!r)return null;let i=n==="high",s=i?r.high:r.low,a=null,o=null;for(let l=e+1;l<t.length&&o===null;l+=1){let c=t[l];(i?c.close>s:c.close<s)?o=l:a===null&&(i?c.high>s:c.low<s)&&(a=l)}return{index:e,high:i,price:s,swept:a,broken:o}}var vg=new WeakMap,Ug=class extends Pe{anchorSchema(){return{min:1,max:1,slots:[{role:"candle",free:"x"}]}}candles(t){let e=this.anchors[0];if(!e)return null;let n=vg.get(t);return n||(n=t.barsInRange?.(Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY)??[],vg.set(t,n)),n.length>0?{bars:n,at:BO(n,e.time)}:null}halfBar(t,e,n){let r=e[Math.max(0,n-1)],i=e[Math.min(e.length-1,Math.max(1,n))];return!r||!i||r===i?3:Math.max(1,Math.abs(t.xOf(i.time)-t.xOf(r.time))/2)}rightEdge(t,e,n){return n===null?Math.max(t.width,t.xOf(e[e.length-1].time)):t.xOf(e[n].time)+this.halfBar(t,e,n)}anchorHandle(t){let e=this.anchors[0],n=e?t.yOf(e.price,this.paneId):null;return e&&n!=null?[[t.xOf(e.time),n]]:[]}hitHandle(t,e,n,r){return De(t,e,this.handlePoints(n),r+3)}priceRange(){return null}},Wg=class extends Ug{zone(t){let e=this.candles(t),n=e&&this.formation(e.bars,e.at);if(!e||!n)return null;let r=t.yOf(n.top,this.paneId),i=t.yOf(n.bottom,this.paneId);if(r==null||i==null)return null;let{bars:s}=e,a=this.settings(),o=f=>t.xOf(s[f].time)-this.halfBar(t,s,f),l=Math.min(r,i),c=Math.max(r,i),u=t.yOf(n.mid,this.paneId)??(l+c)/2,h=n.flip&&{x1:o(n.flip.from),x2:this.rightEdge(t,s,n.flip.to),fill:n.bull?a.downColor:a.upColor},p=a.extend==="tested"?n.bull?n.top:n.bottom:a.extend==="half"?n.mid:n.bull?n.bottom:n.top,d=t.yOf(p,this.paneId);return{x1:o(n.start),x2:this.rightEdge(t,s,n.end),yTop:l,yBottom:c,fill:n.bull?a.upColor:a.downColor,border:a.border,midY:a.midline?u:null,faded:n.end!==null&&a.fade&&!h,marker:n.end!==null&&!h&&d!=null?{x:t.xOf(s[n.end].time),y:d}:null,flip:h,handle:[t.xOf(s[n.index].time),u]}}hitTest(t,e,n,r){let i=this.zone(n);if(!i){let a=this.anchors[0];return a!=null&&Math.abs(t-n.xOf(a.time))<=r}let s=e>=i.yTop-r&&e<=i.yBottom+r;return s&&t>=i.x1-r&&t<=i.x2+r?!0:i.flip!=null&&s&&t>=i.flip.x1-r&&t<=i.flip.x2+r}handlePoints(t){let e=this.zone(t);return e?[e.handle]:this.anchorHandle(t)}bounds(t){let e=this.zone(t);if(!e)return null;let n=Math.min(t.width,e.flip?e.flip.x2:e.x2);return{x:e.x1,y:e.yTop,w:Math.max(1,n-e.x1),h:Math.max(1,e.yBottom-e.yTop)}}},wg=[{value:"tested",label:v("drawing.fairvaluegap.option.tested","Until tested")},{value:"half",label:v("drawing.fairvaluegap.option.half","Until 50%")},{value:"filled",label:v("drawing.fairvaluegap.option.filled","Until filled")},{value:"always",label:v("drawing.fairvaluegap.option.always","Always")}];function Sg(){return{extend:"filled",upColor:`${dt}33`,downColor:`${Wt}33`,midline:!0,border:!1,fade:!0,inverse:!1}}var UO=class extends Wg{constructor(t){super(t),this.type="fairvaluegap",this.gap||(this.gap=Sg())}settings(){return this.gap}formation(t,e){let n=zO(t,e);if(!n)return null;let{extend:r,inverse:i}=this.gap,s=i&&r==="filled"&&n.inverted!==null?{from:n.inverted,to:null}:null;return{...n,start:n.index-1,end:r==="always"?null:n[r],flip:s}}schema(){return{fields:[{path:"gap.extend",label:v("drawing.fairvaluegap.gapExtend","Extend right"),kind:"select",options:wg,group:"behavior"},{path:"gap.upColor",label:v("drawing.fairvaluegap.gapUpColor","Bullish"),kind:"color",group:"fill"},{path:"gap.downColor",label:v("drawing.fairvaluegap.gapDownColor","Bearish"),kind:"color",group:"fill"},{path:"gap.midline",label:v("drawing.fairvaluegap.gapMidline","Midline"),kind:"boolean",group:"line"},{path:"gap.border",label:v("drawing.fairvaluegap.gapBorder","Border"),kind:"boolean",group:"line"},{path:"gap.fade",label:v("drawing.fairvaluegap.gapFade","Fade at end"),kind:"boolean",group:"behavior",when:{path:"gap.extend",in:["tested","half","filled"]}},{path:"gap.inverse",label:v("drawing.fairvaluegap.gapInverse","Flip on close"),kind:"boolean",group:"behavior",when:{path:"gap.extend",in:["filled"]}}]}}writeProps(){return{...this.gap}}readProps(t){let e=Sg(),n=t;this.gap={extend:wg.some(r=>r.value===n.extend)?n.extend:e.extend,upColor:typeof n.upColor=="string"?n.upColor:e.upColor,downColor:typeof n.downColor=="string"?n.downColor:e.downColor,midline:typeof n.midline=="boolean"?n.midline:e.midline,border:typeof n.border=="boolean"?n.border:e.border,fade:typeof n.fade=="boolean"?n.fade:e.fade,inverse:typeof n.inverse=="boolean"?n.inverse:e.inverse}}},WO=[{value:"body",label:v("drawing.orderblock.option.body","Body")},{value:"wick",label:v("drawing.orderblock.option.wick","Full range")}],Eg=[{value:"tested",label:v("drawing.orderblock.option.tested","Until tested")},{value:"half",label:v("drawing.orderblock.option.half","Until 50%")},{value:"broken",label:v("drawing.orderblock.option.broken","Until broken")},{value:"always",label:v("drawing.orderblock.option.always","Always")}];function kg(){return{range:"body",extend:"broken",upColor:`${dt}29`,downColor:`${Wt}29`,midline:!0,border:!0,fade:!0,breaker:!0}}var HO=class extends Wg{constructor(t){super(t),this.type="orderblock",this.block||(this.block=kg())}settings(){return this.block}formation(t,e){let n=jO(t,e,this.block.range);if(!n)return null;let{extend:r,breaker:i}=this.block,s=i&&r==="broken"&&n.broken!==null?{from:n.broken,to:n.retest}:null;return{...n,start:n.index,end:r==="always"?null:n[r],flip:s}}schema(){return{fields:[{path:"block.range",label:v("drawing.orderblock.blockRange","Zone"),kind:"select",options:WO,group:"behavior"},{path:"block.extend",label:v("drawing.orderblock.blockExtend","Extend right"),kind:"select",options:Eg,group:"behavior"},{path:"block.upColor",label:v("drawing.orderblock.blockUpColor","Bullish"),kind:"color",group:"fill"},{path:"block.downColor",label:v("drawing.orderblock.blockDownColor","Bearish"),kind:"color",group:"fill"},{path:"block.midline",label:v("drawing.orderblock.blockMidline","Midline"),kind:"boolean",group:"line"},{path:"block.border",label:v("drawing.orderblock.blockBorder","Border"),kind:"boolean",group:"line"},{path:"block.fade",label:v("drawing.orderblock.blockFade","Fade at end"),kind:"boolean",group:"behavior",when:{path:"block.extend",in:["tested","half","broken"]}},{path:"block.breaker",label:v("drawing.orderblock.blockBreaker","Breaker"),kind:"boolean",group:"behavior",when:{path:"block.extend",in:["broken"]}}]}}writeProps(){return{...this.block}}readProps(t){let e=kg(),n=t;this.block={range:n.range==="body"||n.range==="wick"?n.range:e.range,extend:Eg.some(r=>r.value===n.extend)?n.extend:e.extend,upColor:typeof n.upColor=="string"?n.upColor:e.upColor,downColor:typeof n.downColor=="string"?n.downColor:e.downColor,midline:typeof n.midline=="boolean"?n.midline:e.midline,border:typeof n.border=="boolean"?n.border:e.border,fade:typeof n.fade=="boolean"?n.fade:e.fade,breaker:typeof n.breaker=="boolean"?n.breaker:e.breaker}}},Ag=[{value:"swept",label:v("drawing.liquidity.option.swept","Until swept")},{value:"broken",label:v("drawing.liquidity.option.broken","Until broken")},{value:"always",label:v("drawing.liquidity.option.always","Always")}];function Tg(){return{extend:"swept",markSweep:!0}}var GO=class extends Ug{constructor(t){super(t),this.type="liquidity",this.liq||(this.liq=Tg())}anchorSchema(){return{min:1,max:1,slots:[{role:"candle",free:"both"}]}}state(t){let e=this.candles(t),n=this.anchors[0];if(!e||!n)return null;let r=e.bars[e.at];return qO(e.bars,e.at,n.price>=(r.high+r.low)/2?"high":"low")}line(t){let e=this.candles(t),n=this.state(t);if(!e||!n)return null;let r=t.yOf(n.price,this.paneId);if(r==null)return null;let{bars:i}=e,{extend:s,markSweep:a}=this.liq,o=s==="always"?null:s==="broken"?n.broken:n.swept??n.broken,l=t.xOf(i[n.index].time),c=null;if(a&&n.swept!==null&&(o===null||n.swept<=o)){let u=i[n.swept],h=t.yOf(n.high?u.high:u.low,this.paneId);h!=null&&(c={x:t.xOf(u.time),y:h+(n.high?-9:9)})}return{x1:l,x2:this.rightEdge(t,i,o),y:r,sweep:c,handle:[l,r]}}hitTest(t,e,n,r){let i=this.line(n);return i!=null&&t>=i.x1-r&&t<=i.x2+r&&Math.abs(e-i.y)<=r}handlePoints(t){let e=this.line(t);return e?[e.handle]:this.anchorHandle(t)}bounds(t){let e=this.line(t);return e?{x:e.x1,y:e.y-4,w:Math.max(1,Math.min(t.width,e.x2)-e.x1),h:8}:null}schema(){return{fields:[...xe,{path:"liq.extend",label:v("drawing.liquidity.liqExtend","Extend right"),kind:"select",options:Ag,group:"behavior"},{path:"liq.markSweep",label:v("drawing.liquidity.liqMarkSweep","Mark sweep"),kind:"boolean",group:"behavior"}]}}writeProps(){return{...this.liq}}readProps(t){let e=Tg(),n=t;this.liq={extend:Ag.some(r=>r.value===n.extend)?n.extend:e.extend,markSweep:typeof n.markSweep=="boolean"?n.markSweep:e.markSweep}}},KO=new Map;function W(t){KO.set(t.type,t)}var YO=D(\'<line x1="4" y1="19" x2="20" y2="5"/>\'),XO=D(\'<line x1="3" y1="12" x2="21" y2="12"/>\');W({type:"trendline",group:"lines",label:v("drawing.trendline.label","Trend Line"),icon:YO,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new cP(t)});W({type:"hline",group:"lines",label:v("drawing.hline.label","Horizontal Line"),icon:XO,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"dashed"},create:t=>new uP(t)});var ZO=D(\'<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>\'),JO=D(\'<rect x="4" y="6" width="16" height="12" rx="1"/>\'),QO=D(\'<path d="M5 6h14M12 6v13"/>\');W({type:"ray",group:"lines",label:v("drawing.ray.label","Ray"),icon:ZO,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new hP(t)});var eR=D(\'<path d="M5 19 19 5"/><path d="M5 19 8.5 19M5 19 5 15.5"/><path d="M19 5 15.5 5M19 5 19 8.5"/>\'),tR=D(\'<line x1="12" y1="3" x2="12" y2="21"/>\'),nR=D(\'<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>\'),rR=D(\'<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>\'),iR=D(\'<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>\'),sR=D(\'<path d="M4 20 20 6"/><path d="M4 20 15 20"/><path d="M11 20a7 7 0 0 0-2-4.9"/>\');W({type:"extendedline",group:"lines",label:v("drawing.extendedline.label","Extended Line"),icon:eR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new pP(t)});W({type:"vline",group:"lines",label:v("drawing.vline.label","Vertical Line"),icon:tR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new dP(t)});W({type:"hray",group:"lines",label:v("drawing.hray.label","Horizontal Ray"),icon:nR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new fP(t)});W({type:"crossline",group:"lines",label:v("drawing.crossline.label","Cross Line"),icon:rR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new mP(t)});W({type:"infoline",group:"lines",label:v("drawing.infoline.label","Info Line"),icon:iR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new yP(t)});W({type:"trendangle",group:"lines",label:v("drawing.trendangle.label","Trend Angle"),icon:sR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new gP(t)});W({type:"box",group:"shapes",label:v("drawing.box.label","Rectangle"),icon:JO,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}26`},create:t=>new _P(t)});W({type:"text",group:"annotations",label:v("drawing.text.label","Text"),icon:QO,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new xP(t)});var aR=D(\'<path d="M5 4h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-6l-5 5v-5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/>\');W({type:"callout",group:"annotations",label:v("drawing.callout.label","Callout"),icon:aR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new EP(t)});var oR=D(\'<path d="M5 4h14a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7l-4 4v-4H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/><path d="M8 8.5h8M8 12h5"/>\'),lR=D(\'<rect x="10" y="4.5" width="11" height="8" rx="1.5"/><path d="M10 8.5 4 16"/><circle cx="3.5" cy="16.5" r="1.6" fill="currentColor" stroke="none"/>\'),cR=D(\'<path d="M5 4.5h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-7l-4 4v-4H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z"/>\'),uR=D(\'<path d="M3 12 7 8h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7Z"/><path d="M10.5 12.5h6" stroke-width="1.4"/>\'),hR=D(\'<path d="M12 11.5V21"/><rect x="5" y="4" width="14" height="7" rx="1"/><path d="M9 7.5h6"/>\');W({type:"note",group:"annotations",label:v("drawing.note.label","Note"),icon:oR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new vP(t)});W({type:"pricenote",group:"annotations",label:v("drawing.pricenote.label","Price Note"),icon:lR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new kP(t)});W({type:"comment",group:"annotations",label:v("drawing.comment.label","Comment"),icon:cR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new AP(t)});W({type:"pricelabel",group:"annotations",label:v("drawing.pricelabel.label","Price Label"),icon:uR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new wP(t)});W({type:"signpost",group:"annotations",label:v("drawing.signpost.label","Signpost"),icon:hR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid",fillColor:`${U}d9`},create:t=>new TP(t)});var pR=D(\'<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>\'),dR=D(\'<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>\'),fR=D(\'<circle cx="4" cy="12" r="1.6" fill="currentColor"/><line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>\');W({type:"parallelchannel",group:"channels",label:v("drawing.parallelchannel.label","Parallel Channel"),icon:pR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new NP(t)});W({type:"disjointchannel",group:"channels",label:v("drawing.disjointchannel.label","Disjoint Channel"),icon:dR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new CP(t)});var mR=D(\'<line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="18" x2="21" y2="11"/>\');W({type:"flattopbottom",group:"channels",label:v("drawing.flattopbottom.label","Flat Top/Bottom"),icon:mR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new IP(t)});var yR=D(\'<line x1="3" y1="8" x2="21" y2="4"/><line x1="3" y1="16" x2="21" y2="12"/><line x1="3" y1="12" x2="21" y2="8" stroke-dasharray="3 3"/>\');W({type:"regressionchannel",group:"channels",label:v("drawing.regressionchannel.label","Linear Regression"),icon:yR,defaultStyle:{lineColor:hr,lineWidth:1,lineStyle:"solid"},create:t=>new DP(t)});W({type:"pitchfork",group:"pitchforks",label:v("drawing.pitchfork.label","Pitchfork"),icon:fR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new UP(t)});var gR=D(\'<circle cx="4" cy="8" r="1.6" fill="currentColor"/><line x1="4" y1="8" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>\'),_R=D(\'<circle cx="6" cy="9" r="1.6" fill="currentColor"/><line x1="6" y1="9" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>\'),bR=D(\'<line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="8" x2="10" y2="16"/><line x1="10" y1="8" x2="21" y2="8"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="16" x2="21" y2="16"/>\');W({type:"schiffpitchfork",group:"pitchforks",label:v("drawing.schiffpitchfork.label","Schiff Pitchfork"),icon:gR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new WP(t)});W({type:"modifiedschiffpitchfork",group:"pitchforks",label:v("drawing.modifiedschiffpitchfork.label","Modified Schiff Pitchfork"),icon:_R,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new HP(t)});W({type:"insidepitchfork",group:"pitchforks",label:v("drawing.insidepitchfork.label","Inside Pitchfork"),icon:bR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new GP(t)});var xR=D(\'<path d="M7 7h10v10"/><path d="M7 17 17 7"/>\'),vR=D(\'<ellipse cx="12" cy="12" rx="9" ry="6"/>\'),wR=D(\'<path d="M12 4 20 19 4 19Z"/>\');W({type:"arrow",group:"shapes",label:v("drawing.arrow.label","Arrow"),icon:xR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",arrowRight:!0},create:t=>new KP(t)});W({type:"ellipse",group:"shapes",label:v("drawing.ellipse.label","Ellipse"),icon:vR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new YP(t)});W({type:"triangle",group:"shapes",label:v("drawing.triangle.label","Triangle"),icon:wR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new XP(t)});var SR=D(\'<polyline points="3 17 9 10 13 14 21 5"/>\'),ER=D(\'<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>\'),kR=D(\'<path d="M9 11 15 5l4 4-6 6H9Z"/><path d="M9 15l-2 2"/><path d="M4 21h6"/>\');W({type:"polyline",group:"shapes",label:v("drawing.polyline.label","Polyline"),icon:SR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new JP(t)});W({type:"freehand",group:"shapes",label:v("drawing.freehand.label","Brush"),icon:ER,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new QP(t)});W({type:"highlighter",group:"shapes",label:v("drawing.highlighter.label","Highlighter"),icon:kR,defaultStyle:{lineColor:`${Fs}59`,lineWidth:14,lineStyle:"solid"},create:t=>new tD(t)});var AR=D(\'<circle cx="12" cy="12" r="8"/>\'),TR=D(\'<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>\'),NR=D(\'<path d="M4 19 9 11 13 14 17 8 20 4"/><path d="M17.2 5.5 20 4 19.4 7.1"/>\'),CR=D(\'<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>\'),IR=D(\'<path d="M4 18Q12 1 20 14"/>\'),MR=D(\'<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>\'),PR=D(\'<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>\');W({type:"circle",group:"shapes",label:v("drawing.circle.label","Circle"),icon:AR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}1a`},create:t=>new nD(t)});W({type:"rotatedrect",group:"shapes",label:v("drawing.rotatedrect.label","Rotated Rectangle"),icon:TR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}26`},create:t=>new rD(t)});W({type:"path",group:"shapes",label:v("drawing.path.label","Path"),icon:NR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new iD(t)});W({type:"arc",group:"shapes",label:v("drawing.arc.label","Arc"),icon:CR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid",fillColor:`${U}26`},create:t=>new sD(t)});W({type:"curve",group:"shapes",label:v("drawing.curve.label","Curve"),icon:IR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new aD(t)});W({type:"arrowmarkup",group:"shapes",label:v("drawing.arrowmarkup.label","Arrow Mark Up"),icon:MR,defaultStyle:{lineColor:dt,lineWidth:1,lineStyle:"solid"},create:t=>new lD(t)});W({type:"arrowmarkdown",group:"shapes",label:v("drawing.arrowmarkdown.label","Arrow Mark Down"),icon:PR,defaultStyle:{lineColor:Wt,lineWidth:1,lineStyle:"solid"},create:t=>new cD(t)});var DR=D(\'<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>\'),OR=D(\'<path d="m12 3 2.6 5.8 6.4.6-4.8 4.2 1.4 6.2L12 16.9 6.4 19.8 7.8 13.6 3 9.4l6.4-.6Z"/>\');W({type:"flagmark",group:"stamps",label:v("drawing.flagmark.label","Flag"),icon:DR,defaultStyle:{lineColor:ur,lineWidth:1,lineStyle:"solid"},create:t=>new pD(t)});W({type:"iconstamp",group:"stamps",label:v("drawing.iconstamp.label","Icon"),icon:OR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new dD(t)});var RR=D(\'<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/>\'),LR=D(\'<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="11" x2="21" y2="11"/><line x1="3" y1="15" x2="14" y2="15"/><line x1="3" y1="20" x2="14" y2="20"/>\');W({type:"fibretracement",group:"fibonacci",label:v("drawing.fibretracement.label","Fib Retracement"),icon:RR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new vD(t)});W({type:"fibextension",group:"fibonacci",label:v("drawing.fibextension.label","Fib Extension"),icon:LR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new SD(t)});var FR=D(\'<path d="M3 20 10 9l4 5"/><path d="M14 14h7M14 9h7M14 4h7"/>\');W({type:"fibextensiontrend",group:"fibonacci",label:v("drawing.fibextensiontrend.label","Trend-Based Fib Extension"),icon:FR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new kD(t)});var BR=D(\'<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>\'),VR=D(\'<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>\');W({type:"fibfan",group:"fibonacci",label:v("drawing.fibfan.label","Fib Fan"),icon:BR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new TD(t)});W({type:"fibtimezones",group:"fibonacci",label:v("drawing.fibtimezones.label","Fib Time Zones"),icon:VR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"dashed"},create:t=>new CD(t)});var $R=D(\'<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>\'),zR=D(\'<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>\'),jR=D(\'<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>\');W({type:"fibchannel",group:"fibonacci",label:v("drawing.fibchannel.label","Fib Channel"),icon:$R,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new MD(t)});W({type:"fibspeedfan",group:"fibonacci",label:v("drawing.fibspeedfan.label","Fib Speed Resistance Fan"),icon:zR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new DD(t)});W({type:"trendfibtime",group:"fibonacci",label:v("drawing.trendfibtime.label","Trend-Based Fib Time"),icon:jR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"dashed"},create:t=>new RD(t)});var qR=D(\'<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>\'),UR=D(\'<path d="M8 20a4 4 0 0 1 8 0"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/><circle cx="12" cy="20" r="1.4" fill="currentColor" stroke="none"/>\'),WR=D(\'<path d="M4 20 20 16M4 20 14 4"/><path d="M11.8 18.1A8 8 0 0 0 8.2 13.2"/><path d="M16.6 16.9A13 13 0 0 0 10.9 9"/>\'),HR=D(\'<path d="M13 12a2 2 0 1 1-2-2 4 4 0 0 1 4 4 6 6 0 0 1-9 5.2 9 9 0 0 1 .5-15"/>\');W({type:"fibcircles",group:"fibonacci",label:v("drawing.fibcircles.label","Fib Circles"),icon:qR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new BD(t)});W({type:"fibarcs",group:"fibonacci",label:v("drawing.fibarcs.label","Fib Speed Resistance Arcs"),icon:UR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new $D(t)});W({type:"fibwedge",group:"fibonacci",label:v("drawing.fibwedge.label","Fib Wedge"),icon:WR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new jD(t)});W({type:"fibspiral",group:"fibonacci",label:v("drawing.fibspiral.label","Fib Spiral"),icon:HR,defaultStyle:{lineColor:U,lineWidth:2,lineStyle:"solid"},create:t=>new GD(t)});var GR=D(\'<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>\'),KR=D(\'<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16M4 4 20 20" opacity="0.6"/>\');W({type:"gannfan",group:"fibonacci",label:v("drawing.gannfan.label","Gann Fan"),icon:GR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new YD(t)});W({type:"gannbox",group:"fibonacci",label:v("drawing.gannbox.label","Gann Box"),icon:KR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new ZD(t)});var YR=D(\'<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 20 20 4M4 20 20 12M4 20 12 4" opacity="0.7"/><path d="M4 20a16 16 0 0 1 16-16" opacity="0.5"/>\');W({type:"gannsquare",group:"fibonacci",label:v("drawing.gannsquare.label","Gann Square"),icon:YR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new eO(t)});var XR=D(\'<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0" opacity="0.9"/><path d="M6 20a4 4 0 0 1 8 0" opacity="0.75"/><path d="M10 20a2 2 0 0 1 4 0" opacity="0.6"/><path d="M8 20v-6M12 20v-9M16 20v-6" opacity="0.45"/>\');W({type:"dedekind",group:"geometry",label:v("drawing.dedekind.label","Dedekind Tessellation"),icon:XR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new sO(t)});var ZR=D(\'<circle cx="16" cy="12" r="5" opacity="0.55"/><circle cx="13" cy="12" r="3.5" opacity="0.75"/><circle cx="10.5" cy="12" r="2"/><path d="M8 4v16"/>\'),JR=D(\'<circle cx="17" cy="12" r="4.5" opacity="0.45"/><circle cx="13" cy="12" r="3" opacity="0.7"/><circle cx="10" cy="12" r="1.6"/><path d="M6 12 16 5M6 12 16 19"/>\');W({type:"sonic",group:"geometry",label:v("drawing.sonic.label","Sonic"),icon:ZR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new lO(t)});W({type:"supersonic",group:"geometry",label:v("drawing.supersonic.label","Supersonic"),icon:JR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new cO(t)});var QR=D(\'<circle cx="16" cy="12" r="5" opacity="0.4"/><circle cx="13" cy="12" r="3.2" opacity="0.65"/><circle cx="10.8" cy="12" r="1.8"/><path d="M8 4v16"/><path d="M15 8.5h2M12.5 10h2" opacity="0.5"/>\'),eL=D(\'<circle cx="17" cy="12" r="4.5" opacity="0.4"/><circle cx="12.5" cy="12" r="2.8" opacity="0.65"/><circle cx="9.8" cy="12" r="1.4"/><path d="M6 12 16 5M6 12 16 19"/>\');W({type:"goldensonic",group:"geometry",label:v("drawing.goldensonic.label","Golden Sonic"),icon:QR,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new hO(t)});W({type:"goldensupersonic",group:"geometry",label:v("drawing.goldensupersonic.label","Golden Supersonic"),icon:eL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new pO(t)});var tL=D(\'<path d="M3 18 7 8 11 14 15 6 20 16"/>\'),nL=D(\'<path d="M4 17 9 7 14 15 20 5"/>\'),rL=D(\'<path d="M3 19 8 9 12 13 17 5 21 9"/>\'),iL=D(\'<path d="M4 7 11 16 20 9"/>\'),sL=D(\'<path d="M3 18 6 12 9 16 12 5 15 16 18 12 21 18"/>\');W({type:"xabcd",group:"patterns",label:v("drawing.xabcd.label","XABCD Pattern"),icon:tL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new dO(t)});W({type:"abcd",group:"patterns",label:v("drawing.abcd.label","ABCD Pattern"),icon:nL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new fO(t)});W({type:"elliottimpulse",group:"patterns",label:v("drawing.elliottimpulse.label","Elliott Impulse Wave (1-5)"),icon:rL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new mO(t)});W({type:"elliottcorrection",group:"patterns",label:v("drawing.elliottcorrection.label","Elliott Correction Wave (ABC)"),icon:iL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new yO(t)});W({type:"headshoulders",group:"patterns",label:v("drawing.headshoulders.label","Head & Shoulders"),icon:sL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new xO(t)});var aL=D(\'<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>\'),Gi={group:"patterns",icon:aL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"}};W({type:"gartley",label:v("drawing.gartley.label","Gartley"),...Gi,create:t=>new vO(t)});W({type:"bat",label:v("drawing.bat.label","Bat"),...Gi,create:t=>new wO(t)});W({type:"butterfly",label:v("drawing.butterfly.label","Butterfly"),...Gi,create:t=>new SO(t)});W({type:"crab",label:v("drawing.crab.label","Crab"),...Gi,create:t=>new EO(t)});W({type:"shark",label:v("drawing.shark.label","Shark"),...Gi,create:t=>new kO(t)});W({type:"cypher",label:v("drawing.cypher.label","Cypher"),...Gi,create:t=>new NO(t)});var oL=D(\'<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M4 18 20 6" opacity="0.5"/>\');W({type:"datepricerange",group:"measure",label:v("drawing.datepricerange.label","Date & Price Range"),icon:oL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new IO(t)});var lL=D(\'<rect x="4.5" y="4.5" width="15" height="7.5" rx="1" fill="currentColor" fill-opacity="0.25"/><rect x="4.5" y="12" width="15" height="7.5" rx="1"/>\');W({type:"position",group:"measure",label:v("drawing.position.label","Long/Short Position"),icon:lL,defaultStyle:{lineColor:U,lineWidth:1,lineStyle:"solid"},create:t=>new PO(t)});var cL=D(\'<circle cx="10.5" cy="10.5" r="6.5"/><path d="m15.3 15.3 5.2 5.2"/><path d="M8 12.5v-3M10.5 13.5v-5.5M13 12v-2"/>\');W({type:"magnifier",group:"measure",label:v("drawing.magnifier.label","Magnifier"),icon:cL,defaultStyle:{lineColor:"",lineWidth:1,lineStyle:"solid"},coversSeries:!0,placementHint:v("drawing.magnifier.placementHint","Drag an area on the chart to view it at a lower timeframe"),create:t=>new LO(t)});var uL=D(\'<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>\');W({type:"anchoredvwap",group:"measure",label:v("drawing.anchoredvwap.label","Anchored VWAP"),icon:uL,defaultStyle:{lineColor:pr,lineWidth:2,lineStyle:"solid"},create:t=>new RP(t)});var hL=D(\'<path d="M4 4v16"/><path d="M4 8h10"/><path d="M4 12h14"/><path d="M4 16h8"/><path d="M4 20h12"/>\');W({type:"fixedrangevp",group:"measure",label:v("drawing.fixedrangevp.label","Fixed Range Volume Profile"),icon:hL,defaultStyle:{lineColor:dt,lineWidth:1,lineStyle:"solid"},create:t=>new qP(t)});var pL=D(\'<path d="M6 15v6M12 3v18M18 2v6"/><rect x="3.5" y="9.5" width="17" height="5" rx="1" fill="currentColor" fill-opacity="0.28" stroke-width="1.4"/>\'),dL=D(\'<rect x="4" y="7.5" width="5" height="8" rx="1"/><path d="M6.5 4v3.5M6.5 15.5V19"/><rect x="9" y="7.5" width="11.5" height="8" rx="1" fill="currentColor" fill-opacity="0.22" stroke-width="1.4"/>\'),fL=D(\'<path d="M3 8h12" stroke-dasharray="2.5 2.5"/><path d="m16.5 4.5 4 4m0-4-4 4"/><path d="M3.5 20 8 13.5l4 3.5 5-8"/>\');W({type:"fairvaluegap",group:"priceaction",label:v("drawing.fairvaluegap.label","Fair Value Gap"),icon:pL,defaultStyle:{lineColor:dt,lineWidth:1,lineStyle:"solid"},placementHint:v("drawing.fairvaluegap.placementHint","Click the middle candle of a gap"),create:t=>new UO(t)});W({type:"orderblock",group:"priceaction",label:v("drawing.orderblock.label","Order Block"),icon:dL,defaultStyle:{lineColor:dt,lineWidth:1,lineStyle:"solid"},placementHint:v("drawing.orderblock.placementHint","Click the candle that forms the block"),create:t=>new HO(t)});W({type:"liquidity",group:"priceaction",label:v("drawing.liquidity.label","Liquidity"),icon:fL,defaultStyle:{lineColor:ji,lineWidth:1,lineStyle:"solid"},placementHint:v("drawing.liquidity.placementHint","Click near a candle\'s high or low"),create:t=>new GO(t)});var tF=v("chart.settings.rangeMin","{label} \\u2014 min"),nF=v("chart.settings.rangeMax","{label} \\u2014 max");function ne(t,e){return{value:t,label:Br(e),name:e}}var rF=[ne("Etc/UTC",v("timezone.Etc.UTC","UTC")),ne("Etc/GMT+12",v("timezone.Etc.GMTPlus12","International Date Line West")),ne("Pacific/Pago_Pago",v("timezone.Pacific.PagoPago","Pago Pago")),ne("Pacific/Honolulu",v("timezone.Pacific.Honolulu","Honolulu")),ne("Pacific/Marquesas",v("timezone.Pacific.Marquesas","Marquesas Islands")),ne("America/Anchorage",v("timezone.America.Anchorage","Anchorage")),ne("America/Los_Angeles",v("timezone.America.LosAngeles","Los Angeles")),ne("America/Phoenix",v("timezone.America.Phoenix","Phoenix")),ne("America/Denver",v("timezone.America.Denver","Denver")),ne("America/Chicago",v("timezone.America.Chicago","Chicago")),ne("America/Mexico_City",v("timezone.America.MexicoCity","Mexico City")),ne("America/New_York",v("timezone.America.NewYork","New York")),ne("America/Bogota",v("timezone.America.Bogota","Bogot\\xE1")),ne("America/Caracas",v("timezone.America.Caracas","Caracas")),ne("America/Santiago",v("timezone.America.Santiago","Santiago")),ne("America/St_Johns",v("timezone.America.StJohns","St. John\'s")),ne("America/Sao_Paulo",v("timezone.America.SaoPaulo","S\\xE3o Paulo")),ne("America/Argentina/Buenos_Aires",v("timezone.America.Argentina.BuenosAires","Buenos Aires")),ne("America/Noronha",v("timezone.America.Noronha","Fernando de Noronha")),ne("Atlantic/Azores",v("timezone.Atlantic.Azores","Azores")),ne("Atlantic/Reykjavik",v("timezone.Atlantic.Reykjavik","Reykjavik")),ne("Europe/London",v("timezone.Europe.London","London")),ne("Europe/Paris",v("timezone.Europe.Paris","Paris")),ne("Europe/Berlin",v("timezone.Europe.Berlin","Berlin")),ne("Europe/Athens",v("timezone.Europe.Athens","Athens")),ne("Africa/Cairo",v("timezone.Africa.Cairo","Cairo")),ne("Africa/Johannesburg",v("timezone.Africa.Johannesburg","Johannesburg")),ne("Europe/Moscow",v("timezone.Europe.Moscow","Moscow")),ne("Europe/Istanbul",v("timezone.Europe.Istanbul","Istanbul")),ne("Asia/Tehran",v("timezone.Asia.Tehran","Tehran")),ne("Asia/Dubai",v("timezone.Asia.Dubai","Dubai")),ne("Asia/Kabul",v("timezone.Asia.Kabul","Kabul")),ne("Asia/Karachi",v("timezone.Asia.Karachi","Karachi")),ne("Asia/Kolkata",v("timezone.Asia.Kolkata","Mumbai")),ne("Asia/Kathmandu",v("timezone.Asia.Kathmandu","Kathmandu")),ne("Asia/Dhaka",v("timezone.Asia.Dhaka","Dhaka")),ne("Asia/Yangon",v("timezone.Asia.Yangon","Yangon")),ne("Asia/Bangkok",v("timezone.Asia.Bangkok","Bangkok")),ne("Asia/Shanghai",v("timezone.Asia.Shanghai","Shanghai")),ne("Asia/Hong_Kong",v("timezone.Asia.HongKong","Hong Kong")),ne("Asia/Singapore",v("timezone.Asia.Singapore","Singapore")),ne("Australia/Eucla",v("timezone.Australia.Eucla","Eucla")),ne("Asia/Tokyo",v("timezone.Asia.Tokyo","Tokyo")),ne("Asia/Seoul",v("timezone.Asia.Seoul","Seoul")),ne("Australia/Adelaide",v("timezone.Australia.Adelaide","Adelaide")),ne("Australia/Sydney",v("timezone.Australia.Sydney","Sydney")),ne("Australia/Lord_Howe",v("timezone.Australia.LordHowe","Lord Howe Island")),ne("Pacific/Noumea",v("timezone.Pacific.Noumea","Noum\\xE9a")),ne("Pacific/Auckland",v("timezone.Pacific.Auckland","Auckland")),ne("Pacific/Chatham",v("timezone.Pacific.Chatham","Chatham Islands")),ne("Pacific/Apia",v("timezone.Pacific.Apia","Apia")),ne("Pacific/Kiritimati",v("timezone.Pacific.Kiritimati","Kiritimati"))];var iF=v("timezone.exchange","Exchange"),sF=v("timezone.menuLabel","({offset}) {location}");function Ch(t){let e=t.title.trim().toLowerCase().replace(/\\s+/g,"-");return`${t.instanceId}:${t.kind}:${e}#${t.ordinal}`}var mL=["symbol","timeframes","style","layout","indicators","actions","undo-redo","alerts","panels","screenshot"];var Hg=["indicators","screenshot"],aF=new Set(Hg),oF=new Set(mL);var Oo={regular:v("widget.contextMenu.scale.regular","Regular"),percent:v("widget.contextMenu.scale.percent","Percent"),indexed:v("widget.contextMenu.scale.indexed","Indexed to 100"),log:v("widget.contextMenu.scale.log","Logarithmic"),auto:v("widget.contextMenu.auto","Auto (fits data to screen)"),priceOnly:v("widget.contextMenu.scalePriceOnly","Scale price chart only"),invert:v("widget.contextMenu.invert","Invert scale"),labels:v("widget.contextMenu.labels","Labels"),axisLabels:v("widget.contextMenu.axisLabels","Price axis labels"),priceLabel:v("widget.contextMenu.priceLabel","Last price label"),countdown:v("widget.contextMenu.countdown","Countdown to bar close"),levels:v("widget.contextMenu.levels","Levels"),priceLine:v("widget.contextMenu.priceLine","Last price line"),moreSettings:v("widget.contextMenu.moreSettings","More settings\\u2026"),timezone:v("widget.contextMenu.timezone","Time zone"),resetView:v("widget.contextMenu.resetView","Reset chart view"),removeDrawings:v("widget.contextMenu.removeDrawings","Remove drawings"),removeIndicators:v("widget.contextMenu.removeIndicators","Remove indicators"),settings:v("widget.contextMenu.settings","Settings\\u2026")};var lF=[["regular",Oo.regular],["percent",Oo.percent],["indexed",Oo.indexed],["log",Oo.log]];var cF={close:v("widget.sidePanel.close","Close"),restore:v("widget.sidePanel.restore","Restore"),maximize:v("widget.sidePanel.maximize","Maximize"),unpin:v("widget.sidePanel.unpin","Unpin \\u2014 float over the chart"),pin:v("widget.sidePanel.pin","Pin beside the chart")},Gg=280;var uF=gh`@layer vela.chrome {\n\n.vela-panel[hidden] { display: none !important; }\n.vela-panel {\n position: relative;\n width: var(--vela-panel-w, ${Gg}px);\n flex: none;\n border-inline-start: 1px solid ${Xe.border};\n display: flex;\n flex-direction: column;\n color: ${Xe.fg};\n font-size: 13px;\n box-sizing: border-box;\n background: ${Xe.bg};\n}\n.vela-panel-header[hidden] { display: none; }\n.vela-panel-header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 10px 8px 10px 14px;\n border-bottom: 1px solid ${Xe.border};\n font-size: 14px;\n font-weight: 600;\n color: ${Xe.fg.bright};\n}\n.vela-panel-title { flex: none; }\n.vela-panel-title:empty { display: none; }\n/* The contributed slot claims the space between title and close; its children lay out\n inline and the close button stays pinned right. */\n.vela-panel-header-slot { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; }\n.vela-panel-close {\n all: unset;\n box-sizing: border-box;\n cursor: pointer;\n width: 26px;\n height: 26px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: ${Xe.radius.sm};\n color: ${Xe.fg.muted};\n font-size: 16px;\n}\n.vela-panel-close .vela-icon { width: 16px; height: 16px; }\n.vela-panel-close:hover { background: ${Xe.hover}; color: ${Xe.fg.bright}; }\n/* The pin: same footprint as the close button it sits beside; filled + bright once pinned. */\n.vela-panel-pin {\n all: unset;\n box-sizing: border-box;\n cursor: pointer;\n width: 26px;\n height: 26px;\n flex: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: ${Xe.radius.sm};\n color: ${Xe.fg.muted};\n}\n.vela-panel-pin .vela-icon { width: 15px; height: 15px; }\n.vela-panel-pin:hover { background: ${Xe.hover}; color: ${Xe.fg.bright}; }\n.vela-panel-pin[data-on=\'1\'] { color: ${Xe.fg.bright}; }\n.vela-panel-max {\n all: unset;\n box-sizing: border-box;\n cursor: pointer;\n width: 26px;\n height: 26px;\n flex: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: ${Xe.radius.sm};\n color: ${Xe.fg.muted};\n}\n.vela-panel-max .vela-icon { width: 15px; height: 15px; }\n.vela-panel-max:hover { background: ${Xe.hover}; color: ${Xe.fg.bright}; }\n/* MAXIMIZED: the panel covers the whole dock host — every chart of the shell — whatever\n its placement; the width handle and the pin have nothing to do meanwhile. */\n.vela-panel[data-maximized] {\n position: absolute;\n inset: 0;\n width: auto;\n max-width: none;\n z-index: 26;\n border-inline-start: none;\n}\n.vela-panel[data-maximized] .vela-panel-resizer,\n.vela-panel[data-maximized] .vela-panel-pin { display: none; }\n.vela-panel-body { flex: 1; overflow: auto; padding: 8px; }\n/* Straddles the panel\'s inner border so the whole seam is grabbable; it paints only under the\n pointer — a permanently visible bar would read as a second border. */\n.vela-panel-resizer {\n position: absolute;\n top: 0;\n bottom: 0;\n inset-inline-start: -3px;\n width: 7px;\n cursor: col-resize;\n touch-action: none;\n z-index: 1;\n}\n.vela-panel-resizer::after {\n content: \'\';\n position: absolute;\n top: 0;\n bottom: 0;\n inset-inline-start: 3px;\n width: 1px;\n background: transparent;\n}\n/* The same hover ink as the workspace grid splitters and the canvas pane separators, so\n every draggable seam in the shell reads as one family. */\n.vela-panel-resizer:hover::after,\n.vela-panel-resizer[data-dragging]::after { background: ${Xe.separatorHover.line}; }\n/* An OVERLAY panel floats over the chart\'s right edge instead of taking a column: the\n chart keeps its width and layout (the dock host is position:relative — the anchoring the\n mobile rule below relies on too). Same z-order as that mobile overlay, above the chart\'s\n own DOM overlays; the shadow separates it from the plot it covers. */\n.vela-panel[data-overlay] {\n position: absolute;\n top: 0;\n inset-inline-end: 0;\n bottom: 0;\n max-width: 100%;\n z-index: 25;\n box-shadow: ${Xe.shadow};\n}\n/* Mobile: a 280px column would crush a phone-width chart — the panel overlays the\n chart area instead (its flex parent is position:relative), full-bleed, closed by\n the same header ✕. Width dragging is a pointer affordance; off on mobile. */\n[data-layout=\'mobile\'] .vela-panel {\n position: absolute;\n inset: 0;\n width: auto;\n z-index: 25;\n border-inline-start: none;\n}\n[data-layout=\'mobile\'] .vela-panel-resizer { display: none; }\n[data-layout=\'mobile\'] .vela-panel-max { display: none; }\n\n}`;var Go=class{constructor(){Zh(this,"ordinals",new Map)}next(e,n,r){let i=`${n}:${r.trim().toLowerCase()}`,s=this.ordinals.get(i)??0;return this.ordinals.set(i,s+1),Ch({instanceId:e,kind:n,title:r,ordinal:s})}};function Ki(t){let e=t.data;if(e.length===0)return[];let n=e[e.length-1]?.value;return Array.isArray(n)?n:[]}function Ve(t){if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t&&typeof t=="object"){let e=t;if(Array.isArray(e.data)){let n=typeof e.offset=="number"?e.offset:0,r=e.data[e.data.length-1-n];return typeof r=="number"&&Number.isFinite(r)?r:void 0}}}function Ko(t){let e=(J(t)??"").toLowerCase();return e==="bt"||e.includes("time")?"bar_time":"bar_index"}function Yg(t){let e=(J(t)??"none").toLowerCase();return e==="b"||e==="both"?"both":e==="l"||e==="left"?"left":e==="r"||e==="right"?"right":"none"}function Mh(t){let e=(J(t)??"").toLowerCase();return e.includes("dot")?"dotted":e.includes("dash")?"dashed":"solid"}function Xg(t){if(t===void 0)return{invisible:!1};if(t===null)return{invisible:!0};if(typeof t=="number")return{invisible:!0};if(typeof t=="string"){if(t==="")return{invisible:!1};let e=Se(t);return e?{color:e,invisible:!1}:{invisible:!0}}return{invisible:!0}}function Ih(t,e){let n=Ve(t.x1),r=Ve(t.y1),i=Ve(t.x2),s=Ve(t.y2);if(n===void 0||r===void 0||i===void 0||s===void 0)return null;let a=(J(t.style)??"").toLowerCase(),o=a==="style_arrow_left"||a==="style_arrow_both",l=a==="style_arrow_right"||a==="style_arrow_both",{color:c,invisible:u}=Xg(t.color);return{id:e,paneId:"unrouted",xloc:Ko(t.xloc),x1:n,y1:r,x2:i,y2:s,extend:Yg(t.extend),color:c,invisible:u,width:Math.max(1,Ve(t.width)??1),style:Mh(t.style),arrowLeft:o,arrowRight:l,overlay:t.force_overlay===!0}}function Zg(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let s=Ih(i,n.next(e,"line",String(i.id??r.length)));s&&r.push(s)}return r}function Jg(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let s=i.line1,a=i.line2;if(!s||!a)continue;let o=n.next(e,"linefill",String(i.id??r.length)),l=Ih(s,`${o}:a`),c=Ih(a,`${o}:b`);!l||!c||r.push({id:o,paneId:"unrouted",line1:l,line2:c,color:Se(i.color),overlay:i.force_overlay===!0})}return r}function Qg(t){return t<=0?"auto":t<=9?"tiny":t<=12?"small":t<=17?"normal":t<=28?"large":"huge"}function yL(t){if(typeof t=="number"&&Number.isFinite(t))return Qg(t);let e=(J(t)??"").toLowerCase();return e==="tiny"||e==="small"||e==="normal"||e==="large"||e==="huge"?e:"auto"}function Ph(t){let e=(J(t)??"").toLowerCase();return e==="left"||e==="right"?e:"center"}function e0(t){let e=(J(t)??"").toLowerCase();return e==="top"||e==="bottom"?e:"center"}function Dh(t){return(J(t)??"").toLowerCase().includes("mono")?"monospace":"default"}function t0(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let s=Ve(i.left),a=Ve(i.top),o=Ve(i.right),l=Ve(i.bottom);if(s===void 0||a===void 0||o===void 0||l===void 0)continue;let c=(J(i.text_formatting)??"").toLowerCase(),u=J(i.text);r.push({id:n.next(e,"box",String(i.id??r.length)),paneId:"unrouted",xloc:Ko(i.xloc),left:s,top:a,right:o,bottom:l,extend:Yg(i.extend),bgColor:Se(i.bgcolor),borderColor:Se(i.border_color),borderWidth:Math.max(0,Ve(i.border_width)??1),borderStyle:Mh(i.border_style),text:u&&u.length>0?u:void 0,textColor:Se(i.text_color),textSize:yL(i.text_size),hAlign:Ph(i.text_halign),vAlign:e0(i.text_valign),wrap:(J(i.text_wrap)??"").toLowerCase().includes("auto"),fontFamily:Dh(i.text_font_family),bold:c.includes("bold"),italic:c.includes("italic"),overlay:i.force_overlay===!0})}return r}var gL=["label_up","label_down","label_left","label_right","label_center","label_lower_left","label_lower_right","label_upper_left","label_upper_right","circle","square","diamond","flag","arrowup","arrowdown","triangleup","triangledown","cross","xcross","text_outline","none"];function _L(t){let e=(J(t)??"").toLowerCase().replace(/^style_/,"");return gL.includes(e)?e:"label_down"}function bL(t){let e=(J(t)??"").toLowerCase();return e==="ab"||e.includes("above")?"abovebar":e==="bl"||e.includes("below")?"belowbar":"price"}function n0(t){if(typeof t=="number"&&Number.isFinite(t))return Qg(t);let e=(J(t)??"").toLowerCase();return e==="auto"||e==="tiny"||e==="small"||e==="large"||e==="huge"?e:"normal"}function r0(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let s=Ve(i.x),a=bL(i.yloc),o=Ve(i.y);if(s===void 0||a==="price"&&o===void 0)continue;let l=J(i.text),c=J(i.tooltip),{color:u,invisible:h}=Xg(i.color);r.push({id:n.next(e,"label",String(i.id??r.length)),paneId:"unrouted",xloc:Ko(i.xloc),x:s,y:o??0,yloc:a,text:l&&l.length>0?l:void 0,style:_L(i.style),color:u,noFill:h,textColor:Se(i.textcolor),size:n0(i.size),textAlign:Ph(i.textalign),tooltip:c&&c.length>0?c:void 0,fontFamily:Dh(i.text_font_family),overlay:i.force_overlay===!0})}return r}function i0(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let s=Array.isArray(i.points)?i.points:[],a=Ko(i.xloc),o=[];for(let c of s){let u=Ve(c.price),h=Ve(c.index),p=Ve(c.time),d=a==="bar_time"?p:h,f=a==="bar_time"?h:p,m,y;if(d!==void 0)m=d,y=a;else if(f!==void 0)m=f,y=a==="bar_time"?"bar_index":"bar_time";else continue;u!==void 0&&o.push({xloc:y,x:m,price:u})}if(o.length<2)continue;let l=(J(i.line_style)??"").toLowerCase();r.push({id:n.next(e,"polyline",String(i.id??r.length)),paneId:"unrouted",points:o,curved:i.curved===!0,closed:i.closed===!0,lineColor:Se(i.line_color),fillColor:Se(i.fill_color),lineWidth:Math.max(1,Ve(i.line_width)??1),lineStyle:Mh(i.line_style),arrowLeft:l==="style_arrow_left"||l==="style_arrow_both",arrowRight:l==="style_arrow_right"||l==="style_arrow_both",overlay:i.force_overlay===!0})}return r}var xL=["top_left","top_center","top_right","middle_left","middle_center","middle_right","bottom_left","bottom_center","bottom_right"];function vL(t){let e=(J(t)??"").toLowerCase();return xL.includes(e)?e:"top_right"}function wL(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:n0(t)}function Kg(t){let e=Ve(t);return e!==void 0&&e>0?e:void 0}function SL(t){if(!t||typeof t!="object")return null;let e=t,n=J(e.text),r=J(e.tooltip),i=(J(e.text_formatting)??"").toLowerCase();return{text:n&&n.length>0?n:void 0,textColor:Se(e.text_color),bgColor:Se(e.bgcolor),hAlign:Ph(e.text_halign),vAlign:e0(e.text_valign),textSize:wL(e.text_size),fontFamily:Dh(e.text_font_family),tooltip:r&&r.length>0?r:void 0,bold:i.includes("bold"),italic:i.includes("italic"),width:Kg(e.width),height:Kg(e.height),merged:e._merged===!0}}function EL(t){if(!Array.isArray(t))return[];let e=[],n=new Set;for(let r of t){if(!r||typeof r!="object")continue;let i=r,s=Ve(i.startCol??i.start_column??i.startColumn),a=Ve(i.startRow??i.start_row),o=Ve(i.endCol??i.end_column??i.endColumn),l=Ve(i.endRow??i.end_row);if(s===void 0||a===void 0||o===void 0||l===void 0)continue;let c={startCol:Math.min(Math.round(s),Math.round(o)),startRow:Math.min(Math.round(a),Math.round(l)),endCol:Math.max(Math.round(s),Math.round(o)),endRow:Math.max(Math.round(a),Math.round(l))},u=`${c.startCol}:${c.startRow}:${c.endCol}:${c.endRow}`;n.has(u)||(n.add(u),e.push(c))}return e}function s0(t,e,n){let r=[];for(let i of Ki(t)){if(i._deleted===!0)continue;let a=(Array.isArray(i.cells)?i.cells:[]).map(l=>(Array.isArray(l)?l:[]).map(c=>SL(c))),o=EL(i.merges);for(let l of o){let c=a[l.startRow]?.[l.startCol];c?.merged&&(c.merged=!1)}r.push({id:n.next(e,"table",String(i.id??r.length)),paneId:"unrouted",position:vL(i.position),columns:Math.max(0,Math.round(Ve(i.columns)??0)),rows:Math.max(0,Math.round(Ve(i.rows)??0)),bgColor:Se(i.bgcolor),frameColor:Se(i.frame_color),frameWidth:Math.max(0,Ve(i.frame_width)??0),borderColor:Se(i.border_color),borderWidth:Math.max(0,Ve(i.border_width)??0),cells:a,merges:o,overlay:i.force_overlay===!0})}return r}var o0=ur;function l0(t,e){let n=new Go,r=[],i=[],s=[],a=[],o=[],l=[],c=[],u=[],h=[],p=[],d=[],f=[],m=new Map,y=new Set,g=[];for(let S of t.plots){let E=_y(S.style),T=S.title??S.key;switch(E){case"skip":break;case"barcolor":{if(!qs(S.options.display))break;let N=Us(S.data.length,Ce(S.options.show_last));for(let $=N;$<S.data.length;$+=1){let z=S.data[$],H=Se(z.options?.color);H&&f.push({time:z.time,color:H})}break}case"fill":qs(S.options.display)&&g.push(S);break;case"hline":{let N=LL(S,T,e,n);N&&o.push(N);break}case"background":qs(S.options.display)&&a.push(...FL(S,T,e,n));break;case"drawing_line":l.push(...Zg(S,e,n));break;case"drawing_box":c.push(...t0(S,e,n));break;case"label":u.push(...r0(S,e,n));break;case"drawing_polyline":h.push(...i0(S,e,n));break;case"linefill":p.push(...Jg(S,e,n));break;case"table":d.push(...s0(S,e,n));break;case"markers":qs(S.options.display)&&u.push(...BL(S,e,n));break;default:{let N=n.next(e,E,T);m.set(S.key,N),S.options.force_overlay===!0&&y.add(S.key),i.push(AL(E,S,N,T));let $=IL(S,T,e,n);$&&o.push($)}}}for(let S of g){let E=S.plot1?m.get(S.plot1):void 0,T=S.plot2?m.get(S.plot2):void 0;if(!E||!T){r.push(`fill "${S.key}" references unknown plots (${S.plot1??"?"}/${S.plot2??"?"})`);continue}let N=y.has(S.plot1)&&y.has(S.plot2);s.push({id:n.next(e,"fill",S.title??S.key),paneId:"unrouted",fromSeriesId:E,toSeriesId:T,...RL(S),...N?{overlay:!0}:{}})}let w=t.trades?kL(t.trades):[];return{model:{id:e,title:t.meta.title,...t.meta.shorttitle?.trim()?{shorttitle:t.meta.shorttitle}:{},overlay:t.meta.overlay,paneHint:t.meta.overlay?"price":"new",series:i,fills:s,backgrounds:a,priceLines:o,lines:l,boxes:c,labels:u,polylines:h,linefills:p,tables:d,barColors:f.length?f:void 0,trades:w.length?w:void 0,inputs:[],inputValues:{}},warnings:r}}function kL(t){let e=new Map,n=r=>{let i=`${r.time}|${r.side}|${r.label??""}`,s=e.get(i);if(!s){e.set(i,r);return}s.qty=(s.qty??0)+(r.qty??0),r.kind==="entry"&&s.kind==="exit"&&(s.kind="entry",s.price=r.price,s.tradeId=r.tradeId)};for(let r of t){let i=r.size>0,s=Math.abs(r.size);n({time:r.entry_time,price:r.entry_price,side:i?"buy":"sell",kind:"entry",label:r.entry_comment??r.entry_id,qty:s,tradeId:r.id}),r.status==="closed"&&r.exit_time!=null&&r.exit_price!=null&&n({time:r.exit_time,price:r.exit_price,side:i?"sell":"buy",kind:"exit",label:r.exit_comment??r.exit_id,qty:s,tradeId:r.id})}return[...e.values()].sort((r,i)=>r.time-i.time)}function AL(t,e,n,r){let i=Ce(e.options.show_last),s=e.options.force_overlay===!0?{overlay:!0}:{},a=c0(e.options.display);if(t==="candle"||t==="bar"){let m={id:n,title:r,paneId:"unrouted",kind:t,bars:OL(e,Us(e.data.length,i)),visible:a.pane,display:a,...s},y=ML(e);return y&&(m.barColors=y),m}let o=t,l=Se(p0(e)),c={...a,pane:a.pane&&!!l},u=Ce(e.options.linewidth)??1,h=o==="line"||o==="step"||o==="area",p=DL(CL(PL(e),i,h),Ce(e.options.offset)),d={color:l??o0,width:u,lineStyle:d0(e.options.linestyle)??"solid"},f=Ce(e.options.histbase);return f!==void 0&&(o==="histogram"||o==="columns"||o==="area")&&(d.base=f),{id:n,title:r,paneId:"unrouted",kind:o,points:p,style:d,visible:c.pane,display:c,...s}}var a0={pane:!0,priceScale:!0,legend:!0,dataWindow:!0},TL={pane:"pane",data_window:"dataWindow",status_line:"legend",price_scale:"priceScale"},NL=["all","none","pane","data_window","status_line","price_scale"];function c0(t){if(typeof t!="string")return{...a0};let e={pane:!1,priceScale:!1,legend:!1,dataWindow:!1};for(let n=0;n<t.length;){let r=NL.find(i=>t.startsWith(i,n));if(!r||r==="all")return{...a0};r!=="none"&&(e[TL[r]]=!0),n+=r.length}return e}function qs(t){return c0(t).pane}function Us(t,e){return e===void 0||e<=0?0:Math.max(0,t-Math.floor(e))}function CL(t,e,n){let r=Us(t.length,e);return n&&(r-=1),r<=0?t:t.map((i,s)=>s<r?{...i,value:null}:i)}function IL(t,e,n,r){if(t.options.trackprice!==!0)return null;for(let i=t.data.length-1;i>=0;i-=1){let s=t.data[i];if(!(typeof s.value!="number"||!Number.isFinite(s.value)))return{id:r.next(n,"hline",e),paneId:"unrouted",price:s.value,color:Se(s.options?.color)??Se(p0(t)),lineStyle:"dotted",width:Ce(t.options.linewidth),title:e}}return null}function ML(t){let e=!1,n=t.data.map(r=>{let i=r.options??{},s=Se(i.color),a=Se(i.wickcolor),o=Se(i.bordercolor);return!s&&!a&&!o?null:(e=!0,{color:s,wickColor:a,borderColor:o})});return e?n:void 0}function PL(t){let e=t.data.some(n=>No(n.options?.color));return t.data.map(n=>{let r=typeof n.value=="number"&&Number.isFinite(n.value)?n.value:null,i=Se(n.options?.color);return i?{time:n.time,value:r,color:i}:e?{time:n.time,value:r,color:by}:{time:n.time,value:r}})}function u0(t){let e=[];for(let n=1;n<t.length;n+=1){let r=t[n].time-t[n-1].time;r>0&&e.push(r)}return e.length===0?0:(e.sort((n,r)=>n-r),e[e.length>>1]??0)}function h0(t,e,n){if(e<0)return t[0].time+e*n;let r=t.length-1;return e<=r?t[e].time:t[r].time+(e-r)*n}function DL(t,e){let n=Math.trunc(e??0);if(!n||t.length===0)return t;let r=u0(t),i=t.length+Math.max(0,n),s=new Array(i);for(let a=0;a<i;a+=1){let o=h0(t,a,r),l=t[a-n];s[a]=l?{...l,time:o}:{time:o,value:null}}return s}function OL(t,e=0){let n=e>0?new Array(t.data.length):[];for(let r=e;r<t.data.length;r+=1){let i=t.data[r],s=i.value;if(!Array.isArray(s)||s.length<4)continue;let a={time:i.time,open:s[0]??0,high:s[1]??0,low:s[2]??0,close:s[3]??0};e>0?n[r]=a:n.push(a)}return n}function p0(t){for(let e of t.data)if(typeof e.options?.color=="string"&&e.options.color)return e.options.color;return J(t.options.color)}function RL(t){if(t.options.gradient===!0||t.data.some(s=>s.options&&(typeof s.options.top_color=="string"||typeof s.options.bottom_color=="string")))return{gradient:t.data.map(a=>{let o=a.options??{},l=Ce(o.top_value),c=Ce(o.bottom_value),u=typeof o.top_color=="string"?o.top_color:void 0,h=typeof o.bottom_color=="string"?o.bottom_color:void 0;return l===void 0||c===void 0||!u&&!h?null:{topValue:l,bottomValue:c,topColor:u??"rgba(0,0,0,0)",bottomColor:h??"rgba(0,0,0,0)"}})};let n=t.data.map(s=>Se(s.options?.color)??null),r=new Set(n.filter(s=>s!==null)),i=n.some(s=>s===null);return r.size===0?{color:Se(t.options.color)}:r.size===1&&!i?{color:[...r][0]}:{colors:n}}function LL(t,e,n,r){if(!qs(t.options.display))return null;let i;for(let s of t.data)if(typeof s.value=="number"&&Number.isFinite(s.value)){i=s.value;break}return i===void 0?null:{id:r.next(n,"hline",e),paneId:"unrouted",price:i,color:Se(t.options.color),lineStyle:d0(t.options.linestyle)??"dashed",title:e,width:Ce(t.options.linewidth)}}function d0(t){let e=J(t)?.replace(/^(hline\\.style_|plot\\.linestyle_|linestyle_|style_)/,"");return e==="solid"||e==="dashed"||e==="dotted"?e:void 0}function FL(t,e,n,r){let i=[],s=t.options.force_overlay===!0?{overlay:!0}:{},a=t.data,o=a.length>1?(a[1]?.time??0)-(a[0]?.time??0):0,l=Us(a.length,Ce(t.options.show_last));for(;l<a.length;){let c=a[l],u=Se(c.options?.color);if(c.value===!0&&u){let h=c.time,p=c.time,d=l;for(;d+1<a.length;){let f=a[d+1];if(f.value===!0&&Se(f.options?.color)===u)p=f.time,d+=1;else break}i.push({id:r.next(n,"background",e),paneId:"unrouted",from:h,to:p+o,color:u,...s}),l=d+1}else l+=1}return i}function BL(t,e,n){let r=Math.trunc(Ce(t.options.offset)??0),i=r?u0(t.data):0,s=t.style==="char"||t.options.char!==void 0,a=!s&&!("shape"in t.options)&&t.data.some(h=>h.options!==void 0&&"height"in h.options),o=a?VL(t):null,l=t.options.force_overlay===!0?{overlay:!0}:{},c=[],u=Us(t.data.length,Ce(t.options.show_last));for(let h=u;h<t.data.length;h+=1){let p=t.data[h],d=p.value,f=typeof d=="number"&&Number.isFinite(d);if(d!==!0&&!f||a&&(!f||d===0))continue;let m=p.options??t.options,y=m.color!==void 0?m.color:t.options.color;if(y!==void 0&&!No(y))continue;let g=J(m.text)??J(t.options.text),w=g&&g.trim().length>0?g:void 0,k=a?f&&d>0?dt:Wt:void 0,S=Se(m.color)??Se(t.options.color)??k??o0,E=s?J(m.char)??J(t.options.char)??"\\u2605":void 0;c.push({id:n.next(e,"label",`${t.key}#${c.length}`),paneId:"unrouted",xloc:"bar_time",x:r?h0(t.data,h+r,i):p.time,y:f?d:0,yloc:zL(J(m.location)??J(t.options.location)),text:E!==void 0?w!==void 0?`${E}\n${w}`:E:w,style:E!==void 0?"none":jL(J(m.shape)??J(t.options.shape)),color:S,textColor:Se(m.textcolor)??Se(t.options.textcolor)??(E!==void 0?S:void 0),size:o!==null&&f?$L(Math.abs(d),o):qL(J(m.size)??J(t.options.size)),textAlign:"center",fontFamily:"default",...l})}return c}function VL(t){let e=0;for(let n of t.data)typeof n.value=="number"&&Number.isFinite(n.value)&&(e=Math.max(e,Math.abs(n.value)));return{maxAbs:e,minH:Ce(t.options.minheight)??5,maxH:Ce(t.options.maxheight)??100}}function $L(t,e){let n=e.maxAbs>0?t/e.maxAbs:1,r=e.minH+n*(e.maxH-e.minH);return r<=12?"tiny":r<=24?"small":r<=44?"normal":r<=72?"large":"huge"}function zL(t){let e=(t??"").toLowerCase();return e==="absolute"?"price":e==="top"?"top":e==="bottom"?"bottom":e.includes("below")?"belowbar":"abovebar"}function jL(t){switch((t??"").toLowerCase().replace(/^shape_/,"").replace(/_/g,"")){case"diamond":return"diamond";case"triangleup":return"triangleup";case"triangledown":return"triangledown";case"labelup":return"label_up";case"labeldown":return"label_down";case"arrowup":return"arrowup";case"arrowdown":return"arrowdown";case"square":return"square";case"cross":return"cross";case"xcross":return"xcross";case"flag":return"flag";default:return"circle"}}function qL(t){let e=(t??"").toLowerCase();return e==="tiny"||e==="small"||e==="large"||e==="huge"||e==="normal"?e:"small"}function UL(t){switch(t){case"int":return"int";case"float":return"float";case"bool":return"bool";case"source":return"source";case"color":return"color";case"price":return"price";case"time":return"time";case"session":return"session";case"timeframe":return"timeframe";case"symbol":return"symbol";case"text_area":return"text_area";default:return"string"}}function WL(t){return t==="int"||t==="float"||t==="price"||t==="time"}var f0={aqua:"#00BCD4",black:"#363A45",blue:"#2196F3",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#F23645",silver:"#B2B5BE",teal:"#089981",white:"#FFFFFF",yellow:"#FDD835"};function HL(t){let e=t.trim().toLowerCase().replace(/^color\\./,"");return f0[e]??t}function GL(t){if(typeof t!="string")return;let e=/^color\\.([a-z]+)$/i.exec(t.trim());return e?f0[e[1].toLowerCase()]:void 0}function KL(t){return(t.type==="string"||t.type==null)&&GL(t.defval)!==void 0}function YL(t,e){if(e==="bool")return!!t;if(WL(e))return typeof t=="number"?t:Number(t)||0;let n=typeof t=="string"?t:t==null?"":String(t);return e==="color"?HL(n):n}function m0(t){return t.map((e,n)=>{let r=KL(e)?"color":UL(e.type);return{key:e.varId??e.title??`input${n}`,title:e.title??e.varId??`Input ${n+1}`,type:r,defval:YL(e.defval,r),min:e.minval,max:e.maxval,step:e.step,options:Array.isArray(e.options)?e.options.map(i=>String(i)):void 0,group:e.group,inline:e.inline,tooltip:e.tooltip}})}function XL(t){switch(t){case"int":return"int";case"float":return"float";case"bool":return"bool";default:return"string"}}function Oh(t,e){return e==="bool"?!!t:e==="int"||e==="float"?typeof t=="number"?t:Number(t)||0:typeof t=="string"?t:t==null?"":String(t)}function ZL(t){let e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}function y0(t,e){let n=t.getPropsMeta(),r=t.prop;return n.filter(i=>i.mutable&&i.name).map(i=>{let s=i.name,a=XL(i.type),o=Oh(i.defval,a),l=Oh(r[s]??i.defval,a),c=e?.[s],u=l!==o?l:c!==void 0?Oh(c,a):o;return{key:s,title:ZL(s),type:a,defval:u,min:i.minval,max:i.maxval,options:Array.isArray(i.options)?i.options.map(h=>String(h)):void 0}})}function g0(t,e){for(let[n,r]of Object.entries(e))try{t.prop[n]=r}catch(i){console.warn(`[vela-pinets] prop "${n}" rejected:`,i instanceof Error?i.message:i)}}var _0=!1;function Rh(){if(_0)return;_0=!0;let t=Di.prototype,e=t.bindContextObject;typeof e=="function"&&(t.bindContextObject=function(n,r,i){if(e.call(this,n,r,i),i!=="table")return;let s=this.pine.table,a=n;if(!s||typeof s.cell_set_text_formatting=="function"||typeof a._setCellProp!="function")return;let o=(c,u,h,p)=>a._setCellProp(c,u,h,"text_formatting",p);s.cell_set_text_formatting=(c,u,h,p)=>o(c,u,h,p);let l=s.cell;typeof l=="function"&&(s.cell=(...c)=>{let u=c[c.length-1],h=u&&typeof u=="object"&&!Array.isArray(u)&&"text_formatting"in u?u:null;if(!h&&c.length<14)return l(...c);let p=h?c.slice(0,-1):c.slice(0,13),d,f;if(h){let{text_formatting:k,...S}=h;d=k,f=Object.keys(S).length>0?[...p,S]:p}else d=c[13],f=p;let m=l(...f),y=h??{},g=p.length>1?p[1]:y.column??0,w=p.length>2?p[2]:y.row??0;return o(p[0],g,w,d),m})})}var b0=["plotshape","plotchar","plotarrow"],x0=!1;function Lh(){if(x0)return;x0=!0;let t=Di.prototype,e=t.bindContextObject;typeof e=="function"&&(t.bindContextObject=function(n,r,i){if(e.call(this,n,r,i),i!==void 0||!b0.some(a=>r.includes(a)))return;let s={idx:void 0,n:0,len:0};for(let a of b0){let o=this.pine[a];if(typeof o!="function")continue;let l=o;this.pine[a]=(...c)=>{let u=c[c.length-1];if(!(u!==null&&typeof u=="object"&&"__callsiteId"in u)){let p=this.idx;s.len===0&&s.idx!==void 0&&p!==s.idx&&(s.len=s.n,s.n=0),s.idx=p;let d=s.len>0?s.n%s.len:s.n;s.n+=1,c.push({__callsiteId:`~m${d}`})}return l(...c)}}})}function Fh(t,e,n,r){return t?{getFootprintData:(i,s,a,o,l)=>{let c=v0(i??e()),u=s??n(),h=a!=null&&c===v0(e())&&u===n();return t(c,u,{from:o,to:l??(h?r?.():void 0),limit:a})}}:{}}function v0(t){return t.split(";")[0]??t}var JL=/^[ \\t]*import[ \\t]+[^\\s/]+\\/[^\\s/]+\\/\\d+/m;async function QL(t,e){if(!e||!JL.test(t))return;let r=await ah(t,typeof e=="function"?e:(i,s)=>e.resolve(i,s));return Object.keys(r).length>0?r:void 0}var w0=new WeakMap;function Vh(t){let e=w0.get(t);return e||(e=new Ns({libraries:t}),w0.set(t,e)),e}function e5(t,e,n){if(n==="none")return[];if(n==="strategy"&&t.getDeclarationType()!=="strategy")return[];let r=y0(t,e);if(typeof n=="string")return r;let i=new Map(r.map(s=>[s.key,s]));return n.map(s=>i.get(s)).filter(s=>s!==void 0)}function t5(t,e,n,r="all"){return N0(Dr.from(t),t,e,n,r,void 0)}async function T0(t,e,n,r="all",i){let s=await QL(t,i);if(!s)return t5(t,e,n,r);let a=Dr.from(t);return await a.resolveImports(Vh(s)),N0(a,t,e,n,r,s)}function N0(t,e,n,r,i,s){let a=m0(t.getInputsMeta()),o=e5(t,r,i),l=t.prop.overlay,c=typeof l=="boolean"?l:void 0,u=c??/(?<![\\w.$])overlay\\s*[:=]\\s*true/.test(e),h=/^\\s*(?:indicator|strategy)\\s*\\(\\s*(?:title\\s*=\\s*)?(["\'])((?:\\\\.|(?!\\1).)*)\\1/m.exec(e)?.[2],p=h===void 0?"Indicator":h.replace(/\\\\(.)/g,"$1").trim()||Ao,d=/chart\\.(left|right)_visible_bar(_time)?\\b/.test(e),f={source:e,instanceId:n,...c!==void 0?{declaredOverlay:c}:{},...s?{libraries:s}:{}};return{language:"pine",inputs:a,...o.length>0?{props:o}:{},meta:{title:p,overlay:u},reactsToViewport:d,token:f}}function $h(t,e,n,r={}){let i=JSON.stringify([n,r]);if(t.lastKey!==i||!t.lastInd){let s=new Dr(e,n);g0(s,r),t.lastInd=s,t.lastKey=i}return t.lastInd}async function C0(t){let{ind:e,bars:n,market:r,visibleRange:i,prepared:s,instanceId:a,inputs:o,props:l,fetchSeries:c,footprints:u}=t;Rh(),Lh();let h=Xo(n,r.timeframe,r.symbolInfo,Date.now()),p={getMarketData:(g,w,k,S,E)=>D0(g,w,r)?Promise.resolve(h):O0(c,g,w,k,S,E,Zo(r,g)),getSymbolInfo:async g=>Zo(r,g),...Fh(u,()=>r.symbol,()=>r.timeframe,()=>P0(h,r.timeframe))},d=new Or(p,zh(r),r.timeframe,h.length),f=s.token.libraries;f&&d.setImportResolver(Vh(f)),await d.ready(),i&&d.setVisibleRange(i.left,i.right);let m=await d.run(e),y=typeof d.usesVisibleRange=="function"?d.usesVisibleRange():!1;return{model:lh(m)?I0(m,a,s,o,l??{},n[0]?.time):null,alerts:(m.alerts??[]).map(L0),warnings:(m.warnings??[]).map(F0),reactsToViewport:y,ctx:m}}function I0(t,e,n,r,i,s){let{model:a}=l0(To(t),e),o=typeof i.overlay=="boolean"?i.overlay:n.token.declaredOverlay;return o!==void 0&&(a.overlay=o,a.paneHint=o?"price":"new"),a.inputs=n.inputs,a.inputValues={...A0(n.inputs),...r},n.props&&(a.props=n.props,a.propValues={...A0(n.props),...i}),s!=null&&(a.anchorTime=s),a}function S0(t){if(typeof t!="string")return null;let e=/^(\\d{2})(\\d{2})-(\\d{2})(\\d{2})$/.exec(t);return e?{start:Number(e[1])*60+Number(e[2]),end:Number(e[3])*60+Number(e[4])}:null}var Bh=(t,e)=>e.start<=e.end?t>=e.start&&t<e.end:t>=e.start||t<e.end,Yo=new Map;function E0(t,e){let n=`${e}:${Math.floor(t/36e5)}`,r=Yo.get(n);if(r==null){try{let i=new Intl.DateTimeFormat("en-US",{timeZone:e,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(t),s=a=>Number(i.find(o=>o.type===a)?.value??NaN);r=Math.round((Date.UTC(s("year"),s("month")-1,s("day"),s("hour")%24,s("minute"))-t)/6e4)}catch{r=NaN}Yo.size>1e5&&Yo.clear(),Yo.set(n,r)}return Number.isNaN(r)?null:((Math.floor(t/6e4)+r)%1440+1440)%1440}function M0(t){return t==null?null:/^\\d+$/.test(t)?Number(t):/^1?D$/i.test(t)?1440:null}function n5(t,e,n){let r=typeof n=="object"&&n!=null?n:null,i=M0(e),s=S0(r?.session),a=typeof r?.timezone=="string"?r.timezone:null;if(i==null||s==null||a==null||t.length===0)return null;let o=S0(r?.session_extended),l=s;if(o)for(let c of t){let u=E0(c.time,a);if(u!=null&&!Bh(u,s)&&Bh(u,o)){l=o;break}}return c=>{let u=E0(c,a);if(u==null||!Bh(u,l))return null;let h=(l.end-u+1440)%1440||1440;return c+Math.min(i,h)*6e4}}function r5(t){if(t==null)return!1;let e=/^(\\d*)\\s*[tT]$/.exec(t.trim());return e?e[1]===""||parseInt(e[1],10)>=1:!1}function Xo(t,e,n,r){let i=r5(e),s=i?null:n5(t,e,n);return t.map((a,o)=>{let l={openTime:a.time,open:a.open,high:a.high,low:a.low,close:a.close,volume:a.volume??0},c;if(i){let u=t[o+1];u&&(c=r!=null?Math.min(u.time,r):u.time)}else c=s?.(a.time);return c!=null&&(l.closeTime=c),l})}function zh(t){return t.chartStyle==="heikinashi"?`${t.symbol};heikinashi`:t.symbol}function P0(t,e){let n=t[t.length-1];if(!n)return;if(n.closeTime!=null)return n.closeTime;let r=M0(e);return r==null||n.openTime==null?void 0:n.openTime+r*6e4}function D0(t,e,n){return(t==null||t===zh(n))&&(e==null||e===n.timeframe)}async function O0(t,e,n,r,i,s,a){if(!t||!e||!n)return[];let o=await t(e,n,{from:i,to:s,limit:r});return Xo(o,n,a,Date.now())}function i5(t,e,n,r){let i="",s=!1;return{...Fh(r,()=>e().symbol,()=>e().timeframe,()=>{let a=e();return P0(Xo(t(),a.timeframe,a.symbolInfo),a.timeframe)}),markDirty:()=>{s=!0},getMarketData:async(a,o,l,c,u)=>{let h=e();if(!D0(a,o,h))return O0(n,a,o,l,c,u,Zo(h,a));let p=Xo(t(),h.timeframe,h.symbolInfo,Date.now());if(c==null)return p;let d=p.filter(y=>(y.openTime??0)>=c),f=d[d.length-1],m=f?`${d.length}|${f.openTime}|${f.close}|${f.high}|${f.low}|${f.volume}`:"";return!s&&m===i?[]:(s=!1,i=m,d)},getSymbolInfo:async a=>Zo(e(),a)}}function R0(t){let e=t.bars();Rh(),Lh();let n=$h(t.cache,t.token.source,t.inputs,t.props??{}),r=e[0]?.time,i=Math.max(1,e.length),s=i5(t.bars,t.market,t.fetchSeries,t.footprints),a=new Or(s,zh(t.market()),t.market().timeframe,i);t.token.libraries&&a.setImportResolver(Vh(t.token.libraries)),t.visibleRange&&a.setVisibleRange(t.visibleRange.left,t.visibleRange.right);let o=a.stream(n,{live:!0,interval:1e3,pageSize:i}),l=!1,c=null;return o.on("data",u=>{if(!l&&(c=u,!!lh(u)))try{t.onModel(I0(u,t.token.instanceId,t.prepared,t.inputs,t.props??{},r))}catch(h){t.onError?.(h instanceof Error?h:new Error(String(h)))}}),o.on("alert",u=>t.onAlert?.(L0(u))),o.on("warning",u=>t.onWarning?.(F0(u))),o.on("error",u=>t.onError?.(u instanceof Error?u:new Error(String(u)))),{stop:()=>{l=!0,o.stop()},setVisibleRange:(u,h)=>{a.setVisibleRange(u,h),s.markDirty()},markDirty:()=>s.markDirty(),lastCtx:()=>c}}function Zo(t,e){let n=e&&e.split(";")[0];return n&&n!==t.symbol?k0({symbol:n,timeframe:t.timeframe}):k0(t)}function k0(t){if(t.symbolInfo)return s5(t.symbolInfo);let e=t.symbol,n=e.replace(/(USDT|USDC|USD|PERP|BUSD)$/i,"")||e;return{ticker:e,tickerid:e,main_tickerid:e,description:e,prefix:"",root:e,type:"crypto",basecurrency:n,currency:"USD",timezone:"UTC",session:"regular",mintick:.01,minmove:1,pointvalue:1,pricescale:100}}function s5(t){let e=typeof t.volumetype=="string"&&t.volumetype!=="";return t.volume===!1&&!e?{...t,volumetype:"n/a"}:t}function A0(t){let e={};for(let n of t)e[n.key]=n.defval;return e}function L0(t){return{id:String(t.id??""),message:String(t.message??""),title:t.title,time:Number(t.time??0),barIndex:Number(t.bar_index??0),freq:t.freq}}function F0(t){return{message:String(t.message??""),method:t.method,bar:Number(t.bar??0)}}var Qt=t=>Ce(t)??0,Yn=(t,e)=>{let n=Ce(e);return n===void 0?{}:{[t]:n}};function B0(t){if(t==null||typeof t!="object")return;let e=t;return{position:Qt(e.position_size),avgPrice:Qt(e.position_avg_price),equity:Qt(e.equity),openPnl:Qt(e.openprofit),netPnl:Qt(e.netprofit),grossProfit:Qt(e.grossprofit),grossLoss:Qt(e.grossloss),wins:Qt(e.wintrades),losses:Qt(e.losstrades),even:Qt(e.eventrades),maxDrawdown:Qt(e.max_drawdown),maxRunup:Qt(e.max_runup),initialCapital:Qt(e.initial_capital),...Yn("cagr",e.cagr),...Yn("sharpe",e.sharpe_ratio),...Yn("sortino",e.sortino_ratio),...Yn("buyHoldPnl",e.buy_and_hold_pnl),...Yn("buyHoldPct",e.buy_and_hold_per_gain),...Yn("outperformance",e.strategy_outperformance)}}function V0(t){if(t==null||typeof t!="object")return[];let e=t,n=[];for(let r of[...Array.isArray(e.closedtrades)?e.closedtrades:[],...Array.isArray(e.opentrades)?e.opentrades:[]]){let i=r??{},s=Ce(i.entry_price),a=Ce(i.entry_time),o=Ce(i.size);if(s===void 0||a===void 0||o===void 0||o===0)continue;let l=Ce(i.exit_price),c=Ce(i.exit_time);n.push({id:J(i.id)??`trade_${n.length}`,side:o>0?"long":"short",qty:Math.abs(o),entry:{id:J(i.entry_id)??"",time:a,price:s,...J(i.entry_comment)!==void 0?{comment:J(i.entry_comment)}:{}},...l!==void 0&&c!==void 0?{exit:{id:J(i.exit_id)??"",time:c,price:l,...J(i.exit_comment)!==void 0?{comment:J(i.exit_comment)}:{}}}:{},open:i.status!=="closed",...Yn("pnl",i.profit),...Yn("commission",i.commission),...Yn("maxDrawdown",i.max_drawdown),...Yn("maxRunup",i.max_runup)})}return n}function $0(t){try{return structuredClone(t)}catch{return}}function a5(t){let e=Array.isArray(t)?t:t!=null&&typeof t=="object"&&Array.isArray(t.data)?t.data:null;return $0(e?e[e.length-1]:t)}function o5(t){return t.replace(/^glb\\d+_/,"")}function jh(t,e){if(t)for(let[n,r]of Object.entries(t)){if(n.startsWith("_"))continue;let i=a5(r);i!==void 0&&(e[o5(n)]=i)}}function z0(t,e,n){let r=t??{},i=r.fullContext??r,s=p=>!n||n.includes(p),a=s("meta")||s("plots")?To(t):null,o={};if(a&&s("plots"))for(let p of a.plots)p.key.startsWith("__")||(o[p.key]=p.data.map(d=>({time:d.time,value:$0(d.value)??null})));let l={};s("variables")&&(jh(i.const,l),jh(i.var,l),jh(i.let,l));let c=s("strategy")?B0(i.strategy):void 0,u=s("trades")&&i.strategy?V0(i.strategy):void 0,h=typeof i.idx=="number"?i.idx:typeof i.length=="number"?i.length-1:-1;return{language:"pine",phase:e,barIndex:h,meta:a&&s("meta")?{title:a.meta.title,overlay:a.meta.overlay,precision:a.meta.precision,shorttitle:a.meta.shorttitle}:{title:"",overlay:!1},plots:o,variables:l,...c?{strategy:c}:{},...u&&u.length>0?{trades:u}:{},warnings:s("warnings")?(i.warnings??[]).map(p=>({message:String(p.message??""),method:typeof p.method=="string"?p.method:void 0,bar:Number(p.bar??0)})):[]}}var j0="DataUnavailableError",q0=["symbol","timeframe","finest","default"];function qh(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.name===j0&&typeof e.reason=="string"&&typeof e.message=="string"&&q0.every(n=>e[n]===void 0||typeof e[n]=="string")}function Uh(t){let e={reason:t.reason};for(let n of q0)t[n]!==void 0&&(e[n]=t[n]);return e}function U0(t,e){return Object.assign(new Error(t),{name:j0},Uh(e))}function W0(t){if(!t)return;let e=new Map;return async(n,r,i)=>{let s=`${n}\\0${r}`,a=e.get(s);if(a)throw a;try{return await t(n,r,i)}catch(o){throw qh(o)&&e.set(s,o),o}}}var H0=self,st=t=>H0.postMessage(t);function G0(t,e){let n=e instanceof Error?e.message:String(e);return{kind:"error",sessionId:t,message:n,...qh(e)?{refusal:Uh(e)}:{}}}var Vr=new Map,Hh=new Map,Gh=new Map,Kh=new Map,Yh=0,l5=(t,e,n)=>new Promise((r,i)=>{let s=++Yh;Hh.set(s,{resolve:r,reject:i}),st({kind:"fetchSeries",reqId:s,symbol:t,timeframe:e,range:n})}),c5=t=>(e,n,r)=>new Promise((i,s)=>{let a=++Yh;Gh.set(a,{resolve:i,reject:s}),st({kind:"fetchFootprints",reqId:a,sessionId:t,symbol:e,timeframe:n,range:r})}),u5=(t,e)=>new Promise((n,r)=>{let i=++Yh;Kh.set(i,{resolve:n,reject:r});let{user:s,name:a,version:o,importer:l}=e;st({kind:"resolveImport",reqId:i,path:t,info:{path:t,user:s,name:a,version:o,...l?{importer:l}:{}}})});function Jo(t){t.chain=t.chain.then(()=>p5(t))}function h5(t,e){let n=t.bars[t.bars.length-1];n&&e.time===n.time?t.bars[t.bars.length-1]=e:(!n||e.time>n.time)&&t.bars.push(e)}function Wh(t){t.stream?.stop(),t.stream=null,!(t.stopped||t.bars.length===0)&&(t.stream=R0({token:t.prepared.token,cache:t.cache,prepared:t.prepared,inputs:t.inputs,props:t.props,bars:()=>t.bars,market:()=>t.market,fetchSeries:t.fetchSeries,footprints:t.footprints,visibleRange:t.visibleRange,onModel:e=>{t.stopped||st({kind:"model",sessionId:t.id,model:e})},onAlert:e=>st({kind:"alert",sessionId:t.id,alert:e}),onWarning:e=>st({kind:"warning",sessionId:t.id,warning:e}),onError:e=>st(G0(t.id,e))}))}async function p5(t){if(!t.stopped)try{let e=t.prepared.token,n=await C0({ind:$h(t.cache,e.source,t.inputs,t.props),bars:t.bars,market:t.market,visibleRange:t.visibleRange,prepared:t.prepared,instanceId:e.instanceId,inputs:t.inputs,props:t.props,fetchSeries:t.fetchSeries,footprints:t.footprints});if(t.stopped)return;st({kind:"reactsToViewport",sessionId:t.id,value:n.reactsToViewport});for(let r of n.alerts)st({kind:"alert",sessionId:t.id,alert:r});for(let r of n.warnings)st({kind:"warning",sessionId:t.id,warning:r});t.lastCtx=n.ctx,n.model&&st({kind:"model",sessionId:t.id,model:n.model}),st({kind:"done",sessionId:t.id})}catch(e){st(G0(t.id,e))}}H0.addEventListener("message",t=>{let e=t.data;switch(e.kind){case"prepare":T0(e.source,e.instanceId,e.defaultProps,e.propsVisibility,e.importResolver?u5:void 0).then(n=>st({kind:"prepared",reqId:e.reqId,prepared:n}),n=>st({kind:"prepared",reqId:e.reqId,error:n instanceof Error?n.message:String(n)}));return;case"execute":{let n={id:e.sessionId,mode:e.mode??"static",prepared:e.prepared,market:e.market,bars:e.bars,inputs:e.inputs,props:e.props??{},visibleRange:e.visibleRange,cache:{},stopped:!1,deferred:e.historyState==="backfill",chain:Promise.resolve(),stream:null,lastCtx:null,footprints:e.footprints?c5(e.sessionId):void 0,fetchSeries:W0(l5)};if(Vr.set(n.id,n),n.mode==="live"){n.deferred||Wh(n);return}n.deferred?st({kind:"done",sessionId:n.id}):Jo(n);return}case"update":{let n=Vr.get(e.sessionId);if(!n)return;if(n.inputs={...n.inputs,...e.inputs},e.props&&(n.props={...n.props,...e.props}),n.mode==="live"){n.deferred||Wh(n);return}n.deferred?st({kind:"done",sessionId:n.id}):Jo(n);return}case"setVisibleRange":{let n=Vr.get(e.sessionId);if(!n)return;if(n.visibleRange=e.range,n.mode==="live"){n.stream?.setVisibleRange(e.range.left,e.range.right);return}n.deferred?st({kind:"done",sessionId:n.id}):Jo(n);return}case"notifyBars":{let n=Vr.get(e.sessionId);if(!n||n.mode==="live")return;n.bars=e.bars,n.deferred=!1,Jo(n);return}case"bars":{let n=Vr.get(e.sessionId);if(!n||n.mode!=="live")return;if(e.restart){n.bars=e.bars,n.deferred=!1,Wh(n);return}for(let r of e.bars)h5(n,r);return}case"getContext":{let n=Vr.get(e.sessionId),r=n?n.mode==="live"?n.stream?.lastCtx()??null:n.lastCtx:null,i=!n||n.stopped?"idle":n.mode==="live"?"streaming":"idle";st({kind:"contextResult",reqId:e.reqId,snapshot:r==null?null:z0(r,i,e.select)});return}case"stop":{let n=Vr.get(e.sessionId);n&&(n.stopped=!0,n.stream?.stop()),Vr.delete(e.sessionId);return}case"fetchSeriesResult":{let n=Hh.get(e.reqId);if(!n)return;Hh.delete(e.reqId),e.error?n.reject(e.refusal?U0(e.error,e.refusal):new Error(e.error)):n.resolve(e.bars??[]);return}case"fetchFootprintsResult":{let n=Gh.get(e.reqId);if(!n)return;Gh.delete(e.reqId),e.error?n.reject(new Error(e.error)):n.resolve(e.bars??[]);return}case"resolveImportResult":{let n=Kh.get(e.reqId);if(!n)return;Kh.delete(e.reqId),e.error?n.reject(new Error(e.error)):n.resolve(e.source??null);return}}});})();\n'],{type:"application/javascript"})),r=new Worker(t);return URL.revokeObjectURL(t),r})(e.workerUrl)),this.defaultProps=e.defaultProps,this.propsVisibility=e.props,this.footprints=e.footprints,this.importResolver=e.importResolver}prepare(e,t){let r=++this.reqId;return new Promise((i,n)=>{this.prepares.set(r,{resolve:i,reject:n}),this.post({kind:"prepare",reqId:r,source:e,instanceId:t,...this.defaultProps?{defaultProps:this.defaultProps}:{},...this.propsVisibility?{propsVisibility:this.propsVisibility}:{},...this.importResolver?{importResolver:!0}:{}})})}execute(e,t){let r=++this.sessionId,i="live"===e.mode?"live":"static",n=this.barsOf(e),a={handlers:t,req:e,mode:i,pendingRuns:0,dirtyBars:!1,lastSentTime:n[n.length-1]?.time??0};this.footprints&&(a.footprints=Q(this.footprints,()=>this.notifyBars(r,"complete"))),"live"===i&&a.footprints?.runStarted(!0),this.sessions.set(r,a);let s={kind:"execute",sessionId:r,prepared:e.prepared,market:e.market,bars:n,inputs:{...e.inputs??{}},...e.props?{props:{...e.props}}:{},visibleRange:e.visibleRange,mode:i,historyState:e.historyState,...this.footprints?{footprints:!0}:{}};return"live"===i?this.post(s):this.postRun(a,s),{getContext:e=>new Promise(t=>{let i=++this.reqId;this.contextWaits.set(i,t),this.post({kind:"getContext",sessionId:r,reqId:i,select:e})}),stop:()=>{this.post({kind:"stop",sessionId:r}),a.footprints?.stop(),this.sessions.delete(r)},update:(e,t)=>{let n={kind:"update",sessionId:r,inputs:e,...t?{props:t}:{}};"live"===i?(this.post(n),a.footprints?.runStarted(!0)):this.postRun(a,n)},setVisibleRange:e=>{"live"===i?this.post({kind:"setVisibleRange",sessionId:r,range:e}):this.postRun(a,{kind:"setVisibleRange",sessionId:r,range:e})},notifyBars:e=>this.notifyBars(r,e)}}notifyBars(e,t){if("backfill"===t)return;let r=this.sessions.get(e);if(r){if("live"===r.mode){let i=this.barsOf(r.req);if("complete"===t){this.post({kind:"bars",sessionId:e,bars:i,restart:!0}),r.lastSentTime=i[i.length-1]?.time??0,r.footprints?.runStarted(!0);return}let n=i.filter(e=>e.time>=r.lastSentTime);if(0===n.length)return;this.post({kind:"bars",sessionId:e,bars:n}),r.lastSentTime=n[n.length-1].time;return}if(r.pendingRuns>0){r.dirtyBars=!0;return}this.postRun(r,{kind:"notifyBars",sessionId:e,bars:this.barsOf(r.req)})}}postRun(e,t){e.pendingRuns+=1,this.post(t)}runFinished(e){let t=this.sessions.get(e);t&&"live"!==t.mode&&(t.pendingRuns=Math.max(0,t.pendingRuns-1),0===t.pendingRuns&&t.dirtyBars&&(t.dirtyBars=!1,this.postRun(t,{kind:"notifyBars",sessionId:e,bars:this.barsOf(t.req)})))}terminate(){this.worker?.terminate(),this.worker=null}barsOf(e){return(e.getBars??(()=>e.bars))()}workerInstance(){return this.worker||(this.worker=this.spawn(),this.worker.addEventListener("message",e=>this.onMessage(e.data))),this.worker}post(e){this.workerInstance().postMessage(e)}onMessage(e){switch(e.kind){case"prepared":{let t=this.prepares.get(e.reqId);if(!t)return;this.prepares.delete(e.reqId),e.error?t.reject(Error(e.error)):e.prepared&&t.resolve(e.prepared);return}case"model":this.sessions.get(e.sessionId)?.handlers.onModel(e.model),this.sessions.get(e.sessionId)?.footprints?.runEnded();return;case"alert":this.sessions.get(e.sessionId)?.handlers.onAlert?.(e.alert);return;case"warning":this.sessions.get(e.sessionId)?.handlers.onWarning?.(e.warning);return;case"error":var t,r;this.sessions.get(e.sessionId)?.handlers.onError?.(e.refusal?(t=e.message,r=e.refusal,Object.assign(Error(t),{name:eA},eT(r))):Error(e.message)),this.runFinished(e.sessionId),this.sessions.get(e.sessionId)?.footprints?.runEnded();return;case"done":this.sessions.get(e.sessionId)?.handlers.onDone?.(),this.runFinished(e.sessionId);return;case"reactsToViewport":{let t=this.sessions.get(e.sessionId);t&&(t.req.prepared.reactsToViewport=e.value);return}case"fetchSeries":this.serveFetch(e.reqId,e.symbol,e.timeframe,e.range);return;case"fetchFootprints":this.serveFootprints(e.reqId,e.sessionId,e.symbol,e.timeframe,e.range);return;case"resolveImport":this.serveImport(e.reqId,e.path,e.info);return;case"contextResult":{let t=this.contextWaits.get(e.reqId);this.contextWaits.delete(e.reqId),t?.(e.snapshot);return}}}async serveFetch(e,t,r,i){let n=[...this.sessions.values()].find(e=>e.req.fetchSeries)?.req.fetchSeries;if(!n)return void this.post({kind:"fetchSeriesResult",reqId:e,bars:[]});try{this.post({kind:"fetchSeriesResult",reqId:e,bars:await n(t,r,i)})}catch(t){this.post({kind:"fetchSeriesResult",reqId:e,error:t instanceof Error?t.message:String(t),...eC(t)?{refusal:eT(t)}:{}})}}async serveFootprints(e,t,r,i,n){let a=this.sessions.get(t)?.footprints;if(!a)return void this.post({kind:"fetchFootprintsResult",reqId:e,bars:[]});try{this.post({kind:"fetchFootprintsResult",reqId:e,bars:await a.ask(r,i,n)})}catch(t){this.post({kind:"fetchFootprintsResult",reqId:e,error:t instanceof Error?t.message:String(t)})}}async serveImport(e,t,r){let i=this.importResolver;try{let n=i?"function"==typeof i?await i(t,r):await i.resolve(t,r):null;this.post({kind:"resolveImportResult",reqId:e,source:n??null})}catch(t){this.post({kind:"resolveImportResult",reqId:e,error:t instanceof Error?t.message:String(t)})}}}}}]);
|